text stringlengths 8 267k | meta dict |
|---|---|
Q: What does the "static" modifier after "import" mean? When used like this:
import static com.showboy.Myclass;
public class Anotherclass{}
what's the difference between import static com.showboy.Myclass and import com.showboy.Myclass?
A: Static import is used to import static fields / method of a class instead of:
package test;
import org.example.Foo;
class A {
B b = Foo.B_INSTANCE;
}
You can write :
package test;
import static org.example.Foo.B_INSTANCE;
class A {
B b = B_INSTANCE;
}
It is useful if you are often used a constant from another class in your code and if the static import is not ambiguous.
Btw, in your example "import static org.example.Myclass;" won't work : import is for class, import static is for static members of a class.
A: See Documentation
The static import declaration is
analogous to the normal import
declaration. Where the normal import
declaration imports classes from
packages, allowing them to be used
without package qualification, the
static import declaration imports
static members from classes, allowing
them to be used without class
qualification.
So when should you use static import?
Very sparingly! Only use it when you'd
otherwise be tempted to declare local
copies of constants, or to abuse
inheritance (the Constant Interface
Antipattern). In other words, use it
when you require frequent access to
static members from one or two
classes. If you overuse the static
import feature, it can make your
program unreadable and unmaintainable,
polluting its namespace with all the
static members you import. Readers of
your code (including you, a few months
after you wrote it) will not know
which class a static member comes
from. Importing all of the static
members from a class can be
particularly harmful to readability;
if you need only one or two members,
import them individually. Used
appropriately, static import can make
your program more readable, by
removing the boilerplate of repetition
of class names.
A: The basic idea of static import is that whenever you are using a static class,a static variable or an enum,you can import them and save yourself from some typing.
I will elaborate my point with example.
import java.lang.Math;
class WithoutStaticImports {
public static void main(String [] args) {
System.out.println("round " + Math.round(1032.897));
System.out.println("min " + Math.min(60,102));
}
}
Same code, with static imports:
import static java.lang.System.out;
import static java.lang.Math.*;
class WithStaticImports {
public static void main(String [] args) {
out.println("round " + round(1032.897));
out.println("min " + min(60,102));
}
}
Note: static import can make your code confusing to read.
A: Say you have static fields and methods inside a class called MyClass inside a package called myPackage and you want to access them directly by typing myStaticField or myStaticMethod without typing each time MyClass.myStaticField or MyClass.myStaticMethod.
Note : you need to do an
import myPackage.MyClass or myPackage.*
for accessing the other resources
A: There is no difference between those two imports you state. You can, however, use the static import to allow unqualified access to static members of other classes. Where I used to have to do this:
import org.apache.commons.lang.StringUtils;
.
.
.
if (StringUtils.isBlank(aString)) {
.
.
.
I can do this:
import static org.apache.commons.lang.StringUtils.isBlank;
.
.
.
if (isBlank(aString)) {
.
.
.
You can see more in the documentation.
A:
the difference between "import static com.showboy.Myclass" and "import com.showboy.Myclass"?
The first should generate a compiler error since the static import only works for importing fields or member types. (assuming MyClass is not an inner class or member from showboy)
I think you meant
import static com.showboy.MyClass.*;
which makes all static fields and members from MyClass available in the actual compilation unit without having to qualify them... as explained above
A: The import allows the java programmer to access classes of a package without package qualification.
The static import feature allows to access the static members of a class without the class qualification.
The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.
Example :
With import
import java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
System.out.println("Hello");
System.out.println("Java");
}
}
With static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
See also : What is static import in Java 5
A: The static modifier after import is for retrieving/using static fields of a class. One area in which I use import static is for retrieving constants from a class.
We can also apply import static on static methods. Make sure to type import static because static import is wrong.
What is static import in Java - JavaRevisited - A very good resource to know more about import static.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "472"
} |
Q: Visual Studio 2008 - Add Reference When adding a DLL as a reference to an ASP.Net project, VS2008 adds several files to the bin directory. If the DLL is called foo.dll, VS2008 adds foo.dll.refresh, foo.pdb and foo.xml. I know what foo.dll is :-), why does VS2008 add the other three files? What do those three files do? Can I delete them? Do they need to be added in source control?
A: foo.pdb is the debugger symbols file for foo.dll, you'll want it or you won't be able to set a breakpoint in that code.
A: Source Control:
Ben Straub said in a comment to this post: The .dll.refresh files should be added to the source control if required, while the .xml, .pdb and of course the .dll files should not be added.
John Rudy explained when to add the .refresh file:
Why is this a good thing (sometimes)?
Let's say you're in a team
environment. Someone checks in code
for foo.dll, and your build system
builds a new DLL, outputting it in a
file share on a server. Your refresh
file points to that server copy of the
DLL. Next time you build, VS will
auto-magically grab the latest and
greatest copy of that DLL.
.xml like David Mohundro said:
The xml file is there for XML comments
and intellisense. Visual Studio will
parse that and display the XML
comments that were added when you call
methods in those DLLs.
.pdb like David Mohundro said:
The pdb is there for debugging and
symbols. If you get an exception
thrown from it, you'll be able to get
stacktraces, etc. You're in control of
choosing whether or not the PDB is
built.
.refresh from a blog post about .refresh files:
It tells VS where to look for updated
versions of the dll with the same base
name. They're text files, you can open
them and see the path it's using.
Their purpose is to prevent you from
having to copy new versions yourself.
In VS2003, the project file would
contain the source location of the
reference, but since VS2005 doesn't
use project files for ASP.NET
projects, this is the replacement for
that particular functionality.
A:
VS2008 adds several files to the bin directory [...]Do they need to be added in source control?
Nothing in the bin directory needs to be added to source control. One of the first thing when initially checking in a project is to ignore the bin and obj directories. So yes, you can delete these files, but Visual Studio will recreate them.
A: The refresh file (since no one's hit on that yet!) describes where the DLL came from. This is for auto-refresh references; whenever you do a full build, VS will look in that path and copy that version of the DLL.
Why is this a good thing (sometimes)? Let's say you're in a team environment. Someone checks in code for foo.dll, and your build system builds a new DLL, outputting it in a file share on a server. Your refresh file points to that server copy of the DLL. Next time you build, VS will auto-magically grab the latest and greatest copy of that DLL.
A: The pdb is there for debugging and symbols. If you get an exception thrown from it, you'll be able to get stacktraces, etc. You're in control of choosing whether or not the PDB is built. The xml file is there for XML comments and intellisense. Visual Studio will parse that and display the XML comments that were added when you call methods in those DLLs.
I don't know about the refresh file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How does a "Schema changed after the target table was created" error occur? I hit this error while my web application was trying to execute a SELECT INTO on a MSSQL 2005 database. I really have two questions:
*
*What does this error mean and how does this happen?
*Is there a way to prevent these errors by coding in a different way?
A: Besides the obvious, that somebody changed the table while the code was executing, it could be a naming conflict with temp tables created in the SQL. It could be that there are two temp tables with different schemas, but they have the same name.
A: You can get this error if a database trigger(AFTER CREATE_TABLE) changes the table, when using SELECT INTO.
A: Also you can get this when you have the
SELECT * INTO #TABLE FROM TABLE
used within a stored procedure and it is run multiple times concurrently.
A: You have to specify dbo. as the schema for the first table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Dataflow Programming API for Java? I am looking for a Dataflow / Concurrent Programming API for Java.
I know there's DataRush, but it's not free. What I'm interested in specifically is multicore data processing, and not distributed, which rules out MapReduce or Hadoop.
Any thoughts?
Thanks,
Rollo
A: You might try gpars; it apparently has implementations of data flow variables and streams in Java even though it is geared towards providing concurrent programming goodies for Groovy.
A: Might try the upcoming fork/join library which will (hopefully) be in Java 7 as part of the JSR 166y update.
Main project page:
- http://gee.cs.oswego.edu/dl/concurrency-interest/index.html
Pointers to lots of links about what it is:
- http://tech.puredanger.com/java7#jsr166
A: Does the built in Java concurrent package meet your needs? It's a very nice package, built in ThreadPools, CopyOnWriteCollections, Executors, Future. We use it to process large volumns of data in thread pools.
A: https://github.com/rfqu/df4j is simple but powerful dataflow library. If it lacks some desired features, they can be added easly. It can exploit java.concurrent.ExecutorService.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to know if a jsp tag attribute is available for EL? I have the following piece of code in my jsp :
<% pageContext.setAttribute("warnings",Globals.WARNING_MESSAGES); %>
<c:choose>
<c:when test="${requestScope[pageScope.warnings] or sessionScope[pageScope.warnings]}">
<html:errors header="warnings.header" footer="warnings.footer" prefix="warnings.prefix" suffix="warnings.suffix"/>
<c:remove var="${pageScope.warnings}" scope="session"/>
</c:when>
<c:otherwise>
<html:errors/>
</c:otherwise>
</c:choose>
I wonder if there is anyway (without delving into the source code) to know if an attribute is available for EL coding.
In this code I would like to use a scripting variable define as a constant that I set in the pageScope container. I would like to use the same mechanism when I remove the variable from the sessionScope referencing the scripting variable but it seems that the <c:remove var> attribute refuses to interpret my scripting variable and this ruins all the effort make to reference my Constant declaration. I can use a jsp scriptlet to work around this but is there any "better" way of doing this ?
A: I'm not sure I understand your question, but I think you're looking for the "empty" operator for EL to test if an attribute exists:
<c:if test="${empty pageScope.warnings}">
//do something
</c:if>
This will return true if pageScope.warnings is not defined (null).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I preserve markup tags? I've got an XML document containing news stories, and the body element of a news story contains p tags amongst the plain text. When I use XSL to retrieve the body, e.g.
<xsl:value-of select="body" />
the p tags seem to get stripped out. I'm using Visual Studio 2005's implementation of XSL.
Does anyone have any ideas how to avoid this? Thanks.
A: If you don't have control over the input document, copy-of should work:
From http://www.xml.com/pub/a/2000/06/07/transforming/index.html
"The xsl:copy-of element, on the other hand, can copy the entire subtree of each node that the template selects. This includes attributes, if the xsl:copy-of element's select attribute has the appropriate value. In the following example, the template copies title element nodes and all of their descendant nodes -- in other words, the complete title elements, including their tags, subelements, and attributes:"
<xsl:template match="title">
<xsl:copy-of select="*"/>
</xsl:template>
A: Try to use
<xsl:copy-of select="body"/>
instead. From w3schools' documentation on same:
The <xsl:copy-of> element creates a
copy of the current node.
Note: Namespace nodes, child nodes,
and attributes of the current node are
automatically copied as well!
A: If you have control over the input document, CDATA is the right way to go.
A: The value of an XML element - this is true not just in XSLT but in DOM implementations - is the concatenation of all of its descendant text nodes. In XSLT, value-of emits an element's value, while copy-of emits a copy of the element.
A: It is because the engine is interpreting the <p> tag (excluding it for the output). You need to specify you want the content "as it is", using the "disable-output-escaping=yes|no" attribute.
<xsl:value-of select="body" disable-output-escaping="yes"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How to open existing file using COM/ATL (no MFC) I have an existing Windows C++ application that links to ATL. I need to open an existing Excel file and access some properties. One of the things I need to do is determine if the user is currently viewing the Excel file.
We can assume that the user has Excel installed, although not sure which version.
What is the C++ / COM code to attach to an existing Excel file? How do I determine if the file is currently open by an instance of Excel? Assume I know the filename. I googled around for 15 minutes but haven't found out how to do this without MFC.
A: Nice challenge. And because a challenge cannot be refused I sat in front of Visual Studio and here is a possible solution.
#include <windows.h>
#include <iostream>
using namespace std;
#import "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE11\\MSO.DLL" \
rename("RGB", "MSORGB") \
rename("DocumentProperties", "MSDocumentProperties")
using namespace Office;
#import "C:\\Program Files\\Common Files\\Microsoft Shared\\VBA\\VBA6\\VBE6EXT.OLB"
using namespace VBIDE;
#import "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE" \
rename("DialogBox", "ExcelDialogBox" ) \
rename("RGB", "ExcelRGB") \
rename("CopyFile", "ExcelCopyFile") \
rename("ReplaceText", "ExcelReplaceText")
void DumpCOMError(_com_error& e) {
wcout << L"Error:" << endl;
wcout << L" Code = " << hex << e.Error() << endl;
wcout << L" Code meaning = " << e.ErrorMessage() << endl;
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
wcout << L" Source = " << bstrSource << endl;
wcout << L" Description = " << bstrDescription << endl;
}
HRESULT IsXlsFileOpen(LPWSTR FileName, BOOL& file_open) {
Excel::_ApplicationPtr pApplication;
HRESULT hr = E_FAIL;
if (FAILED(hr = pApplication.CreateInstance(L"Excel.Application"))) {
file_open = FALSE;
return hr;
}
_variant_t varOption(static_cast<long>(DISP_E_PARAMNOTFOUND), VT_ERROR);
Excel::_WorkbookPtr pBook;
try {
pBook = pApplication->Workbooks->Open(
FileName,
varOption,
varOption,
varOption,
varOption,
varOption,
varOption,
varOption,
varOption,
varOption,
varOption,
varOption,
varOption);
file_open = pBook->ReadOnly == VARIANT_TRUE;
pBook->Close(VARIANT_FALSE);
hr = S_OK;
} catch (_com_error& e) {
file_open = FALSE;
DumpCOMError(e);
hr = e.Error();
}
pApplication->Quit();
return hr;
}
int main(int argc, wchar_t* argv[])
{
CoInitialize(NULL);
{
BOOL fileOpen;
HRESULT hr = IsXlsFileOpen(L"f:\\temp\\treta.xls", fileOpen);
if (SUCCEEDED(hr)) {
cout << "File is " << (fileOpen ? "open" : "not open") << "." << endl;
}
cout << "IsXlsFileOpen returned: 0x" << hex << hr << endl;
}
CoUninitialize();
return 0;
}
Some deserved credits are in order:
http://www.vbaexpress.com/kb/getarticle.php?kb_id=625
http://www.codeproject.com/KB/wtl/WTLExcel.aspx
http://www.codeguru.com/forum/printthread.php?s=26acdf89a1a6b79b7aa6a52e11b8d832&threadid=61997
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What constitutes 'high cpu' for SQL Server What level of CPU usage should be considered high for SQL Server? ie 80% 90% 100%?
A: if under normal loads the CPU averages above 40% I start to get nervous. However, that's because I know the nature of our traffic and the spikes we get. Your mileage may vary.
A: We actually aim even lower, for about a 7-10% average, but we do sometimes get processing that will spike us to 60%.
We measure total CPU every 30 seconds and email a report daily, and if we see a move of 2% away from that average we expect for that day we investigate.
It takes time but it's helps me sleep better at night :)
A: Generally, you don't want a machine to sustain a constant CPU of over 40 or 50%, because it won't be able to handle spikes in activity.
A: It really depends on your machine. The best thing is to monitor the server using perfmon and see when things start to run slowly. It is normal for SQL to use a lot of CPU under load.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Java development for the web I'm looking to start developing for the web using Java - I have some basic Java knowledge, so that's not a problem, but I'm at a loss when it comes to deciphering the various technologies for use in web applications.
What options are available to me? How do they work? Are there any frameworks similar to Django/Ruby on Rails which I could use to simplify things?
Any links which could help with understanding what's available would be much appreciated.
A: Start with JSP backed by logic in Java classes. Or use servlets.
The advantage of using JSP and Servlets is that you gain knowledge of what all the frameworks do under the hood. And that understanding is crucial to figure out how to do X in that particular framework.
Furthermore, JSP is very easy. You can easily see what you're doing and very easily see it when you mess up the view with business logic.
And quite a lot of frameworks (Struts, Spring MVC) use JSP as their view technology. It's a natural first step in web development using Java.
A: I don't know if there's anything quite as nice as Django for Java, but Spring has a light-weight web framework built on J2EE
http://www.springframework.org/about
A flexible MVC web application
framework, built on core Spring
functionality. This framework is
highly configurable via strategy
interfaces, and accommodates multiple
view technologies like JSP, Velocity,
Tiles, iText, and POI. Note that a
Spring middle tier can easily be
combined with a web tier based on any
other web MVC framework, like Struts,
WebWork, or Tapestry.
A: Java frameworks come in two basic flavors. One is called the "Action" Framework, the other the "Component" Framework.
Action frameworks specialize on mapping HTTP requests to Java code (actions), and binding HTTP Requests to Java objects. Servlets is the most basic of the Action Frameworks, and is the basic upon all of the others are built.
Struts is the most popular Action framework, but I can't in good conscience recommend it to anyone. Struts 2 and Stripes are more modern, and very similar to each other. Both are light on the configuration and easy to use out of the box, providing very good binding functionality.
Component Frameworks focus on the UI and tend to promote a more event driven architecture based on high level UI components (buttons, list boxes, etc.). The frameworks tend to hide that actual HTTP request from the coder under several layers. They make developing the more advanced UIs much easier. .NET is a component framework for Windows. On Java, the popular component frameworks are JSF (a standard) and Wicket.
As a rule, if you're creating a "web site". that is something more akin to presenting information (like a blog, or a community site), the Action frameworks work better. These sites tend to be simpler, get bookmarked often, require "pretty URLs" etc. This is generally easier to do with an Action framework.
Component frameworks are much better for things like back office applications with lots of UI elements and complicated workflows. You'll find, particularly with tooling, that these style of apps will go together faster using a component framework. But component frameworks have more complicated request workflow, sometimes relying on hidden state, lots of POST actions, etc. Many have "horrible" URLs, and sometimes create pages that are difficult to bookmark.
Both frameworks can be used for both tasks, just some are more suited to the task than others.
None of these frameworks directly address persistence, but many have extension modules or idioms that work tightly with JPA/EJB3 or Hibernate.
A: something like grails ?
there is also the projects from spring
A: You'll need to start with servlets and JSP. There are many web frameworks in Java and all of them are based on these two technologies.
A: You could try Jboss Seam : http://www.seamframework.org/Documentation/GettingStarted
If you are using Eclipe as your IDE there is good integration via Jboss Tools or you can use the Seam-Gen tool that comes with Seam. This allows you to define a database table (or tables) and with a few easy commands, build an entire runnable web project from it. It's a nice way to get the ball rolling.
A: Your basic java web technology is servlets. Servlets let you write Java code that responds to various HTTP events (doGet, doPost, doPut, etc). They're generally used for controllers in the MVC architecture.
Link: http://java.sun.com/products/servlet/
JSP lets you write HTML with embedded Java instead of the other way around (in servlets). JSP has been extended via JSF to incorporate more recent architectural advances. This is in the same line as PHP and ASP. This is the view portion of the MVC architecture.
Link: http://java.sun.com/developer/technicalArticles/GUI/JavaServerFaces/
A lot of more complex applications utilize Enterprise Java Beans (EJB) for session management, clustering, etc. This isn't a web technology, per se, but you see it go hand-in-hand when dealing with more complex webapps. Alternatives include frameworks such as Spring.
EJB: http://docs.jboss.org/ejb3/app-server/tutorial/
Spring: http://www.springframework.org/
Also, you'll want to familiarize yourself with ORM technology (after servlets and JSP/JSF). The leading ORM framework is currently Hibernate. This lets you map SQL tables to java objects and interact with them accordingly. This is more advanced stuff so save it for when you're trying to get your head around EJB/Spring, etc.
Link: http://www.hibernate.org/
edit: I forgot to define ORM. It stands for Object Relational Mapping/Mapper (whatever version of "Map" you feel like using :)
A: Also Java Server Faces
http://en.wikipedia.org/wiki/Java_Server_Faces
A: This is a very open-ended question. The short answer is "yes" there are frameworks, libraries and standards to do everything from writing things at the HTTP request level up to content management systems in Java.
You can also use other languages (e.g. Python, Ruby, etc) on the JVM for that matter.
For some of the Java-only technologies, investigate JSP/Servlets, Struts, Struts2 (which is the updated version of Webwork), Spring MVC, Tapestry, web4j, Wicket.
There are other frameworks built on the JVM but use languages other than Java such as Grails.
To get started I would download Eclipse (latest version) and Tomcat. Create a new web application in Eclipse. There are guides that can get you started.
Start with learning how JSPs and Servlets work, these are a bit low level and aren't really a framework, but will let you get up and running quickly. From there investigate and choose your framework.
Spring MVC is pretty easy to get set up and going. I'm certain there are others.
A: If you already know Ruby On Rails, you can use it with JRuby and deploy to a Java server (like Tomcat) with Warbler.
In pure Java, Wicket has a good approach and is getting quite popular.
A: Before studying those frameworks, why not study first where it all started? Try programming with servlets first, so you could a peek at the core of most of those java web frameworks. It would help you understand J2EE better.
A: J2EE is the standard. You can use this to build apps with Java Server Pages, Servlets and EJBs.
Struts is also a very popular framework that uses JSPs and Servlets. Its a bit tricky to get setup but it is a very good option for mid size sites.
http://en.wikipedia.org/wiki/Struts
A: In general Java is more component-based, i.e. you don't have frameworks that do it all for you (you'll probably have to pick a database access framework yourself, for example). For Data Access I'd recommend Hibernate or iBATIS.
For the front-end there are literally hundreds of frameworks around. Investigate JSF, Wicket, Struts 2, Stripes - whichever one you use depends on your specific needs as they all have different strengths.
And for a business layer I'd recommend the Spring Framework, which is very comprehensive and has a great reference guide / tutorial :)
A: I learned Java in college back when it was in version 1.1.5. I recently started trying to program for the web, but it didn't make sense until I read Head First Servlets and JSP. There are way more things involved in web development with Java than I ever realized, and without this book, I would have quit and just used PHP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How to check the maximum number of allowed connections to an Oracle database? What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".
A: Note: this only answers part of the question.
If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:
SQL> show parameter sessions
This gives you an output like:
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size integer 0
java_soft_sessionspace_limit integer 0
license_max_sessions integer 0
license_sessions_warning integer 0
sessions integer 248
shared_server_sessions integer
The sessions parameter is the one what you want.
A: The sessions parameter is derived from the processes parameter and changes accordingly when you change the number of max processes. See the Oracle docs for further info.
To get only the info about the sessions:
select current_utilization, limit_value
from v$resource_limit
where resource_name='sessions';
CURRENT_UTILIZATION LIMIT_VALUE
------------------- -----------
110 792
Try this to show info about both:
select resource_name, current_utilization, max_utilization, limit_value
from v$resource_limit
where resource_name in ('sessions', 'processes');
RESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE
------------- ------------------- --------------- -----------
processes 96 309 500
sessions 104 323 792
A: Use gv$session for RAC, if you want get the total number of session across the cluster.
A: I thought this would work, based on this source.
SELECT
'Currently, '
|| (SELECT COUNT(*) FROM V$SESSION)
|| ' out of '
|| DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX)
|| ' connections are used.' AS USAGE_MESSAGE
FROM
V$LICENSE VL
However, Justin Cave is right. This query gives better results:
SELECT
'Currently, '
|| (SELECT COUNT(*) FROM V$SESSION)
|| ' out of '
|| VP.VALUE
|| ' connections are used.' AS USAGE_MESSAGE
FROM
V$PARAMETER VP
WHERE VP.NAME = 'sessions'
A: v$resource_limit view is so interesting for me in order to glance oracle sessions,processes..:
https://bbdd-error.blogspot.com.es/2017/09/check-sessions-and-processes-limit-in.html
A: There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.
The number of sessions the database was configured to allow
SELECT name, value
FROM v$parameter
WHERE name = 'sessions'
The number of sessions currently active
SELECT COUNT(*)
FROM v$session
As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.
A: select count(*),sum(decode(status, 'ACTIVE',1,0)) from v$session where type= 'USER'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "99"
} |
Q: JQuery Facebox Plugin : Get it inside the form tag I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server.
Has anyone dealt with this that can give me some pointers?
A: poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
and it loads up in the form tag, not sure yet if there are any side effects
A: You can use this code to register the PostBack event:
btn.OnClientClick = string.Format("{0}; $.facebox.close();",ClientScript.GetPostBackEventReference(btn, null));
this will let the button fires a PostBack.
A: Even after the :
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
change I found it problematic. When you look at the page source using firebug you see that all the html in the div assigned to be the facebox div is doubled up (repeated).
So all of those controls with supposed unique id's are doubled up on the page, that can't be good on the postback, i've decided putting asp.net web controls in a facebox is not a good idea.
A: I modified facbox.js to do this. Maybe there is a better solution but this works like a charm
Here what i did:
*
*add two lines on top of facbox.js before '(function($)'
var willremove = '';
var willremovehtml = '';
*find "reveal: function(data, klass) {" and add this lines before the first line of function.
willremove = data.attr('id')
willremovehtml = $('#'+willremove).html()
$('#'+willremove).html('')
*find "close: function() {" and make it look like below.
close: function() {
$(document).trigger('close.facebox')
$('#'+willremove).html(willremovehtml)
willremovehtml = ''
willremove = ''
return false
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to check if a process is running via a batch script How can I check if an application is running from a batch (well cmd) file?
I need to not launch another instance if a program is already running. (I can't change the app to make it single instance only.)
Also the application could be running as any user.
A: I use PV.exe from http://www.teamcti.com/pview/prcview.htm installed in Program Files\PV with a batch file like this:
@echo off
PATH=%PATH%;%PROGRAMFILES%\PV;%PROGRAMFILES%\YourProgram
PV.EXE YourProgram.exe >nul
if ERRORLEVEL 1 goto Process_NotFound
:Process_Found
echo YourProgram is running
goto END
:Process_NotFound
echo YourProgram is not running
YourProgram.exe
goto END
:END
A: Here's how I've worked it out:
tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log
FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end
start notepad.exe
:end
del search.log
The above will open Notepad if it is not already running.
Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.
A: The answer provided by Matt Lacey works for Windows XP. However, in Windows Server 2003 the line
tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log
returns
INFO: No tasks are running which match the specified criteria.
which is then read as the process is running.
I don't have a heap of batch scripting experience, so my soulution is to then search for the process name in the search.log file and pump the results into another file and search that for any output.
tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log
FINDSTR notepad.exe search.log > found.log
FOR /F %%A IN (found.log) DO IF %%~zA EQU 0 GOTO end
start notepad.exe
:end
del search.log
del found.log
I hope this helps someone else.
A: I like the WMIC and TASKLIST tools but they are not available in home/basic editions of windows.Another way is to use QPROCESS command available on almost every windows machine (for the ones that have terminal services - I think only win XP without SP2 , so practialy every windows machine):
@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
:: QPROCESS can display only the first 12 symbols of the running process
:: If other tool is used the line bellow could be deleted
set process_to_check=%process_to_check:~0,12%
QPROCESS * | find /i "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
endlocal
QPROCESS command is not so powerful as TASKLIST and is limited in showing only 12 symbols of process name but should be taken into consideration if TASKLIST is not available.
More simple usage where it uses the name if the process as an argument (the .exe suffix is mandatory in this case where you pass the executable name):
@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
:: .exe suffix is mandatory
set "process_to_check=%~1"
QPROCESS "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
endlocal
The difference between two ways of QPROCESS usage is that the QPROCESS * will list all processes while QPROCESS some.exe will filter only the processes for the current user.
Using WMI objects through windows script host exe instead of WMIC is also an option.It should on run also on every windows machine (excluding the ones where the WSH is turned off but this is a rare case).Here bat file that lists all processes through WMI classes and can be used instead of QPROCESS in the script above (it is a jscript/bat hybrid and should be saved as .bat):
@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off
cscript //E:JScript //nologo "%~f0"
exit /b
************** end of JSCRIPT COMMENT **/
var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes = new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
var process=processes.item();
WScript.Echo( process.processID + " " + process.Name );
}
And a modification that will check if a process is running:
@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
cscript //E:JScript //nologo "%~f0" | find /i "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
exit /b
************** end of JSCRIPT COMMENT **/
var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes = new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
var process=processes.item();
WScript.Echo( process.processID + " " + process.Name );
}
The two options could be used on machines that have no TASKLIST.
The ultimate technique is using MSHTA . This will run on every windows machine from XP and above and does not depend on windows script host settings. the call of MSHTA could reduce a little bit the performance though (again should be saved as bat):
@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
mshta "about:<script language='javascript' src='file://%~dpnxf0'></script>" | find /i "%process_to_check%" >nul 2>&1 && (
echo process %process_to_check% is running
) || (
echo process %process_to_check% is not running
)
endlocal
exit /b
************** end of JSCRIPT COMMENT **/
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes = new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
var process=processes.item();
fso.Write( process.processID + " " + process.Name + "\n");
}
close();
A: I like Chaosmaster's solution! But I looked for a solution which does not start another external program (like find.exe or findstr.exe). So I added the idea from Matt Lacey's solution, which creates an also avoidable temp file. At the end I could find a fairly simple solution, so I share it...
SETLOCAL EnableExtensions
set EXE=MyProg.exe
FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF NOT %%x == %EXE% (
echo %EXE% is Not Running
)
This is working for me nicely...
The above is an edit. The original code apparently had a GOTO in it, which someone in the comments thought uncouth.
Spaces
If you are concerned that the program name may have spaces in it then you need to complicate the code very slightly:
SETLOCAL EnableExtensions
set EXE=My Prog.exe
FOR /F %%x IN ("%EXE%") do set EXE_=%%x
FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF NOT %%x == %EXE_% (
echo %EXE% is Not Running
)
The original code will work fine whether or not other running processes have spaces in their names. The only concern is whether or not the process we are targeting has space(s).
ELSE
Keep in mind that if you add an ELSE clause then it will be executed once for every instance of the application that is already running. There is no guarantee that there be only a single instance running when you run this script.
Should you want one anyway, either a GOTO or a flag variable is indicated.
Ideally the targeted application should already mutex itself to prevent multiple instances, but that is a topic for another SO question and is not necessarily applicable to the subject of this question.
GOTO again
I do agree with the "ELSE" comment. The problem with the GOTO-less solution, that is may run the condition part (and the ELSE part) multiple times, so it is a bit messy as it has to quit the loop anyway. (Sorry, but I do not deal with the SPACE issue here, as it seems to be pretty rare and a solution is shown for it)
SETLOCAL EnableExtensions
SET EXE=MyProg.exe
REM for testing
REM SET EXE=svchost.exe
FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF NOT %%x == %EXE% (
ECHO %EXE% is Not Running
REM This GOTO may be not necessary
GOTO notRunning
) ELSE (
ECHO %EXE is running
GOTO Running
)
...
:Running
REM If Running label not exists, it will loop over all found tasks
A: Another possibility I came up with, which does not require to save a file, inspired by using grep is:
tasklist /fi "ImageName eq MyApp.exe" /fo csv 2>NUL | find /I "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running
*
*/fi "" defines a filter of apps to find, in our case it's the *.exe name
*/fo csv defines the output format, csv is required because by default the name of the executable may be truncated if it is too long and thus wouldn't be matched by find later.
*find /I means case-insensitive matching and may be omitted
See the man page of the tasklist command for the whole syntax.
A: The suggestion of npocmaka to use QPROCESS instead of TASKLIST is great but, its answer is so big and complex that I feel obligated to post a quite simplified version of it which, I guess, will solve the problem of most non-advanced users:
QPROCESS "myprocess.exe">NUL
IF %ERRORLEVEL% EQU 0 ECHO "Process running"
The code above was tested in Windows 7, with a user with administrator rigths.
A: TASKLIST | FINDSTR ProgramName || START "" "Path\ProgramName.exe"
A: Under Windows you can use Windows Management Instrumentation (WMI) to ensure that no apps with the specified command line is launched, for example:
wmic process where (name="nmake.exe") get commandline | findstr /i /c:"/f load.mak" /c:"/f build.mak" > NUL && (echo THE BUILD HAS BEEN STARTED ALREADY! > %ALREADY_STARTED% & exit /b 1)
A: I don't know how to do so with built in CMD but if you have grep you can try the following:
tasklist /FI "IMAGENAME eq myApp.exe" | grep myApp.exe
if ERRORLEVEL 1 echo "myApp is not running"
A: Just mentioning, if your task name is really long then it won't appear in its entirety in the tasklist result, so it might be safer (other than localization) to check for the opposite.
Variation of this answer:
:: in case your task name is really long, check for the 'opposite' and find the message when it's not there
tasklist /fi "imagename eq yourreallylongtasknamethatwontfitinthelist.exe" 2>NUL | find /I /N "no tasks are running">NUL
if "%errorlevel%"=="0" (
echo Task Found
) else (
echo Not Found Task
)
A: If you have more than one .exe-file with the same name and you only want to check one of them (e.g. you care about C:\MyProject\bin\release\MyApplication.exe but not C:\MyProject\bin\debug\MyApplication.exe) then you can use the following:
@echo off
set "workdir=C:\MyProject\bin\release"
set "workdir=%workdir:\=\\%"
setlocal enableDelayedExpansion
for /f "usebackq tokens=* delims=" %%a in (`
wmic process where 'CommandLine like "%%!workdir!%%" and not CommandLine like "%%RuntimeBroker%%"' get CommandLine^,ProcessId /format:value
`) do (
for /f "tokens=* delims=" %%G in ("%%a") do (
if "%%G" neq "" (
rem echo %%G
set "%%G"
rem echo !ProcessId!
goto :TheApplicationIsRunning
)
)
)
echo The application is not running
exit /B
:TheApplicationIsRunning
echo The application is running
exit /B
A: TrueY's answer seemed the most elegant solution, however, I had to do some messing around because I didn't understand what exactly was going on. Let me clear things up to hopefully save some time for the next person.
TrueY's modified Answer:
::Change the name of notepad.exe to the process .exe that you're trying to track
::Process names are CASE SENSITIVE, so notepad.exe works but Notepad.exe does NOT
::Do not change IMAGENAME
::You can Copy and Paste this into an empty batch file and change the name of
::notepad.exe to the process you'd like to track
::Also, some large programs take a while to no longer show as not running, so
::give this batch a few seconds timer to avoid a false result!!
@echo off
SETLOCAL EnableExtensions
set EXE=notepad.exe
FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto ProcessFound
goto ProcessNotFound
:ProcessFound
echo %EXE% is running
goto END
:ProcessNotFound
echo %EXE% is not running
goto END
:END
echo Finished!
Anyway, I hope that helps. I know sometimes reading batch/command-line can be kind of confusing sometimes if you're kind of a newbie, like me.
A: I needed a solution with a retry. This code will run until the process is found and then kill it. You can set a timeout or anything if you like.
Notes:
*
*The ".exe" is mandatory
*You could make a file runnable with parameters, version below
:: Set programm you want to kill
:: Fileextension is mandatory
SET KillProg=explorer.exe
:: Set waiting time between 2 requests in seconds
SET /A "_wait=3"
:ProcessNotFound
tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
IF "%ERRORLEVEL%"=="0" (
TASKKILL.EXE /F /T /IM %KillProg%
) ELSE (
timeout /t %_wait%
GOTO :ProcessNotFound
)
taskkill.bat:
:: Get program name from argumentlist
IF NOT "%~1"=="" (
SET "KillProg=%~1"
) ELSE (
ECHO Usage: "%~nx0" ProgramToKill.exe & EXIT /B
)
:: Set waiting time between 2 requests in seconds
SET /A "_wait=3"
:ProcessNotFound
tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
IF "%ERRORLEVEL%"=="0" (
TASKKILL.EXE /F /T /IM %KillProg%
) ELSE (
timeout /t %_wait%
GOTO :ProcessNotFound
)
Run with .\taskkill.bat ProgramToKill.exe
A: I'm assuming windows here. So, you'll need to use WMI to get that information. Check out The Scripting Guy's archives for a lot of examples on how to use WMI from a script.
A: I used the script provided by Matt (2008-10-02). The only thing I had trouble with was that it wouldn't delete the search.log file. I expect because I had to cd to another location to start my program. I cd'd back to where the BAT file and search.log are, but it still wouldn't delete. So I resolved that by deleting the search.log file first instead of last.
del search.log
tasklist /FI "IMAGENAME eq myprog.exe" /FO CSV > search.log
FOR /F %%A IN (search.log) DO IF %%-zA EQU 0 GOTO end
cd "C:\Program Files\MyLoc\bin"
myprog.exe myuser mypwd
:end
A: Building on vtrz's answer and Samuel Renkert's answer on an other topic, I came up with the following script that only runs %EXEC_CMD% if it isn't already running:
@echo off
set EXEC_CMD="rsync.exe"
wmic process where (name=%EXEC_CMD%) get commandline | findstr /i %EXEC_CMD%> NUL
if errorlevel 1 (
%EXEC_CMD% ...
) else (
@echo not starting %EXEC_CMD%: already running.
)
As was said before, this requires administrative privileges.
A: You should check the parent process name, see The Code Project article about a .NET based solution**.
A non-programmatic way to check:
*
*Launch Cmd.exe
*Launch an application (for instance, c:\windows\notepad.exe)
*Check properties of the Notepad.exe process in Process Explorer
*Check for parent process (This shows cmd.exe)
The same can be checked by getting the parent process name.
A: I usually execute following command in cmd prompt to check if my program.exe is running or not:
tasklist | grep program
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "299"
} |
Q: Font problems in charts (Reporting services 2008) While generating charts using RS 2008 betas, RC0 and such., I never specified any fonts for axis labels, legends etc. They were all rendered with the Arial font by default, which looked awesome. But as soon as we switched to RS 2008 final, the fonts got all messed up - they are rendered in some kind of bold console font.
My initial thought was that the default changed - I tried setting the font to Arial explicitly (either through RDL or the designer). That didn't work - only certain fonts seem to work (e.g. Calibri). What's even more weird, the legend does not listen to the font setting - it is always rendered in this ugly bold thing.
One other thought was maybe the fonts are missing somewhere, however, the Tablix element is using the same fonts and they seem to work.
This behaviour is universal - it is seen using the development studio preview, the report viewing control and while exporting it to all available formats.
So, obviously, I'm stuck - has anyone ever encountered this behaviour ?
A: I have seen this behaviour before. Not in SSRS, but in GDI+ rendering in .NET desktop applications. It has to do with antialiasing and palettes that don't support transparency - all the nearly-transparent pixels surrounding the glyphs are coerced to solid colour.
You don't get this effect with post-LCD fonts like Calibri because they are aligned to pixel boundaries for better rendering on LCD displays, which have sharply defined pixels. CRTs allowed colour to bleed into adjacent pixels, producing what was essentially analog antialiasing. (This is why TV pictures look much better than they should considering their horribly low resolution.)
I did find a way around it with GDI, and when I remember I'll tell you. That said, you don't have access to the rendering code so you probably can't apply the fix. Actually I think I've just remembered - you explicitly set the background to white rather than transparent, forcing GDI to composit the edge colours instead of hoping the graphics card will do it. I don't know whether you'll be able to use this answer, sorry.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to replay soap message? I would like to replay soap message against my server. I've recorded a few messages and i've tampered with Timestamps, soapbodies etc and now I would like to see that my SecurityAssertions lites up like xmastrees. The deployed server will use clientcertificates and servercertifivcates for authentisation, and the whole messageflow will go encrypted with ssl. But I would still like to test the implementation with http and no authentication.
How would one do to replay a soapmessage? Is there any application around that can do this easy?
A: You could try soapUI. It has quite a few capabilities for interacting with web services including creating tests for them in which you can replay messages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RoR: Model validation question I have a basic ActiveRecord model in which i have two fields that i would like to validate. The requirement is that at least one of the fields must have a value. Both can have values, but at least one needs a value.
How do i express this with
validates_presence_of
statements? For example:
validates_presence_of :main_file
validates_presence_of :alt_file
i don't want an error to be generated if only one of them is empty, only if both are empty.
A: validates_presence_of :main_file, :if => Proc.new { |p| p.alt_file.blank? }
validates_presence_of :alt_file, :if => Proc.new { |p| p.main_file.blank? }
A: changing .nil? to .blank? does the trick!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Convert Char[] to a List (c#) How can I convert a Char[] (of any length) to a List ?
A: I have managed to use the following to get the job done:
byte[] arr = new System.Text.UTF8Encoding( true ).GetBytes( str );
List<byte> byteList = new List<byte>( arr );
Thanks for your help
A: First you need to understand that chars aren't bytes in .NET. To convert between chars (a textual type) and bytes (a binary type) you need to use an encoding (see System.Text.Encoding).
Encoding will let you convert between string/char[] and byte[]. Once you've got a byte array, there are various ways of converting that into a List<byte> - although you may not even need to, as byte[] implements IList<byte>.
See my article on Unicode for more about the text conversion side of things (and links to more articles).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I shutdown, restart, or log off Windows via a bat file? I've been using Remote Desktop Connection to get into a workstation. But in this environment, I cannot use the power options in Start Menu. I need an alternative way to shutdown or restart.
How do I control my computer's power state through the command line?
A: No one has mentioned -m option for remote shutdown:
shutdown -r -f -m \\machinename
Also:
*
*The -r parameter causes a reboot (which is usually what you want on a remote machine, since physically starting it might be difficult).
*The -f parameter option forces the reboot.
*You must have appropriate privileges to shut down the remote machine, of course.
A: When remoted into a machine (target is Windows XP anyway; I am not sure about target Windows Vista), although Shutdown on the start menu is replaced by Disconnect Session or something like that, there should be one called 'Windows Security' which also does the same thing as Ctrl + Alt + End as pointed to by Owen.
A: You're probably aware of this, but just in case: it's much easier to just type shutdown -r (or whatever command you like) into the "Run" box and hit enter.
Saves leaving batch files lying around everywhere.
A: I'm late to the party, but did not see this answer yet.
When you don't want to use a batch file or type the command. You can just set focus to the desktop and then use Alt + F4.
Windows will ask you what you want to do, select shutdown or restart.
For screenshots and even a video, see: https://tinkertry.com/how-to-shutdown-or-restart-windows-over-rdp
A: I would write this in Notepad or WordPad for a basic logoff command:
@echo off
shutdown -l
This is basically the same as clicking start and logoff manually, but it is just slightly faster if you have the batch file ready.
A: Original answer: Oct. 2008
You also got all the "rundll32.exe shell32.dll" serie:
(see update below)
*
*rundll32.exe user.exe,**ExitWindows** [Fast Shutdown of Windows]
*rundll32.exe user.exe,**ExitWindowsExec** [Restart Windows]
rundll32.exe shell32.dll,SHExitWindowsEx n
where n stands for:
*
*0 - LOGOFF
*1 - SHUTDOWN
*2 - REBOOT
*4 - FORCE
*8 - POWEROFF
(can be combined -> 6 = 2+4 FORCE REBOOT)
Update April 2015 (6+ years later):
1800 INFORMATION kindly points out in the comments:
Don't use rundll32.exe for this purpose. It expects that the function you passed on the command line has a very specific method signature - it doesn't match the method signature of ExitWindows.
Raymond CHEN wrote:
*
*in 2004 "What can go wrong when you mismatch the calling convention?":
The function signature required for functions called by rundll32.exe is:
void CALLBACK ExitWindowsEx(HWND hwnd, HINSTANCE hinst,
LPSTR pszCmdLine, int nCmdShow);
That hasn't stopped people from using rundll32 to call random functions that weren't designed to be called by rundll32, like user32 LockWorkStation or user32 ExitWindowsEx.
(oops)
The actual function signature for ExitWindowsEx is:
BOOL WINAPI ExitWindowsEx(UINT uFlags, DWORD dwReserved);
*
*in 2011: "Throwing garbage on the sidewalk: The sad history of the rundll32 program"
And to make it crystal-clear:
*
*in 2013 "What's the guidance on when to use rundll32? Easy: Don't use it":
Rundll32 is a leftover from Windows 95, and it has been deprecated since at least Windows Vista because it violates a lot of modern engineering guidelines.
A: If you are on a remote machine, you may also want to add the -f option to force the reboot. Otherwise your session may close and a stubborn app can hang the system.
I use this whenever I want to force an immediate reboot:
shutdown -t 0 -r -f
For a more friendly "give them some time" option, you can use this:
shutdown -t 30 -r
As you can see in the comments, the -f is implied by the timeout.
Brutus 2006 is a utility that provides a GUI for these options.
A: Some additions to the shutdown and rundll32.exe shell32.dll,SHExitWindowsEx n commands.
LOGOFF - allows you to logoff user by sessionid or session name
PSShutdown - requires a download from windows sysinternals.
bootim.exe - windows 10/8 shutdown iu
change/chglogon - prevents new users to login or take another session
NET SESSION /DELETE - ends a session for user
wusa /forcerestart /quiet - windows update manager but also can restart the machine
tsdiscon - disconnects you
rdpinit - logs you out , though I cant find any documentation at the moment
A: Another small tip: when going the batch file route, I like to be able to abort it in case I run it accidentally. So the batch file invokes the shutdown but leaves you at the command prompt afterwards.
@echo off
echo Shutting down in 10 seconds. Please type "shutdown /a" to abort.
cmd.exe /K shutdown /f /t 10 /r
Plus, since it's on a timer, you get about the same thrill as you do when hunting in The Oregon Trail.
A: The most common ways to use the shutdown command are:
*
*shutdown -s — Shuts down.
*shutdown -r — Restarts.
*shutdown -l — Logs off.
*shutdown -h — Hibernates.
Note: There is a common pitfall wherein users think -h means "help" (which it does for every other command-line program... except shutdown.exe, where it means "hibernate"). They then run shutdown -h and accidentally turn off their computers. Watch out for that.
*shutdown -i — "Interactive mode". Instead of performing an action, it displays a GUI dialog.
*shutdown -a — Aborts a previous shutdown command.
The commands above can be combined with these additional options:
*
*-f — Forces programs to exit. Prevents the shutdown process from getting stuck.
*-t <seconds> — Sets the time until shutdown. Use -t 0 to shutdown immediately.
*-c <message> — Adds a shutdown message. The message will end up in the Event Log.
*-y — Forces a "yes" answer to all shutdown queries.
Note: This option is not documented in any official documentation. It was discovered by these StackOverflow users.
I want to make sure some other really good answers are also mentioned along with this one. Here they are in no particular order.
*
*The -f option from JosephStyons
*Using rundll32 from VonC
*The Run box from Dean
*Remote shutdown from Kip
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "678"
} |
Q: How to launch a Windows process as 64-bit from 32-bit code? To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick:
ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */, windir + "\\Reg", "add HKLM\\Software\\Company\\KeyName /v valueName /t REG_MULTI_TZ /d ValueData", NULL, SW_HIDE);
This solution works fine, besides that our application is a 32-bit one, and it runs the REG.EXE command as it would be a 32-bit app using the WOW compatibility layer! :( If REG.EXE is ran from the command line, it's properly ran in 64-bit mode. This matters, because if it's ran as a 32-bit app, the registry keys will end up in the wrong place due to registry reflection.
So is there any way to launch a 64-bit app programmatically from a 32-bit app and not have it run using the WOW64 subsystem like its parent 32-bit process (i.e. a "*" suffix in the Task Manager)?
A: Whether a 32-bit or 64-bit native (unmanaged) program is run depends solely on the executable. There are two copies of reg.exe, in C:\Windows\System32 (64-bit) and C:\Windows\SysWOW64 (32-bit). Because you don't specify a path, you're getting whatever appears first in the PATH environment variable, which is the 32-bit version for a 32-bit process.
You should really factor this function out into a separate program or COM object, and mark the program with a manifest, or launch the COM object using the COM elevation moniker.
A: Have you considered creating a small "helper" application to make the registry update for you? If you compile it to 64bit and include a manifest that indicates it requires administrator rights, then it'll cover both bases for you.
There are API's to detect the "bitness" of the OS you're running on so you could, conceivably, compile both RegistryUpdate32.exe and RegistryUpdate64.exe and call the relevant one.
A: try this (from a 32bit process):
> %WINDIR%\sysnative\reg.exe query ...
(found that here).
A: One thing that I've done as a solution for myself is to PInvoke disabling redirection:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx
You can always turn it right back on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: What is the role of Spring in Struts + Spring + Hibernate? What role is Spring taking in Struts + Spring + Hibernate?
A: Well, Hibernate handles the persistence part, JSP handles your GUI, Struts controls the flow between pages/actions/etc, and Spring can manage all your beans which contain the main business logic, instead of using EJB. Plus it can simplify the coding of your Hibernate DAO's and transaction managing.
Instead of having to code your Locator to obtain some EJB through JNDI and all that stuff, you can just get the Spring ApplicationContext and ask for the bean you need. All the beans defined in Spring can be interconnected. If you have to connect one of your beans to an external EJB through JNDI you can even do so without any code (Spring offers a JNDI proxy object which obtains the reference you give it and returns it as an object with the interface you specify). This can help you simplify unit testing of all those beans and change the config without recoding anything; you can use one of Spring's PlatformTransactionManagers to manage a DataSource or point it to a J2EE container's JTA manager; define your own pooled DataSource or use your container's DataSource published through JNDI, etc.
A: Spring provides many different "modules" and different programmers will use different parts of Spring.
However, commonly in this sort of stack, you will see Spring being used as a provider of
*
*An inversion of control container for dependency injection
*An abstraction to Hibernate called "HibernateTemplate"
*Framework classes for simplifying Aspect Oriented Programming
*Transaction support, often "declaratively" via the IoC container and AOP.
A: Well to add;
(Views and Controllers) Struts for its extensive JSP features with Struts tags and web request handling features
(Service and application management) Spring to handle the ORM and service layers with its excellent dependency injections,etc.
(ORM with db independence) Hibernate for well proven ORM
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Firebird 1.5.3: How to add FK with connected users to the DB? I use FB1.5.3 and need to eventually add some FK to the database.
It happens that if I try to do it while anyone else is connected to the DB I get an exception.
Is there a way to add an FK while the system is running?
A: There's no way.
It's a known limitation that has been removed in Firebird 2.0. You should either upgrade, or live with it.
A: I believe this is a limitation on firebird 1.5 and earlier.
Try google for (firebird foreign key "object is in use").
hth
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SQL Duplicate Delete Query over Millions of Rows for Performance This has been an adventure. I started with the looping duplicate query located in my previous question, but each loop would go over all 17 million records, meaning it would take weeks (just running *select count * from MyTable* takes my server 4:30 minutes using MSSQL 2005). I gleamed information from this site and at this post.
And have arrived at the query below. The question is, is this the correct type of query to run on 17 million records for any type of performance? If it isn't, what is?
SQL QUERY:
DELETE tl_acxiomimport.dbo.tblacxiomlistings
WHERE RecordID in
(SELECT RecordID
FROM tl_acxiomimport.dbo.tblacxiomlistings
EXCEPT
SELECT RecordID
FROM (
SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank
FROM tl_acxiomimport.dbo.tblacxiomlistings
) al WHERE Rank = 1)
A: Seeing the QueryPlan would help.
Is this feasible?
SELECT m.*
into #temp
FROM tl_acxiomimport.dbo.tblacxiomlistings m
inner join (SELECT RecordID,
Rank() over (Partition BY BusinessName,
latitude,
longitude,
Phone
ORDER BY webaddress DESC,
caption1 DESC,
caption2 DESC ) AS Rank
FROM tl_acxiomimport.dbo.tblacxiomlistings
) al on (al.RecordID = m.RecordID and al.Rank = 1)
truncate table tl_acxiomimport.dbo.tblacxiomlistings
insert into tl_acxiomimport.dbo.tblacxiomlistings
select * from #temp
A: Something's up with your DB, server, storage or some combination thereof. 4:30 for a select count * seems VERY high.
Run a DBCC_SHOWCONTIG to see how fragmented your table is, this could cause a major performance hit over a table that size.
Also, to add on to the comment by RyanKeeter, run the show plan and if there are any table scans create an index for the PK field on that table.
A: Wouldn't it be more simple to do:
DELETE tl_acxiomimport.dbo.tblacxiomlistings
WHERE RecordID in
(SELECT RecordID
FROM (
SELECT RecordID,
Rank() over (Partition BY BusinessName,
latitude,
longitude,
Phone
ORDER BY webaddress DESC,
caption1 DESC,
caption2 DESC) AS Rank
FROM tl_acxiomimport.dbo.tblacxiomlistings
)
WHERE Rank > 1
)
A: Run this in query analyzer:
SET SHOWPLAN_TEXT ON
Then ask query analyzer to run your query. Instead of running the query, SQL Server will generate a query plan and put it in the result set.
Show us the query plan.
A: 17 million records is nothing. If it takes 4:30 to just do a select count(*) then there is a serious problem, probably related to either lack of memory in the server or a really old processor.
For performance, fix the machine. Pump it up to 2GB. RAM is so cheap these days that its cost is far less than your time.
Is the processor or disk thrashing when that query is going? If not, then something is blocking the calls. In that case you might consider putting the database in single user mode for the amount of time it takes to run the cleanup.
A: So you're deleting all the records that aren't ranked first? It might be worth comparing a join against a top 1 sub query against (which might also work in 2000, as rank is 2005 and above only)
Do you need to remove all the duplicates in a single operation? I assume that you're preforming some sort of housekeeping task, you might be able to do it piece-wise.
Basically create a cursor that loops all the records (dirty read) and removes dupes for each. It'll be a lot slower overall, but each operation will be relatively minimal. Then your housekeeping becomes a constant background task rather than a nightly batch.
A: The suggestion above to select into a temporary table first is your best bet. You could also use something like:
set rowcount 1000
before running your delete. It will stop running after it deletes the 1000 rows. Then run it again and again until you get 0 records deleted.
A: if i get it correctly you query is the same as
DELETE tl_acxiomimport.dbo.tblacxiomlistings
FROM
tl_acxiomimport.dbo.tblacxiomlistings allRecords
LEFT JOIN (
SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank
FROM tl_acxiomimport.dbo.tblacxiomlistings
WHERE Rank = 1) myExceptions
ON allRecords.RecordID = myExceptions.RecordID
WHERE
myExceptions.RecordID IS NULL
I think that should run faster, I tend to avoid using "IN" clause in favor of JOINs where possible.
You can actually test the speed and the results safely by simply calling SELECT * or SELECT COUNT(*) on the FROM part like e.g.
SELECT *
FROM
tl_acxiomimport.dbo.tblacxiomlistings allRecords
LEFT JOIN (
SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank
FROM tl_acxiomimport.dbo.tblacxiomlistings
WHERE Rank = 1) myExceptions
ON allRecords.RecordID = myExceptions.RecordID
WHERE
myExceptions.RecordID IS NULL
That is another reason why I would prefer the JOIN approach
I hope that helps
A: This looks fine but you might consider selecting your data into a temporary table and using that in your delete statement. I've noticed huge performance gains from doing this instead of doing it all in that one query.
A: Remember when doing a large delete it is best to have a good backup first.(And I also usually copy the deleted records to another table just in case, I need to recover them right away. )
A: Other than using truncate as suggested, I've had the best luck using this template for deleting lots of rows from a table. I don't remember off hand, but I think using the transaction helped to keep the log file from growing -- may have been another reason though -- not sure. And I usually switch the transaction logging method over to simple before doing something like this:
SET ROWCOUNT 5000
WHILE 1 = 1
BEGIN
begin tran
DELETE FROM ??? WHERE ???
IF @@rowcount = 0
BEGIN
COMMIT
BREAK
END
COMMIT
END
SET ROWCOUNT 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get the checked option in a group of radio inputs with JavaScript? How to get the checked option in a group of radio inputs with JavaScript?
A: http://www.somacon.com/p143.php
A: If you need the actual element and not just the selected value, try this:
function findSelected(){
for (i=0;i<document.formname.radioname.length;i++){
if (document.formname.radioname[i].checked){
return document.formname.radioname[i];
}
}
}
A: <html>
<head>
<script type="text/javascript">
function testR(){
var x = document.getElementsByName('r')
for(var k=0;k<x.length;k++)
if(x[k].checked){
alert('Option selected: ' + x[k].value)
}
}
</script>
</head>
<body>
<form>
<input type="radio" id="r1" name="r" value="1">Yes</input>
<input type="radio" id="r2" name="r" value="2">No</input>
<input type="radio" id="r3" name="r" value="3">Don't Know</input>
<br/>
<input type="button" name="check" value="Test" onclick="testR()"/>
</form>
</body>
</html>
A: generic functions (loosely based on yours )
function getRadioGroupSelectedElement(radioGroupName) {
var radioGroup = document.getElementsByName(radioGroupName);
var radioElement = radioGroup.length - 1;
for(radioElement; radioElement >= 0; radioElement--) {
if(radioGroup[radioElement].checked){
return radioGroup[radioElement];
}
}
return false;
}
function getRadioGroupSelectedValue(radioGroupName) {
var selectedRadio = getRadioGroupSelectedElement(radioGroupName);
if (selectedRadio !== false) {
return selectedRadio.value;
}
return false;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Finding the default application for opening a particular file type on Windows I'm developing an application targeting .NET Framework 2.0 using C# for which I need to be able to find the default application that is used for opening a particular file type.
I know that, for example, if you just want to open a file using that application you can use something like:
System.Diagnostics.Process.Start( "C:\...\...\myfile.html" );
to open an HTML document in the default browser, or
System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" );
to open a text file in the default text editor.
However, what I want to be able to do is to open files that don't necessarily have a .txt extension (for example), in the default text editor, so I need to be able to find out the default application for opening .txt files, which will allow me to invoke it directly.
I'm guessing there's some Win32 API that I'll need to P/Invoke in order to do this, however a quick look with both Google and MSDN didn't reveal anything of much interest; I did find a very large number of completely irrelevant pages, but nothing like I'm looking for.
A: All current answers are unreliable. The registry is an implementation detail and indeed such code is broken on my Windows 8.1 machine. The proper way to do this is using the Win32 API, specifically AssocQueryString:
using System.Runtime.InteropServices;
[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern uint AssocQueryString(
AssocF flags,
AssocStr str,
string pszAssoc,
string pszExtra,
[Out] StringBuilder pszOut,
ref uint pcchOut
);
[Flags]
public enum AssocF
{
None = 0,
Init_NoRemapCLSID = 0x1,
Init_ByExeName = 0x2,
Open_ByExeName = 0x2,
Init_DefaultToStar = 0x4,
Init_DefaultToFolder = 0x8,
NoUserSettings = 0x10,
NoTruncate = 0x20,
Verify = 0x40,
RemapRunDll = 0x80,
NoFixUps = 0x100,
IgnoreBaseClass = 0x200,
Init_IgnoreUnknown = 0x400,
Init_Fixed_ProgId = 0x800,
Is_Protocol = 0x1000,
Init_For_File = 0x2000
}
public enum AssocStr
{
Command = 1,
Executable,
FriendlyDocName,
FriendlyAppName,
NoOpen,
ShellNewValue,
DDECommand,
DDEIfExec,
DDEApplication,
DDETopic,
InfoTip,
QuickTip,
TileInfo,
ContentType,
DefaultIcon,
ShellExtension,
DropTarget,
DelegateExecute,
Supported_Uri_Protocols,
ProgID,
AppID,
AppPublisher,
AppIconReference,
Max
}
Relevant documentation:
*
*AssocQueryString
*ASSOCF
*ASSOCSTR
Sample usage:
static string AssocQueryString(AssocStr association, string extension)
{
const int S_OK = 0;
const int S_FALSE = 1;
uint length = 0;
uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length);
if (ret != S_FALSE)
{
throw new InvalidOperationException("Could not determine associated string");
}
var sb = new StringBuilder((int)length); // (length-1) will probably work too as the marshaller adds null termination
ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length);
if (ret != S_OK)
{
throw new InvalidOperationException("Could not determine associated string");
}
return sb.ToString();
}
A: Doh! Of course.
HKEY_CLASSES_ROOT\.txt
includes a reference to
HKEY_CLASSES_ROOT\txtfile
which contains a subkey
HKEY_CLASSES_ROOT\txtfile\shell\open\command
which references Notepad.
Sorted, many thanks!
Bart
A: Here is a blog post with about this topic. The code samples are in VB.net, but it should be easy to port them to C#.
A: You can just query the registry. First get the Default entry under HKEY_CLASSES_ROOT\.ext
That will give you the classname. For example .txt has a default of txtfile
Then open up HKEY_CLASSES_ROOT\txtfile\Shell\Open\Command
That will give you the default command used.
A:
A late answer, but there is a good NUGET package that handles file associations: File Association
Link NUGET File Association
Usage is simple, for instance to add all allowed file extensions to a context menu:
private void OnMenuSourceFileOpening(object sender, ...)
{ // open a context menu with the associated files + ".txt" files
if (File.Exists(this.SelectedFileName))
{
string fileExt = Path.GetExtension(this.SelectedFileNames);
string[] allowedExtensions = new string[] { fileExt, ".txt" };
var fileAssociations = allowedExtensions
.Select(ext => new FileAssociationInfo(ext));
var progInfos = fileAssociations
.Select(fileAssoc => new ProgramAssociationInfo (fileAssoc.ProgID));
var toolstripItems = myProgInfos
.Select(proginfo => new ToolStripLabel (proginfo.Description) { Tag = proginfo });
// add also the prog info as Tag, for easy access
// when the toolstrip item is selected
// of course this can also be done in one long linq statement
// fill the context menu:
this.contextMenu1.Items.Clear();
this.contextMenuOpenSourceFile.Items.AddRange (toolstripItems.ToArray());
}
}
A: You can check under registry section HKEY_CLASSES_ROOT for the extension and action details. Documentation for this is on MSDN. Alternatively, you can use the IQueryAssociations interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
} |
Q: What is wrong with DateTime.Parse(myString)? I was browsing Scott Hanselman's Developer Interview question list, and ran across this question:
What is wrong with
DateTime.Parse(myString)?
While I know there are inherent risks in parsing a string of unknow format or origin, are there other reasons? Is it to use DateTime.ParseExact instead? Should it be myString.ToString() first?
A: As MSDN Puts it:
Because the Parse(String) method tries
to parse the string representation of
a date and time using the formatting
rules of the current culture, trying
to parse a particular string across
different cultures can either fail or
return different results. If a
specific date and time format will be
parsed across different locales, use
the DateTime.Parse(String,
IFormatProvider) method or one of the
overloads of the ParseExact method and
provide a format specifier.
A: That question is just to see if the developer knows the issues with that. First you should use TryParse because Parse throws an exception if it's unparseable. Also it doesn't take locale into account so in a web scenario, if a british User types 02/10/2008, and my server is using an en-US locale, I get February 10,2008 instead of October 2, 2008.
There might be other issues but those are the first two that sprung to mind.
A: In addition the locale problem, DateTime.Parse() could also throw an exception which you would then have to catch. Use DateTime.TryParse() or DateTime.TryParseExact() instead.
A: Using the current thread culture on the system is often a bad idea, as is "try a variety of formats, and see if any of them work."
ParseExact with a specific culture is a much more controlled and precise approach. (Even if you specify the current culture, it makes it more obvious to readers that that's what's going on.)
A: In addition to unknown user input the environment may be unknown.., so I guess that even if you control the input format, what the parse expect may be different..
A: My gut reaction is going to be that you hit it with unknown formats/origins. There may be other reasons -- for example, from that single line, do we know that myString is a string? (I'm assuming it is, of course.)
Generally I recommend the TryParse method instead. It's slightly more verbose, but helps prevent exceptions -- as long as your code behaves appropriately in the case of invalid input.
Of course, based on your wording to this ... I assume you already knew all that. :)
A: this blog post explains it, but the general thing is that there's no cultureinfo associated with the parse.
A: The answer depends on the code which surrounds DateTime.Parse(myString) and the requirements of the parse
You may already have check the string is a valid format based on a regex and you may not be interesting in Culture Information. You may also know that the data comes from a known file format with a known date convention so throwing an exception may be exactly what is desired.
Without context the question is quite ambiguous and the real answer to it has to be "it depends on the context where the code is used as to what is wrong with it, if an
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: With WinDbg, can I modify an item in memory while a process is running? Can I, using an address found in a map file, use windbg to alter a variable in memory while the app is running?
I'm really interested in turning on/off functionality in run-time maybe with a variable.
How would you do this? Does it require breaking the app through the debugger?
A: If you have the address, you can use the any of the e* (Enter Value) commands.
You can attach to any running process if you know the process id, or you can launch the exe directly with cdb. You do have to break the process to make any modifications. In CDB, you can use Ctrl+C, and the it will inject a DebugBreak into the process, you can then look at the stack, threads, and memory.
A: I just did it. Assuming you got the symbos mapped, and are in a breakpoint where you can see a variable, you just do this - assuming "myvar" is an integer:
?? myvar
[[ this shows the current contents ]]
?? myvar=55
[[ this will change the value of myvar to 55]]
?? myvar
[[ this will show the updated contents of my var - which is 55 ]]
g
[[ your program will now run, and the next read of myvar will produce 55 ]]
A: You can set a breakpoint that is only hit once and edit a value and continue execution.
Something like:
bp /1 012ABCDEF "myVar=42;g"
replace the above with your address value and your variable name.
A: I'm not sure what exactly you trying to achieve, but debugger should be activated on some event (exception, break point or something), after it's activated, for example you can have a thread that create an exception and after get control back check the variable.
In debugger you can set a break point with command, see this guide, what will change the parameter.
I hope that this answer your question, if not please clarify the question.
In case of break point with command the application will be break and will continue execution without human intervention, i don't know any way how debugger can do something without application stops execution.
Just a thought, are you sure you need debugger for this? Can't you just use registry for that and use this to get notification about registry change.
A: You can definately do that. Either break on a function and edit it in the locals window. Or use e commands to edit values. Check out the windbg help for more on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there any way to create a patch for an ASP.Net web application installer? Is it possible to create patch installers for web deployment installers generated in VS2005?
I have a situation in which it is undesirable to perform a complete uninstall/reinstall of a web site, but in which periodic bug fixes and minor upgrades are made.
I've tried following the instructions in various online posts about using msimsp.exe to generate a patch file, but most/all of them rely on some usage of msiexec.exe to create an administrative install for comparison, since msimsp.exe can't cope with compressed content (e.g. CAB files). Web installations don't really have an administrative install, however, and ultimately the patch creation fails.
Of course, I can create an installer containing just the changed files by hand, but that's prone to error, and having an automated process is more desirable.
Any help is appreciated.
A: We deploy using Subversion.
http://blog.lavablast.com/post/2008/02/I2c-for-one2c-welcome-our-new-revision-control-overlords!.aspx
A: The WIX (Windows Installer XML) documentation has a section on Patch Building using a Patch Creation Properties (PCP) authoring file for creating a delta patch file.
A: Thanks for the suggestion but again, this is a web installer. All of the documentation I've found for generating patch files with PCP and MSIMSP.EXE involves performing an administrative installation of the installers. There isn't really an administrative install for a web installer (at least not the kind generated in VS2005), so the MSIMSP.EXE patch generation process kind of short-circuits there.
I'm looking into InstallShield to see if any finer control is available there...
A: Sorry for not helping, I can however tell you how we use WIX to create the installation for our web-site.
We have created a WIX template (Plan Old XML), and we then traverse the build output folder using an utility we wrote our-selves to get the list of folders and files that need to go into the resulting WIX file. This process is rolled into the build (MSBuild) for the web-site, so the MSI creation is automatic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Streaming audio to a browser I have a large amount of audio stored on my web server in a very custom format that can't be replayed by anything other than my own application. That application is a Win32 app that can connect to my web server and stream and replay that audio.
I'd really like to be able to do the streaming and replaying from within a browser, but don't know where to start. Ideally I'd like the technology to be cross-platform (unlike my current Win32 app) and cross-browser (IE 6 and above and Firefox).
My current thoughts are to look at things like:
*
*Flash, but doesn't that only replay mp3 audio?
*Java, are VMs freely available still?
*Converting the audio to a WAV file on the web server and then using someone else's plugin to replay that file. I'd rather keep the conversion off the web server for performance reasons, but is still an option.
*Writing my own custom plugin to do the complete stream and replay operation.
Any guidance would be most useful.
Please note that the audio is not music and that simply converting to another audio format is not trivial. The audio that is stored also changes frequently (every minute) would need constant conversion.
A: Why are you using a proprietary music format? I'd probably not even bother downloading a program to listen to it.
I would suggest you convert it to mp3 and then use flash.
Building your own plugin would probably be hard, there are so many different platforms you'd have to cater for, something like flash is written for them already.
A: Apart from converting server-side: Implement a decoder for your format in ActionScript or Java. Then you can write a Flash movie or Java applet that plays it. Both languages/runtimes should be fast enough to decode in realtime unless your format is very complex. Flash would be the more accessible of the two, since nearly everyone has the plugin installed. (It's possible that playing a raw sound buffer isn't supported by older Flash versions than 10, I'm no expert on that.) The Java plugin is definitely free, but you'd require the users to install it.
A: I'd go with converting the audio to WAV (or MP3) on the server. Writing your own cross-platform browser component would be a lot of work, thanks to the different ways the major OSes handle their audio APIs.
A: Try taking a look at shoutcast.
Basically its a server app that will stream music to any client that connects to it through a browser (effectively your own radio station). I've never used it myself but should be straight forward.
Another idea is winamp remote. Again you install the app on the server but this time you can browse your music collection on their website and play individual songs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Web Services authentication - best practices? We have SOAP web services in production that are relying on SOAP Headers (containing plain client credentials) for the authentication. The WS are used in heterogeneous environments with .NET/Java/PHP/Python/C++ clients both web app or desktop app.
We are considering a v2 for those WS and I am wondering what are considered as the best practices for WS SOAP authentication? (reasonably secure, yet easy to handle on a wide variety of platforms).
A: If you have to roll it all yourself and can't use HTTPS, I'd suggest the hash-based UsernameToken portion of WS-Security. It's pretty secure and fairly easy to implement as long as your libraries have the hashing functions.
If you're doing web services, I wouldn't rely on HTTP for authentication.
WS-Security as a whole is way too big.
A: The way I have tackled this in the past is to use the standard WS-* features.
Instead of using the authentication feature we set the message header integrity feature on. This requires both sides of the dialog have access to public/private key pair and detects any tampering of the username field in the header. So you can be sure whoever sent the message and set the user id has access to the private key.
This provides a reasonable level of integrity if the keys are managed properly.
A: The easiest way to handle it across a variety of platforms is to use HTTP basic authentication and HTTPS for the transport layer. WS-Security would be good if your needs go beyond simple username/password but the support is going to vary quite a bit between platforms. HTTP authentication is supported by every decent SOAP implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: SQL count query Hi why doesn't this work in SQL Server 2005?
select HALID, count(HALID) as CH from Outages.FaultsInOutages
where CH > 3
group by HALID
I get invalid column name 'CH'
i think having was the right way to go but still receive the error:
Invalid column name 'CH'.
When running:
select HALID, count(HALID) as CH from Outages.FaultsInOutages
group by HALID having CH > 3
A: Try
select HALID, count(HALID) from Outages.FaultsInOutages
group by HALID having count(HALID) > 3
Your query has two errors:
*
*Using where an aggregate when grouping by, solved by using having
*Using an alias for an aggregate in the condition, not supported, solved by using the aggregate again
A: You can't use the alias in the where clause or having clause, as it isn't processed until AFTER the result set is generated, the proper syntax is
SELECT HALID, COUNT(HALID) AS CH
FROM Outages.FaultsInOutages
GROUP BY HALID
HAVING COUNT(HALID) > 3
This will group items on HALID, then ONLY return results that have more than 3 entries for the specific HALID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the point of @import? Can someone explain what are the benefits of using the @import syntax comparing to just including css using the standard link method?
A: As the answerer said, it lets you split your CSS into multiple files whilst only linking to one in the browser.
That said, it's still wasteful to have multiple CSS files downloading on high-traffic websites. Our build script actually "compiles" our CSS when building in release mode by doing the following:
*
*All CSS files are minified (extra whitespace and comments removed)
*We have a "core.css" file that's just a list of @import statements; during compilation, each of these is replaced by the minified CSS of that file
Thus we end up with a single, minified CSS file in production, whilst in development mode we have the separate files to make debugging easier.
A: If you use <link>s in your HTML files, all those files have to keep track of all the CSS files. This obviously makes changes and additions (both for CSS and HTML files) harder.
Using @import, you reduce a theoretically infinite number of changes down to one.
A: @import allows you have an extensible styesheet without having to change the html. You can link once to your main sheet and then if you want to add or remove additional sheets your html doesn't change.
Also, more smaller files help the browser do better caching. If you make a change in one part of a large sheet, the entire sheet must be downloaded again for every user. If the styles are separated into logical areas among a few sheets, only the file containing the part that changed needs to be downloaded. Of course, this comes at the cost of additional http requests.
A: One other handy bit, although pretty outdated, is that Netscape 4 couldn't handle @import, so it is a good way of serving a stylesheet to NS4, then having another stylesheet for more modern browsers that was imported in a standards compliant way.
A: @import is CSS code. <link> is HTML code. So, if you want to include stylesheets in other stylesheets (or if you can’t change HTML), @import is the way to go.
According to the CSS spec, all @import declarations must appear before any style rules in your stylesheet. In other words, all at the top of your stylesheet
Any @import declarations that appear after style rules should be ignored. Internet Explorer has never respected this; I believe other browsers do. This makes @import a bit less useful, because rules in a stylesheet that’s imported will be overriden by rules of equal specificity in the importing stylesheet.
A: It allows you to keep your logic CSS file spread over multiple physical files. Helps in team development, for example. Also useful when you have a lot of CSS files that you want to separate by functional areas (one for grids, one for lists, etc), let have accessible in the same logical file.
A: Say you work for Massive Dynamics, Corp.. It has a Widgets division. The Widgets division has an Accounts department. Accounts is divided into Accounts Payable and Accounts Receivable.
Using @include, you start the website with one top-level global.css stylesheet, which applies to everything.
Then you create a second stylesheet, widgets.css for the Widgets division. It @includes the global one, and its own styles (which can over-ride the global styles if needed, because of the Cascade). Then you create a third accounts.css for Accounts. It @includes widgets.css, which means it also includes global.css. Lather, rinse, repeat.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: With Rails, where should I put html snippets? I don't want partials but I want them reloaded during development Being lazy (and liking DRY code), I'm the kind of guy who's going to write a few little wrappers for recurring HTML markup. Those provided by Rails are good already, but sometimes I have something a little more specific that I know I'm going to repeat over and over.
In some situations a partial can be the solution, but sometimes I'm just going to call the snippet way too often to justify the overhead of using partials.
Right now I create a helpers/html_helper.rb file and stick them in there. The problem is that helpers are not reloaded dynamically per request during development. So each time I tweak my snippet or the code around it, I have to kill the server and restart it.
Granted, it's just a 5 seconds process, but I love Rails' convenience of just developing and then refreshing the browser. So I'd love to have that for my markup snippets as well.
Note: Just sticking 'unloadable' inside the helper module doesn't work.
A: Good question! This is a technique I should abuse more frequently.
#I go in environment.db (presumably it will work in one of the per-environment files, too.)
Dependencies.explicitly_unloadable_constants << 'NameOfHelperToReloadHere'
That array starts out empty, incidentally, at least in my install. (Checked via console.)
I tested this locally and it works for me, at least on Rails 2.0.2. Major credit for the solution belongs to this gentleman.
A: If you stick them in application_helper.rb they'll be loaded every time and be available for all of your views. This is loaded every time in development mode (or at least I haven't encountered any issues).
I typically will create little helpers that I use throughout the site (sortable table headers for instance) that use the same logic.
A: This should reload ALL helpers on every request (assuming you've stuck to the default naming conventions)
#Put this in config/environments/development.rb
ActiveSupport::Dependencies.explicitly_unloadable_constants.concat(Dir.glob("#{RAILS_ROOT}/app/helpers/**/*.rb").map {|file| File.basename(file, '.rb').camelize})
Or if you are using an older version of Rails (2.0.2 or earlier I think)
#Put this in config/environments/development.rb
Dependencies.explicitly_unloadable_constants.concat(Dir.glob("#{RAILS_ROOT}/app/helpers/**/*.rb").map {|file| File.basename(file, '.rb').camelize})
Works for me in RoR 2.1.1
Update: modified top snippet to include 'ActiveSupport::', must have copied / pasted incorrectly from my code.
A: It's not a real solution but you could use tests (TestUnit, RSpec or whatever) to make sure your helpers work as expected. That way, you wouldn't rely on automatic reloading of your helpers so much.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Track started applications in Windows We're trying to put together kiosk solution where we can charge people by hour for applications they use. As such, we need a way to figure out when an application is started, when it is closed and log this information for billing. I am a reasonably experienced .NET programmer so a managed code solution would be great. I have also dabbled in Windows API a little bit so that might work too. Any ideas out there?
A: This is simple enough with WMI calls. You can actually catch events from the OS on when an app is started, when it's closed, how long it was running, how much memory it used, etc.
Here is one example of monitoring process creating, deletion, etc.
http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx
A: If you're talking about applications you wrote yourself, just log DateTime.Now on either side of the Application.Run() method:
static void Main()
{
DateTime StartTime = DateTime.Now;
Application.Run(new frmBilling());
DateTime EndTime = DateTime.Now;
//Log information to DB for billing
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to know the real size of a web page? I wan't to know the real size of a web page (HTML + CSS + Javascript + Images + etc.) but from the browser side, maybe with a software, Firefox Add-On or similar?
A: YSlow is a FireBug plugin (Firebug is a FireFox plugin), and it works great.
If you meant the entire website, you could get HTTrack (Software) and download the entire site... just be careful.. people don't like it when you do that!
A: Use firefox, and get FireBug.
Then get the YSlow addon for firefox.
For IE, you can get the DebugBar which comes pretty close to giving the same information.
A: I think the Firefox Plugin Extended Statusbar can do that for you.
It will give detailed information about what has been downloaded, including the size of the downloaded data.
A: If you can't or don't want to use firefox and its plugins, you can use Pingdom Tools.
A: Firefox now embedded developper tools (in the tools menu, or Ctrl+Shift+S) has a "Network" tab which allows for detailed monitoring of size and load time of a webpage. The context menu (right click) allows to save data in HTTP archive format (HAR).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: SQL Join question I have 3 tables
*
*Links
Link ID
Link Name
GroupID (FK into Groups)
SubGroupID (FK into Subgroups)
*Groups
GroupID
GroupName
*SubGroup
SubGroupID
SubGroupName
GroupID (FK into Groups)
Every link needs to have a GroupID but teh SubGroupID is optional. How do i write a SQL query to show:
Links.LinkName, Groups.GroupName, SubGroup.SubGroupName
For the records with no subgroup just put a blank entry in that field. If i have 250 link rows, i should get back 250 reecords from this query.
Is there a way to do this in one query or do i need to do multiple queries?
A: This assumes that there is at most only 1 subgroup per group. if there are more, then you have the potential to get additional records.
select links.linkname, groups.groupname, subgroup.subgroupname
from links
inner join groups on (links.groupid = groups.groupid)
left outer join subgroup on (links.subgroupid = subgroup.subgroupid)
A: SELECT
links.linkname
, groups.groupname
, subgroup.groupname
FROM
links
JOIN groups ON links.groupid = groups.groupid
LEFT OUTER JOIN subgroups ON links.subgroupid = subgroup.subgroupid
(re-added to address OP's question)
incidentally, why not keep groups and subgroups in the same table, and use a self-referential join?
Akantro:
You'd have something like this:
create table groups(
groupid integer primary key,
parentgroupid integer foreign key references groups (groupid),
groupname varchar(50))
your query would then be
SELECT
links.linkname
, groups.groupname
, SUBGROUPS.groupname
FROM
links
JOIN groups ON links.groupid = groups.groupid
LEFT OUTER JOIN groups SUBGROUPS ON links.subgroupid = subgroup.groupid
there's no functional difference to keeping the tables like this, but the benefit is you only have to go to one place to edit the groups/subgroups
A: SELECT Links.LinkName, Groups.GroupName, SubGroup.SubGroupName -- Will potentially be NULL
FROM Links
INNER JOIN Groups
ON Group.GroupID = Links.GroupID
LEFT JOIN SubGroup
ON SubGroup.SubGroupID = Links.SubGroupID
A: You would use an Outer Join:
select Links.LinkName, Groups.GroupName, SubGroup.SubGroupName
from Links
inner join Groups on Groups.GroupID = Links.GroupID
left outer join SubGroup on Links.SubGroupID = SubGroup.SubGroupID
A: You're not too clear, but I think you want to get all rows including those that don't have a correspondent in the SubGroup table.
For this you can use LEFT JOIN, it will fetch NULLs if there are no matching rows.
A: Just use a LEFT OUTER JOIN on the SubGroup table like:
select
l.LinkName,
g.GroupName,
s.SubGroupName
from
Links l
'
JOIN Group g
on ( g.GroupId = l.GroupId)
'
LEFT OUTER JOIN SubGroup s
on ( s.SubGroupId = l.SubGroupId )
That should do it.
A: SELECT LinkName, GroupName, SubGroupNamne
FROM Links INNER JOIN Groups ON LInks.GroupID = Groups.GroupID
LEFT JOIN SubGroup ON Links.SubGroupID = SubGroup.SubGroupID
This will include rows that do not have a sub group. That column will simply be NULL.
A: select L1.LinkName, G1.GroupName, NVL(S1.SubGroupName,' ')
from Links L1, Groups G1, SubGroup S1
where L1.GroupID = G1.GroupID and
L1.GroupID = S1.GroupID
A: Okay, try:
select a.linkname, b.groupname, c.subgroupname
from links a, groups b, subgroup c
where a.groupid = b.groupid
and a.subgroupid = c.subgroupid
and a.subgroupid is not null
union all
select a.linkname, b.groupname, ' '
from links a, groups b
where a.groupid = b.groupid
and a.subgroupid is null
I think that should work (it does in DB2 which is the DBMS I use most) - you'll need to adjust the spaces in the second select to match the subgroup.subgroupname size.
A: Use a LEFT OUTER JOIN on the SubGroup table will give you all rows from the Links table and where a SubGroup exists will return that otherwise you see a NULL value.
SELECT L.LinkName, G.GroupName, S.SubGroupName
FROM Links As L
INNER JOIN Groups As G ON L.GroupID=G.GroupID
LEFT OUTER JOIN SubGroup S ON L.SubGroupID=S.SubGroupID
This does not check that your SubGroups.LinkID matches the Links.LinkID which should never happen but if you need to check this then add in another clause to the join:
SELECT L.LinkName, G.GroupName, S.SubGroupName
FROM Links As L
INNER JOIN Groups As G ON L.GroupID=G.GroupID
LEFT OUTER JOIN SubGroup S ON L.SubGroupID=S.SubGroupID AND L.GroupID=S.GroupID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: 'const int' vs. 'int const' as function parameters in C++ and C Consider:
int testfunc1 (const int a)
{
return a;
}
int testfunc2 (int const a)
{
return a;
}
Are these two functions the same in every aspect or is there a difference?
I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.
A: const int is identical to int const, as is true with all scalar types in C. In general, declaring a scalar function parameter as const is not needed, since C's call-by-value semantics mean that any changes to the variable are local to its enclosing function.
A: They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions must be declared this way:
int getInt() const;
It changes the this pointer in the function from Foo * const to Foo const * const. See here.
A: The trick is to read the declaration backwards (right-to-left):
const int a = 1; // read as "a is an integer which is constant"
int const a = 1; // read as "a is a constant integer"
Both are the same thing. Therefore:
a = 2; // Can't do because a is constant
The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:
const char *s; // read as "s is a pointer to a char that is constant"
char c;
char *const t = &c; // read as "t is a constant pointer to a char"
*s = 'A'; // Can't do because the char is constant
s++; // Can do because the pointer isn't constant
*t = 'A'; // Can do because the char isn't constant
t++; // Can't do because the pointer is constant
A: Yes, they are same for just int
and different for int*
A: This isn't a direct answer but a related tip. To keep things straight, I always use the convection "put const on the outside", where by "outside" I mean the far left or far right. That way there is no confusion -- the const applies to the closest thing (either the type or the *). E.g.,
int * const foo = ...; // Pointer cannot change, pointed to value can change
const int * bar = ...; // Pointer can change, pointed to value cannot change
int * baz = ...; // Pointer can change, pointed to value can change
const int * const qux = ...; // Pointer cannot change, pointed to value cannot change
A: const T and T const are identical. With pointer types it becomes more complicated:
*
*const char* is a pointer to a constant char
*char const* is a pointer to a constant char
*char* const is a constant pointer to a (mutable) char
In other words, (1) and (2) are identical. The only way of making the pointer (rather than the pointee) const is to use a suffix-const.
This is why many people prefer to always put const to the right side of the type (“East const” style): it makes its location relative to the type consistent and easy to remember (it also anecdotally seems to make it easier to teach to beginners).
A: I think in this case they are the same, but here is an example where order matters:
const int* cantChangeTheData;
int* const cantChangeTheAddress;
A: There is no difference. They both declare "a" to be an integer that cannot be changed.
The place where differences start to appear is when you use pointers.
Both of these:
const int *a
int const *a
declare "a" to be a pointer to an integer that doesn't change. "a" can be assigned to, but "*a" cannot.
int * const a
declares "a" to be a constant pointer to an integer. "*a" can be assigned to, but "a" cannot.
const int * const a
declares "a" to be a constant pointer to a constant integer. Neither "a" nor "*a" can be assigned to.
static int one = 1;
int testfunc3 (const int *a)
{
*a = 1; /* Error */
a = &one;
return *a;
}
int testfunc4 (int * const a)
{
*a = 1;
a = &one; /* Error */
return *a;
}
int testfunc5 (const int * const a)
{
*a = 1; /* Error */
a = &one; /* Error */
return *a;
}
A: Prakash is correct that the declarations are the same, although a little more explanation of the pointer case might be in order.
"const int* p" is a pointer to an int that does not allow the int to be changed through that pointer. "int* const p" is a pointer to an int that cannot be changed to point to another int.
See https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "135"
} |
Q: Asking to see employer's code/database in an interview I've been asked to write code/design things in an interview. Sometimes even to provide code samples. Very reasonable and very wise (always surprised when this DOESN'T happen)
I had a job a year or so back where the code was so awful that I would not have taken the job, if I'd seen the mess I had to deal with ahead of time. And I can't tell you how many horrendous databases I've had to work with.
Is it out of the question for me to ask them to provide a code sample and to view their database design? Assuming I'd be happy to sign an NDA, part of me feels it would insane to take a job without examining the codebase or database I'd be working with.
Anyone done this?
Update
This would be something I would ask later in the interview process, if things were proceeding well and I felt an offer was forthcoming.
It's also in the context of working in a small shop or small project as my preference is to avoid places that use phrases like "get a developer off the floor"
A: None of the candidates we have interviewed have ever asked that; however, many of them have been co-ops/interns in the company so they are familiar with our code...
Having said that, it is highly unlikely we will show our code to ANY candidate, regardless of an NDA. I would be happy to answer questions about what technologies we use, what system we use for revisions, practices around, etc. Actual code though? No.
Also in a large enough system (as ours is) someone can just show you the "best" code there is...and you would be where you started :) As for a database design...both companies I have worked at have had enormously large databases (university, corporate company)...so that wouldn't work either.
A: I've asked this in interviews with Xerox PARC, a startup, and Yahoo.
At PARC they sat me at a workstation with the code I'd take over if hired, went over the structure of the codebase super-briefly, and left me alone for around 20 minutes. This was enough to get an idea whether I could stand working with it, though I'd have liked some more time, like an hour total. Afterward I asked about a design decision that seemed dubious, and we chatted about the design and the style in general. This didn't just tell me more about the job, it told them more about me: did I explore their code top-down or bottom-up, what did I pick up on or ask about, etc. Valuable all around.
At the startup, they set up a separate meeting on another day, bringing in the author of the code (who wasn't an employee); we sat down at a laptop and went over things together. It was an unusual request to them and I think I had to sign a new NDA. This was once again worthwhile: my earlier interviews hadn't really cleared up what this fancy AI language was all about or what they'd want me to do with it, and sitting down with some concrete code blew away a lot of fog.
At Yahoo, I didn't see much of anything; I don't recall just what their response was. If I'd seen the code I ended up dealing with I might have had second thoughts (though it worked out all right in the end). (Both of the above codebases that I did get to see seemed generally nicer; the PARC one was open-sourced later on.)
In all these cases I shared some code of my own with them.
A: If you are going to do this then I think you need to give them a little warning so they can prepare an NDA and get an apppriate environment set up in which you can see it. Also be prepared to dedicate a little time to understanding why the code is in the shape it is.
If you turn up at your first interview and say, right, can I see the code, all but a very few people will say no. And not necessarily because they are evil and don't want to show you, but because it just isn't as simple as saying yes.
In my experience as a recruiter for a large software company it would have taken a considerable amount of time for us to disclose enough detail of the code and internally developed frameworks for any candidate - however bright - to be able to make a meaningful judgement of its pros and cons. We would only contemplate doing that if we were serious about hiring them.
If I were asked that question I woul say yes, come back another time and we'll arrange something. I would get a trustworthy developer off the floor and have them bring a laptop to the next interview and show a little of the code.
The reality is pretty much any software project which is of a reasonable size and has been in existence for more than one release will have some horrible scary rubbish in it.
A: Similarly to some of the other responses, I've never had a candidate ask to see our code. Even if they did I've be very careful to do so and most likely would not. As Swati mentions, pretty much any non-trivial system will have sections that look good so even seeing the code won't help that much.
Better than looking at actual code is the Joel Test. Basically it is 12 yes or no questions that you can ask an employer. The more yes answers, the better the work environment is expected to be. It's obviously not a hard and fast "rule", but it would seem to indicate those companies that take code (and coders) seriously.
A: I can't think a reason for not showing some classes or talking about the architecture they're using. From my point of view it's like asking them to show you where are you going to work (room, table, chairs, teammates...).
Anyhow, asking for it will show them you're interested in best practices and also that you're not desperate about finding a job at any price, and don't know how this can hurt.
A: Go to open source projects. There you don't have to ask for permission to see the code.
A: It can't hurt to ask and this is a very good idea which I am going to add to my checklist of questions to ask employers.
A: An interesting idea, but I don't know how many companies would go for it. I know we can't do it where I work now.
I think the biggest problem you're going to have with this is that I have found that a lot of people take offense to people not liking their code. It's like criticising someone's therapist, it's just not a good idea to be an outsider and do it. Seeing the code and then not taking the job could give you the reputation that you're arrogant or not good enough to work on the code and that's why you didn't take the job. It might save you from getting job you don't want, but it could give you a negative reputation down the line. I live in a sizable city, but the IT people still know one another and word spreads. People in our field have egos, and it's easier to trash somoene else's reputation than it is to admit that code you wrote isn't up to par.
A: You can definitely ask. The answer may be "No," but nobody should consider that to be a bad or inappropriate question.
If they won't show you the code, you should definitely take that into account when you decide whether you want to accept an offer. I would take it as a sign that at least one of the following things is true:
*
*The code is so horrible that they know you'll run away screaming.
*The company has an ultra-secretive trust-nobody culture (which I would hate).
*The company thinks they have such amazing code that just glancing at it would turn you into a superstar competitor. (In other words, they're self-deluded morons.)
*They have glaring security holes that they hope to keep secret.
*The people who are interviewing you don't know how to get the code themselves. (In which case you are not talking to the right people.)
A: I'd be more interested in seeing the company's systems - i.e. test framework, release process, autobuilds.... The presence or absence of those would tell me a lot more than a couple hundred lines of code.
A: I did ask: "Can I see some code and talk to programmers working here?"
The employer replied: "Sure! Come you can directly talk to our lead programmer of our information system!"
What an honor!
*
*they showed me concept papers
*I could talk to the lead programmer
*they showed me a small part of a very new project telling: "this is just a prototype, direct3d is so sketchy, that's why this code is so messy"
It turned out that:
*
*the lead programmer left the day I arrived
*the software he had the lead, was a big mess
*somehow I ended up spending 50% of my time, fighting against the mess
A: Even if they showed you some code, would that be sufficient for you to come to a rough conclusion about the quality of code that you would be spending time with? For example, at my previous place, one of their products was a large e-banking middleware application. The core of the application was in C++ and designed and written in a great way. However, the extensions (which by far covered a large part of the application and its various different versions), which were in C++ too, that were mostly coded by the less-experienced and less-knowledgeable developers were a pile of crappy code (which I had to fix and work with or write from scratch at times) slapped together to just somehow work. If I had asked them to show me a snippet of the code during the interview, and they had shown me some of the core stuff (the extension code actually mostly contained the client-specific business logic so it wouldn't make much sense without the business-domain knowledge, etc), I would've thought that the overall quality of the code is good (which was not completely the case).
A: More important than to ask for code snippets, I believe, is to ask them for which source code control product they use (run away from companies that answer "Visual SourceSafe") and which methodology they use: "Agile" or "Scrum" sends positive signals, CMMI usually means company loves bureaucratic processes, if they give you a "huh?" then you're warned ;)
A: I think this is a great idea; however, as an employer, I would be hesitant -- even with an NDA -- to provide an interview candidate samples of real, working code unless I was pretty sure I wanted to hire the person.
A: The problem is they will show you a little bit of code, but each of their programmers will write code in a different way. You are unluckily to have to work on the part of the code base that is well written.
Asking to see their coding standard and how they enforce it is more likely to be of use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: Spring MVC Form tags: Is there a standard way to add "No selection" item? There is a select dropdown and I want to add "No selection" item to the list which should give me 'null' when submitted.
I'm using SimpleFormController derived controller.
protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("countryList", Arrays.asList(Country.values()));
return map;
}
And the jspx part is
<form:select path="country" items="${countryList}" title="country"/>
One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to display this 'null' as 'No selection'.
Is there a better solution?
@Edit: I have solved this with a custom validation annotation which checks if the selected value is "No Selection". Is there a more standard and easier solution?
A: One option:
<form:select path="country" title="country" >
<form:option value=""> </form:option>
<form:options items="${countryList}" />
</form:select>
A: I don't think you should need a property editor for this. If the "blank" option is first in the list, and the tag that outputs the list doesn't mark any of them as selected, then the browser should select the first, "blank" one automatically.
When you submit the form, try and work it so that the "blank" value is bound to your command as a null, which might happen automatically, depending on the type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: Is there a way to script diagrams in SQL 2000 (or save them another way)? It's possible to create digrams in SQL Server 2000 that can be useful to show the relationships between tables. The problem we run into is that when somebody refreshes our development database, the diagrams get lost. We can load tables, stored procedures, views, etc. with SQL scripts, but we have to create the diagrams by hand.
Is there a way to script out the diagrams? Or can they be saved outside of the database some other way?
A: It can be done for SQL Server 2005 - see here.
And info. on SQL Server 2000 - here.
A: If you have Visio you can use the "Reverse Engineer" to diagram the DB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SSAS Cube Browsing not working after SQL 2008 CTP uninstall I've had SQL 2005 & 2008 CTP installed side-by-side with no problems.
Recently uninstalled the CTP after it expired and now whenever I try to browse an analysis services cube in SSMS 2005 or VS 2005, I get the follwoing error:
Retrieving the COM class factory for component with CLSID {C4F9B80B-89F7-4800-9C26-504D6E692B2C} failed due to the following error: 80040154.
I've tried re-installing Office Web Components but it's made no difference. I've also installed SQL 2008 SSMS RTM and this has made no difference to VS or SSMS 2005.
When I try to browse from SSMS 2008 RTM I get this error:
Invalid class string (Exception from HRESULT: 0x800401F3 (CO_E_CLASSSTRING))
Anyone have any ideas?
Thanks
Mike
A: This error plagued me for weeks, then I searched my registry backup and restored these:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID{C4F9B80B-89F7-4800-9C26-504D6E692B2C}]
@="MarshalledToIStreamDataObject Class"
"AppID"="{B2463DC8-B3FA-4BEC-945E-60219DCC6FD8}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID{C4F9B80B-89F7-4800-9C26-504D6E692B2C}\InprocServer32]
@="c:\Program Files\Microsoft SQL Server\90\Tools\Bin\Microsoft.DataWarehouse.VsIntegration.Helpers.dll"
"ThreadingModel"="Apartment"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID{C4F9B80B-89F7-4800-9C26-504D6E692B2C}\ProgID]
@="VsIntergrationNativeHelpers.Marshalle.1"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID{C4F9B80B-89F7-4800-9C26-504D6E692B2C}\VersionIndependentProgID]
@="VsIntergrationNativeHelpers.MarshalledT"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VsIntergrationNativeHelpers.Marshalle.1\CLSID]
@="{C4F9B80B-89F7-4800-9C26-504D6E692B2C}"
Copy and paste them into notepad, save as a reg file (double click .reg file to import into registry) and restart - this solved my problem.
HTH,
Gaz
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mock IIdentity and IPrincipal I just wanna ask what would be better approach to supply these objects in my unit tests.
In my unit test I am testing CSLA object. CSLA object is internally using one property and one method of ApplicationUser object. ApplicationUser is inherited from IPrincipal.
The properties are:
1) ApplicationContext.User.IsInRole(...) - the method is part of IPrincipal
2) ApplicationContext.User.Identity.Name - the name is property of IIdentity which is part of ApplicationUser aka IPricipal
Example of my test (using RhinoMock):
public void BeforeTest()
{
mocks = new MockRepository();
IPrincipal mockPrincipal = mocks.CreateMock<IPrincipal>();
ApplicationContext.User = mockPrincipal;
using (mocks.Record()) {
Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true);
Expect.Call(mockPrincipal.Identity.Name).Return("ju"); //doesn't work!!!! return null ref exc
}
}
I have slight problem with second value, the identity name. I tried to mock it but have problem to assign mocked IIdentity to ApplicationUser, as it is done internaly.
I was told to just create some IIPrincipal (including IIdentity) by myself and not to mock it at all. Which can be done for sure. Not sure if this can be called as Stub using?
So can you advice me how to deal with IPrincipal and IIdentity? Any suggestion most welcome.
A: Here is the code I use to return a test user (using Stubs):
[SetUp]
public void Setup()
{
var identity = MockRepository.GenerateStub<IIdentity>();
identity.Stub(p => p.Name).Return("TestUser").Repeat.Any();
var principal = MockRepository.GenerateStub<IPrincipal>();
principal.Stub(p => p.Identity).Return(identity).Repeat.Any();
Thread.CurrentPrincipal = principal;
}
I've got linq in other code so I'm using the var type for the variables; just substitute the correct types (IPrincipal, IIdentity) if needed.
A: The reason you're getting a null reference error is because IPrincipal.Identity is null; it hasn't been set in your mocked IPrincipal yet. Calling .Name the null Identity results in your exception.
The answer, as Carlton pointed out, is to mock IIdentity also, and set it up to return "ju" for its Name property. Then you can tell IPrincipal.Identity to return the mock IIdentity.
Here is an expansion of your code to do this (using Rhino Mocks rather than Stubs):
public void BeforeTest()
{
mocks = new MockRepository();
IPrincipal mockPrincipal = mocks.CreateMock<IPrincipal>();
IIdentity mockIdentity = mocks.CreateMock<IIdentity>();
ApplicationContext.User = mockPrincipal;
using (mocks.Record())
{
Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true);
Expect.Call(mockIdentity.Name).Return("ju");
Expect.Call(mockPrincipal.Identity).Return(mockIdentity);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: What is the difference between "global::System" and "System" in .NET? I just upgraded a VS 2005 project to VS 2008 and was examining the changes. I noticed one of the .Designer.cs files had changed significantly. The majority of the changes were simply replacements of System with global::System. For example,
protected override System.Data.DataTable CreateInstance()
became
protected override global::System.Data.DataTable CreateInstance()
What's going on here?
A: The :: operator is called a Namespace Alias Qualifier.
global::System.Data.DataTable
is the same as:
System.Data.DataTable
Visual Studio 2008 added it to the designer generated code to avoid ambigious reference issues that occasionally happened when people created classes named System...For example:
class TestApp
{
// Define a new class called 'System' to cause problems.
public class System { }
// Define a constant called 'Console' to cause more problems.
const int Console = 7;
const int number = 66;
static void Main()
{
// Error Accesses TestApp.Console
//Console.WriteLine(number);
}
}
However:
global::System.Console.Writeline("This works");
For further reading:
http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx
A: To prevent people from doing #1 on this list. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Performing AJAX delete operations restfully in rails How do you perform delete and put operations restfully in rails? I have read the documentation and thought I was doing everything properly, but I can't seem to get it to work.
For example, if I wanted to delete an employee I would create a controller called "EmployeesController" and create a destroy method to perform the delete.
Then I went into the routes.rb file and entered map.resources :employees, which gives you access to the URL helper functions.
In whatever I want to call the Ajax operation from, I should just have a line like:
<%= link_to_remote "Delete", employee_path(@employee), :method => :delete %>
When I click on the link, it is still is sending a POST operation, so it does nothing.
What am I missing or doing wrong?
A: Try
:url => employee_url(@employee)
IIRC, *_path is a named route generated by the :resource directive which includes the method, thus overwriting your :method => :delete
A: From my code:
<%= link_to_remote "Delete", :url => post_url(post), :method => :delete %>
A: Just to add a few extra details: Using :url => employee_url(@employee) helped (from the accepted answer). The other part that was messing me up was the fact that I was expecting an HTTP delete request, but I kept getting POST requests with a parameter "_method" (automatically added by rails) which was set to delete.
So it was calling the proper destroy action, which I proved by adding a couple of debug statements to the controller. Yes, my delete code was wrong in the controller, so it wasn't really deleting when I thought it was.
A: If your problem is not having AJAX request you have to add proper javascript tags
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to find unused/dead code in java projects What tools do you use to find unused/dead code in large java projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible.
Suggestions for general strategies/techniques (other than specific tools) are also appreciated.
Edit: Note that we already use code coverage tools (Clover, IntelliJ), but these are of little help. Dead code still has unit tests, and shows up as covered. I guess an ideal tool would identify clusters of code which have very little other code depending on it, allowing for docues manual inspection.
A: In Eclipse Goto Windows > Preferences > Java > Compiler > Errors/Warnings
and change all of them to errors. Fix all the errors. This is the simplest way. The beauty is that this will allow you to clean up the code as you write.
Screenshot Eclipse Code :
A: CodePro was recently released by Google with the Eclipse project. It is free and highly effective. The plugin has a 'Find Dead Code' feature with one/many entry point(s). Works pretty well.
A: IntelliJ has code analysis tools for detecting code which is unused. You should try making as many fields/methods/classes as non-public as possible and that will show up more unused methods/fields/classes
I would also try to locate duplicate code as a way of reducing code volume.
My last suggestion is try to find open source code which if used would make your code simpler.
A: The Structure101 slice perspective will give a list (and dependency graph) of any "orphans" or "orphan groups" of classes or packages that have no dependencies to or from the "main" cluster.
A: I would instrument the running system to keep logs of code usage, and then start inspecting code that is not used for months or years.
For example if you are interested in unused classes, all classes could be instrumented to log when instances are created. And then a small script could compare these logs against the complete list of classes to find unused classes.
Of course, if you go at the method level you should keep performance in mind. For example, the methods could only log their first use. I dont know how this is best done in Java. We have done this in Smalltalk, which is a dynamic language and thus allows for code modification at runtime. We instrument all methods with a logging call and uninstall the logging code after a method has been logged for the first time, thus after some time no more performance penalties occur. Maybe a similar thing can be done in Java with static boolean flags...
A: I'm suprised ProGuard hasn't been mentioned here. It's one of the most mature products around.
ProGuard is a free Java class file shrinker, optimizer, obfuscator,
and preverifier. It detects and removes unused classes, fields,
methods, and attributes. It optimizes bytecode and removes unused
instructions. It renames the remaining classes, fields, and methods
using short meaningless names. Finally, it preverifies the processed
code for Java 6 or for Java Micro Edition.
Some uses of ProGuard are:
*
*Creating more compact code, for smaller code archives, faster transfer across networks, faster loading, and smaller memory
footprints.
*Making programs and libraries harder to reverse-engineer.
*Listing dead code, so it can be removed from the source code.
*Retargeting and preverifying existing class files for Java 6 or higher, to take full advantage of their faster class loading.
Here example for list dead code: https://www.guardsquare.com/en/products/proguard/manual/examples#deadcode
A: DCD is not a plugin for some IDE but can be run from ant or standalone. It looks like a static tool and it can do what PMD and FindBugs can't. I will try it.
P.S. As mentioned in a comment below, the Project lives now in GitHub.
A: One thing I've been known to do in Eclipse, on a single class, is change all of its methods to private and then see what complaints I get. For methods that are used, this will provoke errors, and I return them to the lowest access level I can. For methods that are unused, this will provoke warnings about unused methods, and those can then be deleted. And as a bonus, you often find some public methods that can and should be made private.
But it's very manual.
A: An Eclipse plugin that works reasonably well is Unused Code Detector.
It processes an entire project, or a specific file and shows various unused/dead code methods, as well as suggesting visibility changes (i.e. a public method that could be protected or private).
A: There are tools which profile code and provide code coverage data. This lets you see (as code is run) how much of it is being called. You can get any of these tools to find out how much orphan code you have.
A: *
*FindBugs is excellent for this sort of thing.
*PMD (Project Mess Detector) is another tool that can be used.
However, neither can find public static methods that are unused in a workspace. If anyone knows of such a tool then please let me know.
A: Use a test coverage tool to instrument your codebase, then run the application itself, not the tests.
Emma and Eclemma will give you nice reports of what percentage of what classes are run for any given run of the code.
A: We've started to use Find Bugs to help identify some of the funk in our codebase's target-rich environment for refactorings. I would also consider Structure 101 to identify spots in your codebase's architecture that are too complicated, so you know where the real swamps are.
A: In theory, you can't deterministically find unused code. Theres a mathematical proof of this (well, this is a special case of a more general theorem). If you're curious, look up the Halting Problem.
This can manifest itself in Java code in many ways:
*
*Loading classes based on user input, config files, database entries, etc;
*Loading external code;
*Passing object trees to third party libraries;
*etc.
That being said, I use IDEA IntelliJ as my IDE of choice and it has extensive analysis tools for findign dependencies between modules, unused methods, unused members, unused classes, etc. Its quite intelligent too like a private method that isn't called is tagged unused but a public method requires more extensive analysis.
A: User coverage tools, such as EMMA. But it's not static tool (i.e. it requires to actually run the application through regression testing, and through all possible error cases, which is, well, impossible :) )
Still, EMMA is very useful.
A: Code coverage tools, such as Emma, Cobertura, and Clover, will instrument your code and record which parts of it gets invoked by running a suite of tests. This is very useful, and should be an integral part of your development process. It will help you identify how well your test suite covers your code.
However, this is not the same as identifying real dead code. It only identifies code that is covered (or not covered) by tests. This can give you false positives (if your tests do not cover all scenarios) as well as false negatives (if your tests access code that is actually never used in a real world scenario).
I imagine the best way to really identify dead code would be to instrument your code with a coverage tool in a live running environment and to analyse code coverage over an extended period of time.
If you are runnning in a load balanced redundant environment (and if not, why not?) then I suppose it would make sense to only instrument one instance of your application and to configure your load balancer such that a random, but small, portion of your users run on your instrumented instance. If you do this over an extended period of time (to make sure that you have covered all real world usage scenarios - such seasonal variations), you should be able to see exactly which areas of your code are accessed under real world usage and which parts are really never accessed and hence dead code.
I have never personally seen this done, and do not know how the aforementioned tools can be used to instrument and analyse code that is not being invoked through a test suite - but I am sure they can be.
A: There is a Java project - Dead Code Detector (DCD). For source code it doesn't seem to work well, but for .jar file - it's really good. Plus you can filter by class and by method.
A: Netbeans here is a plugin for Netbeans dead code detector.
It would be better if it could link to and highlight the unused code. You can vote and comment here: Bug 181458 - Find unused public classes, methods, fields
A: Eclipse can show/highlight code that can't be reached. JUnit can show you code coverage, but you'd need some tests and have to decide if the relevant test is missing or the code is really unused.
A: I found Clover coverage tool which instruments code and highlights the code that is used and that is unused. Unlike Google CodePro Analytics, it also works for WebApplications (as per my experience and I may be incorrect about Google CodePro).
The only drawback that I noticed is that it does not takes Java interfaces into account.
A: I use Doxygen to develop a method call map to locate methods that are never called. On the graph you will find islands of method clusters without callers. This doesn't work for libraries since you need always start from some main entry point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "316"
} |
Q: Utilizing Java API from a Cobol program We have some COBOL programs running on our mainframe and we need one of those to communicate with our back end vault through a Java API. Is there any way a Cobol program can invoke the Java program?
Would it be possible to use a Web Service from Cobol? How would I integrate a Cobol program with anything else?
A: Found this:
A COBOL program can interoperate with
JAVA.
To achieve inter-language
interoperability with Java™, you must
follow certain rules and guidelines
for: Using services in the Java Native
Interface (JNI) Coding data types
Compiling your COBOL programs You can
invoke methods that are written in
Java from COBOL programs, and you can
invoke methods that are written in
COBOL from Java programs. For basic
Java object capabilities, you can use
COBOL object-oriented language. For
additional Java capabilities, you can
call JNI services.
Because Java programs might be
multi-threaded and use asynchronous
signals, compile your COBOL programs
with the THREAD option.
Also, we are using Cobol Enterprise, which has support for web services. The integration shall then be done using the WS functionality found in Cobol Enterprise.
A: I'm guessing that any Java integration would be a vendor extension. What compiler are you using?
If your Cobol program is running as a batch job, you might be able to split it into two batch jobs, one that writes all of the queries for Java land into a file, and one that uses the answers from Java land. Run a Java program between them that reads the query file and writes out an answers file.
A: This is a shot in the dark but Dr Dobbs has a recent article on Cobol and Java (see here). On page 3, they mention running Cobol on the JVM with some vendor info. That is quite a departure from your question but might lead to some new resources on the web.
A: Microfocus does allow COBOL and Java to interact but to do what you require you will need to use a Microfocus derivative called OO COBOL.
A: I don't code in COBOL, but at my work, we have an MVS system where the programmers have output XML/Web services from COBOL.
A: For the AS/400 there is the IBM Java toolbox. Check the java programming section in the infocenter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Update Month value on datefield in MS sql 2005 I need a way to update the month value on a dateTime field in my db. I'm being past an int value for the month and need to use that for the update.
Is it possible to do this in the sql statement or would I be best doing it in c# in the webservice?
A: Shift down and then up again:
UPDATE table
SET datecol = DATEADD(m, @newmonth, DATEADD(m, -MONTH(datecol), datecol))
WHERE id = @id
or, more simply:
UPDATE table
SET datecol = DATEADD(m, @newmonth - MONTH(datecol), datecol)
WHERE id = @id
A: You can do this all in TSQL in Sql Server. Check out the DateDiff and DateAdd functions.
I expect this would work:
DECLARE @newMonth int
SET @newMonth = 5 --As an example
UPDATE dbo.TheTable
SET DateField = DATEADD(month, @newMonth - DATEPART(month, DateField) , DateField)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the row count in JDBC? I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance?
I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.
A: If your driver supports it(!), you can call ResultSet.afterLast() ResultSet.getRow() ResultSet.beforeFirst(). Performance may or may not be good.
A better solution would be to rewrite your algorithm not to require the size up front.
A: You're going to have to do this as a separate query, for example:
SELECT COUNT(1) FROM table_name
Some JDBC drivers might tell you but this is optional behaviour and, more to the point, the driver may not know yet. This can be due to how the query is optimised eg two example execution strategies in Oracle are to get all rows as quickly as possible or to get the first row as quickly as possible.
If you do two separate queries (one a count and the other the query) then you'll need to do them within the same transaction. This will work well on Oracle but can be problematic on other databases (eg SQL Server will either show you uncommitted data or block on an external uncommitted update depending on your isolation level whereas Oracle supports an isolation level that gives you a transactionally consistent view of the data without blocking on external updates).
Normally though it doesn't really matter how many rows there are. Typically this sort of query is either batch processed or paged and either way you have progress information in the form of rows loaded/processed and you can detect the end of the result set (obviously).
A: ResultSet rs = stmt.executeQuery(sql);
int rowCount = rs.last() ? rs.getRow() : 0; // Number of rows in result set. Don't forget to set cyrsor to beforeFirst() row! :)
A: Without ternary operator
rs.last(); // Moves the cursor to the last row in this ResultSet object.
int rowCount = rs.getRow(); //Retrieves the current row number.
rs.beforeFirst(); //Moves the cursor to the front of this ResultSet object,just before the first row.
With ternary operator one line
int rowCount = rs.last() ? rs.getRow() : 0;
rs.beforeFirst();
A: Short answer: you can't.
Long answer: you can't, partly because the database may be lazily evaluating the query, only returning rows as you ask for them.
EDIT: Using a scrollable ResultSet you can :)
Indeed, I asked this very question in the Java databases newsgroup a long time ago (back in 2001!) and had some helpful responses.
A: To get the number of rows from JDBC:
ResultSet rs = st.executeQuery("select count(*) from TABLE_NAME");
rs.next();
int count = rs.getInt(1);
A: Code:
//Create a Statement class to execute the SQL statement
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS COUNT FROM
TABLENAME");
while(rs.next()) {
System.out.println("The count is " + rs.getInt("COUNT"));
}
//Closing the connection
con.close();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: How can I save email attachments to the server in PHP? I've been battling PHP's email reading functions for the better part of two days. I'm writing a script to read emails from a mailbox and save any attachments onto the server. If you've ever done something similar, you might understand my pain: PHP doesn't play well with email!
I've connected to the POP3 server and I can iterate the files. Here's a rough outline of the code:
if (!$mbox = imap_open ("{myserver.com:110/pop3/notls}INBOX", "u", "p"))
die ('Cannot connect/check mail! Exiting');
if ($hdr = imap_check($mbox))
$msgCount = $hdr->Nmsgs;
else
die ("Failed to get mail");
foreach ($overview as $message) {
$msgStruct = imap_fetchstructure($mbox, $message->msgno);
// if it has parts, there are attachments that need reading
if ($msgStruct->parts) {
foreach ($msgStruct->parts as $key => $part) {
switch (strtoupper($part->subtype)) {
case 'GIF': case 'JPEG':case 'PNG':
//do something - but what?!
break;
}
}
}
}
I've marked where I'm stuck. I can use imap_fetchbody($mbox, $message->msgno, $key+1) but that gets me a bunch of data like this:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8S
EhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEU
Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAAR
CAHiAi0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA
AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK
FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG
h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl
5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA
...
I'm lead to believe that this is MIME data. I need it as an image! I've seen several classes bombing around the internet that claim to do the required wizardry. I can't get any of them to work. I don't understand why I'm finding this so hard!
In short, I'm looking for something that can turn a raw MIME string into real data.
A: I found a quick guide how to treat emails with PHP: here.
At the bottom of that page there's a attachment-body echo:
if (substr($ContentType,0,4) == "text") {
echo imap_qprint($fileContent);
} else {
echo imap_base64($fileContent);
}
I guess this is what you might need...
(edit: in your case if it's image always you can skip the if part. And of course, save the file instead of echoing it:)
A: MIME data is base-64 encoded, so I think you should be able to decode it using base64_decode
A: you can use the imap_base64 function and just output that to a file, or use imap_savebody
A: Zend framework contains Zend_Mail, which should make reading mail messages much easier, and Zend_Mime, which I believe can parse a multipart mime message into a sensible data structure.
http://framework.zend.com/manual/en/zend.mail.read.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Different team members on Visual Studio 2005 and 2008 I am currently working on an asp.net application in Visual Studio 2005. I would like to upgrade to 2008 to take advantage of some of the new features, but my remote team won't be able to upgrade to it for a while.
Is it possible for only a few people on my team to upgrade to Visual Studio 2008, while the rest of the team continues to use 2005?
At this point, I don't plan on using any of the 3.0+ foundation stuff yet, so that isn't a concern.
A: Yes, the project files between 2005 and 2008 are compatible. The solutions are not, but those are easy to remake or copy. There is one gotcha with the project files, if you're using Web Applications projects. The two versions reference different MSBuild target files. Steven Harman has a blog with a fix to add to the project file.
So long as you aren't using anything new from the 3.5 compiler, you should be good. Note that even if you are targeting the 2.0 Framework, the compiler will still accept 3.5 syntax (var, object initializers, etc.) so you'll still need to be aware of those.
A: For C#: Projects initialy created in Visual Studio 2008 can't be opened in 2005 until you change a few lines at the bottom of the project file.
Visual C++ projects are incompatible, but it is pretty easy to merge changes in one file version into the other
A: Make copies of your project files and rename the physical copies to "Name2005.proj". Then upgrade the solution you are working on which will upgrade the project and solution files. Finally go back in VS2005 and create a new 2005 solution and stitch up the 2005 projects into it.
This gives you two parrallel sets of project files that you can use for the code in each visual studio revision. Make sure you keep the VS2008 target .net version at .net2.0 and you can't share MS-Test files. You will also have to manually keep the project files in synch.
It's a bit of a pain but it works.
A: If you're using source control, you can always branch to "2008", upgrade the project, and then manually merge branches when appropriate. You'll just have to be careful to target your solution to 2.0 and only merge code files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Subversion: deleting old feature branches vs. keeping them I have a subversion repository with the standard layout, i.e. trunk/ and branches/ (and tags/). When working on a bigger change, a feature branch is used, regularly synced with trunk, and later reintegrated back into trunk (using 1.5 now). Pretty standard stuff.
What I am wondering is whether such a feature branch, once finished and merged should be kept around, or deleted. The subversion book occasionally seems to suggest that it is common to delete them, but I've also seen a bunch of Open Source projects which do keep the branches.
I am also somewhat concerned about how deleting a branch will make it harder to keep track of which branches existed, especially when potentially duplicate names enter the scenario (say we search-refactor twice), their commit histories disappearing somewhere in the depth of the repository etc.
On the other hand, branches are used quite a lot, especially with 1.5 now, and I do like the thought of not having to poke through a large list of inactive branches to find the ones I am currently working on.
What are the pros and cons that I am missing? What are people doing?
A: My team deletes them to keep the clutter down. It's not like the go away after all; they can be retrieved if desired. You are right that it can be difficult to find them again: you need to know a revision number where the branch existed so you tell your client to look at that revision in order to see your files.
We use FogBugz for our project management which keeps track of when things were committed to our SVN repository by revision number. We can use this to determine what revision we need to revert to in order to see our files: we find the feature history in FogBugz, look to determine what revisions the branch existed in, and use that information to jump backwards.
A: If you are really worried about deleting them, lest they be forgotten, then simply create a folder under branches called 'inactive' and svn move your older, inactive branches into that folder. This might be the best of both worlds for you.
A: You can safely delete them. Deleting them doesn't remove them from the repository, the allocated space is never reclaimed, but it sure makes your whole project tree look more cleaned up.
A: I've been deleting feature branches as we're done, as I like the lack of clutter. There has been minor confusion on the part of some other developers, but since we record revision numbers of commits in our bug-tracking system, it's been pretty smooth. If someone comes by saying they can't find a branch, advice to use the -rrevision flag on their log/diff/checkout/whatever is generally all that's needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: Iterating shuffled [0..n) without arrays I know of a couple of routines that work as follows:
Xn+1 = Routine(Xn, max)
For example, something like a LCG generator:
Xn+1 = (a*Xn + c) mod m
There isn't enough parameterization in this generator to generate every sequence.
Dream Function:
Xn+1 = Routine(Xn, max, permutation number)
This routine, parameterized by an index into the set of all permutations, would return the next number in the sequence. The sequence may be arbitrarily large (so storing the array and using factoradic numbers is impractical.
Failing that, does anyone have pointers to similar functions that are either stateless or have a constant amount of state for arbitrary 'max', such that they will iterate a shuffled list.
A: There are n! permutations of n elements. Storing which one you're using requires at least log(n!) / log(2) bits. By Stirling's approximation, this takes roughly n log(n) / log (2) bits.
Explicitly storing one index takes log(n) / log(2) bits. Storing all n, as in an array of indices takes n times as many, or again n log(n) / log(2). Information-theoretically, there is no better way than explicitly storing the permutation.
In other words, the index you pass in of what permutation in the set you want takes the same asymptotic storage space as just writing out the permutation. If, for, example, you limit the index of the permutation to 32 bit values, you can only handle permutations of up to 12 elements. 64 bit indices only get you up to 20 elements.
As the index takes the same space as the permutation would, either change your representation to just use the permutation directly, or accept unpacking into an array of size N.
A: From my response to another question:
It is actually possible to do this in
space proportional to the number of
elements selected, rather than the
size of the set you're selecting from,
regardless of what proportion of the
total set you're selecting. You do
this by generating a random
permutation, then selecting from it
like this:
Pick a block cipher, such as TEA
or XTEA. Use XOR folding to
reduce the block size to the smallest
power of two larger than the set
you're selecting from. Use the random
seed as the key to the cipher. To
generate an element n in the
permutation, encrypt n with the
cipher. If the output number is not in
your set, encrypt that. Repeat until
the number is inside the set. On
average you will have to do less than
two encryptions per generated number.
This has the added benefit that if
your seed is cryptographically secure,
so is your entire permutation.
I wrote about this in much more detail
here.
Of course, there's no guarantee that every permutation can be generated (and depending on your block size and key size, that may not even be possible), but the permutations you can get are highly random (if they weren't, it wouldn't be a good cipher), and you can have as many of them as you want.
A: If you are wanting a function that takes up less stack space, then you should look into using an iterated version, rather than a function. You can also use a datastructure like a TreeMap, and have it stored on disk, and read on an as needed basis.
X(n+1) = Routine(Xn, max, permutation number)
for(i = n; i > 0; i--)
{
int temp = Map.lookup(i)
otherfun(temp,max,perm)
}
A: Is it possible to index a set of permutations without previously computing and storing the whole thing in memory? I tried something like this before and didn't find a solution - I think it is impossible (in the mathematical sense).
Disclaimer: I may have misunderstood your question...
A: Code that unpacks a permutation index into an array, with a certain mapping from index to permutation. There are loads of others, but this one is convenient.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char index_t;
typedef unsigned int permutation;
static void permutation_to_array(index_t *indices, index_t n, permutation p)
{
index_t used = 0;
for (index_t i = 0; i < n; ++i) {
index_t left = n - i;
index_t digit = p % left;
for (index_t j = 0; j <= digit; ++j) {
if (used & (1 << j)) {
digit++;
}
}
used |= (1 << digit);
indices[i] = digit;
p /= left;
}
}
static void dump_array(index_t *indices, index_t n)
{
fputs("[", stdout);
for (index_t i = 0; i < n; ++i) {
printf("%d", indices[i]);
if (i != n - 1) {
fputs(", ", stdout);
}
}
puts("]");
}
static int factorial(int n)
{
int prod = 1;
for (int i = 1; i <= n; ++i) {
prod *= i;
}
return prod;
}
int main(int argc, char **argv)
{
const index_t n = 4;
const permutation max = factorial(n);
index_t *indices = malloc(n * sizeof (*indices));
for (permutation p = 0; p < max; ++p) {
permutation_to_array(indices, n, p);
dump_array(indices, n);
}
free(indices);
}
A: Code that uses an iterate interface. Time complexity is O(n^2), Space complexity has an overhead of: copy of n (log n bits), an iteration variable (log n bits), keeping track of n-i (log n bits), , copy of current value (log n bits), copy of p (n log n bits), creation of next value (log n bits), and a bit set of used values (n bits). You can't avoid an overhead of n log n bits. Timewise, this is also O(n^2), for setting the bits. This can be reduced a bit, but at the cost of using a decorated tree to store the used values.
This can be altered to use arbitrary precision integers and bit sets by using calls to the appropriate libraries instead, and the above bounds will actually start to kick in, rather than being capped at N=8, portably (an int can be the same as a short, and as small as 16 bits). 9! = 362880 > 65536 = 2^16
#include <math.h>
#include <stdio.h>
typedef signed char index_t;
typedef unsigned int permutation;
static index_t permutation_next(index_t n, permutation p, index_t value)
{
permutation used = 0;
for (index_t i = 0; i < n; ++i) {
index_t left = n - i;
index_t digit = p % left;
p /= left;
for (index_t j = 0; j <= digit; ++j) {
if (used & (1 << j)) {
digit++;
}
}
used |= (1 << digit);
if (value == -1) {
return digit;
}
if (value == digit) {
value = -1;
}
}
/* value not found */
return -1;
}
static void dump_permutation(index_t n, permutation p)
{
index_t value = -1;
fputs("[", stdout);
value = permutation_next(n, p, value);
while (value != -1) {
printf("%d", value);
value = permutation_next(n, p, value);
if (value != -1) {
fputs(", ", stdout);
}
}
puts("]");
}
static int factorial(int n)
{
int prod = 1;
for (int i = 1; i <= n; ++i) {
prod *= i;
}
return prod;
}
int main(int argc, char **argv)
{
const index_t n = 4;
const permutation max = factorial(n);
for (permutation p = 0; p < max; ++p) {
dump_permutation(n, p);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I automatically add some skeleton code when creating a new file with vim When creating a new file with vim, I would like to automatically add some skeleton code.
For example, when creating a new xml file, I would like to add the first line:
<?xml version="1.0"?>
Or when creating an html file, I would like to add:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
A: Sorry for the lateness, but I feel the way I do it might be useful to some. It uses the file's filetype, making it shorter and more dynamic than more conventional methods. It was tested only on Vim 7.3.
if has("win32") || has ('win64')
let $VIMHOME = $HOME."/vimfiles/"
else
let $VIMHOME = $HOME."/.vim/"
endif
" add templates in templates/ using filetype as file name
au BufNewFile * :silent! exec ":0r ".$VIMHOME."templates/".&ft
A: If you want to adapt your skeleton to the context, or to the user choices, have a look at the template-expander plugins listed on vim.wikia
A: I got something like this in my .vimrc:
au BufNewFile *.xml 0r ~/.vim/xml.skel | let IndentStyle = "xml"
au BufNewFile *.html 0r ~/.vim/html.skel | let IndentStyle = "html"
And so on, whatever you'll need.
A: You can save your skeleton/template to a file, for example ~/vim/skeleton.xml
Then add the following to your .vimrc
augroup Xml
au BufNewFile *.xml 0r ~/vim/skeleton.xml
augroup end
A: Here are two examples using python scripting.
Add something like this in your .vimrc or another file sourced by your .vimrc:
augroup Xml
au BufNewFile *.xml :python import vim
au BufNewFile *.xml :python vim.current.buffer[0:0] = ['<?xml version="1.0"?>']
au BufNewFile *.xml :python del vim
augroup END
fu s:InsertHtmlSkeleton()
python import vim
python vim.current.buffer[0:0] = ['<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', "<html>", "<head>", " <title></title>", "</head>", "<body>", "", "</body>", "</html>"]
python del vim
endfu
augroup Html
au BufNewFile *.html call <SID>InsertHtmlSkeleton()
augroup END
A: You can add various hooks when files are read or created. to
:help event
and read what's there. What you want is
:help BufNewFile
A: It can work with snipmate too:
augroup documentation
au!
au BufNewFile *.py :call ExecuteSnippet('docs')
augroup END
function! ExecuteSnippet(name)
execute "normal! i" . a:name . "\<c-r>=TriggerSnippet()\<cr>"
endfunction
with "docs" the snippet to trigger.
It works with multi-snippets but then the :messages window appears and it's cumbersome.
A: I wrote a plugin for html:
On vim scripts: http://www.vim.org/scripts/script.php?script_id=4845
On Github: https://github.com/linuscl/vim-htmltemplate
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: .NET : How do you remove a specific node from an XMLDocument using XPATH? Using C#
How do you remove a specific node from an XMLDocument using XPATH?
A: Here you go. ChildNodeName, could be just the node name or an XPath query.
XmlDocument doc = new XmlDocument();
// Load you XML Document
XmlNode childNode = doc.SelectSingleNode(childNodeName);
// Remove from the document
doc.RemoveChild(childNode);
There is a different way using Linq, but I guessed you were using .NET 2.0
A: XPath can only select nodes from a document, not modify the document.
A: If you want to delete nodes, that are not direct children of the documents root, you can do this:
XmlDocument doc = new XmlDocument();
// ... fill or load the XML Document
XmlNode childNode = doc.SelectSingleNode("/rootnode/childnode/etc"); // apply your xpath here
childNode.ParentNode.RemoveChild(childNode);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What tools and techniques do you use to find dead code? What tools and techniques do you use to find dead code in .NET?
In the past, I've decorated methods with the Obsolete attribute (passing true so the compiler will issue an error, as described in MSDN).
I'd be interested in seeing the suggestions of others (beyond tools like FxCop or ReSharper). I want to make sure I'm not missing out on other tools that would be helpful.
A: it appears gray in ReSharper if it's dead code (at least within the solution only)...like uncalled methods or classes or unused properties and variables
A: TDD + NCover
A: Once again, I recommend AQTime. The static code analysis already does what you want (and a lot more), but the other profilers are even more useful. Worth the money, if you can afford it.
A: Why do you need other answers? FxCop and Resharper do the trick, especially seeing as FxCop is now integrated into VS through "Code Analysis".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Why can't I save CSS changes in Firebug? Firebug is the most convenient tool I've found for editing CSS - so why isn't there a simple "save" option for CSS?
I am always finding myself making tweaks in Firebug, then going back to my original .css file and replicating the tweaks.
Has anyone come up with a better solution?
EDIT: I'm aware the code is stored on a server (in most cases not my own), but I use it when building my own websites.
Firebug's just using the .css file Firefox downloaded from the server, it knows precisely what lines in which files it's editing. I can't see why there's not an "export" or "save" option, which allows you to store the new .css file. (Which I could then replace the remote one with).
I have tried looking in temporary locations, and choosing File > Save... and experimenting with the output options on Firefox, but I still haven't found a way.
EDIT 2:
The official discussion group has a lot of questions, but no answers.
A: I think the closest you're going to get is by going into Edit mode in Firebug and copying and pasting the contents of the CSS file.
A: We just introduced Backfire, an open source javascript engine that allows you to save CSS changes made in Firebug and Webkit inspector to the server. The library includes an example C# implementation of how to save the incoming changes to your CSS.
Here's a blog post about how it works:
http://blog.quplo.com/2010/08/backfire-save-css-changes-made-in-firebug/
And here's the code hosted at Google Code:
http://code.google.com/p/backfire/
A: I know this doesn't answer your question, but surprisingly, Internet Explorer 8's Firebug clone "developer toolbar" (accessible via F12) offers the option to "save html". This function saves the current DOM to a local file, which means that if you edit the DOM somehow, e.g. by adding a style attribute somewhere, this will be saved too.
Not particularly useful if you're using Firebug to mess around with CSS like everyone does, but a step in the right direction.
A: I propose a solution that involves a combination of Firebug and FireFTP as well as code that directly accesses the local file system when running a website locally.
Here are the scenarios:
Working on a website that is hosted on a remote machine
In this case you would provide the FTP details and the location of the CSS/HTML/Javascript and Firebug would then update these files when you save your changes. It may even be able to locate the files itself and then prompt you to verify that it has the correct file. If file names are unique it shouldn't be a problem.
Working on a website running on your local machine
In this case you could provide Firebug with the local folder location of the website and the same behaviour would be used to match and verify the files. The access to the local file system could be performed through FireFTP if necessary.
Working on a website hosted remotely without FTP access
In this case something like the FireFile add-on would have to be implemented.
An additional feature would be the ability to save and open project files that store the mappings between the local files and the URLs they are associated with as well as saving the FTP details as FireFTP already does.
A: FireFile
Firebug was created to detect a problem not to be a debugger. but you can save change if you add new tool that integrate firebug with save changes. it is FireFile, click here
http://thelistoflist.blogspot.com/2010/04/how-to-save-change-you-make-in-firebug.html.
FireFile provide the desired functionality by adding a small PHP file to the server side.
A: I am the author of CSS-X-Fire which Sorin Sbarnea also kindly posted about in this thread. Guess I'm a bit late ;)
CSS-X-Fire emits CSS property changes from Firebug to the IDE where the changes can be applied or discarded.
There are a couple of advantages with this solution over most of the other existing tools which only know know about the filenames and the content downloaded by the browser (see NickFitz comment in the original post).
Scenario 1: You have a website (project) which has a handful of themes from which the user can select from. Each theme has its own CSS file but only one is known to Firebug, the current one. CSS-X-Fire will detect all matching selectors in the project and let you decide which should be modified.
Scenario 2: The web project has stylesheets created compile-time or during deployment. They might be merged from several files and the file names may change. CSS-X-Fire doesn't care of the names of the files, it only deals with CSS selector names and their properties.
Above are examples of scenarios where CSS-X-Fire excels. Since it works with the source files, and knows about the language structure, it also helps to find duplicates not known to Firebug, jump-to-code, etcetera.
CSS-X-Fire is open source under the Apache 2 license.
Project home: http://code.google.com/p/css-x-fire/
A: I got here looking exactly for this feature, that is, being able to save edited CSS properties back to the original file (on my local development machine). Unfortunately after searching a lot and not finding anything that suits my needs (OK, there's CSS Updater but you have to register and it's a paid extension...) I gave up on Firefox + Firebug and looked for something similar for Google Chrome. Guess what... I just found this great post that shows a nice way of getting this to work ( built into Chrome - there's no need for additional extensions ):
Change CSS and SAVE on local file system using Chrome Developer Tools
I tried it now and it works great highlighting the changed lines. Just click Save and you're done! :)
Here's a video explaining this and much more: Google I/O 2011: Chrome Dev Tools Reloaded
I hope it helps if it doesn't matter to you changing browser while editing your CSS files. I made the change already for now, but I would really love to have this functionality built into Firebug. :)
[Update 1]
Today I just saw this video: Firefox CSS live edit in Sublimetext (work in progress) Looks promising indeed.
[Update 2]
If you happen to be using Visual Studio 2013 with Web Essentials you'll be able to sync CSS automagically as shown in this video:
Web Essentials: Browser tools integration
A: Since Firebug is not working on your server but taking the CSS from the site and storing it locally and showing you the site with those local changes.
A: Use the CSS editor in the Firefox Web Developer toolbar:
http://chrispederick.com/work/web-developer/
It's got enough good stuff to use in conjunction with Firebug, and it lets you save your CSS out to a text file.
A: Use Backfire.
http://blog.quplo.com/2010/08/backfire-save-css-changes-made-in-firebug/
It's an open source solution that sends CSS changes back to the server and saves them.
Backfire uses a single javascript file, and the sourcecode package has a working .NET server implementation example that is easily portable to other platforms.
A: I had this problem forever as well, and finally decided that we shouldn't be editing things in the web inspector and built something for it (https://github.com/viatropos/design.io).
A better solution:
The browser automatically reflects CSS changes without reloading when you press save in your text editor.
The main reason we're editing css in the web inspector (I use webkit, but FireBug is along the same lines) is because we need to make small adjustments, and it takes too long to reload the page.
There are 2 main problems with this approach. First, you're allowed to edit an individual element that may not have an id selector. So even if you were able to copy/paste the generated CSS from the web inspector, it would have to generate an id to scope the css. Something like:
#element-127 {
background: red;
}
That would start making your css a mess.
You could get around that by only changing styles for an existing selector (the .space class selector in the webkit inspector image below).
Still though, the second problem. The interface to that thing is pretty rough, it's hard to make big changes - like if you want to try real quick copying this block of css to this place, or whatever.
I'd rather just stick to TextMate.
The ideal would be to just write the CSS in your text editor and have the browser reflect the changes without reloading the page. This way you'd be writing your final css as you're making the little changes.
The next level would be to write in a dynamic CSS language, like Stylus, Less, SCSS, etc, and have that update the browser with the generated CSS. This way you could start creating mixins like box-shadow(), that abstracted away the complexities, which the web inspector definitely couldn't do.
There's a few things out there that kind of do this, but nothing really streamlining it in my opinion.
*
*LiveReload: pushes css to browser without refreshing when you press save, but it's a mac app, so it'd be difficult to customize.
*CodeKit: also a mac app, but it refreshes the browser every time you save.
Not having the ability to easily customize the way these work is the main reason I didn't use them.
I put together https://github.com/viatropos/design.io specifically to solve this problem, and make it so:
*
*The browser reflects the css/js/html/etc anytime you save, without reloading the page
*It can handle any template/language/framework (Stylus, Less, CoffeeScript, Jade, Haml, etc.)
*It's written in JavaScript, and you can whip together extensions real quick in JavaScript.
This way, when you need to make those little changes to CSS, you can say, set background color, press save, see nope, not quite, adjust the hue by 10, save, nope, adjust by 5, save, looks good.
The way it works is by watching whenever you save a file (at the os level), processing the file (this is where the extensions work), and pushing the data to the browser through websockets, which are then handled (the client side of the extension).
Not to plug or anything, but I struggled with this issue for a long ass time.
Hope that helps.
A: The Web Developer add-on let's you save your edits. I'd like to combine the editing of Firebug with the Save feature of Web Developer.
(source: mozilla.org)
Use the "Save" button (click CSS menu -> Edit CSS) to save the modified CSS to disk.
Recomendation: Use the "Stick" button to prevent losing your changes when you change the tab for doing other browsing. If it is possible, use only one tab to do the edit and other firefox window the related searches, webmail, etc.
A: I just released a firebug addon at the mozilla addon sandbox which might quite do what you want:
https://addons.mozilla.org/en/firefox/addon/52365/
It actually saves the "touched" css files on demand to your web server (by communication with a one-file webservice php script).
Documentation can be found at my homepage or on the addon page
I would appreciate any testing, bug reports, comments, ratings, discussion on this, as it's still in early beta, but should already work fine.
A: CSS-X-Fire
I'm surprised that it still not listed to this question, but probably because is new and the author didn't have time to promote it yet.
It is called CSS-X-Fire and it is a plugin for JetBrains series of IDEs : IntelliJ IDEA, PHPWebStorm, PyCharm, WebStorm, RubyMine.
How it works:
You install one of these IDEs and configure the deployment (supports FTP and SCP). This will allow you to stay in sync with the server.
After this you install this plugin. When it starts it will ask tell you that he will install a plugin for Firefox, in order to do the integration between Firebug and the IDE. If it fails to install the plugin, just use the drag-n-drop technique to install it.
Once installed it will track all your changes from Firebug and you will be able to apply them with a simple click inside de IDE.
FireFile
FireFile is an alternative that requires you to add one small php file to the server side in order to be able to upload the modified css.
A: Been wondering the same for quite some time now,
just gut-wrenching when your in-the-moment-freestyle-css'ing with firebug gets blown to bits by
an accidental reload or whatnot....
For my intents and purposes, I've finally found the tool.... : FireDiff.
It gives you a new tab, probably some weird David Bowie reference, called "changes";
which not only allows you to see/save what firebug, i. e. you, have been doing,
but also optionally track changes made by the page itself....if it and/or you are so inclined.
So thankful not having to re-type, or re-imagine and then re-re-type, every css rule I make...
Here is a link to the developer (don't be disparaged by first appearance, mayhap just as well head straight over to the Mozilla Add-On repository .
A: You could link firebug to eclipse with fireclipse and then save the file from eclipse
A: Firebug works on the computed CSS (the one which you get by taking the CSS in the files and applying inheritance, etc. plus the changes made with JavaScript). This means that probably you couldn't use it directly to include in an HTML file, which is browser/version specific (unless you care only about Firefox). On the other hand, it keeps track of what is original and what is computed... I think it should not be very difficult to add some JS to Firebug to be able to export that CSS to a text file.
A: You could write your own server script file that takes a filename parameter and a content parameter.
The server script would find the requested file and replace its contents with the new one.
Writing the Javascript that taps into firebug's info and retrieves the useful data would be the tricky part.
I'd personally rather ask the dev team at firebug to supply a function, it shouldn't be too hard for them.
Finally, Ajax sends the filename/content pair to the php file you created.
A: I was wondering why can't I bloody well select and copy the text in front of my eyes. Especially when others say you can just "select and copy". Turns out you can, you just have to start the drag outside of any text (i.e. in the gutter above or to the left of the text) as any mousedown -- whether it's a click or drag -- on any text immediately invokes the property editor. You can also click outside text to get a cursor (even if it's not always visible) which you can then move around with the arrow keys and select text that way.
The text copied to the clipboard is devoid of any indenting, unfortunately, but at least it saves you from manually transcribing the entire contents of the CSS file. Just have your diff programme ignore changes in whitespace when comparing against the original.
A: Quoted from the Firebug FAQ:
Editing Pages
*
*Can I save to the source the changes I made to the webpage I'm seeing?
Right now you can't. As John J. Barton wrote on the newsgroup:
Editing in Firebug is kinda like taking out the pickles from and adding mustard to a restaurant sandwich: you can enjoy the result, but the next customer at the restaurant will still get pickles and no mustard.
This is a long-requested functionality, so someday it'll be available directly from Firebug. Meanwhile, you can try Firediff, an extension for firebug by Kevin Decker.
*How can I output all changes that have been made to a site's CSS within firebug?
That's a feature implemented in Kevin Decker's Firediff.
A: Here's a partial solution. After you make your changes, click on one of the links to the relevant file. This is the original file, so you'll have to refresh the file, which is under the options menu button in the upper right of the firebug pane. Now you have the modified css page, which you can copy & paste. Obviously, you'll have to do it for each css file.
Edit: looks like Mark Biek has a quicker version
A: A very easy way to "edit" your page is to go onto the site via your internet browser. Save the page as html only onto your desktop. Go to your desktop and right click on the new web page file and select open with, choose notepad and edit the page from there, if you know html it will be easy. After all your editing is done, save the file and reopen your webpage, the changes should be there if done correctly. You can then use your new edited page and export or copy it to your remote location
A: Actually Firebug is a debug and analyze-Tool: not an editor and obviously not considered to be one. The other reason was already mentioned: how to you want to change CSS, stored on a server when debugging a webpage?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "143"
} |
Q: How do I detect "Easter Egg" mode in my Palm OS application? Since the early days, Palm OS has had a special "easter egg" mode that's enabled by making the right gesture in one of the Preference panels. On current Palm Treo and Centro devices, this is turned on by doing a clockwise swirl above the "Tips" button in the Power panel.
Some applications, like the Blazer web browser, enable special features when easter eggs are active. How can I detect this in my own program?
A: The standard system preference for this is prefAllowEasterEggs (see Preference.h). This setting can be accessed using the PrefGetPreference API:
UInt32 enableEasterEggs = PrefGetPreference(prefAllowEasterEggs);
The value will be non-zero when the user has requested that Easter eggs be available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What is the difference with these two sets of code What is the difference between these two pieces of code
type
IInterface1 = interface
procedure Proc1;
end;
IInterface2 = interface
procedure Proc2;
end;
TMyClass = class(TInterfacedObject, IInterface1, IInterface2)
protected
procedure Proc1;
procedure Proc2;
end;
And the following :
type
IInterface1 = interface
procedure Proc1;
end;
IInterface2 = interface(Interface1)
procedure Proc2;
end;
TMyClass = class(TInterfacedObject, IInterface2)
protected
procedure Proc1;
procedure Proc2;
end;
If they are one and the same, are there any advantages, or readability issues with either.
I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.
A: The two snippets of code have very different effects, and are in almost no way equivalent, if we are talking about Delphi for Win32 (Delphi for .NET has different rules).
*
*A class that implements its interface must implement all the members of that interface's ancestors, but it does not implicitly implement the ancestors. Thus, attempts to assign instances of type TMyClass to locations of type IInterface1 will fail for the second case.
*Related to the previous point, if IInterface1 and IInterface2 both had GUIDs, dynamic casts (using Supports or 'as') of interface references with a target type of IInterface1 would fail on instances of TMyClass in the second case.
*The interface IInterface2 has an extra method in the second case, which it does not in the first.
*Values of type IInterface2 in the second case are assignable to locations of type IInterface1; this is not true for the first case.
See for yourself in this example:
type
A_I1 = interface
end;
A_I2 = interface(A_I1)
end;
A_Class = class(TInterfacedObject, A_I2)
end;
procedure TestA;
var
a: A_Class;
x: A_I1;
begin
a := A_Class.Create;
x := a; // fails!
end;
type
B_I1 = interface
end;
B_I2 = interface
end;
B_Class = class(TInterfacedObject, B_I1, B_I2)
end;
procedure TestB;
var
a: B_Class;
x: B_I1;
begin
a := B_Class.Create;
x := a; // succeeds!
end;
begin
TestA;
TestB;
end.
A: First off, I'm assuming that the second example's declaration for IInterface2 is a typo and should be
IInterface2 = interface(Interface1)
because inheriting from itself is nonsensical (even if the compiler accepted it).
And "inheriting" is the key word there for answering your question. In example 1 the two interfaces are completely independent and you can implement one, the other, or both without problems. In example 2, you are correct that you can't implement interface2 without also implementing interface1, but the reason why that's so is because it makes interface1 a part of interface2.
The difference, then, is primarily structural and organizational, not just readability.
A: Assuming you meant
...
IInterface2 = interface(Interface1)
...
I interpret it the same as you, the second form requires a class implementing Interface2 to implement Interface1 as well, while the first form does not.
A:
I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.
That would be the technical difference.
Which one is better depends very much on what the interfaces actually are. Does it ever make sense for an IInterface2 to exist without it also being an IInterface1?
If IInterface1 is "displayable" and IInterface2 is "storable," then the first option probably makes more sense. If IInterface1 is "vehicle" and IInterface2 is "truck," then the second option probably makes much more sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Interface to versioned dictionary I have an versioned document store which I want to access through an dict like interface.
Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int).
from UserDict import DictMixin
class VDict(DictMixin):
def __getitem__(self, key):
if isinstance(key, tuple):
docid, rev = key
else:
docid = key
rev = None # set to tip rev
print docid, rev
# return ...
In [1]: d = VDict()
In [2]: d[2]
2 None
In [3]: d[2, 1]
2 1
This solution is a little bit tricky and I'm not sure if it is a clean, understandable interface. Should I provide a function
def getrev(self, docid, rev):
...
instead?
A: Yes, provide a different API for getting different versions. Either a single methodcall for doing a retrieval of a particular item of a particular revision, or a methodcall for getting a 'view' of a particular revision, which you could then access like a normal dict, depending on whether such a 'view' would see much use. Or both, considering the dict-view solution would need some way to get a particular revision's item anyway:
class RevisionView(object):
def __init__(self, db, revid):
self.db = db
self.revid = revid
def __getitem__(self, item):
self.db.getrev(item, self.revid)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Non-interactive authentication/authorization for XML-RPC? We don't exactly comply with the XML-RPC spec, but the concepts are nearly identical. A client comes in over HTTP/HTTPS with an XML payload. We respond with an XML payload answering the request. This is primarily machine to machine, so no human to type a username/password. Our construct runs within apache tomcat. We would like to authenticate the request and since not every service is available to every client, we need to authorize the request as well. We have both subscription and per use charging models so it is necessary to log everything.
What would you recommend for both server and client?
A: HTTP BASIC/DIGEST works fine for most machine to machine tasks, and it handled by the server so your API is unaffected.
It doesn't work as well for interactive uses because it's difficult to "log out" the user without closing the browser.
Otherwise you'll most likely need to alter your APIs to include authentication information and have your methods authenticate that within your code.
Or you could use the classic "login", set a cookie, keep a session technique.
But, frankly, for machine to machine work, HTTP BASIC is the easiest.
edit, regarding comments.
HTTP BASIC is simply a protocol used to present the artifacts necessary for authentication, and it works well for machine to machine web services.
HOW IT IS IMPLEMENTED is dependent on you and your application. Using Java, you can use container authentication and that will provide authentication as well as role mapping. The user -> role mapping is handled in either a data file or database. The URLs protected, and what roles are valid for each URL, is managed by web.xml.
If you continue to add different roles to different URLs, then, yes, you'll need to redeploy that application.
However, if you're just adding new users, then you simply update your file or database. And if you're adding new logic, and this new URLs, then you have to redeploy anyway. If you have a ROLE structure with a fine enough granularity, you won't have to be messing with the web.xml until you actually add new methods. For example you could, at the extreme, create a role per method, and assign them individually to users. Most don't need to go that far.
If you don't want to use container authentication, then write a Servlet Filter to implement your vision of mapping user and roles to URLs. You can still use the HTTP BASIC protocol for your clients, even if you implement your own facility.
If you're looking for an overall generic Java security framework, I defer to google -- there are several, I've not used any of them. I've had good luck with container authentication and writing our own.
A: @Will
I second the HTTP Basic suggestion, and can testify that it integrates fairly well with Spring Security, which I implemented on top of a legacy application that rolled its own DB-based authentication/authorization logic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change ToolTip's position on a TreeView? When using tooltips to show a detailed description of a TreeNode, the tooltip is drawn on top of the node, as if it was completing the node's text. Also, if the text is long, the tooltip is positioned in a way that the text exceeds the screen.
But what I need is the tooltip to show right below the mouse pointer and not on top of the TreeNode.
Any idea how to do this?
Show, don't tell:
How it is:
How I want:
A: I didn't find the answer I was looking for, but I somehow made it work the way I wanted.
Before, I was trying to set up the tooltip as follows:
private void treeView1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
TreeNode node = treeView1.GetNodeAt(e.X, e.Y);
if (node != null)
{
string text = GetNodeTooltip(node);
string currentText = toolTip1.GetToolTip(treeView1);
if (text.Equals(currentText) == false)
{
toolTip1.SetToolTip(treeView1, text);
}
}
else
{
toolTip1.SetToolTip(tree, string.Empty);
}
}
else
{
toolTip1.SetToolTip(tree, string.Empty);
}
}
Now, I just make treeView1.ShowNodeToolTips=true and when I create every node, I just set its TreeNode.ToolTipText value with the desired text.
A: private ToolTip toolTipController = new ToolTip() { UseFading = false,UseAnimation = false};
protected override void OnMouseMove(MouseEventArgs e)
{
var node = GetNodeAt(e.X, e.Y);
if (node != null)
{
var text = node.Text;
if (!text.Equals(toolTipController.GetToolTip(this)))
{
toolTipController.Show(text, this, e.Location, 2000);
}
}
else
{
toolTipController.RemoveAll();
}
}
A: You need to define a ToolTip and write an MouseOverEventHandler for the TreeView. In the MouseOverEventHandler calculate the node above which mouse is positioned, then show the description ToolTip. Also make sure you are not setting the tooltip description more than once, otherwise the behavior is quite ugly.
A better way is to show the description in the StatusStrip - bottom left of the Form.
Update:
OK since you have clarified your question. You can use ToolTip.Show method where you can specify coordinates:
public void Show(
string text,
IWin32Window window,
int x,
int y,
int duration
)
Obviously, you'll have to add offset to x and y.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I handle HTTP file uploads? How would I write a Perl CGI script that receives a file via a HTTP post and saves that to the file system?
A: Use the CGI module.
my $fh = $query->upload('upload_field');
while(<$fh>) {
print SAVE_FILE $_;
}
A: Just a note: however you will write it, don't save it in a place accessible from your web-server.
And now to the point: below is a script which I was using for some time for photo-uploading. It might need some tweaking, but should show you the way.
As the image isnt uploaded to web-accesible directory, we then have separate process checking it, resizing, putting a watermark and placing it where it can be accessed.
#!/usr/bin/perl -wT
use strict;
use CGI;
use CGI::Carp qw ( fatalsToBrowser );
use File::Basename;
$CGI::POST_MAX = 1024 * 5000;
my $safe_filename_characters = "a-zA-Z0-9_.-";
my $upload_dir = "/home/www/upload";
my $query = new CGI;
my $filename = $query->param("photo");
my $email_address = $query->param("email_address");
if ( !$filename )
{
print $query->header ( );
print "There was a problem uploading your photo (try a smaller file).";
exit;
}
my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' );
$filename = $name . $extension;
$filename =~ tr/ /_/;
$filename =~ s/[^$safe_filename_characters]//g;
if ( $filename =~ /^([$safe_filename_characters]+)$/ )
{
$filename = $1;
}
else
{
die "Filename contains invalid characters";
}
my $upload_filehandle = $query->upload("photo");
open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!";
binmode UPLOADFILE;
while ( <$upload_filehandle> )
{
print UPLOADFILE;
}
close UPLOADFILE;
print $query->header ( );
print <<END_HTML;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thanks!</title>
</head>
<body>
<p>Thanks for uploading your photo!</p>
</body>
</html>
END_HTML
A: See the CGI.pm documentation for file uploads.
A: I'd start by using CGI and reading CREATING A FILE UPLOAD FIELD, and using open to create a file and print to write to it. (and then close to close it).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: The value of hobby game development Does attempting to develop some sort of game, even just as a hobby during leisure time provide useful (professional) experience or is it a childish waste of time?
I have pursued small personal game projects on and off throughout my programming career. I've found the (often) strict performance requirements and escalating design complexity have taught me some of my most useful programming lessons.
In these projects to name just a few, I very quickly came face to face with: "Everything is fast for small N". I also discovered the hard way about using basic object oriented design principles to manage complexity.
In a field where many technologies and topics can be quite dry/dull, I think hobby game development is important in motivating new (and not so new) developers to brush up on essential skills while having fun at the same time.
This question talks about hobby projects in general, however here I am more interested in game projects specially and how valuable they are to professional programmers.
A: I think extra-curricular development is a good thing whether it is games or not. For a start you can try different technologies and development platforms and it is a great way of keeping your skills up to date. I prefer mathematical algorithms to games, but that's just a preference which doesn;t speak to the value of doing it at all.
If you bring any of this back to your employer then they are getting the benefit of your broadening knowledge which you are gaining on your own time. That is good for them too.
I say code away to your heart's content!
A: Games have some of the most complicated processing that's "agreeable" to a layman, hobbyist programmer. In high school, all I wrote were games. Want to explore physics? Write a game. 3D graphics? Write a game. High performance computing? Write a game. AI? Economics? Military Strategy? Natural Language Processing? Theorem Proving? Write a game.
You don't have to publish it, you don't have to document it, you don't even have to PLAY it, you just need to fiddle with it, and you'll learn any algorithm you find interesting as you try to apply it -- in a game.
Games are interesting because of the wide domain they can cover. Everything else is just data processing, and you can do that at work!
A: You can learn a lot from game development. Game development requires a discipline that you can't find in other programming projects.
Here are just a small set of things game development has taught me:
*
*Optimization for speed
*Sacrificing computational depth for speed
*Developing under small constraints of memory
*Building a system that works like an operating system but is geared toward speed.
*Keeping hundreds to thousands of objects in a tree, each with their own unique characteristics
*Some areas of game development have great academic value (like Artificial Intelligence, Procedural Algorithms, etc)
*It doesn't matter how much of a hack the code is, as long as the gameplay is there. Translating this to other disciplines, the objective of programming is to make the customers happy, regardless of how clever or ugly your code is.
Because game programmers are forced to use less resources, they become better programmers.
A: Game development (or any other sort of personal programming) is a good way to:
*
*learn new languages
*learn new concepts (TDD, OO, etc..)
*Use and evaluate different tools/technologies (CI, automated tests, etc...)
These sorts of projects give you the freedom to explore different aspects of the programming world that you are not able to do at work. If you are stuck doing line of business applications at work, you probably won't deal with a physics engine, or spacial rendering. But you could explore these subjects in your game.
This would also provide you with a good portfolio of code you can bring if/when you interview for new positions. Assuming the code you write is in decent shape...
A: If you are looking to get a job in game development, you should absolutely be doing some hobby development on the side while you look. Being able to send a more-or-less complete game along with your resume makes it stand out from the crowd. When we list a game programming job we get a ton of resumes, and while I'm thrilled to hire people with no industry experience to fill them, it's kind of hard to pick between all the options.
A: Sitting down at a problem and solving it with the tools at hand (whatever the problem is, fixing a database, programming an interface or making chess in ascii) is helping you becoming a better programmer.
Hands down.
A: YES
I taught myself C (and Psion's proprietary OO extensions) using the Psion Series 3 TopSpeed C SDK and wrote several games which I released under the GNU license. (Previously I had quite a bit of experience in Turbo Pascal and Pascal on the Amiga and Borland C++ 3.1 on Window 3.1 in a financial analysis internship doing signal processing, but when I got the Psion, I have to go back to C and I used K & R to get a good solid basis for that code.)
Then I parlayed the expertise I learned about the Psion platform into a 3 year gig doing mobile development using their industrial handhelds where I gained experience in databases, too. It was a huge turnaround for them, the product was in disarray and I had a ton more experience in the platform than anyone else - just from that year writing games.
I parlayed that into a Windows development gig where I eventually became IT director and got massive experience with SQL Server, Windows, ASP, data centers, DR, you name it.
Then I moved into data warehouse consultancy.
I owe a lot of it back to that first foot in the door where I really was able to make a massive difference to that first company because of the platform experience in C and that particular C-based library system.
A: I think more importantly, is the hobby game development making you happy?
Many areas of game development can absolutely be applicable on a more professional level, but if that's the only reason why you're developing games as a hobby then you may want to re-evaluate the situation and perhaps put your efforts toward various open source projects that could proudly be displayed on a resume (not that hobby game developing couldn't) or discuss at an interview.
Your hobbies should be something you love doing and if you love game development, then absolutely stick with it and hey, maybe you'll find yourself doing it professionally which ultimately seems like the ideal situation for your scenario.
A: I don't see how anything that enables you learn, practise and experiment could be considered 'childish'.
Besides, if you are aiming to produce a decent (even 'professional') game, it will almost certainly require learning and mastering skills that are directly transferable to may 'conventional' roles. Optimisation, testing, cross platform working, UI design and usability... the list goes on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How to parse formatted email address into display name and email address? Given the email address: "Jim" <jim@example.com>
If I try to pass this to MailAddress I get the exception:
The specified string is not in the form required for an e-mail address.
How do I parse this address into a display name (Jim) and email address (jim@example.com) in C#?
EDIT: I'm looking for C# code to parse it.
EDIT2: I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string.
A: Works for me:
string s = "\"Jim\" <jim@example.com>";
System.Net.Mail.MailAddress a = new System.Net.Mail.MailAddress(s);
Debug.WriteLine("DisplayName: " + a.DisplayName);
Debug.WriteLine("Address: " + a.Address);
The MailAddress class has a private method that parses an email address. Don't know how good it is, but I'd tend to use it rather than writing my own.
A: If you are looking to parse the email address manually, you want to read RFC2822 (https://www.rfc-editor.org/rfc/rfc822.html#section-3.4). Section 3.4 talks about the address format.
But parsing email addresses correctly is not easy and MailAddress should be able to handle most scenarios.
According to the MSDN documentation for MailAddress:
http://msdn.microsoft.com/en-us/library/591bk9e8.aspx
It should be able to parse an address with a display name. They give "Tom Smith <tsmith@contoso.com>" as an example. Maybe the quotes are the issue? If so, just strip the quotes out and use MailAddress to parse the rest.
string emailAddress = "\"Jim\" <jim@example.com>";
MailAddress address = new MailAddress(emailAddress.Replace("\"", ""));
Manually parsing RFC2822 isn't worth the trouble if you can avoid it.
A: Try:
"Jimbo <jim@example.com>"
A: new MailAddress("jim@example.com", "Jimbo");
to parse out the string you gave:
string input = "\"Jimbo\" jim@example.com";
string[] pieces = input.Split(' ');
MailAddress ma = new MailAddress(pieces[1].Replace("<", string.Empty).Replace(">",string.Empty), pieces[0].Replace("\"", string.Empty));
A: try: "Jim" <jim@example.com>
not sure if it'll work, but that's how I generally see it in e-mail clients.
A: string inputEmailString = "\"Jimbo\" <jim@example.com>";
string[] strSet = inputEmailString.Split('\"','<','>');
MailAddress mAddress = new MailAddress(strSet[0], strSet[2]);
A: if you make the assumption there is always a space between the 2, you could just use String.Split(' ') to split it on the spaces. That would give you an array with the parts split.
so maybe like this:
string str = "\"Jimbo\" jim@example.com"
string[] parts = str.Trim().Replace("\"","").Split(' ')
An issue with this to check for is that if the display name has a space in it, it will be split into 2 or more items in your array itself, but the email would always be last.
Edit - you might also need to edit out the brackets, just add replaces with those.
A: I just wrote this up, it grabs the first well formed e-mail address out of a string. That way you don't have to assume where the e-mail address is in the string
Lots of room for improvement, but I need to leave for work :)
class Program
{
static void Main(string[] args)
{
string email = "\"Jimbo\" <jim@example.com>";
Console.WriteLine(parseEmail(email));
}
private static string parseEmail(string inputString)
{
Regex r =
new Regex(@"^((?:(?:(?:[a-zA-Z0-9][\.\-\+_]?)*)[a-zA-Z0-9])+)\@((?:(?:(?:[a-zA-Z0-9][\.\-_]?){0,62})[a-zA-Z0-9])+)\.([a-zA-Z0-9]{2,6})$");
string[] tokens = inputString.Split(' ');
foreach (string s in tokens)
{
string temp = s;
temp = temp.TrimStart('<'); temp = temp.TrimEnd('>');
if (r.Match(temp).Success)
return temp;
}
throw new ArgumentException("Not an e-mail address");
}
}
A: It's a bit "rough and ready" but will work for the example you've given:
string emailAddress, displayname;
string unparsedText = "\"Jimbo\" <jim@example.com>";
string[] emailParts = unparsedText.Split(new char[] { '<' });
if (emailParts.Length == 2)
{
displayname = emailParts[0].Trim(new char[] { ' ', '\"' });
emailAddress = emailParts[1].TrimEnd('>');
}
A: To handle embedded spaces, split on the brackets, as follows:
string addrin = "\"Jim Smith\" <jim@example.com>";
char[] bracks = {'<','>'};
string[] pieces = addrin.Split(bracks);
pieces[0] = pieces[0]
.Substring(0, pieces[0].Length - 1)
.Replace("\"", string.Empty);
MailAddress ma = new MailAddress(pieces[1], pieces[0]);
A: So, this is what I have done. It's a little quick and dirty, but seems to work.
string emailTo = "\"Jim\" <jim@example.com>";
string emailRegex = @"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])";
string emailAddress = Regex.Match(emailTo.ToLower(), emailRegex).Value;
string displayName = null;
try
{
displayName = emailTo.Substring(0, emailTo.ToLower().IndexOf(emailAddress) - 1);
}
catch
{
// No display name
}
MailAddress addr = new MailAddress(emailAddress, displayName);
Comments?
A: I don't code in this language, but I see two issues you might want to check:
1- You don't know exactly why it was rejected. On immediate possibility was that it has a blacklist for example.com.
2- The real solution you want is to probably implement a strict validator. Stack Overflow is probably a good place to develop this, because there are lots of people with practical experience.
Here are a couple things you need:
*
*trim whitespace and obviously cruft.
*parse into individual parts (display name, left-hand-side of address, right-hand side of address).
*validate each of these with a data structure specific validator. For example, the right-hand side needs to be a valid FQDN (or unqualified hostname if you are on a liberal mail system).
That's the best long-term approach to solving this problem.
A: I can suggest my regex-based solution for decoding email address field values ("From", "To") and field value "Subject"
https://www.codeproject.com/Tips/1198601/Parsing-and-Decoding-Values-of-Some-Email-Message
A: If you are using MailKit, as recommended, then you can use the methods Parse and TryParse of MimeKit.MailboxAddress. Here's an example.
[Test]
public void Should_Parse_EmailAddress_With_Alias()
{
//Arrange
var expectedAlias = "Jim";
var expectedAddress = "jim@example.com";
string addressWithAlias = "\"Jim\" <jim@example.com>";
//Act
var mailboxAddressWithAlias = MimeKit.MailboxAddress.Parse(addressWithAlias);
//Assert
Assert.AreEqual(expectedAddress, mailboxAddressWithAlias.Address);
Assert.AreEqual(expectedAlias, mailboxAddressWithAlias.Name);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Doing your own custom .NET event processing loop A few years ago, I read a book that described how you could override the default event 'dispatcher' implementation in .NET with your own processor.
class foo {
public event EventHandler myEvent;
...
}
...
myFoo.myEvent += myBar1.EventHandler;
myFoo.myEvent += myBar2.EventHandler;
Whenever the event fires, both myBar1 and myBar2 handlers will be called.
As I recall, the default implementation of this loop uses a linked list and simply iterates over the list and calls the EventHandler delegates in order.
My question is two fold:
*
*Does someone know which book I was reading?
*Why would you want to override the default implementation (which might be answered in the book)?
Edit: The book I was referring to was indeed Jeffrey Richter's CLR via C#
A: It could have been one of many books or web articles.
There are various reasons why you might want to change how events are subscribed/unsubscribed:
*
*If you have many events, many of which may well not be subscribed to, you may want to use EventHandlerList to lower your memory usage
*You may wish to log subscription/unsubscription
*You may wish to use a weak reference to avoid the subscriber's lifetime from being tied to yours
*You may wish to change the locking associated with subscription/unsubscription
I'm sure there are more - those are off the top of my head :)
EDIT: Also note that there's a difference between having a custom way of handling subscription/unsubscription and having a custom way of raising the event (which may call GetInvocationList and guarantee that all handlers are called, regardless of exceptions, for example).
A: I seem to remember something similar in Jeffrey Richter's CLR via C#. Edit: I definitely do remember that he goes into detail about it.
There are a few different reasons for taking control of event registration. One of them is to reduce code bloat when you've got TONS of events. I think Jeffrey went into this in detail within the book...
A: *
*No
*You might, for example, need to break the call chain based on the result of one of the handlers. Say your CustomEventArgs object has a property 'Blocked', which when set to true suppresses all further event handler invocations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using system's standard Edit menu in a Palm OS app How can I use the standard Edit menu in my Palm OS application, instead of having to implement my own Cut/Copy/Paste/Keyboard handlers?
A: Palm OS's system form code had built-in handlers for the command IDs in the Edit menu. If you use a standard form for these menus, you have the advantage of not needing to write code and being compatible with system extensions that look for this particular menu construction.
If your form has a menubar that consists of just the "Edit" menu, you can specify menu ID 10000 at form creation time.
If your form has a menubar with several menus, you should specify your Edit menu like this, using PilRC notation:
PULLDOWN "Edit"
BEGIN
MENUITEM "Undo" ID 10000 "U"
MENUITEM "Cut" ID 10001 "X"
MENUITEM "Copy" ID 10002 "C"
MENUITEM "Paste" ID 10003 "P"
MENUITEM "Select All" ID 10004 "S"
MENUITEM "-" ID 10005
MENUITEM "Keyboard" ID 10006 "K"
MENUITEM "Grafitti Help" ID 10007 "G"
END
If you're using Constructor, you can use the "Create Edit Menu" command to add this menu to your resource file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to embed a browser object, other than IE, in a Delphi application Using the default TWebBrowser makes things easy to embed a web browser. Unfortunately the one that comes in by default is IE<n>.
I'm wondering how does one integrate a Gecko or WebKit one.
*
*Are there VCL examples somewhere?
*If not, how would one go about doing it?
*Where's the best place to find the core for Gecko and/or WebKit in an embeddable format?
A: Edit: Lars beat me to it, unfortunately
Well there is an ActiveX control based on the Gecko engine that tries to present an exact copy of the IWebBrowser API (which TWebBrowser uses).
You can find it here: http://www.iol.ie/~locka/mozilla/control.htm
Unfortunately it looks like it hasn't been updated in a while. The last version is based on Gecko 1.7.12 and I believe Gecko is currently up to 1.9.x (used in Firefox 3)
A: An alternative is THTMLViewer component. I have used this for some years.
This is now available free. the web siteis here http://pbear.com/htmlviewers.html. According to the songbeamer web site (http://www.songbeamer.com/delphi/) there is a Delphi 2009 version available.
A: TWebBrowser is IE. It is not a plugable construction for browsers. You can have other browsers integrated in your application. See
*
*http://www.adamlock.com/mozilla/
*http://delphi.mozdev.org/articles/taming_the_lizard_with_delphi.html
*http://ftp.newbielabs.com/Delphi%20Gecko%20SDK/
Time has moved on
This answer is from '08 and since then time has moved on. The links don't work anymore and there are probably better alternatives now.
A: Over the last three years I have come across very little in the way of embedding Gecko in Delphi. One library that showed up fairly late in the game (for me) was the GeckoSDK project on SourceForge. I did a lot of work early on trying to make embedded Gecko work correctly in Delphi. Our first attempt at a Gecko rendering engine based internal "browser" was built using Delphi and Gecko 1.8. We have since moved on and our browser is now a XULRunner application. I have pieces of code laying around on my hard drive yet from that early attempt that I have not deleted yet.
When Mozilla releases Gecko 2.0 I think it will become a lot easier to embed in Delphi. The XPCOM object system in Gecko makes it very difficult to embed because most everything returns an NS_RESULT. Strings especially were hard.
edit: I just looked through my old bookmarks (almost all of which are dead) and searched for a new url for the Japanese language "bagel" browser based on Gecko and found it here,
http://github.com/plus7/bagel/tree/master/Legacy.
This is probably your best bet for some excellent code to start from. Unfortunately the comments in the code are Japanese and the author never responded to questions.
A: A viable alternative is CEF - Chromium Embedded Framework which encapsulates the Chromium browser which by itself encapsulates WebKit. This library is provided as plain DLLs with an exported C API.
There's a delphi interface available at code.google.com/p/delphichromiumembedded
I've been using it with my own interface implementation and works great, though not so easy to properly use as THTML or IE, but great for whoever needs a powerful and embeddable browser.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Read fixed width record from text file I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way?
For example, the format could be described as:
<Field1(8)><Field2(16)><Field3(12)>
And an example file with two records could look like:
SomeData0000000000123456SomeMoreData
Data2 0000000000555555MoreData
I just want to make sure I'm not overlooking a more elegant way than Substring().
Update: I ultimately went with a regex like Killersponge suggested:
private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled);
const string REGEX_LOT = "^(?<Field1>.{6})" +
"(?<Field2>.{16})" +
"(?<Field3>.{12})";
I then use the following to access the fields:
Match match = reLot.Match(record);
string field1 = match.Groups["Field1"].Value;
A: Substring sounds good to me. The only downside I can immediately think of is that it means copying the data each time, but I wouldn't worry about that until you prove it's a bottleneck. Substring is simple :)
You could use a regex to match a whole record at a time and capture the fields, but I think that would be overkill.
A: Why reinvent the wheel? Use .NET's TextFieldParser class per this how-to for Visual Basic: How to read from fixed-width text files.
A: Use FileHelpers.
Example:
[FixedLengthRecord()]
public class MyData
{
[FieldFixedLength(8)]
public string someData;
[FieldFixedLength(16)]
public int SomeNumber;
[FieldFixedLength(12)]
[FieldTrim(TrimMode.Right)]
public string someMoreData;
}
Then, it's as simple as this:
var engine = new FileHelperEngine<MyData>();
// To Read Use:
var res = engine.ReadFile("FileIn.txt");
// To Write Use:
engine.WriteFile("FileOut.txt", res);
A: You may have to watch out, if the end of the lines aren't padded out with spaces to fill the field, your substring won't work without a bit of fiddling to work out how much more of the line there is to read. This of course only applies to the last field :)
A: Unfortunately out of the box the CLR only provides Substring for this.
Someone over at CodeProject made a custom parser using attributes to define fields, you might wanna look at that.
A: Nope, Substring is fine. That's what it's for.
A: You could set up an ODBC data source for the fixed format file, and then access it as any other database table.
This has the added advantage that specific knowledge of the file format is not compiled into your code for that fateful day that someone decides to stick an extra field in the middle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Rendered pIxel width data for each character in a browser's font I have a table column that needs to be limited to a certain width - say 100 pixels. At times the text in that column is wider than this and contains no spaces. For example:
a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy
I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters. The problem is that I don't have data about the rendered size of the text.
For example, assuming the browser was Firefox 3 and the font was 12px Arial. What would be the width of the letter "a", the width of the letter "b", etc.?
Do you have data showing the pixel width of each character? Or a program to generate it?
I think a clever one-time javascript script could do the trick. But I don't want to spend time re-inventing the wheel if someone else has already done this. I am surely not the first person to come up against this problem.
A: How about overflow: scroll?
A: Ext JS has a module to do just that
TextMetrics
Provides precise pixel measurements
for blocks of text so that you can
determine exactly how high and wide,
in pixels, a given block of text will
be.
I am sure that there are other libraries available out there that do it as well.
A: This would not only be impossible to do server-side, it would also not make sense. You don't what browser your client will be using, and you don't know what font settings on the client side will override whatever styling information you assign to a piece of HTML. You might think that you're using absolute positioning pixels in your style properties, but the client could simply be ignoring those or using some plugin to zoom everything because the client uses a high-dpi screen.
Using fixed widths is generally a bad idea.
A: Very very hard to do server-side. You can never know what fonts users have installed, and there are many things that affect the display of text.
Try this instead:
table-layout: fixed;
That'll make sure the table is never larger than the size you specified.
A: Here is my client-side solution that I came up with. It is pretty specific to my application but I am sharing it here in case someone else comes across the same problem.
It works a bit more quickly than I had expected. And it assumes the contents of the cells are text only - any HTML will formatting will be erased in the shortening process.
It requires jQuery.
function fixFatColumns() {
$('table#MyTable td').each(function() {
var defined_width = $(this).attr('width');
if (defined_width) {
var actual_width = $(this).width();
var contents = $(this).html();
if (contents.length) {
var working_div = $('#ATempDiv');
if (working_div.is('*')) {
working_div.html(contents);
} else {
$('body').append('<div id="ATempDiv" style="position:absolute;top:-100px;left:-500px;font-size:13px;font-family:Arial">'+contents+'</div>');
working_div = $('#ATempDiv');
}
if (working_div.width() > defined_width) {
contents = working_div.text();
working_div.text(contents);
while (working_div.width() + 8 > defined_width) {
// shorten the contents of the columns
var working_text = working_div.text();
if (working_text.length > 1) working_text = working_text.substr(0,working_text.length-1);
working_div.text(working_text);
}
$(this).html(working_text+'...')
}
working_div.empty();
}
}
});
}
A: This is essentially impossible to do on the server side. In addition to the problem of people having different fonts installed, you also have kerning (the letter "f" will take up a different amount of space depending on what is next to it) and font rendering options (is cleartype on? "large fonts"?).
A: You could put the text into an invisible span and read that spans width, but basicly this looks like someone trying to sabotage your site, and therefore I would recommend banning posts with words longer than a certain lenth, for example 30 characters without spaces (allowing links to be longer !-)
-- but the simple approach is to put a block-element inside the table-cell:
<td><div style="width:100px;overflow:hidden">a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_ta ... </div></td>
This will effectively stop the table-cluttering !o]
A: There's nothing you can do server-side to calculate it. All you have to work with is the browser identification string, which may or may not tell you the user's operating system and browser accurately. You can also "ask" (via a font tag or CSS) for a certain font to be used to display the text but there's no guarantee that the user has that font installed. Beyond that the user could have a different DPI setting at the operating system level, or could have made the text bigger or smaller with the browser zoom function, or could be using their own stylesheet altogether.
A: If you're ok with this not working for FireFox, why not just use CSS? Have the table with table-layout:fixed, have the column in question have overflow:hidden;text-overflow:ellipsis; white-space:nowrap.
A: http://www.css3.info/preview/text-overflow/
This is a new function of css3.
A: Some users have larger or smaller default font settings. You can't do this on the server. You can only measure it once the browser has rendered the page.
A: Since font size can be easily changed on the browser side, your server-side calculation is made invalid very easily.
A quick client side fix would be to style your cells with an overflow attribute:
td
{
overflow: scroll; /* or overflow: hidden; etc. */
}
A better alternative is to truncate your strings server side and provide a simple javascript tooltip that can display the longer version. An "expand" button may also help that could display the result in an overlay div.
A: What you want is the <wbr> tag. This is a special HTML tag that tells the browser that it is acceptable to break a word here if a wrap is necessary. I would not inject the into the text for persistent storage because then you are coupling your data with where/how you will display that data. However, it is perfectly acceptable to inject the tags server side in code that is view-centric (like with a JSP tag or possibly in the controller). That's how I would do it. Just use some regular expression to find words that are longer than X characters and inject this tag every X characters into such words.
Update: I was doing some looking around and it looks like wbr is not supported on all browsers. Most notably, IE8. I haven't tested this myself though. Perhaps you could use overflow:hidden as a backup or something like that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Dojo DnD acceptance of outside objects Is it possible to code a Dojo DnD target to accept external objects, such as files or folders from a file explorer? Windows Explorer, for example.
A: I doubt it, because it will be the browser that will receive the DnD event...
At best you can count on a plugin or extension to handle it, like the excellent DragDropUpload extension does for file upload fields in Firefox.
A: What kind of file explorer are you talking about? From what I can recall you'd be lucky to get dnd working properly even for table rows, the api is a pain in the @$$.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C, C++, Java, what is next and what will it look like? What do you think the next evolution of languages will look like?
A: You might assume C and C++ are being "phased out" and that Java/.Net/Python/whatever is an "advance" or the "next stop".
They are all used heavily (see the number C or C++ of tags on this site). The difference is that neither one is the lingua-franca of the programming world anymore. It used to be that the majority of apps were desktop or DOS apps on systems with very limited resources, furthermore all the major desktop APIs were written in C or C++. So everyone learned these.
Now its more complex. Languages are becomming more application specific. C/C++ for when performance is important. Scripting languages for when your main performance hit is db reads/writes. Java and .Net for generic, non-performance-critical desktop apps.
Its the same thing with computer or electrical engineering. In the past these were huge fields at the highest level of abstraction available. Now we have all sorts of higher levels of abstraction. Still, we need people to do this lower-level kind of engineering. They are still in demand. In the same manner, C will continue to be used in many environments, as will C++. You'd be crazy, for instance, to think that you could write a device driver in Java, you'd also be mildly crazy (but perhaps less so) to write a full fledged GUI app in C if you had the choice and ability to do it in Java or .Net.
Each tool has its purpose. I expect C, C++, and Java to evolve and continue to be used for new and legacy development.
A: I can't speak for C++ and Java, but C definitely ain't goin' nowhere...
It's pretty much unthinkable to write any kind of operating system kernel without most of it in C (well, you can use assembly language entirely if you are really stubborn :-P).
C is basically a thin wrapper of niceness around assembly language. It's so tightly coupled to a standard Von Neumann CPU architecture that no standard library or runtime is required to implement most of its features: pointers, character strings, automatic variables on the stack, integer arithmetic, etc.
For the same reasons, C is great for user-level applications that absolutely demand high performance, things like multiplying huge matrices or parsing complex languages. It may be a pain to write a parser in C, but the speed and efficiency advantages of manual memory management are hard to pass up...
A: Alan Kay once said "Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind."
He is working on changing the future of programming
"The real romance is out ahead and yet to come. The computer revolution hasn't started yet. Don't be misled by the enormous flow of money into bad defacto standards for unsophisticated buyers using poor adaptations of incomplete ideas." source
Well, I might add that Bjarne once said "There are only two kinds of languages: the ones people complain about and the ones nobody uses."
A: Languages evolve to fill a niche problem that is not covered by other languages.
Weather that language gets a foot hold and establishes itself is another question entirely and has a lot to do with popularity.
What comes next?
The problem I see that needs filling is multi-processors (or multi-cores). Currently all the popular languages have very limited ability to exploit the additional cores. Basically all current popular languages give the developer the very basic objects (threads/locks etc) to use the cores and then leave it up to the developer to try and exploit the parallelism available from multi-cores.
It would be a nice to have a language that abstracted away the concept of cores (even threads) and could automatically exploit the enherant parallelism available from multi-cores/multi-processor architecture. Unfortunately all these languages (that I know about) are still research projects at universities and are unlikely to see real adoption any time soon.
You imply that there was a progression C -> C++ -> Java.
That's a bit artificial, each language represents a method of solving problems and each language has inherent problem domains where it is efficient at solve a problem and other problem domains where that language would be a bad choice.
Personally:
*
*I would never write a device driver with Java.
*I would probably not write back-end web module with C (you probably can but not me)
etc.
A: C# ? -- oh, but that is Java :) (sorry, couldn't resist)
The next generation of languages is already here, Scripting ones. Its no mistake that Microsoft is working on the DLR (dynamic language runtime). I think the future will be interpreted (but JITted), dynamic languages that have few constraints and lots of flexibility.
Performance constraints for the majority of languages are not so important nowadays, or no-one would be writing Java or C# apps at all, but considering CPUs are super-fast, and RAM is cheap, we don't notice the inefficiencies of these higher-level designs (eg if you have a 1mhz cpu, you write your code in C, not C#. If you have a CPU running at 3Ghz, you write it whatever you like)
So.. Ruby, Python, "Dynamic-C#"... these are the future. When MS releases the DLR, expect a lot of interest in it, expect a lot of companies to start talking about programmer productivity as the most important part of most application development.
After that.... probably a GUI-driven system where you connect blocks together in a UML-a-like system and add properties to them that produces generated code.
A: I believe the answer is twofold.
First, client side applications are more and more implemented as browser based applications. To give a browser based application a look and feel comparable to rich desktop application you need something like Javascript. And if you followed the news a bit you see a tremendous effort towards speeding up the javascript implementation in browsers, and a flourishing ecosystem of libraries which help you create a responsive, intuitive GUI with javascript in a browser.
So, for GUIs I believe the future is Javascript.
For the backend, the server, I very much doubt that the near future has a scripted language in store. Server-side software tends to live for years and years, features added, bugs fixed and all. The language in which that is written needs to be not so much fast to write, but easy to read (maintain).
And scripted languages tend to be a bit more difficult to understand if you revisit your code after a year or two to fix that bug. That has (in my opinion) two primary reasons which will not go away in the short term:
*
*IDEs have trouble giving hints with dynamic languages
*In the context your working there is by definition less context information available; in Java you know you can only get type X. In a scripted language you should check all referencing code, not easy in a large project
These problems can be mitigated by using very experienced developers, but if, in the future, the only kind of usefull developer is a experienced one we won't need to hire inexperienced ones, which will give trouble in the future.
For those reasons I believe the next-gen server-side language is statically typed. And from the statically typed languages I think C# and Java have the best chances due to the enormous amount of usefull libraries available and the very readable nature of those languages.
A: As other have mentioned, languages tend to adapt around new technologies and trends. So in order to answer that question, you first have to look at the overall future of computers and see what languages are most suitable for these purposes.
For example, to use your language progression as an example, in the beginning (:-)) there was a need for a language that would make maximum use of the limited resources available, C fit the bill in that regard. As time went on, and the spectrum of software applications incresed there was a greater demand for OO based languages in order to facilitate software reuse, easier design etc. and C++ / Java became popular.
Currently, there is an increased drift in the industry towards server side components that do all the work with thin client UIs (i.e. browsers). So languages that cater for this demand are becomming more popular (Ruby, ASP/Java EE languages).
New languages will become popular when the technology that they are closest to become popular.
Personally (and this is guesswork), I think there is huge scope for a language that truly takes advantage of multi-core systems. This will mean having multi-threading built from the very start and will probably require a change in approach and thinking (like going from procedural to OO).
A: It's going on a couple years old now, but Tim Sweeney's The Next Mainstream Programming Language: A Game Developer's Perspective is an interesting cogitation on the subject.
A: What is the future of programming? Away from languages as we know them.
It's 2009 and we're still using text editors? With the project I'm a part of you can build entire applications simply by setting attributes. Outside of (mainly mathematical) expressions and string values, there's not a line of text anywhere.
One of the developers complained that "you can't print out the code," and I replied, "Would a company print out its entire accounting structure? Or would it print out the aspects it wants to see, such as Cashflow Statements and Balance Sheets?" It's only when we move out into new abstraction mechanisms that we can really move ahead.
The future of programming remains to be seen, but I think there are some exciting developments happening that will finally release us from the C/C++/Java harness we've had on for so long.
A: On the short term, I expect high level languages to become more powerful and more used. Perl 6 and Javascript 2.0 are good examples of what awaits us.
On the long term, functional languages might make it into the mainstream, but I expect that will not happen any time soon.
A: At some point programs will start writing their own programs making humans redundant as far as programming is concerned. The major disagreement is when this will happen.
A: If you follow only this branch of programming language history, I think one can write both JavaScript and C#, since they came after the three you mention, share a similar syntax, and took from the predecessors.
Others might mention D or Objective-C (they are already here, of course).
By next language, I suppose you mean "next successful", because there is almost a new language each month...
I think it will be a language with garbage collection, running on bytecode with Jit, highly portable.
I can't tell if it will be object-oriented or functional, with static or dynamic typing, but I would bet on a mix, like does the interesting Fan Programming Language.
Or maybe we are all wrong, it might just a natural language, with spoken or graphical interface: "Take the weather box of this page, change its color and this logo to that, and integrate in my page".
A: What would be great, in my opinion, is a language like C++ with a more compact definition, better standard library, native garbage collection, and native synchronization constructs. It should be usable by relative novices, but still provide facilities for experts to program in an efficient, low-level way when needed. I believe D meets most of these criteria, but it seems unlikely to me that it will take hold.
A: D language, especially the 2.0 version has learnt from Ruby, Python and lots of modern languages without keeping source compatibility with C, still allowing for raw access to the metal. The design decisions of this language are a perfect solution for next-generation system and general programming languages, with even functional programming and metaprogramming built-in.
A: The language question is in my opinion no either or. It allways depends on your application. And since languages have mostly a standard set of libraries that are well suited for this or that application. Languages are tied somewhat to a particular application field.
For Example:
C -> Device drivers
C++ -> Highperformance Computing
Java -> Server side programs (J2EE)
C# -> Server, Client(Silverlight, WinForm, WPF)
Ruby, Python, ... -> WebScripting (Serverside) and helper scripts
ECMAScript (Javascript) -> WebScripting (Clientside)
I think any of these languages are capable to solve any computing program (also performance wise since we have Jits) but they are not used in any field since it is not feasible to recreate every library for every language.
On thing that makes C and C++ special is, that there is a standard library but compared to the others it is a rather minimalistic standard library. To use those languages efficiently 3rd party (non-standard) libraries are needed.
So when choosing a language for a project you look for these things:
*
*Are there the right libraries you can use in your project
*Do you know the language
*Is it efficient to programm in this language (look at brainfuck)
*Does your team know and master the language?
The last thing is also do you like the language? At the end that is the biggest motivation to use this or that language.
So the next step in language evolution will be higher level libraries and concepts to be faster and more expressive. Examples are
*
*Lambda expressions
*Linq (C# feature to do sort of sql in the language)
*functional programming
*variable typing
*dynamic typing
*not particular language: better IDEs that assists the programmer
*Important: Support for easy! parallelism (Axum, Nesl, orca, Chapel, ... ) Here list
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What are your favorite tools to backport modifications from branch to trunk in subversion directories? On a project I'm working on, we use subversion, with tortoiseSVN as a client, under windows XP.
As we enter in production and continue development in parallel, many branches are created.
Often, we have to backport modifications made on the branch to the trunk, or to older branches. Backporting is a very delicate task, as many errors can be introduced into the code.
What are your favorite tools to make backporting easier and more secure ? If possible, add only one tool per answer, and vote for your favorite ones.
A: I am using BeyondCompare. I believe it's one of the most essential tools for a developper, up there with TortoiseSVN.
A: Whatever diff-merge-tool you use, make sure you read the "Branching and Merging" chapter from the Subversion book. Since version 1.5, Subversion supports merge tracking, so read the documentation appropriate for your version:
*
*version 1.5
*version 1.4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Algorithm to calculate next set in sequence I am looking for an algorithm to calculate the next set of operations in a sequence. Here is the simple definition of the sequence.
*
*Task 1A will be done every 500 hours
*Task 2A will be done every 1000 hours
*Task 3A will be done every 1500 hours
So at t=500, do 1A. At t=1000, do both 1A and 2A, at t=1500 do 1A and 3A, but not 2A as 1500 is not a multiple of 1000. You get the idea.
It would be quite easy if I had the actual time, but I don't. What I have is the history of tasks (eg last time a [1A+2A] was done).
Knowing last time (eg [1A+2A]) is not enough to decide:
*
*[1A+2A] could be at t=1000: next is [1A+3A] at t=1500
*[1A+2A] could be at t=5000: next is [1A] at t=5500
Is there an algorithm for this? It looks like a familiar problem (some sort of sieve?) but I can't seem to find a solution.
Also it must "scale" as I actually have more than 3 tasks.
A: If you have enough history to get the last two times each task was done you could reconstruct the original task sequence definitions. When they coincide is incidental.
A: The sequence must repeat. For the example given, the sequence would be 1A, 1A+2A, 1A+3A, 1A+2A, 1A, 1A+2A+3A. In this situation, you could see how far back the last 1A+2A+3A is and use that distance as an index into an array. In the general case, for a cycle of length N, you could always do it by testing the last N events against all rotations of the cycle, but I suspect that there will usually be some kind of shortcut available, like how many events back the last "do everything" event happened, or how long ago the last "do everything" event happened.
A: Seems like a greatest common denominator problem.
A: Edit:
Ah, you have to go the other way. In that case, as someone mentioned, you can calculate an effective @TimeLastJob using the least common multiple of the three
--Note: uses some SQL Server 2005 SQL extentions,
-- but can still serve as a psuedocode specification of the algorithm
DECLARE @constEvaluationPeriodLength int
DECLARE @constCycleTimeJob1A int
DECLARE @constCycleTimeJob2A int
DECLARE @constCycleTimeJob3A int
SET @constEvaluationPeriodLength = 500
SET @constCycleTimeJob1A = 500
SET @constCycleTimeJob2A = 1000
SET @constCycleTimeJob3A = 1500
DECLARE @Indicator1ARunAtLastCyclePoint int
DECLARE @Indicator2ARunAtLastCyclePoint int
DECLARE @Indicator3ARunAtLastCyclePoint int
SET @Indicator1ARunAtLastCyclePoint = 1
SET @Indicator2ARunAtLastCyclePoint = 0
SET @Indicator3ARunAtLastCyclePoint = 1
DECLARE @tblPrimeFactors TABLE(
TaskId int
CycleTimePrimeFactor int
)
--Capture the prime factors for each TaskId
IF (@Indicator1ARunAtLastCyclePoint = 1)
BEGIN
INSERT @tblPrimeFactors
SELECT
TaskId = 1
,PrimeFactor
FROM dbo.tvfGetPrimeFactors(@constCycleTimeJob1A) --Table-valued function left for the reader
END
IF (@Indicator2ARunAtLastCyclePoint = 1)
BEGIN
INSERT @tblPrimeFactors
SELECT
TaskId = 2
,PrimeFactor
FROM dbo.tvfGetPrimeFactors(@constCycleTimeJob2A) --Table-valued function left for the reader
END
IF (@Indicator3ARunAtLastCyclePoint = 1)
BEGIN
INSERT @tblPrimeFactors
SELECT
TaskId = 3
,PrimeFactor
FROM dbo.tvfGetPrimeFactors(@constCycleTimeJob3A) --Table-valued function left for the reader
END
--Calculate the LCM, which can serve as an effective time
--Utilizes SQL Server dynamic table capability
--(Inner select statements w/in parenthesis and given the alias names t0 & t1 below)
DECLARE @LCM int
SELECT
--Fun w/ logs/powers to effect a product aggregate function
@LCM = Power(sum(log10(power(PrimeFactor,Frequency))),10)
FROM
(
SELECT
PrimeFactor
,Frequency = max(Frequency)
FROM
(
SELECT
PrimeFactor
,Frequency = count(*)
FROM @tblPrimeFactors
GROUP BY
TaskId
,PrimeFactor
) t0
) t1
DECLARE @TimeLastJob int
DECLARE @TimeNextJob int
SET @TimeLastJob = @LCM
SET @TimeNextJob = @TimeLastJob + @constEvaluationPeriodLength
SELECT
Indicator1A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob1A)
,Indicator2A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob2A)
,Indicator3A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob3A)
Original:
The modulus operataor % should do the trick
If I'm reading this correctly, you do have the time of the last task
*
*t=1000 or
*t=5000
and frequency of task selection evaluation is every 500 hours.
Try varying @TimeLastJob to see if the script below provides you w/ what you need
DECLARE @constEvaluationPeriodLength int
DECLARE @constCycleTimeJob1A int
DECLARE @constCycleTimeJob2A int
DECLARE @constCycleTimeJob3A int
SET @constEvaluationPeriodLength = 500
SET @constCycleTimeJob1A = 500
SET @constCycleTimeJob2A = 1000
SET @constCycleTimeJob3A = 1500
DECLARE @TimeLastJob int
DECLARE @TimeNextJob int
--SET @TimeLastJob = 1000
SET @TimeLastJob =5000
SET @TimeNextJob = @TimeLastJob + @constEvaluationPeriodLength
SELECT
Indicator1A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob1A)
,Indicator2A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob2A)
,Indicator3A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob3A)
A: Bill the Lizard is right. Here is how to determine the task intervals from the history (in Python):
history = [list of tuples like (timestamp, (A, B, ...)), ordered by timestamp]
lastTaskTime = {}
taskIntervals = {}
for timestamp, tasks in history:
for task in tasks:
if task not in lastTaskTime:
lastTaskTime[task] = timestamp
else:
lastTimestamp = lastTaskTime[task]
interval = abs(timestamp - lastTimestamp)
if task not in taskIntervals or interval < taskIntervals[task]:
taskIntervals[task] = interval # Found a shorter interval
# Always remember the last timestamp
lastTaskTime[task] = timestamp
# taskIntervals contains the shortest time intervals of each tasks executed at least twice in the past
# lastTaskTime contains the last time each task was executed
To get the set of tasks, which will be executed next:
nextTime = None
nextTasks = []
for task in lastTaskTime:
lastTime = lastTaskTime[task]
interval = taskIntervals[task]
if not nextTime or lastTime + interval < nextTime:
nextTime = lastTime + interval
nextTasks = [task]
elif lastTime + interval == nextTime:
nextTasks.append(task)
# nextTime contains the time when the next set of tasks will be executed
# nextTasks contains the set of tasks to be executed
A: Prerequisites:
*
*Calculate the LCM of the tasks' time; this is the period of a full cycle.
*Compute the event timeline for the full cycle.
As each task / group of tasks is started, move an index through the timeline.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Using Length() with multi-dimensional dynamic arrays in Delphi I am using a multi-dimensional dynamic array in delphi and am trying to figure this out:
I have 2 seperate values for the first index and second index that are totally seperate of each other.
As new values come I want to grow the array if that new value is outside of either bound.
For new values x, y
I check:
if Length(List) < (x + 1) then
SetLength(List, x + 1);
if Length(List[0]) < (y + 1) then
SetLength(List, Length(List), y + 1);
Is this the correct way to do this or is there a better way to grow the array as needed?
A: It looks fine to me - if you change the last line to
SetLength(List, Length(List), y + 1);
A: I think you forgot to use the second index on the second dimension;
Your code should probably read like this :
if Length(List) < (x + 1) then
SetLength(List, x + 1);
if Length(List[x]) < (y + 1) then
SetLength(List[x], y + 1);
Note the use of 'x' as the first dimension index when growing the second dimension.
One caution though :
You should be aware of the fact that Delphi uses reference-counting on dynamic arrays too (just like how it's done with AnsiString).
Because of this, growing the array like above will work, but any other reference to it will still have the old copy of it!
The only way around this, is keeping track of these array's with one extra level of indirection - ie. : Use a pointer to the dynamic array (which is also a pointer in itself, but that's okay).
Also note that any of those 'external' pointers should be updated in any situation that the address of the dynamic array could change, as when growing/shrinking it using SetLength().
A: @PatrickvL:
Sorry, but that is just plain wrong. Your code does not even compile because it tries to set two dimensions for the single-dimensional element List[x]. (PatrickvL updated his code so this part of the answer is no longer valid.)
The following code demonstrates multidimensional array resizing.
program TestDimensions;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
List: array of array of integer;
begin
//set both dimensions
SetLength(List, 3, 2);
Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 3, Y = 2
//set main dimension to 4, keep subdimension untouched
SetLength(List, 4);
Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 2
//set subdimension to 3, keep main dimenstion untouched
SetLength(List, Length(List), 3);
Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 3
//all List[0]..List[3] have 3 elements
Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //3333
//you can change subdimension for each List[] vector
SetLength(List[0], 1);
SetLength(List[3], 7);
//List is now a ragged array
Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //1337
//this does not even compile because it tries to set dimension that does not exist!
// SetLength(List[0], Length(List[0]), 12);
Readln;
end.
The Delphi help also explains this quite nicely (Structured Types, Arrays).
Multidimensional Dynamic Arrays
To declare multidimensional dynamic arrays, use iterated array of ... constructions. For example,
type TMessageGrid = array of array of string;
var Msgs: TMessageGrid;
declares a two-dimensional array of strings. To instantiate this array, call SetLength with two integer arguments. For example, if I
and J are integer-valued variables,
SetLength(Msgs,I,J);
allocates an I-by-J array, and Msgs[0,0] denotes an element of that array.
You can create multidimensional dynamic arrays that are not rectangular. The first step is to call SetLength, passing it parameters for the first n dimensions of the array. For example,
var Ints: array of array of Integer;
SetLength(Ints,10);
allocates ten rows for Ints but no columns. Later, you can allocate the columns one at a time (giving them different lengths); for example
SetLength(Ints[2], 5);
makes the third column of Ints five integers long. At this point (even if the other columns haven't been allocated) you can assign values to the third column - for example, Ints[2,4] := 6.
The following example uses dynamic arrays (and the IntToStr function declared in the SysUtils unit) to create a triangular matrix of strings.
var
A : array of array of string;
I, J : Integer;
begin
SetLength(A, 10);
for I := Low(A) to High(A) do
begin
SetLength(A[I], I);
for J := Low(A[I]) to High(A[I]) do
A[I,J] := IntToStr(I) + ',' + IntToStr(J) + ' ';
end;
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ora 12154 error I recently deploy one web application in one of my development servers. I'm using oracle, asp.net and c#. When I run the application in the server everything works fine, but when I try to run the application outside of the server (using my pc, for example) i get this error:
ORA-12154: TNS:could not resolve the connect identifier specified
If i run the application in my pc with visual studio it works fine.
Oracle is installed in Server "A" and the application is in server "B". Server "A" is in one domain and server "B" is in other domain.My pc is in the same domain has Server "A".
In my pc I can find the file tnsname.ora in C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN, but in Server "B" i can´t find it anywhere
any idea?
Thanks for the help.
A: Have you tried this yet? (from http://ora-12154.ora-code.com/)
ORA-12154: TNS:could not resolve the connect identifier specified
Cause: A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.
Action:
- If you are using local naming (TNSNAMES.ORA file):
*
*Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)
*Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.
*Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.
*Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.
*If you are using directory naming:
*Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
*Verify that the LDAP directory server is up and that it is accessible.
*Verify that the net service name or database name used as the connect identifier is configured in the directory.
*Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier
*If you are using easy connect naming:
*Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
*Make sure the host, port and service name specified are correct.
*Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.
A: Resolving TNS errors can be a real pain. A few things to keep in mind.
Most development environments (like visual studio) keep their own copy of the TNS connection information, and do not use the TNSNAMES.ora file. The file where this information is kept does not have to be called TNSNAMES.ora, that's just the default name. Which may be the reason you can't find it on Server B.
If you have the oracle client software (or an oracle database) you can use tnsping to check if your TNSNAMES.ora file is configured correctly.
The most frequent problems with a TNSNAMES.ora file configuration are using the wrong service name and/or using the wrong host name. You may need to change the "ODB_A" to "ODB_A.WORLD" or vice versa, depending upon the SQLNET settings. For Oracle 10, the latter is the default SQLNET setting. For the latter, you need to use ping to see server "A", and know if you need to use "SERVERA" or "SERVERA.DOMIN.COM" or an IP address.
A: Do not put @ in the password you are setting or remove it from the password.
I was also getting the error and after changing it, the error got resolved.
A: Guess: An oracle client is not installed on Server B.
If you do have an oracle client installed then you can still put a tnsnames file in any location (Such as a directory on a network share). In order to do this, set a TNS_ADMIN system variable (System Properties->Advanced->Environment Variables on XP) to the directory containing your tnsnames files.
For me for example I have a system variable: TNS_ADMIN - C:\oracle\ora92\network\ADMIN
A: Is ORACLE_HOME set on server B?
A: It seems you need to install Oracle Client on "Server B" (the application server), and configure it's TNSNAMES.ORA file. This is required since otherwise, the running code will have no idea where to look for the database you use in the application (probably you're configured a data source in web.config or hard-coded something).
Remember - you cannot access Oracle (easily) without Oracle Client.
A: Had the same problem. Turns out the TNSNAMES.ORA in out deployment environment had a different ADDRESS_NAME and SID/SERVICE_NAME ,and the application was configured to use the SID - which caused the problem.
Your connection string must contain the ADDRESS_NAME and not the SID
A: Possible Resolutions -
Verify that the TNSNAMES.ORA exists and is accessible.
Make sure that there are no syntax errors in TNSNAMES.ORA.
Verify that the connection string is correct.
Verify if there are any DNS issues.
If the problem is while connect to server using PL sql developer client.try to install SQL developer within Program File instead of Program Files(x86)'s
A: Add the environment:
Variable Name: TNS_ADMIN
Variable Value: (YourDrive):\app\(UserName)\product\11.2.0\dbhome_1\NETWORK\ADMIN
A: I had faced the similar issue. The below code was working in my system but was not working in another server even though I had added a tns entry in tnsnames.ora file.
con = new OracleConnection();
con.ConnectionString = "User Id=username;Password=password;Data Source=uit45";
con.Open(); // throws error here
After digging and digging, I found out the solution for this. We need to ignore the entry in tns file and can be given tns entry as connection string, which worked fine for me. Try the below code.
con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=db-uit45.xxx)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=uit45)));User Id=username;Password=password");
con.Open();
Note that you need to give the associated values, especially for HOST,PORT,SID,User Id and Password.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Sql Server 2005 how to change dbo login name I have a database with user 'dbo' that has a login name "domain\xzy". How do I change it from "domain\xzy" to "domain\abc".
A: If you are trying to remap a login to a db user you can use sp_change_user_login
exec sp_change_user_login 'Update_One', 'user', 'login'
A: I figured it out. Within SQL Management Studio you have to right-click on the database -> Properties -> Files -> Owner field. Change this field to the login name/account that you want associated with the "dbo" username for that database. Please keep in mind that the login name/account you choose must already be setup in the sql server under Security -> Logins
A: PhantomTypist gives a good answer using the GUI. For achieving the same result with TSQL, you can use this code:
USE [My_Database_Name]
GO
EXEC dbo.sp_changedbowner @loginame = N'domain\abc', @map = false
GO
A: This is a Windows login, not a SQL Server login, so you cannot 'change' the login name since it is linked to the user account in Active Directory.
Create a new Server Login (Windows) mapped to the new windows user (and remove the old one if necessary). Then in login's Security > User Mapping, permission that login to the appropriate database as user 'dbo' (or assign to the db_owner role)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
} |
Q: Best way to store urls locally I am creating an RSS reader as a hobby project, and at the point where the user is adding his own URL's.
I was thinking of two things.
*
*A plaintext file where each url is a single line
*SQLite where i can have unique ID's and descriptions following the URL
Is the SQLite idea to much of an overhead or is there a better way to do things like this?
A: Why not XML?
If you're dealing with RSS anyway you mayaswell :)
A: What about as an OPML file? It's XML, so if you needed to store more data then the OPML specification supplies, you can always add your own namespace.
Additionally, importing and exporting from other RSS readers is all done via OPML. Often there is library support for it. If you're interested in having users switch then you have to support OPML. Thansk to jamesh for bringing that point up.
A: Do you plan just to store URLs? Or you plan to add data like last_fetch_time or so?
If it's just a simple URL list that your program will read line-by-line and download data, store it in a file or even better in some serialized object written to a file.
If you plan to extend it, add comments/time of last fetch, etc, I'd go for SQLite, it's not that much overhead.
A: If it's a single user application that only has one instance, SQLite might be overkill.
You've got a few options as I see it:
*
*SQLite / Database layer. Increases the dependencies your code needs to run. But allows concurrent access
*Roll your own text parser. Complexity increases as you want to save more data and you're re-inventing the wheel. Less dependency and initially, while your data is simple, it's trivial for a novice user of your application to edit.
*Use XML. It's well formed & defined and text editable. Could be overkill for storing just a URL though.
*Use something like pickle to serialize your objects and save them to disk. Changes to your data structure means "upgrading" the pickle files. Not very intuitive to edit for a novice user, but extremely easy to implement.
A: I'd go with the XML text file option. You can use the XSD tool built into Visual Studio to create a DataTable out of the XML data, and it easily serializes back into the file when needed.
The other caveat is that I'm sure you're going to want the end user to be able to categorize their RSS feeds and be able to potentially search/sort them, and having that kind of datatable style will help with this.
You'll get easy file storage and access, the benefit of a "database" structure, but not quite the overhead of SQLite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Picture over Flash Do you know any solution to put a picture over a Flash?
It must work in IE6, IE7, Firefox for Windows, MacOSX, Linux and Safari.
A: Off the top of my head you could try this:
Absolute positioned div with the image over the swf
You must set swf's parameter "wmode" value as "transparent".
You could also go to www.actionscript.org and do a search on their forum.
A: Funnily, I did something similar on SO, but over the arrow of a combo box...
Reusing the technique:
<object width="550" height="450"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"
classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000">
<param name="movie" value="http://somesite.org/Tests/Spiffy.swf"/>
<param name="wmode" value="opaque"/>
<object type="application/x-shockwave-flash" width="550" height="450"
data="http://somesite.org/Tests/Spiffy.swf">
<param name="wmode" value="opaque"/>
<img src="NoFlash.png" width="550" height="450" alt="Placeholder if no Flash" />
</object>
</object>
<div style="background-color: blue;
min-width: 100px; width: 100px; min-height: 100px; height: 100px;
position: relative; right: -250px; top: -250px;">&Nbsp;</div>
Found the wparam=opaque trick at wmode and z-index, search fueled by the remark of tehborkentooth above (which advised to use transparent, but it didn't work for me).
Of course, the style of the div should go in a class. The Nbsp is to make SO happy, it must be or real content, of course.
A: The wmode=opaque provides better performance than "transparent", with pretty much the same results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Subclassing a class with private members One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:
self.__value = 1
def value():
return self.__value
Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.
I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?
A: Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '__value' attribute, the attribute is actually being stored as '_ContainerThing__value'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute.
This is exactly why the double-underscore name-mangling (which is not really "private", just "inconvenient") is a bad idea to use. Just use a single leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible.
For the record, '__value' and 'value' (and '_value') are not the same name. The underscores are part of the name.
A: "I know this seems to go against the general idea of private and public" Not really "against", just different from C++ and Java.
Private -- as implemented in C++ and Java is not a very useful concept. It helps, sometimes, to isolate implementation details. But it is way overused.
Python names beginning with two __ are special and you should not, as a normal thing, be defining attributes with names like this. Names with __ are special and part of the implementation. And exposed for your use.
Names beginning with one _ are "private". Sometimes they are concealed, a little. Most of the time, the "consenting adults" rule applies -- don't use them foolishly, they're subject to change without notice.
We put "private" in quotes because it's just an agreement between you and your users. You've marked things with _. Your users (and yourself) should honor that.
Often, we have method function names with a leading _ to indicate that we consider them to be "private" and subject to change without notice.
The endless getters and setters that Java requires aren't as often used in Python. Python introspection is more flexible, you have access to an object's internal dictionary of attribute values, and you have first class functions like getattr() and setattr().
Further, you have the property() function which is often used to bind getters and setters to a single name that behaves like a simple attribute, but is actually well-defined method function calls.
A: Not sure of where to cite it from, but the following statement in regard to access protection is Pythonic canon: "We're all consenting adults here".
Just as Thomas Wouters has stated, a single leading underscore is the idiomatic way of marking an attribute as being a part of the object's internal state. Two underscores just provides name mangling to prevent easy access to the attribute.
After that, you should just expect that the client of your library won't go and shoot themselves in the foot by meddling with the "private" attributes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to retrieve n characters from char array I have a char array in a C application that I have to split into parts of 250 so that I can send it along to another application that doesn't accept more at one time.
How would I do that? Platform: win32.
A: From the MSDN documentation:
The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.
Note that strncpy doesn't check for valid destination space; that is left to the programmer. Prototype:
char *strncpy(
char *strDest,
const char *strSource,
size_t count
);
Extended example:
void send250(char *inMsg, int msgLen)
{
char block[250];
while (msgLen > 0)
{
int len = (msgLen>250) ? 250 : msgLen;
strncpy(block, inMsg, 250);
// send block to other entity
msgLen -= len;
inMsg += len;
}
}
A: I can think of something along the lines of the following:
char *somehugearray;
char chunk[251] ={0};
int k;
int l;
for(l=0;;){
for(k=0; k<250 && somehugearray[l]!=0; k++){
chunk[k] = somehugearray[l];
l++;
}
chunk[k] = '\0';
dohandoff(chunk);
}
A: If you strive for performance and you're allowed to touch the string a bit (i.e. the buffer is not const, no thread safety issues etc.), you could momentarily null-terminate the string at intervals of 250 characters and send it in chunks, directly from the original string:
char *str_end = str + strlen(str);
char *chunk_start = str;
while (true) {
char *chunk_end = chunk_start + 250;
if (chunk_end >= str_end) {
transmit(chunk_start);
break;
}
char hijacked = *chunk_end;
*chunk_end = '\0';
transmit(chunk_start);
*chunk_end = hijacked;
chunk_start = chunk_end;
}
A: jvasaks's answer is basically correct, except that he hasn't null terminated 'block'. The code should be this:
void send250(char *inMsg, int msgLen)
{
char block[250];
while (msgLen > 0)
{
int len = (msgLen>249) ? 249 : msgLen;
strncpy(block, inMsg, 249);
block[249] = 0;
// send block to other entity
msgLen -= len;
inMsg += len;
}
}
So, now the block is 250 characters including the terminating null. strncpy will null terminate the last block if there are less than 249 characters remaining.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Django and Python 2.6 I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup?
All the google searches I did were inconclusive, I saw bits about some initial test runs on beta 2 but nothing more recent seemed to show up.
Edit: http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04
They've confirmed here 1.0 w/2.6 works fine as far as they know.
A: The impression I get is that 2.6 should work fine with Django 1.0. As found here: http://simonwillison.net/2008/Oct/2/whatus/
A: Note that there is currently no python-mysql adapter for python2.6. If you need MySQL, stick with 2.5 for now.
A: There is an unofficial build for mysqldb 1.2.2 win32 python 2.6 @ http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do you log the machine name via log4net? I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.
I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.
But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.
Is there a way to log the machine name via log4net in this manner?
A: You can use the pre-populated property log4net:HostName, for example:
<conversionPattern value="%property{log4net:HostName}" />
This way you don't need to populate the MDC.
A: you can create a parameter similar to the following:
<parameter>
<parameterName value="@machine" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%X{machine}" />
</layout>
</parameter>
Then add this line before writing to the log: MDC.Set("machine", Environment.MachineName);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Using PostMessage in Windows Mobile to simulate a menu pick I'm writing a routine to provide user definable keyboard short-cuts for any menu item in my Windows Mobile 5 application, which is in C++/MFC. To do this I am getting all of the available menu command IDs, and using the CWnd::PostMessage(WM_COMMAND,MyMenuID) to post it to the application. I use this technique to good effect elsewhere for inter-thread comms, but not with menu command IDs. Any ideas why this doesn't work. The app is document view, and I have tried posting to the CMainFrame and CView derived windows. I could write a god awful switch statement but I feel posting a message should work.
Edit: Ok, i've tried a number of things, including suggestions from this post, to no avail. Big ugly switch statement it is for now, I'll update again if i find anything better.
A: The only reason I can think of is the message is going to the wrong window. Don't forget that not all menu commands are always processed by a particular window. Some menu commands like Cut are usually processed by a view window. Others are processed by frame windows and some possibly by the application object.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Packaging up the .net framework with a .net application deployment Can you package up the .Net framework in an installer created in Visual Studio? If so how?
I've seen this done with Install4J packaging a JVM but I think that was the JVM to run Install4J.
A: I just learned this lesson about deployment projects: the .MSI file delivers the application to the target machine, but that SETUP.EXE is the bootstrapper that installs prerequisites, such as the .NET Framework, MDAC, or Windows Installer. I specified the .NET Framework as a prerequisite but, because I only distributed the .MSI, no checks were run and the app crashed when starting up without the framework.
To ensure your prerequisites are on the target machine, you need to distribute the setup.exe too.
A: Sucky, yeah - I created an installer just recently before realizing that the .Net Framework (which was one of the things I needed to install) was required. I ended up making a c++ program that installed .Net before my installer was launched.
Seems kind of odd to me to offer the ability to create an installer and not have it offer to install what it needs to run. Kinda pointless at that point, eh? Unless you know that every machine you give the installer to will have the necessary components...
Oh well, live and learn
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I fix the error unable to enlist Sybase database in distributed transaction? I know very little (arguably nothing) about Sybase setup, but I do know SSIS is having trouble enlisting Sybase in a distributed transaction. Has anyone been able to make this work?
The SSIS Runtime has failed to enlist the OLE DB connection in a
distributed transaction with error 0x80004005 "Unspecified error".
This happens when I change the package's TransactionOption to Required. When I revert to the default "Supported", the package runs without errors (albeit not thread safe).
A: I had this same problem when I tried to create a transaction around a read from a Gupta SQLBase. Basically, it seems that SSIS (at least as of 2005) isn't able to enroll any other providers in a transaction as part of a package. I've tried a few times without luck, and usually I just end up reading the data from my OLEDB into a temporary table, and then creating a transaction around the import of that data into its resting place in SQL Server. That's the read side, though - if you're trying to use a transaction to write to SYBASE, you'll need to do something on that side - SSIS won't be able to use a transaction to push data to another provider.
I addition to that, I didn't even want my transaction to extend to Gupta - I only wanted to enroll my INSERT/UPDATE on the SQL Server side in a transaction, to block users from reading half-updated data, but SSIS refused to allow me to wrap the process in a transaction because Gupta didn't support it. There seems to be no support for transactions just on certain providers, or only on the "Write" side of the process but not on the "Read" side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a way to compact a SQL2000/2005 MDF file? I deleted millions of rows of old data from a production SQL database recently, and it didn't seem to shrink the size of the .MDF file much. We have a finite amount of disk space.
I am wondering if there is anything else I can do to "tighten" the file (like something analogous to Access' Compact and Repair function)?
A: Use the Shrink File option in Sql Server Management Studio
Right-click on Database > Tasks > Shrink > Database (or Files)
A: DBCC SHRINKDATABASE etc. - read up on transaction logs and backups in the Books Online
A: If large log files are the problem, this may help:
backup log MY_DATABASE WITH TRUNCATE_ONLY;
Then right click on MY_DATABASE and choose All Tasks->Shrink Database as teller suggested.
A: This worked for me and shrank my log files by a thousand.
*
*Using the SQL Server Manager.
*Right Click on the database in question.
*Choose Properties, then the options tab.
*Change the Recovery Model to Simple From Full.
If you need it in full mode switch it back after it shrinks.
That's it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: NHibernate Query problem I'm quite new to NHibernate and starting to find my way around.
I have a domain model that is somewhat like a tree.
Funds have Periods have Selections have Audits
Now I would like to get all Audits for a specific Fund
Would look like this if I made it in SQL
SELECT A.*
FROM Audit A
JOIN Selection S ON A.fkSelectionID = S.pkID
JOIN Period P ON S.fkPeriodID = P.pkID
JOIN Fund F ON P.fkFundID = F.pkID
WHERE F.pkID = 1
All input appreciated!
A: Try this
select elements(s.Audits)
from Fund as f inner join Period as p inner join Selection as s
where f = myFundInstance
A: session.CreateCriteria ( typeof(Audit) )
.CreateCriteria("Selection")
.CreateCriteria("Period")
.CreateCriteria("Fund")
.Add(Restrinction.IdEq(fundId))
A: using LINQ ....
(from var p in Fund.Periods
let fundPeriodSelections = p.Selections
from var selection in fundPeriodSelections
select selection.Audit).ToList()
... but it does depend on those many-to-many / one-to-many relations being 2-way. Also, I was thinking you may need a mapping table / class in bewteen the Period / Fund table.. but I guess you've already considered it.
Hope the LINQ statemanet above works ... it depends on those mentioend properties, but it's an apraoch we've used on our project that's really cleaned up the code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I include a file over 2 directories back? How do you include a file that is more than 2 directories back. I know you can use ../index.php to include a file that is 2 directories back, but how do you do it for 3 directories back?
Does this make sense?
I tried .../index.php but it isn't working.
I have a file in /game/forum/files/index.php and it uses PHP include to include a file. Which is located in /includes/boot.inc.php; / being the root directory.
A: following are ways to access your different directories:-
./ = Your current directory
../ = One directory lower
../../ = Two directories lower
../../../ = Three directories lower
A: if you are using php7 you can use dirname function with level parameter of 2, for example :
dirname("/usr/local/lib", 2);
the second parameter "2" indicate how many level up
dirname referance
A: I recomend to use __DIR__ to specify current php file directory. Check here for the reason.
__DIR__ . /../../index.php
A: You can do ../../directory/file.txt - This goes two directories back.
../../../ - this goes three. etc
A: ../../../index.php
A: But be VERY careful about letting a user select the file. You don't really want to allow them to get a file called, for example,
../../../../../../../../../../etc/passwd
or other sensitive system files.
(Sorry, it's been a while since I was a linux sysadmin, and I think this is a sensitive file, from what I remember)
A: To include a file one directory back, use '../file'.
For two directories back, use '../../file'.
And so on.
Although, realistically you shouldn't be performing includes relative to the current directory. What if you wanted to move that file? All of the links would break. A way to ensure that you can still link to other files, while retaining those links if you move your file, is:
require_once($_SERVER['DOCUMENT_ROOT'] . 'directory/directory/file');
DOCUMENT_ROOT is a server variable that represents the base directory that your code is located within.
A: ../../../includes/boot.inc.php
A: . = current directory
.. = parent directory
So ../ gets you one directory back not two.
Chain ../ as many times as necessary to go up 2 or more levels.
A: including over directories can be processed by proxy file
*
*root
*.....|__web
*.....|.........|_requiredDbSettings.php
*.....|
*.....|___db
*.....|.........|_dbsettings.php
*.....|
*.....|_proxy.php
dbsettings.php:
$host='localhost';
$user='username':
$pass='pass';
proxy.php:
include_once 'db/dbsettings.php
requiredDbSettings.php:
include_once './../proxy.php';
A: include dirname(__FILE__).'/../../index.php';
is your best bet here, and it will avoid most of the relative path bugs you can encounter with other solutions.
Indeed, it will force the include to always be relative to the position of the current script where this code is placed (which location is most likely stable, since you define the architecture of your application). This is different from just doing include '../../index.php' which will include relatively to the executing (also named "calling") script and then relatively to the current working directory, which will point to the parent script that includes your script, instead of resolving from your included script's path.
From the PHP documentation:
Files are included based on the file path given or, if none is given,
the include_path specified. If the file isn't found in the
include_path, include will finally check in the calling script's own
directory and the current working directory before failing.
And the oldest post I've found citing this trick dates back to 2003, by Tapken.
You can test with the following setup:
Create a layout like this:
htdocs
¦ parent.php
¦ goal.php
¦
+---sub
¦ included.php
¦ goal.php
In parent.php, put:
<?php
include dirname(__FILE__).'/sub/included.php';
?>
In sub/included.php, put:
<?php
print("WRONG : " . realpath('goal.php'));
print("GOOD : " . realpath(dirname(__FILE__).'/goal.php'));
?>
Result when accessing parent.php:
WRONG : X:\htdocs\goal.php
GOOD : X:\htdocs\sub\goal.php
As we can see, in the first case, the path is resolved from the calling script parent.php, while by using the dirname(__FILE__).'/path' trick, the include is done from the script included.php where the code is placed in.
Beware, the following NOT equivalent to the trick above contrary to what can be read elsewhere:
include '/../../index.php';
Indeed, prepending / will work, but it will resolve just like include ../../index.php from the calling script (the difference is that include_path won't be looked afterwards if it fails). From PHP doc:
If a path is defined — whether absolute (starting with a drive letter
or \ on Windows, or / on Unix/Linux systems) or relative to the
current directory (starting with . or ..) — the include_path will be
ignored altogether.
A: if you include the / at the start of the include, the include will be taken as the path from the root of the site.
if your site is http://www.example.com/game/forum/files/index.php you can add an include to /includes/boot.inc.php which would resolve to http://www.example.com/includes/boot.inc.php .
You have to be careful with .. traversal as some web servers have it disabled; it also causes problems when you want to move your site to a new machine/host and the structure is a little different.
A: I saw your answers and I used include path with syntax
require_once '../file.php'; // server internal error 500
and http server (Apache 2.4.3) returned internal error 500.
When I changed the path to
require_once '/../file.php'; // OK
everything is fine.
A: Try ../../. You can modify it accordingly as it will take you up back two directories. First reach to root directory then access the required directory.
E.g. You are in root/inc/usr/ap and there is another directory root/2nd/path. You can access the path directory from ap like this:
../../2nd/path first go to root than desired directory. If not working please share.
A: .. selects the parent directory from the current. Of course, this can be chained:
../../index.php
This would be two directories up.
A: ../../index.php
A: ../ is one directory, Repeat for two directories ../../ or even three: ../../../ and so on.
Defining constants may reduce confusion because you will drill forward into directories verses backwards
You could define some constants like so:
define('BD', '/home/user/public_html/example/');
define('HTMLBD', 'http://example.com/');
When using 'BD' or my 'base directory' it looks like so:
file(BD.'location/of/file.php');
define(); reference
A: ../../../includes/boot.inc.php
Each instance of ../ means up/back one directory.
A: Try This
this example is one directory back
require_once('../images/yourimg.png');
this example is two directory back
require_once('../../images/yourimg.png');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "124"
} |
Q: Why do Jars get Excluded from Enunciate's Deployment? I'm using Enunciate to build a prototype REST api and need to include a jar containing custom code as a library.
My Ant Script looks like this:
<!--include all jars-->
<path id="en.classpath">
<fileset dir="${lib}">
<include name="**/*.jar" />
</fileset>
</path>
<!--define the task-->
<taskdef name="enunciate" classname="org.codehaus.enunciate.main.EnunciateTask">
<classpath refid="en.classpath" />
</taskdef>
<mkdir dir="${dist}" />
<enunciate dir="${src}" configFile="${basedir}/enunciate.xml">
<include name="**/*.java" />
<classpath refid="en.classpath"/>
<export artifactId="spring.war.file" destination="${dist}/${war.name}" />
</enunciate>
The problem is that my custom jar is being excluded from the WAR file. It is necessary to compile the enunciate annotated classes so the jar is obviously on the classpath at compile time but enunciate is failing to include it in the distribution. I have also noticed that several of the jars needed by enunciate are not being included in the WAR file.
Why are they being excluded and how do I fix it?
A: I never used enunciate, but as a quick hack you can add the jars to the war:
<jar jarfile="${dist}/${war.name}" update="true">
<fileset dir="${lib}">
<include name="**/*.jar" />
</fileset>
</jar>
Note: you probably want to add the jars to the WEB-INF/lib directory, instead of the root directory.
I'm guessing that enunciate does the mininum to interfere with your own build process, since you know best what to put within your jar file.
A: As it turns out one of the jars we're attempting to include has a dependency listed in it's Manifest file of a jar that Enunciate depends on (freemarker). Enunciate automatically excludes freemarker and at first glance it seems as though it automatically excludes anything that depends on freemarker as well. If we remove freemarker from the list of dependent jars in our code's manifest file it works just fine.
However; I've spoken with the main developer of Enunciate (Ryan Heaten) and he assures me this isn't what's happening. Including his response below:
Really?!
Wow. Interesting. I can't explain
it; Enunciate doesn't look at what's
in the Manifest in order to determine
what to include in the war, so I'm
kind of stumped here. It could also
be some weird Ant behavior (not
including that jar in the
"en.classpath" reference for some
reason).
~Ryan
A: In enunciate.xml I tell it not to copy any libs itself:
<webapp doLibCopy="false">
Then in the ant build file at the end of the enunciate task I update the war (you can do this to update the included/excluded jars whether or not you have Enunciate copy the jars for you in the step above):
<war destfile="build-output/{mywar}" update="true">
<lib dir="WebContent/WEB-INF/lib">
<include name="**/*.jar" />
</lib>
<lib dir="build-output">
<include name="some_other.jar" />
</lib>
</war>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Same property, different types Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri? How would you build it?
I'd like to be able to do something like one of the following, but neither are supported (using VB, since it lets you specify type in the Set declaration for the 2nd one):
Class MyClass
Private _link As Uri
'Option 1: overloaded property
Public Property Link1 As Uri
Get
return _link
End Get
Set(ByVal value As Uri)
_link = value
End Set
End Property
Public Property link1 As String
Get
return _link.ToString()
End Get
Set(Byval value As String)
_link = new Uri(value)
End Set
End Property
' Option 2: Overloaded setter
Public Property link2 As Uri
Get
return _link
End Get
Set(Byval value As Uri)
_link = value
End Set
Set(Byval value As String)
_link = new Uri(value)
End Set
End Class
Given that those probably won't be supported any time soon, how else would you handle this? I'm looking for something a little nicer than just providing an additional .SetLink(string value) method, and I'm still on .Net2.0 (though if later versions have a nice feature for this, I'd like to hear about it).
I can think of other scenarios where you might want to provide this kind of overload: a class with an SqlConnection member that lets you set either a new connection or a new connection string, for example.
A: I think you just need to provide an accompanying
Public Sub SetLink(ByVal value as String)
_link = new Uri(value)
End Sub
Nothing nicer is available, AFAIK.
A: Alternatively, you can of course forego overloading and just name the properties appropriately:
Public WriteOnly Property UriString() As String
Set(ByVal value As String)
m_Uri = new Uri(value)
End Set
End Property
Of course you don't have to make this WriteOnly but it seems appropriate.
A:
Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri?
No because this would mean having two getters that vary only in their return type and this isn't allowed in .NET.
I would use the Uri method exclusively and perhaps create a convenienec method to set the URI property, given a string. However, since the conversion from String to URI is straightforward, even this might be unnecessary.
A: You can't have one property like that, but you could create two properties which both manipulated the same underlying field - just like Height/Width/Size in Windows Forms.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Tracking Changes to a Directory Tree over Time Does anyone know of an application or system out there for tracking changes (files added/removed, diffs on text files) to a non-source controlled directory over time? Something that would let you
*
*Take a snapshot of a certain directory tree at time A
*Come back at time period B and see what has changed
*Come back at time period C and see what's changed since time period A, and what's changed since time period B
A source control repository isn't an option here. I want something that works on a directory structure that isn't under any kind of revision control. My group isn't in control of the servers or directory trees in question, but changes to those trees impact us and we'd like to keep track of them. The objects to "source control" are
*
*Objections to any kind of centralized repository that requires document authors to check-in, check-out.
*Objections to having to hand-roll/automate a bunch of tasks that can leverage a version control system's feature set
I want a semi-mature package where people have spent some time thinking about the problem. If there's a version control system that's been built to handle this kind of thing, it applies.
A: Write a scripted scheduled task which copies the directory tree to another place, perhaps on a different machine, which is part of a version controlled repostiory. Then, the scheduled task would automatically commit changes, using the version control system of your choice (Mercurial should work nicely for this system, since hg commit -A -m "automated snapshot" will quickly do what you need without any interactive prompts).
I'd suggest rsync for the copy, which is available for many platforms, and is fast and efficient since it won't copy files which haven't changed. Configure the copy to delete files from your copy which have been deleted on the main directory.
A: Your options are really:
*
*Full source control
*Source control 'lite' in the form of something like FileHamster
*Differential backup/restore facility
*Full backup/restore and a diff tool
*(I think) A journaling file system.
With just a standard directory there isn't really a way to do this without keeping a copy elsewhere, which essentially means it's a source control repo though.
A: I'd like something that looks, tastes and smells just like milk. But it shouldn't be milk.
In other words: you're describing a vcs. If you tell us why a vcs can't be used, it might be easier to answer.
Only thing I can think of is Apple's Time Machine, which (again) is basically vcs for the masses.
A: Automate committing it to revision control at set intervals. If you don't want any extra files/directories in the directory but the repository you pick requires them in the working copy then make part of the process copying the content of the directory to a separate working copy.
A: You either need a source code management system or a document management system.
Why is source code management not an option? SVN is easy to use for non-programmers with the Tortise SVN windows integration.'
Sounds like you don't have many options for the server....
How about this?
1. Setup a SVN repository on your computer
2. Nightly copy from the Directory to your computer and commit changes.
Or...
Use windows "Search" command for files changed in the last n days. Run the report manually each week. Or write an automation for that report.
A: What you're describing is a version control system?! So I'm not sure I understand why you wouldn't want to install one. You could very easy implement a local version of SVN/CVS and interface in it through your applications (e.g. add new files, remove old ones). This could be done on a periodic basis using a scheduled task or something.
I haven't heard of anything else that's "simple" which you could use. I guess because it's already been done ;) So why recreate the wheel...
I guess you could look at an open source backup software package. They must have some logic in there to track file changes used for incremental backups. They probably don't track file changes though..
A: This is a solution:
use a subversion local repository and use a scheduled task which will commit your files at a regular base(once an hour?)
a simple example:
your directory you want to track:
c:\tracking_dir
the directory you store the data of differences and other historical infos:
c:\repository
*
*svnadmin create c:\repository
*svn co file:///c:/repository c:\tracking_dir\
*setup an scheduled task which should run this commands:
svn add c:\tracking_dir*.*
svn ci c:\tracking_dir*.* -m"automatic commit through scheduled task"
In this way you have a running example and can access the history via any subversion frontend
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Emacs on Mac OS X Leopard key bindings I'm a Mac user and I've decided to learn Emacs. I've read that to reduce hand strain and improve accuracy the CTRL and CAPS LOCK keys should be swapped. How do I do this in Leopard?
Also, in Terminal I have to use the ESC key to invoke meta. Is there any way to get the alt/option key to invoke meta instead?
update: While the control key is much easier to hit now, the meta key is also used often enough that its position on my MacBook and Apple Keyboard also deserves attention. In fact, I find that the control key is actually easier to hit, so I've remapped my control key to act as a meta key. Does anyone have a better/more standard solution?
A: If you use emacs over an ssh connection, or through a machine not on your local computer, the page up/page down buttons scroll through the terminal buffer - in my experience, not too helpful.
You can set your page down and page up buttons to send the appropriate commands to emacs. In emacs, you can scroll through the emacs buffer like so:
*
*Page Up: Ctl-v
*Page Down: Esc-v
So, to have the terminal send these commands to emacs, follow the instructions above to alter the Alt keys for Meta. However, instead of setting the "use option as meta" option, find the "page down" and "page up" options.
Page Down
Double click the "page down" option to edit it. Change Action to "send string to shell" and enter \026 as the string. Save it.
Page Up
Double click the "page up" button to edit it. Change Action to "send string to shell" and enter \033v as the string. Save it.
A: Not sure if you're totally married to using Emacs from the terminal, but another option is to use Carbon Emacs (my favorite) and Aquamacs (very Mac-like). Carbon Emacs uses the command key for meta, this is nice because you can do Control-Meta commands just by holding Control and Command down instead of first hitting escape then the control key sequence.
Also, if you're a serious Emacs user I thoroughly recommend that you get a keyboard suited for programming (that is one that is completely reprogrammable by itself). I use a Kinesis, it's a little bit of money but they are extremely durable and quite nice.
A: For reference, here are the key bindings, for moving around text:
⌥ + ← - move left one word
⌥ + → - move right one word
⌥ + delete - back delete one word
Shift + ⌥ + delete - foward delete one word
⌥ + ↑ - move up one paragraph
⌥ + ↓ - move down one paragraph
⌘ + ← - move to start of current line
⌘ + → - move to end of current line
Shift + any of the above extend selection by appropriate amount
Click then drag - select text
Double-click then drag - select text, wrapping to word ends
Triple-click then drag - select text, wrapping to paragraph ends
Shift + Select text with mouse - add to selection (contiguous)
⌘ + Select text with mouse - add to selection (non-contiguous)
⌥ + Drag - select rectangular area (non-contiguous)
⌘ + ⌥ + drag - add rectangular area to selection
Drag selection - move text
⌥ + drag selection - copy text
Ctrl + A - move to start of current paragraph
Ctrl + B - move left one character
Ctrl + D - forwards delete
Ctrl + E - move to end of current paragraph
Ctrl + F - move right one character
Ctrl + H - delete
Ctrl + K - delete remainder of current paragraph
Ctrl + L - center the window on the current line
Ctrl + N - move down one line
Ctrl + O - insert new line after cursor
Ctrl + P - move up one line
Ctrl + T - transpose (swap) two surrounding character
Ctrl + V - move to end, then left one character
Ctrl + Y - paste text previously deleted with Ctrl - K
Add Option to Ctrl + F or Ctrl + B to move a word instead of a character at a time.
A: Personally i have setup caps lock to behave like command on the system preferences and then on my emacs init.el file have:
(setq mac-command-modifier 'ctrl)
and this lets me use caps lock as command in most osx applications and as control in emacs. works well enough for me.
A: Your joy is just beginning. Other tricks include:
*
*Use the left and right shift keys to also be ( and ) for fast typing.
*Remap your fn key or another key to be "super".
*Make caps lock be control, but only with another key. By itself, it is escape.
Read the excellent article at http://stevelosh.com/blog/2012/10/a-modern-space-cadet/ for a lot more information.
A: This thread was started 5 years ago and there is no mention of ns-win.el or build --with-ns. Here are all the key bindings available (out of the box) in Emacs Trunk as of October 2013. And, of course, you can create your own. Personally, I have one init.el with all my key bindings that can be used with Windows XP through Parallels on OSX, and also with OSX natively. Since the user can define his / her own keyboard shortcuts, I do not see a need to remap the keyboard in system preferences (with an Apple U.S. keyboard) unless using a keyboard that does not include the Command key. But, would I throw away my stash of IBM clicky keyboards with trackpoint built in? Of course not. :) I'm taking my IBM clicky keyboards with me into the next life. Any hand strain is most likely caused by improper wrist / arm / elbow position, not by hitting control versus caps lock. Accuracy is improved through practice, and with the help of a boss looking over your shoulder to see how you are coming along -- i.e., a little pressure to be more productive :)
(define-key global-map [?\s-,] 'customize)
(define-key global-map [?\s-'] 'next-multiframe-window)
(define-key global-map [?\s-`] 'other-frame)
(define-key global-map [?\s-~] 'ns-prev-frame)
(define-key global-map [?\s--] 'center-line)
(define-key global-map [?\s-:] 'ispell)
(define-key global-map [?\s-?] 'info)
(define-key global-map [?\s-^] 'kill-some-buffers)
(define-key global-map [?\s-&] 'kill-this-buffer)
(define-key global-map [?\s-C] 'ns-popup-color-panel)
(define-key global-map [?\s-D] 'dired)
(define-key global-map [?\s-E] 'edit-abbrevs)
(define-key global-map [?\s-L] 'shell-command)
(define-key global-map [?\s-M] 'manual-entry)
(define-key global-map [?\s-S] 'ns-write-file-using-panel)
(define-key global-map [?\s-a] 'mark-whole-buffer)
(define-key global-map [?\s-c] 'ns-copy-including-secondary)
(define-key global-map [?\s-d] 'isearch-repeat-backward)
(define-key global-map [?\s-e] 'isearch-yank-kill)
(define-key global-map [?\s-f] 'isearch-forward)
(define-key global-map [?\s-g] 'isearch-repeat-forward)
(define-key global-map [?\s-h] 'ns-do-hide-emacs)
(define-key global-map [?\s-H] 'ns-do-hide-others)
(define-key global-map [?\s-j] 'exchange-point-and-mark)
(define-key global-map [?\s-k] 'kill-this-buffer)
(define-key global-map [?\s-l] 'goto-line)
(define-key global-map [?\s-m] 'iconify-frame)
(define-key global-map [?\s-n] 'make-frame)
(define-key global-map [?\s-o] 'ns-open-file-using-panel)
(define-key global-map [?\s-p] 'ns-print-buffer)
(define-key global-map [?\s-q] 'save-buffers-kill-emacs)
(define-key global-map [?\s-s] 'save-buffer)
(define-key global-map [?\s-t] 'ns-popup-font-panel)
(define-key global-map [?\s-u] 'revert-buffer)
(define-key global-map [?\s-v] 'yank)
(define-key global-map [?\s-w] 'delete-frame)
(define-key global-map [?\s-x] 'kill-region)
(define-key global-map [?\s-y] 'ns-paste-secondary)
(define-key global-map [?\s-z] 'undo)
(define-key global-map [?\s-|] 'shell-command-on-region)
(define-key global-map [s-kp-bar] 'shell-command-on-region)
;; (as in Terminal.app)
(define-key global-map [s-right] 'ns-next-frame)
(define-key global-map [s-left] 'ns-prev-frame)
(define-key global-map [home] 'beginning-of-buffer)
(define-key global-map [end] 'end-of-buffer)
(define-key global-map [kp-home] 'beginning-of-buffer)
(define-key global-map [kp-end] 'end-of-buffer)
(define-key global-map [kp-prior] 'scroll-down-command)
(define-key global-map [kp-next] 'scroll-up-command)
;; Allow shift-clicks to work similarly to under Nextstep.
(define-key global-map [S-mouse-1] 'mouse-save-then-kill)
(global-unset-key [S-down-mouse-1])
A: (not an ergonomic keyboard, but i really like the keys' travel and feel, and Control key , Caps Lock are swapped).
http://matias.ca/osxkeyboard/index.php
A: Swapping CTRL and CAPS LOCK
*
*Go into System Preferences
*Enter the Keyboard & Mouse preference pane
*In the Keyboard tab, click Modifier Keys...
*Swap the actions for Caps Lock and Control.
Using ALT/OPTION as META
*
*In the menu bar, click Terminal
*Click Preferences...
*Under the Settings tab, go to the Keyboard tab
*Check the box labeled Use option as meta key
That's it! You should be well on your way to becoming an Emacs master!
A: The other answer was very complete, but additionally I'd mention I just set the caps lock
key to a second control key instead of swapping them.
Also, you'll notice that the large majority of the text entry fields in Mac OS X
already accept emacs keystrokes (^A beginning of line, ^E end of line, ^P, ^N, ^K, ^Y, etc)
good luck
A: I really like the answer provided by Kyle Cronin, but I want to add one thing - make sure you select the appropriate keyboard for this to work. If you have an external keyboard plugged into your laptop, then there are is an additional drop down box and you will need to do this for both keyboards (or at least for your external keyboard). The screen shot below shows the "Select Keyboard" dialog box - I have selected "Joint Mac Keyboard", which is MacBook's way of saying GoldTouch external keyboard - the default is the built-in keyboard.
Once I figured that out - this works great for me!
A: I've created a fairly comprehensive set of bindings here for use outside of Terminal.
Personally, I can't use the mac laptop keyboard due to the absence of the right control key.
Instead, I have been using the Microsoft Natural Ergonomic Keyboard 4000 for over 7 years: it's got really fat, well-positioned Ctrl and Alt keys, and after downloading its drivers the "Start" and "Application" keys are trivially remapped to the Mac Cmd key, which is also fat and easily depressed.
To avoid emacs ergonomic concerns I've trained myself to use Ctrl, Alt, and Cmd the same way we use Shift - depressing them with the hand opposite the one typing the actual key. (That is, I just leave Caps Lock as is.)
A: I set caps lock to control in system preference and I have the following in my init.el to set command to meta and option to super:
(custom-set-variables
'(ns-alternate-modifier (quote super))
'(ns-command-modifier (quote meta)))
A: I would like to recommend 2 softwares
Seil and Karabiner. By simply installing Seil and following the instructions in the software, you should be able to achieve what you want. From my experience, Karabiner is more powerful. I have a Japanese keyboard whose layout is different from the normal ones. I have some snippet which remaps two extra keys on my keyboard to F18 and F19 for other use. You can use the same syntax to edit your "private.xml" file to do more things.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "106"
} |
Q: Marshal "char *" in C# Given the following C function in a DLL:
char * GetDir(char* path );
How would you P/Invoke this function into C# and marshal the char * properly.
.NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.
A: OregonGhost's answer is only correct if the char* returned from GetDir is either allocated in HGlobal or LocalAlloc. I can't remember which one but the CLR will assume that any string return type from a PInvoke function was allocated with one or the other.
A more robust way is to type the return of GetDir to be IntPtr. Then you can use any of the Marshal.PtrToStringAnsi functions in order to get out a string type. It also gives you th flexibility of freeing the string in the manner of your choosing.
[DllImport("your.dll", CharSet = CharSet.Ansi)]
IntPtr GetDir(StringBuilder path);
Can you give us any other hints as to the behavior of GetDir? Does it modify the input string? How is the value which is returned allocated? If you can provide that I can give a much better answer.
A: Try
[DllImport("your.dll", CharSet = CharSet.Ansi)]
string GetDir(StringBuilder path);
string is automatically marshalled to a zero-terminated string, and with the CharSet property, you tell the Marshaller that it should use ANSI rather than Unicode.
Note: Use string (or System.String) for a const char*, but StringBuilder for a char*.
You can also try MarshalAs, as in this example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: How do I call Java code from JavaScript code in Wicket? If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket.
A: Excerpt from https://cwiki.apache.org/WICKET/calling-wicket-from-javascript.html
If you add any class that extends AbstractDefaultAjaxBehavior to your page, wicket-ajax.js will be added to the header ofyour web page. wicket-ajax.js provides you with two basic methods to call your component:
function wicketAjaxGet(url, successHandler, failureHandler, precondition, channel)
and
function wicketAjaxPost(url, body, successHandler, failureHandler, precondition, channel)
Here is an example:
JavaScript
function callWicket() {
var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { });
}
$url$ is obtained from the method abstractDefaultAjaxBehavior.getCallbackUrl(). If you paste the String returned from that method into your browser, you'll invoke the respond method, the same applies for the javascript method.
You can optionally add arguments by appending these to the URL string. They take the form &foo=bar.
you get the optional arguments in the Java response method like this:
Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();
or this:
String paramFoo = RequestCycle.get().getRequest().getParameter("foo");
A: http://www.wicket-library.com/wicket-examples-6.0.x/index.html/ has plenty of examples to get you going.
Or have a Have a look at DWR
http://directwebremoting.org/
DWR allows Javascript in a browser to interact with Java on a server and helps you manipulate web pages with the results.
As Dorward mentioned this is done via AJAX
A: erk. The correct answer would be ajax call backs. You can either manually code the js to hook into the wicket js, or you can setup the callbacks from wicket components in java.
For example, from AjaxLazyLoadPanel:
component.add( new AbstractDefaultAjaxBehavior() {
@Override
protected void respond(AjaxRequestTarget target) {
// your code here
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead( response );
response.renderOnDomReadyJavascript( getCallbackScript().toString() );
}
}
This example shows how to add call back code to any Component in Wicket. After the OnDomReady event fires in your browser, when loading a page, Wicket will cause it's js enging, to call back into your code, using Ajax, to the 'respond' method shown above, at which point you can execute Java code on the server, and potentially add components to the ajax target to be re-rendered.
To do it manually, from js, you can hook into wicket's system by printing out getCallbackScript().toString() to a attribute on a wicket component, which you'll then be able to access from js. Calling this url from js manually with wicket's wicketAjaxGet from wicket-ajax.js.
Check out the mailing list for lot's of conversation on this topic:
http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438
A: Assuming you mean JavaScript running on the client - you cause an HTTP redirect to be made to the server, and have your servlet react to the request for the given URL.
This is known as Ajax, and there are a number of libraries that help you do it..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: SQL Server 2005 encryption trigger I have a script that successfully encrypts a credit card. I need it to work as a trigger, so that any insert done to the creditcard column automatically encrypts it. Right now, my trigger works BUT the creditcard column is a varchar. When an app tries to insert, I do this:
DECLARE @encryptedCreditCardNumber varbinary(max)
SET @encryptedCreditCardNumber = EncryptByKey(Key_GUID('testKey'), @CreditCardNumber));
That works fine, but how do I then convert the varbinary(max) to a varchar (which is what the credit card column is). The creditcard column has been a varchar for a long time at my company and a lot of legacy code depends on it being a varchar.
Thank you
A: Your simplest approach is going to be to convert the binary to base64 and store that in the varchar column. Base64 is a method for rendering binary data using ascii encoding so that it could be represented in formats such as XML. You can perform the conversion by doing:
select cast(N'' as xml).value('xs:base64Binary(xs:hexBinary(sql:variable("@encryptedCreditCardNumber")))', 'varchar(max)');
This goes through an XML intermediary to correctly encode the varbinary to a varchar. To reverse the process on the DB use:
select cast(N'' as xml).value('xs:base64Binary(sql:variable("@base64stringvariable"))', 'varbinary(20)');
Edit: Useful reference - http://blogs.msdn.com/sqltips/archive/2008/06/30/converting-from-base64-to-varbinary-and-vice-versa.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I report an error midway through a chunked http repsonse without closing the connection? I have an HTTP server that returns large bodies in response to POST requests (it is a SOAP server). These bodies are "streamed" via chunking. If I encounter an error midway through streaming the response how can I report that error to the client and still keep the connection open? The implementation uses a proprietary HTTP/SOAP stack so I am interested in answers at the HTTP protocol level.
A: Once the server has sent the status line (the very first line of the response) to the client, you can't change the status code of the response anymore. Many servers delay sending the response by buffering it internally until the buffer is full. While the buffer is filling up, you can still change your mind about the response.
If your client has access to the response headers, you could use the fact that chunked encoding allows the server to add a trailer with headers after the chunked-encoded body. So, your server, having encountered the error, could gracefully stop sending the body, and then send a trailer that sets some header to some value. Your client would then interpret the presence of this header as a sign that an error happened.
A: Also keep in mind that chunked responses can contain "footers" which are just like HTTP headers. After failing, you can send a footer such as:
X-RealStatus: 500 Some bad stuff happened
Or if you succeed:
X-RealStatus: 200 OK
A: you can change the status code as long as response.iscommitted() returns false.
(fot HttpServletResponse in java, im sure there exists an equivalent in other languages)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Spawning multiple SQL tasks in SQL Server 2005 I have a number of stored procs which I would like to all run simultaneously on the server. Ideally all on the server without reliance on connections to an external client.
What options are there to launch all these and have them run simultaneously (I don't even need to wait until all the processes are done to do additional work)?
I have thought of:
*
*Launching multiple connections from
a client, having each start the
appropriate SP.
*Setting up jobs for
each SP and starting the jobs from a
SQL Server connection or SP.
*Using
xp_cmdshell to start additional runs
equivalent to osql or whetever
*SSIS - I need to see if the package can be dynamically written to handle more SPs, because I'm not sure how much access my clients are going to get to production
In the job and cmdshell cases, I'm probably going to run into permissions level problems from the DBA...
SSIS could be a good option - if I can table-drive the SP list.
This is a datawarehouse situation, and the work is largely independent and NOLOCK is universally used on the stars. The system is an 8-way 32GB machine, so I'm going to load it down and scale it back if I see problems.
I basically have three layers, Layer 1 has a small number of processes and depends on basically all the facts/dimensions already being loaded (effective, the stars are a Layer 0 - and yes, unfortunately they will all need to be loaded), Layer 2 has a number of processes which depend on some or all of Layer 1, and Layer 3 has a number of processes which depend on some or all of Layer 2. I have the dependencies in a table already, and would only initially launch all the procs in a particular layer at the same time, since they are orthogonal within a layer.
A: Is SSIS an option for you? You can create a simple package with parallel Execute SQL tasks to execute the stored procs simultaneously. However, depending on what your stored procs do, you may or may not get benefit from starting this in parallel (e.g. if they all access the same table records, one may have to wait for locks to be released etc.)
A: At one point I did some architectural work on a product known as Acumen Advantage that has a warehouse manager that does this.
The basic strategy for this is to have a control DB with a list of the sprocs and their dependencies. Based on the dependencies you can do a Topological Sort to give them an order to run in. If you do this, you need to manage the dependencies - all of the predecessors of a stored procedure must complete before it executes. Just starting the sprocs in order on multiple threads will not accomplish this by itself.
Implementing this meant knocking much of the SSIS functionality on the head and implementing another scheduler. This is OK for a product but probably overkill for a bespoke system. A simpler solution is thus:
You can manage the dependencies at a more coarse-grained level by organising the ETL vertically by dimension (sometimes known as Subject Oriented ETL) where a single SSIS package and set of sprocs takes the data from extraction through to producing dimensions or fact tables. Typically the dimensions will mostly be siloed, so they will have minimal interdependency. Where there is interdependency, make one dimension (or fact table) load process dependent on whatever it needs upstream.
Each loader becomes relatively modular and you still get a useful degree of parallelism by kicking off the load processes in parallel and letting the SSIS scheduler work it out. The dependencies will contain some redundancy. For example an ODS table may not be dependent on a dimension load being completed but the upstream package itself takes the components right through to the dimensional schema before it completes. However this is not likely to be an issue in practice for the following reasons:
*
*The load process probably has plenty of other tasks that can execute in the meantime
*The most resource-hungry tasks will almost certainly be the fact table loads, which will mostly not be dependent on each other. Where there is a dependency (e.g. a rollup table based on the contents of another table) this cannot be avoided anyway.
You can construct the SSIS packages so they pick up all of their configuration from an XML file and the location can be supplied exernally in an environment variable. This sort of thing can be fairly easily implemented with scheduling systems like Control-M.
This means that a modified SSIS package can be deployed with relatively little manual intervention. The production staff can be handed the packages to deploy along with the stored procedures and can mainain the config files on a per-environment basis without having to manually fiddle configuration in the SSIS packages.
A: you might want to look at the service broker and it's activation stored procedures... might be an option...
A: In the end, I created a C# management console program which launches the processes Async as they are able to be run and keeps track of the connections.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Formatting a field using ToText in a Crystal Reports formula field I'm trying to create a Crystal Reports formula field (to calculate the percentage change in a price) that will return "N/A" if a particular report field is null, but return a number to two decimal places using accounting format (negative numbers surrounded by parentheses) if it is not.
The closest I have been able to manage is this:
If IsNull({ValuationReport.YestPrice}) Then
'N/A'
Else
ToText({@Price}/{ValuationReport.YestPrice}*100-100, '###.00', 2)
However this represents negative numbers using a negative sign, not parentheses.
I tried format strings like '###.00;(###.00)' and '(###.00)' but these were rejected as invalid. How can I achieve my goal?
A: I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
A: if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Readonly ComboBox in WinForms I'm writing a GUI in C#, Visual Studio 2008, using the Designer and WinForms. I've got a ComboBox control, and I'd like it to only allow to select from the provided options and not to accept a user-entered string. It doesn't appear to have a ReadOnly property, and disabling it hinders the readability of the control (as well as disallowing user-selection).
A: Set DropDownStyle to "DropDownList"
A: Use code similar to the following to set the allowed options and only those options.
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.Items.AddRange(new object[] {
"One",
"Two",
"Three",
"Four"});
A: Another simple way to go about it.
private void combobox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
A: Set the ComboBox.DropDownStyle property to ComboBoxStyle.DropDownList.
A: Try using a DropDownListbox
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Would it be possible to use web services from a Cobol program? We have some COBOL programs in our financial applications which need to interact with some of our backend systems. One of the available interfaces is through a web service. Can a program written in Cobol make requests to a web service?
A: Microfocus provide a tool called Enterprise Server which allows COBOL to interact with web services.
If you have a COBOL program A and another COBOL program B and A calls B via the interface section, the tool allows you to expose B's interface section as a web service.
For program A, you then generate a client proxy and A can now call B via a web service.
Of course, because B now has a web service any other type of program (command line, Windows application, Java, ASP etc.) can now also call it.
A: I've never used COBOL but from quick Google search it looks like it's possible.
This looks like it'll help, and talks about integrating webservices with cobol through c code.
A: What platform is this on? IBM's CICS supports webservices invokationnn from cobol program via EXEC CICS INVOKE.
A: ibm is now trying to implement a technology called embedded websphere with java.
ibm belives this is the only way to give the life to mainframes.
A: I know I can write a WebService with Delphi and call a COBOL DLL or
call a Delphi dll to comunicate with webservice.
Right now Im writing a webservice client, it will be a DLL, and Ill call from old COBOL systems.
A: If you have and are using CICS, it has built-in mechanisms for that. But assuming you can't use that for some reason, you can build an HTTP client using the IBM TCP/IP 'EZASOKET' modules.
I work for a company with a z/OS system running mostly COBOL, batch (JCL) and CICS. To call webservices, we wrote a module to implement HTTP 1.0 using TCP/IP. With modules
*
*EZASOKET
*
*GETHOSTBYNAME
*SOCKET
*CONNECT
*WRITE
*FCNTL
*READ
*CLOSE
*SELECTEX
supplementary modules:
*
*EZACIC04 translates EBCDIC to ASCII
*EZACIC05 translates ASCII to EBCDIC
*EZACIC06 convert character to bit mask
*EZACIC08 decode IP address
Since I wrote this for my company, I can't just give out the code. But for reference, it took me 3 days to write the module (plus a little debugging later), and that was with an example to start with that did a partial hacky way of doing it.
You will need to read through IBM's references to know how to use the EZA modules.
*
*http://publib.boulder.ibm.com/infocenter/zos/v1r11/index.jsp?topic=/com.ibm.zos.r11.halc001/sampcs.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why use pointers? I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.
Basically I have three questions:
*
*Why use pointers over normal variables?
*When and where should I use pointers?
*How do you use pointers with arrays?
A: Pointers are important in many data structures whose design requires the ability to link or chain one "node" to another efficiently. You would not "choose" a pointer over say a normal data type like float, they simply have different purposes.
Pointers are useful where you require high performance and/or compact memory footprint.
The address of the first element in your array can be assigned to a pointer. This then allows you to access the underlying allocated bytes directly. The whole point of an array is to avoid you needing to do this though.
A: One way to use pointers over variables is to eliminate duplicate memory required. For example, if you have some large complex object, you can use a pointer to point to that variable for each reference you make. With a variable, you need to duplicate the memory for each copy.
A: In C++, if you want to use subtype polymorphism, you have to use pointers. See this post: C++ Polymorphism without pointers.
Really, when you think about it, this makes sense. When you use subtype polymorphism, ultimately, you don't know ahead of time which class's or subclass's implementation of the method will be invoked because you don't know what the actual class is.
This idea of having a variable that holds an object of an unknown class is incompatible with C++'s default (non-pointer) mode of storing objects on the stack, where the amount of space allocated directly corresponds to the class. Note: if a class has 5 instance fields versus 3, more space will need to be allocated.
Note that if you are using '&' to pass arguments by reference, indirection (i.e., pointers) is still involved behind the scenes. The '&' is just syntactic sugar that (1) saves you the trouble of using pointer syntax and (2) allows the compiler to be more strict (such as prohibiting null pointers).
A: Because copying big objects all over the places wastes time and memory.
A: Here's my anwser, and I won't promse to be an expert, but I've found pointers to be great in one of my libraries I'm trying to write. In this library (It's a graphics API with OpenGL:-)) you can create a triangle with vertex objects passed into them. The draw method takes these triangle objects, and well.. draws them based on the vertex objects i created. Well, its ok.
But, what if i change a vertex coordinate? Move it or something with moveX() in the vertex class? Well, ok, now i have to update the triangle, adding more methods and performance is being wasted because i have to update the triangle every time a vertex moves. Still not a big deal, but it's not that great.
Now, what if i have a mesh with tons of vertices and tons of triangles, and the mesh is rotateing, and moveing, and such. I'll have to update every triangle that uses these vertices, and probably every triangle in the scene because i wouldn't know which ones use which vertices. That's hugely computer intensive, and if I have several meshes ontop of a landscape, oh god! I'm in trouble, because im updateing every triangle almost every frame because these vertices are changing al the time!
With pointers, you don't have to update the triangles.
If I had three *Vertex objects per triangle class, not only am i saving room because a zillion triangles don't have three vertex objects which are large themselves, but also these pointers will always point to the Vertices they are meant to, no matter how often the vertices change. Since the pointers still point to the same vertex, the triangles don't change, and the update process is easier to handle. If I confused you, I wouldn't doubt it, I don't pretend to be an expert, just throwing my two cents into the discussion.
A: The need for pointers in C language is described here
The basic idea is that many limitations in the language (like using arrays, strings and modifying multiple variables in functions) could be removed by manipulating with the memory location of the data. To overcome these limitations, pointers were introduced in C.
Further, it is also seen that using pointers, you can run your code faster and save memory in cases where you are passing big data types (like a structure with many fields) to a function. Making a copy of such data types before passing would take time and would consume memory. This is another reason why programmers prefer pointers for big data types.
PS: Please refer the link provided for detailed explanation with sample code.
A: One reason to use pointers is so that a variable or an object can be modified in a called function.
In C++ it is a better practice to use references than pointers. Though references are essentially pointers, C++ to some extent hides the fact and makes it seem as if you are passing by value. This makes it easy to change the way the calling function receives the value without having to modify the semantics of passing it.
Consider the following examples:
Using references:
public void doSomething()
{
int i = 10;
doSomethingElse(i); // passes i by references since doSomethingElse() receives it
// by reference, but the syntax makes it appear as if i is passed
// by value
}
public void doSomethingElse(int& i) // receives i as a reference
{
cout << i << endl;
}
Using pointers:
public void doSomething()
{
int i = 10;
doSomethingElse(&i);
}
public void doSomethingElse(int* i)
{
cout << *i << endl;
}
A: *
*Pointers allow you to refer to the same space in memory from multiple locations. This means that you can update memory in one location and the change can be seen from another location in your program. You will also save space by being able to share components in your data structures.
*You should use pointers any place where you need to obtain and pass around the address to a specific spot in memory. You can also use pointers to navigate arrays:
*An array is a block of contiguous memory that has been allocated with a specific type. The name of the array contains the value of the starting spot of the array. When you add 1, that takes you to the second spot. This allows you to write loops that increment a pointer that slides down the array without having an explicit counter for use in accessing the array.
Here is an example in C:
char hello[] = "hello";
char *p = hello;
while (*p)
{
*p += 1; // increase the character by one
p += 1; // move to the next spot
}
printf(hello);
prints
ifmmp
because it takes the value for each character and increments it by one.
A: Pointers are one way of getting an indirect reference to another variable. Instead of holding the value of a variable, they tell you its address. This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).
The best explanation of pointers and pointer arithmetic that I've read is in K & R's The C Programming Language. A good book for beginning learning C++ is C++ Primer.
A: In java and C# all the object references are pointers, the thing with c++ is that you have more control on where you pointer points. Remember With great power comes grand responsibility.
A: Let me try and answer this too.
Pointers are similar to references. In other words, they're not copies, but rather a way to refer to the original value.
Before anything else, one place where you will typically have to use pointers a lot is when you're dealing with embedded hardware. Maybe you need to toggle the state of a digital IO pin. Maybe you're processing an interrupt and need to store a value at a specific location. You get the picture. However, if you're not dealing with hardware directly and are just wondering about which types to use, read on.
Why use pointers as opposed to normal variables? The answer becomes clearer when you're dealing with complex types, like classes, structures and arrays. If you were to use a normal variable, you might end up making a copy (compilers are smart enough to prevent this in some situations and C++11 helps too, but we'll stay away from that discussion for now).
Now what happens if you want to modify the original value? You could use something like this:
MyType a; //let's ignore what MyType actually is right now.
a = modify(a);
That will work just fine and if you don't know exactly why you're using pointers, you shouldn't use them. Beware of the "they're probably faster" reason. Run your own tests and if they actually are faster, then use them.
However, let's say you're solving a problem where you need to allocate memory. When you allocate memory, you need to deallocate it. The memory allocation may or may not be successful. This is where pointers come in useful - they allow you to test for the existence of the object you've allocated and they allow you to access the object the memory was allocated for by de-referencing the pointer.
MyType *p = NULL; //empty pointer
if(p)
{
//we never reach here, because the pointer points to nothing
}
//now, let's allocate some memory
p = new MyType[50000];
if(p) //if the memory was allocated, this test will pass
{
//we can do something with our allocated array
for(size_t i=0; i!=50000; i++)
{
MyType &v = *(p+i); //get a reference to the ith object
//do something with it
//...
}
delete[] p; //we're done. de-allocate the memory
}
This is the key to why you would use pointers - references assume the element you're referencing exists already. A pointer does not.
The other reason why you would use pointers (or at least end up having to deal with them) is because they're a data type that existed before references. Therefore, if you end up using libraries to do the things that you know they're better at, you will find that a lot of these libraries use pointers all over the place, simply because of how long they've been around (a lot of them were written before C++).
If you didn't use any libraries, you could design your code in such a way that you could stay away from pointers, but given that pointers are one of the basic types of the language, the faster you get comfortable using them, the more portable your C++ skills would be.
From a maintainability point of view, I should also mention that when you do use pointers, you either have to test for their validity and handle the case when they're not valid, or, just assume they are valid and accept the fact that your program will crash or worse WHEN that assumption is broken. Put another way, your choice with pointers is to either introduce code complexity or more maintenance effort when something breaks and you're trying to track down a bug that belongs to a whole class of errors that pointers introduce, like memory corruption.
So if you control all of your code, stay away from pointers and instead use references, keeping them const when you can. This will force you to think about the life times of your objects and will end up keeping your code easier to understand.
Just remember this difference: A reference is essentially a valid pointer. A pointer is not always valid.
So am I saying that its impossible to create an invalid reference? No. Its totally possible, because C++ lets you do almost anything. It's just harder to do unintentionally and you will be amazed at how many bugs are unintentional :)
A: *
*Why use pointers over normal variables?
Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...
*
*When and where should I use pointers?
Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.
*
*How do you use pointers with arrays?
With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer.
These declarations are very similar (but not the same - e.g., sizeof will return different values):
char* a = "Hello";
char a[] = "Hello";
You can reach any element in the array like this
printf("Second char is: %c", a[1]);
Index 1 since the array starts with element 0. :-)
Or you could equally do this
printf("Second char is: %c", *(a+1));
The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:
printf("Second char is: %s", (a+1)); /* WRONG */
But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?
char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);
This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).
Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:
char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);
Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.
A: *
*In some cases, function pointers are required to use functions that are in a shared library (.DLL or .so). This includes performing stuff across languages, where oftentimes a DLL interface is provided.
*Making compilers
*Making scientific calculators, where you have an array or vector or string map of function pointers?
*Trying to modify video memory directly - making your own graphics package
*Making an API!
*Data structures - node link pointers for special trees you are making
There are Lots of reasons for pointers. Having C name mangling especially is important in DLLs if you want to maintain cross-language compatibility.
A: Regarding your second question, generally you don't need to use pointers while programming, however there is one exception to this and that is when you make a public API.
The problem with C++ constructs that people generally use to replace pointers are very dependent on the toolset that you use which is fine when you have all the control you need over the source code, however if you compile a static library with visual studio 2008 for instance and try to use it in a visual studio 2010 you will get a ton of linker errors because the new project is linked with a newer version of STL which is not backwards compatible. Things get even nastier if you compile a DLL and give an import library that people use in a different toolset because in that case your program will crash sooner or later for no apparent reason.
So for the purpose of moving large data sets from one library to another you could consider giving a pointer to an array to the function that is supposed to copy the data if you don't want to force others to use the same tools that you use. The good part about this is that it doesn't even have to be a C-style array, you can use a std::vector and give the pointer by giving the address of the first element &vector[0] for instance, and use the std::vector to manage the array internally.
Another good reason to use pointers in C++ again relates to libraries, consider having a dll that cannot be loaded when your program runs, so if you use an import library then the dependency isn't satisfied and the program crashes. This is the case for instance when you give a public api in a dll alongside your application and you want to access it from other applications. In this case in order to use the API you need to load the dll from its' location (usually it's in a registry key) and then you need to use a function pointer to be able to call functions inside the DLL. Sometimes the people that make the API are nice enough to give you a .h file that contain helper functions to automate this process and give you all the function pointers that you need, but if not you can use LoadLibrary and GetProcAddress on windows and dlopen and dlsym on unix to get them (considering that you know the entire signature of the function).
A: Here's a slightly different, but insightful take on why many features of C make sense: http://steve.yegge.googlepages.com/tour-de-babel#C
Basically, the standard CPU architecture is a Von Neumann architecture, and it's tremendously useful to be able to refer to the location of a data item in memory, and do arithmetic with it, on such a machine. If you know any variant of assembly language, you will quickly see how crucial this is at the low level.
C++ makes pointers a bit confusing, since it sometimes manages them for you and hides their effect in the form of "references." If you use straight C, the need for pointers is much more obvious: there's no other way to do call-by-reference, it's the best way to store a string, it's the best way to iterate through an array, etc.
A: One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.
Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:
unsigned char *pVideoMemory = (unsigned char *)0xA0000000;
Many embedded devices still use this technique.
A: In large part, pointers are arrays (in C/C++) - they are addresses in memory, and can be accessed like an array if desired (in "normal" cases).
Since they're the address of an item, they're small: they take up only the space of an address. Since they're small, sending them to a function is cheap. And then they allow that function to work on the actual item rather than a copy.
If you want to do dynamic storage allocation (such as for a linked-list), you must use pointers, because they're the only way to grab memory from the heap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "448"
} |
Q: Is there a source-control system that allows tracking of file name changes? So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project.
From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files?
A: The online CVS manual has some detail on how to do this:
The normal way to move a file is to issue a cvs rename command.
$ cvs rename old new
$ cvs commit -m "Renamed old to new"
This is the simplest way to move a file. It is not error prone, and it preserves the history of what was done. CVSNT clients can retrieve the original name by checking out an older version of the repository.
This feature is only supported on CVSNT servers 2.0.55 and later.
A: Pretty much any modern version control system will allow this (Subversion, Perforce, Vault, git, Mercurial, TFS, etc.).
The only ones I can think of that won't (or that have major caveats) are CVS and VSS.
A: In svn, use svn mv.
See also: http://subversion.tigris.org/faq.html#case-change in the FAQ.
A: Subversion can do this, but you have to do it with
svn move <oldfile> <newfile>
Edit: And in this decade, we do git mv <oldfile> <newfile>, or just use mv and git usually figures it out on its own.
A: Subversion has rename capability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/162960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.