text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Physics of a snooker game Anyone can point me to any info regarding physics of a snooker game, if possible more about the ball collisions? I would like to make a game and I need some help about the physics.
A: There's a book online about this,
"Amateur Physics for the Amateur Pool Player" by Ron Shepard (PDF Link)
I haven't read it but I've heard it's good for game developers.
A: Carom3D is a great one, they seem to have mastered the physics. See these links for more info:
http://www.jimloy.com/billiard/phys.htm
http://archive.ncsa.uiuc.edu/Classes/MATH198/townsend/math.html
http://www2.swgc.mun.ca/physics/physlets/billiards.html
http://www.regispetit.com/bil_praa.htm
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Why can't strings be mutable in Java and .NET? Why is it that they decided to make String immutable in Java and .NET (and some other languages)? Why didn't they make it mutable?
A: String is not a primitive type, yet you normally want to use it with value semantics, i.e. like a value.
A value is something you can trust won't change behind your back.
If you write: String str = someExpr();
You don't want it to change unless YOU do something with str.
String as an Object has naturally pointer semantics, to get value semantics as well it needs to be immutable.
A: Wow! I Can't believe the misinformation here. Strings being immutable have nothing with security. If someone already has access to the objects in a running application (which would have to be assumed if you are trying to guard against someone 'hacking' a String in your app), they would certainly be a plenty of other opportunities available for hacking.
It's a quite novel idea that the immutability of String is addressing threading issues. Hmmm ... I have an object that is being changed by two different threads. How do I resolve this? synchronize access to the object? Naawww ... let's not let anyone change the object at all -- that'll fix all of our messy concurrency issues! In fact, let's make all objects immutable, and then we can removed the synchonized contruct from the Java language.
The real reason (pointed out by others above) is memory optimization. It is quite common in any application for the same string literal to be used repeatedly. It is so common, in fact, that decades ago, many compilers made the optimization of storing only a single instance of a String literal. The drawback of this optimization is that runtime code that modifies a String literal introduces a problem because it is modifying the instance for all other code that shares it. For example, it would be not good for a function somewhere in an application to change the String literal "dog" to "cat". A printf("dog") would result in "cat" being written to stdout. For that reason, there needed to be a way of guarding against code that attempts to change String literals (i. e., make them immutable). Some compilers (with support from the OS) would accomplish this by placing String literal into a special readonly memory segment that would cause a memory fault if a write attempt was made.
In Java this is known as interning. The Java compiler here is just following an standard memory optimization done by compilers for decades. And to address the same issue of these String literals being modified at runtime, Java simply makes the String class immutable (i. e, gives you no setters that would allow you to change the String content). Strings would not have to be immutable if interning of String literals did not occur.
A: One factor is that, if Strings were mutable, objects storing Strings would have to be careful to store copies, lest their internal data change without notice. Given that Strings are a fairly primitive type like numbers, it is nice when one can treat them as if they were passed by value, even if they are passed by reference (which also helps to save on memory).
A: I know this is a bump, but...
Are they really immutable?
Consider the following.
public static unsafe void MutableReplaceIndex(string s, char c, int i)
{
fixed (char* ptr = s)
{
*((char*)(ptr + i)) = c;
}
}
...
string s = "abc";
MutableReplaceIndex(s, '1', 0);
MutableReplaceIndex(s, '2', 1);
MutableReplaceIndex(s, '3', 2);
Console.WriteLine(s); // Prints 1 2 3
You could even make it an extension method.
public static class Extensions
{
public static unsafe void MutableReplaceIndex(this string s, char c, int i)
{
fixed (char* ptr = s)
{
*((char*)(ptr + i)) = c;
}
}
}
Which makes the following work
s.MutableReplaceIndex('1', 0);
s.MutableReplaceIndex('2', 1);
s.MutableReplaceIndex('3', 2);
Conclusion: They're in an immutable state which is known by the compiler. Of couse the above only applies to .NET strings as Java doesn't have pointers. However a string can be entirely mutable using pointers in C#. It's not how pointers are intended to be used, has practical usage or is safely used; it's however possible, thus bending the whole "mutable" rule. You can normally not modify an index directly of a string and this is the only way. There is a way that this could be prevented by disallowing pointer instances of strings or making a copy when a string is pointed to, but neither is done, which makes strings in C# not entirely immutable.
A: Actually, the reasons string are immutable in java doesn't have much to do with security. The two main reasons are the following:
Thead Safety:
Strings are extremely widely used type of object. It is therefore more or less guaranteed to be used in a multi-threaded environment. Strings are immutable to make sure that it is safe to share strings among threads. Having an immutable strings ensures that when passing strings from thread A to another thread B, thread B cannot unexpectedly modify thread A's string.
Not only does this help simplify the already pretty complicated task of multi-threaded programming, but it also helps with performance of multi-threaded applications. Access to mutable objects must somehow be synchronized when they can be accessed from multiple threads, to make sure that one thread doesn't attempt to read the value of your object while it is being modified by another thread. Proper synchronization is both hard to do correctly for the programmer, and expensive at runtime. Immutable objects cannot be modified and therefore do not need synchronization.
Performance:
While String interning has been mentioned, it only represents a small gain in memory efficiency for Java programs. Only string literals are interned. This means that only the strings which are the same in your source code will share the same String Object. If your program dynamically creates string that are the same, they will be represented in different objects.
More importantly, immutable strings allow them to share their internal data. For many string operations, this means that the underlying array of characters does not need to be copied. For example, say you want to take the five first characters of String. In Java, you would calls myString.substring(0,5). In this case, what the substring() method does is simply to create a new String object that shares myString's underlying char[] but who knows that it starts at index 0 and ends at index 5 of that char[]. To put this in graphical form, you would end up with the following:
| myString |
v v
"The quick brown fox jumps over the lazy dog" <-- shared char[]
^ ^
| | myString.substring(0,5)
This makes this kind of operations extremely cheap, and O(1) since the operation neither depends on the length of the original string, nor on the length of the substring we need to extract. This behavior also has some memory benefits, since many strings can share their underlying char[].
A: Thread safety and performance. If a string cannot be modified it is safe and quick to pass a reference around among multiple threads. If strings were mutable, you would always have to copy all of the bytes of the string to a new instance, or provide synchronization. A typical application will read a string 100 times for every time that string needs to be modified. See wikipedia on immutability.
A: For most purposes, a "string" is (used/treated as/thought of/assumed to be) a meaningful atomic unit, just like a number.
Asking why the individual characters of a string are not mutable is therefore like asking why the individual bits of an integer are not mutable.
You should know why. Just think about it.
I hate to say it, but unfortunately we're debating this because our language sucks, and we're trying to using a single word, string, to describe a complex, contextually situated concept or class of object.
We perform calculations and comparisons with "strings" similar to how we do with numbers. If strings (or integers) were mutable, we'd have to write special code to lock their values into immutable local forms in order to perform any kind of calculation reliably. Therefore, it is best to think of a string like a numeric identifier, but instead of being 16, 32, or 64 bits long, it could be hundreds of bits long.
When someone says "string", we all think of different things. Those who think of it simply as a set of characters, with no particular purpose in mind, will of course be appalled that someone just decided that they should not be able to manipulate those characters. But the "string" class isn't just an array of characters. It's a STRING, not a char[]. There are some basic assumptions about the concept we refer to as a "string", and it generally can be described as meaningful, atomic unit of coded data like a number. When people talk about "manipulating strings", perhaps they're really talking about manipulating characters to build strings, and a StringBuilder is great for that. Just think a bit about what the word "string" truly means.
Consider for a moment what it would be like if strings were mutable. The following API function could be tricked into returning information for a different user if the mutable username string is intentionally or unintentionally modified by another thread while this function is using it:
string GetPersonalInfo( string username, string password )
{
string stored_password = DBQuery.GetPasswordFor( username );
if (password == stored_password)
{
//another thread modifies the mutable 'username' string
return DBQuery.GetPersonalInfoFor( username );
}
}
Security isn't just about 'access control', it's also about 'safety' and 'guaranteeing correctness'. If a method can't be easily written and depended upon to perform a simple calculation or comparison reliably, then it's not safe to call it, but it would be safe to call into question the programming language itself.
A: Immutability is not so closely tied to security. For that, at least in .NET, you get the SecureString class.
Later edit: In Java you will find GuardedString, a similar implementation.
A: According to Effective Java, chapter 4, page 73, 2nd edition:
"There are many good reasons for this: Immutable classes are easier to
design, implement, and use than mutable classes. They are less prone
to error and are more secure.
[...]
"Immutable objects are simple. An immutable object can be in
exactly one state, the state in which it was created. If you make sure
that all constructors establish class invariants, then it is
guaranteed that these invariants will remain true for all time, with
no effort on your part.
[...]
Immutable objects are inherently thread-safe; they require no synchronization. They cannot be corrupted by multiple threads
accessing them concurrently. This is far and away the easiest approach
to achieving thread safety. In fact, no thread can ever observe any
effect of another thread on an immutable object. Therefore,
immutable objects can be shared freely
[...]
Other small points from the same chapter:
Not only can you share immutable objects, but you can share their internals.
[...]
Immutable objects make great building blocks for other objects, whether mutable or immutable.
[...]
The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
A: It's a trade off. Strings go into the String pool and when you create multiple identical Strings they share the same memory. The designers figured this memory saving technique would work well for the common case, since programs tend to grind over the same strings a lot.
The downside is that concatenations make a lot of extra Strings that are only transitional and just become garbage, actually harming memory performance. You have StringBuffer and StringBuilder (in Java, StringBuilder is also in .NET) to use to preserve memory in these cases.
A: The decision to have string mutable in C++ causes a lot of problems, see this excellent article by Kelvin Henney about Mad COW Disease.
COW = Copy On Write.
A: Strings in Java are not truly immutable, you can change their value's using reflection and or class loading. You should not be depending on that property for security.
For examples see: Magic Trick In Java
A: One should really ask, "why should X be mutable?" It's better to default to immutability, because of the benefits already mentioned by Princess Fluff. It should be an exception that something is mutable.
Unfortunately most of the current programming languages default to mutability, but hopefully in the future the default is more on immutablity (see A Wish List for the Next Mainstream Programming Language).
A: There are at least two reasons.
First - security http://www.javafaq.nu/java-article1060.html
The main reason why String made
immutable was security. Look at this
example: We have a file open method
with login check. We pass a String to
this method to process authentication
which is necessary before the call
will be passed to OS. If String was
mutable it was possible somehow to
modify its content after the
authentication check before OS gets
request from program then it is
possible to request any file. So if
you have a right to open text file in
user directory but then on the fly
when somehow you manage to change the
file name you can request to open
"passwd" file or any other. Then a
file can be modified and it will be
possible to login directly to OS.
Second - Memory efficiency http://hikrish.blogspot.com/2006/07/why-string-class-is-immutable.html
JVM internally maintains the "String
Pool". To achive the memory
efficiency, JVM will refer the String
object from pool. It will not create
the new String objects. So, whenever
you create a new string literal, JVM
will check in the pool whether it
already exists or not. If already
present in the pool, just give the
reference to the same object or create
the new object in the pool. There will
be many references point to the same
String objects, if someone changes the
value, it will affect all the
references. So, sun decided to make it
immutable.
A: Immutability is good. See Effective Java. If you had to copy a String every time you passed it around, then that would be a lot of error-prone code. You also have confusion as to which modifications affect which references. In the same way that Integer has to be immutable to behave like int, Strings have to behave as immutable to act like primitives. In C++ passing strings by value does this without explicit mention in the source code.
A: There is an exception for nearly almost every rule:
using System;
using System.Runtime.InteropServices;
namespace Guess
{
class Program
{
static void Main(string[] args)
{
const string str = "ABC";
Console.WriteLine(str);
Console.WriteLine(str.GetHashCode());
var handle = GCHandle.Alloc(str, GCHandleType.Pinned);
try
{
Marshal.WriteInt16(handle.AddrOfPinnedObject(), 4, 'Z');
Console.WriteLine(str);
Console.WriteLine(str.GetHashCode());
}
finally
{
handle.Free();
}
}
}
}
A: It's largely for security reasons. It's much harder to secure a system if you can't trust that your Strings are tamperproof.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "204"
}
|
Q: Windsor Container: Registering things in Code vs Xml From what I've read about Windsor/Microkernel it is in theory possible to do everything that you can do using xml files with code. As a matter of fact - and please correct me if I'm wrong - it seems like the major contribution of the Windsor layer is to add xml configuration for things Microkernel can already do.
However, I have been struggling lately with finding out how to implement some slightly more complicated functionality in code though (ie. how to assign a default constructor argument value). Now while I am going to use xml in my production release, I am registering components in code for my tests and this is getting to be quite problematic. This is not helped by the unfortunate state of their documentation and the fact that the only articles I can find focus on xml registration.
Does anybody know a source which lists how to register things in code (preferably with the xml equivalent)? Baring the existence of that, does anyone simply know of an open source/sample project where there is significant non-xml use of Castle Windsor/Microkernel?
A: I've always found looking at the unit test the best way to learn how to use an open source project. Castle has a fluent interface that will allow you to do everything in code. From the WindsorDotNet2Tests test case:
[Test]
public void ParentResolverIntercetorShouldNotAffectGenericComponentInterceptor()
{
WindsorContainer container = new WindsorContainer();
container.AddComponent<MyInterceptor>();
container.Register(
Component.For<ISpecification>()
.ImplementedBy<MySpecification>()
.Interceptors(new InterceptorReference(typeof(MyInterceptor)))
.Anywhere
);
container.AddComponent("repos", typeof(IRepository<>), typeof(TransientRepository<>));
ISpecification specification = container.Resolve<ISpecification>();
bool isProxy = specification.Repository.GetType().FullName.Contains("Proxy");
Assert.IsFalse(isProxy);
}
And for more, check out the the ComponentRegistrationTestCase and AllTypesTestCase
There is also a DSL for doing it, this is my prefered option, as it really simplifies things and offers alot of easy extensibility. The DSL is called Binsor, which you can read more about here: http://www.ayende.com/Blog/archive/7268.aspx But again, the best place for infor is the Unit Tests. This is a code example of whats possible with binsor:
for type in AllTypesBased of IController("Company.Web.Controller"):
component type
Those two lines will register ever type that inherits the IController interface into the container :D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is Object-Oriented Modeling different from Object-Oriented Programming? What is the difference between Object-Oriented Modeling and Object-Oriented Programming? I overheard a conversation on my subway train this morning and it seems that these things are different. Aren't they?
A: Object-Oriented Modeling refers to the process where you are designing how the code will look like. You will use a modeling language like UML to do Object-Oriented Modeling. Object-Oriented Programming refers to a programming paradigm where you use objects. These objects have been designed during the desing phase using Object-Oriented Modeling techniques, and they are implemented during the construction (programming phase) using a language that supports Object-Oriented programming and based on the model.
A: Modeling is creating an abstraction of a problem, where as programming is the implementation of such an abstraction.
Modeling can be done in many ways: textual, formulas, diagrams... UML is one standard of modeling object oriented concepts.
Programming can be done in different ways too, depending on the tool, language etc. There are ways to generate the program right out of the modeling tool, typically out of UML models. This goes even a step further, where UML models are "executed" directly.
Other common confusions about object-oriented programming exist too - starting from "it's the thing where your drag and click", over hybrid 3rd generation concepts I refer to as "processing Objects" to practical patterns and ending with pure OOP.
A: I'd say the modeling precludes the programing, where the modeling is the physical design, before the programming is implemented.
http://en.wikipedia.org/wiki/Object-Oriented_Modeling
http://en.wikipedia.org/wiki/Object_oriented_programming
A: I just found this:
Object-oriented modeling is a formal
way of representing something in the
real world. It draws from traditional
set theory and classification theory.
object-oriented modeling is not
limited to computer-related elements.
One may use object-oriented modeling
to represent many different types of
things, from organizational
structures, to organic materials, to
physical buildings.
A: Object-Oriented Modeling is used to define, usually without any actual code, the classes, methods, and variables. There are many tools out there to help with such modelling. Netbeans is one such package. Netbeans can help you model your code and will even attempt to help you get started after you make your class diagrams.
A: I found this extraction is from the DTMF website about Key concepts of object oriented modeling.
Abstraction: DENotes the essential
characteristics of an object that
distinguish it from all other kinds of
objects and thus provide crisply
defined conceptual boundaries.
Example: A Cheesburger - is good to
eat and fun to cook.
Modularity: Decomposition of
abstractions into discrete units.
Example: The various "layers" of a
cheesburger - the bun, the lettuce,
the ketchup, the mayonnaise, the
burger, the cheese, onions, pickels,
etc.
Encapsulation: Process of
compartmentalizing the elements of an
abstraction that constitute its
structure and behavior; encapsulation
serves to separate the interface of an
abstraction and its implementation.
Example: • To cook the cheeseburger:
- Is the stove available? Are the burners working? Are the ingredients
available? • To eat the
cheeseburger: - Is it made correctly?
Is my plate clean or disgusting?
Hierarchy: A ranking or ordering of
abstractions. Example: A
cheeseburger is really a subclass of a
hamburger with cheese added which is a
sub class of sandwich which is a
subclass of the Hierarchal superclass
food.
Key Elements: Classes – A collection
of definitions of state, behavior,
and/or identity • Properties •
Methods
Objects: Instances of a class
Associations: Relationships •
Dependency • Identity •
Aggregation • Composition • And
others
A: Well, given that code is a means of communicating, object-oriented programming in an object-oriented programming language is a form of modelling.
One can however model at a more abstract level using modelling languages that are less expressive, but perhaps more useful for other purposes. For the purposes of developing software, modelling not relatively closely tied to programmes is mainly an exercise for a certain class of person who thinks it is terribly important, and is paid as if it were, but it is not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Handling the data in an IN clause, with SQL parameters? We all know that prepared statements are one of the best way of fending of SQL injection attacks. What is the best way of creating a prepared statement with an "IN" clause. Is there an easy way to do this with an unspecified number of values? Take the following query for example.
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (1,2,3)
Currently I'm using a loop over my possible values to build up a string such as.
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDVAL_1,@IDVAL_2,@IDVAL_3)
Is it possible to use just pass an array as the value of the query paramter and use a query as follows?
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDArray)
In case it's important I'm working with SQL Server 2000, in VB.Net
A: Here you go - first create the following function...
Create Function [dbo].[SeparateValues]
(
@data VARCHAR(MAX),
@delimiter VARCHAR(10)
)
RETURNS @tbldata TABLE(col VARCHAR(10))
As
Begin
DECLARE @pos INT
DECLARE @prevpos INT
SET @pos = 1
SET @prevpos = 0
WHILE @pos > 0
BEGIN
SET @pos = CHARINDEX(@delimiter, @data, @prevpos+1)
if @pos > 0
INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, @pos-@prevpos-1))))
else
INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, len(@data)-@prevpos))))
SET @prevpos = @pos
End
RETURN
END
then use the following...
Declare @CommaSeparated varchar(50)
Set @CommaSeparated = '112,112,122'
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (select col FROM [SeparateValues](@CommaSeparated, ','))
I think sql server 2008 will allow table functions.
UPDATE
You'll squeeze some extra performance using the following syntax...
SELECT ID,Column1,Column2 FROM MyTable
Cross Apply [SeparateValues](@CommaSeparated, ',') s
Where MyTable.id = s.col
Because the previous syntax causes SQL Server to run an extra "Sort" command using the "IN" clause. Plus - in my opinion it looks nicer :D!
A: If you would like to pass an array, you will need a function in sql that can turn that array into a sub-select.
These functions are very common, and most home grown systems take advantage of them.
Most commercial, or rather professional ORM's do ins by doing a bunch of variables, so if you have that working, I think that is the standard method.
A: You could create a temporary table TempTable with a single column VALUE and insert all IDs. Then you could do it with a subselect:
SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (SELECT VALUE FROM TempTable)
A: Go with the solution posted by digiguru. It's a great reusable solution and we use the same technique as well. New team members love it, as it saves time and keeps our stored procedures consistent. The solution also works well with SQL Reports, as the parameters passed to stored procedures to create the recordsets pass in varchar(8000). You just hook it up and go.
A: Here's one technique I use
ALTER Procedure GetProductsBySearchString
@SearchString varchar(1000),
as
set nocount on
declare @sqlstring varchar(6000)
select @sqlstring = 'set nocount on
select a.productid, count(a.productid) as SumOf, sum(a.relevence) as CountOf
from productkeywords a
where rtrim(ltrim(a.term)) in (''' + Replace(@SearchString,' ', ''',''') + ''')
group by a.productid order by SumOf desc, CountOf desc'
exec(@sqlstring)
A: In SQL Server 2008, they finally got around to addressing this classic problem by adding a new "table" datatype. Apparently, that lets you pass in an array of values, which can be used in a sub-select to accomplish the same as an IN statement.
If you're using SQL Server 2008, then you might look into that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: What's the best way to determine if a character is a letter in VB6? Need a function that takes a character as a parameter and returns true if it is a letter.
A: Seanyboy's IsCharAlphaA answer is close. The best method is to use the W version like so:
Private Declare Function IsCharAlphaW Lib "user32" (ByVal cChar As Integer) As Long
Public Property Get IsLetter(character As String) As Boolean
IsLetter = IsCharAlphaW(AscW(character))
End Property
Of course, this all rarely matters as all of VB6's controls are ANSI only
A: Private Function IsLetter(Char As String) As Boolean
IsLetter = UCase(Char) Like "[ABCDEFGHIJKLMNOPQRSTUVWXYZ]"
End Function
A: This was part of the code posted by rpetrich in response to a question by Joel Spolsky. I felt it needed a post specific to the problem it solves. It really is brilliant.
Private Function IsLetter(ByVal character As String) As Boolean
IsLetter = UCase$(character) <> LCase$(character)
End Function
You may be thinking to yourself, "Will this always work?" The documentation on the UCase and LCase functions, confirms that it will:
UCase Function Only lowercase letters are converted to uppercase;
all uppercase letters and nonletter characters remain unchanged.
LCase Function Only uppercase letters are converted to lowercase;
all lowercase letters and nonletter characters remain unchanged.
A: What's wrong with the following, which doesn't rely on obscure language behaviour?
Private Function IsLetter(ByVal ch As String) As Boolean
IsLetter = (ch >= "A" and ch <= "Z") or (ch >= "a" and ch <= "z")
End Function
A: I believe we can improve upon this a little more. rpetrich's code will work, but perhaps only by luck. The API call's parameter should be a TCHAR (WCHAR here actually) and not a Long. This also means no fiddling with converting to a Long or masking with &HFFFF. This by the way is Integer and adds an implicit conversion to Long here too. Perhaps he meant &HFFFF& in this case?
On top of that it might be best to explictly call the UnicoWS wrapper for this API call, for Win9X compatibility. The UnicoWS.dll may need to be deployed but at least we gain that option. Then again maybe from VB6 this is automagically redirected, I don't have Win9X installed to test it.
Option Explicit
Private Declare Function IsCharAlphaW Lib "unicows" (ByVal WChar As Integer) As Long
Private Function IsLetter(Character As String) As Boolean
IsLetter = IsCharAlphaW(AscW(Character))
End Function
Private Sub Main()
MsgBox IsLetter("^")
MsgBox IsLetter("A")
MsgBox IsLetter(ChrW$(&H34F))
MsgBox IsLetter(ChrW$(&HFEF0))
MsgBox IsLetter(ChrW$(&HFEFC))
End Sub
A: Looking around a bit came up with the following...
Private Declare Function IsCharAlphaA Lib "user32" Alias "IsCharAlphaA" (ByVal cChar As Byte) As Long
I believe IsCharAlphaA tests ANSI character sets and IsCharAlpha tests ASCII. I may be wrong.
A: Private Function IsAlpha(ByVal vChar As String) As Boolean
Const letters$ = "abcdefghijklmnopqrstuvwxyz"
If InStr(1, letters, LCase$(vChar)) > 0 Then IsAlpha = True
End Function
A: I use this in VBA
Function IsLettersOnly(Value As String) As Boolean
IsLettersOnly = Len(Value) > 0 And Not UCase(Value) Like "*[!A-Z]*"
End Function
A: It doesn't exactly document itself. And it may be slow. It's a clever hack, but that's all it is. I'd be tempted to be more obvious in my checking. Either use regex's or write a more obvious test.
public bool IsAlpha(String strToCheck)
{
Regex objAlphaPattern=new Regex("[^a-zA-Z]");
return !objAlphaPattern.IsMatch(strToCheck);
}
public bool IsCharAlpha(char chToCheck)
{
return ((chToCheck=>'a') and (chToCheck<='z')) or ((chToCheck=>'A') and (chToCheck<='Z'))
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes I'm importing a MySQL dump and getting the following error.
$ mysql foo < foo.sql
ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes
Apparently there are attachments in the database, which makes for very large inserts.
This is on my local machine, a Mac with MySQL 5 installed from the MySQL package.
Where do I change max_allowed_packet to be able to import the dump?
Is there anything else I should set?
Just running mysql --max_allowed_packet=32M … resulted in the same error.
A: You probably have to change it for both the client (you are running to do the import) AND the daemon mysqld that is running and accepting the import.
For the client, you can specify it on the command line:
mysql --max_allowed_packet=100M -u root -p database < dump.sql
Also, change the my.cnf or my.ini file (usually found in /etc/mysql/) under the mysqld section and set:
max_allowed_packet=100M
or you could run these commands in a MySQL console connected to that same server:
set global net_buffer_length=1000000;
set global max_allowed_packet=1000000000;
(Use a very large value for the packet size.)
A: On CENTOS 6 /etc/my.cnf , under [mysqld] section the correct syntax is:
[mysqld]
# added to avoid err "Got a packet bigger than 'max_allowed_packet' bytes"
#
net_buffer_length=1000000
max_allowed_packet=1000000000
#
A: I have resolved my issue by this query
SET GLOBAL max_allowed_packet=1073741824;
and check max_allowed_packet with this query
SHOW VARIABLES LIKE 'max_allowed_packet';
A: Use a max_allowed_packet variable issuing a command like
mysql --max_allowed_packet=32M
-u root -p database < dump.sql
A: Slightly unrelated to your problem, so here's one for Google.
If you didn't mysqldump the SQL, it might be that your SQL is broken.
I just got this error by accidentally having an unclosed string literal in my code. Sloppy fingers happen.
That's a fantastic error message to get for a runaway string, thanks for that MySQL!
A: This can be changed in your my.ini file (on Windows, located in \Program Files\MySQL\MySQL Server) under the server section, for example:
[mysqld]
max_allowed_packet = 10M
A: Error:
ERROR 1153 (08S01) at line 6772: Got a packet bigger than
'max_allowed_packet' bytes Operation failed with exitcode 1
QUERY:
SET GLOBAL max_allowed_packet=1073741824;
SHOW VARIABLES LIKE 'max_allowed_packet';
Max value:
Default Value (MySQL >= 8.0.3) 67108864
Default Value (MySQL <= 8.0.2) 4194304
Minimum Value 1024
Maximum Value 1073741824
A: Sometimes type setting:
max_allowed_packet = 16M
in my.ini is not working.
Try to determine the my.ini as follows:
set-variable = max_allowed_packet = 32M
or
set-variable = max_allowed_packet = 1000000000
Then restart the server:
/etc/init.d/mysql restart
A: It is a security risk to have max_allowed_packet at higher value, as an attacker can push bigger sized packets and crash the system.
So, Optimum Value of max_allowed_packet to be tuned and tested.
It is to better to change when required (using set global max_allowed_packet = xxx)
than to have it as part of my.ini or my.conf.
A: Re my.cnf on Mac OS X when using MySQL from the mysql.com dmg package distribution
By default, my.cnf is nowhere to be found.
You need to copy one of /usr/local/mysql/support-files/my*.cnf to /etc/my.cnf and restart mysqld. (Which you can do in the MySQL preference pane if you installed it.)
A: The fix is to increase the MySQL daemon’s max_allowed_packet. You can do this to a running daemon by logging in as Super and running the following commands.
# mysql -u admin -p
mysql> set global net_buffer_length=1000000;
Query OK, 0 rows affected (0.00 sec)
mysql> set global max_allowed_packet=1000000000;
Query OK, 0 rows affected (0.00 sec)
Then to import your dump:
gunzip < dump.sql.gz | mysql -u admin -p database
A: In etc/my.cnf try changing the max_allowed _packet and net_buffer_length to
max_allowed_packet=100000000
net_buffer_length=1000000
if this is not working then try changing to
max_allowed_packet=100M
net_buffer_length=100K
A: As michaelpryor said, you have to change it for both the client and the daemon mysqld server.
His solution for the client command-line is good, but the ini files don't always do the trick, depending on configuration.
So, open a terminal, type mysql to get a mysql prompt, and issue these commands:
set global net_buffer_length=1000000;
set global max_allowed_packet=1000000000;
Keep the mysql prompt open, and run your command-line SQL execution on a second terminal..
A: I am working in a shared hosting environment and I have hosted a website based on Drupal. I cannot edit the my.ini file or my.conf file too.
So, I deleted all the tables which were related to Cache and hence I could resolve this issue. Still I am looking for a perfect solution / way to handle this problem.
Edit - Deleting the tables created problems for me, coz Drupal was expecting that these tables should be existing. So I emptied the contents of these tables which solved the problem.
A: Set max_allowed_packet to the same (or more) than what it was when you dumped it with mysqldump. If you can't do that, make the dump again with a smaller value.
That is, assuming you dumped it with mysqldump. If you used some other tool, you're on your own.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "516"
}
|
Q: How to design a rule engine? I'm supposed to create a simple rule engine in C#. Any leads on how I can proceed?. It's a minimalistic rule engine, and would use SQL server as the back end. Do we have any general blueprint or design patterns that generally apply to rule engines? What kind of .Net technologies can I use to design one? Any directions would be helpful.
Thanks.
A: *
*I cannot believe you would implement your own considering there are so many available commercially and open source.
*I recommend taking a look at InRule as a great commercial option that is reasonable priced, or NxBRE in the open source space.
A: If you're using .NET 3.0 or later, you can use the Rules Engine of Windows Workflow Foundation without having to acutally use Workflow.
I've done this on a project, and you can use SQL or XML as the backend, and it works great. You can use the IDE that comes with the Workflow examples and put it in your own apps. It's excellent.
A: You can also try
http://rulesengine.codeplex.com/
A: What kind of Rule engine you looking for? For styling practices? If so, go check out StyleCop. Not the answer, but there might already be something out there for you.
A: Are you given any indication on method? (ie if this is supplemented by course material what are you currently learning?) If this is meant to be a fairly basic system you might find success looking into to Deterministic Finite State Machine and Nondeterministic Finite State Machine
A: If you have business analysts to program the high level rule engine, then fine - pick one of the before-mentioned rule engines or roll your own (including workflows). If not, then just code your business logic in code and if you ever need to hire business analysts and redo the system, you're in a good place to be.
A: If you want to write your implementation something like this...
[TestMethod]
public void GreaterThanRule_WhenGreater_ResultsTrue()
{
// ARRANGE
int threshold = 5;
int actual = 10;
// ACT
var integerRule = new IntegerGreaterThanRule();
integerRule.Initialize(threshold, actual);
var integerRuleEngine = new RuleEngine<int>();
integerRuleEngine.Add(integerRule);
var result = integerRuleEngine.MatchAll();
// ASSERT
Assert.IsTrue(result);
}
... or this...
[TestMethod]
public void GreaterThanRule_WhenGreater_ResultsTrue()
{
// ARRANGE
int threshold = 5;
int actual = 10;
// ACT
var integerRule = new IntegerGreaterThanRule(threshold);
var integerRuleEngine = new RuleEngine<int>();
integerRuleEngine.ActualValue = actual;
integerRuleEngine.Add(integerRule);
// Get the result
var result = integerRuleEngine.MatchAll();
// ASSERT
Assert.IsTrue(result);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: SQL Server post-join rowcount underestimate The Query Optimizer is estimating that the results of a join will have only one row, when the actual number of rows is 2000. This is causing later joins on the dataset to have an estimated result of one row, when some of them go as high as 30,000.
With a count of 1, the QO is choosing a loop join/index seek strategy for many of the joins which is much too slow. I worked around the issue by constraining the possible join strategies with a WITH OPTION (HASH JOIN, MERGE JOIN), which improved overall execution time from 60+ minutes to 12 seconds. However, I think the QO is still generating a less than optimal plan because of the bad rowcounts. I don't want to specify the join order and details manually-- there are too many queries affected by this for it to be worthwhile.
This is in Microsoft SQL Server 2000, a medium query with several table selects joined to the main select.
I think the QO may be overestimating the cardinality of the many side on the join, expecting the joining columns between the tables to have less rows in common.
The estimated row counts from scanning the indexes before the join are accurate, it's only the estimated row count after certain joins that's much too low.
The statistics for all the tables in the DB are up to date and refreshed automatically.
One of the early bad joins is between a generic 'Person' table for information common to all people and a specialized person table that about 5% of all those people belong to. The clustered PK in both tables (and the join column) is an INT. The database is highly normalized.
I believe that the root problem is the bad row count estimate after certain joins, so my main questions are:
*
*How can I fix the QO's post join rowcount estimate?
*Is there a way that I can hint that a join will have a lot of rows without specifying the entire join order manually?
A: Although the statistics were up to date, the scan percentage wasn't high enough to provide accurate information. I ran this on each of the base tables that was having a problem to update all the statistics on a table by scanning all the rows, not just a default percentage.
UPDATE STATISTICS <table> WITH FULLSCAN, ALL
The query still has a lot of loop joins, but the join order is different and it runs in 2-3 seconds.
A: can't you prod the QO with a well-placed query hint?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Easy way to set CurrentCulture for the entire application? In a .net 2 winforms application, what's a good way to set the culture for the entire application?
Setting CurrentThread.CurrentCulture for every new thread is repetitive and error-prone.
Ideally I'd like to set it when the app starts and forget about it.
A: The culture for a thread in .NET is the culture for the system (as viewed by a single application/process). There is no way to override that in .NET, you'll have to continue setting the CurrentCulture for each new thread.
A: You can set application current culture this way:
static void Main()
{
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("fi-FI");
Application.CurrentCulture = cultureInfo;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
I'm not sure if it helps, because I have never tested it with threads.
edit: it doesn't work. I think you have to set current culture in every thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to protect yourself against shell DLLs loaded into your process? When you use a standard Windows "file open" dialog using GetOpenFileName(), the shell will load various DLLs that it requires to display the file list, including custom ones.
In my application, I found that the DLL that TortoiseCVS uses to draw overlays on the icons was calling GdiPlusShutdown(), and so some time after displaying a "file open" dialog, the TortoiseCVS DLL would be unloaded, it would shut down GDI+ and my graphics functions would all fail!
It seems quite bad that basically any old DLL could be loaded by my application at any time and start doing random things to its state. The workaround in my case was quite simple - just restart GDI+ if I detect that it's been shut down. However had this happened on a client's machine where I couldn't debug it, it would have been a lot more challenging to figure out what was going on.
Can anybody offer any insight? What could I do to stop this from happening?
A: I've had to deal with the crap that Dell puts on its machines, in particular wxVault. My solution was to "simply" patch the code. Slightly tricky with DEP, but still doable. You could have a peek at Microsoft Detours, which is a slightly more structured way to do the same. You'd still have the DLL load, but at least you can stop it calling functions that it should not be calling.
At to why Windows has such a crappy mechanism, read Raymond Chen's "Old New Thing" blog or book.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Editing Autogenerated DMBL file for WCF Service In our project we have a standard auto-generated designer.cs file, linked to a DBML file, that contains all our object classes that map onto our database tables.
We want to pass these objects directly through a WCF Service and so they need decorating with the [DataContract] and [DataMember] attributes where appropriate. What is the best approach to doing this so the changes won't get wiped out when the designer.cs file is re-generated upon a change to the database scheme or some other change.
Partial classes are an option, but if the property I want to decorate with the DataMember attribute is already defined in the autogenerated designer.cs file then I can't add the same property definition to the partial class as this means the property will have been defined twice.
A: Setting the DBML serialization mode to unidirectional will decorate the classes and a number of the members with the required attributes however it will ignore some of the associations to avoid circular references that were a problem prior to SP1.
If you want those too check out my LINQ to SQL T4 template that provides full SP1 compatible DataContract attributes (uncomment the line data.SerializationMode = DataContractSP1 in the DataClasses.tt file) as well as letting you customize any other parts of the DBML to C#/VB.NET code generation process.
A: The dbml files give partial classes, so you can create a new .cs file, define the partial class that you want to extend, and then decorate that with the attributes that you want. For instance if you have a generated data context that looks like
public partial class MyDataContext : System.Data.Linq.DataContext
{
...
}
you can define the following in a separate .cs file:
[DataContract]
public partial class MyDataContext
{
...
}
This way you can extend the generated classes without worrying about them being overwritten when your dbml file is re-generated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Obtaining client IP address in WCF 3.0 Apparently you can easily obtain a client IP address in WCF 3.5 but not in WCF 3.0. Anyone know how?
A: It turns out you can, so long as (a) your service is being hosted in a Web Service (obviously) and (b) you enable AspNetCompatibility mode, as follows:
<system.serviceModel>
<!-- this enables WCF services to access ASP.Net http context -->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
...
</system.serviceModel>
And then you can get the IP address by:
HttpContext.Current.Request.UserHostAddress
A: You can if you are targeting .NET 3.0 SP1.
OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;
Credits:
http://blogs.msdn.com/phenning/archive/2007/08/08/remoteendpointmessageproperty-in-wcf-net-3-5.aspx
Reference:
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx
A: This doesn't help you in 3.0, but I can just see people finding this question and being frustrated because they are trying to get the client IP address in 3.5. So, here's some code which should work:
using System.ServiceModel;
using System.ServiceModel.Channels;
OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
}
|
Q: Non-breaking non-space in HTML I have a bowling web application that allows pretty detailed frame-by-frame information entry. One thing it allows is tracking which pins were knocked down on each ball. To display this information, I make it look like a rack of pins:
o o o o
o o o
o o
o
Images are used to represent the pins. So, for the back row, I have four img tags, then a br tag. It works great... mostly. The problem is in small browsers, such as IEMobile. In this case, where there are may 10 or 11 columns in a table, and there may be a rack of pins in each column, Internet Explorer will try to shrink the column size to fit on the screen, and I end up with something like this:
o o o
o
o o o
o o
o
or
o o
o o
o o
o
o o
o
The structure is:
<tr>
<td>
<!-- some whitespace -->
<div class="..."><img .../><img .../><img .../><img .../><br/>...</div>
<!-- some whitespace -->
</td>
</tr>
There is no whitespace inside the inner div. If you look at this page in a regular browser, it should display fine. If you look at it in IEMobile, it does not.
Any hints or suggestions? Maybe some sort of that doesn't actually add a space?
Follow-up/Summary
I have received and tried several good suggestions, including:
*
*Dynamically generate the whole image on the server. It is a good solution, but doesn't really fit my need (hosted on GAE), and a bit more code than I'd like to write. These images could also be cached after the first generation.
*Use CSS white-space declaration. It is a good standards-based solution, but it fails miserably in the IEMobile view.
What I ended up doing
*hangs head and mumbles something*
Yes, that's right, a transparent GIF at the top of the div, sized to the width I need. End code (simplified) looks like:
<table class="game">
<tr class="analysis leave">
<!-- ... -->
<td> <div class="smallpins"><img class="spacer" src="http://seasrc.th.net/gif/cleardot.gif" /><br/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/pinsmall.gif"/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/></div> </td>
<!-- ... -->
</tr>
</table>
And CSS:
div.smallpins {
background: url(/img/lane.gif) repeat;
text-align: center;
padding: 0;
white-space: nowrap;
}
div.smallpins img {
width: 1em;
height: 1em;
}
div.smallpins img.spacer {
width: 4.5em;
height: 0px;
}
table.game tr.leave td{
padding: 0;
margin: 0;
}
table.game tr.leave .smallpins {
min-width: 4em;
white-space: nowrap;
background: none;
}
P.S.: No, I will not be hotlinking someone else's clear dot in my final solution :)
A: Why not have an image for all possible outcomes for the pins? No Messing with layouts for browsers an image is an image
Generate them on the fly caching the created images for reuse.
A: I've got around this type of issue in the past by dynamically creating the entire image (with appropriate pin arrangement) as a single image. If you are using ASP.NET, this is pretty easy to do with GDI calls. You just dynamically create the image with pin placement, then serve to the page as a single image. Takes all the alignment issues out of the picture (pun intended).
A: What would make the most sense is changing out which image is displayed on the fly:
<div id="pin-images">
<img src="fivepins.jpg" />
<img src="fourpins.jpg" />
<img src="threepins.jpg" />
<img src="twopins.jpg" />
<img src="onepin.jpg" />
</div>
A: You could try the css "nowrap" option in the containing div.
{white-space: nowrap;}
Not sure how widely that is supported.
A: Since you are using images anyway, why not generate an image representing the whole layout on the fly? You can use something like GD or ImageMagick to do the trick.
A: Add a "nowrap" in your td tag...
A: Since you're going for maximum compatibility, consider generating a single image representing the frame.
If you're using PHP, you can use GD to dynamically create images representing the frames based on the same input that you would use to create the HTML in your question. The biggest advantage to doing this is that any browser which could display a PNG or GIF would be able to display your frame.
A: I figured out that there is a setting on the client where they can select the view as 1) Single Column, 2) Desktop View, and 3) Fit Window.
According to MSDN, the default is supposed to be to Fit Window. But my wife's IE Mobile phone was defaulting to a Single Column. So no matter what, it would wrap everything into a single column. If I switched to any of the other two options it looked fine.
Well, you can set this with a meta tag:
<meta name="MobileOptimized" content="320">
will set the page width to 320 pixels. But I don't know how to make it go to auto.
This does not work on BlackBerry's prior to v4.6 - you're stuck with single column unless the user manually changes to desktop view. With 4.6 or later, the following is supposed to work, but I haven't tested it:
<meta name="viewport" content="width=320">
A: You might need an actual space immediately following the semi-colon in
A: Try it with the <div> tag on the same line as <td>...</td>
A: I may have misunderstood what you are after but I think that you can do what I've done for logos on a map.
The map background tile is drawn then each image is told to float left and given some interesting margins so that they are positioned as I want them to be (view source to see how it's done).
A: Use the word joiner character, U+2060 (i.e. ⁠)
A: Maybe this is just one case where you could use tables to enforce layout. It's not optimal, and I know you aren't supposed to use tables for things that aren't tabular, but you could do something like this.
<table>
<tr>
<td><img src="Pin.jpg"></td>
<td> </td>
<td><img src="Pin.jpg"></td>
<td> ></td>
<td><img src="Pin.jpg"></td>
<td> </td>
<td><img src="Pin.jpg"></td>
</tr>
<tr>
<td> </td>
<td><img src="Pin.jpg"></td>
<td> </td>
<td><img src="Pin.jpg"></td>
<td> </td>
<td><img src="Pin.jpg"></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><img src="Pin.jpg"></td>
<td> </td>
<td><img src="Pin.jpg"></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><img src="Pin.jpg"></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
A: Do you have tried to define a width for the column? Like <td width="123px"> or <td style="width:123px">. And maybe also for the div ?
A: You can replace img with span and use a background image with each span, depending on a CSS class:
<p class="..."><span class="pin"></span><span> </span><span class="pin"></span>...
<p class="..."><span class="pin"></span><span> </span><span class="pin"></span>...
<p class="..."><span class="pin"></span><span> </span><span class="pin"></span>...
<p class="..."><span class="pin"></span><span> </span><span class="pin"></span>...
(Personally I think it's better to have four lines with a p tag instead of a single div with br.)
Then in CSS you can have something like this:
p.smallpins {
margin: 0;
padding: 0;
height: 11px;
font-size: 1px;
}
p.smallpins span {
width: 11px;
background-image: url(nopinsmall.gif);
background-repeat: ...
background-position: ...
}
p.smallpins span.pin {
background-image: url(pinsmall.gif);
}
A: *
*There isn't any nobr HTML tag; I am not sure how well-supported this is, though.
*You could use CSS overflow:visible and non-breaking spaces between your elements (images), but no other white space in the HTML content for those lines.
A: Have separate images for every possible arrangement of each row.
That would only require 30 images (16+8+4+2)
A: Would it not be easier if you do it like this?
<div id="container">
<div id="row1">
<img/><img/><img/><img/>
</div>
<div id="row2">
<img/><img/><img/>
</div>
<div id="row3">
<img/><img/>
</div>
<div id="row4">
<img/>
</div>
</div>
Whereby your CSS would handle the alignment?
.container div{
text-align:center;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Modifying JVM parameters at runtime Does someone know if it is possible to modify the JVM settings at runtime (e.g. -dname=value)?
I need this little trick to run my Java stored procedure (oracle 10g).
A: Assuming you mean system properties (-D...; -d picks data model) System.setProperty(...) may do what you want.
A: You can use the OracleRuntime class inside your java stored procedure.
int times = 2;
OracleRuntime.setMaxRunspaceSize(times *OracleRuntime.getMaxRunspaceSize());
OracleRuntime.setSessionGCThreshold(times *OracleRuntime.getSessionGCThreshold());
OracleRuntime.setNewspaceSize(times *OracleRuntime.getNewspaceSize());
OracleRuntime.setMaxMemorySize(times *OracleRuntime.getMaxMemorySize());
OracleRuntime.setJavaStackSize(times *OracleRuntime.getJavaStackSize());
OracleRuntime.setThreadStackSize(times *OracleRuntime.getThreadStackSize());
This sample code multiplies by 2 memory status in oracle jvm.
Note: import oracle.aurora.vm.OracleRuntime; will be resolved on oracle jvm, found on "aurora.zip"
A: You can definitely set system properties in a Java stored procedure using System.setProperty(). But, they will only be available to the current Oracle session.
For example, if you connect to Oracle, and run a Java stored procedure that sets system properties, then disconnect from Oracle. When you next connect to Oracle, the system property will not be present. Each session with Oracle has its own pseudo-separate JVM (even though all sessions really share a single JVM).
If the account you are using for your Oracle session has sufficient rights, you can run external operating system commands including a separate, external JVM.
A: You can change a system property using System.setProperty(), but whether or not this has an effect really depends on that system property. Some properties are read statically, i.e. at class loading time, and others might cache the value in some object field.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the difference between Subclipse Get Contents and Get Revision? When using the Eclipse->Team->Show History view, what's the difference between using Subclipse "Get Contents" and "Get Revision" options on a revision of a file?
Is there any way to see what svn commands Subclipse is issuing behind the scenes?
A: From the Subclipse manual (Help > Help Contents):
Get Contents
Use this option to update the contents
of the selected file in your working
copy with the contents of the revision
in the repository. The revision number
of your local file is not changed by
this option.
This option is only valid when the
resource history was launched for an
individual file in a local working
copy.
Get Revision
Use this option to replace the file in
your working copy with the selected
revision in the repository. The
revision number of your local file is
changed to the selected revision.
This option is only valid when the
resource history was launched for an
individual file in a local working
copy.
Pretty self-explanatory.
A: Get contents just shows you the file's contents, while get revision replaces your version of the file.
To see the commands run by subclipse in the console view you should check the "Show SVN console automatically when command is run" option in tools/preferences/team/svn/console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Can I automatically 'Generate Scripts' in a SQL Server 2005 task? I'd like to automatically generate database scripts on a regular basis. Is this possible.
A: To generate script for an object you have to pass up to six parameters:
exec proc_genscript
@ServerName = 'Server Name',
@DBName = 'Database Name',
@ObjectName = 'Object Name to generate script for',
@ObjectType = 'Object Type',
@TableName = 'Parent table name for index and trigger',
@ScriptFile = 'File name to save the script'
http://www.databasejournal.com/features/mssql/article.php/2205291
A: You might want to look at the SQL Server Management Objects (SMO). There are objects for scripting that will assist in generating T-SQL scripts from database objects. A good reference for this is "Programming SQL Server 2005" by Bill Hamilton. Chapter 12 in particular references the SMO utility classes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do you mock params when testing a Rails model's setter? Given the code from the Complex Form part III how would you go about testing the virtual attribute?
def new_task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
I am currently trying to test it like this:
def test_adding_task_to_project
p = Project.new
params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]}
p.new_tasks_attributes=(params)
p.save
assert p.tasks.length == 1
end
But I am getting the following error:
NoMethodError: undefined method `stringify_keys!' for "new_tasks_attributes":String
Any suggestions on improving this test would be greatly appreciated.
A: It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:
def test_adding_task_to_project
p = Project.new
new_tasks_attributes = [{ "name" => "paint fence"}]
p.new_tasks_attributes = (new_tasks_attributes)
p.save
assert p.tasks.length == 1
end
A: Can we see the whole stack trace? Where does it think String#stringify_keys! is being called?
Also, params looks odd to me. Is tasks.build() expecting input like this: ["new_tasks_attribute", {"name" => "paint fence"}] ?
If not, maybe you actually want Hash#each_key() instead of Hash#each()?
Need more data. Also, you might consider a Ruby tag to accompany your Rails tag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I find out what triggered the TRACKER_ID rule in spamassassin? I recently received an email from my girlfriend that spamassassin marked as spam, mostly because spamassassin detected a tracker ID... except there wasn't one. I'd like to know what triggered it, so that I can report a sensible bug.
A: How about looking at the rule in question? Google says this:
/^[a-z0-9]{6,24}[-_a-z0-9]{12,36}[a-z0-9]{6,24}\s*\z/is
...which in its current form will hit (some, depending on hyphenation) words
with 24 or more characters. So maybe someone who is familiar with tracker IDs
can adjust the regexp so that large words (say 30 characters?) won't get hit.
URL: https://issues.apache.org/SpamAssassin/show_bug.cgi?id=2307
That's 2005, so it might have changed.
A: FYI, you can see the TRACKER_ID rule as distributed in SpamAssassin 3.2.5 at http://cpansearch.perl.org/src/JMASON/Mail-SpamAssassin-3.2.5/rules/20_body_tests.cf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Debugging Eclipse Application Problem: Launches repeatedly I'm having a problem debugging an Eclipse Application from Eclipse. When I launch the Debug Configuration, the Eclipse Application starts up and then stops repeatedly. It shows the splash screen and then disappears. This is the farthest it gets before restarting:
MyDebugConfiguration [Eclipse Application]
org.eclipse.equinox.launcher.Main at localhost:2599
Thread [main] (Running)
Daemon Thread [Signal Dispatcher] (Running)
Daemon Thread [State Data Manager] (Running)
Daemon Thread [Framework Event Dispatcher] (Running)
Thread [State Saver] (Running)
Daemon Thread [Start Level Event Dispatcher] (Running)
Thread [Refresh Packages] (Running)
C:\MyApp\eclipse\jdk\jre\bin\javaw.exe (Sep 18, 2008 9:38:19 AM)
I am using Version 3.4.0 of the Eclipse SDK.
What is causing this?
A: Have you tried launching Eclipse with the -clean option? This may resolve the issue if it's somehow related to a configuration problem or the registry cache.
A: Does your eclipse application have an analog to the hidden logfile in the workspace on launch of the IDE? You can find this in workspace/.metadata/.log
If your application has that somewhere, you might be able to get a little bit better information on what's happening at startup of your eclipse app.
A: I always add the -console and -consoleLog to the launch configuration.
The first will dump the eclipse log to the console, and the second gives you access to the OSGi console.
In this situation, I check the status of all bundles (using ss). Chances are that the bundle you are interested in hasn't been started. This is probably due to:
*
*an exception in the Activator.
*an unresolved dependency of the bundle.
If you haven't already seen the error via the consoleLog, then you try and start the bundle manually on the console, with start <bundle-number>. The <bundle-number> is the index of the bundle as seen in ss output. If it is a problem starting the bundle, then the stack trace will be useful in tracking down the real problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A free tool to check C/C++ source code against a set of coding standards? It looks quite easy to find such a tool for Java (Checkstyle, JCSC), but I can't seem to find one for C/C++. I am not looking for a lint-like static code analyzer, I only would like to check against coding standards like variable naming, capitalization, spacing, identation, bracket placement, and so on.
A: I'm sure this could help to some degree cxx checker. Also this tool seems to be pretty good KWStyle It's from Kitware, the guys who develop Cmake.
A: Not exactly what you ask for, but I've found it easier to just all agree on a coding standard astyle can generate and then automate the process.
A: Try nsiqcppstyle. It's a Python based coding style checker for C/C++. It's easy to extend to add your own rules.
A: The only tool I know is Vera. Haven't used it, though, so can't comment how viable it is. Demo looks promising.
A: Google c++lint from Google code style guide.
A: There's a list. There is also a putative C++ frontend on splint.
A: I have used a tool in my work its LDRA tool suite
It is used for testing the c/c++ code but it also can check against coding standards such as MISRA etc.
A: Check universalindentgui on sourceforge.net.
it has many style checkers for C and you can customise the checkers.
A: There is cppcheck which is supported also by Hudson via the plugin of the same name.
A: Check Metrix++ http://metrixplusplus.sourceforge.net/. It may require some extensions which are specific for your needs.
A: Check out Abraxas Code Check
http://www.abxsoft.com/codchk_user.html
A: I'm currently working on a project with another project to write just such a tool. I looked at other static code analysis tools and decided that I could do better.
Unfortunately, the project is not yet ready to be used without fairly intimate knowledge of the code (read: it's buggy as all hell). However, we're moving fairly quickly, and hope to have a beta release within the next 8 weeks.
The project is open source - you can visit the project page, and if you want to get involved, we'd love some more external input.
I won't bore you with the details - you can visit the project page for that, but I will say one thing: Most static code analysis tools are aimed at checking your code for mistakes, and not very concerned with checking for coding guidelines. We have taken a more flexible approach that allows us to write plugiins to check for both "house rules" as well as possible bugs.
If you want any more information, please don't hesitate to contact me.
Cheers,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "159"
}
|
Q: In the COFF file format, what is the significance of the relocation information section? I am reading about COFF file formats, which is commonly used to create an executable file format (it has some variants also).
While reading, I came across the relocation section of the format. How is this relocation section used to create an executable file.
It would be very useful if you point me to some links which will help me.
A: Actually, with COFF there are 2 types of relocation information:
*
*COFF Relocation records
*The relocation section in an executable image.
They have similar, but different purposes. The relocation information in an executable identifies things that need to be fixed up, at load time, should the executable image be loaded at a different addresses from its preferred address.
COFF Relocation records identify things that need to be fixed up, at link time, when a section in an object file is assigned to an offset in an executable image.
A: Relocation is used to place executable code in its own memory space in a process. For example, if you try to load two dlls that both request the same base address (ie, the same place in memory), then one of the dlls will have to be relocated to another address.
NTCore is a useful site for exploring Portable Executable (PE) files, which is what COFF is now called. Here is another site that explains relocation pretty well.
A: An unintended addition use of relocation is (de-)obfuscating binaries at run time with no additional unpacking code. See this paper.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I drop a foreign key in SQL Server? I have created a foreign key (in SQL Server) by:
alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID)
references Country;
I then run this query:
alter table company drop column CountryID;
and I get this error:
Msg 5074, Level 16, State 4, Line 2
The object 'Company_CountryID_FK' is dependent on column 'CountryID'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column
I have tried this, yet it does not seem to work:
alter table company drop foreign key Company_CountryID_FK;
alter table company drop column CountryID;
What do I need to do to drop the CountryID column?
Thanks.
A: This will work:
ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]
A: I don't know MSSQL but would it not be:
alter table company drop **constraint** Company_CountryID_FK;
A: Try
alter table company drop constraint Company_CountryID_FK
alter table company drop column CountryID
A: I think this will helpful to you...
DECLARE @ConstraintName nvarchar(200)
SELECT
@ConstraintName = KCU.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE
KCU.TABLE_NAME = 'TABLE_NAME' AND
KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'
IF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + @ConstraintName)
It will delete foreign Key Constraint based on specific table and column.
A: First check of existence of the constraint then drop it.
if exists (select 1 from sys.objects where name = 'Company_CountryID_FK' and type='F')
begin
alter table company drop constraint Company_CountryID_FK
end
A: alter table company drop constraint Company_CountryID_FK
A: You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.
A: Are you trying to drop the FK constraint or the column itself?
To drop the constraint:
alter table company drop constraint Company_CountryID_FK
You won't be able to drop the column until you drop the constraint.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "231"
}
|
Q: Min-width in MSIE 6 What is the definitive way to mimic the CSS property min-width in Internet Explorer 6? Is it better not to try?
A: foo { min-width: 100px } // for everyone
* html foo { width: 100px } // just for IE
(or serve a separate stylesheet to IE using conditional comments)
A: You could use an expression (as suggested by HBoss), but if you are worried about performance then the best way to do this is to add a shim inside the element you want to apply a min-width to.
<div id="container">
The "shim" div will hold the container div open to at least 500px!
You should be able to put it anywhere in the container div.
<div class="shim"> </div>
</div>
#container .shim {
width: 500px;
height: 0;
line-height: 0;
}
This requires a little non-semantic markup but is a truly cross-browser solution and doesn't require the overhead of using an expression.
A: This article on CSS Play, by Stu Nicholls, shows the different methods for achieving min-width in IE, in all modes (Quirks, etc) and even for IE/Mac.
A: I've fiddled with every answer given here in the past month. And after playing with Pretaul's method (Min-width in MSIE 6), it seems to be the best alternative to min-width. No hacks or anything, just straight up compliant CSS code which takes 30 seconds to implement.
From Googling around, expressions seem to be the most popular. For me anyways, ittended to randomly lock up my browser (both IE and FF).
A: I dunno, I had some success with:
min-width: 193px;
width:auto !important;
_width: 193px; /* IE6 hack */
A combination of dustin diaz' min-height fast hack & How do I specify in HTML or CSS the absolute minimum width of a table cell
A: do your css tag as _Width: 500px or whatever.
A: This works pretty well...
div.container {
min-width: 760px;
width:expression(document.body.clientWidth < 760? "760px": "auto" );
}
A: Min-height fast hack works for me (also works for width)
A: The shim example is fine for forcing the browser to show a horizontal scroll bar when the container gets to a certain size but you'll notice that the content in the container will still be resized as the window gets smaller. I imagine that this is not the overall goal when trying to achieve minimum width in IE 6.
Incomplete min-width technique http://www.mediafire.com/imgbnc.php/260264acec99b5aba3e77c1c4cdc54e94g.jpg
Furthermore, the use of expressions and other crazy CSS hacks just isn't good practice. They are unsafe and unclean. This article explains the caveats of CSS hacks and why they should be avoided altogether.
I personally consider scaryjeff's post to be the best advice for achieving true min-width in IE6 and as an experienced CSS layout developer I've yet to find a better solution that is as applicable to problems of this kind.
This article on CSS Play, by Stu Nicholls, shows the different methods for achieving min-width in IE, in all modes (Quirks, etc) and even for IE/Mac.
I've provided an answer to a similar question that details the use of this technique to correctly achieve min-width. It can be viewed here:
CSS: Two 50% fluid columns not respecting min width
The technique is simple, valid CSS that can be used in almost any situation. Applied to the shim example above it results in what I consider to be correct min-width functionality.
Correct min-width technique http://www.mediafire.com/imgbnc.php/a67b2820bfbd6a5b588bea23c4c0462f4g.jpg
A: Single line button
button{
background-color:#069;
float:left;
min-width:200px;
width:auto !important;
width:200px;
white-space: nowrap}
A: Use conditional comments to reference and MSIE 6 specific style sheet, then create CSS as below.
Compliant browsers will use:
min-width: 660px;
Then MSIE 6 will use:
width: expression((document.body.clientWidth < 659)? "660px" : "auto");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What Does ActiveRecord::MultiparameterAssignmentErrors Mean? I have a rails form with a datetime_select field. When I try to submit the form, I get the following exception:
ActiveRecord::MultiparameterAssignmentErrors in WidgetsController#update
1 error(s) on assignment of multiparameter attributes
If it's a validation error, why don't I see an error on the page?
This is in Rails 2.0.2
A: Super hack, but I needed to solve this problem right away for a client project. It's still a bug with Rails 2.3.5.
Using either date_select or datetime_select, if you add this to your model in the initialize method, you can pre-parse the passed form-serialized attributes to make it work:
def initialize(attributes={})
date_hack(attributes, "deliver_date")
super(attributes)
end
def date_hack(attributes, property)
keys, values = [], []
attributes.each_key {|k| keys << k if k =~ /#{property}/ }.sort
keys.each { |k| values << attributes[k]; attributes.delete(k); }
attributes[property] = values.join("-")
end
I am using this with a nested, polymorphic, model. Here's a question I had showing the models I'm using. So I needed accepts_nested_attributes_for with a datetime.
Here's the input and output using the console:
e = Event.last
=> #<Event id: 1052158304 ...>
e.model_surveys
=> []
e.model_surveys_attributes = [{"survey_id"=>"864743981", "deliver_date(1i)"=>"2010", "deliver_date(2i)"=>"2", "deliver_date(3i)"=>"11"}]
PRE ATTRIBUTES: {"survey_id"=>"864743981", "deliver_date(1i)"=>"2010", "deliver_date(2i)"=>"2", "deliver_date(3i)"=>"11"}
# run date_hack
POST ATTRIBUTES: {"survey_id"=>"864743981", "deliver_date"=>"2010-2-11"}
e.model_surveys
=> [#<ModelSurvey id: 121, ..., deliver_date: "2010-02-11 05:00:00">]
>> e.model_surveys.last.deliver_date.class
=> ActiveSupport::TimeWithZone
Otherwise it was either null, or it would throw the error:
1 error(s) on assignment of multiparameter attributes
Hope that helps,
Lance
A: This is not a bug in Rails, it is the intended behavior of the multi-parameter attribute writer. I'm willing to bet that the original poster's deliver_date field in the database is a varchar as opposed to a date or datetime type. ActiveRecord uses each part of the multi-parameter attribute to send to the new method of the serialized type. The number 1, 2, 3, etc indicates the constructor parameter position and the "i" tells ActiveRecord to call to_i on the parameter before passing it to the constructor. In this case they are all "i's" because DateTime.new(year, month, day) expects three Integers not three Strings.
If the deliver_date column in the database isn't a type that's serialized to a DateTime then ActiveRecord will throw a ActiveRecord::MultiparameterAssignmentErrors exception because String.new(2010,2,11) won't be successful.
Source:
https://github.com/rails/rails/blob/v3.0.4/activerecord/lib/active_record/base.rb#L1739
A: ActiveRecord throws the MultiparameterAssignmentErrors exception when you try to set an invalid date to a models attribute.
Try to pick a Nov 31 date from the date_select or datetime_select dropdown and you will get this error.
A: It turns out that rails uses something called Multi-parameter assignment to transmit dates and times in small parts that are reassembled when you assign params to the model instance.
My problem was that I was using a datetime_select form field for a date model field. It apparently chokes when the multi-parameter magic tries to set the time on a Date object.
The solution was to use a date_select form field rather than a datetime_select.
A: Like Zubin I've seen this exception when the form submits a month as a month name rather than a numerical month string (eg. October rather than 10).
One user agent I've encountered seems to submit the contents of the option tag rather than the value attribute:
Mozilla/5.0 (SymbianOS/9.2; U;
Series60/3.1 NokiaE66-1/300.21.012;
Profile/MIDP-2.0
Configuration/CLDC-1.1 )
AppleWebKit/413 (KHTML, like Gecko)
Safari/413
So in the case of submitting a multi-parameter date from a helper generated select (from date_select helper) your params will have:
"event"=> {
"start_on(2i)"=>"October",
"start_on(3i)"=>"19",
"start_on(1i)"=>"2010"
}
This creates an exception: ActiveRecord::MultiparameterAssignmentErrors: 1 error(s) on assignment of multiparameter attributes
Most user agents will correctly submit:
"event"=> {
"start_on(2i)"=>"10",
"start_on(3i)"=>"19",
"start_on(1i)"=>"2010"
}
A: This error can also occur with webrat/cucumber when filling in form data using a table.
eg this doesn't work:
When I fill in the following:
| report_from_1i | 2010 |
| report_from_2i | January |
| report_from_3i | 1 |
| report_to_1i | 2010 |
| report_to_2i | February |
| report_to_3i | 1 |
but this does:
When I fill in the following:
| report_from_1i | 2010 |
| report_from_2i | 1 |
| report_from_3i | 1 |
| report_to_1i | 2010 |
| report_to_2i | 2 |
| report_to_3i | 1 |
A: In my case the ActiveRecord am/pm plugin caused the error through an incorrect alias_method_chain resulting in an StackLevelTooDeep exception.
The plugin was included by the unobtrusive_date_picker plugin.
The look into this before hacking away.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: How to create a fast PHP library? For our online game, we have written tons of PHP classes and functions grouped by theme in files and then folders. In the end, we have now all our backend code (logic & DB access layers) in a set of files that we call libs and we include our libs in our GUI (web pages, presentation layer) using include_once('pathtolib/file.inc').
The problem is that we have been lazy with inclusions and most include statements are made inside our libs file resulting that from each webpage, each time we include any libs file, we actually load the entire libs, file by file.
This has a significant impact on the performance. Therefore What would be the best solution ?
*
*Remove all include statements from the libs file and only call the necessary one from the web pages ?
*Do something else ?
Server uses a classic LAMP stack (PHP5).
EDIT: We have a mix of simple functions (legacy reason and the majority of the code) and classes. So autoload will not be enough.
A: *
*Manage all includes manually, only where needed
*Set your include_path to only where it has to be, the default is something like .:/usr/lib/pear/:/usr/lib/php, point it only at where it has to be, php.net/set_include_path
*Don't use autoload, it's slow and makes APC and equivalent caches jobs a lot harder
*You can turn off the "stat"-operation in APC, but then you have to clear the cache manually every time you update the files
A: If you've done your programming in an object-oriented way, you can make use of the autoload function, which will load classes from their source files on-demand as you call them.
Edit: I noticed that someone downvoted both answers that referred to autoloading. Are we wrong? Is the overhead of the __autoload function too high to use it for performance purposes? If there is something I'm not realizing about this technique, I'd be really interested to know what it is.
A: If you want to get really hard-core, do some static analysis, and figure out exactly what libraries are needed when, and only include those.
If you use include and not include_once, then there is a bit of a speed savings there as well.
All that said, Matt's answer about the Zend Optimizer is right on the money. If you want, try the Advanced PHP Cache (APC), which is an opcode cache, and free. It should be in the PECL repository.
A: You could use spl_autoload_register() or __autoload() to create whatever rules you need for including the files that you need for classes, however autoload introduces its own performance overheads. You'll need to make sure whatever you use is prepended to all gui pages using a php.ini setting or an apache config.
For your files with generic functions, I would suggest that you wrap them in a utility class and do a simple find and replace to replace all your function() calls with util::function(), which would then enable you to autoload these functions (again, there is an overhead introduced to calling a method rather than a global function).
Essentially the best thing to do is go back through your code and pay off your design debt by fixing the include issues. This will give you the most performance benefit, and it will allow you to make the most of optimisers like eAccelerator, Zend Platform and APC
Here is a sample method for loading stuff dynamically
public static function loadClass($class)
{
if (class_exists($class, false) ||
interface_exists($class, false))
{
return;
}
$file = YOUR_LIB_ROOT.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
if (file_exists($file))
{
include_once $file;
if (!class_exists($class, false) &&
!interface_exists($class, false))
{
throw new Exception('File '.$file.' was loaded but class '.$class.' was not found');
}
}
}
A: What your looking for is Automap PECL extension.
It basically allows for auto loading with only a small overhead of loading a pre-computed map file. You can also sub divide the map file if you know a specific directory will only pull from certain PHP files.
You can read more about it here.
A: It's been a while since I used php, but shouldn't the Zend Optimizer or Cache help in this case? Does php still load & compile every included file again for every request?
I'm not sure if autoloading is the answer. If these files are included, they are probably needed in the class including it, so they will still be autoloaded anyway.
A: Use a byte code cache (ideally APC) so that PHP doesn't need to parse the libraries on each page load. Be aware that using autoload will negate the benefits of using a byte code cache (you can read more about this here).
A: Use a profiler. If you try to optimise without having measures, you're working blind.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best Java Obfuscation Application For Size Reduction An important part of mobile development, especially when you are talking about mobile games, is dealing with the application size restrictions. Some devices enforce their own size limits, while all the carriers have their own size requirements for applications to be released in their deck space.
My question is, is there a java obfuscation application that gets better size reduction results than the other java obfuscation apps that are out there?
I use Proguard because it is the default Netbeans obfuscator and you can get fairly good size reduction results out of it (by the way, the version of Proguard that comes with Netbeans 6.1 is 3.7. There are newer versions that get even better results, I recommend getting the latest). But, I'm interested in what else is out there and whether they do a better job than Proguard.
My Conclusion:
I appreciate the responses. Carlos, your response was enough to convince me that Proguard is the current way to go. I could still be convinced otherwise, but don't feel bad with my current setup.
I have also had some issues with proguard obfuscating and running on some phones, but not too many. I was always able to fix the problem by not using the Proguard argument "-overloadaggressively". Just something to keep in mind if you are experiencing odd behavior related to obfuscating.
Thanks again.
A: I also prefer ProGuard for both it's size reduction and breadth of obfuscation - see http://proguard.sourceforge.net/. I don't necessarily have size constraints other than download speeds, but haven't found anything that shrinks further.
A: When it comes to J2ME and obfuscation it pays to be a bit cautious. Proguard is the best choice because of the many years it has been in development, and the many bugfixes that it has received. I remember the version transition between 2.X and 3.X and how it broke many of my (then) employer builds. This happened because some of the changes that enabled more size savings also broke the class files in subtle ways in some handsets, while being perfectly fine in others and on desktop JVMs.
Nowadays Proguard 3.11 is the safest choice in obfuscators. 4.XX is probably fine if you don't have to support very old handsets.
A: Strange that no one remembered that ProGuard can not just shrink and obfuscate the code, but optimize as well. The last versions allow to specify several passes for optimization (by default there is a single pass), I may specify, say, 9 passes.
After I decompile my classes I can hardly recognise them, ProGuard restructures a lot of method calls. All it takes is just a bit of tweaking this wonderful app. So I think ProGuard is the way to go, just don't forget to adjust it a little. It also has a very nice manual.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Stack overflow from .NET code in IIS, but not in Winforms So I have a nasty stack overflow I have been trying to track down / solve for the past 8 hours or so, and I'm at the point where i think i need advice.
The details:
Interestingly enough this code runs fine when called in the context of our regular winforms application -- but I am tasked with writing a web-based version of our software, and this same exact code causes the stack overflow when called out of an ASPX page running on IIS. The first thing I did was attach and attempt normal .NET debugging through visual studio. At the point of the exception the call stack seemed relatively shallow (about 11 frames deep, of our code), and I could find none of the usual suspects on a stack overflow (bad recursion, self-calling constructors, exception loops).
So I resigned myself to breaking out windbg and S.O.S. -- which i know can be useful for this sort of thing, although I had limited experience with it myself. After hours of monkeying around I think I have some useful data, but I need some help analyzing it.
First up is a !dumpstack I took while broken just before the stack overflow was about to come down.
0:015> !dumpstack
PDB symbol for mscorwks.dll not loaded
OS Thread Id: 0x1110 (15)
Current frame: ntdll!KiFastSystemCallRet
ChildEBP RetAddr Caller,Callee
01d265a8 7c827d0b ntdll!NtWaitForSingleObject+0xc
01d265ac 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d2661c 79e789c6 mscorwks!LogHelp_NoGuiOnAssert+0x58ca
01d26660 79e7898f mscorwks!LogHelp_NoGuiOnAssert+0x5893, calling mscorwks!LogHelp_NoGuiOnAssert+0x589b
01d26680 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d26694 79fc1d6b mscorwks!CorExeMain+0x8724, calling kernel32!InterlockedDecrement
01d26698 79ef3892 mscorwks!GetCLRFunction+0x107de, calling mscorwks+0x17c0
01d266b0 79e78944 mscorwks!LogHelp_NoGuiOnAssert+0x5848, calling mscorwks!LogHelp_NoGuiOnAssert+0x584c
01d266c4 7a14de5d mscorwks!CorLaunchApplication+0x2f243, calling mscorwks!LogHelp_NoGuiOnAssert+0x5831
01d266ec 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d266f8 77e61d43 kernel32!WaitForSingleObjectEx+0xad, calling kernel32!GetTickCount+0x73
01d26714 7c8279bb ntdll!NtSetEvent+0xc
01d26718 77e62321 kernel32!SetEvent+0x10, calling ntdll!NtSetEvent
01d26748 7a14df79 mscorwks!CorLaunchApplication+0x2f35f, calling mscorwks!CorLaunchApplication+0x2f17c
01d2675c 7a022dde mscorwks!NGenCreateNGenWorker+0x4516b, calling mscorwks!CorLaunchApplication+0x2f347
01d26770 79fbc685 mscorwks!CorExeMain+0x303e, calling mscorwks+0x1bbe
01d26788 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d2678c 79e734f2 mscorwks!LogHelp_NoGuiOnAssert+0x3f6, calling mscorwks!LogHelp_NoGuiOnAssert+0x380
01d267a8 7a2d259e mscorwks!CreateHistoryReader+0xafd3
01d267b4 7a2e6292 mscorwks!CreateHistoryReader+0x1ecc7, calling mscorwks!CreateHistoryReader+0xaf9d
01d26814 7a064d52 mscorwks!NGenCreateNGenWorker+0x870df, calling mscorwks!CreateHistoryReader+0x1eb43
01d26854 79f91643 mscorwks!ClrCreateManagedInstance+0x46ff, calling mscorwks!ClrCreateManagedInstance+0x4720
01d2688c 79f915c4 mscorwks!ClrCreateManagedInstance+0x4680
01d268b4 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d268cc 79f04e98 mscorwks!GetCLRFunction+0x21de4, calling mscorwks!GetCLRFunction+0x21e4b
01d26900 79f0815e mscorwks!GetCLRFunction+0x250aa, calling mscorwks!GetCLRFunction+0x21d35
01d2691c 7c858135 ntdll!RtlIpv4StringToAddressExW+0x167b7, calling ntdll!RtlReleaseResource
01d2692c 79f080a7 mscorwks!GetCLRFunction+0x24ff3, calling mscorwks!GetCLRFunction+0x25052
01d26950 7c828752 ntdll!RtlRaiseStatus+0xe0
01d26974 7c828723 ntdll!RtlRaiseStatus+0xb1, calling ntdll!RtlRaiseStatus+0xba
01d26998 7c8315c2 ntdll!RtlSubtreePredecessor+0x208, calling ntdll!RtlRaiseStatus+0x7e
01d26a1c 7c82855e ntdll!KiUserExceptionDispatcher+0xe, calling ntdll!RtlSubtreePredecessor+0x17c
01d26d20 13380333 (MethodDesc 0x10936710 +0x243 ASI.ParadigmPlus.LoadedWindows.WID904.QuestionChangeLogic(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Question)) ====> Exception Code 0 cxr@1d26a54 exr@1d26000
01d26bd8 77e64590 kernel32!VirtualAllocEx+0x4b, calling kernel32!GetTickCount+0x73
01d26bec 7c829f59 ntdll!RtlFreeHeap+0x142, calling ntdll!CIpow+0x464
01d26bf0 79e78d11 mscorwks!LogHelp_NoGuiOnAssert+0x5c15, calling ntdll!RtlFreeHeap
01d3e86c 103b4064 (MethodDesc 0xf304c90 +0x174 ASI.ParadigmPlus.Window.TrackQuestionChange(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Answer))
01d3e88c 103b4064 (MethodDesc 0xf304c90 +0x174 ASI.ParadigmPlus.Window.TrackQuestionChange(ASI.ParadigmPlus.Question, ASI.ParadigmPlus.Answer))
01d3e8b0 103b3e6b (MethodDesc 0xebb4b38 +0x23 ASI.CommonLibrary.ASIArrayList3.get_Item(Int32))
01d3e8d4 103b3d70 (MethodDesc 0xf304e98 +0x1b0 ASI.ParadigmPlus.Window.TrackQuestionChange())
01d3e910 0f90febf (MethodDesc 0xf30d250 +0x190f ASI.ParadigmPlus.Data.RemoteDataAccess.GetWindow(Int32))
01d3ec0c 10a2a572 (MethodDesc 0x10935aa0 +0x1f2 ASI.ParadigmPlus.LoadedWindowSets.WSID904.ApplyLayoutChanges()), calling 02259472
01d3ecec 0f90c880 (MethodDesc 0xebb91f8 +0xe8 ASI.ParadigmPlus.Windowset.ApplyLayoutChangesWrap())
01d3ed0c 0f90c880 (MethodDesc 0xebb91f8 +0xe8 ASI.ParadigmPlus.Windowset.ApplyLayoutChangesWrap())
01d3ed54 0f4d2388 (MethodDesc 0x22261a0 +0x5e8 WebConfigurator.NewDefault.ProductSelectedIndexChange(Int32, Int32))
01d3f264 0f4d1d7f (MethodDesc 0x2226180 +0x47 WebConfigurator.NewDefault.btnGo_Click1(System.Object, System.EventArgs)), calling (MethodDesc 0x22261a0 +0 WebConfigurator.NewDefault.ProductSelectedIndexChange(Int32, Int32))
01d3f284 0e810a05 (MethodDesc 0x22260f8 +0x145 WebConfigurator.NewDefault.Page_Load(System.Object, System.EventArgs)), calling (MethodDesc 0x2226180 +0 WebConfigurator.NewDefault.btnGo_Click1(System.Object, System.EventArgs))
01d3f2a8 793ae896 (MethodDesc 0x79256848 +0x52 System.MulticastDelegate.RemoveImpl(System.Delegate))
01d3f2ac 79e7bee8 mscorwks!LogHelp_TerminateOnAssert+0x2bd0, calling mscorwks!LogHelp_TerminateOnAssert+0x2b60
01d3f2c4 66f12980 (MethodDesc 0x66f1bcd0 +0x10 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr, System.Object, System.Object, System.EventArgs))
01d3f2d0 6628efd2 (MethodDesc 0x66474328 +0x22 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(System.Object, System.EventArgs)), calling (MethodDesc 0x66f1bcd0 +0 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr, System.Object, System.Object, System.EventArgs))
01d3f2e4 6613cb04 (MethodDesc 0x66468a58 +0x64 System.Web.UI.Control.OnLoad(System.EventArgs))
01d3f2f8 6613cb50 (MethodDesc 0x66468a60 +0x30 System.Web.UI.Control.LoadRecursive())
01d3f30c 6614e12d (MethodDesc 0x66467688 +0x59d System.Web.UI.Page.ProcessRequestMain(Boolean, Boolean))
01d3f4e0 6614c717 (MethodDesc 0x66467430 +0x63 System.Web.UI.Page.AddWrappedFileDependencies(System.Object)), calling (MethodDesc 0x66478de8 +0 System.Web.ResponseDependencyList.AddDependencies(System.String[], System.String, Boolean, System.String))
01d3f504 6614d8c3 (MethodDesc 0x66467650 +0x67 System.Web.UI.Page.ProcessRequest(Boolean, Boolean)), calling (MethodDesc 0x66467688 +0 System.Web.UI.Page.ProcessRequestMain(Boolean, Boolean))
01d3f528 79371311 (MethodDesc 0x7925ac80 +0x25 System.Globalization.CultureInfo.get_UserDefaultUICulture()), calling (JitHelp: CORINFO_HELP_GETSHARED_GCSTATIC_BASE)
01d3f53c 6614d80f (MethodDesc 0x66467648 +0x57 System.Web.UI.Page.ProcessRequest()), calling (MethodDesc 0x66467650 +0 System.Web.UI.Page.ProcessRequest(Boolean, Boolean))
01d3f560 6615055c (MethodDesc 0x664676f0 +0x184 System.Web.UI.Page.SetIntrinsics(System.Web.HttpContext, Boolean)), calling (MethodDesc 0x664726b0 +0 System.Web.UI.TemplateControl.HookUpAutomaticHandlers())
01d3f578 6614d72f (MethodDesc 0x66467630 +0x13 System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext)), calling (MethodDesc 0x66467648 +0 System.Web.UI.Page.ProcessRequest())
01d3f580 6614d6c2 (MethodDesc 0x66467620 +0x32 System.Web.UI.Page.ProcessRequest(System.Web.HttpContext)), calling (MethodDesc 0x66467630 +0 System.Web.UI.Page.ProcessRequestWithNoAssert(System.Web.HttpContext))
01d3f594 0e810206 (MethodDesc 0x22265a0 +0x1e ASP.newdefault_aspx.ProcessRequest(System.Web.HttpContext)), calling (MethodDesc 0x66467620 +0 System.Web.UI.Page.ProcessRequest(System.Web.HttpContext))
01d3f5a0 65fe6bfb (MethodDesc 0x66470fc0 +0x167 System.Web.HttpApplication+CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()), calling 01dee5da
01d3f5d4 65fe3f51 (MethodDesc 0x6642f090 +0x41 System.Web.HttpApplication.ExecuteStep(IExecutionStep, Boolean ByRef)), calling 01de7d0a
01d3f610 65fe7733 (MethodDesc 0x66470cd0 +0x1b3 System.Web.HttpApplication+ApplicationStepManager.ResumeSteps(System.Exception)), calling (MethodDesc 0x6642f090 +0 System.Web.HttpApplication.ExecuteStep(IExecutionStep, Boolean ByRef))
01d3f64c 7939eef2 (MethodDesc 0x7925eda8 +0x26 System.Runtime.InteropServices.GCHandle.Alloc(System.Object)), calling mscorwks!InstallCustomModule+0x1e8d
01d3f664 65fccbfe (MethodDesc 0x6642ebb0 +0x8e System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext, System.AsyncCallback, System.Object))
01d3f678 65fd19c5 (MethodDesc 0x6642cde8 +0x1b5 System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest)), calling 01de7cba
01d3f69c 7938111c (MethodDesc 0x79262df0 +0xc System.DateTime.get_UtcNow()), calling mscorwks!GetCLRFunction+0x109f9
01d3f6a4 01c32cbc 01c32cbc, calling 01daa248
01d3f6b4 65fd16b2 (MethodDesc 0x664619e0 +0x62 System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest)), calling (MethodDesc 0x6642cde8 +0 System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest))
01d3f6c0 65fcfa6d (MethodDesc 0x6642d4a0 +0xfd System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr, Int32)), calling (MethodDesc 0x664619e0 +0 System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest))
01d3f6d8 65fcf9f4 (MethodDesc 0x6642d4a0 +0x84 System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr, Int32)), calling *** ERROR: Symbol file could not be found. Defaulted to export symbols for \\?\C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\webengine.dll -
webengine!GetEcb
01d3f710 79f047fd mscorwks!GetCLRFunction+0x21749
01d3f720 01c32cbc 01c32cbc, calling 01daa248
01d3f730 79f047fd mscorwks!GetCLRFunction+0x21749
01d3f75c 79f01621 mscorwks!GetCLRFunction+0x1e56d, calling mscorwks+0x1b86
01d3f770 79ef98cf mscorwks!GetCLRFunction+0x1681b, calling mscorwks!GetCLRFunction+0x1682f
01d3f7d0 79e74f98 mscorwks!LogHelp_NoGuiOnAssert+0x1e9c, calling mscorwks!LogHelp_NoGuiOnAssert+0x1ec1
01d3f7e8 79f0462c mscorwks!GetCLRFunction+0x21578, calling mscorwks!GetCLRFunction+0x215b0
01d3f7f8 01c32cbc 01c32cbc, calling 01daa248
01d3f844 79f044fa mscorwks!GetCLRFunction+0x21446, calling mscorwks!GetCLRFunction+0x21541
01d3f854 01c32cbc 01c32cbc, calling 01daa248
01d3f898 660167e9 (MethodDesc 0x6646f6b0 +0x5 System.Web.RequestQueue.TimerCompletionCallback(System.Object)), calling (MethodDesc 0x6646f698 +0 System.Web.RequestQueue.ScheduleMoreWorkIfNeeded())
01d3f89c 793af6c6 (MethodDesc 0x792672b0 +0x1a System.Threading._TimerCallback.TimerCallback_Context(System.Object))
01d3f8b4 793af647 (MethodDesc 0x7914fc18 +0x5b System.Threading._TimerCallback.PerformTimerCallback(System.Object)), calling (MethodDesc 0x7914e0d8 +0 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object))
01d3f8b8 793af654 (MethodDesc 0x7914fc18 +0x68 System.Threading._TimerCallback.PerformTimerCallback(System.Object)), calling mscorwks!LogHelp_TerminateOnAssert
01d3f8f8 79e74466 mscorwks!LogHelp_NoGuiOnAssert+0x136a, calling mscorwks+0x1813
01d3f8fc 79e7c709 mscorwks!LogHelp_TerminateOnAssert+0x33f1, calling mscorwks!LogHelp_NoGuiOnAssert+0x1360
01d3f964 7c829f3d ntdll!RtlFreeHeap+0x126, calling ntdll!RtlGetNtGlobalFlags+0x12
01d3f96c 7c829f59 ntdll!RtlFreeHeap+0x142, calling ntdll!CIpow+0x464
01d3f9ac 6a2a9998 webengine!CSharelock::ChangeExclusiveLockToSharedLock+0x2d, calling kernel32!InterlockedCompareExchange
01d3f9b4 6a2ab03b webengine!EcbGetUnicodeServerVariables+0x3d5, calling kernel32!InterlockedIncrement
01d3f9f4 01c32cbc 01c32cbc, calling 01daa248
01d3fa28 01daa295 01daa295, calling mscorwks!GetCLRFunction+0x2119e
01d3fa50 6a2aa63f webengine!CookieAuthConstructTicket+0x232
01d3fa6c 01c32cbc 01c32cbc, calling 01daa248
01d3fa70 6a2aa63f webengine!CookieAuthConstructTicket+0x232
01d3fac8 79e734c4 mscorwks!LogHelp_NoGuiOnAssert+0x3c8, calling mscorwks+0x17c0
01d3facc 79e734f2 mscorwks!LogHelp_NoGuiOnAssert+0x3f6, calling mscorwks!LogHelp_NoGuiOnAssert+0x380
01d3fad8 79f00c03 mscorwks!GetCLRFunction+0x1db4f, calling mscorwks!LogHelp_NoGuiOnAssert+0xf0
01d3fadc 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fae0 79f00c0b mscorwks!GetCLRFunction+0x1db57, calling mscorwks+0x1b86
01d3fb1c 79ef30c3 mscorwks!GetCLRFunction+0x1000f, calling mscorwks!GetCLRFunction+0x10040
01d3fb64 79f00c0b mscorwks!GetCLRFunction+0x1db57, calling mscorwks+0x1b86
01d3fb68 79f02a93 mscorwks!GetCLRFunction+0x1f9df, calling mscorwks!GetCLRFunction+0x1d8e5
01d3fb70 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fb74 79f02aa7 mscorwks!GetCLRFunction+0x1f9f3, calling mscorwks+0x1b86
01d3fb88 79f00e8d mscorwks!GetCLRFunction+0x1ddd9, calling mscorwks+0x18bb
01d3fb8c 79f00f03 mscorwks!GetCLRFunction+0x1de4f, calling mscorwks!GetCLRFunction+0x1dd84
01d3fbc0 79f02978 mscorwks!GetCLRFunction+0x1f8c4, calling mscorwks!GetCLRFunction+0x1de1a
01d3fbfc 79e73220 mscorwks!LogHelp_NoGuiOnAssert+0x124, calling (JitHelp: CORINFO_HELP_GET_THREAD)
01d3fc08 79ef2884 mscorwks!GetCLRFunction+0xf7d0, calling mscorwks!LogHelp_NoGuiOnAssert+0x118
01d3fc0c 79ef28ab mscorwks!GetCLRFunction+0xf7f7, calling mscorwks+0x17c0
01d3fc24 79e7904f mscorwks!LogHelp_NoGuiOnAssert+0x5f53, calling mscorwks+0x1b95
01d3fc38 79ef31ca mscorwks!GetCLRFunction+0x10116, calling mscorwks!LogHelp_NoGuiOnAssert+0x5f3d
01d3fc3c 79e71b90 mscorwks+0x1b90, calling mscorwks+0x1813
01d3fc40 79ef31d9 mscorwks!GetCLRFunction+0x10125, calling mscorwks+0x1b86
01d3fc90 7c829fb5 ntdll!RtlGetNtGlobalFlags+0x38, calling ntdll!ExpInterlockedPopEntrySListEnd+0x11
01d3fc94 7c827d0b ntdll!NtWaitForSingleObject+0xc
01d3fc98 77e61d1e kernel32!WaitForSingleObjectEx+0x88, calling ntdll!NtWaitForSingleObject
01d3fca4 77e61d43 kernel32!WaitForSingleObjectEx+0xad, calling kernel32!GetTickCount+0x73
01d3fdb4 6a2aa748 webengine!CookieAuthConstructTicket+0x33b, calling webengine!CookieAuthConstructTicket+0x11d
01d3fdc4 6a2aa715 webengine!CookieAuthConstructTicket+0x308
01d3fddc 79f024cf mscorwks!GetCLRFunction+0x1f41b
01d3fdf4 79ef3a3f mscorwks!GetCLRFunction+0x1098b, calling mscorwks+0x17c0
01d3fe28 79f0202a mscorwks!GetCLRFunction+0x1ef76
01d3fe3c 79f021a0 mscorwks!GetCLRFunction+0x1f0ec, calling mscorwks!GetCLRFunction+0x1eef9
01d3fe94 79fc9840 mscorwks!CorExeMain+0x101f9
01d3ffa4 79fc982e mscorwks!CorExeMain+0x101e7, calling mscorwks!LogHelp_NoGuiOnAssert+0x61c0
01d3ffb8 77e64829 kernel32!GetModuleHandleA+0xdf
Lot of stuff there, but nothing that in my (admittedly limited) stack analyzing knowledge indicates looping. I think this next section might have some value however. This is a !dumpstackobjects I got at the same breakpoint:
0:000> ~16e !dumpstackobjects
OS Thread Id: 0x172c (16)
ESP/REG Object Name
01d0ee30 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef68 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef6c 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0ef74 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d0f280 0295f810 ASI.ParadigmPlus.Question
01d0f284 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d26cec 02fdb36c ASI.ParadigmPlus.GrilleApp.GA1000
01d26cf0 0295f674 ASI.ParadigmPlus.QuestionList
01d26cf4 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d26cf8 02fdb36c ASI.ParadigmPlus.GrilleApp.GA1000
01d26cfc 0295f810 ASI.ParadigmPlus.Question
01d26d00 0295f810 ASI.ParadigmPlus.Question
01d26d08 0295f810 ASI.ParadigmPlus.Question
01d26d30 06c3a958 System.String SP1:SP1
01d26d40 029c232c System.String TNE:TNE
01d26d50 06c3a958 System.String SP1:SP1
01d26d54 029c232c System.String TNE:TNE
01d26d60 029c232c System.String TNE:TNE
01d26d78 06c3a958 System.String SP1:SP1
01d26d7c 06c3a958 System.String SP1:SP1
01d26d84 06c3a958 System.String SP1:SP1
01d26da4 06c357a0 System.String SB1:SB1
01d26da8 06c357a0 System.String SB1:SB1
01d26db0 06c3a958 System.String SP1:SP1
01d26db4 06ba3d08 System.String WHT:WHT
01d26db8 06b987c8 System.String WHT:WHT
01d26dbc 06b8aa10 System.String WF:WF
01d26dc0 029fab00 System.String L:L
01d26dc4 06c3a958 System.String SP1:SP1
01d26dc8 06c4a518 System.String S000:S000
01d26dd4 06c4a518 System.String S000:S000
01d26dd8 0296b404 ASI.ParadigmPlus.Question
01d26ddc 0296a00c ASI.ParadigmPlus.Question
01d26de0 02968a90 ASI.ParadigmPlus.Question
01d26de4 02966af8 ASI.ParadigmPlus.Question
01d26de8 06be6e1c ASI.ParadigmPlus.Answer
01d26dec 06c357a0 System.String SB1:SB1
01d26df0 029fab00 System.String L:L
01d26df4 0295fa54 ASI.ParadigmPlus.QuestionGroup
01d26df8 02963f80 ASI.ParadigmPlus.QuestionGroup
01d26dfc 029662fc ASI.ParadigmPlus.QuestionGroup
01d26e00 02961cb4 ASI.ParadigmPlus.QuestionGroup
01d26e0c 0295f810 ASI.ParadigmPlus.Question
01d26e10 0295ef60 ASI.ParadigmPlus.LoadedWindows.WID904
01d270d4 06c38ddc ASI.ParadigmPlus.Answer
01d270dc 06c4bc0c ASI.ParadigmPlus.Dimension
01d270e0 06c4b99c ASI.ParadigmPlus.DimensionList
01d27104 029607f8 ASI.ParadigmPlus.Question
01d27108 0295fa80 ASI.ParadigmPlus.QuestionList
01d27118 06c38e74 System.String 5:5
01d2711c 02960564 ASI.ParadigmPlus.Question
01d27120 0295fa80 ASI.ParadigmPlus.QuestionList
01d2781c 029fac84 ASI.ParadigmPlus.Answer
01d27820 02960464 ASI.ParadigmPlus.AnswerList
01d27824 029fcbd8 ASI.ParadigmPlus.Answer
01d27828 02960464 ASI.ParadigmPlus.AnswerList
01d2782c 029fca28 ASI.ParadigmPlus.Answer
01d27830 02960464 ASI.ParadigmPlus.AnswerList
01d27844 029faa84 ASI.ParadigmPlus.Answer
01d2784c 06c38e74 System.String 5:5
01d27850 02960564 ASI.ParadigmPlus.Question
01d27854 0295fa80 ASI.ParadigmPlus.QuestionList
01d27860 06c38e74 System.String 5:5
01d27864 02960564 ASI.ParadigmPlus.Question
01d27868 0295fa80 ASI.ParadigmPlus.QuestionList
01d27870 06c38e74 System.String 5:5
01d27874 02960564 ASI.ParadigmPlus.Question
01d27878 0295fa80 ASI.ParadigmPlus.QuestionList
01d2787c 029faa84 ASI.ParadigmPlus.Answer
01d27880 02960464 ASI.ParadigmPlus.AnswerList
01d27884 029fab84 ASI.ParadigmPlus.Answer
01d27888 02960464 ASI.ParadigmPlus.AnswerList
01d27974 02960e80 ASI.ParadigmPlus.Question
01d27978 0295fa80 ASI.ParadigmPlus.QuestionList
01d27bd0 06c3a8dc ASI.ParadigmPlus.Answer
01d27c08 06c3b924 ASI.ParadigmPlus.Answer
01d27c0c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c10 06c3b860 ASI.ParadigmPlus.Answer
01d27c14 02960f44 ASI.ParadigmPlus.AnswerList
01d27c18 06c3ac90 ASI.ParadigmPlus.Answer
01d27c1c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c20 06c3abcc ASI.ParadigmPlus.Answer
01d27c24 02960f44 ASI.ParadigmPlus.AnswerList
01d27c28 06c3ab08 ASI.ParadigmPlus.Answer
01d27c2c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c30 06c3aa44 ASI.ParadigmPlus.Answer
01d27c34 02960f44 ASI.ParadigmPlus.AnswerList
01d27c38 06c3b4dc ASI.ParadigmPlus.Answer
01d27c3c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c40 06c3a990 ASI.ParadigmPlus.Answer
01d27c44 02960f44 ASI.ParadigmPlus.AnswerList
01d27c48 06c3a8dc ASI.ParadigmPlus.Answer
01d27c4c 02960f44 ASI.ParadigmPlus.AnswerList
01d27c6c 02960e80 ASI.ParadigmPlus.Question
01d27c70 0295fa80 ASI.ParadigmPlus.QuestionList
01d27e04 029628d0 ASI.ParadigmPlus.Question
01d27e08 02961ce0 ASI.ParadigmPlus.QuestionList
01d27e28 029628d0 ASI.ParadigmPlus.Question
01d27e2c 02961ce0 ASI.ParadigmPlus.QuestionList
01d27f14 06b89804 ASI.ParadigmPlus.Answer
01d27f18 02962994 ASI.ParadigmPlus.AnswerList
01d27f1c 029628d0 ASI.ParadigmPlus.Question
01d27f20 02961ce0 ASI.ParadigmPlus.QuestionList
01d27f38 06c38e74 System.String 5:5
01d27f3c 02960564 ASI.ParadigmPlus.Question
01d27f40 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f4c 06c38e74 System.String 5:5
01d27f50 02960564 ASI.ParadigmPlus.Question
01d27f54 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f60 06c38e74 System.String 5:5
01d27f64 02960564 ASI.ParadigmPlus.Question
01d27f68 0295fa80 ASI.ParadigmPlus.QuestionList
01d27f88 06b89964 ASI.ParadigmPlus.Answer
01d27f8c 029628d0 ASI.ParadigmPlus.Question
01d27f90 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fa8 06c4b34c System.String FDIA:FDIA
01d27fac 0295fd84 ASI.ParadigmPlus.Question
01d27fb0 0295fa80 ASI.ParadigmPlus.QuestionList
01d27fb4 06b896dc ASI.ParadigmPlus.Answer
01d27fb8 02962994 ASI.ParadigmPlus.AnswerList
01d27fbc 029628d0 ASI.ParadigmPlus.Question
01d27fc0 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fc8 029fab00 System.String L:L
01d27fcc 029603a0 ASI.ParadigmPlus.Question
01d27fd0 0295fa80 ASI.ParadigmPlus.QuestionList
01d27fd4 06b89964 ASI.ParadigmPlus.Answer
01d27fd8 02962994 ASI.ParadigmPlus.AnswerList
01d27fdc 029628d0 ASI.ParadigmPlus.Question
01d27fe0 02961ce0 ASI.ParadigmPlus.QuestionList
01d27fe4 029628d0 ASI.ParadigmPlus.Question
01d27fe8 02961ce0 ASI.ParadigmPlus.QuestionList
01d28610 06b987c8 System.String WHT:WHT
01d28614 02961dd8 ASI.ParadigmPlus.Question
01d28618 02961ce0 ASI.ParadigmPlus.QuestionList
01d2872c 06ba3d08 System.String WHT:WHT
01d28730 029621f0 ASI.ParadigmPlus.Question
01d28734 02961ce0 ASI.ParadigmPlus.QuestionList
01d28778 029f1d94 ASI.ParadigmPlus.Answer
01d2877c 02963c14 ASI.ParadigmPlus.AnswerList
01d28780 06c37884 ASI.ParadigmPlus.Answer
01d28784 02963c14 ASI.ParadigmPlus.AnswerList
01d28788 06c379cc ASI.ParadigmPlus.Answer
01d2878c 02963c14 ASI.ParadigmPlus.AnswerList
01d28790 06c36798 ASI.ParadigmPlus.Answer
01d28794 02963c14 ASI.ParadigmPlus.AnswerList
01d28798 06c36510 ASI.ParadigmPlus.Answer
01d2879c 02963c14 ASI.ParadigmPlus.AnswerList
01d287a0 06c36648 ASI.ParadigmPlus.Answer
01d287a4 02963c14 ASI.ParadigmPlus.AnswerList
01d287ac 06c37a78 System.String Custom Paint
01d287b0 06c379cc ASI.ParadigmPlus.Answer
01d287b8 072eb468 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d287bc 02963c14 ASI.ParadigmPlus.AnswerList
01d289dc 029640b8 ASI.ParadigmPlus.Question
01d289e0 02963fac ASI.ParadigmPlus.QuestionList
01d28a38 029f13f4 System.String Venting Sidelite Locking System
01d28a3c 029f1390 ASI.ParadigmPlus.Answer
01d28a44 072f0568 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d28a48 0296417c ASI.ParadigmPlus.AnswerList
01d28a60 06c356f4 ASI.ParadigmPlus.Answer
01d28a68 06c4a518 System.String S000:S000
01d28a6c 0295ffec ASI.ParadigmPlus.Question
01d28a70 0295fa80 ASI.ParadigmPlus.QuestionList
01d28a7c 06c4a518 System.String S000:S000
01d28a80 0295ffec ASI.ParadigmPlus.Question
01d28a84 0295fa80 ASI.ParadigmPlus.QuestionList
01d28a90 0295f768 System.String CustItemNumber
01d28a98 06c4b34c System.String FDIA:FDIA
01d28a9c 0295fd84 ASI.ParadigmPlus.Question
01d28aa0 0295fa80 ASI.ParadigmPlus.QuestionList
01d28aa4 029ecd64 ASI.ParadigmPlus.Answer
01d28aa8 0296417c ASI.ParadigmPlus.AnswerList
01d28aac 029e95ac ASI.ParadigmPlus.Answer
01d28ab0 0296417c ASI.ParadigmPlus.AnswerList
01d28ab8 029f13f4 System.String Venting Sidelite Locking System
01d28abc 029f1390 ASI.ParadigmPlus.Answer
01d28ac4 072ef574 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d28ac8 0296417c ASI.ParadigmPlus.AnswerList
01d28acc 029f1230 ASI.ParadigmPlus.Answer
01d28ad0 0296417c ASI.ParadigmPlus.AnswerList
01d28f4c 02961798 ASI.ParadigmPlus.Question
01d28f50 0295fa80 ASI.ParadigmPlus.QuestionList
01d2903c 0296466c ASI.ParadigmPlus.Question
01d29040 02963fac ASI.ParadigmPlus.QuestionList
01d290cc 06c07914 System.String C:C
01d290d0 02964268 ASI.ParadigmPlus.Question
01d290d4 02963fac ASI.ParadigmPlus.QuestionList
01d29144 06c30604 ASI.ParadigmPlus.Answer
01d29148 02964730 ASI.ParadigmPlus.AnswerList
01d2914c 0296466c ASI.ParadigmPlus.Question
01d29150 02963fac ASI.ParadigmPlus.QuestionList
01d29154 06c0f9d8 ASI.ParadigmPlus.Answer
01d29158 0296450c ASI.ParadigmPlus.AnswerList
01d2915c 02964448 ASI.ParadigmPlus.Question
01d29160 02963fac ASI.ParadigmPlus.QuestionList
01d29164 02964268 ASI.ParadigmPlus.Question
01d29168 02963fac ASI.ParadigmPlus.QuestionList
01d2991c 029d6c7c System.String 021022
01d29928 029d6c7c System.String 021022
01d29934 029d6c7c System.String 021022
01d29938 029d5700 ASI.ParadigmPlus.Answer
01d2993c 0296450c ASI.ParadigmPlus.AnswerList
01d29940 029d6bdc ASI.ParadigmPlus.Answer
01d29944 0296450c ASI.ParadigmPlus.AnswerList
01d29948 02964448 ASI.ParadigmPlus.Question
01d2994c 02963fac ASI.ParadigmPlus.QuestionList
01d2f908 06c4b34c System.String FDIA:FDIA
01d2f90c 0295fd84 ASI.ParadigmPlus.Question
01d2f910 0295fa80 ASI.ParadigmPlus.QuestionList
01d2ffd0 02964c28 ASI.ParadigmPlus.Question
01d2ffd4 02963fac ASI.ParadigmPlus.QuestionList
01d2ffe4 06c32030 System.String SB:SB
01d2ffe8 02964a54 ASI.ParadigmPlus.Question
01d2ffec 02963fac ASI.ParadigmPlus.QuestionList
01d2fffc 06c3368c ASI.ParadigmPlus.Answer
01d30000 02964b18 ASI.ParadigmPlus.AnswerList
01d30004 02964a54 ASI.ParadigmPlus.Question
01d30008 02963fac ASI.ParadigmPlus.QuestionList
01d3000c 02964a54 ASI.ParadigmPlus.Question
01d30010 02963fac ASI.ParadigmPlus.QuestionList
01d30144 06c32030 System.String SB:SB
01d30148 02964a54 ASI.ParadigmPlus.Question
01d3014c 02963fac ASI.ParadigmPlus.QuestionList
01d30154 06c31f90 ASI.ParadigmPlus.Answer
01d3015c 06c344d8 System.String (COM) Lifetime Brass
01d30160 06c34418 ASI.ParadigmPlus.Answer
01d30168 072f16a0 System.Collections.ArrayList+ArrayListEnumeratorSimple
01d3016c 02964b18 ASI.ParadigmPlus.AnswerList
01d30174 06c31f90 ASI.ParadigmPlus.Answer
01d30178 06c34294 ASI.ParadigmPlus.Answer
01d3017c 02964b18 ASI.ParadigmPlus.AnswerList
01d30180 06c33e48 ASI.ParadigmPlus.Answer
01d30184 02964b18 ASI.ParadigmPlus.AnswerList
01d30188 06c32e6c ASI.ParadigmPlus.Answer
01d3018c 02964b18 ASI.ParadigmPlus.AnswerList
01d30190 06c32b78 ASI.ParadigmPlus.Answer
01d30194 02964b18 ASI.ParadigmPlus.AnswerList
^^ I had to cut off some of the above to make this post fit, but imagine it keeps going like that ^^
Please ignore the details of our custom code. All this seems excessive to me, but I am no expert at the stack. Most of those stack objects listed above (there are 1500+) are not function paramteters, so I would think they do not belong there. Here is an example of the kind of code that is generating all those items on the stack (tons of code like this is run):
gUnitType.Questions("French Door Style").CommonLogicValue = CommonLogicValues.AlwaysDisplay
gUnitType.Questions("French Door Style").ShowAllAnswers()
If Me.NumberOfUnits > 1 Then
Me.Dimensions("Call Size Height").Answers("6-8 Handicap sill").Visible = False
Me.Dimensions("Call Size Height").Answers("6-10 Handicap Sill").Visible = False
Me.Dimensions("Call Size Height").Answers("7-0 Handicap Sill").Visible = False
Me.Dimensions("Call Size Height").Answers("8-0 Handicap Sill").Visible = False
End If
I am also no expert on VB (this code is from a different part of our application I do not normally work with), but is it normal for code like this to be filling up the stack with stuff? If anyone has any insight, or could even just point me in the direction of some resources with info about this kind of stuff, it would be greatly appreciated. Thanks for looking!
A: I thought I'd post back here with the resolution to this in case someone else runs into it. The replies above were all helpful, and pointed out why i might be overflowing the stack -- but the thing that I still couldn't come to grips with was why the exact same code ran fine in our winforms app.
What I eventually discovered was that at some point microsoft changed the stack size of IIS threads from 1MB (like in the general .NET context) to 256k. This explained everything, including the especially frustrating fact that even the ASPX version ran fine under the visual studio dev server. I resolved the problem by working with this particular customer to drastically cut the ammount of code in the QuestionChangeLogic function mentioned above (when I looked up the source, the function had > 15,000 lines!).
Thanks for the help guys.
A: You need some decent symbols for the CLR. Set _NT_SYMBOL_PATH (in WinDBG, use File/Symbol File Path) so that it includes:
SRV*C:\WebSymbols*http://msdl.microsoft.com/download/symbols
That tells the debugger symbol engine that it can download symbols from Microsoft's online symbol server to C:\WebSymbols. Pick another folder if you prefer them to be cached elsewhere.
It looks like Question, QuestionList, Answer, etc are structs - that is, value types - so they're allocated on the stack rather than on the heap. You may need to create your own class that wraps these types so they're on the heap instead.
A: According to stack object dump "ASI.ParadigmPlus.GrilleApp.GA1000" is 96872 bytes. You might want to figure out what that object is all about. That's a pretty big chunk of your stack space right there.
A: Analyzing the callstack I clearly see that the method that is causing this exception is:
ASI.ParadigmPlus.LoadedWindows.WID904.QuestionChangeLogic
How come you have 315 variables in this method? Isn't that too much?
"!clrstack -a" (after running "!dso") should give you much more information of each managed frame.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Newbie wants to create a PDF reader for ipod touch - what's the best approach? I want to make a small app that displays a PDF, presenting zoom-able single pages with a previous-next page function.
A: Based on the gradually evolving Apple policy of rejecting application submissions that duplicate functionality already on the iPhone I would worry about spending too much time even as a newbie on something that is part of the core iPhone feature-set.
A: The Core Graphics API is pretty much the same in Cocoa and Cocoa touch. Read up on CGPDFDocument, it should provide you with everything you will need to render PDF pages. You won't need to read the PDF spec or use a library to parse PDF files directly. You will probably to learn more about Core Graphics / Quartz 2D / etc. to understand how to use those functions inside of a Cocoa app.
A: This is pretty trivial. The CGPDFDocument functions will allow you to do anything you'd want to do with a PDF file.
A: The iPhone and iPod touch can view PDFs already, as one of the TV adverts in the UK shows an email with a .pdf attachment (of swimming lessons) being viewed. It can also view .doc, .xls, and so on, so if he is creating a viewer type application then supporting those as well could be a nice feature addition later on.
This means there is a PDF framework on these devices that you will need to access. Presumably Apple can provide support here if he is a paid up developer. Syncing the PDFs to the device is the actual real difficulty, as this isn't supported by iTunes. I assume that you would need to write a network based synchronisation tool, or have an online cloud for holding people's PDFs.
The device doesn't support Flash, so using PDF to Flash conversion tools will not work.
A: I found this HTML5 framework that should work on an iPad http://bakerframework.com/
but I didn't test it yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Does IBM WebSphere MQ support a 64 bit client on windows? I'm porting a C++ 32 bit application to 64 bit on windows. The application is a client of IBM WebSphere MQ. It uses the MQ client API.
Now, as the port progresses, I'm trying to find a 64 bit client. So far, no luck.
Does anyone here happen to know if where I can find one or confirm that there isn't one?
A: Websphere MQ 7 for Windows supports x86 and x64, but not Itanium 64-bit. It only officially supports Visual C++ 2005 for development at the moment but IBM usually issues PTFs for toleration on a regular basis so it shouldn't be too long before C++ 2008 support is there.
The statements of support and requirements are hosted on IBM web pages at http://www-01.ibm.com/support/docview.wss?rs=171&uid=swg27011920 if you're interested in further details.
A: Since this is getting lots of views, let's provide the direct link to the WMQ V7 client download. Note that it DOES support 64-bit Windows clients in some versions of Windows.
The System Requirements page for WMQ v7.0.1 now lists Visual Studio 2008 as supported.
Note that some of the supporting code is 32 bit so the client installs to the Program Files (x86) directory.
The IA94 SupportPac referenced by another poster implements the JMS API over C++ and the supported environments for that SupportPac are a subset of those for the WMQ client. If you are not using the SupportPac, refer to the link above for System Requirements instead.
A: I found this page on IBM's site: IA94: IBM Message Service Client for C/C++. On it there is a link to a readme.txt file which, under "Supported environments" lists "Windows 2003 Server x64 edition - Microsoft Visual C++ .NET 2005 Service Pack1".
Hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I initialize Zend_Form_Element_Select with a config array? I tried:
$form->addElement(
'select',
'salutation',
array(
'required' => true,
'options' => array(
'Mr.' => 'Mr.',
'Mrs.' => 'Mrs.',
'Ms.' => 'Ms.',
),
)
);
Then I print_r()ed the form, and options for salutation are empty. Does anybody know the correct spell for that? As far as I see, there's no documentation for Zend element configs' format.
A: You should use 'multiOptions' instead of 'options'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WSDL Generator for C# Does anyone know of a good tool to generate the WSDL for a service contract written in C# (i.e. set of methods that are tagged as "[OperationContract]" using WCF)? All the tools I've found work the other way around: create code stubs from a WSDL. I don't want to have to hand-jam a WSDL file. I've found tools for php and J2EE, but not C#. Thanks!
A: svcutil or just host it quickly and hit the MEX point :)
A: Easiest thing to do is host the service with a base address setup, and then just hit it from a browser with "?wsdl" appended to the end.
Here's an example of a service configuration with a base address specified. Note this goes in the <configuration><services> element in your config:
<service name="MyServiceName" behaviorConfiguration="MyServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9000/MyService"/>
</baseAddresses>
</host>
<endpoint address="net.tcp://localhost:9001/MyService"
binding="netTcpBinding"
contract="IMyService"
bindingConfiguration="MyServiceBinding"/>
</service>
Once you get it hosted, just go to http://localhost:9000/MyService?wsdl to see the WSDL definition.
A: Two ways:
a) Download wsdl file and do below steps:
i) Open visual studio command prompt as an administrator.
ii) Type below command:
wsdl.exe [path To Your WSDL File]
b) With endpoint:
i) Open Visual studio command prompt as an administrator.
ii) type below command:
wsdl.exe http://localhost:9000/MyService
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Create many constrained, random permutation of a list I need to make a random list of permutations. The elements can be anything but assume that they are the integers 0 through x-1. I want to make y lists, each containing z elements. The rules are that no list may contain the same element twice and that over all the lists, the number of times each elements is used is the same (or as close as possible). For instance, if my elements are 0,1,2,3, y is 6, and z is 2, then one possible solution is:
0,3
1,2
3,0
2,1
0,1
2,3
Each row has only unique elements and no element has been used more than 3 times. If y were 7, then 2 elements would be used 4 times, the rest 3.
A: This could be improved, but it seems to do the job (Python):
import math, random
def get_pool(items, y, z):
slots = y*z
use_each_times = slots/len(items)
exceptions = slots - use_each_times*len(items)
if (use_each_times > y or
exceptions > 0 and use_each_times+1 > y):
raise Exception("Impossible.")
pool = {}
for n in items:
pool[n] = use_each_times
for n in random.sample(items, exceptions):
pool[n] += 1
return pool
def rebalance(ret, pool, z):
max_item = None
max_times = None
for item, times in pool.items():
if times > max_times:
max_item = item
max_times = times
next, times = max_item, max_times
candidates = []
for i in range(len(ret)):
item = ret[i]
if next not in item:
candidates.append( (item, i) )
swap, swap_index = random.choice(candidates)
swapi = []
for i in range(len(swap)):
if swap[i] not in pool:
swapi.append( (swap[i], i) )
which, i = random.choice(swapi)
pool[next] -= 1
pool[swap[i]] = 1
swap[i] = next
ret[swap_index] = swap
def plist(items, y, z):
pool = get_pool(items, y, z)
ret = []
while len(pool.keys()) > 0:
while len(pool.keys()) < z:
rebalance(ret, pool, z)
selections = random.sample(pool.keys(), z)
for i in selections:
pool[i] -= 1
if pool[i] == 0:
del pool[i]
ret.append( selections )
return ret
print plist([0,1,2,3], 6, 2)
A: Ok, one way to approximate that:
1 - shuffle your list
2 - take the y first elements to form the next row
4 - repeat (2) as long as you have numbers in the list
5 - if you don't have enough numbers to finish the list, reshuffle the original list and take the missing elements, making sure you don't retake numbers.
6 - Start over at step (2) as long as you need rows
I think this should be as random as you can make it and will for sure follow your criteria. Plus, you have very little tests for duplicate elements.
A: First, you can always randomly sort the list in the end, so let's not worry about making "random permutations" (hard); and just worry about 1) making permutations (easy) and 2) randomizing them (easy).
If you want "truly" random groups, you have to accept that randomization by nature doesn't really allow for the constraint of "even distribution" of results -- you may get that or you may get a run of similar-looking ones. If you really want even distribution, first make the sets evenly distributed, and then randomize them as a group.
Do you have to use each element in the set x evenly? It's not clear from the rules that I couldn't just make the following interpretation:
Note the following: "over all the lists, the number of times each elements is used is the same (or as close as possible)"
Based on this criteria, and the rule that z < x*, I postulate that you can simply enumerate all the items over all the lists. So you automatically make y list of the items enumerated to position z. Your example doesn't fulfill the rule above as closely as my version will. Using your example of x={0,1,2,3} y=6 and z=2, I get:
0,1 0,1 0,1 0,1 0,1 0,1
Now I didn't use 2 or 3, but you didn't say I had to use them all. If I had to use them all and I don't care to be able to prove that I am "as close as possible" to even usage, I would just enumerate across all the items through the lists, like this:
0,1 2,3 0,1 2,3 0,1 2,3
Finally, suppose I really do have to use all the elements. To calculate how many times each element can repeat, I just take (y*z)/(count of x). That way, I don't have to sit and worry about how to divide up the items in the list. If there is a remainder, or the result is less than 1, then I know that I will not get an exact number of repeats, so in those cases, it doesn't much matter to try to waste computational energy to make it perfect. I contend that the fastest result is still to just enumerate as above, and use the calculation here to show why either a perfect result was or wasn't achieved. A fancy algorithm to extract from this calculation how many positions will be duplicates could be achieved, but "it's too long to fit here in the margin".
*Each list has the same z number of elements, so it will be impossible to make lists where z is greater than x and still fulfill the rule that no list may contain the same element twice. Therefore, this rule demands that z cannot be greater than x.
A: Based on new details in the comments, the solution may simply be an implementation of a standard random permutation generation algorithm. There is a lengthy discussion of random permutation generation algorithms here:
http://www.techuser.net/randpermgen.html
(From Google search: random permutation generation)
A: This works in Ruby:
# list is the elements to be permuted
# y is the number of results desired
# z is the number of elements per result
# equalizer keeps track of who got used how many times
def constrained_permutations list, y, z
list.uniq! # Never trust the user. We want no repetitions.
equalizer = {}
list.each { |element| equalizer[element] = 0 }
results = []
# Do this until we get as many results as desired
while results.size < y
pool = []
puts pool
least_used = equalizer.each_value.min
# Find how used the least used element was
while pool.size < z
# Do this until we have enough elements in this resultset
element = nil
while element.nil?
# If we run out of "least used elements", then we need to increment
# our definition of "least used" by 1 and keep going.
element = list.shuffle.find do |x|
!pool.include?(x) && equalizer[x] == least_used
end
least_used += 1 if element.nil?
end
equalizer[element] += 1
# This element has now been used one more time.
pool << element
end
results << pool
end
return results
end
Sample usage:
constrained_permutations [0,1,2,3,4,5,6], 6, 2
=> [[4, 0], [1, 3], [2, 5], [6, 0], [2, 5], [3, 6]]
constrained_permutations [0,1,2,3,4,5,6], 6, 2
=> [[4, 5], [6, 3], [0, 2], [1, 6], [5, 4], [3, 0]]
enter code here
A: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I set a timeout against a BufferedReader based upon a URLConnection in Java? I want to read the contents of a URL but don't want to "hang" if the URL is unresponsive. I've created a BufferedReader using the URL...
URL theURL = new URL(url);
URLConnection urlConn = theURL.openConnection();
urlConn.setDoOutput(true);
BufferedReader urlReader = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));
...and then begun the loop to read the contents...
do
{
buf = urlReader.readLine();
if (buf != null)
{
resultBuffer.append(buf);
resultBuffer.append("\n");
}
}
while (buf != null);
...but if the read hangs then the application hangs.
Is there a way, without grinding the code down to the socket level, to "time out" the read if necessary?
A: If you have java 1.4:
I assume the connection timeout (URLConnection.setConnectTimeout(int timeout) ) is of no use because you are doing some kind of streaming.
---Do not kill the thread--- It may cause unknown problems, open descriptors, etc.
Spawn a java.util.TimerTask where you will check if you have finished the process, otherwise, close the BufferedReader and the OutputStream of the URLConnection
Insert a boolean flag isFinished and set it to true at the end of your loop and to false before the loop
TimerTask ft = new TimerTask(){
public void run(){
if (!isFinished){
urlConn.getInputStream().close();
urlConn.getOutputStream().close();
}
}
};
(new Timer()).schedule(ft, timeout);
This will probably cause an ioexception, so you have to catch it. The exception is not a bad thing in itself.
I'm omitting some declarations (i.e. finals) so the anonymous class can access your variables. If not, then create a POJO that maintains a reference and pass that to the timertask
A: Since Java 1.5, it is possible to set the read timeout in milliseconds on the underlying socket via the 'setReadTimeout(int timeout)' method on the URLConnection class.
Note that there is also the 'setConnectTimeout(int timeout)' which will do the same thing for the initial connection to the remote server, so it is important to set that as well.
A: I think URLConnection.setReadTimeout is what you are looking for.
A: I have been working on this issue in a JVM 1.4 environment just recently. The stock answer is to use the system properties sun.net.client.defaultReadTimeout (read timeout) and/or sun.net.client.defaultConnectTimeout. These are documented at Networking Properties and can be set via the -D argument on the Java command line or via a System.setProperty method call.
Supposedly these are cached by the implementation so you can't change them from one thing to another so one they are used once, the values are retained.
Also they don't really work for SSL connections ala HttpsURLConnection. There are other ways to deal with that using a custom SSLSocketFactory.
Again, all this applies to JVM 1.4.x. At 1.5 and above you have more methods available to you in the API (as noted by the other responders above).
A: For Java 1.4, you may use SimpleHttpConnectionManager.getConnectionWithTimeout(hostConf,CONNECTION_TIMEOUT) from Apache
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Can I generate a Flex web and Air desktop app from the same source code? I'm new to Air. I've got an existing Flex 2 application which I'm considering bringing into Flexbuilder 3. My question is can I use the same base application (and source code) to make the Air version, or would I have to maintain to separate code trees: one for the Air version and one for the Flex/SWF version?
A: The best approach I've found to creating both Flex and AIR applications from the same source, is to use a core library project for almost all code, with separate small projects for the Flex and AIR applications.
There are two key concepts that make this very powerful and maintainable, allowing for not just two applications, but for many "editions" if you're so inclined.
*
*Modules:- If the core application is
actually a module (or a module that
loads other modules) you'll be able
to easily create stub Flex and AIR
applications that are basically
there to set project properties,
reference classes for cross-module
communication, and then simply load
the core application module with a
ModuleLoader.
*Factory Objects:- When there are
things you want to do on the AIR
desktop application that you can't
do in the Flex application, or any
case where you want something to
work differently across
applications, a factory object that
creates an instance of a project
specific class is a great way to do
it. for example, you can call your
"save" function, which for AIR saves
to the file system, but for Flex calls
a web service.
Have a look at Todd Prekaski's
excellent Flex DevNet article on
Building Flex and Adobe AIR
applications from the same code base
on how to do this.
Once you've created a Flex Library project where you're going to create your main module, create your Flex and AIR application projects. In the properties of the two application projects add the library project src directory to the Flex Build Path. While in the project settings you'll also need to add the modules to the Flex Modules section, setting the option to optimise for the project.
A: You can't mix both AIR and Flex in the same Flex Builder project, but you can share code. Here's how...
*
*Create a Flex based project as you
normally would.
*Create a second AIR based project.
*In the second application, go to
project->properties.
*Select the "Flex build path" option.
*Under "Source Path" add the folder
that contains the source from your
first Flex based project.
Now both projects share the code from the flex project.
You need to be careful not to use AIR only API's in code you intend to share between both apps.
A: You can use the same.
A: One way is to put the bulk of the application in a Group-based component in a library.
Both Flex and AIR applications can embed that component in their Window.
If you need to have custom code, have your Group component accept an Interface object that has all the methods that are specific to a platform (loadFile, saveFile, etc.). Each application injects an object that implements these methods appropriately.
I've worked on a product that injected a whole local-data access layer (to the SQLite database) and the core application had no idea if it was running in a browser or on the desktop (connected or disconnected).
Cheers
A: Create 3 project: Air, Web, and common. from air and web, include common.
http://simplifiedchaos.com/how-to-compile-both-flex-and-air-application
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Can I serve a ClickOnce application with Apache? We're testing our ClickOnce deployed application internally on IIS (Internet Information Services), but we're wondering if we can deploy it to the wider internet using Apache on Linux so we can make use of our existing external website host.
If so, is there anything else I need to consider other than as specifying the correct mime types such as .application and .deploy?
A: The Paul Clement article is the best description I've found. I also came across a topic in the Apache documentation that suggests putting the configuration in the httpd.conf file instead of .htaccess files. Here are the lines I added to my httpd.conf file:
AddType application/x-ms-application .application
AddType application/manifest .manifest
AddType application/octet-stream .deploy
A: I found a number of people asking the same question starting around 2005, but here is the first google result - also discusses silverlight.
http://software.clempaul.me.uk/articles/clickonce/
As far as I can tell, however, the only thing you would need to worry about would be setting up the mime types and providing access to the files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: OSX Security Framework NameAndPassword sample application I am investigating security plugins using SFAuthorizationPluginView under Mac OSX and as a first step looking at the NameAndPassword sample application. The app builds OK but I cannot get it to authenticate. So does anyone have any experience of SFAuthorizationPluginView or any other examples.
A: Does Debugging An Authorization Plug-In With Xcode help?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: test attribute in JSTL tag I saw some code like the following in a JSP
<c:if test="<%=request.isUserInRole(RoleEnum.USER.getCode())%>">
<li>user</li>
</c:if>
My confusion is over the "=" that appears in the value of the test attribute. My understanding was that anything included within <%= %> is printed to the output, but surely the value assigned to test must be a Boolean, so why does this work?
For bonus points, is there any way to change the attribute value above such that it does not use scriptlet code? Presumably, that means using EL instead.
Cheers,
Don
A: The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:
<c:if test="true">
<li>user</li>
</c:if>
and then the c:if tag would be executed.
A: Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.
If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
A: All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"
<c:if test="true">Hello world!</c:if>
The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.
A: You can also use something like
<c:if test="${ testObject.testPropert == "testValue" }">...</c:if>
A: <%=%> by itself will be sent to the output, in the context of the JSTL it will be evaluated to a string
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Maximizing an Emacs frame to just one monitor with elisp I use maxframe.el to maximize my Emacs frames.
It works great on all three major platforms, except on my dual-head Mac setup (Macbook Pro 15-inch laptop with 23-inch monitor).
When maximizing an Emacs frame, the frame expands to fill the width of both monitors and the height of the larger monitor.
Obviously, I would like the frame to maximize to fill only the monitor it's on. How can I detect the resolutions of the two individual monitors using elisp?
Thanks,
Jacob
EDIT: As Denis points out, setting mf-max-width is a reasonable workaround. But (as I should have mentioned) I was hoping for a solution that works on both monitors and with any resolution. Maybe something OSX-specific in the style of the Windows-specific w32-send-sys-command.
A: I quickly scanned the reference that you provided to maxframe.el and I don't think that you're using the same technique that I use. Does the following code snippet help you?
(defun toggle-fullscreen ()
"toggles whether the currently selected frame consumes the entire display or is decorated with a window border"
(interactive)
(let ((f (selected-frame)))
(modify-frame-parameters f `((fullscreen . ,(if (eq nil (frame-parameter f 'fullscreen)) 'fullboth nil))))))
A: Does customising `mf-max-width' work? Its documentation:
"*The maximum display width to support. This helps better support the true
nature of display-pixel-width. Since multiple monitors will result in a
very large display pixel width, this value is used to set the stop point for
maximizing the frame. This could also be used to set a fixed frame size
without going over the display dimensions."
A: This sort of thing is the job of your window manager, not the job of emacs. (For example, Xmonad handles full-screen emacs just fine.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How do you query object collections in Java (Criteria/SQL-like)? Suppose you have a collection of a few hundred in-memory objects and you need to query this List to return objects matching some SQL or Criteria like query. For example, you might have a List of Car objects and you want to return all cars made during the 1960s, with a license plate that starts with AZ, ordered by the name of the car model.
I know about JoSQL, has anyone used this, or have any experience with other/homegrown solutions?
A: yes, I know it's an old post, but technologies appear everyday and the answer will change in the time.
I think this is a good problem to solve it with LambdaJ. You can find it here:
http://code.google.com/p/lambdaj/
Here you have an example:
LOOK FOR ACTIVE CUSTOMERS // (Iterable version)
List<Customer> activeCustomers = new ArrayList<Customer>();
for (Customer customer : customers) {
if (customer.isActive()) {
activeCusomers.add(customer);
}
}
LambdaJ version
List<Customer> activeCustomers = select(customers,
having(on(Customer.class).isActive()));
Of course, having this kind of beauty impacts in the performance (a little... an average of 2 times), but can you find a more readable code?
It has many many features, another example could be sorting:
Sort Iterative
List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
}
});
Sort with lambda
List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge());
Update: after java 8 you can use out of the box lambda expressions, like:
List<Customer> activeCustomers = customers.stream()
.filter(Customer::isActive)
.collect(Collectors.toList());
A: Continuing the Comparator theme, you may also want to take a look at the Google Collections API. In particular, they have an interface called Predicate, which serves a similar role to Comparator, in that it is a simple interface that can be used by a filtering method, like Sets.filter. They include a whole bunch of composite predicate implementations, to do ANDs, ORs, etc.
Depending on the size of your data set, it may make more sense to use this approach than a SQL or external relational database approach.
A: Filtering is one way to do this, as discussed in other answers.
Filtering is not scalable though. On the surface time complexity would appear to be O(n) (i.e. already not scalable if the number of objects in the collection will grow), but actually because one or more tests need to be applied to each object depending on the query, time complexity more accurately is O(n t) where t is the number of tests to apply to each object.
So performance will degrade as additional objects are added to the collection, and/or as the number of tests in the query increases.
There is another way to do this, using indexing and set theory.
One approach is to build indexes on the fields within the objects stored in your collection and which you will subsequently test in your query.
Say you have a collection of Car objects and every Car object has a field color. Say your query is the equivalent of "SELECT * FROM cars WHERE Car.color = 'blue'". You could build an index on Car.color, which would basically look like this:
'blue' -> {Car{name=blue_car_1, color='blue'}, Car{name=blue_car_2, color='blue'}}
'red' -> {Car{name=red_car_1, color='red'}, Car{name=red_car_2, color='red'}}
Then given a query WHERE Car.color = 'blue', the set of blue cars could be retrieved in O(1) time complexity. If there were additional tests in your query, you could then test each car in that candidate set to check if it matched the remaining tests in your query. Since the candidate set is likely to be significantly smaller than the entire collection, time complexity is less than O(n) (in the engineering sense, see comments below). Performance does not degrade as much, when additional objects are added to the collection. But this is still not perfect, read on.
Another approach, is what I would refer to as a standing query index. To explain: with conventional iteration and filtering, the collection is iterated and every object is tested to see if it matches the query. So filtering is like running a query over a collection. A standing query index would be the other way around, where the collection is instead run over the query, but only once for each object in the collection, even though the collection could be queried any number of times.
A standing query index would be like registering a query with some sort of intelligent collection, such that as objects are added to and removed from the collection, the collection would automatically test each object against all of the standing queries which have been registered with it. If an object matches a standing query then the collection could add/remove it to/from a set dedicated to storing objects matching that query. Subsequently, objects matching any of the registered queries could be retrieved in O(1) time complexity.
The information above is taken from CQEngine (Collection Query Engine). This basically is a NoSQL query engine for retrieving objects from Java collections using SQL-like queries, without the overhead of iterating through the collection. It is built around the ideas above, plus some more. Disclaimer: I am the author. It's open source and in maven central. If you find it helpful please upvote this answer!
A: If you need a single concrete match, you can have the class implement Comparator, then create a standalone object with all the hashed fields included and use it to return the index of the match. When you want to find more than one (potentially) object in the collection, you'll have to turn to a library like JoSQL (which has worked well in the trivial cases I've used it for).
In general, I tend to embed Derby into even my small applications, use Hibernate annotations to define my model classes and let Hibernate deal with caching schemes to keep everything fast.
A: I have used Apache Commons JXPath in a production application. It allows you to apply XPath expressions to graphs of objects in Java.
A: I would use a Comparator that takes a range of years and license plate pattern as input parameters. Then just iterate through your collection and copy the objects that match. You'd likely end up making a whole package of custom Comparators with this approach.
A: The Comparator option is not bad, especially if you use anonymous classes (so as not to create redundant classes in the project), but eventually when you look at the flow of comparisons, it's pretty much just like looping over the entire collection yourself, specifying exactly the conditions for matching items:
if (Car car : cars) {
if (1959 < car.getYear() && 1970 > car.getYear() &&
car.getLicense().startsWith("AZ")) {
result.add(car);
}
}
Then there's the sorting... that might be a pain in the backside, but luckily there's class Collections and its sort methods, one of which receives a Comparator...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: Reading an ASCII file with FileChannel and ByteArrays I have the following code:
String inputFile = "somefile.txt";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
for ( int i = 0; i < rd/2; i++ ) {
/* print each character */
System.out.print(buf.getChar());
}
buf.clear();
}
But the characters get displayed at ?'s. Does this have something to do with Java using Unicode characters? How do I correct this?
A: You have to know what the encoding of the file is, and then decode the ByteBuffer into a CharBuffer using that encoding. Assuming the file is ASCII:
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class Buffer
{
public static void main(String args[]) throws Exception
{
String inputFile = "somefile";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
Charset cs = Charset.forName("ASCII"); // Or whatever encoding you want
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
CharBuffer chbuf = cs.decode(buf);
for ( int i = 0; i < chbuf.length(); i++ ) {
/* print each character */
System.out.print(chbuf.get());
}
buf.clear();
}
}
}
A: buf.getChar() is expecting 2 bytes per character but you are only storing 1. Use:
System.out.print((char) buf.get());
A: Changing your print statement to:
System.out.print((char)buf.get());
Seems to help.
A: Depending on the encoding of somefile.txt, a character may not actually be composed of two bytes. This page gives more information about how to read streams with the proper encoding.
The bummer is, the file system doesn't tell you the encoding of the file, because it doesn't know. As far as it's concerned, it's just a bunch of bytes. You must either find some way to communicate the encoding to the program, detect it somehow, or (if possible) always ensure that the encoding is the same (such as UTF-8).
A: Is there a particular reason why you are reading the file in the way that you do?
If you're reading in an ASCII file you should really be using a Reader.
I would do it something like:
File inputFile = new File("somefile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
And then use either readLine or similar to actually read in the data!
A: Yes, it is Unicode.
If you have 14 Chars in your File, you only get 7 '?'.
Solution pending. Still thinking.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Add RSS to any website? Is there any website/service which will enable me to add RSS subscription to any website?
This is for my company I work. We have a website which displays company related news. These news are supplied by an external agency and they gets updated to our database automatically. Our website picks up random/new news and displays them. We are looking at adding a "Subscribe via RSS" button to our website.
A: If you have the data in your database, creating one yourself is fairly straight forward - there's a simple tutorial here.
Once you've set up a feed, in the <head> of your page, you put text like:
<link rel="alternate" title="RSS Feed"
href="http://www.example.com/rss-feed/latest/" type="application/rss+xml" />
This allows the feed to be "auto-discovered" by your user's browser (e.g. the RSS icon appears in the address bar in FF).
A: Here's an article that discusses various webscrapers that will generate feeds: http://www.masternewmedia.org/news/2006/03/09/how_to_create_a_rss.htm
If you don't care to click through, here are the services the author discusses:
*
*http://www.feedyes.com/
*http://www.feed43.com/
*http://www.feedfire.com/site/index.html
Other webscrapers suggested in the other answers:
*
*http://page2rss.com/
*http://www.dapper.net/
However, you're probably better off generating the feeds yourself from the info in the DB.
A: Your question is a little difficult to understand. Are you trying to generate the RSS for others to consume, or are you trying to consume someone else's RSS?
If you are trying to generate your RSS feed for others to consume you will need to read the spec:
http://cyber.law.harvard.edu/rss/rss.html
If you are trying to consume it, that link will also help. Then you'll need to look into an XML / RSS parser.
If you can provide more details I can update my answer.
A: If you are not in a position to add an RSS feed to the existing site, see Page2Rss as an intermediate solution.
A: Might Dapper be of some use? You just need to set up which bits of your news feed to scour and voila, instant rss without having to touch any code...
A: Actually this is very doable with Yahoo! Pipes. Assuming that 1) your page is under 200k, 2) your robots.txt file does not disallow Pipes, and 3) your news feed has a unique ID, like so:
<ul id="newsfeed">
... you could use the Fetch Page module, trim it to just the items inside the news feed, loop though each list item, and use an Item Builder module to mangle the relevant bits as a proper RSS feed. Then, in the head of your document, you'd put in an RSS link, like so:
<link rel="alternate" type="application/atom+xml" title="News Feed" href="http://pipes.yahoo.com/your_pipe_id" />
This is of course completely ass-backwards, but would work for a quick fix, or in situations where you had no control over the body of the page.
A: Write a webhandler that exposes the content of the database as an RSS feed.
A: You either need to roll your own, or get a service that is a screen scraper.
After you have created your feed, you can use something like Feedburner to disseminate it.
A: If you happen to be using ASP.NET, you might want to check out the ASP.NET RSS Toolkit. It's useful for both generating and consuming feeds.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Does AES (128 or 256) encryption expand the data? If so, by how much? I would like to add AES encryption to a software product, but am concerned by increasing the size of the data. I am guessing that the data does increase in size, and then I'll have to add a compression algorithm to compensate.
A: AES does not expand data. Moreover, the output will not generally be compressible; if you intend to compress your data, do so before encrypting it.
However, note that AES encryption is usually combined with padding, which will increase the size of the data (though only by a few bytes).
A: I am fairly sure AES encryption adds nothing to the data being encrypted, since that would give away information about the state variables, and that is a Bad Thing when it comes to cryptography.
If you want to mix compression and encryption, do them in that order. The reason is encrypted data (ideally) looks like totally random data, and compression algorithms will end up making the data bigger, due to its inability to actually compress any of it and overhead of book keeping that comes with any compressed file format.
A: AES does not expand the data, except for a few bytes of padding at the end of the last block.
The resulting data are not compressible, at any rate, because they are basically random - no dictionary-based algorithm is able to effectively compress them. A best practice is to compress the data first, then encrypt them.
A: It is common to compress data before encrypting. Compressing it afterwards doesn't work, because AES encrypted data appears random (as for any good cipher, apart from any headers and whatnot).
However, compression can introduce side-channel attacks in some contexts, so you must analyse your own use. Such attacks have recently been reported against encrypted VOIP: the gist is that different syllables create characteristic variations in bitrate when compressed with VBR, because some sounds compress better than others. Some (or all) syllables may therefore be recoverable with sufficient analysis, since the data is transmitted at the rate it is generated. The fix is to either to use (less efficient) CBR compression, or to use a buffer to transmit at constant rate regardless of the data rate coming out of the encoder (increasing latency).
AES turns 16 byte input blocks into 16 byte output blocks. The only expansion is to round the data up to a whole number of blocks.
A: If compression is necessary do it before you encrypt.
A: No. The only change will be a small amount of padding to align the data to the size of a block
However, if you are compressing the content note that you should do this before encrypting. Encrypted data should generally be indistinguishable from random data, which means that it will not compress.
A: @freespace and others: One of the things I remember from my cryptography classes is that you should not compress your data before encryption, because some repeatable chunks of compressed stream (like section headers for example) may make it easier to crack your encryption.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: Assembly names and versions What is considered as best practice when it comes to assemblies and releases?
I would like to be able to reference multiple versions of the same library - solution contains multiple projects that depend on different versions of a commonutils.dll library we build ourselves.
As all dependencies are copied to the bin/debug or bin/release, only a single copy of commonutils.dll can exist there despite each of the DLL files having different assembly version numbers.
Should I include version numbers in the assembly name to be able to reference multiple versions of a library or is there another way?
A: Assemblies can coexist in the GAC (Global Assembly Cache) even if they have the same name given that the version is different. This is how .NET Framework shipped assemblies work. A requirement that must be meet in order for an assembly to be able to be GAC registered is to be signed.
Adding version numbers to the name of the Assembly just defeats the whole purpose of the assembly ecosystem and is cumbersome IMHO. To know which version of a given assembly I have just open the Properties window and check the version.
A: Here's what I've been living by --
It depends on what you are planning to use the DLL files for. I categorize them in two main groups:
*
*Dead-end Assemblies. These are EXE files and DLL files you really aren't planning on referencing from anywhere. Just weakly name these and make sure you have the version numbers you release tagged in source-control, so you can rollback whenever.
*Referenced Assemblies. Strong name these so you can have multiple versions of it being referenced by other assemblies. Use the full name to reference them (Assembly.Load). Keep a copy of the latest-and-greatest version of it in a place where other code can reference it.
Next, you have a choice of whether to copy local or not your references. Basically, the tradeoff boils down to -- do you want to take in patches/upgrades from your references? There can be positive value in that from getting new functionality, but on the other hand, there could be breaking changes. The decision here, I believe, should be made on a case-by-case basis.
While developing in Visual Studio, by default you will take the latest version to compile with, but once compiled the referencing assembly will require the specific version it was compiled with.
Your last decision is to Copy Local or not. Basically, if you already have a mechanism in place to deploy the referenced assembly, set this to false.
If you are planning a big release management system, you'll probably have to put a lot more thought and care into this. For me (small shop -- two people), this works fine. We know what's going on, and don't feel restrained from having to do things in a way that doesn't make sense.
Once you reach runtime, you Assembly.Load whatever you want into the application domain. Then, you can use Assembly.GetType to reach the type you want. If you have a type that is present in multiple loaded assemblies (such as in multiple versions of the same project), you may get an AmbiguousMatchException exception. In order to resolve that, you will need to get the type out of an instance of an assembly variable, not the static Assembly.GetType method.
A: Giving different names to different assembly versions is the easiest way and surely works.
If your assembly (commonutils.dll) is strong-named (i.e. signed), you can think about installing it in the GAC (Global Assembly Cache - you can install different versions of the same assembly side-by-side in the GAC), therefore the calling application automatically gets the proper version from there because .NET Types include assembly version information.
In your VS project you reference the correct version of the library, but you don't deploy it in the application folder; you install it in the GAC instead (during application setup).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Practical Alternative for Windows Scheduled Tasks (small shop) I work in a very small shop (2 people), and since I started a few months back we have been relying on Windows Scheduled tasks. Finally, I've decided I've had enough grief with some of its inabilities such as
*
*No logs that I can find except on a domain level (inaccessible to machine admins who aren't domain admins)
*No alerting mechanism (e-mail, for one) when the job fails.
Once again, we are a small shop. I'm looking to do the analogous scheduling system upgrade than I'm doing with source control (VSS --> Subversion). I'm looking for suggestions of systems that
*
*Are able to do the two things outlined above
*Have been community-tested. I'd love to be a guinae pig for exciting software, but job scheduling is not my day job.
*Ability to remotely manage jobs a plus
*Free a plus. Cheap is okay, but I have very little interest in going through a full blown sales pitch with 7 power point presentations.
*Built-in ability to run common tasks besides .EXE's a (minor) plus (run an assembly by name, run an Excel macro by name a plus, run a database stored procedure, etc.).
A: Consider Cygwin and its version of "cron". It meets requirements #1 thru 4 (though without a nice UI for #3.)
A: I think you can look at :
http://www.visualcron.com/
A: Apologize for kicking up the dust here on a very old thread. But I couldn't disagree more with what's been presented here.
Scheduled tasks in Windows are AWESOME (a %^#% load better than writing services I might add). Yes, not without limitations. But still extremely powerful. I rely on them in earnest for a variety of different things.
If you even have a slight grasp on c# you can write as custom "task" (essentially a console application) to do, well, virtually anything. If persistent/accessible logging is what you're after, why not something like Serilog or NLog? Even at the time of writing, it had a very robust feature set. This tool in and of itself, in conjunction with some c#, could've solved both your problems very easily.
Perhaps I'm missing the point, but it seems to me that this isn't really a problem. At least not anymore...
A: If you're looking for a free tool there is plenty of implementations for the popular Cron tool for Windows, for example CRONw. It's pretty easy to configure and maintain. You could easily write add custom WSH scripts to send your emails and add log entries.
If you're going commercial way BMC Control-M is arguably one of the best but I don't believe that it is particularly cheap.
You may also consider some upcoming packages like JobScheduler
A: Pretty old question, but we use Jenkins. Yes its main purpose is for CI\CD, but its also a really nice UI for CRON with a ton of plugins and integrations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: SQL Server Express DB is 'in recovery' - how to detect / know when it is when an SQL Server Express DB is 'in recovery', you are unable to connect using SQL Authentication.
Is there a simple way of determining the stat of the DB prior to connecting to it?
(Using .Net)
A: SELECT DATABASEPROPERTYEX ('master', 'STATUS') AS 'Status';
Replace 'master' with your database name
A: That's kind of a trick question. Instead of connecting to that particular database, you still need to connect to the server itself, but specify a different database. When connecting, your default database might be the one that's in recovery. In that case, you'll need to specify a different database upon connecting, and THEN issue a query to check the database's extended properties.
Unfortunately, this means your SQL login will need permissions to that other database you'll be connecting to, AND it'll need permissions to query the database's extended properties.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Call .NET objects/dlls across virtual sites Site 1 has dll's for x amount of object and data calls. Can Site 2 (a separate .net web app) call the objects/dll's of Site 1 ?
A: This may be more semantics:
You can't call an object of another process. You can however potentially instantiate a class within a dll as long as there is a reference to that dll in the calling web application.
If you GAC the dll, the classes (not objects) will be accessible to the entire machine.
A: I never used .NET Remoting but isn't that the kind of problem it could solve?
A: My understanding of the situation was that because you couldn't access the Bin directory cross site, you'd need to develop an api or web service. Your best bet is to have a local copy of the dll on each server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DateTimePicker: pick both date and time Is it possible to use DateTimePicker (Winforms) to pick both date and time (in the dropdown)? How do you change the custom display of the picked value? Also, is it possible to enable the user to type the date/time manually?
A: It is best to use two DateTimePickers for the Job
One will be the default for the date section and the second DateTimePicker is for the time portion. Format the second DateTimePicker as follows.
timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
timePortionDateTimePicker.ShowUpDown = true;
The Two should look like this after you capture them
To get the DateTime from both these controls use the following code
DateTime myDate = datePortionDateTimePicker.Value.Date +
timePortionDateTimePicker.Value.TimeOfDay;
To assign the DateTime to both these controls use the following code
datePortionDateTimePicker.Value = myDate.Date;
timePortionDateTimePicker.Value = myDate.TimeOfDay;
A: Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.
To use the DateTimePicker for times, set the Format property to either Time
or Custom (Use Custom if you want to control the format of the time using
the CustomFormat property). Then set the ShowUpDown property to true.
Although a user may set the date and time together manually, they cannot use the GUI to set both.
A: DateTime Picker can be used to pick both date and time that is why it is called 'Date and Time Picker'. You can set the "Format" property to "Custom" and set combination of different format specifiers to represent/pick date/time in different formats in the "Custom Format" property. However if you want to change Date, then the pop-up calendar can be used whereas in case of Time selection (in the same control you are bound to use up/down keys to change values.
For example a custom format " ddddd, MMMM dd, yyyy hh:mm:ss tt " will give you a result like this : "Thursday, August 20, 2009 02:55:23 PM".
You can play around with different combinations for format specifiers to suit your need e.g MMMM will give "August" whereas MM will give "Aug"
A: Set the Format to Custom and then specify the format:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";
or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)
Don't know about the picker for date and time together. Sounds like a custom control to me.
A: Go to the Properties of your dateTimePickerin Visual Studio and set Format to Custom. Under CustomFormat enter your format. In my case I used MMMMdd, yyyy | hh:mm
A: You can get it to display time. From that you will probably have to have two controls (one date, one time) the accomplish what you want.
A: I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.
For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.
A: If you need (24 hours) military time. You should use "HH" instead of "hh".
"MM/dd/yyyy HH:mm"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "159"
}
|
Q: Classical ASP in IIS 6.0 not scaling The IIS 6.0 is serving my Classical ASP pages in a serial fashion (one at a time)
The #2 request will be handled by the web server only when the #1 request ends.
If the #1 request takes a little longer, the #2 request will have to wait for the #1 ends to starts being handled by IIS.
Is this a missconfiguration in IIS?
The operation system is Windows Server 2003 Standard Edition (Service Pack 2)
A: Yes, IIS or the site is most likely configured for server-side debugging, which causes all requests to the site to go through a single thread.
To check if this is the case/turn it off:
*
*In the Properties pages for any Web site or Web virtual directory, click the Home Directory or Virtual Directory tab.
*Under Application Settings, click Configuration. An application must be created for the button to be active.
*Click the Debugging tab.
*Un-check the Enable ASP server-side script debugging check box.
(Above steps were copied from the Debugging ASP Applications in IIS KB article)
A: Is this happening across machines? Like if you start loading a page on one computer, then another, the second is blocked? I've seen this on a single computer, but only because the browser is limiting connections to the server
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Persisting Checkbox State Across Postbacks I have a web form that binds a DataGrid to a, normally, different data source on each postback. I have a static CheckBox column that is always present to the left of the autogenerated columns. I achieve a TabControl effect with a horizontal Menu control above the grid, with each menu item being a tab that contains a different grid.
Now I would like to persist the state of these checkboxes for a particular 'tab', when another tab is selected. I would welcome any imaginative solution for doing this without using session variables.
A: I think the best bet for this is to have a different gridview for each of your "tabs". Use the MultiView control with a View control for each tab, and a gridview in each View. In the click event of your menu change to the correct view. Only bind each gridview once, and then your checkboxes will persist.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to verify existence of a table with a given ID in a word doc in C# VSTO 3 I want to check for the existence of a table with a given ID in a word document in C# (VS 2008) Visual Studio Tools for Office (version 3).
Obviously I can iterate through the document's Tables collection and check every ID, but this seems inefficient; the document will end up having a few dozen tables after I'm done with it, and while I know that's not a lot, looping through the collection seems sloppy. The Tables collection is only indexed by integer id, not by the string ID assigned to the table, so I cant just use an index, and there's no apparent Exists method of the document or tables collection.
I thought of casting the Tables collection to an IQueryable using AsQueryable(), but I don't know how to go about doing this in such a way that I could query it by ID.
Pointers to docs or sample code would be appreciated, or if there's a better way to go about it, I'm all for that, too
A: I don't think there's a better way to do it. Any solution including IQueryable would presumably need to iterate the collection internally so wouldn't be any faster.
Performance is unlikely to be a problem anyway, so I wouldn't worry about the inefficiency.
If you are doing it a lot, you could provide a wrapper that iterates once through the tables and generates a dictionary that you subsequently use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Counter inside xsl:for-each loop How to get a counter inside xsl:for-each loop that would reflect the number of current element processed.
For example my source XML is
<books>
<book>
<title>The Unbearable Lightness of Being </title>
</book>
<book>
<title>Narcissus and Goldmund</title>
</book>
<book>
<title>Choke</title>
</book>
</books>
What I want to get is:
<newBooks>
<newBook>
<countNo>1</countNo>
<title>The Unbearable Lightness of Being </title>
</newBook>
<newBook>
<countNo>2</countNo>
<title>Narcissus and Goldmund</title>
</newBook>
<newBook>
<countNo>3</countNo>
<title>Choke</title>
</newBook>
</newBooks>
The XSLT to modify:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<newBooks>
<xsl:for-each select="books/book">
<newBook>
<countNo>???</countNo>
<title>
<xsl:value-of select="title"/>
</title>
</newBook>
</xsl:for-each>
</newBooks>
</xsl:template>
</xsl:stylesheet>
So the question is what to put in place of ???. Is there any standard keyword or do I simply must declare a variable and increment it inside the loop?
As the question is pretty long I should probably expect one line or one word answer :)
A: You can also run conditional statements on the Postion() which can be really helpful in many scenarios.
for eg.
<xsl:if test="(position( )) = 1">
//Show header only once
</xsl:if>
A: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<newBooks>
<xsl:for-each select="books/book">
<newBook>
<countNo><xsl:value-of select="position()"/></countNo>
<title>
<xsl:value-of select="title"/>
</title>
</newBook>
</xsl:for-each>
</newBooks>
</xsl:template>
</xsl:stylesheet>
A: position(). E.G.:
<countNo><xsl:value-of select="position()" /></countNo>
A: Try inserting <xsl:number format="1. "/><xsl:value-of select="."/><xsl:text> in the place of ???.
Note the "1. " - this is the number format. More info: here
A: Try:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit - had a brain freeze there, position() is more straightforward!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "95"
}
|
Q: How can I add an HyperLink in TRichEdit using Delphi How can I add an HyperLink in a TRichEdit (using Delphi).
I need to have something like:
"This is my text, click here to do something."
A: According to this article on delphi.about.com
Unfortunately, Delphi's implementation of the RichEdit control leaves out a lot of the functionality found in more recent versions of this control (from Microsoft).
You can add your own functionality as discussed here.
NOTE: Delphi 2009 has just been released, so the TRichEdit control may have been updated to support mode features.
A: If you really want hyperlinks and more, you could check out TRichView. There is a good demonstration of its capabilities at link text.
A: i don't know if it's mentioned in the About.com article but i think it's worth mentioning that the hyperlink in TRichEdit only works if the TRichEdit itself is directly placed on the form (not in a panel).
http://www.scalabium.com/faq/dct0146.htm
A: The richedit in Infopower supports hyperlinks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is a Y-combinator? A Y-combinator is a computer science concept from the “functional” side of things. Most programmers don't know much at all about combinators, if they've even heard about them.
*
*What is a Y-combinator?
*How do combinators work?
*What are they good for?
*Are they useful in procedural languages?
A: I wonder if there's any use in attempting to build this from the ground up. Let's see. Here's a basic, recursive factorial function:
function factorial(n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
Let's refactor and create a new function called fact that returns an anonymous factorial-computing function instead of performing the calculation itself:
function fact() {
return function(n) {
return n == 0 ? 1 : n * fact()(n - 1);
};
}
var factorial = fact();
That's a little weird, but there's nothing wrong with it. We're just generating a new factorial function at each step.
The recursion at this stage is still fairly explicit. The fact function needs to be aware of its own name. Let's parameterize the recursive call:
function fact(recurse) {
return function(n) {
return n == 0 ? 1 : n * recurse(n - 1);
};
}
function recurser(x) {
return fact(recurser)(x);
}
var factorial = fact(recurser);
That's great, but recurser still needs to know its own name. Let's parameterize that, too:
function recurser(f) {
return fact(function(x) {
return f(f)(x);
});
}
var factorial = recurser(recurser);
Now, instead of calling recurser(recurser) directly, let's create a wrapper function that returns its result:
function Y() {
return (function(f) {
return f(f);
})(recurser);
}
var factorial = Y();
We can now get rid of the recurser name altogether; it's just an argument to Y's inner function, which can be replaced with the function itself:
function Y() {
return (function(f) {
return f(f);
})(function(f) {
return fact(function(x) {
return f(f)(x);
});
});
}
var factorial = Y();
The only external name still referenced is fact, but it should be clear by now that that's easily parameterized, too, creating the complete, generic, solution:
function Y(le) {
return (function(f) {
return f(f);
})(function(f) {
return le(function(x) {
return f(f)(x);
});
});
}
var factorial = Y(function(recurse) {
return function(n) {
return n == 0 ? 1 : n * recurse(n - 1);
};
});
A: Here is a JavaScript implementation of the Y-Combinator and the Factorial function (from Douglas Crockford's article, available at: http://javascript.crockford.com/little.html).
function Y(le) {
return (function (f) {
return f(f);
}(function (f) {
return le(function (x) {
return f(f)(x);
});
}));
}
var factorial = Y(function (fac) {
return function (n) {
return n <= 2 ? n : n * fac(n - 1);
};
});
var number120 = factorial(5);
A: A Y-Combinator is another name for a flux capacitor.
A: I have written a sort of "idiots guide" to the Y-Combinator in both Clojure and Scheme in order to help myself come to grips with it. They are influenced by material in "The Little Schemer"
In Scheme:
https://gist.github.com/z5h/238891
or Clojure:
https://gist.github.com/z5h/5102747
Both tutorials are code interspersed with comments and should be cut & pastable into your favourite editor.
A: As a newbie to combinators, I found Mike Vanier's article (thanks Nicholas Mancuso) to be really helpful. I would like to write a summary, besides documenting my understanding, if it could be of help to some others I would be very glad.
From Crappy to Less Crappy
Using factorial as an example, we use the following almost-factorial function to calculate factorial of number x:
def almost-factorial f x = if iszero x
then 1
else * x (f (- x 1))
In the pseudo-code above, almost-factorial takes in function f and number x (almost-factorial is curried, so it can be seen as taking in function f and returning a 1-arity function).
When almost-factorial calculates factorial for x, it delegates the calculation of factorial for x - 1 to function f and accumulates that result with x (in this case, it multiplies the result of (x - 1) with x).
It can be seen as almost-factorial takes in a crappy version of factorial function (which can only calculate till number x - 1) and returns a less-crappy version of factorial (which calculates till number x). As in this form:
almost-factorial crappy-f = less-crappy-f
If we repeatedly pass the less-crappy version of factorial to almost-factorial, we will eventually get our desired factorial function f. Where it can be considered as:
almost-factorial f = f
Fix-point
The fact that almost-factorial f = f means f is the fix-point of function almost-factorial.
This was a really interesting way of seeing the relationships of the functions above and it was an aha moment for me. (please read Mike's post on fix-point if you haven't)
Three functions
To generalize, we have a non-recursive function fn (like our almost-factorial), we have its fix-point function fr (like our f), then what Y does is when you give Y fn, Y returns the fix-point function of fn.
So in summary (simplified by assuming fr takes only one parameter; x degenerates to x - 1, x - 2... in recursion):
*
*We define the core calculations as fn: def fn fr x = ...accumulate x with result from (fr (- x 1)), this is the almost-useful function - although we cannot use fn directly on x, it will be useful very soon. This non-recursive fn uses a function fr to calculate its result
*fn fr = fr, fr is the fix-point of fn, fr is the useful funciton, we can use fr on x to get our result
*Y fn = fr, Y returns the fix-point of a function, Y turns our almost-useful function fn into useful fr
Deriving Y (not included)
I will skip the derivation of Y and go to understanding Y. Mike Vainer's post has a lot of details.
The form of Y
Y is defined as (in lambda calculus format):
Y f = λs.(f (s s)) λs.(f (s s))
If we replace the variable s in the left of the functions, we get
Y f = λs.(f (s s)) λs.(f (s s))
=> f (λs.(f (s s)) λs.(f (s s)))
=> f (Y f)
So indeed, the result of (Y f) is the fix-point of f.
Why does (Y f) work?
Depending the signature of f, (Y f) can be a function of any arity, to simplify, let's assume (Y f) only takes one parameter, like our factorial function.
def fn fr x = accumulate x (fr (- x 1))
since fn fr = fr, we continue
=> accumulate x (fn fr (- x 1))
=> accumulate x (accumulate (- x 1) (fr (- x 2)))
=> accumulate x (accumulate (- x 1) (accumulate (- x 2) ... (fn fr 1)))
the recursive calculation terminates when the inner-most (fn fr 1) is the base case and fn doesn't use fr in the calculation.
Looking at Y again:
fr = Y fn = λs.(fn (s s)) λs.(fn (s s))
=> fn (λs.(fn (s s)) λs.(fn (s s)))
So
fr x = Y fn x = fn (λs.(fn (s s)) λs.(fn (s s))) x
To me, the magical parts of this setup are:
*
*fn and fr interdepend on each other: fr 'wraps' fn inside, every time fr is used to calculate x, it 'spawns' ('lifts'?) an fn and delegates the calculation to that fn (passing in itself fr and x); on the other hand, fn depends on fr and uses fr to calculate result of a smaller problem x-1.
*At the time fr is used to define fn (when fn uses fr in its operations), the real fr is not yet defined.
*It's fn which defines the real business logic. Based on fn, Y creates fr - a helper function in a specific form - to facilitate the calculation for fn in a recursive manner.
It helped me understanding Y this way at the moment, hope it helps.
BTW, I also found the book An Introduction to Functional Programming Through Lambda Calculus very good, I'm only part through it and the fact that I couldn't get my head around Y in the book led me to this post.
A: Most of the answers above describe what the Y-combinator is but not what it is for.
Fixed point combinators are used to show that lambda calculus is turing complete. This is a very important result in the theory of computation and provides a theoretical foundation for functional programming.
Studying fixed point combinators has also helped me really understand functional programming. I have never found any use for them in actual programming though.
A: Here are answers to the original questions, compiled from the article (which is TOTALY worth reading) mentioned in the answer by Nicholas Mancuso, as well as other answers:
What is a Y-combinator?
An Y-combinator is a "functional" (or a higher-order function — a function that operates on other functions) that takes a single argument, which is a function that isn't recursive, and returns a version of the function which is recursive.
Somewhat recursive =), but more in-depth definition:
A combinator — is just a lambda expression with no free variables.
Free variable — is a variable that is not a bound variable.
Bound variable — variable which is contained inside the body of a lambda expression that has that variable name as one of its arguments.
Another way to think about this is that combinator is such a lambda expression, in which you are able to replace the name of a combinator with its definition everywhere it is found and have everything still work (you will get into an infinite loop if combinator would contain reference to itself, inside the lambda body).
Y-combinator is a fixed-point combinator.
Fixed point of a function is an element of the function's domain that is mapped to itself by the function.
That is to say, c is a fixed point of the function f(x) if f(c) = c
This means f(f(...f(c)...)) = fn(c) = c
How do combinators work?
Examples below assume strong + dynamic typing:
Lazy (normal-order) Y-combinator:
This definition applies to languages with lazy (also: deferred, call-by-need) evaluation — evaluation strategy which delays the evaluation of an expression until its value is needed.
Y = λf.(λx.f(x x)) (λx.f(x x)) = λf.(λx.(x x)) (λx.f(x x))
What this means is that, for a given function f (which is a non-recursive function), the corresponding recursive function can be obtained first by computing λx.f(x x), and then applying this lambda expression to itself.
Strict (applicative-order) Y-combinator:
This definition applies to languages with strict (also: eager, greedy) evaluation — evaluation strategy in which an expression is evaluated as soon as it is bound to a variable.
Y = λf.(λx.f(λy.((x x) y))) (λx.f(λy.((x x) y))) = λf.(λx.(x x)) (λx.f(λy.((x x) y)))
It is same as lazy one in it's nature, it just has an extra λ wrappers to delay the lambda's body evaluation. I've asked another question, somewhat related to this topic.
What are they good for?
Stolen borrowed from answer by Chris Ammerman: Y-combinator generalizes recursion, abstracting its implementation, and thereby separating it from the actual work of the function in question.
Even though, Y-combinator has some practical applications, it is mainly a theoretical concept, understanding of which will expand your overall vision and will, likely, increase your analytical and developer skills.
Are they useful in procedural languages?
As stated by Mike Vanier: it is possible to define a Y combinator in many statically typed languages, but (at least in the examples I've seen) such definitions usually require some non-obvious type hackery, because the Y combinator itself doesn't have a straightforward static type. That's beyond the scope of this article, so I won't mention it further
And as mentioned by Chris Ammerman: most procedural languages has static-typing.
So answer to this one — not really.
A: A Y-combinator is a "functional" (a function that operates on other functions) that enables recursion, when you can't refer to the function from within itself. In computer-science theory, it generalizes recursion, abstracting its implementation, and thereby separating it from the actual work of the function in question. The benefit of not needing a compile-time name for the recursive function is sort of a bonus. =)
This is applicable in languages that support lambda functions. The expression-based nature of lambdas usually means that they cannot refer to themselves by name. And working around this by way of declaring the variable, refering to it, then assigning the lambda to it, to complete the self-reference loop, is brittle. The lambda variable can be copied, and the original variable re-assigned, which breaks the self-reference.
Y-combinators are cumbersome to implement, and often to use, in static-typed languages (which procedural languages often are), because usually typing restrictions require the number of arguments for the function in question to be known at compile time. This means that a y-combinator must be written for any argument count that one needs to use.
Below is an example of how the usage and working of a Y-Combinator, in C#.
Using a Y-combinator involves an "unusual" way of constructing a recursive function. First you must write your function as a piece of code that calls a pre-existing function, rather than itself:
// Factorial, if func does the same thing as this bit of code...
x == 0 ? 1: x * func(x - 1);
Then you turn that into a function that takes a function to call, and returns a function that does so. This is called a functional, because it takes one function, and performs an operation with it that results in another function.
// A function that creates a factorial, but only if you pass in
// a function that does what the inner function is doing.
Func<Func<Double, Double>, Func<Double, Double>> fact =
(recurs) =>
(x) =>
x == 0 ? 1 : x * recurs(x - 1);
Now you have a function that takes a function, and returns another function that sort of looks like a factorial, but instead of calling itself, it calls the argument passed into the outer function. How do you make this the factorial? Pass the inner function to itself. The Y-Combinator does that, by being a function with a permanent name, which can introduce the recursion.
// One-argument Y-Combinator.
public static Func<T, TResult> Y<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> F)
{
return
t => // A function that...
F( // Calls the factorial creator, passing in...
Y(F) // The result of this same Y-combinator function call...
// (Here is where the recursion is introduced.)
)
(t); // And passes the argument into the work function.
}
Rather than the factorial calling itself, what happens is that the factorial calls the factorial generator (returned by the recursive call to Y-Combinator). And depending on the current value of t the function returned from the generator will either call the generator again, with t - 1, or just return 1, terminating the recursion.
It's complicated and cryptic, but it all shakes out at run-time, and the key to its working is "deferred execution", and the breaking up of the recursion to span two functions. The inner F is passed as an argument, to be called in the next iteration, only if necessary.
A: A fixed point combinator (or fixed-point operator) is a higher-order function that computes a fixed point of other functions. This operation is relevant in programming language theory because it allows the implementation of recursion in the form of a rewrite rule, without explicit support from the language's runtime engine. (src Wikipedia)
A: The y-combinator implements anonymous recursion. So instead of
function fib( n ){ if( n<=1 ) return n; else return fib(n-1)+fib(n-2) }
you can do
function ( fib, n ){ if( n<=1 ) return n; else return fib(n-1)+fib(n-2) }
of course, the y-combinator only works in call-by-name languages. If you want to use this in any normal call-by-value language, then you will need the related z-combinator (y-combinator will diverge/infinite-loop).
A: The this-operator can simplify your life:
var Y = function(f) {
return (function(g) {
return g(g);
})(function(h) {
return function() {
return f.apply(h(h), arguments);
};
});
};
Then you avoid the extra function:
var fac = Y(function(n) {
return n == 0 ? 1 : n * this(n - 1);
});
Finally, you call fac(5).
A: For programmers who haven't encountered functional programming in depth, and don't care to start now, but are mildly curious:
The Y combinator is a formula which lets you implement recursion in a situation where functions can't have names but can be passed around as arguments, used as return values, and defined within other functions.
It works by passing the function to itself as an argument, so it can call itself.
It's part of the lambda calculus, which is really maths but is effectively a programming language, and is pretty fundamental to computer science and especially to functional programming.
The day to day practical value of the Y combinator is limited, since programming languages tend to let you name functions.
In case you need to identify it in a police lineup, it looks like this:
Y = λf.(λx.f (x x)) (λx.f (x x))
You can usually spot it because of the repeated (λx.f (x x)).
The λ symbols are the Greek letter lambda, which gives the lambda calculus its name, and there's a lot of (λx.t) style terms because that's what the lambda calculus looks like.
A: y-combinator in JavaScript:
var Y = function(f) {
return (function(g) {
return g(g);
})(function(h) {
return function() {
return f(h(h)).apply(null, arguments);
};
});
};
var factorial = Y(function(recurse) {
return function(x) {
return x == 0 ? 1 : x * recurse(x-1);
};
});
factorial(5) // -> 120
Edit:
I learn a lot from looking at code, but this one is a bit tough to swallow without some background - sorry about that. With some general knowledge presented by other answers, you can begin to pick apart what is happening.
The Y function is the "y-combinator". Now take a look at the var factorial line where Y is used. Notice you pass a function to it that has a parameter (in this example, recurse) that is also used later on in the inner function. The parameter name basically becomes the name of the inner function allowing it to perform a recursive call (since it uses recurse() in it's definition.) The y-combinator performs the magic of associating the otherwise anonymous inner function with the parameter name of the function passed to Y.
For the full explanation of how Y does the magic, checked out the linked article (not by me btw.)
A: Anonymous recursion
A fixed-point combinator is a higher-order function fix that by definition satisfies the equivalence
forall f. fix f = f (fix f)
fix f represents a solution x to the fixed-point equation
x = f x
The factorial of a natural number can be proved by
fact 0 = 1
fact n = n * fact (n - 1)
Using fix, arbitrary constructive proofs over general/μ-recursive functions can be derived without nonymous self-referentiality.
fact n = (fix fact') n
where
fact' rec n = if n == 0
then 1
else n * rec (n - 1)
such that
fact 3
= (fix fact') 3
= fact' (fix fact') 3
= if 3 == 0 then 1 else 3 * (fix fact') (3 - 1)
= 3 * (fix fact') 2
= 3 * fact' (fix fact') 2
= 3 * if 2 == 0 then 1 else 2 * (fix fact') (2 - 1)
= 3 * 2 * (fix fact') 1
= 3 * 2 * fact' (fix fact') 1
= 3 * 2 * if 1 == 0 then 1 else 1 * (fix fact') (1 - 1)
= 3 * 2 * 1 * (fix fact') 0
= 3 * 2 * 1 * fact' (fix fact') 0
= 3 * 2 * 1 * if 0 == 0 then 1 else 0 * (fix fact') (0 - 1)
= 3 * 2 * 1 * 1
= 6
This formal proof that
fact 3 = 6
methodically uses the fixed-point combinator equivalence for rewrites
fix fact' -> fact' (fix fact')
Lambda calculus
The untyped lambda calculus formalism consists in a context-free grammar
E ::= v Variable
| λ v. E Abstraction
| E E Application
where v ranges over variables, together with the beta and eta reduction rules
(λ x. B) E -> B[x := E] Beta
λ x. E x -> E if x doesn’t occur free in E Eta
Beta reduction substitutes all free occurrences of the variable x in the abstraction (“function”) body B by the expression (“argument”) E. Eta reduction eliminates redundant abstraction. It is sometimes omitted from the formalism. An irreducible expression, to which no reduction rule applies, is in normal or canonical form.
λ x y. E
is shorthand for
λ x. λ y. E
(abstraction multiarity),
E F G
is shorthand for
(E F) G
(application left-associativity),
λ x. x
and
λ y. y
are alpha-equivalent.
Abstraction and application are the two only “language primitives” of the lambda calculus, but they allow encoding of arbitrarily complex data and operations.
The Church numerals are an encoding of the natural numbers similar to the Peano-axiomatic naturals.
0 = λ f x. x No application
1 = λ f x. f x One application
2 = λ f x. f (f x) Twofold
3 = λ f x. f (f (f x)) Threefold
. . .
SUCC = λ n f x. f (n f x) Successor
ADD = λ n m f x. n f (m f x) Addition
MULT = λ n m f x. n (m f) x Multiplication
. . .
A formal proof that
1 + 2 = 3
using the rewrite rule of beta reduction:
ADD 1 2
= (λ n m f x. n f (m f x)) (λ g y. g y) (λ h z. h (h z))
= (λ m f x. (λ g y. g y) f (m f x)) (λ h z. h (h z))
= (λ m f x. (λ y. f y) (m f x)) (λ h z. h (h z))
= (λ m f x. f (m f x)) (λ h z. h (h z))
= λ f x. f ((λ h z. h (h z)) f x)
= λ f x. f ((λ z. f (f z)) x)
= λ f x. f (f (f x)) Normal form
= 3
Combinators
In lambda calculus, combinators are abstractions that contain no free variables. Most simply: I, the identity combinator
λ x. x
isomorphic to the identity function
id x = x
Such combinators are the primitive operators of combinator calculi like the SKI system.
S = λ x y z. x z (y z)
K = λ x y. x
I = λ x. x
Beta reduction is not strongly normalizing; not all reducible expressions, “redexes”, converge to normal form under beta reduction. A simple example is divergent application of the omega ω combinator
λ x. x x
to itself:
(λ x. x x) (λ y. y y)
= (λ y. y y) (λ y. y y)
. . .
= _|_ Bottom
Reduction of leftmost subexpressions (“heads”) is prioritized. Applicative order normalizes arguments before substitution, normal order does not. The two strategies are analogous to eager evaluation, e.g. C, and lazy evaluation, e.g. Haskell.
K (I a) (ω ω)
= (λ k l. k) ((λ i. i) a) ((λ x. x x) (λ y. y y))
diverges under eager applicative-order beta reduction
= (λ k l. k) a ((λ x. x x) (λ y. y y))
= (λ l. a) ((λ x. x x) (λ y. y y))
= (λ l. a) ((λ y. y y) (λ y. y y))
. . .
= _|_
since in strict semantics
forall f. f _|_ = _|_
but converges under lazy normal-order beta reduction
= (λ l. ((λ i. i) a)) ((λ x. x x) (λ y. y y))
= (λ l. a) ((λ x. x x) (λ y. y y))
= a
If an expression has a normal form, normal-order beta reduction will find it.
Y
The essential property of the Y fixed-point combinator
λ f. (λ x. f (x x)) (λ x. f (x x))
is given by
Y g
= (λ f. (λ x. f (x x)) (λ x. f (x x))) g
= (λ x. g (x x)) (λ x. g (x x)) = Y g
= g ((λ x. g (x x)) (λ x. g (x x))) = g (Y g)
= g (g ((λ x. g (x x)) (λ x. g (x x)))) = g (g (Y g))
. . . . . .
The equivalence
Y g = g (Y g)
is isomorphic to
fix f = f (fix f)
The untyped lambda calculus can encode arbitrary constructive proofs over general/μ-recursive functions.
FACT = λ n. Y FACT' n
FACT' = λ rec n. if n == 0 then 1 else n * rec (n - 1)
FACT 3
= (λ n. Y FACT' n) 3
= Y FACT' 3
= FACT' (Y FACT') 3
= if 3 == 0 then 1 else 3 * (Y FACT') (3 - 1)
= 3 * (Y FACT') (3 - 1)
= 3 * FACT' (Y FACT') 2
= 3 * if 2 == 0 then 1 else 2 * (Y FACT') (2 - 1)
= 3 * 2 * (Y FACT') 1
= 3 * 2 * FACT' (Y FACT') 1
= 3 * 2 * if 1 == 0 then 1 else 1 * (Y FACT') (1 - 1)
= 3 * 2 * 1 * (Y FACT') 0
= 3 * 2 * 1 * FACT' (Y FACT') 0
= 3 * 2 * 1 * if 0 == 0 then 1 else 0 * (Y FACT') (0 - 1)
= 3 * 2 * 1 * 1
= 6
(Multiplication delayed, confluence)
For Churchian untyped lambda calculus, there has been shown to exist a recursively enumerable infinity of fixed-point combinators besides Y.
X = λ f. (λ x. x x) (λ x. f (x x))
Y' = (λ x y. x y x) (λ y x. y (x y x))
Z = λ f. (λ x. f (λ v. x x v)) (λ x. f (λ v. x x v))
Θ = (λ x y. y (x x y)) (λ x y. y (x x y))
. . .
Normal-order beta reduction makes the unextended untyped lambda calculus a Turing-complete rewrite system.
In Haskell, the fixed-point combinator can be elegantly implemented
fix :: forall t. (t -> t) -> t
fix f = f (fix f)
Haskell’s laziness normalizes to a finity before all subexpressions have been evaluated.
primes :: Integral t => [t]
primes = sieve [2 ..]
where
sieve = fix (\ rec (p : ns) ->
p : rec [n | n <- ns
, n `rem` p /= 0])
*
*David Turner: Church's Thesis and Functional Programming
*Alonzo Church: An Unsolvable Problem of Elementary Number Theory
*Lambda calculus
*Church–Rosser theorem
A: If you're ready for a long read, Mike Vanier has a great explanation. Long story short, it allows you to implement recursion in a language that doesn't necessarily support it natively.
A: Other answers provide pretty concise answer to this, without one important fact: You don't need to implement fixed point combinator in any practical language in this convoluted way and doing so serves no practical purpose (except "look, I know what Y-combinator is"). It's important theoretical concept, but of little practical value.
A: I've lifted this from http://www.mail-archive.com/boston-pm@mail.pm.org/msg02716.html which is an explanation I wrote several years ago.
I'll use JavaScript in this example, but many other languages will work as well.
Our goal is to be able to write a recursive function of 1
variable using only functions of 1 variables and no
assignments, defining things by name, etc. (Why this is our
goal is another question, let's just take this as the
challenge that we're given.) Seems impossible, huh? As
an example, let's implement factorial.
Well step 1 is to say that we could do this easily if we
cheated a little. Using functions of 2 variables and
assignment we can at least avoid having to use
assignment to set up the recursion.
// Here's the function that we want to recurse.
X = function (recurse, n) {
if (0 == n)
return 1;
else
return n * recurse(recurse, n - 1);
};
// This will get X to recurse.
Y = function (builder, n) {
return builder(builder, n);
};
// Here it is in action.
Y(
X,
5
);
Now let's see if we can cheat less. Well firstly we're using
assignment, but we don't need to. We can just write X and
Y inline.
// No assignment this time.
function (builder, n) {
return builder(builder, n);
}(
function (recurse, n) {
if (0 == n)
return 1;
else
return n * recurse(recurse, n - 1);
},
5
);
But we're using functions of 2 variables to get a function of 1
variable. Can we fix that? Well a smart guy by the name of
Haskell Curry has a neat trick, if you have good higher order
functions then you only need functions of 1 variable. The
proof is that you can get from functions of 2 (or more in the
general case) variables to 1 variable with a purely
mechanical text transformation like this:
// Original
F = function (i, j) {
...
};
F(i,j);
// Transformed
F = function (i) { return function (j) {
...
}};
F(i)(j);
where ... remains exactly the same. (This trick is called
"currying" after its inventor. The language Haskell is also
named for Haskell Curry. File that under useless trivia.)
Now just apply this transformation everywhere and we get
our final version.
// The dreaded Y-combinator in action!
function (builder) { return function (n) {
return builder(builder)(n);
}}(
function (recurse) { return function (n) {
if (0 == n)
return 1;
else
return n * recurse(recurse)(n - 1);
}})(
5
);
Feel free to try it. alert() that return, tie it to a button, whatever.
That code calculates factorials, recursively, without using
assignment, declarations, or functions of 2 variables. (But
trying to trace how it works is likely to make your head spin.
And handing it, without the derivation, just slightly reformatted
will result in code that is sure to baffle and confuse.)
You can replace the 4 lines that recursively define factorial with
any other recursive function that you want.
A: I think the best way to answer this is to pick a language, like JavaScript:
function factorial(num)
{
// If the number is less than 0, reject it.
if (num < 0) {
return -1;
}
// If the number is 0, its factorial is 1.
else if (num == 0) {
return 1;
}
// Otherwise, call this recursive procedure again.
else {
return (num * factorial(num - 1));
}
}
Now rewrite it so that it doesn't use the name of the function inside the function, but still calls it recursively.
The only place the function name factorial should be seen is at the call site.
Hint: you can't use names of functions, but you can use names of parameters.
Work the problem. Don't look it up. Once you solve it, you will understand what problem the y-combinator solves.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "432"
}
|
Q: What is the difference between Views and Materialized Views in Oracle? What is the difference between Views and Materialized Views in Oracle?
A: A view uses a query to pull data from the underlying tables.
A materialized view is a table on disk that contains the result set of a query.
Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH has been in place since at least Oracle 10.
A: Materialized views are disk based and are updated periodically based upon the query definition.
Views are virtual only and run the query definition each time they are accessed.
A: Adding to Mike McAllister's pretty-thorough answer...
Materialized views can only be set to refresh automatically through the database detecting changes when the view query is considered simple by the compiler. If it's considered too complex, it won't be able to set up what are essentially internal triggers to track changes in the source tables to only update the changed rows in the mview table.
When you create a materialized view, you'll find that Oracle creates both the mview and as a table with the same name, which can make things confusing.
A: Materialized views are the logical view of data-driven by the select query but the result of the query will get stored in the table or disk, also the definition of the query will also store in the database.
The performance of Materialized view it is better than normal View because the data of materialized view will be stored in table and table may be indexed so faster for joining also joining is done at the time of materialized views refresh time so no need to every time fire join statement as in case of view.
Other difference includes in case of View we always get latest data but in case of Materialized view we need to refresh the view for getting latest data.
In case of Materialized view we need an extra trigger or some automatic method so that we can keep MV refreshed, this is not required for views in the database.
A: Views
They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.
The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.
Materialized views
They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.
In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.
Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.
Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.
Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.
A: Materialised view - a table on a disk that contains the result set of a query
Non-materiased view - a query that pulls data from the underlying table
A: Views are essentially logical table-like structures populated on the fly by a given query. The results of a view query are not stored anywhere on disk and the view is recreated every time the query is executed. Materialized views are actual structures stored within the database and written to disk. They are updated based on the parameters defined when they are created.
A: View: View is just a named query. It doesn't store anything. When there is a query on view, it runs the query of the view definition. Actual data comes from table.
Materialised views: Stores data physically and get updated periodically. While querying MV, it gives data from MV.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "419"
}
|
Q: Baseline snaplines in custom Winforms controls I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.
A: Thanks to all those for the help. This was a tough one to swallow. The thought having a private sub-class in every UserControl wasn't very palatable.
I came up with this base class to help out..
[Designer(typeof(UserControlSnapLineDesigner))]
public class UserControlBase : UserControl
{
protected virtual Control SnapLineControl { get { return null; } }
private class UserControlSnapLineDesigner : ControlDesigner
{
public override IList SnapLines
{
get
{
IList snapLines = base.SnapLines;
Control targetControl = (this.Control as UserControlBase).SnapLineControl;
if (targetControl == null)
return snapLines;
using (ControlDesigner controlDesigner = TypeDescriptor.CreateDesigner(targetControl,
typeof(IDesigner)) as ControlDesigner)
{
if (controlDesigner == null)
return snapLines;
controlDesigner.Initialize(targetControl);
foreach (SnapLine line in controlDesigner.SnapLines)
{
if (line.SnapLineType == SnapLineType.Baseline)
{
snapLines.Add(new SnapLine(SnapLineType.Baseline, line.Offset + targetControl.Top,
line.Filter, line.Priority));
break;
}
}
}
return snapLines;
}
}
}
}
Next, derive your UserControl from this base:
public partial class MyControl : UserControlBase
{
protected override Control SnapLineControl
{
get
{
return txtTextBox;
}
}
...
}
Thanks again for posting this.
A: VB.Net Version:
Note: you have to change the txtDescription to the Textbox or another internal control name that you use. and ctlUserControl to your usercontrol name
<Designer(GetType(ctlUserControl.MyCustomDesigner))> _
Partial Public Class ctlUserControl
'...
'Your Usercontrol class specific code
'...
Class MyCustomDesigner
Inherits ControlDesigner
Public Overloads Overrides ReadOnly Property SnapLines() As IList
Get
' Code from above
Dim lines As IList = MyBase.SnapLines
' *** This will need to be modified to match your user control
Dim control__1 As ctlUserControl = TryCast(Me.Control, ctlUserControl)
If control__1 Is Nothing Then Return lines
' *** This will need to be modified to match the item in your user control
' This is the control in your UC that you want SnapLines for the entire UC
Dim designer As IDesigner = TypeDescriptor.CreateDesigner(control__1.txtDescription, GetType(IDesigner))
If designer Is Nothing Then
Return lines
End If
' *** This will need to be modified to match the item in your user control
designer.Initialize(control__1.txtDescription)
Using designer
Dim boxDesigner As ControlDesigner = TryCast(designer, ControlDesigner)
If boxDesigner Is Nothing Then
Return lines
End If
For Each line As SnapLine In boxDesigner.SnapLines
If line.SnapLineType = SnapLineType.Baseline Then
' *** This will need to be modified to match the item in your user control
lines.Add(New SnapLine(SnapLineType.Baseline, line.Offset + control__1.txtDescription.Top, line.Filter, line.Priority))
Exit For
End If
Next
End Using
Return lines
End Get
End Property
End Class
End Class
A: As an update to the Miral's answer.. here are a few of the "missing steps", for someone new that's looking how to do this. :) The C# code above is almost 'drop-in' ready, with the exception of changing a few of the values to reference the UserControl that will be modified.
Possible References Needed:
System.Design (@robyaw)
Usings needed:
using System.Windows.Forms.Design;
using System.Windows.Forms.Design.Behavior;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
On your UserControl you need the following Attribute:
[Designer(typeof(MyCustomDesigner))]
Then you need a "designer" class that will have the SnapLines override:
private class MyCustomerDesigner : ControlDesigner {
public override IList SnapLines {
get {
/* Code from above */
IList snapLines = base.SnapLines;
// *** This will need to be modified to match your user control
MyControl control = Control as MyControl;
if (control == null) { return snapLines; }
// *** This will need to be modified to match the item in your user control
// This is the control in your UC that you want SnapLines for the entire UC
IDesigner designer = TypeDescriptor.CreateDesigner(
control.textBoxValue, typeof(IDesigner));
if (designer == null) { return snapLines; }
// *** This will need to be modified to match the item in your user control
designer.Initialize(control.textBoxValue);
using (designer)
{
ControlDesigner boxDesigner = designer as ControlDesigner;
if (boxDesigner == null) { return snapLines; }
foreach (SnapLine line in boxDesigner.SnapLines)
{
if (line.SnapLineType == SnapLineType.Baseline)
{
// *** This will need to be modified to match the item in your user control
snapLines.Add(new SnapLine(SnapLineType.Baseline,
line.Offset + control.textBoxValue.Top,
line.Filter, line.Priority));
break;
}
}
}
return snapLines;
}
}
}
}
A: I just had a similar need, and I solved it like this:
public override IList SnapLines
{
get
{
IList snapLines = base.SnapLines;
MyControl control = Control as MyControl;
if (control == null) { return snapLines; }
IDesigner designer = TypeDescriptor.CreateDesigner(
control.textBoxValue, typeof(IDesigner));
if (designer == null) { return snapLines; }
designer.Initialize(control.textBoxValue);
using (designer)
{
ControlDesigner boxDesigner = designer as ControlDesigner;
if (boxDesigner == null) { return snapLines; }
foreach (SnapLine line in boxDesigner.SnapLines)
{
if (line.SnapLineType == SnapLineType.Baseline)
{
snapLines.Add(new SnapLine(SnapLineType.Baseline,
line.Offset + control.textBoxValue.Top,
line.Filter, line.Priority));
break;
}
}
}
return snapLines;
}
}
This way it's actually creating a temporary sub-designer for the subcontrol in order to find out where the "real" baseline snapline is.
This seemed reasonably performant in testing, but if perf becomes a concern (and if the internal textbox doesn't move) then most of this code can be extracted to the Initialize method.
This also assumes that the textbox is a direct child of the UserControl. If there are other layout-affecting controls in the way then the offset calculation becomes a bit more complicated.
A: You're on the right track. You will need to override the SnapLines property in your designr and do something like this:
Public Overrides ReadOnly Property SnapLines() As System.Collections.IList
Get
Dim snapLinesList As ArrayList = TryCast(MyBase.SnapLines, ArrayList)
Dim offset As Integer
Dim ctrl As MyControl = TryCast(Me.Control, MyControl)
If ctrl IsNot Nothing AndAlso ctrl.TextBox1 IsNot Nothing Then
offset = ctrl.TextBox1.Bottom - 5
End If
snapLinesList.Add(New SnapLine(SnapLineType.Baseline, offset, SnapLinePriority.Medium))
Return snapLinesList
End Get
End Property
In this example the usercontrol contains a textbox. The code adds a new snapline that represents the baseline for the textbox. The important thing is to calculate the offset correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: How do you detect dialup, broadband or wireless Internet connections in C++ for Windows? I have an installation program (just a regular C++ MFC program, not Windows Installer based) that needs to set some registry values based on the type of Internet connection: broadband, dialup, and/or wireless. Right now this information is being determined by asking a series of yes or no questions. The problem is that the person doing the installations is not the same person that owns and uses the computer, so they're not always sure what the answers to these questions should be. Is there a way to programatically determine any of this information? The code is written in C++ (and optionally MFC) for Windows XP and up. .NET-based solutions are not an option because I don't want to have to determine if the framework is installed before our installation program can run.
To clarify, the issue is mainly that wireless and dialup connections are not "always-on", which creates a need for our product to behave a different way because our server is not always available. So a strictly speed-measuring solution wouldn't help, though there is a setting that's speed dependent so that the product doesn't try to send MB of information through a dialup connection as soon as it connects.
A: [I have no idea how to get exactly the information you asked for, but...] Maybe you could rephrase (for yourself) what you try to accomplish? Like, instead of asking "does the user have broadband or dialup", ask "how much bandwidth does the user's internet connection have" - and then you can try to answer the rephrased question without any user input (like by measuring bandwidth).
Btw. if you ask the user just for "broadband or dialup", you might encounter some problems:
*
*what if the user has some connection type you didn't anticipate?
*what if the user doesn't know (because there's just an ethernet cable going to a PPPoE DSL modem/router)?
*what if the user is connected through a series of connections (VPN via dialup, to some other network which has broadband?)
Asking for "capabilities" instead of "type" might be more useful in those cases.
A: Use InternetGetConnectedState API to retrieve internet connection state.
I tested it and it works fine.
I found this document which can help:
http://www.pcausa.com/resources/InetActive.txt
A: Regarding the question "is the internet connection permanent or not?":
*
*best way would be probably to make the app robust enough to always cope with a non-permanent connection :-) which would work the same with dialup and broadband...
*alternatively, maybe you can find out how long the user's internet connection has been established already, and compare with system uptime? If the connection has been online for almost as long as the computer was running, it's probably a permanent connection.
Anyway, these heuristics will probably fail for obscure connection types.
Also, regarding the point about not sending lots of data: if people have a "broadband + low traffic limit" tariff, you shouldn't send lots of data either even if bandwidth allows :-)
A: Best bet would be to grab the default active network connection, ensure it is an internet connection (ping google.com or similar) and then ask it what type of device it is. You should be able to determine from that what connection the user has.
I'm fairly confident this is possible, but not sure how to go about it though.
A: I think you should just do a quick connection-speed test. Just download some specific sized files, time how long it takes, and you'll know the speed. I agree with the other guy, don't ask them what type of connection they have, what's more important is the speed. Perhaps next year they come out with 100mbit dialup...do you want everyone using this amazing new device to get the crappy lowbandwidth version of your app?
A: I would agree with oliver, as you imply: you have the functionality already to cope with connection loss, why not enable it by default.
Broadband connections can get messed up to: routersoftware that freezes (happens a lot to me), or poweradapter that fries, ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to encode the filename parameter of Content-Disposition header in HTTP? Web applications that want to force a resource to be downloaded rather than directly rendered in a Web browser issue a Content-Disposition header in the HTTP response of the form:
Content-Disposition: attachment; filename=FILENAME
The filename parameter can be used to suggest a name for the file into which the resource is downloaded by the browser. RFC 2183 (Content-Disposition), however, states in section 2.3 (The Filename Parameter) that the file name can only use US-ASCII characters:
Current [RFC 2045] grammar restricts
parameter values (and hence
Content-Disposition filenames) to
US-ASCII. We recognize the great
desirability of allowing arbitrary
character sets in filenames, but it is
beyond the scope of this document to
define the necessary mechanisms.
There is empirical evidence, nevertheless, that most popular Web browsers today seem to permit non-US-ASCII characters yet (for the lack of a standard) disagree on the encoding scheme and character set specification of the file name. Question is then, what are the various schemes and encodings employed by the popular browsers if the file name “naïvefile” (without quotes and where the third letter is U+00EF) needed to be encoded into the Content-Disposition header?
For the purpose of this question, popular browsers being:
*
*Google Chrome
*Safari
*Internet Explorer or Edge
*Firefox
*Opera
A: In ASP.NET Web API, I url encode the filename:
public static class HttpRequestMessageExtensions
{
public static HttpResponseMessage CreateFileResponse(this HttpRequestMessage request, byte[] data, string filename, string mediaType)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(data);
stream.Position = 0;
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType =
new MediaTypeHeaderValue(mediaType);
// URL-Encode filename
// Fixes behavior in IE, that filenames with non US-ASCII characters
// stay correct (not "_utf-8_.......=_=").
var encodedFilename = HttpUtility.UrlEncode(filename, Encoding.UTF8);
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") { FileName = encodedFilename };
return response;
}
}
A: RFC 6266 describes the “Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)”. Quoting from that:
6. Internationalization Considerations
The “filename*” parameter (Section 4.3), using the encoding defined
in [RFC5987], allows the server to transmit characters outside the
ISO-8859-1 character set, and also to optionally specify the language
in use.
And in their examples section:
This example is the same as the one above, but adding the "filename"
parameter for compatibility with user agents not implementing
RFC 5987:
Content-Disposition: attachment;
filename="EURO rates";
filename*=utf-8''%e2%82%ac%20rates
Note: Those user agents that do not support the RFC 5987 encoding
ignore “filename*” when it occurs after “filename”.
In Appendix D there is also a long list of suggestions to increase interoperability. It also points at a site which compares implementations. Current all-pass tests suitable for common file names include:
*
*attwithisofnplain: plain ISO-8859-1 file name with double quotes and without encoding. This requires a file name which is all ISO-8859-1 and does not contain percent signs, at least not in front of hex digits.
*attfnboth: two parameters in the order described above. Should work for most file names on most browsers, although IE8 will use the “filename” parameter.
That RFC 5987 in turn references RFC 2231, which describes the actual format. 2231 is primarily for mail, and 5987 tells us what parts may be used for HTTP headers as well. Don't confuse this with MIME headers used inside a multipart/form-data HTTP body, which is governed by RFC 2388 (section 4.4 in particular) and the HTML 5 draft.
A: In PHP this did it for me (assuming the filename is UTF8 encoded):
header('Content-Disposition: attachment;'
. 'filename="' . addslashes(utf8_decode($filename)) . '";'
. 'filename*=utf-8\'\'' . rawurlencode($filename));
Tested against IE8-11, Firefox and Chrome.
If the browser can interpret filename*=utf-8 it will use the UTF8 version of the filename, else it will use the decoded filename. If your filename contains characters that can't be represented in ISO-8859-1 you might want to consider using iconv instead.
A: Just an update since I was trying all this stuff today in response to a customer issue
*
*With the exception of Safari configured for Japanese, all browsers our customer tested worked best with filename=text.pdf - where text is a customer value serialized by ASP.Net/IIS in utf-8 without url encoding. For some reason, Safari configured for English would accept and properly save a file with utf-8 Japanese name but that same browser configured for Japanese would save the file with the utf-8 chars uninterpreted. All other browsers tested seemed to work best/fine (regardless of language configuration) with the filename utf-8 encoded without url encoding.
*I could not find a single browser implementing Rfc5987/8187 at all. I tested with the latest Chrome, Firefox builds plus IE 11 and Edge. I tried setting the header with just filename*=utf-8''texturlencoded.pdf, setting it with both filename=text.pdf; filename*=utf-8''texturlencoded.pdf. Not one feature of Rfc5987/8187 appeared to be getting processed correctly in any of the above.
A: If you are using a nodejs backend you can use the following code I found here
var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''"
+ encodeRFC5987ValueChars(fileName);
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}
A: I know this is an old post but it is still very relevant. I have found that modern browsers support rfc5987, which allows utf-8 encoding, percentage encoded (url-encoded). Then Naïve file.txt becomes:
Content-Disposition: attachment; filename*=UTF-8''Na%C3%AFve%20file.txt
Safari (5) does not support this. Instead you should use the Safari standard of writing the file name directly in your utf-8 encoded header:
Content-Disposition: attachment; filename=Naïve file.txt
IE8 and older don't support it either and you need to use the IE standard of utf-8 encoding, percentage encoded:
Content-Disposition: attachment; filename=Na%C3%AFve%20file.txt
In ASP.Net I use the following code:
string contentDisposition;
if (Request.Browser.Browser == "IE" && (Request.Browser.Version == "7.0" || Request.Browser.Version == "8.0"))
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName);
else if (Request.Browser.Browser == "Safari")
contentDisposition = "attachment; filename=" + fileName;
else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(fileName);
Response.AddHeader("Content-Disposition", contentDisposition);
I tested the above using IE7, IE8, IE9, Chrome 13, Opera 11, FF5, Safari 5.
Update November 2013:
Here is the code I currently use. I still have to support IE8, so I cannot get rid of the first part. It turns out that browsers on Android use the built in Android download manager and it cannot reliably parse file names in the standard way.
string contentDisposition;
if (Request.Browser.Browser == "IE" && (Request.Browser.Version == "7.0" || Request.Browser.Version == "8.0"))
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName);
else if (Request.UserAgent != null && Request.UserAgent.ToLowerInvariant().Contains("android")) // android built-in download manager (all browsers on android)
contentDisposition = "attachment; filename=\"" + MakeAndroidSafeFileName(fileName) + "\"";
else
contentDisposition = "attachment; filename=\"" + fileName + "\"; filename*=UTF-8''" + Uri.EscapeDataString(fileName);
Response.AddHeader("Content-Disposition", contentDisposition);
The above now tested in IE7-11, Chrome 32, Opera 12, FF25, Safari 6, using this filename for download: 你好abcABCæøåÆØÅäöüïëêîâéíáóúýñ½§!#¤%&()=`@£$€{[]}+´¨^~'-_,;.txt
On IE7 it works for some characters but not all. But who cares about IE7 nowadays?
This is the function I use to generate safe file names for Android. Note that I don't know which characters are supported on Android but that I have tested that these work for sure:
private static readonly Dictionary<char, char> AndroidAllowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._-+,@£$€!½§~'=()[]{}0123456789".ToDictionary(c => c);
private string MakeAndroidSafeFileName(string fileName)
{
char[] newFileName = fileName.ToCharArray();
for (int i = 0; i < newFileName.Length; i++)
{
if (!AndroidAllowedChars.ContainsKey(newFileName[i]))
newFileName[i] = '_';
}
return new string(newFileName);
}
@TomZ: I tested in IE7 and IE8 and it turned out that I did not need to escape apostrophe ('). Do you have an example where it fails?
@Dave Van den Eynde: Combining the two file names on one line as according to RFC6266 works except for Android and IE7+8 and I have updated the code to reflect this. Thank you for the suggestion.
@Thilo: No idea about GoodReader or any other non-browser. You might have some luck using the Android approach.
@Alex Zhukovskiy: I don't know why but as discussed on Connect it doesn't seem to work terribly well.
A: I tested the following code in all major browsers, including older Explorers (via the compatibility mode), and it works well everywhere:
$filename = $_GET['file']; //this string from $_GET is already decoded
if (strstr($_SERVER['HTTP_USER_AGENT'],"MSIE"))
$filename = rawurlencode($filename);
header('Content-Disposition: attachment; filename="'.$filename.'"');
A: I ended up with the following code in my "download.php" script (based on this blogpost and these test cases).
$il1_filename = utf8_decode($filename);
$to_underscore = "\"\\#*;:|<>/?";
$safe_filename = strtr($il1_filename, $to_underscore, str_repeat("_", strlen($to_underscore)));
header("Content-Disposition: attachment; filename=\"$safe_filename\""
.( $safe_filename === $filename ? "" : "; filename*=UTF-8''".rawurlencode($filename) ));
This uses the standard way of filename="..." as long as there are only iso-latin1 and "safe" characters used; if not, it adds the filename*=UTF-8'' url-encoded way. According to this specific test case, it should work from MSIE9 up, and on recent FF, Chrome, Safari; on lower MSIE version, it should offer filename containing the ISO8859-1 version of the filename, with underscores on characters not in this encoding.
Final note: the max. size for each header field is 8190 bytes on apache. UTF-8 can be up to four bytes per character; after rawurlencode, it is x3 = 12 bytes per one character. Pretty inefficient, but it should still be theoretically possible to have more than 600 "smiles" %F0%9F%98%81 in the filename.
A: From .NET 4.5 (and Core 1.0) you can use ContentDispositionHeaderValue to do the formatting for you.
var fileName = "Naïve file.txt";
var h = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
h.FileNameStar = fileName;
h.FileName = "fallback-ascii-name.txt";
Response.Headers.Add("Content-Disposition", h.ToString());
h.ToString() Will result in:
attachment; filename*=utf-8''Na%C3%AFve%20file.txt; filename=fallback-ascii-name.txt
A: PHP framework Symfony 4 has $filenameFallback in HeaderUtils::makeDisposition.
You can look into this function for details - it is similar to the answers above.
Usage example:
$filenameFallback = preg_replace('#^.*\.#', md5($filename) . '.', $filename);
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename, $filenameFallback);
$response->headers->set('Content-Disposition', $disposition);
A: For those who need a JavaScript way of encoding the header, I found that this function works well:
function createContentDispositionHeader(filename:string) {
const encoded = encodeURIComponent(filename);
return `attachment; filename*=UTF-8''${encoded}; filename="${encoded}"`;
}
This is based on what Nextcloud seems to be doing when downloading a file. The filename appears first as UTF-8 encoded, and possibly for compatibility with some browsers, the filename also appears without the UTF-8 prefix.
A: *
*There is no interoperable way to encode non-ASCII names in Content-Disposition. Browser compatibility is a mess.
*The theoretically correct syntax for use of UTF-8 in Content-Disposition is very weird: filename*=UTF-8''foo%c3%a4 (yes, that's an asterisk, and no quotes except an empty single quote in the middle)
*This header is kinda-not-quite-standard (HTTP/1.1 spec acknowledges its existence, but doesn't require clients to support it).
There is a simple and very robust alternative: use a URL that contains the filename you want.
When the name after the last slash is the one you want, you don't need any extra headers!
This trick works:
/real_script.php/fake_filename.doc
And if your server supports URL rewriting (e.g. mod_rewrite in Apache) then you can fully hide the script part.
Characters in URLs should be in UTF-8, urlencoded byte-by-byte:
/mot%C3%B6rhead # motörhead
A: The following document linked from the draft RFC mentioned by Jim in his answer further addresses the question and definitely worth a direct note here:
Test Cases for HTTP Content-Disposition header and RFC 2231/2047 Encoding
A: Put the file name in double quotes. Solved the problem for me. Like this:
Content-Disposition: attachment; filename="My Report.doc"
http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download
I've tested multiple options. Browsers do not support the specs and act differently, I believe double quotes is the best option.
A: I use the following code snippets for encoding (assuming fileName contains the filename and extension of the file, i.e.: test.txt):
PHP:
if ( strpos ( $_SERVER [ 'HTTP_USER_AGENT' ], "MSIE" ) > 0 )
{
header ( 'Content-Disposition: attachment; filename="' . rawurlencode ( $fileName ) . '"' );
}
else
{
header( 'Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode ( $fileName ) );
}
Java:
fileName = request.getHeader ( "user-agent" ).contains ( "MSIE" ) ? URLEncoder.encode ( fileName, "utf-8") : MimeUtility.encodeWord ( fileName );
response.setHeader ( "Content-disposition", "attachment; filename=\"" + fileName + "\"");
A: There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."
RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.
A: in asp.net mvc2 i use something like this:
return File(
tempFile
, "application/octet-stream"
, HttpUtility.UrlPathEncode(fileName)
);
I guess if you don't use mvc(2) you could just encode the filename using
HttpUtility.UrlPathEncode(fileName)
A: Classic ASP Solution
Most modern browsers support passing the Filename as UTF-8 now but as was the case with a File Upload solution I use that was based on FreeASPUpload.Net (site no longer exists, link points to archive.org) it wouldn't work as the parsing of the binary relied on reading single byte ASCII encoded strings, which worked fine when you passed UTF-8 encoded data until you get to characters ASCII doesn't support.
However I was able to find a solution to get the code to read and parse the binary as UTF-8.
Public Function BytesToString(bytes) 'UTF-8..
Dim bslen
Dim i, k , N
Dim b , count
Dim str
bslen = LenB(bytes)
str=""
i = 0
Do While i < bslen
b = AscB(MidB(bytes,i+1,1))
If (b And &HFC) = &HFC Then
count = 6
N = b And &H1
ElseIf (b And &HF8) = &HF8 Then
count = 5
N = b And &H3
ElseIf (b And &HF0) = &HF0 Then
count = 4
N = b And &H7
ElseIf (b And &HE0) = &HE0 Then
count = 3
N = b And &HF
ElseIf (b And &HC0) = &HC0 Then
count = 2
N = b And &H1F
Else
count = 1
str = str & Chr(b)
End If
If i + count - 1 > bslen Then
str = str&"?"
Exit Do
End If
If count>1 then
For k = 1 To count - 1
b = AscB(MidB(bytes,i+k+1,1))
N = N * &H40 + (b And &H3F)
Next
str = str & ChrW(N)
End If
i = i + count
Loop
BytesToString = str
End Function
Credit goes to Pure ASP File Upload by implementing the BytesToString() function from include_aspuploader.asp in my own code I was able to get UTF-8 filenames working.
Useful Links
*
*Multipart/form-data and UTF-8 in a ASP Classic application
*Unicode, UTF, ASCII, ANSI format differences
A: I normally URL-encode (with %xx) the filenames, and it seems to work in all browsers. You might want to do some tests anyway.
A: We had a similar problem in a web application, and ended up by reading the filename from the HTML <input type="file">, and setting that in the url-encoded form in a new HTML <input type="hidden">. Of course we had to remove the path like "C:\fakepath\" that is returned by some browsers.
Of course this does not directly answer OPs question, but may be a solution for others.
A: The method mimeHeaderEncode($string) from the library class Unicode does the job.
$file_name= Unicode::mimeHeaderEncode($file_name);
Example in drupal/php:
https://github.com/drupal/core-utility/blob/8.8.x/Unicode.php
/**
* Encodes MIME/HTTP headers that contain incorrectly encoded characters.
*
* For example, Unicode::mimeHeaderEncode('tést.txt') returns
* "=?UTF-8?B?dMOpc3QudHh0?=".
*
* See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.
*
* Notes:
* - Only encode strings that contain non-ASCII characters.
* - We progressively cut-off a chunk with self::truncateBytes(). This ensures
* each chunk starts and ends on a character boundary.
* - Using \n as the chunk separator may cause problems on some systems and
* may have to be changed to \r\n or \r.
*
* @param string $string
* The header to encode.
* @param bool $shorten
* If TRUE, only return the first chunk of a multi-chunk encoded string.
*
* @return string
* The mime-encoded header.
*/
public static function mimeHeaderEncode($string, $shorten = FALSE) {
if (preg_match('/[^\x20-\x7E]/', $string)) {
// floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
$chunk_size = 47;
$len = strlen($string);
$output = '';
while ($len > 0) {
$chunk = static::truncateBytes($string, $chunk_size);
$output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
if ($shorten) {
break;
}
$c = strlen($chunk);
$string = substr($string, $c);
$len -= $c;
}
return trim($output);
}
return $string;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "610"
}
|
Q: Are POD types always aligned? For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior?
some more info:
a. It is possible to explicitely create a misaligned integer (*bar):
char foo[5]
int * bar = (int *)(&foo[1]);
b. Apparently, #pragma pack() only affects structures, classes, and unions.
c. MSVC documentation states that POD types are aligned to their respective sizes (but is it always or by default, and is it standard behavior, I don't know)
A: By default, yes. However, it can be changed via the pack() #pragma.
I don't believe the C++ Standard make any requirement in this regard, and leaves it up to the implementation.
A: As others have mentioned, this isn't part of the standard and is left up to the compiler to implement as it sees fit for the processor in question. For example, VC could easily implement different alignment requirements for an ARM processor than it does for x86 processors.
Microsoft VC implements what is basically called natural alignment up to the size specified by the #pragma pack directive or the /Zp command line option. This means that, for example, any POD type with a size smaller or equal to 8 bytes will be aligned based on its size. Anything larger will be aligned on an 8 byte boundary.
If it is important that you control alignment for different processors and different compilers, then you can use a packing size of 1 and pad your structures.
#pragma pack(push)
#pragma pack(1)
struct Example
{
short data1; // offset 0
short padding1; // offset 2
long data2; // offset 4
};
#pragma pack(pop)
In this code, the padding1 variable exists only to make sure that data2 is naturally aligned.
Answer to a:
Yes, that can easily cause misaligned data. On an x86 processor, this doesn't really hurt much at all. On other processors, this can result in a crash or a very slow execution. For example, the Alpha processor would throw a processor exception which would be caught by the OS. The OS would then inspect the instruction and then do the work needed to handle the misaligned data. Then execution continues. The __unaligned keyword can be used in VC to mark unaligned access for non-x86 programs (i.e. for CE).
A: C and C++ don't mandate any kind of alignment. But natural alignment is strongly preferred by x86 and is required by most other CPU architectures, and compilers generally do their utmost to keep CPUs happy. So in practice you won't see a compiler generate misaligned data unless you really twist it's arm.
A: Yes, all types are always aligned to at least their alignment requirements.
How could it be otherwise?
But note that the sizeof() a type is not the same as it's alignment.
You can use the following macro to determine the alignment requirements of a type:
#define ALIGNMENT_OF( t ) offsetof( struct { char x; t test; }, test )
A: Depends on the compiler, the pragmas and the optimisation level. With modern compilers you can also choose time or space optimisation, which could change the alignment of types as well.
A: Generally it will be because reading/writing to it is faster that way. But almost every compiler has a switch to turn this off. In gcc its -malign-???. With aggregates they are generally aligned and sized based on the alignment requirements of each element within.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: symbian application as background process is it possible to create java application that will
work as background process on symbian smartphones?
A: You can approximate it but J2ME (the version of java on mobile phones) may not be the right technology to do this.
*
*starting a MIDlet (a Java application for mobile phones) when the phone is switched on is tricky at best without coding a small Symbian OS C++ module that will start it for you. If you want to try anyway, look at the PushRegistry class in the MIDP specs
(http://java.sun.com/javame/reference/apis/jsr118/). The Content Handling API might provide some way to do it too (http://java.sun.com/javame/reference/apis/jsr211). When you are ready to give up, do it in C++.
*Backgrounding a MIDlet isn't hard. The phone's "menu" key will do it for you. Programatically, Canvas.setCurrent(null) has a good chance of working. Trying to trick the phone by providing a fully transparent GUI and not handling any keypad activity will absolutely not work. Creating and starting a separate Thread in the MIDlet should allow you to keep something running even after your overload of MIDlet.pauseApp() has been called by the application management system.
*The real issue is that the MIDlet will not have any Inter Process Communication system unless you make one. The usual way of doing that is a loopback socket connection over which you transfer data. Not a nice or efficient way of simulating IPC. Sharing a RMS record can only be done from within the same MIDlet suite (you can package several MIDlets into the same .jar file), I think. The code to create a provider/consumer data flow over a file connection is even uglier and will raise security issues.
Without any more information about what you want to use it for, my answer is : maybe but you should probably not try.
A: You will have in-built MIDP support for background MIDlets in MIDP 3.0 (http://jcp.org/en/jsr/detail?id=271). Don't hold your breath for devices to appear, however - might be some time.
(Note that a few Symbian OS devices have more than just MIDP - the S-E p990 for instance, https://developer.sonyericsson.com/site/global/products/phonegallery/p990/p_p990.jsp).
As already pointed out, it might be helpful to have more information on what product functionality you are trying to implement - often more than one way to skin a cat.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Accessing a resource file from a filesystem plugin on SymbianOS I cannot use the Resource File API from within a file system plugin due to a PlatSec issue:
*PlatSec* ERROR - Capability check failed - Can't load filesystemplugin.PXT because it links to bafl.dll which has the following capabilities missing: TCB
My understanding of the issue is that:
File system plugins are dlls which are executed within the context of the file system process. Therefore all file system plugins must have the TCB PlatSec privilege which in turn means they cannot link against a dll that is not in the TCB.
Is there a way around this (without resorting to a text file or an intermediate server)? I suspect not - but it would be good to get a definitive answer.
A: The Symbian file server has the following capabilities:
TCB ProtServ DiskAdmin AllFiles PowerMgmt CommDD
So any DLL being loaded into the file server process must have at least these capabilities. There is no way around this, short of writing a new proxy process as you allude to.
However, there is a more fundamental reason why you shouldn't be using bafl.dll from within a fileserver plugin: this DLL provides utility functions which interface to the file servers client API. Attempting to use it from within the filer server will not work; at best, it will lead to the file server deadlocking as it attempts to connect to itself.
I'd suggest rethinking that you're trying to do, and investigating an internal file-server API to achieve it instead.
A: Using RFs/RFile/RDir APIs from within a file server plugin is not safe and can potentially lead to deadlock if you're not very careful.
Symbian 9.5 will introduce new APIs (RFilePlugin, RFsPlugin and RDirPlugin) which should be used instead.
A: Theres a proper mechanism for communicating with plugins, RPlugin.
Do not use RFile. I'm not even sure that it would work as the path is checked in Initialise of RFile functions which is called before the plugin stack.
A: Tell us what kind of data you are storing in the resource file.
Things that usually go into resource files have no place in a file server plugin, even that means hardcoding a few values.
Technically, you can send data to a file server plugin using RFile.Write() but that's not a great solution (intercept RFile.Open("invalid file name that only your plugin understands") in the plugin).
EDIT: Someone indicated that using an invalid file name will not let you send data to the plugin. hey, I didn't like that solution either. for the sake of completness, I should clarify. make up a filename that looks OK enough to go through to your plugin. like using a drive letter that doesn't have a real drive attached to it (but will still be considered correct by filename-parsing code).
Writing code to parse the resource file binary in the plugin, while theoratically possible, isn't a great solution either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Want to write to a file, but may have potentially multiple writers at once, need to lock In a asp.net web application, I want to write to a file. This function will first get data from the database, and then write out the flat file.
What can I do to make sure only 1 write occurs, and once the write occurrs, the other threads that maybe want to write to the file don't since the write took place.
I want to have this write done ONLY if it hasn't been done in say 15 minutes.
I know there is a lock keyword, so should I wrap everything in a lock, then check if it has been updated in 15 minutes or more, or visa versa?
Update
Workflow:
Since this is a web application, the multiple instances will be people viewing a particular web page. I could use the build in cache system, but if asp.net recycles it will be expensive to rebuild the cache so I just want to write it out to a flat file. My other option would be just to create a windows service, but that is more work to manage that I want.
A: Synchronize your writing code to lock on a shared object so that only one thread gets inside the block. Others wait till the current one exits.
lock(this)
{
// perform the write.
}
Update: I assumed that you have a shared object. If these are different processes on the same machine, you'd need something like a Named Mutex. Looky here for an example
A: is it not better to lock an object variable rather than the whole instance?
A: File I/O operations that write to the file will automatically lock the file. Check if the file is locked (by trying the write) and if it is do not write. Before doing any writes, check the timestamp on the file and see if its more than 15 minutes.
afaik you can not write to a file without it being locked by Windows/whatever.
Now all that's left for you is to look up how to do the above using msdn (sorry, I can't be bothered to look it all up and I don't remember the C# classes very well). :)
A: I'm not convinced that .NET's locking is applicable to different processes. Moreover, lock(this) will only exclude other threads that are running the method on the same instance of "this" - so other threads even in the same process could run at once on different instances.
Assuming all your processes are running on the same machine, file locking should do it though.
If you're on different machines, your mileage may vary- win32 claims to have file locking which works over a network, but historically applications which rely on it (Think MSAccess) have problems with file corruption anyway.
A: // try enter will return false if another thread owns the lock
if (Monitor.TryEnter(lockObj))
{
try
{
// check last write time here, return if too soon; otherwise, write
}
finally
{
Monitor.Exit(lockobj);
}
}
A: Use file-system locks
Like others suggested, .NET locks will be of limited use in this situation.
Here is the code:
FileInfo fi = new FileInfo(path);
if (fi.Exists
&& (DateTime.UtcNow - fi.LastWriteTimeUtc < TimeSpan.FromMinutes(15)) {
// file is fresh
return;
}
FileStream fs;
try {
fs = new FileStream(
path, FileMode.Create, FileAccess.Write, FileShare.Read);
} catch (IOException) {
// file is locked
return;
}
using (fs) {
// write to file
}
This will work across threads and processes.
A: You guys should consider a Mutex. It can synchronize between multiple threads and processes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Is FileStream lazy-loaded in .NET? I have a question about using streams in .NET to load files from disk. I am trying to pinpoint a performance problem and want to be sure it's where I think it is.
Dim provider1 As New MD5CryptoServiceProvider
Dim stream1 As FileStream
stream1 = New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read)
provider1.ComputeHash(stream1)
Q: Are the bytes read from disk when I create the FileStream object, or when the object consuming the stream, in this case an MD5 Hash algorithm, actually reads it?
I see significant performance problems on my web host when using the ComputeHash method, compared to my local test environment. I'm just trying to make sure that the performance problem is in the hashing and not in the disk access.
A: FileStream simply exposes an IO.Stream around a file object, and uses buffers. It doesn't read the entire file in the constructor (the file could be larger than RAM).
The performance issue is most likely in the hashing, and you can perform some simple benchmarks to prove whether it's because of file IO or the algorithm itself.
But one of the first things you might try is:
provider1.ComputeHash(stream1.ToArray());
This should make the FileStream read the entire file and return an array of bytes. .ToArray() may invoke a faster method than the .Read() method that ComputeHash will call.
A: Yes content of the file will be read then you run ComputeHash method and not when you just open a FileStream.
The best way to test where the performance problem is , it is to read data from file to memory stream hash it and measure performance of each of this steps. You can use System.Diagnostics.Stopwatch class for this.
A: Bytes from disk should be read when the caller requests them by invoking Read or similar methods. At any rate, both the hard disk and the operating system perform some read-ahead to improve sequential read operations, but this is surely hard to predict.
You could also try to play with the buffer size parameter that some constructor overloads provide for FileStream.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I use IntelliJ to auto-complete method parameters? A feature in Eclipse that I really miss is how you can auto-complete method parameters with currently in-scope variables. This feature will, with a single key combo (ctrl+space) fill in all method parameters. As long as my variables were named similarly to the method parameters, I never had a problem with this auto-complete. Is there a plugin or a native way to accomplish this in Intellij?
A: You might already know that IntelliJ IDEA has the CTRL+P shortcut (Windows) and CMD+P (OX X) that brings up a brief description of which parameters are passed to the method. It's very handy and saves a lot of time that otherwise would have been spent looking up the method declaration.
A: IntelliJ IDEA 9 now supports what they call "super completion" which matches the behavior you are looking for and is available through their early access program.
(source: jetbrains.com)
IntelliJ IDEA 8 does not allow you to autocomplete more than one parameter at a time. You are forced to use Control-Shift-Space once for each parameter.
A: There is also an IntelliJ plugin called 'kotlin-fill-class' that will fill in some default values automagically. Tested the latest snapshot version of the plugin with IntelliJ 2019.1 and it appears to be working.
A: Control-Shift-Space (and the completion is based on type, not name)
For more goodness: Help -> Default Keymap Reference
A: from this post: https://stackoverflow.com/a/55160515/405749:
The plugin https://plugins.jetbrains.com/plugin/8638-auto-filling-java-call-arguments at least will provide a smart fix to do it when pressing alt+enter.
I have not found a away to do this completely automatically as it works in eclipse.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
}
|
Q: Do you generate code? If so, what do you use and what do you generate? I've used MyGeneration, and I love it for generating code that uses Data Access Applicaiton Blocks from Microsoft for my Data Access Layer, and keeping my database concepts in sync with the domain I am modeling. Although, it took a steeper than expected learning curve one weekend to make it productive.
I'm wondering what others are doing related to code generation.
http://www.mygenerationsoftware.com
http://www.codesmithtools.com/
Others?
Back in 2000, or so, the company I worked for used a product from Veritas Software (I believe it was) to model components and generate code that integrated components (dlls). I didn't get a lot of experience with it, but it seems that code generation has been the "holy grail" for a long time. Is it practical? How are others using it?
Thanks!
A: T4 is the CodeSmith killer for Microsoft!!!!
Go check it out. Microsoft doesn't want to destroy their partners so they don't advertise it, but it is a thing to be reckoned with and ITS FREE and comes installed in Visual Studio 2008.
www.olegsych.com
codeplex.com/t4toolbox
www.t4editor.net
A: I have used LLBLGen and nHibernate successfully to generate Entity and DAL layers.
A: We use Codesmith and have had great success with it. I am now constantly trying to find where we can implement templates to speed up mundane processes.
A: I've done work with CSLA and used codesmith to generate my code using the CSLA templates.
codesmithtools.com
A: If your database is your model, SubSonic has an excellent code generator that as of v2.1, no longer requires ActiveRecord (you can use the Repository Pattern instead). It's less flexible than others, but there are customizations that can be made in the stock templates.
A: I have used CodeSmith and MyGeneration, wasn't overly keen on either, felt somewhat terse to use, learning template languages etc.
SubSonic is what we sometimes use here to generate a Data Access Layer. Used in the right size projects, it is a fantastic time saving tool. clicky
A: I see code generation harmfull as well, but only if you use 3rd party tools like codesmith and mygeneration. I have 2 stored procedures that generate my domain objects and domain interfaces
Example
GenerateDomainInterface 'TableName'
Then I just copy and paste it into visual studio. Works pretty awesome for those tasks I hate to do.
A: Two framworks I use often.
Ragel
Something worth checking out is Ragel. It's used to generate code for state machines.
You just add some simple markup to your source code, then run a generator on
Ragel generates code for C, C++, Objective-C, D, Java and Ruby, and it's easy to mix it with your regular source.
Ragel even allow you to execute code on state transitions and such. It makes it easy to create file format and protocol parsers.
Some notable projects that user Ragel are, Mongrel, a great ruby web server. And Hpricot, a ruby based html-parser, sort of inspired by jQuery.
Another great feature of Ragel is how it can generate graphviz-based charts that visualize your state machines. Below is an example taken from Zed Shaw's article on ragel state charts.
(source: zedshaw.com)
XMLBeans
XMLBeans is a java-based xml-binding. It's got a great workflow and I use it often.
XMLBeans processen an xml-schema that describes your model, into a set of java-classes that represents that model. You can programmatically create models then serialise them to and from xml.
A: I have used CodeSmith. Was pretty helpful.
A: I love to use
SubSonic. Open source is the way to go with code generation I think because it is very easy to modify the templates and the core as they always tend to have bugs or one or two things you want to do that is not built in.
A: I've used code generation for swizzle functions in a vector math library. I used a custom PERL script for it. None of the FLOSS generators I looked at seemed well-suited to creating swizzle functions
I generally use C++ templates, rather than code generation.
A: I've primarily used LLBLGen Pro to generate code. It offers a variety of patterns to use for generation and you can supply your own patters, just like CodeSmith. The customer support has been excellent.
Essentially, I generate my business objects and DAL using LLBLGen and keep them up to date. The code templates have sections where you can add your own logic that won't be wiped out during regeneration. It's definitely worth taking a look.
A: We custom build our code generation using linq and XML literals (VB).
We haven't found a way to break the solutions into templates yet; however, those two technologies make this task so trivial, I don't think we will.
A: I'd consider code generation harmful as it bloats the codebase without adding new logic or insight. Ideally one should raise the level of abstraction, use data files, templates or macros etc. to avoid generating large amounts of boiler plate code. It helps you get things done quickly but can hurt maintainability in the long run.
If your chosen programming language becomes much less painful by generating it from some template language, that seems indicate you'd save even more time by doing the higher level work in another, perhaps more dynamic language. YMMV.
A: LLBLGen Pro is an excellent tool which allows you to write a database agnostic solution. It's really quick to pick up the basic features. Advanced features aren't much more challenging. I highly recommend you check it out.
A: I worked for four years as the main developer in a web agency, as I wrote from ground-up my first two or three websites, I soon realized that it was going to be a very boring task to do it all the times. So I started writing my own web site generator engine.
My starting point was this site http://www.codegeneration.net/. I took one of their examples for a simple crud generation and extended to the level that i was generating entire sites with it.
I used xml for the definition of various parts of the website (pages, datalists, joins, tables, form management). The generated web sites were completely detached from the generator, so the generated website could also be modified by hand.
Here is their article http://www.codegeneration.net/tiki-read_article.php?articleId=19.
A: I've done several one-off's of code generation using Castor to create Java source code based on XSD's. The latest use was to create Java classes for an Open Travel Association implementation. The OTA Schema is pretty hairy and would have been a bear to do by hand. Castor did a pretty good job given the complexity of the schema.
A: Python.
I have used MyGeneration which uses C# to write your code templates. However, I started using Python and I found that I can write code that generates other code faster in that language than I would if written in C#. Subsequently, I have used Python to code gen C#, TSQL, and VB.
Generally, code that generates other code tends to be harder to follow by its very nature. Python's cleaner syntax helps tremendously by making it more readable and more maintainable than the equivalent in C#.
A: codesmith for .net
A: I wrote a utility where you specify a table and it generates an Oracle trigger which records all changes to that table. Makes logging really simple.
There's another one I wrote that generates a Delphi class that models any database table you give it, but I consider it a code smell to do that, so I rarely use it.
A: At the company we've written our own to generate most of our entity/dalc/business classes and the related stored procedures as it took only a little time and we had some special requirements. Although I'm sure we could've achieved the same thing using an existing generator, it was a fun little project to work on.
Codesmith's been recommended by many people and it does seem to be a good one. Personally all I need from a code generator is to make it easy to amend templates.
A: MyGeneration all the way!
MyGeneration is an extremely flexible template based code generator written in Microsoft.NET. MyGeneration is great at generating code for ORM architectures. The meta-data from your database is made available to the templates through the MyMeta API.
A: I use the hibernate tools in myEclipse to generate domain models and DAO code from my data model. It seems to work pretty well (there are some issues if you write custom methods in your DAO's, these seem to get lost on over-writes), but generally it seems to work pretty well- especially in conjunction with Spring.
A: SubSonic is great!! The query capability is easy to grasp, and the stored procedure implementation is truly awesome. I could go on and on. It makes you productive instantly.
A: I mainly code in C# and when i need code generation I do it in XLST when the source could be simply converted to XML or a ruby script when it's more complex.
If the code generation part need frequent modifications by more than a few developers CodeSmith works pretty well (And is easier to learn than XSLT or ruby by new developers).
A: Outsystems' Agile Platform can be used to generate open source, well documented C# and Java applications. Because it has also several features related to deploying, managing and changing, most people end up using it not just to generate the code but actually to manage the full life-cycle of web applications.
A: For some time, I've used a home-grown script/template language for code generation. (I've used that languge mostly for no other reason than to find use for my little pet project)
Recently, I've created some SQL*PLUS scripts to create database access code (no Hibernate for us...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Floating div's in list items (ul, li) I have a list with two <div>s in every <li> and I want to float them one next to the other and I want the <li> to take the whole availabe space. How do I do it?
<html>
<head>
<title></title>
<style type="text/css">
body {
}
ul {
}
li {
}
.a {
}
.b {
}
</style>
</head>
<body>
<ul>
<li>
<div class="a">
content
</div>
<div class="b">
content
</div>
</li>
</ul>
</body>
</html>
A: *{ margin: 0; padding: 0;}
li{ width: 100%: display: block; }
li:after{ clear: both; }
div.a{ width: 49%; float: left; }
div.b{ width: 49%; float: left; }
Should do the trick.
A: For the divs, you just need to float left and the li, you want to do a clear. So:
li
{
clear: left;
}
.a
{
float: left;
}
.b
{
float: left;
}
A: I see this is an old post but if someone runs into the same issue think about this:
<div>A block-level section in a document</div>
<span>An inline section in a document</span>
You can use span instead of div
To get a div besides the other or horizontally you have to apply brute force with .css but if you use span it will naturally. Copy and paste the following code in a html and see what I'm talking about:
<ul>
<li>
<div style="background-color:red">red</div>
<div style="background-color:blue">blue</div>
</li>
<li>
<span style="background-color:red">red</span>
<span style="background-color:blue">blue</span>
</li>
</ul>
Also, at least for Microsoft <li><div></div></li> won't validate.
A: Without checking to make sure, this should work
LI { width: 100%; }
.a { float: left; }
.b { float: right; }
A: li { width: 100%;}
.a { float: left;}
.b { float: left;}
A: I assume by take the whole space you mean a width of 100%. I would also assume that you do not want styling applied to the list, which is why I have removed it in this example. This is also hack-free. You need not clear anything, so long as your list item has a width and the overflow: hidden property/value pair.
ul,
li {
width: 100%;
list-style-type: none;
margin: 0;
padding: 0;
}
li {
overflow: hidden;
}
li div.a,
li div.b {
float: left;
}
A: li{width:100%;}
.a{}
.b{float: left;}
That should do as required from my knowledge of CSS
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CakePHP View including other views I have a CakePHP application that in some moment will show a view with product media (pictures or videos) I want to know if, there is someway to include another view that threats the video or threats the pictures, depending on a flag. I want to use those "small views" to several other purposes, so It should be "like" a cake component, for reutilization.
What you guys suggest to use to be in Cake conventions (and not using a raw include('') command)
A: In the interest of having the information here in case someone stumbles upon this, it is important to note that the solution varies depending on the CakePHP version.
For CakePHP 1.1
$this->renderElement('display', array('flag' => 'value'));
in your view, and then in /app/views/elements/ you can make a file called display.thtml, where $flag will have the value of whatever you pass to it.
For CakePHP 1.2
$this->element('display', array('flag' => 'value'));
in your view, and then in /app/views/elements/ you can make a file called display.ctp, where $flag will have the value of whatever you pass to it.
In both versions the element will have access to all the data the view has access to + any values you pass to it. Furthermore, as someone pointed out, requestAction() is also an option, but it can take a heavy toll in performance if done without using cache, since it has to go through all the steps a normal action would.
A: In your controller (in this example the posts controller).
function something() {
return $this->Post->find('all');
}
In your elements directory (app/views/element) create a file called posts.ctp.
In posts.ctp:
$posts = $this->requestAction('posts/something');
foreach($posts as $post):
echo $post['Post']['title'];
endforeach;
Then in your view:
<?php echo $this->element('posts'); ?>
This is mostly taken from the CakePHP book here:
Creating Reusable Elements with requestAction
I do believe that using requestAction is quite expensive, so you will want to look into caching.
A: Simply use:
<?php include('/<other_view>.ctp'); ?>
in the .ctp your action ends up in.
For example, build an archived function
function archived() {
// do some stuff
// you can even hook the index() function
$myscope = array("archived = 1");
$this->index($myscope);
// coming back, so the archived view will be launched
$this->set("is_archived", true); // e.g. use this in your index.ctp for customization
}
Possibly adjust your index action:
function index($scope = array()) {
// ...
$this->set(items, $this->paginate($scope));
}
Your archive.ctp will be:
<?php include('/index.ctp'); ?>
Ideal reuse of code of controller actions and views.
A: For CakePHP 2.x
New for Cake 2.x is the abilty to extend a given view. So while elements are great for having little bits of reusable code, extending a view allows you to reuse whole views.
See the manual for more/better information
http://book.cakephp.org/2.0/en/views.html#extending-views
A: Elements work if you want them to have access to the same data that the calling view has access to.
If you want your embedded view to have access to its own set of data, you might want to use something like requestAction(). This allows you to embed a full-fledged view that would otherwise be stand-alone.
A:
I want to use those "small views" to
several other purposes, so It should
be "like" a cake component, for
reutilization.
This is done with "Helpers", as described here. But I'm not sure that's really what you want. The "Elements" suggestion seems correct too. It heavily depends of what you're trying to accomplish. My two cents...
A: In CakePHP 3.x you can simple use:
$this->render('view')
This will render the view from the same directory as parent view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: How to determine WPF SelectedItem for a window I have a WPF app with many list based controls in a window, which all are bound to different CollectionViews.
At the window level is there a way to get the current selected item for the currently in focus list based control? I know I can do this with some fairly trivial code by looking for the in focus element but does WPF support this as a concept out of the box?
Something like Window.CurrentSelectedDataItem would be great. I am looking into using this as a way to centralize command management for enabling disabling commands based on a current selected data item.
A: I don't think that there is a property like you specify, but as an alternative you could register a ClassHandler for the ListBox.SelectionChanged event in your Window class:
EventManager.RegisterClassHandler(typeof(ListBox), ListBox.SelectionChanged,
new SelectionChangedEventHandler(this.OnListBoxSelectionChanged));
This will get called whenever the selection changes in any ListBox in your application. You can use the sender argument to determine which ListBox it was that changed its selection, and cache this value for when you need it.
A: I haven't tried this, but you could try using a MultiBinding with a converter to get to the correct item:
<MultiBinding Converter="{StaticResource coalesce}">
<MultiBinding.Bindings>
<MultiBinding Converter="{StaticResource nullIfFalse}">
<MultiBinding.Bindings>
<Binding ElementName="List1" Path="HasFocus" />
<Binding ElementName="List1" Path="SelectedItem" />
nullIfFalse returns the second parameter, if the first is true, null otherwise. coalesce returns the first non-null element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do download accelerators work? We require all requests for downloads to have a valid login (non-http) and we generate transaction tickets for each download. If you were to go to one of the download links and attempt to "replay" the transaction, we use HTTP codes to forward you to get a new transaction ticket. This works fine for a majority of users. There's a small subset, however, that are using Download Accelerators that simply try to replay the transaction ticket several times.
So, in order to determine whether we want to or even can support download accelerators or not, we are trying to understand how they work.
How does having a second, third or even fourth concurrent connection to the web server delivering a static file speed the download process?
What does the accelerator program do?
A: You'll get a more comprehensive overview of Download Accelerators at wikipedia.
Acceleration is multi-faceted
First
A substantial benefit of managed/accelerated downloads is the tool in question remembers Start/Stop offsets transferred and uses "partial" and 'range' headers to request parts of the file instead of all of it.
This means if something dies mid transaction ( ie: TCP Time-out ) it just reconnects where it left off and you don't have to start from scratch.
Thus, if you have an intermittent connection, the aggregate transfer time is greatly lessened.
Second
Download accelerators like to break a single transfer into several smaller segments of equal size, using the same start-range-stop mechanics, and perform them in parallel, which greatly improves transfer time over slow networks.
There's this annoying thing called bandwidth-delay-product where the size of the TCP buffers at either end do some math thing in conjunction with ping time to get the actual experienced speed, and this in practice means large ping times will limit your speed regardless how many megabits/sec all the interim connections have.
However, this limitation appears to be "per connection", so multiple TCP connections to a single server can help mitigate the performance hit of the high latency ping time.
Hence, people who live near by are not so likely to need to do a segmented transfer, but people who live in far away locations are more likely to benefit from going crazy with their segmentation.
Thirdly
In some cases it is possible to find multiple servers that provide the same resource, sometimes a single DNS address round-robins to several IP addresses, or a server is part of a mirror network of some kind. And download managers/accelerators can detect this and apply the segmented transfer technique across multiple servers, allowing the downloader to get more collective bandwidth delivered to them.
Support
Supporting the first kind of acceleration is what I personally suggest as a "minimum" for support. Mostly, because it makes a users life easy, and it reduces the amount of aggregate data transfer you have to provide due to users not having to fetch the same content repeatedly.
And to facilitate this, its recommended you, compute how much they have transferred and don't expire the ticket till they look "finished" ( while binding traffic to the first IP that used the ticket ), or a given 'reasonable' time to download it has passed. ie: give them a window of grace before requiring they get a new ticket.
Supporting the second and third give you bonus points, and users generally desire it at least the second, mostly because international customers don't like being treated as second class customers simply because of the greater ping time, and it doesn't objectively consume more bandwidth in any sense that matters. The worst that happens is they might cause your total throughput to be undesirable for how your service operates.
It's reasonably straight forward to deliver the first kind of benefit without allowing the second simply by restricting the number of concurrent transfers from a single ticket.
A: I believe the idea is that many servers limit or evenly distribute bandwidth across connections. By having multiple connections, you're cheating that system and getting more than your "fair" share of bandwidth.
A: It's all about Little's Law. Specifically each stream to the web server is seeing a certain amount of TCP latency and so will only carry so much data. Tricks like increasing the TCP window size and implementing selective acks help but are poorly implemented and generally cause more problems than they solve.
Having multiple streams means that the latency seen by each stream is less important as the global throughput increases overall.
Another key advantage with a download accelerator even when using a single thread is that it's generally better than using the web browsers built in download tool. For example if the web browser decides to die the download tool will continue. And the download tool may support functionality like pausing/resuming that the built-in brower doesn't.
A: My understanding is that one method download accelerators use is by opening many parallel TCP connections - each TCP connection can only go so fast, and is often limited on the server side.
TCP is implemented such that if a timeout occurs, the timeout period is increased. This is very effective at preventing network overloads, at the cost of speed on individual TCP connections.
Download accelerators can get around this by opening dozens of TCP connections and dropping the ones that slow to below a certain threshold, then opening new ones to replace the slow connections.
While effective for a single user, I believe it is bad etiquette in general.
You're seeing the download accelerator trying to re-authenticate using the same transaction ticket - I'd recommend ignoring these requests.
A: From: http://askville.amazon.com/download-accelerator-protocol-work-advantages-benefits-application-area-scope-plz-suggest-URLs/AnswerViewer.do?requestId=9337813
Quote:
The most common way of accelerating downloads is to open up parllel downloads. Many servers limit the bandwith of one connection so opening more in parallel increases the rate. This works by specifying an offset a download should start which is supported for HTTP and FTP alike.
Of course this way of acceleration is quite "unsocial". The limitation of bandwith is implemented to be able to serve a higher number of clients so using this technique lowers the maximum number of peers that is able to download. That's the reason why many servers are limiting the number of parallel connection (recognized by IP), e.g. many FTP-servers do this so you run into problems if you download a file and try to continue browsing using your browser. Technically these are two parallel connections.
Another technique to increase the download-rate is a peer-to-peer-network where different sources e.g. limited by asynchron DSL on the upload-side are used for downloading.
A: Most download 'accelerators' really don't speed up anything at all. What they are good at doing is congesting network traffic, hammering your server, and breaking custom scripts like you've seen. Basically how it works is that instead of making one request and downloading the file from beginning to end, it makes say four requests...the first one downloads from 0-25%, the second from 25-50%, and so on, and it makes them all at the same time. The only particular case where this helps any, is if their ISP or firewall does some kind of traffic shaping such that an individual download speed is limited to less than their total download speed.
Personally, if it's causing you any trouble, I'd say just put a notice that download accelerators are not supported, and have the users download them normally, or only using a single thread.
A: They don't, generally.
To answer the substance of your question, the assumption is that the server is rate-limiting downloads on a per-connection basis, so simultaneously downloading multiple chunks will enable the user to make the most of the bandwidth available at their end.
A: Typically download-accelerators depend on partial content download - status code 206. Just like the streaming media players, media players ask for a small chunk of the full file to the server and then download it and play. Now the catch is if a server restricts partial-content-download then the download accelerator won't work!. It's easy to configure a server like Nginx to restrict partial-content-download.
How to know if a file can be downloaded via ranges/partially?
Ans: check for a header value Accept-Ranges:. If it does exist then you are good to go.
How to implement a feature like this in any programming language?
Ans: well, it's pretty easy. Just spin up some threads/co-routines(choose threads/co-routines over processes in I/O or network bound system) to download the N-number of chunks in parallel. Save the partial files in the right position in the file. and you are technically done. Calculate the download speed by keeping a global variable downloaded_till_now=0 and increment it as one thread completes downloading a chunk. don't forget about mutex as we are writing to a global resource from multiple thread so do a thread.acquire() and thread.release(). And also keep a unix-time counter. and do math like
speed_in_bytes_per_sec = downloaded_till_now/(current_unix_time-start_unix_time)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Apply stroke to a textblock in WPF How do you apply stroke (outline around text) to a textblock in xaml in WPF?
A: Below is my more idiomatically WPF, full-featured take on this. It supports pretty much everything you'd expect, including:
*
*all font related properties including stretch and style
*text alignment (left, right, center, justify)
*text wrapping
*text trimming
*text decorations (underline, strike through etcetera)
Here's a simple example of what can be achieved with it:
<local:OutlinedTextBlock FontFamily="Verdana" FontSize="20pt" FontWeight="ExtraBold" TextWrapping="Wrap" StrokeThickness="1" Stroke="{StaticResource TextStroke}" Fill="{StaticResource TextFill}">
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit
</local:OutlinedTextBlock>
Which results in:
Here's the code for the control:
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
[ContentProperty("Text")]
public class OutlinedTextBlock : FrameworkElement
{
public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
"Stroke",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(
"StrokeThickness",
typeof(double),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextInvalidated));
public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(
"TextAlignment",
typeof(TextAlignment),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(
"TextDecorations",
typeof(TextDecorationCollection),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(
"TextTrimming",
typeof(TextTrimming),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(
"TextWrapping",
typeof(TextWrapping),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));
private FormattedText formattedText;
private Geometry textGeometry;
public OutlinedTextBlock()
{
this.TextDecorations = new TextDecorationCollection();
}
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
[TypeConverter(typeof(FontSizeConverter))]
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public FontStretch FontStretch
{
get { return (FontStretch)GetValue(FontStretchProperty); }
set { SetValue(FontStretchProperty, value); }
}
public FontStyle FontStyle
{
get { return (FontStyle)GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
public FontWeight FontWeight
{
get { return (FontWeight)GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
public Brush Stroke
{
get { return (Brush)GetValue(StrokeProperty); }
set { SetValue(StrokeProperty, value); }
}
public double StrokeThickness
{
get { return (double)GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public TextAlignment TextAlignment
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public TextDecorationCollection TextDecorations
{
get { return (TextDecorationCollection)this.GetValue(TextDecorationsProperty); }
set { this.SetValue(TextDecorationsProperty, value); }
}
public TextTrimming TextTrimming
{
get { return (TextTrimming)GetValue(TextTrimmingProperty); }
set { SetValue(TextTrimmingProperty, value); }
}
public TextWrapping TextWrapping
{
get { return (TextWrapping)GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
protected override void OnRender(DrawingContext drawingContext)
{
this.EnsureGeometry();
drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry);
}
protected override Size MeasureOverride(Size availableSize)
{
this.EnsureFormattedText();
// constrain the formatted text according to the available size
// the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions
// the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw
this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width);
this.formattedText.MaxTextHeight = Math.Max(0.0001d, availableSize.Height);
// return the desired size
return new Size(this.formattedText.Width, this.formattedText.Height);
}
protected override Size ArrangeOverride(Size finalSize)
{
this.EnsureFormattedText();
// update the formatted text with the final size
this.formattedText.MaxTextWidth = finalSize.Width;
this.formattedText.MaxTextHeight = finalSize.Height;
// need to re-generate the geometry now that the dimensions have changed
this.textGeometry = null;
return finalSize;
}
private static void OnFormattedTextInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.formattedText = null;
outlinedTextBlock.textGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.UpdateFormattedText();
outlinedTextBlock.textGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private void EnsureFormattedText()
{
if (this.formattedText != null || this.Text == null)
{
return;
}
this.formattedText = new FormattedText(
this.Text,
CultureInfo.CurrentUICulture,
this.FlowDirection,
new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal),
this.FontSize,
Brushes.Black);
this.UpdateFormattedText();
}
private void UpdateFormattedText()
{
if (this.formattedText == null)
{
return;
}
this.formattedText.MaxLineCount = this.TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;
this.formattedText.TextAlignment = this.TextAlignment;
this.formattedText.Trimming = this.TextTrimming;
this.formattedText.SetFontSize(this.FontSize);
this.formattedText.SetFontStyle(this.FontStyle);
this.formattedText.SetFontWeight(this.FontWeight);
this.formattedText.SetFontFamily(this.FontFamily);
this.formattedText.SetFontStretch(this.FontStretch);
this.formattedText.SetTextDecorations(this.TextDecorations);
}
private void EnsureGeometry()
{
if (this.textGeometry != null)
{
return;
}
this.EnsureFormattedText();
this.textGeometry = this.formattedText.BuildGeometry(new Point(0, 0));
}
}
A: you should wrap the TextBlock with a Border.. something like this:
<Border BorderBrush="Purple" BorderThickness="2">
<TextBlock>My fancy TextBlock</TextBlock>
</Border>
in the off chance you are asking how to put a stroke around the actual letters (and not the whole TextBlock) you may want to look at using a BitmapEffect of Glow and setting the parameters on the Glow to be the stroke color you want, etc. Otherwise you may have to create something custom.
A: I modified the most voted answer with several fixes, including:
*
*Fix so texts with a single line would show when using
UseLayoutRounding.
*Outlines would show outside the text instead of in the middle of the
border.
*The pen is created only once instead of on each render.
*Fix so it won't crash when the text is set to null.
*Fix so outline uses proper round caps.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
[ContentProperty("Text")]
public class OutlinedTextBlock : FrameworkElement
{
private void UpdatePen() {
_Pen = new Pen(Stroke, StrokeThickness) {
DashCap = PenLineCap.Round,
EndLineCap = PenLineCap.Round,
LineJoin = PenLineJoin.Round,
StartLineCap = PenLineCap.Round
};
InvalidateVisual();
}
public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
"Stroke",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender, StrokePropertyChangedCallback));
private static void StrokePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) {
(dependencyObject as OutlinedTextBlock)?.UpdatePen();
}
public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(
"StrokeThickness",
typeof(double),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender, StrokePropertyChangedCallback));
public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextInvalidated));
public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(
"TextAlignment",
typeof(TextAlignment),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(
"TextDecorations",
typeof(TextDecorationCollection),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(
"TextTrimming",
typeof(TextTrimming),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(
"TextWrapping",
typeof(TextWrapping),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));
private FormattedText _FormattedText;
private Geometry _TextGeometry;
private Pen _Pen;
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
[TypeConverter(typeof(FontSizeConverter))]
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public FontStretch FontStretch
{
get { return (FontStretch)GetValue(FontStretchProperty); }
set { SetValue(FontStretchProperty, value); }
}
public FontStyle FontStyle
{
get { return (FontStyle)GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
public FontWeight FontWeight
{
get { return (FontWeight)GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
public Brush Stroke
{
get { return (Brush)GetValue(StrokeProperty); }
set { SetValue(StrokeProperty, value); }
}
public double StrokeThickness
{
get { return (double)GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public TextAlignment TextAlignment
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public TextDecorationCollection TextDecorations
{
get { return (TextDecorationCollection)GetValue(TextDecorationsProperty); }
set { SetValue(TextDecorationsProperty, value); }
}
public TextTrimming TextTrimming
{
get { return (TextTrimming)GetValue(TextTrimmingProperty); }
set { SetValue(TextTrimmingProperty, value); }
}
public TextWrapping TextWrapping
{
get { return (TextWrapping)GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
public OutlinedTextBlock() {
UpdatePen();
TextDecorations = new TextDecorationCollection();
}
protected override void OnRender(DrawingContext drawingContext) {
EnsureGeometry();
drawingContext.DrawGeometry(null, _Pen, _TextGeometry);
drawingContext.DrawGeometry(Fill, null, _TextGeometry);
}
protected override Size MeasureOverride(Size availableSize) {
EnsureFormattedText();
// constrain the formatted text according to the available size
double w = availableSize.Width;
double h = availableSize.Height;
// the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions
// the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw
_FormattedText.MaxTextWidth = Math.Min(3579139, w);
_FormattedText.MaxTextHeight = Math.Max(0.0001d, h);
// return the desired size
return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));
}
protected override Size ArrangeOverride(Size finalSize) {
EnsureFormattedText();
// update the formatted text with the final size
_FormattedText.MaxTextWidth = finalSize.Width;
_FormattedText.MaxTextHeight = Math.Max(0.0001d, finalSize.Height);
// need to re-generate the geometry now that the dimensions have changed
_TextGeometry = null;
return finalSize;
}
private static void OnFormattedTextInvalidated(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs e) {
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock._FormattedText = null;
outlinedTextBlock._TextGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) {
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.UpdateFormattedText();
outlinedTextBlock._TextGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private void EnsureFormattedText() {
if (_FormattedText != null) {
return;
}
_FormattedText = new FormattedText(
Text ?? "",
CultureInfo.CurrentUICulture,
FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
FontSize,
Brushes.Black);
UpdateFormattedText();
}
private void UpdateFormattedText() {
if (_FormattedText == null) {
return;
}
_FormattedText.MaxLineCount = TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;
_FormattedText.TextAlignment = TextAlignment;
_FormattedText.Trimming = TextTrimming;
_FormattedText.SetFontSize(FontSize);
_FormattedText.SetFontStyle(FontStyle);
_FormattedText.SetFontWeight(FontWeight);
_FormattedText.SetFontFamily(FontFamily);
_FormattedText.SetFontStretch(FontStretch);
_FormattedText.SetTextDecorations(TextDecorations);
}
private void EnsureGeometry() {
if (_TextGeometry != null) {
return;
}
EnsureFormattedText();
_TextGeometry = _FormattedText.BuildGeometry(new Point(0, 0));
}
}
A: Found It. Not so easy to do apparently, there is no built in Stroke text in WPF (kind of a big missing feature if you ask me). First create the custom class:
using System;
using System.Windows.Media;
using System.Globalization;
using System.Windows;
using System.Windows.Markup;
namespace CustomXaml
{
public class OutlinedText : FrameworkElement, IAddChild
{
#region Private Fields
private Geometry _textGeometry;
#endregion
#region Private Methods
/// <summary>
/// Invoked when a dependency property has changed. Generate a new FormattedText object to display.
/// </summary>
/// <param name="d">OutlineText object whose property was updated.</param>
/// <param name="e">Event arguments for the dependency property.</param>
private static void OnOutlineTextInvalidated(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((OutlinedText)d).CreateText();
}
#endregion
#region FrameworkElement Overrides
/// <summary>
/// OnRender override draws the geometry of the text and optional highlight.
/// </summary>
/// <param name="drawingContext">Drawing context of the OutlineText control.</param>
protected override void OnRender(DrawingContext drawingContext)
{
CreateText();
// Draw the outline based on the properties that are set.
drawingContext.DrawGeometry(Fill, new Pen(Stroke, StrokeThickness), _textGeometry);
}
/// <summary>
/// Create the outline geometry based on the formatted text.
/// </summary>
public void CreateText()
{
FontStyle fontStyle = FontStyles.Normal;
FontWeight fontWeight = FontWeights.Medium;
if (Bold == true) fontWeight = FontWeights.Bold;
if (Italic == true) fontStyle = FontStyles.Italic;
// Create the formatted text based on the properties set.
FormattedText formattedText = new FormattedText(
Text,
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface(Font, fontStyle, fontWeight, FontStretches.Normal),
FontSize,
Brushes.Black // This brush does not matter since we use the geometry of the text.
);
// Build the geometry object that represents the text.
_textGeometry = formattedText.BuildGeometry(new Point(0, 0));
//set the size of the custome control based on the size of the text
this.MinWidth = formattedText.Width;
this.MinHeight = formattedText.Height;
}
#endregion
#region DependencyProperties
/// <summary>
/// Specifies whether the font should display Bold font weight.
/// </summary>
public bool Bold
{
get
{
return (bool)GetValue(BoldProperty);
}
set
{
SetValue(BoldProperty, value);
}
}
/// <summary>
/// Identifies the Bold dependency property.
/// </summary>
public static readonly DependencyProperty BoldProperty = DependencyProperty.Register(
"Bold",
typeof(bool),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
/// <summary>
/// Specifies the brush to use for the fill of the formatted text.
/// </summary>
public Brush Fill
{
get
{
return (Brush)GetValue(FillProperty);
}
set
{
SetValue(FillProperty, value);
}
}
/// <summary>
/// Identifies the Fill dependency property.
/// </summary>
public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
new SolidColorBrush(Colors.LightSteelBlue),
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
/// <summary>
/// The font to use for the displayed formatted text.
/// </summary>
public FontFamily Font
{
get
{
return (FontFamily)GetValue(FontProperty);
}
set
{
SetValue(FontProperty, value);
}
}
/// <summary>
/// Identifies the Font dependency property.
/// </summary>
public static readonly DependencyProperty FontProperty = DependencyProperty.Register(
"Font",
typeof(FontFamily),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
new FontFamily("Arial"),
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
/// <summary>
/// The current font size.
/// </summary>
public double FontSize
{
get
{
return (double)GetValue(FontSizeProperty);
}
set
{
SetValue(FontSizeProperty, value);
}
}
/// <summary>
/// Identifies the FontSize dependency property.
/// </summary>
public static readonly DependencyProperty FontSizeProperty = DependencyProperty.Register(
"FontSize",
typeof(double),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
(double)48.0,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
/// <summary>
/// Specifies whether the font should display Italic font style.
/// </summary>
public bool Italic
{
get
{
return (bool)GetValue(ItalicProperty);
}
set
{
SetValue(ItalicProperty, value);
}
}
/// <summary>
/// Identifies the Italic dependency property.
/// </summary>
public static readonly DependencyProperty ItalicProperty = DependencyProperty.Register(
"Italic",
typeof(bool),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
/// <summary>
/// Specifies the brush to use for the stroke and optional hightlight of the formatted text.
/// </summary>
public Brush Stroke
{
get
{
return (Brush)GetValue(StrokeProperty);
}
set
{
SetValue(StrokeProperty, value);
}
}
/// <summary>
/// Identifies the Stroke dependency property.
/// </summary>
public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
"Stroke",
typeof(Brush),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
new SolidColorBrush(Colors.Teal),
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
/// <summary>
/// The stroke thickness of the font.
/// </summary>
public ushort StrokeThickness
{
get
{
return (ushort)GetValue(StrokeThicknessProperty);
}
set
{
SetValue(StrokeThicknessProperty, value);
}
}
/// <summary>
/// Identifies the StrokeThickness dependency property.
/// </summary>
public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(
"StrokeThickness",
typeof(ushort),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
(ushort)0,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
/// <summary>
/// Specifies the text string to display.
/// </summary>
public string Text
{
get
{
return (string)GetValue(TextProperty);
}
set
{
SetValue(TextProperty, value);
}
}
/// <summary>
/// Identifies the Text dependency property.
/// </summary>
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
"",
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnOutlineTextInvalidated),
null
)
);
public void AddChild(Object value)
{
}
public void AddText(string value)
{
Text = value;
}
#endregion
}
}
The you can reference it in your xaml.
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:customControls="clr-namespace:CustomXaml;assembly=CustomXaml">
<Grid>
<customControls:OutlinedText x:Name="TextContent" Fill="#ffffffff" FontSize="28"
Bold="True" Stroke="Black" StrokeThickness="1" Text="Back" Margin="10,0,10,0"
HorizontalAlignment="Center" VerticalAlignment="Center" Height="Auto" Width="Auto" />
</Grid>
</Page>
A: Another option is to use a regular Textblock, but apply a custom effect to it.
Combining this Shader tutorial and the Prewitt Edge Detection Filter I managed to get a decent outline effect around text. While it has the advantage of rendering using the GPU, and applying to ANY UIElement, I'd say that @Kent Boogaart's answer looks a little better, and the EdgeResponse is finicky - I had to play with it a lot to get a nice outline.
The end result in XAML:
<Grid>
<Grid.Resources>
<local:EdgeDetectionEffect x:Key="OutlineEffect"
x:Shared="false"
EdgeResponse=".44"
ActualHeight="{Binding RelativeSource={RelativeSource AncestorType=TextBlock}, Path=ActualHeight}"
ActualWidth="{Binding RelativeSource={RelativeSource AncestorType=TextBlock}, Path=ActualWidth}"/>
</Grid.Resources>
<TextBlock Text="The Crazy Brown Fox Jumped Over the Lazy Dog."
FontWeight="Bold"
FontSize="25"
Foreground="Yellow"
Effect="{StaticResource OutlineEffect}"/>
</Grid>
In order to create the custom effect, I first created the EdgeDetectionColorEffect.fx (hdld) file - this is the code the GPU uses to filter the image. I compiled it in Visual Studio Command Prompt with the command:
fxc /T ps_2_0 /E main /Focc.ps EdgeDetectionColorEffect.fx
sampler2D Input : register(s0);
float ActualWidth : register(c0);
float ActualHeight : register(c1);
float4 OutlineColor : register(c2);
float EdgeDetectionResponse : register(c3);
float4 GetNeighborPixel(float2 pixelPoint, float xOffset, float yOffset)
{
float2 NeighborPoint = {pixelPoint.x + xOffset, pixelPoint.y + yOffset};
return tex2D(Input, NeighborPoint);
}
// pixel locations:
// 00 01 02
// 10 11 12
// 20 21 22
float main(float2 pixelPoint : TEXCOORD) : COLOR
{
float wo = 1 / ActualWidth; //WidthOffset
float ho = 1 / ActualHeight; //HeightOffset
float4 c00 = GetNeighborPixel(pixelPoint, -wo, -ho); // color of the pixel up and to the left of me.
float4 c01 = GetNeighborPixel(pixelPoint, 00, -ho);
float4 c02 = GetNeighborPixel(pixelPoint, wo, -ho);
float4 c10 = GetNeighborPixel(pixelPoint, -wo, 0);
float4 c11 = tex2D(Input, pixelPoint); // this is the current pixel
float4 c12 = GetNeighborPixel(pixelPoint, wo, 0);
float4 c20 = GetNeighborPixel(pixelPoint, -wo, ho);
float4 c21 = GetNeighborPixel(pixelPoint, 0, ho);
float4 c22 = GetNeighborPixel(pixelPoint, wo, ho);
float t00 = c00.r + c00.g + c00.b; //total of color channels
float t01 = c01.r + c01.g + c01.b;
float t02 = c02.r + c02.g + c02.b;
float t10 = c10.r + c10.g + c10.b;
float t11 = c11.r + c11.g + c11.b;
float t12 = c12.r + c12.g + c12.b;
float t20 = c20.r + c20.g + c20.b;
float t21 = c21.r + c21.g + c21.b;
float t22 = c22.r + c22.g + c22.b;
//Prewitt - convolve the 9 pixels with:
// 01 01 01 01 00 -1
// Gy = 00 00 00 Gx = 01 00 -1
// -1 -1 -1 01 00 -1
float gy = 0.0; float gx = 0.0;
gy += t00; gx += t00;
gy += t01; gx += t10;
gy += t02; gx += t20;
gy -= t20; gx -= t02;
gy -= t21; gx -= t12;
gy -= t22; gx -= t22;
if((gy*gy + gx*gx) > EdgeDetectionResponse)
{
return OutlineColor;
}
return c11;
}
Here's the wpf effect class:
public class EdgeDetectionEffect : ShaderEffect
{
private static PixelShader _shader = new PixelShader { UriSource = new Uri("path to your compiled shader probably called cc.ps", UriKind.Absolute) };
public EdgeDetectionEffect()
{
PixelShader = _shader;
UpdateShaderValue(InputProperty);
UpdateShaderValue(ActualHeightProperty);
UpdateShaderValue(ActualWidthProperty);
UpdateShaderValue(OutlineColorProperty);
UpdateShaderValue(EdgeResponseProperty);
}
public Brush Input
{
get => (Brush)GetValue(InputProperty);
set => SetValue(InputProperty, value);
}
public static readonly DependencyProperty InputProperty =
ShaderEffect.RegisterPixelShaderSamplerProperty(nameof(Input),
typeof(EdgeDetectionEffect), 0);
public double ActualWidth
{
get => (double)GetValue(ActualWidthProperty);
set => SetValue(ActualWidthProperty, value);
}
public static readonly DependencyProperty ActualWidthProperty =
DependencyProperty.Register(nameof(ActualWidth), typeof(double), typeof(EdgeDetectionEffect),
new UIPropertyMetadata(1.0, PixelShaderConstantCallback(0)));
public double ActualHeight
{
get => (double)GetValue(ActualHeightProperty);
set => SetValue(ActualHeightProperty, value);
}
public static readonly DependencyProperty ActualHeightProperty =
DependencyProperty.Register(nameof(ActualHeight), typeof(double), typeof(EdgeDetectionEffect),
new UIPropertyMetadata(1.0, PixelShaderConstantCallback(1)));
public Color OutlineColor
{
get => (Color)GetValue(OutlineColorProperty);
set => SetValue(OutlineColorProperty, value);
}
public static readonly DependencyProperty OutlineColorProperty=
DependencyProperty.Register(nameof(OutlineColor), typeof(Color), typeof(EdgeDetectionEffect),
new UIPropertyMetadata(Colors.Black, PixelShaderConstantCallback(2)));
public double EdgeResponse
{
get => (double)GetValue(EdgeResponseProperty);
set => SetValue(EdgeResponseProperty, value);
}
public static readonly DependencyProperty EdgeResponseProperty =
DependencyProperty.Register(nameof(EdgeResponse), typeof(double), typeof(EdgeDetectionEffect),
new UIPropertyMetadata(4.0, PixelShaderConstantCallback(3)));
}
A: "How to: Create Outlined Text" on MSDN has all the information you need.
A: If applied for anyone, here a simple solution using ONLY XAML. I am not sure if it performs better or worse, but in my opinion, it looks better then any other solution above.
I wrap it in a ContentControl Style (and Template), following this Old School example :)
http://oldschooldotnet.blogspot.co.il/2009/02/fancy-fonts-in-xaml-silverlight-and-wpf.html
<Style x:Key="OutlinedText" TargetType="{x:Type ContentControl}">
<!-- Some Style Setters -->
<Setter Property="Content" Value="Outlined Text"/>
<Setter Property="Padding" Value="0"/>
<!-- Border Brush Must be equal '0' because TextBlock that emulate the stroke will using the BorderBrush as to define 'Stroke' color-->
<Setter Property="BorderThickness" Value="0"/>
<!-- Border Brush define 'Stroke' Color-->
<Setter Property="BorderBrush" Value="White"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="24"/>
<Setter Property="FontFamily" Value="Seoge UI Bold"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Canvas Width="{Binding ActualWidth, ElementName=FillText}" Height="{Binding ActualHeight, ElementName=FillText}">
<Canvas.Resources>
<!-- Style to ease the duplication of Text Blocks that emulate the stroke: Binding to one element (or to template) is the first part of the Trick -->
<Style x:Key="OutlinedTextStrokeTextBlock_Style" TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="{Binding Text, ElementName=FillText}"/>
<Setter Property="FontSize" Value="{Binding FontSize, ElementName=FillText}"/>
<Setter Property="FontFamily" Value="{Binding FontFamily, ElementName=FillText}"/>
<Setter Property="FontStyle" Value="{Binding FontStyle, ElementName=FillText}"/>
<Setter Property="FontWeight" Value="{Binding FontWeight, ElementName=FillText}"/>
<Setter Property="Padding" Value="{Binding TextAlignment, ElementName=Padding}"/>
<Setter Property="TextAlignment" Value="{Binding TextAlignment, ElementName=FillText}"/>
<Setter Property="VerticalAlignment" Value="{Binding VerticalAlignment, ElementName=FillText}"/>
</Style>
</Canvas.Resources>
<!-- Offseting the Text block will create the outline, the margin is the Stroke Width-->
<TextBlock Foreground="{TemplateBinding BorderBrush}" Margin="-1,0,0,0" Style="{DynamicResource OutlinedTextStrokeTextBlock_Style}"/>
<TextBlock Foreground="{TemplateBinding BorderBrush}" Margin="0,-1,0,0" Style="{DynamicResource OutlinedTextStrokeTextBlock_Style}"/>
<TextBlock Foreground="{TemplateBinding BorderBrush}" Margin="0,0,-1,0" Style="{DynamicResource OutlinedTextStrokeTextBlock_Style}"/>
<TextBlock Foreground="{TemplateBinding BorderBrush}" Margin="0,0,0,-1" Style="{DynamicResource OutlinedTextStrokeTextBlock_Style}"/>
<!-- Base TextBlock Will be the Fill -->
<TextBlock x:Name="FillText" Text="{TemplateBinding Content}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}"
FontStyle="{TemplateBinding FontStyle}" FontWeight="{TemplateBinding FontWeight}" Padding="0" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
TextAlignment="{TemplateBinding HorizontalContentAlignment}"
Style="{DynamicResource TbMediaOverlay_Style}"/>
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
A: as already mentioned, convert text to path
FormattedText t = new FormattedText
(
"abcxyz",
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface(
new FontFamily("Arial"),
new FontStyle(),
new FontWeight(),
new FontStretch()),
20,
Brushes.Transparent
);
Geometry g = t.BuildGeometry(new System.Windows.Point(0, 0));
Path p = new Path();
p.Fill = Brushes.White;
p.Stroke = Brushes.Black;
p.StrokeThickness = 1;
p.Data = g;
A: I modified @Javier G. answer
*
*Stroke position can be: center, outside or Inside, the default
is outside.
*Fill can be transparent.
Center:
Outside:
Inside:
Code:
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
namespace WpfApp2
{
public enum StrokePosition
{
Center,
Outside,
Inside
}
[ContentProperty("Text")]
public class OutlinedTextBlock : FrameworkElement
{
private void UpdatePen()
{
_Pen = new Pen(Stroke, StrokeThickness)
{
DashCap = PenLineCap.Round,
EndLineCap = PenLineCap.Round,
LineJoin = PenLineJoin.Round,
StartLineCap = PenLineCap.Round
};
if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)
{
_Pen.Thickness = StrokeThickness * 2;
}
InvalidateVisual();
}
public StrokePosition StrokePosition
{
get { return (StrokePosition)GetValue(StrokePositionProperty); }
set { SetValue(StrokePositionProperty, value); }
}
public static readonly DependencyProperty StrokePositionProperty =
DependencyProperty.Register("StrokePosition",
typeof(StrokePosition),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(StrokePosition.Outside, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register(
"Stroke",
typeof(Brush),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register(
"StrokeThickness",
typeof(double),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner(
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextInvalidated));
public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register(
"TextAlignment",
typeof(TextAlignment),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register(
"TextDecorations",
typeof(TextDecorationCollection),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextTrimmingProperty = DependencyProperty.Register(
"TextTrimming",
typeof(TextTrimming),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(OnFormattedTextUpdated));
public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register(
"TextWrapping",
typeof(TextWrapping),
typeof(OutlinedTextBlock),
new FrameworkPropertyMetadata(TextWrapping.NoWrap, OnFormattedTextUpdated));
private FormattedText _FormattedText;
private Geometry _TextGeometry;
private Pen _Pen;
private PathGeometry _clipGeometry;
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
[TypeConverter(typeof(FontSizeConverter))]
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public FontStretch FontStretch
{
get { return (FontStretch)GetValue(FontStretchProperty); }
set { SetValue(FontStretchProperty, value); }
}
public FontStyle FontStyle
{
get { return (FontStyle)GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
public FontWeight FontWeight
{
get { return (FontWeight)GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
public Brush Stroke
{
get { return (Brush)GetValue(StrokeProperty); }
set { SetValue(StrokeProperty, value); }
}
public double StrokeThickness
{
get { return (double)GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public TextAlignment TextAlignment
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public TextDecorationCollection TextDecorations
{
get { return (TextDecorationCollection)GetValue(TextDecorationsProperty); }
set { SetValue(TextDecorationsProperty, value); }
}
public TextTrimming TextTrimming
{
get { return (TextTrimming)GetValue(TextTrimmingProperty); }
set { SetValue(TextTrimmingProperty, value); }
}
public TextWrapping TextWrapping
{
get { return (TextWrapping)GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
public OutlinedTextBlock()
{
UpdatePen();
TextDecorations = new TextDecorationCollection();
}
protected override void OnRender(DrawingContext drawingContext)
{
EnsureGeometry();
drawingContext.DrawGeometry(Fill, null, _TextGeometry);
if (StrokePosition == StrokePosition.Outside)
{
drawingContext.PushClip(_clipGeometry);
}
else if (StrokePosition == StrokePosition.Inside)
{
drawingContext.PushClip(_TextGeometry);
}
drawingContext.DrawGeometry(null, _Pen, _TextGeometry);
if (StrokePosition == StrokePosition.Outside || StrokePosition == StrokePosition.Inside)
{
drawingContext.Pop();
}
}
protected override Size MeasureOverride(Size availableSize)
{
EnsureFormattedText();
// constrain the formatted text according to the available size
double w = availableSize.Width;
double h = availableSize.Height;
// the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions
// the Math.Max call is to ensure we don't hit zero, which will cause MaxTextHeight to throw
_FormattedText.MaxTextWidth = Math.Min(3579139, w);
_FormattedText.MaxTextHeight = Math.Max(0.0001d, h);
// return the desired size
return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));
}
protected override Size ArrangeOverride(Size finalSize)
{
EnsureFormattedText();
// update the formatted text with the final size
_FormattedText.MaxTextWidth = finalSize.Width;
_FormattedText.MaxTextHeight = Math.Max(0.0001d, finalSize.Height);
// need to re-generate the geometry now that the dimensions have changed
_TextGeometry = null;
UpdatePen();
return finalSize;
}
private static void OnFormattedTextInvalidated(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock._FormattedText = null;
outlinedTextBlock._TextGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private static void OnFormattedTextUpdated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var outlinedTextBlock = (OutlinedTextBlock)dependencyObject;
outlinedTextBlock.UpdateFormattedText();
outlinedTextBlock._TextGeometry = null;
outlinedTextBlock.InvalidateMeasure();
outlinedTextBlock.InvalidateVisual();
}
private void EnsureFormattedText()
{
if (_FormattedText != null)
{
return;
}
_FormattedText = new FormattedText(
Text ?? "",
CultureInfo.CurrentUICulture,
FlowDirection,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
FontSize,
Brushes.Black);
UpdateFormattedText();
}
private void UpdateFormattedText()
{
if (_FormattedText == null)
{
return;
}
_FormattedText.MaxLineCount = TextWrapping == TextWrapping.NoWrap ? 1 : int.MaxValue;
_FormattedText.TextAlignment = TextAlignment;
_FormattedText.Trimming = TextTrimming;
_FormattedText.SetFontSize(FontSize);
_FormattedText.SetFontStyle(FontStyle);
_FormattedText.SetFontWeight(FontWeight);
_FormattedText.SetFontFamily(FontFamily);
_FormattedText.SetFontStretch(FontStretch);
_FormattedText.SetTextDecorations(TextDecorations);
}
private void EnsureGeometry()
{
if (_TextGeometry != null)
{
return;
}
EnsureFormattedText();
_TextGeometry = _FormattedText.BuildGeometry(new Point(0, 0));
if (StrokePosition == StrokePosition.Outside)
{
var boundsGeo = new RectangleGeometry(new Rect(0, 0, ActualWidth, ActualHeight));
_clipGeometry = Geometry.Combine(boundsGeo, _TextGeometry, GeometryCombineMode.Exclude, null);
}
}
}
}
Usage:
<Grid Margin="12" Background="Bisque">
<local:OutlinedTextBlock Stroke="Red"
ClipToBounds="False"
FontSize="56"
Fill="Transparent"
StrokePosition="Inside"
StrokeThickness="1" Text=" abc">
</local:OutlinedTextBlock>
</Grid>
A: In Blend you could convert the TextBlock to a Path, and then use the normal Stroke properties. But I'm assuming you wanted something that you could make dynamic...
Otherwise I would think it would have to be some sort of bitmap effect or special brush.
A: Slight modification to Kent Boogaart's code which, while awesome, is missing a small detail. This is probably a little inaccurate in that it will only measure the fill and not the stroke but adding a couple of lines to OnRender() Viewbox will be able to get a handle on what to do with it (although, as with TextBox, not in preview).
protected override void OnRender(DrawingContext drawingContext)
{
this.EnsureGeometry();
this.Width = this.formattedText.Width;
this.Height = this.formattedText.Height;
drawingContext.DrawGeometry(this.Fill, new Pen(this.Stroke, this.StrokeThickness), this.textGeometry);
}
I'm using this with two layers of text so the stroke appears to only be around the outside as follows. This will obviously not work straight away as it refers to specific images and fonts.
<Viewbox Stretch="UniformToFill" Margin="0" Grid.Column="1">
<bd:OutlinedText x:Name="LevelTitleStroke" Text="Level" FontSize="80pt" FontFamily="/fonts/papercuts-2.ttf#Paper Cuts 2" Grid.Row="1" TextAlignment="Center" IsHitTestVisible="False" StrokeThickness="15">
<bd:OutlinedText.Stroke>
<ImageBrush ImageSource="/WpfApplication1;component/GrungeMaps/03DarkBlue.jpg" Stretch="None" />
</bd:OutlinedText.Stroke>
</bd:OutlinedText>
</Viewbox>
<Viewbox Stretch="UniformToFill" Margin="0" Grid.Column="1">
<bd:OutlinedText x:Name="LevelTitleFill" Text="Level" FontSize="80pt" FontFamily="/fonts/papercuts-2.ttf#Paper Cuts 2" Grid.Row="1" TextAlignment="Center" IsHitTestVisible="False">
<bd:OutlinedText.Fill>
<ImageBrush ImageSource="/WpfApplication1;component/GrungeMaps/03Red.jpg" Stretch="None" />
</bd:OutlinedText.Fill>
</bd:OutlinedText>
</Viewbox>
A: I was trying to achieve something similar to this as well. The classes mentioned here were great, but weren't exactly what I was looking for, because it only really looked right if the text was large enough. The text I was trying to display was around 10 - 11 font size, and the stroke was so large the letters sort of blended together.
Just to clarify, this text was supposed to be overlaid on a user-defined picture, which could have varying colors, and I wanted to ensure this text would show up.
I don't know if this is best practice or not, but this at least achieved the look I wanted (based on this article):
<Style x:Key="OutlinedTextBlockOuter" TargetType="TextBlock">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontSize" Value="10"/>
<Setter Property="Effect">
<Setter.Value>
<BlurEffect Radius="3.0"/>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="OutlinedTextBlockInner" TargetType="TextBlock">
<Setter Property="Foreground" Value="White" />
<Setter Property="FontSize" Value="10"/>
</Style>
Then for the actual TextBlocks, I combined two Outer styled TextBlocks because one was too light, and one Inner styled TextBlock:
<Grid Margin="5">
<TextBlock Style="{StaticResource OutlinedTextBlockOuter}" Text="This is outlined text using BlurEffect"/>
<TextBlock Style="{StaticResource OutlinedTextBlockOuter}" Text="This is outlined text using BlurEffect"/>
<TextBlock Style="{StaticResource OutlinedTextBlockInner}" Text="This is outlined text using BlurEffect"/>
</Grid>
Alternatively, you could use the DropShadowEffect, which looked okay with using only two textboxes (although adding more DropShadowEffects with varying directions and lowered opacity may look even better):
<Grid Margin="5">
<TextBlock Text="This is my outlined text using the DropShadowEffect" FontSize="10" Foreground="White">
<TextBlock.Effect>
<DropShadowEffect ShadowDepth="1" BlurRadius="2" Opacity="0.75" Direction="315"/>
</TextBlock.Effect>
</TextBlock>
<TextBlock Text="This is my outlined text using the DropShadowEffect" FontSize="10" Foreground="White">
<TextBlock.Effect>
<DropShadowEffect ShadowDepth="1" BlurRadius="2" Opacity="0.75" Direction="135"/>
</TextBlock.Effect>
</TextBlock>
</Grid>
A: I had to add this to MeasureOverride so it would show single lines of text while using layout rounding. It worked fine when the text was wrapping though.
// return the desired size
return new Size(Math.Ceiling(_FormattedText.Width), Math.Ceiling(_FormattedText.Height));
A: <TextBlock> has no decorative attributes itself. I would put it on a <Canvas> with a <Rectangle> and apply the stroke there.
A: Could just use a Label instead. It has more properties that you can play with. Example:
<Style x:Key="LeftBorderLabel" TargetType="{x:Type Label}">
<Setter Property="Margin" Value="0" />
<Setter Property="BorderThickness" Value="1,0,0,0" />
<Setter Property="BorderBrush" Value="Blue" />
</Style>
A: This helped me out tremendously! Just in case anyone needs it in the future, here's the VB version (made StrokeThickness a double and added an Underline property):
Imports System
Imports System.Windows.Media
Imports System.Globalization
Imports System.Windows
Imports System.Windows.Markup
Namespace CustomXaml
Public Class OutlinedText
Inherits FrameworkElement
Implements IAddChild
Private _textGeometry As Geometry
Private Shared Sub OnOutlineTextInvalidated(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
DirectCast(d, OutlinedText).CreateText()
End Sub
Protected Overrides Sub OnRender(drawingContext As System.Windows.Media.DrawingContext)
CreateText()
drawingContext.DrawGeometry(Fill, New Pen(Stroke, StrokeThickness), _textGeometry)
End Sub
Public Sub CreateText()
Dim fontStyle = FontStyles.Normal
Dim fontWeight = FontWeights.Medium
Dim fontDecoration = New TextDecorationCollection()
If Bold Then fontWeight = FontWeights.Bold
If Italic Then fontStyle = FontStyles.Italic
If Underline Then fontDecoration.Add(TextDecorations.Underline)
Dim formattedText = New FormattedText( _
Text, _
CultureInfo.GetCultureInfo("en-us"), _
FlowDirection.LeftToRight, _
New Typeface(Font, fontStyle, fontWeight, FontStretches.Normal), _
FontSize, _
Brushes.Black _
)
formattedText.SetTextDecorations(fontDecoration)
_textGeometry = formattedText.BuildGeometry(New Point(0, 0))
Me.MinWidth = formattedText.Width
Me.MinHeight = formattedText.Height
End Sub
Public Property Bold As Boolean
Get
Return CType(GetValue(BoldProperty), Boolean)
End Get
Set(value As Boolean)
SetValue(BoldProperty, value)
End Set
End Property
Public Shared ReadOnly BoldProperty As DependencyProperty = DependencyProperty.Register( _
"Bold", _
GetType(Boolean), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
False, _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property Underline As Boolean
Get
Return CType(GetValue(UnderlineProperty), Boolean)
End Get
Set(value As Boolean)
SetValue(UnderlineProperty, value)
End Set
End Property
Public Shared ReadOnly UnderlineProperty As DependencyProperty = DependencyProperty.Register( _
"Underline", _
GetType(Boolean), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
False, _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property Fill As Brush
Get
Return CType(GetValue(FillProperty), Brush)
End Get
Set(value As Brush)
SetValue(FillProperty, value)
End Set
End Property
Public Shared ReadOnly FillProperty As DependencyProperty = DependencyProperty.Register( _
"Fill", _
GetType(Brush), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
New SolidColorBrush(Colors.LightSteelBlue), _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property Font As FontFamily
Get
Return CType(GetValue(FontProperty), FontFamily)
End Get
Set(value As FontFamily)
SetValue(FontProperty, value)
End Set
End Property
Public Shared ReadOnly FontProperty As DependencyProperty = DependencyProperty.Register( _
"Font", _
GetType(FontFamily), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
New FontFamily("Arial"), _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property FontSize As Double
Get
Return CType(GetValue(FontSizeProperty), Double)
End Get
Set(value As Double)
SetValue(FontSizeProperty, value)
End Set
End Property
Public Shared ReadOnly FontSizeProperty As DependencyProperty = DependencyProperty.Register( _
"FontSize", _
GetType(Double), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
CDbl(48.0), _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property Italic As Boolean
Get
Return CType(GetValue(ItalicProperty), Boolean)
End Get
Set(value As Boolean)
SetValue(ItalicProperty, value)
End Set
End Property
Public Shared ReadOnly ItalicProperty As DependencyProperty = DependencyProperty.Register( _
"Italic", _
GetType(Boolean), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
False, _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property Stroke As Brush
Get
Return CType(GetValue(StrokeProperty), Brush)
End Get
Set(value As Brush)
SetValue(StrokeProperty, value)
End Set
End Property
Public Shared ReadOnly StrokeProperty As DependencyProperty = DependencyProperty.Register( _
"Stroke", _
GetType(Brush), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
New SolidColorBrush(Colors.Teal), _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property StrokeThickness As Double
Get
Return CType(GetValue(StrokeThicknessProperty), Double)
End Get
Set(value As Double)
SetValue(StrokeThicknessProperty, value)
End Set
End Property
Public Shared ReadOnly StrokeThicknessProperty As DependencyProperty = DependencyProperty.Register( _
"StrokeThickness", _
GetType(Double), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
CDbl(0), _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Property Text As String
Get
Return CType(GetValue(TextProperty), String)
End Get
Set(value As String)
SetValue(TextProperty, value)
End Set
End Property
Public Shared ReadOnly TextProperty As DependencyProperty = DependencyProperty.Register( _
"Text", _
GetType(String), _
GetType(OutlinedText), _
New FrameworkPropertyMetadata( _
"", _
FrameworkPropertyMetadataOptions.AffectsRender, _
New PropertyChangedCallback(AddressOf OnOutlineTextInvalidated), _
Nothing _
) _
)
Public Sub AddChild(value As Object) Implements System.Windows.Markup.IAddChild.AddChild
End Sub
Public Sub AddText(text As String) Implements System.Windows.Markup.IAddChild.AddText
Me.Text = text
End Sub
End Class
End Namespace
A: I was using Kent's solution in my custom control. It resulted in a null exception when using templatebinding against the text property.
I had to modify the MeasureOverride function like so:
protected override Size MeasureOverride(Size availableSize)
{
this.EnsureFormattedText();
if (this.formattedText == null)
{
this.formattedText = new FormattedText(
(this.Text == null) ? "" : this.Text,
CultureInfo.CurrentUICulture,
this.FlowDirection,
new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal),
this.FontSize,
Brushes.Black);
}
// constrain the formatted text according to the available size
// the Math.Min call is important - without this constraint (which seems arbitrary, but is the maximum allowable text width), things blow up when availableSize is infinite in both directions
this.formattedText.MaxTextWidth = Math.Min(3579139, availableSize.Width);
this.formattedText.MaxTextHeight = availableSize.Height;
// return the desired size
return new Size(this.formattedText.Width, this.formattedText.Height);
}
It should be noted that I did not thoroughly test this.
A: Since I have another answer, I'll post it for the record.
I think it is a less elegant one, without using Geometry, Path and FormattedText, though simpler, and (if you know I'd like to know) might be faster to render ??
It basically had the same text 8 times, but shifted on all cardinal direction.
here is the code of my UserControl :
/// <summary>
/// User Control to display a Text with an outline
/// </summary>
public partial class OutlinedText : UserControl, INotifyPropertyChanged
{
#region DependencyProperties
/// <summary>
/// The Text to render
/// </summary>
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(OutlinedText), new PropertyMetadata(""));
/// <summary>
/// The size (thickness) of the Stroke
/// </summary>
public int StrokeSize
{
get { return (int)GetValue(StrokeSizeProperty); }
set { SetValue(StrokeSizeProperty, value); }
}
// Using a DependencyProperty as the backing store for StrokeSize. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StrokeSizeProperty =
DependencyProperty.Register("StrokeSize", typeof(int), typeof(OutlinedText), new PropertyMetadata(1));
/// <summary>
/// The Color of the Stroke
/// </summary>
public Brush StrokeColor
{
get { return (Brush)GetValue(StrokeColorProperty); }
set { SetValue(StrokeColorProperty, value); }
}
// Using a DependencyProperty as the backing store for StrokeColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StrokeColorProperty =
DependencyProperty.Register("StrokeColor", typeof(Brush), typeof(OutlinedText), new PropertyMetadata(Brushes.Black));
#endregion
#region ctor
public OutlinedText()
{
InitializeComponent();
this.DataContext = this;
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
and on XAML side :
<UserControl x:Class="NAMESPACE.OutlinedText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:NAMESPACE"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<ResourceDictionary>
<local:IntegerInverterConverter x:Key="IntegerInverterConverterKey"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<!--Bottom Right ⬊ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="{Binding StrokeSize}" Y="{Binding StrokeSize}"/>
</TextBlock.RenderTransform>
</TextBlock>
<!--Top Left ⬉ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}" Y="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}"/>
</TextBlock.RenderTransform>
</TextBlock>
<!--Bottom Left ⬋ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}" Y="{Binding StrokeSize}"/>
</TextBlock.RenderTransform>
</TextBlock>
<!--Top Right ⬈ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="{Binding StrokeSize}" Y="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}"/>
</TextBlock.RenderTransform>
</TextBlock>
<!--Top ⬆ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="0" Y="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}"/>
</TextBlock.RenderTransform>
</TextBlock>
<!--Bottom ⬇ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="0" Y="{Binding StrokeSize}"/>
</TextBlock.RenderTransform>
</TextBlock>
<!--Right ➡ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="{Binding StrokeSize}" Y="0"/>
</TextBlock.RenderTransform>
</TextBlock>
<!--Left ⬅ -->
<TextBlock Foreground="{Binding StrokeColor}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
RenderTransformOrigin="0.5, 0.5"
Text="{Binding Text}" >
<TextBlock.RenderTransform>
<TranslateTransform X="{Binding StrokeSize, Converter={StaticResource IntegerInverterConverterKey}}" Y="0"/>
</TextBlock.RenderTransform>
</TextBlock>
<TextBlock Foreground="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=Foreground}"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontSize}"
FontWeight="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontWeight}"
FontFamily="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=FontFamily}"
Text="{Binding Text}" />
</Grid>
The used converter here is a simple *(-1) on an integer, to avoid using another property.
Usage :
<local:OutlinedText Margin="WHATEVER" HorizontalAlignment="WHATEVER" VerticalAlignment="WHATEVER"
Text="Your Text" StrokeColor="WhiteSmoke" StrokeSize="2" FontSize="20" FontWeight="Bold"
Foreground="Magenta"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "72"
}
|
Q: Inserting a string of form "GUID1, GUID2, GUID3 ..." into an IN statement in TSQL I've got a stored procedure in my database, that looks like this
ALTER PROCEDURE [dbo].[GetCountingAnalysisResults]
@RespondentFilters varchar
AS
BEGIN
@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'''
DECLARE @SQL nvarchar(600)
SET @SQL =
'SELECT *
FROM Answer
WHERE Answer.RespondentId IN ('+@RespondentFilters+'''))
GROUP BY ChosenOptionId'
exec sp_executesql @SQL
END
It compiles and executes, but somehow it doesn't give me good results, just like the IN statement wasn't working. Please, if anybody know the solution to this problem, help me.
A: You should definitely look at splitting the list of GUIDs into a table and joining against that table. You should be able to find plenty of examples online for a table-valued function that splits an input string into a table.
Otherwise, your stored procedure is vulnerable to SQL injection. Consider the following value for @RespondentFilters:
@RespondentFilters = '''''); SELECT * FROM User; /*'
Your query would be more secure parsing (i.e. validating) the parameter values and joining:
SELECT *
FROM Answer
WHERE Answer.RespondentId IN (SELECT [Item] FROM dbo.ParseList(@RespondentFilters))
GROUP BY ChosenOptionId
or
SELECT *
FROM Answer
INNER JOIN dbo.ParseList(@RespondentFilters) Filter ON Filter.Item = Answer.RespondentId
GROUP BY ChosenOptionId
It's slightly more efficient as well, since you aren't dealing with dynamic SQL (sp_executesql will cache query plans, but I'm not sure if it will accurately identify your query as a parameterized query since it has a variable list of items in the IN clause).
A: You need single quotes around each GUID in the list
@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'', ''114c61f2-8935-4755-b4e9-4a598a51cc7f'''
A: It looks like you don't have closing quotes around your @RespondentFilters '8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'
Since GUIDs do a string compare, that's not going to work.
Your best bet is to use some code to split the list out into multiple values.
Something like this:
-- This would be the input parameter of the stored procedure, if you want to do it that way, or a UDF
declare @string varchar(500)
set @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'
declare @pos int
declare @piece varchar(500)
-- Need to tack a delimiter onto the end of the input string if one doesn't exist
if right(rtrim(@string),1) ','
set @string = @string + ','
set @pos = patindex('%,%' , @string)
while @pos 0
begin
set @piece = left(@string, @pos - 1)
-- You have a piece of data, so insert it, print it, do whatever you want to with it.
print cast(@piece as varchar(500))
set @string = stuff(@string, 1, @pos, '')
set @pos = patindex('%,%' , @string)
end
Code stolen from Raymond Lewallen
A: I think you need quotes inside the string too. Try:
@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'',''114c61f2-8935-4755-b4e9-4a598a51cc7f'''
You could also consider parsing the @RespondentFilters into a temporary table.
A: Tank you all for your ansewers. They all helped a lot. I've dealt with the problem by writing a split function, and it works fine. It's a litte bit overhead from what I could have done, but you know, the deadline is hiding around the corner :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a .NET/C# wrapper for SQLite? I'd sort of like to use SQLite from within C#.Net, but I can't seem to find an appropriate library. Is there one? An official one? Are there other ways to use SQLite than with a wrapper?
A: I'd definitely go with System.Data.SQLite (as previously mentioned: http://sqlite.phxsoftware.com/)
It is coherent with ADO.NET (System.Data.*), and is compiled into a single DLL. No sqlite3.dll - because the C code of SQLite is embedded within System.Data.SQLite.dll. A bit of managed C++ magic.
A: sqlite-net is an open source, minimal library to allow .NET and Mono applications to store data in SQLite 3 databases. More information at the wiki page.
It is written in C# and is meant to be simply compiled in with your projects. It was first designed to work with MonoTouch on the iPhone, but has grown up to work on all the platforms (Mono for Android, .NET, Silverlight, WP7, WinRT, Azure, etc.).
It is available as a Nuget package, where it is the 2nd most popular SQLite package with over 60,000 downloads as of 2014.
sqlite-net was designed as a quick and convenient database layer. Its design follows from these goals:
*
*Very easy to integrate with existing projects and with MonoTouch projects.
*Thin wrapper over SQLite and should be fast and efficient. (The library should not be the performance bottleneck of your queries.)
*Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.
*Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)
*0 dependencies aside from a compiled form of the sqlite2 library.
Non-goals include:
*
*Not an ADO.NET implementation. This is not a full SQLite driver. If you need that, use System.Data.SQLite.
A: From https://system.data.sqlite.org:
System.Data.SQLite is an ADO.NET adapter for SQLite.
System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now mostly performed by the SQLite Development Team. The SQLite team is committed to supporting System.Data.SQLite long-term.
"System.Data.SQLite is the original SQLite database engine and a complete ADO.NET 2.0 provider all rolled into a single mixed mode assembly. It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll). Unlike normal mixed assemblies, it has no linker dependency on the .NET runtime so it can be distributed independently of .NET."
It even supports Mono.
A: Here are the ones I can find:
*
*managed-sqlite
*SQLite.NET wrapper
*System.Data.SQLite
Sources:
*
*sqlite.org
*other posters
A: There's also now this option: http://code.google.com/p/csharp-sqlite/ - a complete port of SQLite to C#.
A: Mono comes with a wrapper. https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0 gives code to wrap the actual SQLite dll ( http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip found on the download page http://www.sqlite.org/download.html/ ) in a .net friendly way. It works on Linux or Windows.
This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.
A: Microsoft.Data.Sqlite
Microsoft now provides Microsoft.Data.Sqlite as a first-party SQLite solution for .NET, which is provided as part of ASP.NET Core. The license is the Apache License, Version 2.0.
*
*NuGet package
*Source repo on GitHub
* Disclaimer: I have not actually tried using this myself yet, but there is some documentation provided on Microsoft Docs here for using it with .NET Core and UWP.
A: For those like me who don't need or don't want ADO.NET, those who need to run code closer to SQLite, but still compatible with netstandard (.net framework, .net core, etc.), I've built a 100% free open source project called SQLNado (for "Not ADO") available on github here:
https://github.com/smourier/SQLNado
It's available as a nuget here https://www.nuget.org/packages/SqlNado but also available as a single .cs file, so it's quite practical to use in any C# project type.
It supports all of SQLite features when using SQL commands, and also supports most of SQLite features through .NET:
*
*Automatic class-to-table mapping (Save, Delete, Load, LoadAll, LoadByPrimaryKey, LoadByForeignKey, etc.)
*Automatic synchronization of schema (tables, columns) between classes and existing table
*Designed for thread-safe operations
*Where and OrderBy LINQ/IQueryable .NET expressions are supported (work is still in progress in this area), also with collation support
*SQLite database schema (tables, columns, etc.) exposed to .NET
*SQLite custom functions can be written in .NET
*SQLite incremental BLOB I/O is exposed as a .NET Stream to avoid high memory consumption
*SQLite collation support, including the possibility to add custom collations using .NET code
*SQLite extensions (.dll) loading support
*SQLite Full Text Search engine (FTS3) support, including the possibility to add custom FTS3 tokenizers using .NET code (like localized stop words for example). I don't believe any other .NET wrappers do that.
*Automatic support for Windows 'winsqlite3.dll' (only on recent Windows versions) to avoid shipping any binary dependency file. This works in Azure Web apps too!.
A: The folks from sqlite.org have taken over the development of the ADO.NET provider:
From their homepage:
This is a fork of the popular ADO.NET
4.0 adaptor for SQLite known as System.Data.SQLite. The originator of
System.Data.SQLite, Robert Simpson, is
aware of this fork, has expressed his
approval, and has commit privileges on
the new Fossil repository. The SQLite
development team intends to maintain
System.Data.SQLite moving forward.
Historical versions, as well as the
original support forums, may still be
found at
http://sqlite.phxsoftware.com, though
there have been no updates to this
version since April of 2010.
The complete list of features can be found at on their wiki. Highlights include
*
*ADO.NET 2.0 support
*Full Entity Framework support
*Full Mono support
*Visual Studio 2005/2008 Design-Time support
*Compact Framework, C/C++ support
Released DLLs can be downloaded directly from the site.
A: Version 1.2 of Monotouch includes support for System.Data. You can find more details here:
http://monotouch.net/Documentation/System.Data
But basically it allows you to use the usual ADO .NET patterns with sqlite.
A: http://www.devart.com/dotconnect/sqlite/
dotConnect for SQLite is an enhanced data provider for SQLite that builds on ADO.NET technology to present a complete solution for developing SQLite-based database applications. As a part of the Devart database application development framework, dotConnect for SQLite offers both high performance native connectivity to the SQLite database and a number of innovative development tools and technologies.
dotConnect for SQLite introduces new approaches for designing application architecture, boosts productivity, and leverages database application implementation.
I use the standard version,it works perfect :)
A: A barebones wrapper of the functions as provided by the sqlite library. Latest version supports functions provided sqlite library 3.7.10
SQLiteWrapper project
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "271"
}
|
Q: Stripping Invalid XML characters in Java I have an XML file that's the output from a database. I'm using the Java SAX parser to parse the XML and output it in a different format. The XML contains some invalid characters and the parser is throwing errors like 'Invalid Unicode character (0x5)'
Is there a good way to strip all these characters out besides pre-processing the file line-by-line and replacing them? So far I've run into 3 different invalid characters (0x5, 0x6 and 0x7). It's a ~4gb database dump and we're going to be processing it a bunch of times, so having to wait an extra 30 minutes each time we get a new dump to run a pre-processor on it is going to be a pain, and this isn't the first time I've run into this issue.
A: I use the following regexp that seems to work as expected for the JDK6:
Pattern INVALID_XML_CHARS = Pattern.compile("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\uD800\uDC00-\uDBFF\uDFFF]");
...
INVALID_XML_CHARS.matcher(stringToCleanup).replaceAll("");
In JDK7 it might be possible to use the notation \x{10000}-\x{10FFFF} for the last range that lies outside of the BMP instead of the \uD800\uDC00-\uDBFF\uDFFF notation that is not as simple to understand.
A: I have a similar problem when parsing content of an Australian export tariffs into an XML document. I cannot use solutions suggested here such as:
- Use an external tool (a jar) invoked from command line.
- Ask Australian Customs to clean up the source file.
The only method to solve this problem at the moment is to iterate through the entire content of the source file, character by character and test if each character does not belong to the ascii range 0x00 to 0x1F inclusively. It can be done, but I was wondering if there is a better way using Java methods for type String.
EDIT
I found a solution that may be useful to others: Use Java method String#ReplaceAll to replace or remove any undesirable characters in XML document.
Example code (I removed some necessary statements to avoid clutter):
BufferedReader reader = null;
...
String line = reader.readLine().replaceAll("[\\x00-\\x1F]", "");
In this example I remove (i.e. replace with an empty string), non-printable characters within range 0x00 to 0x1F inclusively. You can change the second argument in method #replaceAll() to replace characters with the string your application requires.
A: I used Xalan org.apache.xml.utils.XMLChar class:
public static String stripInvalidXmlCharacters(String input) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (XMLChar.isValid(c)) {
sb.append(c);
}
}
return sb.toString();
}
A: I haven't used this personally but Atlassian made a command line XML cleaner that may suit your needs (it was made mainly for JIRA but XML is XML):
Download atlassian-xml-cleaner-0.1.jar
Open a DOS console or shell, and locate the XML or ZIP backup file on your computer, here assumed to be called data.xml
Run:
java -jar atlassian-xml-cleaner-0.1.jar data.xml > data-clean.xml
This will write a copy of data.xml to data-clean.xml, with invalid characters removed.
A: Is it possible your invalid characters are present only within the values and not the tags themselves i.e. the XML notionally meets the schema but the values have not been properly sanitized? If so, what about overriding InputStream to create a CleansingInputStream that replaces your invalid characters with their XML equivalents?
A: Your problem does not concern XML: it concerns character encodings. What it comes down to is that every string, be it XML or otherwise, consists of bytes and you cannot know what characters these bytes represent, unless you are told what character encoding the string has. If, for instance, the supplier tells you it's UTF-8 and it's actually something else, you are bound to run into problems. In the best case, everything works, but some bytes are translated into 'wrong' characters. In the worst case you get errors like the one you encountered.
Actually, your problem is even worse: your string contains byte sequences that do not represent characters in any character encoding. There is no texthandling tool, let alone an XML parser, that can help you here. This needs byte-level cleaning up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: Any Yahoo YUI validation framework that I can implement in asp.net MVC? Has anyone seen a Yahoo YUI validation framework that I could implement into asp.net MVC? I've seen a jQuery one but I want to work wit YUI.
A: It's not quite as spiffy (IMO) as jQuery, but here's a yazaar validation framework.
A: It's worth noting that Microsoft have announced they'll be shipping JQuery with Visual Studio and there will be more integration with the MVC framework. This may or may not affect your decision to use YUI.
More details here:
http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx
A: You might try the yui-form-validator on Google code...
It looks promising for what you are looking for.
A: I recently found indputEx. Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: 7-Zip command-line switch Is there a 7-Zip command-line switch that prevents the filenames from echoing to the screen as they are added to the archive?
A: Not built in, but if you add
<7z command here> 2>&1 NUL
to the end of your command-line, it will redirect all the output into the null device and stops it echoing to the screen. This is the MS-DOS equivalent of
2>&1 /dev/null
in Linux and Unix systems.
A: 7-Zip has no switch for this. If you are using PowerShell to call 7-Zip, you can redirect the output to null using Out-Null. For example,
C:\PS>my-create-7zip-function | out-null
A: If it doesn't have one, you can still redirect the output using > into a file, then deleting the file afterwards. If you are on *nix, you can redirect into /dev/null.
Edit
In MS-DOS and cmd.exe you can redirect into NUL, instead of a file. Thanks to agnul for this hint.
A: AFAIK, there is not a switch for that, but you could hide the output redirecting it to a file, for example (DOS batch):
7z.exe ... normal parameters > DumpFile.txt
This way all the output ends in DumpFile.txt and not on the screen.
A: To avoid file names echoing on the screen and display only the confirmations, do:
...\right_path\7z a output.zip folder_to_be_compressed | findstr /b /r /c:"\<Everything is Ok" /c:"\<Scanning" /c:"\<Creating archive"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Which Javascript engine would you embed in your application? I want to embed Javascript in a hobby game engine of mine. Now that we have the 5th generation of Javascript engines out (all blazing fast) I'm curious what engine would you choose to embed in a C++ framework (that includes actual ease of embeding it)?
Note: Just to make it clear, I'm not interested in DOM scripting or writing Javascript in a browser.
Here's a compilation of links so far and some tips from the thread
*
*SpiderMonkey
*tracemonkey (note:backwards compatible with spidermonkey):
*V8
*Squirrelfish
Just for the record, I love Lua and have already embedded it in game engines about 5 times at work.
However now this is a hobby project, and I think that Javascript being known by most web developers and because its ECMA, Flash and Flex developers, a game engine that uses Javascript and XML for scripting would be more user-friendly and cater to a larger user base (and one that so far has not had a chance to use their skills for games) than one with Lua (and there are plenty of those around!).
Also for the record I'll go with V8 on this one, mostly because I like it's C++ style.
A: Is Java Script really the right language for your game?
Many of games out there are using the Lua programming language for scripting. It's easy to integrate, it's very small, it compiles on almost every platform and it's easy to learn.
This somewhat off topic, but thinking outside the box can be important to get things right .
A: I believe that v8 only works on x86, x64 and arm processors at the moment. Which might be a disadvantage.
With regards to thread safety, from include/v8.h:
* Multiple threads in V8 are allowed, but only one thread at a time
* is allowed to use V8. The definition of 'using V8' includes
* accessing handles or holding onto object pointers obtained from V8
* handles. It is up to the user of V8 to ensure (perhaps with
* locking) that this constraint is not violated.
You can read more in the source file (it looks like doxygen documentation, but they don't seem to have put it up anywhere).
Update: That comment has been removed, probably some time ago. It looks like v8 now has an Isolate object which represents an instance of the engine. A single Isolate instance can only be used in a single thread at a time, but other Isolate instances can be used in other threads at the same time.
A: When speaking of a scripting engine and c++ you could also consider chaiscript. It is close to ecma script (~Javascript) and very easy to embed in c++.
Seller from the webpage:
... ChaiScript, on the other hand, was designed from the ground up
with integration with C++ in mind.
...
ChaiScript has no meta-compiler, no library dependencies, no build
system requirements and no legacy baggage of any kind. At can work
seamlessly with any C++ functions you expose to it. It does not have
to be told explicitly about any type, it is function centric.
With ChaiScript you can literally begin scripting your application by
adding three lines of code to your program and not modifying your
build steps at all.
A: The benchmark that came out when V8 first hit the scene that showed V8 being 1000% (or whatever) faster than other engines was heavily weighted towards favoring engines that were good at recursion. If your code uses a lot of recursion, then V8 might give you a significant advantage, speed-wise. For "real world" (currently, at least) web stuff, SquirrelFish Extreme seems to be the hands down winner at the moment (see my blog post on the topic for the results of my own, informal testing).
As others have pointed out, ease of integration and quality of documentation might prevail over pure speed. It don't mean jack if you don't ship!
A: I'd wait for TraceMonkey, the next evolution of SpiderMonkey to come out. Faster and better designed. ( Uses code donated from Adobe Flash ).
Tracemonkey prides itself in making repetitious actions much faster by aggressively optimizing the structure at runtime based on actual usage, which aught to be handy for game-augmentation.
A: Mozilla's SpiderMonkey is fairly easy and well-documented. It's a C API, but it's straightforward to wrap it in C++. It can be compiled to be thread-safe, which is useful for games since you'd likely want to have your main logic in one thread and user interface logic in a second thread.
Google's V8 might be a good choice, since you're using C++, but I have no experience with it yet. According to the documentation (thanks to Daniel James), V8 is not thread-safe, although this may change in the future.
There's also WebKit's SquirrelFish, but I couldn't find a standalone version of that when I was looking earlier.
A: I've tried both SpiderMonkey and V8. With SpiderMonkey, I couldn't get anything to work. I couldn't even get the examples on mozilla.org to compile.
V8 worked out-of-the-box and I got some basic C++ <-> Javascript interaction going pretty quickly. There are some google lists for people using V8, and I found most of my questions answered there already.
A: Try Javascript .NET:
http://javascriptdotnet.codeplex.com/
It implements Google V8. You can compile and run Javascript directly from .NET code with it, and supply CLI objects to be used by the Javascript code as well. And V8 is probably the best engine ever created in terms of performance, it generates native code from Javascript.
A: You may also want to look at V8 from Google. It's pretty new, though.
A: I would keep an eye on v8 as it is screaming fast javascript engine, and i'm sure it will develop cross-platform support as it grows to maturity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "67"
}
|
Q: Best cross-browser method to capture CTRL+S with JQuery? My users would like to be able to hit Ctrl+S to save a form. Is there a good cross-browser way of capturing the Ctrl+S key combination and submit my form?
App is built on Drupal, so jQuery is available.
A: I combined a few options to support FireFox, IE and Chrome. I've also updated it to better support mac
// simply disables save event for chrome
$(window).keypress(function (event) {
if (!(event.which == 115 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) && !(event.which == 19)) return true;
event.preventDefault();
return false;
});
// used to process the cmd+s and ctrl+s events
$(document).keydown(function (event) {
if (event.which == 83 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
event.preventDefault();
save(event);
return false;
}
});
A:
$(document).keydown(function(e) {
if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try pressing ctrl+s somewhere.
This is an up-to-date version of @AlanBellows's answer, replacing which with key. It also works even with Chrome's capital key glitch (where if you press Ctrl+S it sends capital S instead of s). Works in all modern browsers.
A: I would like Web applications to not override my default shortcut keys, honestly. Ctrl+S already does something in browsers. Having that change abruptly depending on the site I'm viewing is disruptive and frustrating, not to mention often buggy. I've had sites hijack Ctrl+Tab because it looked the same as Ctrl+I, both ruining my work on the site and preventing me from switching tabs as usual.
If you want shortcut keys, use the accesskey attribute. Please don't break existing browser functionality.
A: @Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.
Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.
A: You could use a shortcut library to handle the browser specific stuff.
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
});
A: This jQuery solution works for me in Chrome and Firefox, for both Ctrl+S and Cmd+S.
$(document).keydown(function(e) {
var key = undefined;
var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];
while (key === undefined && possible.length > 0)
{
key = possible.pop();
}
if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true;
});
A: This one worked for me on Chrome...
for some reason event.which returns a capital S (83) for me, not sure why (regardless of the caps lock state) so I used fromCharCode and toLowerCase just to be on the safe side
$(document).keydown(function(event) {
//19 for Mac Command+S
if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-s pressed");
event.preventDefault();
return false;
});
If anyone knows why I get 83 and not 115, I will be happy to hear, also if anyone tests this on other browsers I'll be happy to hear if it works or not
A: This works for me (using jquery) to overload Ctrl+S, Ctrl+F and Ctrl+G:
$(window).bind('keydown', function(event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 's':
event.preventDefault();
alert('ctrl-s');
break;
case 'f':
event.preventDefault();
alert('ctrl-f');
break;
case 'g':
event.preventDefault();
alert('ctrl-g');
break;
}
}
});
A: $(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Key codes can differ between browsers, so you may need to check for more than just 115.
A: I like this little plugin. It needs a bit more cross browser friendliness though.
A: To Alan Bellows answer: !(e.altKey) added for users who use AltGr when typing (e.g Poland). Without this pressing AltGr+S will give same result as Ctrl+S
$(document).keydown(function(e) {
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true; });
A: example:
shortcut.add("Ctrl+c",function() {
alert('Ok...');
}
,{
'type':'keydown',
'propagate':false,
'target':document
});
usage
<script type="text/javascript" src="js/shortcut.js"></script>
link for download: http://www.openjs.com/scripts/events/keyboard_shortcuts/#
A: This should work (adapted from https://stackoverflow.com/a/8285722/388902).
var ctrl_down = false;
var ctrl_key = 17;
var s_key = 83;
$(document).keydown(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = true;
}).keyup(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = false;
});
$(document).keydown(function(e) {
if (ctrl_down && (e.keyCode == s_key)) {
alert('Ctrl-s pressed');
// Your code
return false;
}
});
A: I solved my problem on IE, using an alert("With a message") to prevent default Behavior:
window.addEventListener("keydown", function (e) {
if(e.ctrlKey || e.metaKey){
e.preventDefault(); //Good browsers
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { //hack for ie
alert("Please, use the print button located on the top bar");
return;
}
}
});
A: This Plugin Made by me may be helpful.
Plugin
You can use this plugin you have to supply the key Codes and function to be run like this
simulatorControl([17,83], function(){
console.log('You have pressed Ctrl+Z');
});
In the code i have displayed how to perform for Ctrl+S. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.
A: This was my solution, which is much easier to read than other suggestions here, can easily include other key combinations, and has been tested on IE, Chrome, and Firefox:
$(window).keydown(function(evt) {
var key = String.fromCharCode(evt.keyCode).toLowerCase();
switch(key) {
case "s":
if(evt.ctrlKey || evt.metaKey) {
fnToRun();
evt.preventDefault(true);
return false;
}
break;
}
return true;
});
A: A lot of answers in this thread mention e.which or e.Keycode which are not recommended nowadays according to MDN and https://keyjs.dev/. Moreover, the most-rated answer looks a little bit overdone since it also brings other hotkeys which leads to usage of switch. I did not check the third-party libraries, but I always try to use as few third-party libraries as possible.
Here's my solution (since you mentioned jQuery in your question):
$(document).keydown(function(e) {
if (e.ctrlKey && e.key == "s" || e.metaKey && e.key == "s") {
myFunction();
e.preventDefault();
}
});
The e.metaKey is here because of Mac devices.
The myFunction(); line is where you specify your function. The e.preventDefault(); line is here to prevent opening of the "Save…" window. If you want to keep it for some reason, feel free to remove this line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "175"
}
|
Q: What is the .NET equivalent of PHP var_dump? I remember seeing a while ago that there is some method in maybe the Reflection namespace that would recursively run ToString() on all of an object's properties and format it nicely for display.
Yes, I know everything I could want will be accessible through the debugger, but I'm wondering if anyone knows that command?
A: I think what you're looking for is/was called ObjectDumper. It uses reflection to iterate through and output all of the different properties for an object. I first heard about it while learning LINQ, and most of the examples in the Linq in Action book use it.
It appears that Microsoft didn't include it in the final version of Linq though, but the code is still out in the wild. I did a quick google search for it and here's a link to it:
ObjectDumper Source Code
A: Example code to dump an object and its properties can be found here:
http://www.developer.com/net/csharp/article.php/3713886
A: You can write it by yourself. For example, serialize it into json using Newtonsoft's JSON.net library and write that json to console. Here is an example:
using Newtonsoft.Json;
static class Pretty
{
public static void Print<T> (T x)
{
string json = JsonConvert.SerializeObject(x, Formatting.Indented);
Console.WriteLine(json);
}
}
Usage:
Pretty.Print(whatever);
A: I could certainly see the use in such a thing, but in .Net won't you mostly just get a list of type names (String, Array, etc)? Most of the built-ins don't have "useful" ToString() overloads pre-written, do they?
A: Here is a link with code dumper and a demo project that shows you how to use it. Download it here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: How do I visualise clusters of users? I have an application in which users interact with each-other. I want to visualize these interactions so that I can determine whether clusters of users exist (within which interactions are more frequent).
I've assigned a 2D point to each user (where each coordinate is between 0 and 1). My idea is that two users' points move closer together when they interact, an "attractive force", and I just repeatedly go through my interaction logs over and over again.
Of course, I need a "repulsive force" that will push users apart too, otherwise they will all just collapse into a single point.
First I tried monitoring the lowest and highest of each of the XY coordinates, and normalizing their positions, but this didn't work, a few users with a small number of interactions stayed at the edges, and the rest all collapsed into the middle.
Does anyone know what equations I should use to move the points, both for the "attractive" force between users when they interact, and a "repulsive" force to stop them all collapsing into a single point?
Edit: In response to a question, I should point out that I'm dealing with about 1 million users, and about 10 million interactions between users. If anyone can recommend a tool that could do this for me, I'm all ears :-)
A: In the past, when I've tried this kind of thing, I've used a spring model to pull linked nodes together, something like: dx = -k*(x-l). dx is the change in the position, x is the current position, l is the desired separation, and k is the spring coefficient that you tweak until you get a nice balance between spring strength and stability, it'll be less than 0.1. Having l > 0 ensures that everything doesn't end up in the middle.
In addition to that, a general "repulsive" force between all nodes will spread them out, something like: dx = k / x^2. This will be larger the closer two nodes are, tweak k to get a reasonable effect.
A: I can recommend some possibilities: first, try log-scaling the interactions or running them through a sigmoidal function to squash the range. This will give you a smoother visual distribution of spacing.
Independent of this scaling issue: look at some of the rendering strategies in graphviz, particularly the programs "neato" and "fdp". From the man page:
neato draws undirected graphs using ``spring'' models (see Kamada and
Kawai, Information Processing Letters 31:1, April 1989). Input files
must be formatted in the dot attributed graph language. By default,
the output of neato is the input graph with layout coordinates
appended.
fdp draws undirected graphs using a ``spring'' model. It relies on a
force-directed approach in the spirit of Fruchterman and Reingold (cf.
Software-Practice & Experience 21(11), 1991, pp. 1129-1164).
Finally, consider one of the scaling strategies, an attractive force, and some sort of drag coefficient instead of a repulsive force. Actually moving things closer and then possibly farther later on may just get you cyclic behavior.
Consider a model in which everything will collapse eventually, but slowly. Then just run until some condition is met (a node crosses the center of the layout region or some such).
Drag or momentum can just be encoded as a basic resistance to motion and amount to throttling the movements; it can be applied differentially (things can move slower based on how far they've gone, where they are in space, how many other nodes are close, etc.).
Hope this helps.
A: The spring model is the traditional way to do this: make an attractive force between each node based on the interaction, and a repulsive force between all nodes based on the inverse square of their distance. Then solve, minimizing the energy. You may need some fairly high powered programming to get an efficient solution to this if you have more than a few nodes. Make sure the start positions are random, and run the program several times: a case like this almost always has several local energy minima in it, and you want to make sure you've got a good one.
Also, unless you have only a few nodes, I would do this in 3D. An extra dimension of freedom allows for better solutions, and you should be able to visualize clusters in 3D as well if not better than 2D.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to disable browser postback warning dialog I have an asp.net application that runs exclusively on IE7 (internal web site).
When a user needs to enter data, I pop up a child window with a form. When the form closes, it calls javascript:window.opener.location.reload(true) so that the new data will display on the main page.
The problem is that the browser complains that it must repost the page. Is there any way to turn this feature off?
A: No, but there is a solution. Its generally considered good design to use a 302 redirect immediately after someone posts data to a page. This prevents that popup from ever occuring. Allow me to elaborate.
1) The user fills in a form and submits data via POST.
2) The backend receives the data and acts upon it.
3) Instead of returning the content to the user, the backend issues a 302 redirect as soon as its done processing the page (possibly redirecting the user back to the exact same url, if need be)
4) The page that the user will see is the page you told their browser to redirect to. They will load up the redirected page with a standard GET request. If they try to refresh the page, it will not repost the data. Problem solved.
A: This is a problem with the usual "postback" way of ASP.NET. If you need to reload a page without this warning, this page must come from a GET, not a POST. You could do a Response.Redirect("...") yourself. But this will destroy the use of viewstate.
A: asp.net mvc fixes this issue, not an ie7 only problem but a security feature of most browsers. No fix that I know of except you could just update the content in the main form with js rather than reloading the whole page
A: I do not believe that there is a way to do that. Instead, why not direct the parent window to a page without a reload.
javascript:window.opener.location='your url'
A: It's because the page in window.opener comes from a POST Request
Maybe you can use
javascript:window.opener.location = window.opener.location; to do just a GET request if the data can be fetched without a POST.
A: AFAIK, not via your scripts.
You might try:
window.opener.location = '#';
It should circumvent the browser reposting. And, you can adjust the hash name as needed.
A: If you move from page1 to page2, and want to disable the browser from going back to page 1,then add the following at the top of page1.
<script>
if(window.history.forward(1) != null)
window.history.forward(1);
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the easiest non-memory intensive way to output XML from Python? Basically, something similar to System.Xml.XmlWriter - A streaming XML Writer that doesn't incur much of a memory overhead. So that rules out xml.dom and xml.dom.minidom. Suggestions?
A: I think I have your poison :
http://sourceforge.net/projects/xmlite
Cheers
A: I think you'll find XMLGenerator from xml.sax.saxutils is the closest thing to what you want.
import time
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesNSImpl
LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR']
class xml_logger:
def __init__(self, output, encoding):
"""
Set up a logger object, which takes SAX events and outputs
an XML log file
"""
logger = XMLGenerator(output, encoding)
logger.startDocument()
attrs = AttributesNSImpl({}, {})
logger.startElementNS((None, u'log'), u'log', attrs)
self._logger = logger
self._output = output
self._encoding = encoding
return
def write_entry(self, level, msg):
"""
Write a log entry to the logger
level - the level of the entry
msg - the text of the entry. Must be a Unicode object
"""
#Note: in a real application, I would use ISO 8601 for the date
#asctime used here for simplicity
now = time.asctime(time.localtime())
attr_vals = {
(None, u'date'): now,
(None, u'level'): LOG_LEVELS[level],
}
attr_qnames = {
(None, u'date'): u'date',
(None, u'level'): u'level',
}
attrs = AttributesNSImpl(attr_vals, attr_qnames)
self._logger.startElementNS((None, u'entry'), u'entry', attrs)
self._logger.characters(msg)
self._logger.endElementNS((None, u'entry'), u'entry')
return
def close(self):
"""
Clean up the logger object
"""
self._logger.endElementNS((None, u'log'), u'log')
self._logger.endDocument()
return
if __name__ == "__main__":
#Test it out
import sys
xl = xml_logger(sys.stdout, 'utf-8')
xl.write_entry(2, u"Vanilla log entry")
xl.close()
You'll probably want to look at the rest of the article I got that from at http://www.xml.com/pub/a/2003/03/12/py-xml.html.
A: Some years ago I used MarkupWriter from 4suite
General-purpose utility class for generating XML (may eventually be
expanded to produce more output types)
Sample usage:
from Ft.Xml import MarkupWriter
writer = MarkupWriter(indent=u"yes")
writer.startDocument()
writer.startElement(u'xsa')
writer.startElement(u'vendor')
#Element with simple text (#PCDATA) content
writer.simpleElement(u'name', content=u'Centigrade systems')
#Note writer.text(content) still works
writer.simpleElement(u'email', content=u"info@centigrade.bogus")
writer.endElement(u'vendor')
#Element with an attribute
writer.startElement(u'product', attributes={u'id': u"100\u00B0"})
#Note writer.attribute(name, value, namespace=None) still works
writer.simpleElement(u'name', content=u"100\u00B0 Server")
#XML fragment
writer.xmlFragment('<version>1.0</version><last-release>20030401</last-release>')
#Empty element
writer.simpleElement(u'changes')
writer.endElement(u'product')
writer.endElement(u'xsa')
writer.endDocument()
Note on the difference between 4Suite writers and printers
Writer - module that exposes a broad public API for building output
bit by bit
Printer - module that simply takes a DOM and creates output from it
as a whole, within one API invokation
Recently i hear a lot about how lxml is great, but I don't have first-hand experience, and I had some fun working with gnosis.
A: xml.etree.cElementTree, included in the default distribution of CPython since 2.5. Lightning fast for both reading and writing XML.
A: Second vote for ElementTree (cElementTree is a C implementation that is a little faster, like cPickle vs pickle). There's some short example code here that you can look at to give you an idea of how it works: http://effbot.org/zone/element-index.htm
(this is Fredrik Lundh, who wrote the module in the first place. It's so good it got drafted into the standard library with 2.5 :-) )
A: I've always had good results with lxml. It's a pain to install, as it's mostly a wrapper around libxml2, but lxml.etree tree objects have a .write() method that takes a file-like object to stream to.
from lxml.etree import XML
tree = XML('<root><a><b/></a></root>')
tree.write(your_file_object)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Windows Form with Resizing Frame and no Title Bar? How can I hide the title bar from a Windows Form but still have a Resizing Frame?
A: Set the ControlBox property of the form to False, and the Text property to empty string. The form will open with no perceivable (to the user) title bar, but they will be able to resize the form.
A: Setting FormBorderStyle = None will remove the title bar (at both design and
run time) - and also remove your ability to resize the form.
If you need a border you can set:
ControlBox = false
Text = ""
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: UML aggregation when interfaces are used How do I represent an aggregation relation between two classes in UML, such that each class has a link to the other class's interface, not the implementing class?
E.g. I have a class Foo that implements iFoo, and Bar that implements iBar. Foo should have a member variable of type iBar, and Bar should have a member variable of type iFoo.
If I create an aggregation between the two implementing classes, then the member will be of the type of the implementing class, not the superclass. And aggregations between interfaces are invalid in UML (and don't make much sense).
A: Can you not have Foo (implementation) aggregate iBar (interface)? That seems to me the proper way to describe this relationship.
So something like this:
----------------- -----------------
| <<interface>> | | <<interface>> |
| iFoo |<> <>| iBar |
----------------- \/ -----------------
^ /\ ^
| / \ |
-----------------/ \-----------------
| Foo | | Bar |
----------------- -----------------
A: Interfaces are not instantiable, so Bar cannot have an attribute of type iFoo, and Foo cannot have an attribute of type iBar.
You say you don't want an Association between Bar and Foo. So you could create a new Class (FooEx) and have that Class implement iFoo. Then Bar can have an Association to FooEx instead of Foo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I import eclipse JDT classes in a project I want to do the following imports in a class.
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.text.edits.TextEdit;
How can I import the JDT within Eclipse?
Cheers.
A: Unless I'm misunderstanding you, you just need to include the JDT JAR files on your classpath; they're all available in your Eclipse plugins directory. So for your project, right-click on the project's name in the Package Explorer, go to the Build Path... submenu, and choose Configure Build Path. Then in the Libraries tab, use the "Add External JARs" button to add each of the relevant JAR files from the Eclipse plugins directory.
A: If your'e writing plugins for Eclipse, you shouldn't really be trying to instantiate the internal packages. According to this API Rules of Engagement
Stick to officially documented APIs. Only reference packages that are documented in the published API Javadoc for the component. Never reference a package belonging to another component that has "internal" in its name---these are never API. Never reference a package for which there is no published API Javadoc---these are not API either.
For the others, add the package name to the Import-Package entry in your manifest.
There are extension points into the JDT, but if what you want to do falls outside of these, then I'm afraid you're out of luck.
If you're just looking to use a compiler in your code, without relying on the JDK (i.e. on a JRE), then I would consider shipping with a more standalone Java based Java compiler like Janino.
A: I think I found an easier way to do this:
*
*right-click on your project in the Package Explorer;
*choose "Build Path...";
*choose "Configure Build Path";
*choose the Libraries tab;
*click the "Add Variable..." button;
*in the list box, choose the "ECLIPSE_HOME" entry, and then click the "Extend" button;
*in the list box, open up the "plugins" folder entry, scroll way down, and shift-click all the org.eclipse.jdt.* JAR files that are in the file listing beneath the folders;
*click OK until you're all the way back out.
That should do it.
A: If you need these classes, you are probably in a plug-in project already. You should be able to import these classes by applying the quick fix "Fix project setup..." (Ctrl+1) on the line where Eclipse is complaining about the imports. That will add the required plug-ins to your MANIFEST.MF file in the META-INF directory (org.eclipse.jdt.core and org.eclipse.jface.text in your case). You can also add them manually in your MANIFEST.MF file. If your project is no plug-in project (and you have no MANIFEST.MF file) you can convert it by right-click on the project -> PDE Tools -> Convert Projects to Plug-in Project first. If you add dependencies to plug-in projects in the normal way ("configure build path") the classloading won't work properly at runtime (though it will compile).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Get Accordian Selected Index in ASP.Net C# Im working on an ASP.Net app with c#. I am stuck on a problem with an accoridian.
My accordian correctly displays data from a datasource which in this case in some text and then a list of images. On each accordians content there are the images to be displayed and then a button to add another image.
This button links to another page that contains the add form. From here I am able to add an image and it forwards me back to the page displaying the accoridan with one new image in the correct section.
Now The problem is that I want to re-open the section that was previously open.
I have tried a couple different ways but all of them have not worked. Any Ideas?
A: If you are redirecting to another page, you are going to have to pass the currently opened section to it via a querystring and then when the new page sends you back, it'll send you back the same value so you know which one to open.
Another quick way would be to pop it into a session and then read from that session. But I would recommend the query string route, it has less overhead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Most common C# bitwise operations on enums For the life of me, I can't remember how to set, delete, toggle or test a bit in a bitfield. Either I'm unsure or I mix them up because I rarely need these. So a "bit-cheat-sheet" would be nice to have.
For example:
flags = flags | FlagsEnum.Bit4; // Set bit 4.
or
if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way?
Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum?
A: The idiom is to use the bitwise or-equal operator to set bits:
flags |= 0x04;
To clear a bit, the idiom is to use bitwise and with negation:
flags &= ~0x04;
Sometimes you have an offset that identifies your bit, and then the idiom is to use these combined with left-shift:
flags |= 1 << offset;
flags &= ~(1 << offset);
A: C++ syntax, assuming bit 0 is LSB, assuming flags is unsigned long:
Check if Set:
flags & (1UL << (bit to test# - 1))
Check if not set:
invert test !(flag & (...))
Set:
flag |= (1UL << (bit to set# - 1))
Clear:
flag &= ~(1UL << (bit to clear# - 1))
Toggle:
flag ^= (1UL << (bit to set# - 1))
A: For the best performance and zero garbage, use this:
using System;
using T = MyNamespace.MyFlags;
namespace MyNamespace
{
[Flags]
public enum MyFlags
{
None = 0,
Flag1 = 1,
Flag2 = 2
}
static class MyFlagsEx
{
public static bool Has(this T type, T value)
{
return (type & value) == value;
}
public static bool Is(this T type, T value)
{
return type == value;
}
public static T Add(this T type, T value)
{
return type | value;
}
public static T Remove(this T type, T value)
{
return type & ~value;
}
}
}
A: Bitwise (Flags) enum guide
Old, but wanted to take a stab at a cheat sheet, even if for my own reference:
Operation
Syntax
Example
On
|=
e |= E.A
Off
&= + ~
e &= ~E.A
Toggle
^=
e ^= E.A
Test (.NET API)
.HasFlag
e.HasFlag(E.A)
Test (bitwise)
(see example)
(e & E.A) == E.A
Examples
[Flags]
enum E {
A = 0b1,
B = 0b10,
C = 0b100
}
E e = E.A; // Assign (e = A)
e |= E.B | E.C; // Add (e = A, B, C)
e &= ~E.A & ~E.B; // Remove (e = C) -- alt syntax: &= ~(E.A | E.B)
e ^= E.A | E.C; // Toggle (e = A)
e.HasFlag(E.A); // Test (returns true)
// Testing multiple flags using bit operations:
bool hasAandB = ( e & (E.A | E.B) ) == (E.A | E.B);
Bonus: defining a Flags enum
Typically, we use integers like so:
[Flags]
enum E {
A = 1,
B = 2,
C = 4,
// etc.
But as we approach larger numbers, it's not as easy to calculate the next value:
// ...
W = 4194304,
X = 8388608,
// ..
There are a couple of alternatives, however: binary and hexadecimal literals.
For Binary, just append a 0 at the end of the previous value:
[Flags]
enum E {
A = 0b1,
B = 0b10,
C = 0b100,
// ...
W = 0b100_0000_0000_0000_0000_0000,
X = 0b1000_0000_0000_0000_0000_0000,
Hexadecimal also has a handy pattern and might look a bit less ugly: cycle through 1, 2, 4, 8, adding a zero after each complete iteration.
[Flags]
enum E {
A = 0x1,
B = 0x2,
C = 0x4,
D = 0x8,
E = 0x10, // 16
F = 0x20, // 32, etc.
// ...
W = 0x400000,
X = 0x800000,
A: I did some more work on these extensions - You can find the code here
I wrote some extension methods that extend System.Enum that I use often... I'm not claiming that they are bulletproof, but they have helped... Comments removed...
namespace Enum.Extensions {
public static class EnumerationExtensions {
public static bool Has<T>(this System.Enum type, T value) {
try {
return (((int)(object)type & (int)(object)value) == (int)(object)value);
}
catch {
return false;
}
}
public static bool Is<T>(this System.Enum type, T value) {
try {
return (int)(object)type == (int)(object)value;
}
catch {
return false;
}
}
public static T Add<T>(this System.Enum type, T value) {
try {
return (T)(object)(((int)(object)type | (int)(object)value));
}
catch(Exception ex) {
throw new ArgumentException(
string.Format(
"Could not append value from enumerated type '{0}'.",
typeof(T).Name
), ex);
}
}
public static T Remove<T>(this System.Enum type, T value) {
try {
return (T)(object)(((int)(object)type & ~(int)(object)value));
}
catch (Exception ex) {
throw new ArgumentException(
string.Format(
"Could not remove value from enumerated type '{0}'.",
typeof(T).Name
), ex);
}
}
}
}
Then they are used like the following
SomeType value = SomeType.Grapes;
bool isGrapes = value.Is(SomeType.Grapes); //true
bool hasGrapes = value.Has(SomeType.Grapes); //true
value = value.Add(SomeType.Oranges);
value = value.Add(SomeType.Apples);
value = value.Remove(SomeType.Grapes);
bool hasOranges = value.Has(SomeType.Oranges); //true
bool isApples = value.Is(SomeType.Apples); //false
bool hasGrapes = value.Has(SomeType.Grapes); //false
A: @Drew
Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:
[Flags]
public enum TestFlags
{
One = 1,
Two = 2,
Three = 4,
Four = 8,
Five = 16,
Six = 32,
Seven = 64,
Eight = 128,
Nine = 256,
Ten = 512
}
class Program
{
static void Main(string[] args)
{
TestFlags f = TestFlags.Five; /* or any other enum */
bool result = false;
Stopwatch s = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
result |= f.HasFlag(TestFlags.Three);
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*
s.Restart();
for (int i = 0; i < 10000000; i++)
{
result |= (f & TestFlags.Three) != 0;
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*
Console.ReadLine();
}
}
Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.
A: To test a bit you would do the following:
(assuming flags is a 32 bit number)
Test Bit:
if((flags & 0x08) == 0x08) (If bit 4 is set then its true)
Toggle Back (1 - 0 or 0 - 1): flags = flags ^ 0x08;
Reset Bit 4 to Zero: flags = flags & 0xFFFFFF7F;
A: This was inspired by using Sets as indexers in Delphi, way back when:
/// Example of using a Boolean indexed property
/// to manipulate a [Flags] enum:
public class BindingFlagsIndexer
{
BindingFlags flags = BindingFlags.Default;
public BindingFlagsIndexer()
{
}
public BindingFlagsIndexer( BindingFlags value )
{
this.flags = value;
}
public bool this[BindingFlags index]
{
get
{
return (this.flags & index) == index;
}
set( bool value )
{
if( value )
this.flags |= index;
else
this.flags &= ~index;
}
}
public BindingFlags Value
{
get
{
return flags;
}
set( BindingFlags value )
{
this.flags = value;
}
}
public static implicit operator BindingFlags( BindingFlagsIndexer src )
{
return src != null ? src.Value : BindingFlags.Default;
}
public static implicit operator BindingFlagsIndexer( BindingFlags src )
{
return new BindingFlagsIndexer( src );
}
}
public static class Class1
{
public static void Example()
{
BindingFlagsIndexer myFlags = new BindingFlagsIndexer();
// Sets the flag(s) passed as the indexer:
myFlags[BindingFlags.ExactBinding] = true;
// Indexer can specify multiple flags at once:
myFlags[BindingFlags.Instance | BindingFlags.Static] = true;
// Get boolean indicating if specified flag(s) are set:
bool flatten = myFlags[BindingFlags.FlattenHierarchy];
// use | to test if multiple flags are set:
bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];
}
}
A: .NET's built-in flag enum operations are unfortunately quite limited. Most of the time users are left with figuring out the bitwise operation logic.
In .NET 4, the method HasFlag was added to Enum which helps simplify user's code but unfortunately there are many problems with it.
*
*HasFlag is not type-safe as it accepts any type of enum value argument, not just the given enum type.
*HasFlag is ambiguous as to whether it checks if the value has all or any of the flags provided by the enum value argument. It's all by the way.
*HasFlag is rather slow as it requires boxing which causes allocations and thus more garbage collections.
Due in part to .NET's limited support for flag enums I wrote the OSS library Enums.NET which addresses each of these issues and makes dealing with flag enums much easier.
Below are some of the operations it provides along with their equivalent implementations using just the .NET framework.
Combine Flags
.NET flags | otherFlags
Enums.NET flags.CombineFlags(otherFlags)
Remove Flags
.NET flags & ~otherFlags
Enums.NET flags.RemoveFlags(otherFlags)
Common Flags
.NET flags & otherFlags
Enums.NET flags.CommonFlags(otherFlags)
Toggle Flags
.NET flags ^ otherFlags
Enums.NET flags.ToggleFlags(otherFlags)
Has All Flags
.NET (flags & otherFlags) == otherFlags or flags.HasFlag(otherFlags)
Enums.NET flags.HasAllFlags(otherFlags)
Has Any Flags
.NET (flags & otherFlags) != 0
Enums.NET flags.HasAnyFlags(otherFlags)
Get Flags
.NET
Enumerable.Range(0, 64)
.Where(bit => ((flags.GetTypeCode() == TypeCode.UInt64 ? (long)(ulong)flags : Convert.ToInt64(flags)) & (1L << bit)) != 0)
.Select(bit => Enum.ToObject(flags.GetType(), 1L << bit))`
Enums.NET flags.GetFlags()
I'm trying to get these improvements incorporated into .NET Core and maybe eventually the full .NET Framework. You can check out my proposal here.
A: In .NET 4 you can now write:
flags.HasFlag(FlagsEnum.Bit4)
A: C++ operations are: & | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and <<, which are bitshift operations.
So, to test for a bit being set in a flag, you would use:
if (flags & 8) //tests bit 4 has been set
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "216"
}
|
Q: Close mootools Rokbox through Javascript I am using the mootools based Rokbox plugin, on one of my sites, and I can't figure out how to close it with javascript.
I triggered the click event on the close button, but that did not work.
I found the code in the rokbox source that is used to add the click listener
this.closeButton.addEvent('click',function(e){new Event(e).stop();self.swtch=false;self.close(e)});
but since it is minified i cannot find what "this" refers to
A: The this likely refers to the rokbox instance; I don't think you need to worry about it, you're interested in the code that runs on the click event. The salient part looks to be the following:
self.swtch=false;
self.close(e);
self most likely refers to the rokbox instance, again, so assuming you instantiate it with something like
var rokbox = new RokBox(...);
you should be able to just call
rokbox.close();
and have it close. I haven't looked at rokbox source, so no guarantees, and not quite sure what the swtch=false does, so you probably will need to experiment a bit.
A: For the current rokbox and mootools 1.12, the command is
window.parent.rokbox.close(null)
it took forever to come up with this. By the way, this is to close the rokbox from the page that's loaded in the rokbox, by clicking a regular button instead of the 'x' for instance. Also, to add to what Aeon wrote, the rokbox is automatically created so it's unnecessary to instantiate it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EEFileLoadException when using C# classes in C++(win32 app) For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper.
I've done it on other projects, but on this one, I am getting an EEFileLoadException. Any help would be appreciated!
Managed C++ wrapper code (this is in a DLL):
extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
//this class references c# in the constructor
return new CMyWrapper( );
}
extern "C" __declspec(dllexport) void DeleteMyObject(IMyObject* pConfigFile)
{
delete pConfigFile;
}
extern "C" __declspec(dllexport) void TestFunction(void)
{
::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK);
}
Test Code (this is an EXE):
typedef void* (*CreateObjectPtr)();
typedef void (*TestFunctionPtr)();
int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[])
{
HMODULE hModule = ::LoadLibrary(_T("MyWrapper"));
_ASSERT(hModule != NULL);
PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction");
_ASSERT(pFunc1 != NULL);
TestFunctionPtr pTest = (TestFunctionPtr)pFunc1;
PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject");
_ASSERT(pFunc2 != NULL);
CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2;
(*pTest)(); //this successfully pops up a message box
(*pCreateObjectFunc)(); //this tosses an EEFileLoadException
return 0;
}
For what it's worth, the Event Log reports the following:
.NET Runtime version 2.0.50727.143 -
Fatal Execution Engine Error (79F97075) (80131506)
Unfortunately, Microsoft has no information on that error.
A: For you native application consuming the mixed mode dll (Your EXE), change the **"Debugger Type" to "Mixed" mode. (Go to Project Properties -> Configuration Properties -> Debugging)
There are some other points (which might not be relevant to you) but in my experience they could cause issues.
- On windows 8 (with tighter security) please try launching your VS as admin.
- Make sure that for x86 configuration you are using x86 binaries.
- Watch for StrongName verification, if your C# assemblies which you are consuming in Managed C++ as signed, please consider signing the mixed mode dll too.
Hope this would help.
A: The problem was where the DLLs were located.
*
*c:\dlls\managed.dll
*c:\dlls\wrapper.dll
*c:\exe\my.exe
I confirmed this by copying managed.dll into c:\exe and it worked without issue. Apparently, the CLR won't look for managed DLLs in the path of the unmanaged DLL and will only look for it where the executable is. (or in the GAC).
For reasons not worth going into, this is the structure I need, which meant that I needed to give the CLR a hand in located the managed dll. See code below:
AssemblyResolver.h:
/// <summary>
/// Summary for AssemblyResolver
/// </summary>
public ref class AssemblyResolver
{
public:
static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
{
Console::WriteLine( "Resolving..." );
Assembly^ thisAssembly = Assembly::GetExecutingAssembly();
String^ thisPath = thisAssembly->Location;
String^ directory = Path::GetDirectoryName(thisPath);
String^ pathToManagedAssembly = Path::Combine(directory, "managed.dll");
Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);
return newAssembly;
}
};
Wrapper.cpp:
#include "AssemblyResolver.h"
extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void)
{
try
{
AppDomain^ currentDomain = AppDomain::CurrentDomain;
currentDomain->AssemblyResolve += gcnew ResolveEventHandler( AssemblyResolver::MyResolveEventHandler );
return new CMyWrapper( );
}
catch(System::Exception^ e)
{
System::Console::WriteLine(e->Message);
return NULL;
}
}
A: I was getting the C++ EEFileLoadException thrown a lot by iisexpress.exe during debugging of an ASP.NET MVC application. The call stack and C++ exception itself were not terribly helpful in helping me pin down the problem.
After looking directly at the pointer address given in the C++ exception I eventually discovered a library string which was pointing to an old version no longer in use. This in turn was due to an out-of-date entry in my web.config file:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly> </assemblyBinding> </runtime>
I had upgraded various Microsoft.Own security libraries via NuGet to version 4.0.30319 but this line in the config was instructing the server to redirect calls to version 3.0.1.0, which was now no longer part of my project. Updating the config resovled my problems.
A: The first issue is to make sure the Debugger type is set to mixed. Then you get useful exceptions.
A: In case anyone else stumbles upon this question, and you are using a dynamic assembly name: make sure you are stripping the assembly name, it may contain version, culture and other content that you may not use.
I.e., your MyResolveEventHandler should be in the form of:
static Assembly^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
{
Console::WriteLine( "Resolving..." );
String^ assemblyName = args->Name;
// Strip irrelevant information, such as assembly, version etc.
// Example: "Acme.Foobar, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
if( assemblyName->Contains(",") )
{
assemblyName = assemblyName->Substring(0, assemblyName->IndexOf(","));
}
Assembly^ thisAssembly = Assembly::GetExecutingAssembly();
String^ thisPath = thisAssembly->Location;
String^ directory = Path::GetDirectoryName(thisPath);
String^ pathToManagedAssembly = Path::Combine(directory, assemblyName );
Assembly^ newAssembly = Assembly::LoadFile(pathToManagedAssembly);
return newAssembly;
}
A: When you run in debugger C++ native project which use C++ managed dll you may get this exception. When VS2010 catch it and your application after some chain exceptions will be aborted you may try in exception filter (Menu|Debug|Excpetion) disable all C++ exceptions. You will still see this exception in output but your application won't abort
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: Why is my programmatically created user missing from the Welcome screen? I have a program that creates a Windows user account using the NetUserAdd() API which is suggested by Microsoft. The user is created successfully, and I can log in as that user.
However, on Windows XP, the newly-created user is missing from the Welcome screen. If I disable the Welcome screen, I can log in as the new user by typing the user name in direcly.
What property of the account I create causes it to be omitted from the Welcome screen?
A: One thing you could do is add the username as a value to the registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList
Use the username (As a REG_DWORD) and a value of 1 to show the user and 0 to hide.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does the ActiveRecord pattern differ from the Domain Object or Data Mapper pattern? I was looking at DataMapper, which appeared at first glance to use the ActiveRecord ORM pattern. Other people said that it uses the DataMapper and/or the Domain Object pattern.
What is the difference between those patterns?
A: Active record is very heavy, data mapper and domain object are separating those concerns out so you have a more defined set of code doing various aspects for you "domain" or "entity" objects.
I personally prefer, not that you asked, going with the separation into domain object, data mapper, probably use an assembly pattern and even a data transfer pattern to assure clear separation of what happens to data between the database an the upper tiers of an application.
...elegant and simple separations always help.
A: The main difference between the two patterns is this:
*
*In the ActiveRecord you have one domain object that both knows all the business logic and how to save/update itself in the database, user.getLinkToProfile() and User::find(1), User::save(user)
*In the DataMapper pattern you have one domain object that holds all the business logic, for exmaple user.getLinkToProfile() (or something similar) but knows nothing about the database in question, in addition to this you have a mapper-object that is responsible for saving, updating, selecting, etc. user objects from the database which would have UserMapper::find(1), UserMapper.save(user)
DataMapper is potentially more complex then ActiveRecord but it's a lot easier to develop your domain model and database asynchronous then with ActiveRecord.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: MySQL Trigger & Stored Procedure Replication Ok,I'm running a setup with a single master and a number of slaves. All writes go through the master and are replicated down to the slaves which are used strictly for reads.
Now I have a stored procedure (not function) which is called by a trigger on an insert. According to the MySQL docs, for replication triggers log the call to the trigger while stored procedures actually log the result of the stored procedure.
So my question is, when my trigger gets fired, will it replicate both the trigger and the results of the procedure that the trigger calls (resulting in the procedure effectively being run twice)? Or will it simply replicate the trigger have the slaves re-run the stored procedure on their own?
Thanks
A: In MySQL 5.0 (and MySQL 5.1 with statement based binary logging), only the calling query is logged, so in your case, the INSERT would be logged.
On the slave, the INSERT will be executed and then the trigger will be re-run on the slave. So the trigger needs to exist on the slave, and assuming it does, then it will be executed in exactly the same way as the master.
In MySQL 5.1, there is row-based binary logging, which will log only the rows being changed, so the trigger would not be re-fired on the slave, but all rows that changed would still be propagated.
A: In addition to Harrison's excellent answer:
*
*Assuming the databases are in sync (schema, data, same version) to start with, it should just work
*If it doesn't, then it may be that you're using something non deterministic in your queries or trigger. Fix that.
*Regardless of how you use replication, you need to have monitoring to check that the slaves are always in sync. Without any monitoring, they will become out of sync (subtly) and you won't notice. MySQL has no automatic built-in feature for checking this or fixing it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Are there many users of PRADO out there? After making some comments, I've been inspired to get some feedback on the PHP MVC framework PRADO. I've been using it for over a year now and I've very much enjoyed working with it, however I notice that throughout Stack Overflow, it doesn't seem to rate a mention when symfony or CakePHP are being talked about as potential candidates for a framework.
Is anybody using Stack Overflow using PRADO now? If so, how do you find it? Has anyone used it in the past but left it behind, and if so, why? Can anybody appraise its strengths and weaknesses against Cake or symfony?
A: I've played with PRADO some, but I felt that if I'm going to be forced into post-back-hell i might as well do it on the platform that it was built for in the beginning - .NET, other then that PRADO is relatively "untalked" about in the blogs, etc. I don't know why really though.
A: I found that the active controls were pretty slick. It makes doing all kinds of ajaxy things really easy. Unfortunately, when you need to do something slightly different, it's pretty obfuscated and difficult to figure out what's up. I felt like I often got something simple and great working, and then one small additional requirement would require me to tear the whole thing apart and come up with a much more complicated solution.
A: The first time I looked into PRADO, I spent about 10 days using it and kept saying to myself: "This framework is amazing!". A couple of months later, I started working on a big project where the customer had chosen to use PRADO... And Hell began... As long as we kept using PRADO's base components, everything was perfect and development was fast. But as soon as the customer wanted an out-of-the-box thing, we literaly spent 2 to 3 times the amount of time we would have done it with another framework. And I'm not talking about big customizations. The PRADO framework forces the application to have a particular structure and workflow. If that logic is not working for you, then check out another framework.
A: Prado is dead now. Also the documentation is poor.
A: I think Prado never really caught on because it's an event-driven framework, which is a bit hard to wrap your head around. Especially for the many PHP developers coming from a more procedural background.
A: PRADO would have been my choice for a framework if I hadn't run across QCodo. I like the event-driven approach -- QCodo just suits me more.
A: We are working with PRADO framework since 4 years.
We are developing huge (+4000 programs) web apps for e-Goverment with Oraracle and MySql databases containing more than 60 millon records. As infrastructure for development we use SVN+TRAC+ our own tools for project control AND phpEdit w/tortoiseSVN as client tools.
Currently we are thinking on changing to Yii.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Infragistics WebTextEdit - Setting value in Javascript function I'm currently using the Infragistics component set for .Net 2.0, Visual Studio 2005 and C#. I have the following chunk of javascript code (text and other variables are declared elsewhere):
***alert(box[select].value);
text.value(box[select].value);
alert(text.value);***
'text' is an Infragistics webTextEdit, while box is just a standard listbox. The two alerts seem to be working fine. Before I set the value, the listBox's selected value might be 'hello', and the alert box which pops up after I've assigned this value to 'text' is also 'hello'.
However, the value shown in the box on my form never appears to get updated. Anybody have some suggestions as to where I'm going wrong, gotchas in how Infragistics handles this kind of thing or anything else? I'm aware there may not be enough info here to diagnose the problem.
A: The value property is only available server-side. Using it client-side won't do anything. Setting it would have to be done server-side, or you'll need to craft fun javascript to address the text of the element that the control is actually rendered as in the browser.
http://help.infragistics.com/Help/NetAdvantage/NET/2007.3/CLR2.0/html/Infragistics2.WebUI.WebDataInput.v7.3~Infragistics.WebUI.WebDataInput.WebTextEdit~Value.html
A: Unless I misunderstand the question, if text is an instance of the Infragistics WebTextEdit, you should just be able to do:
text.setValue(box[select].value)
Or if text is the underlying input control, but 'id' is the ID of it,
var edit = igedit_getById(id)
edit.setValue(box[select].value)
See the WebTextEdit CSOM for more.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I maintain consistent DB schema accross 18 databases (sql server)? We have 18 databases that should have identical schemas, but don't. In certain scenarios, a table was added to one, but not the rest. Or, certain stored procedures were required in a handful of databases, but not the others. Or, our DBA forgot to run a script to add views on all of the databases.
What is the best way to keep database schemas in sync?
A: SQL Compare by Red Gate is a great tool for this.
A: For legacy fixes/cleanup, there are tools, like SQLCompare, that can generate scripts to sync databases.
For .NET shops running SQL Server, there is also the Visual Studio Database Edition, which can create change scripts for schema changes that can be checked into source control, and automatically built using your CI/build process.
A: SQLCompare is the best tool that I have used for finding differences between databases and getting them synced.
To keep the databases synced up, you need to have several things in place:
1) You need policies about who can make changes to production. Generally this should only be the DBA (DBA team for larger orgs) and 1 or 2 backaps. The backups should only make changes when the DBA is out, or in an emergency. The backups should NOT be deploying on a regular basis. Set Database rights according to this policy.
2) A process and tools to manage deployment requests. Ideally you will have a development environment, a test environment, and a production environment. Developers should do initial development in the dev environment, and have changes pushed to test and production as appropriate. You will need some way of letting the DBA know when to push changes. I would NOT recommend a process where you holler to the next cube. Large orgs may have a change control committee and changes only get made once a month. Smaller companies may just have the developer request testing, and after testing is passed a request for deployment to production. One smaller company I worked for used Problem Tracker for these requests.
Use whatever works in your situation and budget, just have a process, and have tools that work for that process.
3) You said that sometimes objects only need to go to a handful of databases. With only 18 databases, probably on one server, I would recommend making each Databse match objects exactly. Only 5 DBs need usp_DoSomething? So what? Put it in every databse. This will be much easier to manage. We did it this way on a 6 server system with around 250-300 DBs. There were exceptions, but they were grouped. Databases on server C got this extra set of objects. Databases on Server L got this other set.
4) You said that sometimes the DBA forgets to deploy change scripts to all the DBs. This tells me that s/he needs tools for deploying changes. S/He is probably taking a SQL script, opening it in in Query Analyzer or Manegement Studio (or whatever you use) and manually going to each database and executing the SQL. This is not a good long term (or short term) solution. Red Gate (makers of SQLCompare above) have many great tools. MultiScript looks like it may work for deployment purposes. I worked with a DBA that wrote is own tool in SQL Server 2000 using O-SQl. It would take an SQL file and execute it on each database on the server. He had to execute it on each server, but it beat executing on each DB. I also helped write a VB.net tool that would do the same thing, except it would also go through a list of server, so it only had to be executed once.
5) Source Control. My current team doesn't use source control, and I don't have enough time to tell you how many problems this causes. If you don't have some kind of source control system, get one.
A: I haven't got enough reputation to comment on the above answer but the pro version of SQL Compare has a scriptable API. Given that you have to replicate stuff to all of these databases you could use this to make an automated job to either generate the change scripts or to validate that the databases are all in sync. It's also not much more expensive than the standard version.
A: Aside from using database comparison tools, with 18 databases you should have a DBA, so enforce a policy that only the DBA can change tables at the database level by restricting access to CREATE and ALTER to the DBA only. On both your test and live databases. The dev database shouldn't have this, of course! Make the developers who have been creating or altering the schemas willy-nilly go via the DBA.
A: Create a single source-controlled DDL/SQL script for each release and only use it to update the databases. The diff tools can be useful but mainly for checking that you haven't made a mistake and getting out of trouble when the policies fail. Combine the DDL, SQL, and stored procedure scripts into a single script so that it's not easy to "forget" to run one of the scripts.
A: We have got a tool called DB Schema Difftective that can compare and sync database schemas. With our other tool, DB MultiRun you can easily deploy generated (sync) scripts to multiple db servers (project based).
A: I realize this post is old, but TurnKey is correct. If you are a developer working in a team environment, the best way to maintain a database schema for a large application, is to make updates to a Master Schema in what ever source safe you use. Simply write your own Scripting class and your Database will be perfect every time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WinForm - draw resizing frame using a single-pixel border In a Windows Form with a Resizing Frame, the frame border draws with a raised 3-D look. I'd like it to draw with a flat single pixel border in a color of my choosing.
Is this possible without having to owner draw the whole form?
A: You could try something like this:
Point lastPoint = Point.Empty;
Panel leftResizer = new Panel();
leftResizer.Cursor = System.Windows.Forms.Cursors.SizeWE;
leftResizer.Dock = System.Windows.Forms.DockStyle.Left;
leftResizer.Size = new System.Drawing.Size(1, 100);
leftResizer.MouseDown += delegate(object sender, MouseEventArgs e) {
lastPoint = leftResizer.PointToScreen(e.Location);
leftResizer.Capture = true;
}
leftResizer.MouseMove += delegate(object sender, MouseEventArgs e) {
if (lastPoint != Point.Empty) {
Point newPoint = leftResizer.PointToScreen(e.Location);
Location = new Point(Location.X + (newPoint.X - lastPoint.X), Location.Y);
Width = Math.Max(MinimumSize.Width, Width - (newPoint.X - lastPoint.X));
lastPoint = newPoint;
}
}
leftResizer.MouseUp += delegate (object sender, MouseEventArgs e) {
lastPoint = Point.Empty;
leftResizer.Capture = false;
}
form.BorderStyle = BorderStyle.None;
form.Add(leftResizer);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Do you chat online for work purposes? I've worked with folks who are chatting online with their peers, constantly batting around ideas. I've also worked with folks who adamantly refuse and think it's a waste of time.
Are online live chatting forums of particular use to you? Why or why not?
Internal to your company, or external and world-wide?
Does your employer encourage or discourage their use?
Update: I see some people are voting this question down, yet so far all the answers have been positive, if with some reservations. If someone has a strong negative opinion (I hate online chatting and think it should be banned etc.) I'd really like to hear why.
A: If you have telecommuters, not chatting online will be the death of you.
Without chat, there is no interaction.
Without interaction, there is no problem solving.
Without problem solving, the code will suck.
The chatting part does waste a lot of time and I often wish I could just pull them out and just WriteSomeCode, but yeah, trade off scenario.
There's an additional benefit to using online converstations, in that it doesn't /have/ to be an interruption. If your working on something you can ignore them till you're done and they just have to deal with it. In real life you have a talking face to try get rid of. ( And the cool thing here is you can ignore them and they still get heard, have your cake and eat it too! )
A: I've used IM at the last three places I have worked. Currently the building that I am in is so large that it takes a couple of minutes just to walk to my managers office. Then there are the days that we work from home (1-2 days a week). Email for some purposes just doesn't cut it and the phone can be too disruptive and all encompassing for some tasks.
When I was doing consulting work I would give my IM contact information to my clients. About 25% of them would use it to contact me and I am still in contact with them to this day which opens up the possibility for future work! The clients that used IM felt that they had a better connection with me because they could see when I was online and available to talk.
I'm still in contact with old work colleagues through IM and this allows me quick access to their knowledge base as well.
My suggestions for using IM in the workplace are:
*
*Use a client that supports multiple
protocols (MSN, Yahoo, AIM, Jaber,
etc)
*Setup and use personal accounts for
each of the networks you are on
(i.e. don't use accounts tied
directly to your work)
*Make sure your IM client records a
history of all of your conversations
*Always be available but minimize
personal conversations
*Provide your IM information freely
to friends, clients, and colleagues
*Add appropriate groups (i.e.
friends, family, work) and filters
to reduce undesired interruptions
while still being available if
needed
*Don't feel that you have to
respond to every chat request. Let
it set until you are ready to deal
with it
One other trick I use is to use text to speech software so that when a chat message comes in it is read allowed. When I am at home (or preoccupied away from the computer in the office) the message is automatically read allowed (I liken it to a ringing phone call) in order to get my attention. But, I don't have to stop what I am doing in order to know what the message is.
A: I used to. I found it a great resource to chat with people I used to work with. In our business I find that we tend to network alot and using that collective knowledge is awesome. Of course my company turned that off so they lose.
I know that a certain large Bank hasd an internal AIM setup so that they can IM each other. That was refreshing and dang useful. They also allowed some external access. Talk about getting the value of IM!
A: Yes, absolutly, I work with most of my employees, and employers via MSN/Yahoo/Skype/.../ it makes the work easier, because I can hire the better people without having to pay them to move to me.
A: When I need to collaborate with someone in another office, it's great ... when I'm deep in thought, I have to turn it off (just like e-mail).
A: It depends on the group dynamics and personal preferences. Personally, I have enjoyed my work groups that use chat to feed on each other's ideas and troubleshoot without as much walking around. If you are geography dispersed, its almost a necessity.
A: I find online chatting invaluable in many cases, but not normally instant messaging. Since I use many open source technologies at work, I tend to join the respective IRC channels, both to ask questions there, and sometimes to help others if I know the answer offhand.
A: It may depend on the work environment. As a self employed consultant, I'm always in chat - it's my primary communication to the world, along with emails for more official type communications.
Being able to converse with others creates synergy, but it also can cause distractions. A good manager can tell the difference.
A: At my last workplace, we used IM extensively for collaboration. Not so much at my present workplace. Infact, i have not once had to do that here in 6 months. But i do look around on the net for answers and sometimes i have posted queries on forums too. IM is a nice tool to have, but its also a time sink. Also, dont underestimate the lost focus. Its particularly hard to concentrate on getting that algo implemented right if someones constantly pinging you about how to establish a connection to an oracle database.
A: I work at home 2 to 3 days a week. I mainly use MSN to stay in touch with my coworkers. It's pretty useful to ask short questions quickly. If we find ourselves typing whole conversations we often agree to continue the conversation by phone.
A: I use IM to communicate with colleagues in other offices when it replaces a face-to-face chat. I turn off notifications in all my comms apps at work though, because they distract me otherwise.
A: I telecommute from California to Colorado and never have used chat. We do have daily SCRUM meetings and constant email threads. When I first started working remotely, we did try it but it seemed intrusive to several co-workers so we stopped using it, that was 4 years ago, I probably should give it another try.
A: It seems I have nothing to really add to what hasn't already been written.
I use it extensively, especially when remote people are involved in development. Without it your real time communication dies. It is the only viable method of communication that isn't as interruptive as phone calls or something of that nature. As we all know we can't just sit on the phone the whole time when developing, so chat is the next best thing for real time communication.
A: I personally don't like it. I think email allows you to take a little time to compose your thoughts.
IM seems to work for other people though. Whatever works!
A: Our entire business unit telecommutes. Only us first years are required to be in the office, so our enterprise IM solution is vital to staying in touch and on task. Its how my manager lets me know what project I'm working on, if I need to bill my time to another customer, or if I need to bounce ideas around. So yes, I do. Is it open for anyone to get on? No, not at all. You have to be on the intranet to access the system, and it is closed to any and all outsiders.
A: Out of the four professional jobs I've had over the past 8 years or so, I've only worked at one place that did not allow any type of instant messaging. All the other companies had at least some type of setup for intranet instant messaging.
I think that IM is almost necessary in today's business environment. I don't IM very much, but it's nice to have it available. Especially when I just need a quick answer to a question - like "Where is this file located?" and then boom I have a link to the file pop up right in front of my face.
A: I use IRC at work - it's almost a requirement for all of us who interact remotely (workign from home, different offices, and client sites) to be able to get help on problems fast.
A: Yup. It's actually required here. But only MSN though. We use it for development/task related communications with the team... which also help minimize noise since this company I'm currently working in is a big one where 90% are developers so utter silence is a MUST...
But if I've got questions to other members of the team, I prefer asking it personally though because I find it hard to explain some things when just chatting...
A: I've had to use it in my last job as my co-workers lived in the UK and my boss worked in California whereas I'm in Atlanta. It was used for quick questions and when it was "whenever you get the chance to respond" type thing. I could be on the phone and an IM pop-up and they would get an automatic message telling them that. Longer discussions were done with web cam and telephone and the ability to share a desktop to view code, data, etc.
A: My company won't allow it. Even if we run a IM server in house (so we aren't wasting time chatting with friends). I've tried to convince them, I find it really useful for knowing if someone is at their desk or not. The phones don't do that so well since if you don't pick up it redirects to a secretary that will get pissed if you are checking if someone's back every 5 min...
So I run a IM client on my phone so I can at least chat with a few people through out the day. (Less interrupting to others if my wife IMs me vs calls me and also easier to ignore if I need to).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: .NET Framework method to quickly build directories Is there a quick way to join paths like the Join-Path function in Powershell? For example, I have two parts of a path "C:\foo" and a subdirectory "bar". Join-Path will join these and take care of the backslash delimiters. Is there a built-in method for this in .NET, or do I need to handle this myself?
A: This is your friend: http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx
A: System.IO.Path.Combine is the one you're looking for. There's quite a few useful methods on the Path class.
A: Path.Combine is the way to go.
A: System.IO.Path.Combine
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does one load a URL from a .NET client application What is the preferred way to open a URL from a thick client application on Windows using C# and the .NET framework? I want it to use the default browser.
A: The following code surely works:
Process.Start("http://www.yoururl.com/Blah.aspx");
It opens the default browser (technically, the default program that handles HTTP URIs).
A: I'd use the Process.Start method.
A: private void launchURL_Click(object sender, System.EventArgs e){
string targetURL = "http://stackoverflow.com";
System.Diagnostics.Process.Start(targetURL);
}
A: System.Diagnostics.Process.Start("http://www.stackoverflow.com");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When is multi-threading not a good idea? I was recently working on an application that sent and received messages over Ethernet and Serial. I was then tasked to add the monitoring of DIO discretes. I throught,
"No reason to interrupt the main
thread which is involved in message
processing, I'll just create
another thread that monitors DIO."
This decision, however, proved to be poor. Sometimes the main thread would be interrupted between a Send and a Receive serial message. This interruption would disrupt the timing and alas, messages would be lost (forever).
I found another way to monitor the DIO without using another thread and Ethernet and Serial communication were restored to their correct functionality.
The whole fiasco, however, got me thinking. Are their any general guidelines about when not to use multiple-threads and/or does anyone have anymore examples of situations when using multiple-threads is not a good idea?
**EDIT:Based on your comments and after scowering the internet for information, I have composed a blog post entitled When is multi-threading not a good idea?
A: To paraphrase an old quote: A programmer had a problem. He thought, "I know, I'll use threads." Now the programmer has two problems. (Often attributed to JWZ, but it seems to predate his use of it talking about regexes.)
A good rule of thumb is "Don't use threads, unless there's a very compelling reason to use threads." Multiple threads are asking for trouble. Try to find a good way to solve the problem without using multiple threads, and only fall back to using threads if avoiding it is as much trouble as the extra effort to use threads. Also, consider switching to multiple threads if you're running on a multi-core/multi-CPU machine, and performance testing of the single threaded version shows that you need the performance of the extra cores.
A: Multi-threading is a bad idea if:
*
*Several threads access and update the same resource (set a variable, write to a file), and you don't understand thread safety.
*Several threads interact with each other and you don't understand mutexes and similar thread-management tools.
*Your program uses static variables (threads typically share them by default).
*You haven't debugged concurrency issues.
A: Actually, multi threading is not scalable and is hard to debug, so it should not be used in any case if you can avoid it. There is few cases where it is mandatory : when performance on a multi CPU matters, or when you deal whith a server that have a lot of clients taking a long time to answer.
In any other cases, you can use alternatives such as queue + cron jobs or else.
A: You might want to take a look at the Dan Kegel's "The C10K problem" web page about handling multiple data sources/sinks.
Basically it is best to use minimal threads, which in sockets can be done in most OS's w/ some event system (or asynchronously in Windows using IOCP).
When you run into the case where the OS and/or libraries do not offer a way to perform communication in a non-blocking manner, it is best to use a thread-pool to handle them while reporting back to the same event loop.
Example diagram of layout:
Per CPU [*] EVENTLOOP ------ Handles nonblocking I/O using OS/library utilities
| \___ Threadpool for various blocking events
Threadpool for handling the I/O messages that would take long
A: Multithreading is bad except in the single case where it is good. This case is
*
*The work is CPU Bound, or parts of it is CPU Bound
*The work is parallelisable.
If either or both of these conditions are missing, multithreading is not going to be a winning strategy.
If the work is not CPU bound, then you are waiting not on threads to finish work, but rather for some external event, such as network activity, for the process to complete its work. Using threads, there is the additional cost of context switches between threads, The cost of synchronization (mutexes, etc), and the irregularity of thread preemption. The alternative in most common use is asynchronous IO, in which a single thread listens to several io ports, and acts on whichever happens to be ready now, one at a time. If by some chance these slow channels all happen to become ready at the same time, It might seem like you will experience a slow-down, but in practice this is rarely true. The cost of handling each port individually is often comparable or better than the cost of synchronizing state on multiple threads as each channel is emptied.
Many tasks may be compute bound, but still not practical to use a multithreaded approach because the process must synchronise on the entire state. Such a program cannot benefit from multithreading because no work can be performed concurrently. Fortunately, most programs that require enormous amounts of CPU can be parallelized to some level.
A: Multi-threading is not a good idea if you need to guarantee precise physical timing (like in your example). Other cons include intensive data exchange between threads. I would say multi-threading is good for really parallel tasks if you don't care much about their relative speed/priority/timing.
A: A recent application I wrote that had to use multithreading (although not unbounded number of threads) was one where I had to communicate in several directions over two protocols, plus monitoring a third resource for changes. Both protocol libraries required a thread to run the respective event loop in, and when those were accounted for, it was easy to create a third loop for the resource monitoring. In addition to the event loop requirements, the messages going through the wires had strict timing requirements, and one loop couldn't be risked blocking the other, something that was further alleviated by using a multicore CPU (SPARC).
There were further discussions on whether each message processing should be considered a job that was given to a thread from a thread pool, but in the end that was an extension that wasn't worth the work.
All-in-all, threads should if possible only be considered when you can partition the work into well defined jobs (or series of jobs) such that the semantics are relatively easy to document and implement, and you can put an upper bound on the number of threads you use and that need to interact. Systems where this is best applied are almost message passing systems.
A: *
*On a single processor machine and a desktop application, you use multi threads so you don't freeze the app but for nothing else really.
*On a single processor server and a web based app, no need for multi threading because the web server handles most of it.
*On a multi-processor machine and desktop app, you are suggested to use multi threads and parallel programming. Make as many threads as there are processors.
*On a multi-processor server and a web based app, no need again for multi threads because the web server handles it.
In total, if you use multiple threads for other than un-freezing desktop apps and any other generic answer, you will make the app slower if you have a single core machine due to the threads interrupting each other.
Why? Because of the hardware switches. It takes time for the hardware to switch between threads in total. On a multi-core box, go ahead and use 1 thread for each core and you will greatly see a ramp up.
A: In priciple everytime there is no overhead for the caller to wait in a queue.
A: I would say multi-threading is generally used to:
*
*Allow data processing in the background while a GUI remains responsive
*Split very big data analysis onto multiple processing units so that you can get your results quicker.
*When you're receiving data from some hardware and need something to continuously add it to a buffer while some other element decides what to do with it (write to disk, display on a GUI etc.).
So if you're not solving one of those issues, it's unlikely that adding threads will make your life easier. In fact it'll almost certainly make it harder because as others have mentioned; debugging mutithreaded applications is considerably more work than a single threaded solution.
Security might be a reason to avoid using multiple threads (over multiple processes). See Google chrome for an example of multi-process safety features.
A: A couple more possible reasons to use threads:
*
*Your platform lacks asynchronous I/O operations, e.g. Windows ME (No completion ports or overlapped I/O, a pain when porting XP applications that use them.) Java 1.3 and earlier.
*A third-party library function that can hang, e.g. if a remote server is down, and the library provides no way to cancel the operation and you can't modify it.
Keeping a GUI responsive during intensive processing doesn't always require additional threads. A single callback function is usually sufficient.
If none of the above apply and I still want parallelism for some reason, I prefer to launch an independent process if possible.
A: Multi-threading is scalable, and will allow your UI to maintain its responsivness while doing very complicated things in the background. I don't understand where other responses are acquiring their information on multi-threading.
When you shouldn't multi-thread is a mis-leading question to your problem. Your problem is this: Why did multi-threading my application cause serial / ethernet communications to fail?
The answer to that question will depend on the implementation, which should be discussed in another question. I know for a fact that you can have both ethernet and serial communications happening in a multi-threaded application at the same time as numerous other tasks without causing any data loss.
The one reason to not use multi-threading is:
*
*There is one task, and no user interface with which the task will interfere.
The reasons to use mutli-threading are:
*
*Provides superior responsiveness to the user
*Performs multiple tasks at the same time to decrease overall execution time
*Uses more of the current multi-core CPUs, and multi-multi-cores of the future.
There are three basic methods of multi-threaded programming that make thread safety implemented with ease - you only need to use one for success:
*
*Thread Safe Data types passed between threads.
*Thread Safe Methods in the threaded object to modify data passed between.
*PostMessage capabilities to communicate between threads.
A: Are the processes parallel? Is performance a real concern? Are there multiple 'threads' of execution like on a web server? I don't think there is a finite answer.
A: A common source of threading issues is the usual approaches employed to synchronize data. Having threads share state and then implement locking at all the appropriate places is a major source of complexity for both design and debugging. Getting the locking right to balance stability, performance, and scalability is always a hard problem to solve. Even the most experienced experts get it wrong frequently. Alternative techniques to deal with threading can alleviate much of this complexity. The Clojure programming language implements several interesting techniques for dealing with concurrency.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: Bit manipulation and output in Java If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file?
This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks!
A: Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file.
The inner loop would look something like:
byte[] buffer = new byte[ ( string.length + 7 ) / 8 ];
for ( int i = 0; i < buffer.length; ++i ) {
byte current = 0;
for ( int j = 7; j >= 0; --j )
if ( string[ i * 8 + j ] == '1' )
current |= 1 << j;
output( current );
}
You'll need to make some adjustments, but that's the general idea.
A: If you're lucky, java.math.BigInteger may do everything for you.
String s = "11001010001010101110101001001110";
byte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray();
This does depend on the byte order (big-endian) and right-aligning (if the number of bits is not a multiple of 8) being what you want but it may be simpler to modify the array afterwards than to do the character conversion yourself.
A: public class BitOutputStream extends FilterOutputStream
{
private int buffer = 0;
private int bitCount = 0;
public BitOutputStream(OutputStream out)
{
super(out);
}
public void writeBits(int value, int numBits) throws IOException
{
while(numBits>0)
{
numBits--;
int mix = ((value&1)<<bitCount++);
buffer|=mix;
value>>=1;
if(bitCount==8)
align8();
}
}
@Override
public void close() throws IOException
{
align8(); /* Flush any remaining partial bytes */
super.close();
}
public void align8() throws IOException
{
if(bitCount > 0)
{
bitCount=0;
write(buffer);
buffer=0;
}
}
}
And then...
if (nextChar == '0')
{
bos.writeBits(0, 1);
}
else
{
bos.writeBits(1, 1);
}
A: Assuming the String has a multiple of eight bits, (you can pad it otherwise), take advantage of Java's built in parsing in the Integer.valueOf method to do something like this:
String s = "11001010001010101110101001001110";
byte[] data = new byte[s.length() / 8];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) Integer.parseInt(s.substring(i * 8, (i + 1) * 8), 2);
}
Then you should be able to write the bytes to a FileOutputStream pretty simply.
On the other hand, if you looking for effeciency, you should consider not using a String to store the bits to begin with, but build up the bytes directly in your compressor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/93839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.