text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: SQL Query Help: Selecting Rows That Appear A Certain Number Of Times I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?
A: SELECT * FROM [MyTable] WHERE [Date] IN
(
SELECT [Date]
FROM [MyTable]
GROUP By [Date]
HAVING COUNT(*) < @Max
)
See @[SQLMenace] 's response also. It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference moot.
A: select dates
from table t
group by dates having count(dates) < k ;
Hopefully, it works for ORACLE.
HTH
A: Use the COUNT aggregate:
SELECT Date
FROM SomeTable
GROUP BY Date
HAVING COUNT(*) < @k
A: For "appears x times" queries it is best to use HAVING clause. In your case, query can be like:
SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k
or, in you need to select other columns except Date:
SELECT * FROM Table WHERE Date IN (
SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k)
You can also rewrite the IN to INNER JOIN, however this won't give performance gain, as, in fact, query optimizer will do this for you in most RDBMS. Having index on Date will certainly improve performance for this query.
A: example
DECLARE @Max int
SELECT @Max = 5
SELECT t1.*
FROM [MyTable] t1
JOIN(
SELECT [Date]
FROM [MyTable]
GROUP By [Date]
HAVING COUNT(*) < @Max
) t2 on t1.[Date] = t2.[Date]
A: SELECT date, COUNT(date)
FROM table
GROUP BY date
HAVING COUNT(date) < k
And then to get the original data back:
SELECT table.*
FROM table
INNER JOIN (
SELECT date, COUNT(date)
FROM table
GROUP BY date
HAVING COUNT(date) < k) dates ON table.date = dates.date
A: Assuming you are using Oracle, and k = 5:-
select date_col,count(*)
from your_table
group by date_col
having count(*) < 5;
If your date column has time filled out as well, and you want to ignore it, modify the query so it looks as follows:-
select trunc(date_col) as date_col,count(*)
from your_table
group by trunc(date_col)
having count(*) < 5;
A: You may not be able to count directly on the datefield if your dates include times. You may need to convert to just the year/month/day format first and then do the count on that.
Otherwise your counts will be off as usually there are very few records withthe exact same time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/104971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: ReSharper giving C# 3.0 Code Inspection Warnings to .NET 2.0 Projects When I am working in .NET 2.0 projects with the newest version of ReSharper (4.1) I am getting warnings about using the var keyword and lambadas etc.. Any idea how I can disable this only for .NET 2.0 projects?
A: Indeed, you can use C# 3.0 compiler features when targeting .NET 2.0, except extension methods and default LINQ implementations, which are located in newer assemblies. But if you need to co-operate with VS2005 users, you can open Properties view for a given project (not Project Properties, but Edit \ Properties Window, or F4) and select desired language level.
A: You can actually use var in 2.0 projects. It's syntactical sugar and the compiler works with it. Check out this for more info.
http://weblogs.asp.net/shahar/archive/2008/01/23/use-c-3-features-from-c-2-and-net-2-0-code.aspx
A: Daniel Moth has a great blog post on how to using C# 3.0 features (including extension methods) in .Net 2.0.
After rereading the question, this really doesn't help. You can turn off specific inspections via the R# Options window. I don't know of a way to switch back and forth between 2.0 and 3.5 project settings without manually changing them :S.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/104978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What is "thread local storage" in Python, and why do I need it? In Python specifically, how do variables get shared between threads?
Although I have used threading.Thread before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?
I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem.
A: Consider the following code:
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread, local
data = local()
def bar():
print("I'm called from", data.v)
def foo():
bar()
class T(Thread):
def run(self):
sleep(random())
data.v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
>> T().start(); T().start()
I'm called from Thread-2
I'm called from Thread-1
Here threading.local() is used as a quick and dirty way to pass some data from run() to bar() without changing the interface of foo().
Note that using global variables won't do the trick:
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread
def bar():
global v
print("I'm called from", v)
def foo():
bar()
class T(Thread):
def run(self):
global v
sleep(random())
v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
>> T().start(); T().start()
I'm called from Thread-2
I'm called from Thread-2
Meanwhile, if you could afford passing this data through as an argument of foo() - it would be a more elegant and well-designed way:
from threading import Thread
def bar(v):
print("I'm called from", v)
def foo(v):
bar(v)
class T(Thread):
def run(self):
foo(self.getName())
But this is not always possible when using third-party or poorly designed code.
A: Just like in every other language, every thread in Python has access to the same variables. There's no distinction between the 'main thread' and child threads.
One difference with Python is that the Global Interpreter Lock means that only one thread can be running Python code at a time. This isn't much help when it comes to synchronising access, however, as all the usual pre-emption issues still apply, and you have to use threading primitives just like in other languages. It does mean you need to reconsider if you were using threads for performance, however.
A: You can create thread local storage using threading.local().
>>> tls = threading.local()
>>> tls.x = 4
>>> tls.x
4
Data stored to the tls will be unique to each thread which will help ensure that unintentional sharing does not occur.
A: In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them.
The Thread object for a particular thread is not a special object in this regard. If you store the Thread object somewhere all threads can access (like a global variable) then all threads can access that one Thread object. If you want to atomically modify anything that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective.
If you want actual thread-local storage, that's where threading.local comes in. Attributes of threading.local are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in _threading_local.py in the standard library.
A: I may be wrong here. If you know otherwise please expound as this would help explain why one would need to use thread local().
This statement seems off, not wrong: "If you want to atomically modify anything that another thread has access to, you have to protect it with a lock." I think this statement is ->effectively<- right but not entirely accurate. I thought the term "atomic" meant that the Python interpreter created a byte-code chunk that left no room for an interrupt signal to the CPU.
I thought atomic operations are chunks of Python byte code that does not give access to interrupts. Python statements like "running = True" is atomic. You do not need to lock CPU from interrupts in this case (I believe). The Python byte code breakdown is safe from thread interruption.
Python code like "threads_running[5] = True" is not atomic. There are two chunks of Python byte code here; one to de-reference the list() for an object and another byte code chunk to assign a value to an object, in this case a "place" in a list. An interrupt can be raised -->between<- the two byte-code ->chunks<-. That is were bad stuff happens.
How does thread local() relate to "atomic"? This is why the statement seems misdirecting to me. If not can you explain?
A: Worth mentioning threading.local() is not a singleton.
You can use more of them per thread.
It is not one storage.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/104983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "128"
}
|
Q: How should a blog be structured to easily extract its data? I'm currently using Wordpress to run my website. However, with each new release I become more concerned with software bloat and the convoluted table structures used to store my data. Maybe this is a fruitless pursuit. Features are always added to blogging software until it claims to be a CMS--and at that point your data is probably stuck.
A: You do have the option of sticking with the 2.0 branch. This will be maintained with just bug fixes until 2010. Take a look at http://wordpress.org/download/legacy/
A: I also sometimes worry about the large changes WordPress undergoes.
However, since all the important data (the posts themselves and the comments) are stored in a database, it does not seem difficult to extract them in case of need (moving to a different system, or just backup). Even if the table structure gets more complex, the MySQL DB WordPress uses is easy to access and extract data from.
I'm sure that it is easy to find such extractors freely floating in the web.
A: Wordpress has an 'export' feature. It downloads most of the data such as posts, pages and comments in an XML file. These XML files can be imported into other Wordpress installations.
You can also create a simple importer to import that data else where.
A: None of the previous answers have really addressed the title of this question.
How should the tables be constructed for a blog? That entirely depends on what you want to do with it, honestly.
One approach could be to have a posts table and a comments table. The posts table could have the title, content, date, and a post id. The comments table could have a post id, comment id, commenter note, and content.
But that's really only relevant if you're building it yourself. None of the blogging tools I have ever seen are very inefficient in terms of space usage, and all of them provide import tools from "standard" formats (from blogger, wordpress, moveabletype, etc to any where else). And don't forget that they will all publish posts and comments via RSS, which makes them eminently portable.
WordPress in particular is still only 1.2 MB as a tar.gz. If that's big enough to be concerned about bloat, I'd strongly suggest building one yourself, or moving to a hosted blogging platform :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should I test private methods or only public ones? I have read this post about how to test private methods. I usually do not test them, because I always thought it's faster to test only public methods that will be called from outside the object. Do you test private methods? Should I always test them?
A: I do not like testing private functionality for a couple of reasons. They are as follows (these are the main points for the TLDR people):
*
*Typically when you're tempted to test a class's private method,
it's a design smell.
*You can test them through the public
interface (which is how you want to test them, because that's how
the client will call/use them). You can get a false sense of security by
seeing the green light on all the passing tests for your private
methods. It is much better/safer to test edge cases on your private functions through your public interface.
*You risk severe test duplication (tests that look/feel
very similar) by testing private methods. This has major
consequences when requirements change, as many more tests than
necessary will break. It can also put you in a position where it is
hard to refactor because of your test suite...which is the ultimate
irony, because the test suite is there to help you safely redesign
and refactor!
I'll explain each of these with a concrete example. It turns out that 2) and 3) are somewhat intricately connected, so their example is similar, although I consider them separate reasons why you shouldn't test private methods.
There are times testing private methods is appropriate, it's just important to be aware of the downsides listed above. I'm going to go over it in more detail later.
I also go over why TDD is not a valid excuse for testing private methods at the very end.
Refactoring your way out of a bad design
One of the most common (anti)paterns that I see is what Michael Feathers calls an "Iceberg" class (if you don't know who Michael Feathers is, go buy/read his book "Working Effectively with Legacy Code". He is a person worth knowing about if you are a professional software engineer/developer). There are other (anti)patterns that cause this issue to crop up, but this is by far the most common one I've stumbled across. "Iceberg" classes have one public method, and the rest are private (which is why it's tempting to test the private methods). It's called an "Iceberg" class because there is usually a lone public method poking up, but the rest of the functionality is hidden underwater in the form of private methods. It might look something like this:
For example, you might want to test GetNextToken() by calling it on a string successively and seeing that it returns the expected result. A function like this does warrant a test: that behavior isn't trivial, especially if your tokenizing rules are complex. Let's pretend it's not all that complex, and we just want to rope in tokens delimited by space. So you write a test, maybe it looks something like this (some language agnostic psuedo-code, hopefully the idea is clear):
TEST_THAT(RuleEvaluator, canParseSpaceDelimtedTokens)
{
input_string = "1 2 test bar"
re = RuleEvaluator(input_string);
ASSERT re.GetNextToken() IS "1";
ASSERT re.GetNextToken() IS "2";
ASSERT re.GetNextToken() IS "test";
ASSERT re.GetNextToken() IS "bar";
ASSERT re.HasMoreTokens() IS FALSE;
}
Well, that actually looks pretty nice. We'd want to make sure we maintain this behavior as we make changes. But GetNextToken() is a private function! So we can't test it like this, because it wont even compile (assuming we are using some language that actually enforces public/private, unlike some scripting languages like Python). But what about changing the RuleEvaluator class to follow the Single Responsibility Principle (Single Responsibility Principle)? For instance, we seem to have a parser, tokenizer, and evaluator jammed into one class. Wouldn't it be better to just separate those responsibilities? On top of that, if you create a Tokenizer class, then it's public methods would be HasMoreTokens() and GetNextTokens(). The RuleEvaluator class could have a Tokenizer object as a member. Now, we can keep the same test as above, except we are testing the Tokenizer class instead of the RuleEvaluator class.
Here's what it might look like in UML:
Note that this new design increases modularity, so you could potentially re-use these classes in other parts of your system (before you couldn't, private methods aren't reusable by definition). This is main advantage of breaking the RuleEvaluator down, along with increased understandability/locality.
The test would look extremely similar, except it would actually compile this time since the GetNextToken() method is now public on the Tokenizer class:
TEST_THAT(Tokenizer, canParseSpaceDelimtedTokens)
{
input_string = "1 2 test bar"
tokenizer = Tokenizer(input_string);
ASSERT tokenizer.GetNextToken() IS "1";
ASSERT tokenizer.GetNextToken() IS "2";
ASSERT tokenizer.GetNextToken() IS "test";
ASSERT tokenizer.GetNextToken() IS "bar";
ASSERT tokenizer.HasMoreTokens() IS FALSE;
}
Testing private components through a public interface and avoiding test duplication
Even if you don't think you can break your problem down into fewer modular components (which you can 95% of the time if you just try to do it), you can simply test the private functions through a public interface. Many times private members aren't worth testing because they will be tested through the public interface. A lot of times what I see is tests that look very similar, but test two different functions/methods. What ends up happening is that when requirements change (and they always do), you now have 2 broken tests instead of 1. And if you really tested all your private methods, you might have more like 10 broken tests instead of 1. In short, testing private functions (by using FRIEND_TEST or making them public or using reflection) that could otherwise be tested through a public interface can cause test duplication. You really don't want this, because nothing hurts more than your test suite slowing you down. It's supposed to decrease development time and decrease maintenance costs! If you test private methods that are otherwise tested through a public interface, the test suite may very well do the opposite, and actively increase maintenance costs and increase development time. When you make a private function public, or if you use something like FRIEND_TEST and/or reflection, you'll usually end up regretting it in the long run.
Consider the following possible implementation of the Tokenizer class:
Let's say that SplitUpByDelimiter() is responsible for returning an array such that each element in the array is a token. Furthermore, let's just say that GetNextToken() is simply an iterator over this vector. So your public test might look this:
TEST_THAT(Tokenizer, canParseSpaceDelimtedTokens)
{
input_string = "1 2 test bar"
tokenizer = Tokenizer(input_string);
ASSERT tokenizer.GetNextToken() IS "1";
ASSERT tokenizer.GetNextToken() IS "2";
ASSERT tokenizer.GetNextToken() IS "test";
ASSERT tokenizer.GetNextToken() IS "bar";
ASSERT tokenizer.HasMoreTokens() IS false;
}
Let's pretend that we have what Michael Feather's calls a groping tool. This is a tool that lets you touch other people's private parts. An example is FRIEND_TEST from googletest, or reflection if the language supports it.
TEST_THAT(TokenizerTest, canGenerateSpaceDelimtedTokens)
{
input_string = "1 2 test bar"
tokenizer = Tokenizer(input_string);
result_array = tokenizer.SplitUpByDelimiter(" ");
ASSERT result.size() IS 4;
ASSERT result[0] IS "1";
ASSERT result[1] IS "2";
ASSERT result[2] IS "test";
ASSERT result[3] IS "bar";
}
Well, now let's say the requirements change, and the tokenizing becomes much more complex. You decide that a simple string delimiter won't suffice, and you need a Delimiter class to handle the job. Naturally, you're going to expect one test to break, but that pain increases when you test private functions.
When can testing private methods be appropriate?
There is no "one size fits all" in software. Sometimes it's okay (and actually ideal) to "break the rules". I strongly advocate not testing private functionality when you can. There are two main situations when I think it's okay:
*
*I've worked extensively with legacy systems (which is why I'm such a big Michael Feathers fan), and I can safely say that sometimes it is simply safest to just test the private functionality. It can be especially helpful for getting "characterization tests" into the baseline.
*You're in a rush, and have to do the fastest thing possible for here and now. In the long run, you don't want to test private methods. But I will say that it usually takes some time to refactor to address design issues. And sometimes you have to ship in a week. That's okay: do the quick and dirty and test the private methods using a groping tool if that's what you think is the fastest and most reliable way to get the job done. But understand that what you did was suboptimal in the long run, and please consider coming back to it (or, if it was forgotten about but you see it later, fix it).
There are probably other situations where it's okay. If you think it's okay, and you have a good justification, then do it. No one is stopping you. Just be aware of the potential costs.
The TDD Excuse
As an aside, I really don't like people using TDD as an excuse for testing private methods. I practice TDD, and I do not think TDD forces you to do this. You can write your test (for your public interface) first, and then write code to satisfy that interface. Sometimes I write a test for a public interface, and I'll satisfy it by writing one or two smaller private methods as well (but I don't test the private methods directly, but I know they work or my public test would be failing). If I need to test edge cases of that private method, I'll write a whole bunch of tests that will hit them through my public interface. If you can't figure out how to hit the edge cases, this is a strong sign you need to refactor into small components each with their own public methods. It's a sign your private functions are doing too much, and outside the scope of the class.
Also, sometimes I find I write a test that is too big of a bite to chew at the moment, and so I think "eh I'll come back to that test later when I have more of an API to work with" (I'll comment it out and keep it in the back of my mind). This is where a lot of devs I've met will then start writing tests for their private functionality, using TDD as the scapegoat. They say "oh, well I need some other test, but in order to write that test, I'll need these private methods. Therefore, since I can't write any production code without writing a test, I need to write a test for a private method." But what they really need to be doing is refactoring into smaller and reusable components instead of adding/testing a bunch of private methods to their current class.
Note:
I answered a similar question about testing private methods using GoogleTest a little while ago. I've mostly modified that answer to be more language agnostic here.
P.S. Here's the relevant lecture about iceberg classes and groping tools by Michael Feathers: https://www.youtube.com/watch?v=4cVZvoFGJTU
A: Unit tests I believe are for testing public methods. Your public methods use your private methods, so indirectly they are also getting tested.
A: I've been stewing over this issue for a while especially with trying my hand at TDD.
I've come across two posts that I think address this problem thoroughly enough in the case of TDD.
*
*Testing private methods, TDD and Test-Driven Refactoring
*Test-Driven Development Isn’t Testing
In Summary:
*
*When using test driven development (design) techniques, private methods should arise only during the re-factoring process of already working and tested code.
*By the very nature of the process, any bit of simple implementation functionality extracted out of a thoroughly tested function will be it self tested (i.e. indirect testing coverage).
To me it seems clear enough that in the beginning part of coding most methods will be higher level functions because they are encapsulating/describing the design.
Therefore, these methods will be public and testing them will be easy enough.
The private methods will come later once everything is working well and we are re factoring for the sake of readability and cleanliness.
A: I kind of feel compelled to test private functions as I am following more and more one of our latest QA recommendation in our project:
No more than 10 in cyclomatic complexity per function.
Now the side effect of the enforcing of this policy is that many of my very large public functions get divided in many more focused, better named private function.
The public function still there (of course) but is essentially reduced to called all those private 'sub-functions'
That is actually cool, because the callstack is now much easier to read (instead of a bug within a large function, I have a bug in a sub-sub-function with the name of the previous functions in the callstack to help me to understand 'how I got there')
However, it now seem easier to unit-test directly those private functions, and leave the testing of the large public function to some kind of 'integration' test where a scenario needs to be addressed.
Just my 2 cents.
A: As quoted above, "If you don't test your private methods, how do you know they won't break?"
This is a major issue. One of the big points of unit tests is to know where, when, and how something broke ASAP. Thus decreasing a significant amount of development & QA effort. If all that is tested is the public, then you don't have honest coverage and delineation of the internals of the class.
I've found one of the best ways to do this is simply add the test reference to the project and put the tests in a class parallel to the private methods. Put in the appropriate build logic so that the tests don't build into the final project.
Then you have all the benefits of having these methods tested and you can find problems in seconds versus minutes or hours.
So in summary, yes, unit test your private methods.
A: You should not. If your private methods have enough complexity that must be tested, you should put them on another class. Keep high cohesion, a class should have only one purpose. The class public interface should be enough.
A: Yes I do test private functions, because although they are tested by your public methods, it is nice in TDD (Test Driven Design) to test the smallest part of the application. But private functions are not accessible when you are in your test unit class. Here's what we do to test our private methods.
Why do we have private methods?
Private functions mainly exists in our class because we want to create readable code in our public methods.
We do not want the user of this class to call these methods directly, but through our public methods. Also, we do not want change their behavior when extending the class (in case of protected), hence it's a private.
When we code, we use test-driven-design (TDD). This means that sometimes we stumble on a piece of functionality that is private and want to test. Private functions are not testable in phpUnit, because we cannot access them in the Test class (they are private).
We think here are 3 solutions:
1. You can test your privates through your public methods
Advantages
*
*Straightforward unit testing (no 'hacks' needed)
Disadvantages
*
*Programmer needs to understand the public method, while he only wants to test the private method
*You are not testing the smallest testable part of the application
2. If the private is so important, then maybe it is a codesmell to create a new separate class for it
Advantages
*
*You can refactor this to a new class, because if it is that
important, other classes may need it too
*The testable unit is now a public method, so testable
Disadvantages
*
*You dont want to create a class if it is not needed, and only used by
the class where the method is coming from
*Potential performance loss because of added overhead
3. Change the access modifier to (final) protected
Advantages
*
*You are testing the smallest testable part of the application. When
using final protected, the function will not be overridable (just
like a private)
*No performance loss
*No extra overhead
Disadvantages
*
*You are changing a private access to protected, which means it's
accessible by it's children
*You still need a Mock class in your test class to use it
Example
class Detective {
public function investigate() {}
private function sleepWithSuspect($suspect) {}
}
Altered version:
class Detective {
public function investigate() {}
final protected function sleepWithSuspect($suspect) {}
}
In Test class:
class Mock_Detective extends Detective {
public test_sleepWithSuspect($suspect)
{
//this is now accessible, but still not overridable!
$this->sleepWithSuspect($suspect);
}
}
So our test unit can now call test_sleepWithSuspect to test our former private function.
A: I do not unit test private methods. A private method is an implementation detail that should be hidden to the users of the class. Testing private methods breaks encapsulation.
If I find that the private method is huge or complex or important enough to require its own tests, I just put it in another class and make it public there (Method Object). Then I can easily test the previously-private-but-now-public method that now lives on its own class.
A: What is the purpose of testing?
The majority of the answers so far are saying that private methods are implementation details which don't (or at least shouldn't) matter so long as the public interface is well-tested and working. That's absolutely correct if your only purpose for testing is to guarantee that the public interface works.
Personally, my primary use for code tests is to ensure that future code changes don't cause problems and to aid my debugging efforts if they do. I find that testing the private methods just as thoroughly as the public interface (if not more so!) furthers that purpose.
Consider: You have public method A which calls private method B. A and B both make use of method C. C is changed (perhaps by you, perhaps by a vendor), causing A to start failing its tests. Wouldn't it be useful to have tests for B also, even though it's private, so that you know whether the problem is in A's use of C, B's use of C, or both?
Testing private methods also adds value in cases where test coverage of the public interface is incomplete. While this is a situation we generally want to avoid, the efficiency unit testing depends both on the tests finding bugs and the associated development and maintenance costs of those tests. In some cases, the benefits of 100% test coverage may be judged insufficient to warrant the costs of those tests, producing gaps in the public interface's test coverage. In such cases, a well-targeted test of a private method can be a very effective addition to the code base.
A: I understand the point of view where private methods are considered as implementations details and then don't have to be tested. And I would stick with this rule if we had to develop outside of the object only. But us, are we some kind of restricted developers who are developing only outside of objects, calling only their public methods? Or are we actually also developing that object? As we are not bound to program outside objects, we will probably have to call those private methods into new public ones we are developing. Wouldn't it be great to know that the private method resist against all odds?
I know some people could answer that if we are developing another public method into that object then this one should be tested and that's it (the private method could carry on living without test). But this is also true for any public methods of an object: when developing a web app, all the public methods of an object are called from controllers methods and hence could be considered as implementation details for controllers.
So why are we unit testing objects? Because it is really difficult, not to say impossible to be sure that we are testing the controllers' methods with the appropriate input which will trigger all the branches of the underlying code. In other words, the higher we are in the stack, the more difficult it is to test all the behaviour. And so is the same for private methods.
To me the frontier between private and public methods is a psychologic criteria when it comes to tests. Criteria which matters more to me are:
*
*is the method called more than once from different places?
*is the method sophisticated enough to require tests?
A: Yes you should test private methods, wherever possible. Why? To avoid an unnecessary state space explosion of test cases which ultimately just end up implicitly testing the same private functions repeatedly on the same inputs. Let's explain why with an example.
Consider the following slightly contrived example. Suppose we want to expose publicly a function that takes 3 integers and returns true if and only if those 3 integers are all prime. We might implement it like this:
public bool allPrime(int a, int b, int c)
{
return andAll(isPrime(a), isPrime(b), isPrime(c))
}
private bool andAll(bool... boolArray)
{
foreach (bool b in boolArray)
{
if(b == false) return false;
}
return true;
}
private bool isPrime(int x){
//Implementation to go here. Sorry if you were expecting a prime sieve.
}
Now, if we were to take the strict approach that only public functions should be tested, we'd only be allowed to test allPrime and not isPrime or andAll.
As a tester, we might be interested in five possibilities for each argument: < 0, = 0, = 1, prime > 1, not prime > 1. But to be thorough, we'd have to also see how every combination of the arguments plays together. So that's 5*5*5 = 125 test cases we'd need to thoroughly test this function, according to our intuitions.
On the other hand, if we were allowed to test the private functions, we could cover as much ground with fewer test cases. We'd need only 5 test cases to test isPrime to the same level as our previous intuition. And by the small scope hypothesis proposed by Daniel Jackson, we'd only need to test the andAll function up to a small length e.g. 3 or 4. Which would be at most 16 more tests. So 21 tests in total. Instead of 125. Of course, we probably would want to run a few tests on allPrime, but we wouldn't feel so obliged to cover exhaustively all 125 combinations of input scenarios we said we cared about. Just a few happy paths.
A contrived example, for sure, but it was necessary for a clear demonstration. And the pattern extends to real software. Private functions are usually the lowest level building blocks, and are thus often combined together to yield higher level logic. Meaning at higher levels, we have more repetitions of the lower level stuff due to the various combinations.
A: I think it's best to just test the public interface of an object. From the point of view of the outside world, only the behavior of the public interface matters and this is what your unit tests should be directed towards.
Once you have some solid unit tests written for an object you do not want to have to go back and change those tests just because the implementation behind the interface changed. In this situation, you've ruined the consistency of your unit testing.
A: If your private method is not tested by calling your public methods then what is it doing?
I'm talking private not protected or friend.
A: If you don't test your private methods, how do you know they won't break?
A: It's obviously language dependent. In the past with c++, I've declared the testing class to be a friend class. Unfortunately, this does require your production code to know about the testing class.
A: If the private method is well defined (ie, it has a function that is testable and is not meant to change over time) then yes. I test everything that's testable where it makes sense.
For instance, an encryption library might hide the fact that it performs block encryption with a private method that encrypts only 8 bytes at a time. I would write a unit test for that - it's not meant to change, even though it's hidden, and if it does break (due to future performance enhancements, for instance) then I want to know that it's the private function that broke, not just that one of the public functions broke.
It speeds debugging later.
-Adam
A: I tend to follow the advice of Dave Thomas and Andy Hunt in their book Pragmatic Unit Testing:
In general, you don't want to break any encapsulation for the sake of
testing (or as Mom used to say, "don't expose your privates!"). Most
of the time, you should be able to test a class by exercising its
public methods. If there is significant functionality that is hidden
behind private or protected access, that might be a warning sign that
there's another class in there struggling to get out.
But sometimes I can't stop myself from testing private methods because it gives me that sense of reassurance that I'm building a completely robust program.
A: I am not an expert in this field, but unit testing should test behaviour, not implementation. Private methods are strictly part of the implementation, so IMHO should not be tested.
A: If you are developing test driven (TDD), you will test your private methods.
A: We test private methods by inference, by which I mean we look for total class test coverage of at least 95%, but only have our tests call into public or internal methods. To get the coverage, we need to make multiple calls to the public/internals based on the different scenarios that may occur. This makes our tests more intentful around the purpose of the code they are testing.
Trumpi's answer to the post you linked is the best one.
A: If I find that the private method is huge or complex or important enough to require its own tests, I just put it in another class and make it public there (Method Object). Then I can easily test the previously private but now public method that now lives on its own class.
A: I never understand the concept of Unit Test but now I know what it's the objective.
A Unit Test is not a complete test. So, it's not a replacement for QA and manual test. The concept of TDD in this aspect is wrong since you can't test everything, including private methods but also, methods that use resources (especially resources that we don't have control). TDD is basing all its quality is something that it could not be achieved.
A Unit test is more a pivot test You mark some arbitrary pivot and the result of pivot should stay the same.
A: Public vs. private is not a useful distinction for what apis to call from your tests, nor is method vs. class. Most testable units are visible in one context, but hidden in others.
What matters is coverage and costs. You need to minimize costs while achieving coverage goals of your project (line, branch, path, block, method, class, equivalence class, use-case... whatever the team decides).
So use tools to ensure coverage, and design your tests to cause least costs(short and long-term).
Don't make tests more expensive than necessary.
If it's cheapest to only test public entry points do that.
If it's cheapest to test private methods, do that.
As you get more experienced, you will become better at predicting when it's worth refactoring to avoid long-term costs of test maintenance.
A: If the method is significant enough/complex enough , I'll usually make it "protected" and test it. Some methods will be left private and tested implicitly as part of unit tests for the public/protected methods.
A: I see many people are in the same line of thinking: test at the public level. but isn't that what our QA team does? They test input and expected output. If as developers we only test the public methods then we are simply redoing QA's job and not adding any value by "unit testing".
A: One main point is
If we test to ensure the correctness of the logic, and a private method is carrying a logic, we should test it. Isn't it? So why are we going to skip that?
Writing tests based on the visibility of methods is completely irrelevant idea.
Conversely
On the other hand, calling a private method outside the original class is a main problem. And also there are limitations to mock a private method in some mocking tools. (Ex: Mockito)
Though there are some tools like Power Mock which supports that, it is a dangerous operation. The reason is it needs to hack the JVM to achieve that.
One work around that can be done is (If you want to write test cases for private methods)
Declare those private methods as protected. But it may not be convenient for several situations.
A: The answer to "Should I test private methods?" is ".......sometimes". Typically you should be testing against the interface of your classes.
*
*One of the reasons is because you do not need double coverage for a feature.
*Another reason is that if you change private methods, you will have to update each test for them, even if the interface of your object hasn't changed at all.
Here is an example:
class Thing
def some_string
one + two
end
private
def one
'aaaa'
end
def two
'bbbb'
end
end
class RefactoredThing
def some_string
one + one_a + two + two_b
end
private
def one
'aa'
end
def one_a
'aa'
end
def two
'bb'
end
def two_b
'bb'
end
end
In RefactoredThing you now have 5 tests, 2 of which you had to update for refactoring, but your object's functionality really hasn't changed. So let's say that things are more complex than that and you have some method that defines the order of the output such as:
def some_string_positioner
if some case
elsif other case
elsif other case
elsif other case
else one more case
end
end
This shouldn't be run by an outside user, but your encapsulating class may be to heavy to run that much logic through it over and over again. In this case maybe you would rather extract this into a seperate class, give that class an interface and test against it.
And finally, let's say that your main object is super heavy, and the method is quite small and you really need to ensure that the output is correct. You are thinking, "I have to test this private method!". Have you that maybe you can make your object lighter by passing in some of the heavy work as an initialization parameter? Then you can pass something lighter in and test against that.
A: No You shouldn't test the Private Methods why? and moreover the popular mocking framework such as Mockito doesn't provide support for testing private methods.
A: It's not only about public or private methods or functions, it is about implementation details. Private functions are just one aspect of implementation details.
Unit-testing, after all, is a white box testing approach. For example, whoever uses coverage analysis to identify parts of the code that have been neglected in testing so far, goes into the implementation details.
A) Yes, you should be testing implementation details:
Think of a sort function which for performance reasons uses a private implementation of BubbleSort if there are up to 10 elements, and a private implementation of a different sort approach (say, heapsort) if there are more than 10 elements. The public API is that of a sort function. Your test suite, however, better makes use of the knowledge that there are actually two sort algorithms used.
In this example, surely, you could perform the tests on the public API. This would, however, require to have a number of test cases that execute the sort function with more than 10 elements, such that the heapsort algorithm is sufficiently well tested. The existence of such test cases alone is an indication that the test suite is connected to the implementation details of the function.
If the implementation details of the sort function change, maybe in the way that the limit between the two sorting algorithms is shifted or that heapsort is replaced by mergesort or whatever: The existing tests will continue to work. Their value nevertheless is then questionable, and they likely need to be reworked to better test the changed sort function. In other words, there will be a maintenance effort despite the fact that tests were on the public API.
B) How to test implementation details
One reason why many people argue one should not test private functions or implementation details is, that the implementation details are more likely to change. This higher likelyness of change at least is one of the reasons for hiding implementation details behind interfaces.
Now, assume that the implementation behind the interface contains larger private parts for which individual tests on the internal interface might be an option. Some people argue, these parts should not be tested when private, they should be turned into something public. Once public, unit-testing that code would be OK.
This is interesting: While the interface was internal, it was likely to change, being an implementation detail. Taking the same interface, making it public does some magic transformation, namely turning it into an interface that is less likely to change. Obviously there is some flaw in this argumentation.
But, there is nevertheless some truth behind this: When testing implementation details, in particular using internal interfaces, one should strive to use interfaces that are likely to remain stable. Whether some interface is likely to be stable is, however, not simply decidable based on whether it is public or private. In the projects from world I have been working in for some time, public interfaces also often enough change, and many private interfaces have remained untouched for ages.
Still, it is a good rule of thumb to use the "front door first" (see http://xunitpatterns.com/Principles%20of%20Test%20Automation.html). But keep in mind that it is called "front door first" and not "front door only".
C) Summary
Test also the implementation details. Prefer testing on stable interfaces (public or private). If implementation details change, also tests on the public API need to be revised. Turning something private into public does not magically change its stability.
A: You can also make your method package-private i.e. default and you should be able to unit test it unless it is required to be private.
A: Absolutely YES. That is the point of Unit testing, you test Units. Private method is a Unit. Without testing private methods TDD (Test Driven Development) would be impossible,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "396"
}
|
Q: Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function? A while ago I came across some code that marked a member variable of a class with the mutable keyword. As far as I can see it simply allows you to modify a variable in a const method:
class Foo
{
private:
mutable bool done_;
public:
void doSomething() const { ...; done_ = true; }
};
Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a boost::mutex as mutable allowing const functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.
A: Well, yeah, that's what it does. I use it for members that are modified by methods that do not logically change the state of a class - for instance, to speed up lookups by implementing a cache:
class CIniWrapper
{
public:
CIniWrapper(LPCTSTR szIniFile);
// non-const: logically modifies the state of the object
void SetValue(LPCTSTR szName, LPCTSTR szValue);
// const: does not logically change the object
LPCTSTR GetValue(LPCTSTR szName, LPCTSTR szDefaultValue) const;
// ...
private:
// cache, avoids going to disk when a named value is retrieved multiple times
// does not logically change the public interface, so declared mutable
// so that it can be used by the const GetValue() method
mutable std::map<string, string> m_mapNameToValue;
};
Now, you must use this with care - concurrency issues are a big concern, as a caller might assume that they are thread safe if only using const methods. And of course, modifying mutable data shouldn't change the behavior of the object in any significant fashion, something that could be violated by the example i gave if, for instance, it was expected that changes written to disk would be immediately visible to the app.
A: Mutable is used when you have a variable inside the class that is only used within that class to signal things like for example a mutex or a lock. This variable does not change the behaviour of the class, but is necessary in order to implement thread safety of the class itself. Thus if without "mutable", you would not be able to have "const" functions because this variable will need to be changed in all functions that are available to the outside world. Therefore, mutable was introduced in order to make a member variable writable even by a const function.
The mutable specified informs both the compiler and the reader that it
is safe and expected that a member variable may be modified within a const
member function.
A: Use "mutable" when for things that are LOGICALLY stateless to the user (and thus should have "const" getters in the public class' APIs) but are NOT stateless in the underlying IMPLEMENTATION (the code in your .cpp).
The cases I use it most frequently are lazy initialization of state-less "plain old data" members. Namely, it is ideal in the narrow cases when such members are expensive to either build (processor) or carry around (memory) and many users of the object will never ask for them. In that situation you want lazy construction on the back end for performance, since 90% of the objects built will never need to build them at all, yet you still need to present the correct stateless API for public consumption.
A: Your use with boost::mutex is exactly what this keyword is intended for. Another use is for internal result caching to speed access.
Basically, 'mutable' applies to any class attribute that does not affect the externally visible state of the object.
In the sample code in your question, mutable might be inappropriate if the value of done_ affects external state, it depends on what is in the ...; part.
A: mutable is mainly used on an implementation detail of the class. The user of the class doesn't need to know about it, therefore method's he thinks "should" be const can be. Your example of having a mutex be mutable is a good canonical example.
A: Your use of it isn't a hack, though like many things in C++, mutable can be hack for a lazy programmer who doesn't want to go all the way back and mark something that shouldn't be const as non-const.
A: Mutable changes the meaning of const from bitwise const to logical const for the class.
This means that classes with mutable members are longer be bitwise const and will no longer appear in read-only sections of the executable.
Furthermore, it modifies type-checking by allowing const member functions to change mutable members without using const_cast.
class Logical {
mutable int var;
public:
Logical(): var(0) {}
void set(int x) const { var = x; }
};
class Bitwise {
int var;
public:
Bitwise(): var(0) {}
void set(int x) const {
const_cast<Bitwise*>(this)->var = x;
}
};
const Logical logical; // Not put in read-only.
const Bitwise bitwise; // Likely put in read-only.
int main(void)
{
logical.set(5); // Well defined.
bitwise.set(5); // Undefined.
}
See the other answers for more details but I wanted to highlight that it isn't merely for type-saftey and that it affects the compiled result.
A: It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.
Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):
int x = 0;
auto f1 = [=]() mutable {x = 42;}; // OK
auto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda
A: Mutable is for marking specific attribute as modifiable from within const methods. That is its only purpose. Think carefully before using it, because your code will probably be cleaner and more readable if you change the design rather than use mutable.
http://www.highprogrammer.com/alan/rants/mutable.html
So if the above madness isn't what
mutable is for, what is it for? Here's
the subtle case: mutable is for the
case where an object is logically
constant, but in practice needs to
change. These cases are few and far
between, but they exist.
Examples the author gives include caching and temporary debugging variables.
A: It's useful in situations where you have hidden internal state such as a cache. For example:
class HashTable
{
...
public:
string lookup(string key) const
{
if(key == lastKey)
return lastValue;
string value = lookupInternal(key);
lastKey = key;
lastValue = value;
return value;
}
private:
mutable string lastKey, lastValue;
};
And then you can have a const HashTable object still use its lookup() method, which modifies the internal cache.
A: The mutable keyword is very useful when creating stubs for class test purposes. You can stub a const function and still be able to increase (mutable) counters or whatever test functionality you have added to your stub. This keeps the interface of the stubbed class intact.
A: The mutable can be handy when you are overriding a const virtual function and want to modify your child class member variable in that function. In most of the cases you would not want to alter the interface of the base class, so you have to use mutable member variable of your own.
A: The mutable keyword is a way to pierce the const veil you drape over your objects. If you have a const reference or pointer to an object, you cannot modify that object in any way except when and how it is marked mutable.
With your const reference or pointer you are constrained to:
*
*only read access for any visible data members
*permission to call only methods that are marked as const.
The mutable exception makes it so you can now write or set data members that are marked mutable. That's the only externally visible difference.
Internally those const methods that are visible to you can also write to data members that are marked mutable. Essentially the const veil is pierced comprehensively. It is completely up to the API designer to ensure that mutable doesn't destroy the const concept and is only used in useful special cases. The mutable keyword helps because it clearly marks data members that are subject to these special cases.
In practice you can use const obsessively throughout your codebase (you essentially want to "infect" your codebase with the const "disease"). In this world pointers and references are const with very few exceptions, yielding code that is easier to reason about and understand. For a interesting digression look up "referential transparency".
Without the mutable keyword you will eventually be forced to use const_cast to handle the various useful special cases it allows (caching, ref counting, debug data, etc.). Unfortunately const_cast is significantly more destructive than mutable because it forces the API client to destroy the const protection of the objects (s)he is using. Additionally it causes widespread const destruction: const_casting a const pointer or reference allows unfettered write and method calling access to visible members. In contrast mutable requires the API designer to exercise fine grained control over the const exceptions, and usually these exceptions are hidden in const methods operating on private data.
(N.B. I refer to to data and method visibility a few times. I'm talking about members marked as public vs. private or protected which is a totally different type of object protection discussed here.)
A: mutable does exist as you infer to allow one to modify data in an otherwise constant function.
The intent is that you might have a function that "does nothing" to the internal state of the object, and so you mark the function const, but you might really need to modify some of the objects state in ways that don't affect its correct functionality.
The keyword may act as a hint to the compiler -- a theoretical compiler could place a constant object (such as a global) in memory that was marked read-only. The presence of mutable hints that this should not be done.
Here are some valid reasons to declare and use mutable data:
*
*Thread safety. Declaring a mutable boost::mutex is perfectly reasonable.
*Statistics. Counting the number of calls to a function, given some or all of its arguments.
*Memoization. Computing some expensive answer, and then storing it for future reference rather than recomputing it again.
A: In some cases (like poorly designed iterators), the class needs to keep a count or some other incidental value, that doesn't really affect the major "state" of the class. This is most often where I see mutable used. Without mutable, you'd be forced to sacrifice the entire const-ness of your design.
It feels like a hack most of the time to me as well. Useful in a very very few situations.
A: The classic example (as mentioned in other answers) and the only situation I have seen the mutable keyword used in so far, is for caching the result of a complicated Get method, where the cache is implemented as a data member of the class and not as a static variable in the method (for reasons of sharing between several functions or plain cleanliness).
In general, the alternatives to using the mutable keyword are usually a static variable in the method or the const_cast trick.
Another detailed explanation is in here.
A: One of the best example where we use mutable is, in deep copy. in copy constructor we send const &obj as argument. So the new object created will be of constant type. If we want to change (mostly we won't change, in rare case we may change) the members in this newly created const object we need to declare it as mutable.
mutable storage class can be used only on non static non const data member of a class. Mutable data member of a class can be modified even if it's part of an object which is declared as const.
class Test
{
public:
Test(): x(1), y(1) {};
mutable int x;
int y;
};
int main()
{
const Test object;
object.x = 123;
//object.y = 123;
/*
* The above line if uncommented, will create compilation error.
*/
cout<< "X:"<< object.x << ", Y:" << object.y;
return 0;
}
Output:-
X:123, Y:1
In the above example, we are able to change the value of member variable x though it's part of an object which is declared as const. This is because the variable x is declared as mutable. But if you try to modify the value of member variable y, compiler will throw an error.
A: The very keyword 'mutable' is actually a reserved keyword.often it is used to vary the value of constant variable.If you want to have multiple values of a constsnt,use the keyword mutable.
//Prototype
class tag_name{
:
:
mutable var_name;
:
:
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "606"
}
|
Q: How do you resolve crashing Windbg Logger on Vista? I would like to use the Logger tool that ships with the Microsoft Debugging Tools for Windows. However, on Vista it crashes even with built-in Vista applications:
> logger calc
or
> logger notepad
The issue occurs if I run the tool from a command prompt with or without administrator rights. I'm using version 3.01 (3/20/2008).
The last thing the Logger output window shows is "Verbose log Enabled".
If I attach a debugger I see that an "Access violation writing location 0x000000" error has occurred with the following call stack:
logexts.dll!_LogGetCategory@20() + 0xb bytes
logger.exe!PopulateLogextsSettings() + 0x31 bytes
logger.exe!SettingsDlgProc() + 0x48 bytes
user32.dll!_InternalCallWinProc@20() + 0x23 bytes
user32.dll!_UserCallDlgProcCheckWow@32() - 0x19bc bytes
user32.dll!_DefDlgProcWorker@20() + 0x7f bytes
user32.dll!_DefDlgProcA@16() + 0x22 bytes
user32.dll!_InternalCallWinProc@20() + 0x23 bytes
user32.dll!_UserCallWinProcCheckWow@32() + 0xb3 bytes
user32.dll!_SendMessageWorker@20() + 0xd5 bytes
user32.dll!_InternalCreateDialog@28() + 0x700 bytes
user32.dll!_InternalDialogBox@24() + 0xa3 bytes
user32.dll!_DialogBoxIndirectParamAorW@24() + 0x36 bytes
user32.dll!_DialogBoxParamA@20() + 0x4c bytes
logger.exe!ChooseSettings() + 0x24 bytes
logger.exe!InitLogexts() + 0x84 bytes
logger.exe!DebuggerLoop() + 0x210 bytes
logger.exe!_WinMain@16() + 0x215 bytes
logger.exe!__initterm_e() + 0x1a1 bytes
kernel32.dll!@BaseThreadInitThunk@12() + 0x12 bytes
ntdll.dll!___RtlUserThreadStart@8() + 0x27 bytes
ntdll.dll!__RtlUserThreadStart@8() + 0x1b bytes
Anybody encountered this issue and know how to fix it?
A: I'm using 6.9.3.113 (April 29, 2008) of the debugging tools, and I don't get any problems on Vista. If I try running
logger notepad
it works OK (even as a non-admin). The first thing I would check is that if you're running the x64 version of Vista, you'll need to use the 64bit version of the debugging tools as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MSI installer: Adding multiple properties to SecureCustomProperties I'm looking for a way to add multiple properties to the SecureCustomProperties value in my .msi installer's property table. I've tried comma delimiting, semi-colon delimiting, and even space delimiters. None of the above seem to work.
Hints?
A: Ok, so I was almost there ... semi-colon delimited with NO SPACES. This appears to do the trick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you get total amount of RAM the computer has? Using C#, I want to get the total amount of RAM that my computer has.
With the PerformanceCounter I can get the amount of Available ram, by setting:
counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
But I can't seem to find a way to get the total amount of memory. How would I go about doing this?
Update:
MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.
A: you can simply use this code to get those information, just add the reference
using Microsoft.VisualBasic.Devices;
and the simply use the following code
private void button1_Click(object sender, EventArgs e)
{
getAvailableRAM();
}
public void getAvailableRAM()
{
ComputerInfo CI = new ComputerInfo();
ulong mem = ulong.Parse(CI.TotalPhysicalMemory.ToString());
richTextBox1.Text = (mem / (1024*1024) + " MB").ToString();
}
A: The Windows API function GlobalMemoryStatusEx can be called with p/invoke:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
}
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
Then use like:
ulong installedMemory;
MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if( GlobalMemoryStatusEx( memStatus))
{
installedMemory = memStatus.ullTotalPhys;
}
Or you can use WMI (managed but slower) to query TotalPhysicalMemory in the Win32_ComputerSystem class.
A: Add a reference to Microsoft.VisualBasic.dll, as someone mentioned above. Then getting total physical memory is as simple as this (yes, I tested it):
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
A: // use `/ 1048576` to get ram in MB
// and `/ (1048576 * 1024)` or `/ 1048576 / 1024` to get ram in GB
private static String getRAMsize()
{
ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject item in moc)
{
return Convert.ToString(Math.Round(Convert.ToDouble(item.Properties["TotalPhysicalMemory"].Value) / 1048576, 0)) + " MB";
}
return "RAMsize";
}
A: You could use 'WMI'.
I found a 'snippet'.
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
strMemory = objComputer.TotalPhysicalMemory
Next
A: All the answers here, including the accepted one, will give you the total amount of RAM available for use. And that may have been what OP wanted.
But if you are interested in getting the amount of installed RAM, then you'll want to make a call to the GetPhysicallyInstalledSystemMemory function.
From the link, in the Remarks section:
The GetPhysicallyInstalledSystemMemory function retrieves the amount of physically installed RAM from the computer's SMBIOS firmware tables. This can differ from the amount reported by the GlobalMemoryStatusEx function, which sets the ullTotalPhys member of the MEMORYSTATUSEX structure to the amount of physical memory that is available for the operating system to use. The amount of memory available to the operating system can be less than the amount of memory physically installed in the computer because the BIOS and some drivers may reserve memory as I/O regions for memory-mapped devices, making the memory unavailable to the operating system and applications.
Sample code:
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);
static void Main()
{
long memKb;
GetPhysicallyInstalledSystemMemory(out memKb);
Console.WriteLine((memKb / 1024 / 1024) + " GB of RAM installed.");
}
A: If you happen to be using Mono, then you might be interested to know that Mono 2.8 (to be released later this year) will have a performance counter which reports the physical memory size on all the platforms Mono runs on (including Windows). You would retrieve the value of the counter using this code snippet:
using System;
using System.Diagnostics;
class app
{
static void Main ()
{
var pc = new PerformanceCounter ("Mono Memory", "Total Physical Memory");
Console.WriteLine ("Physical RAM (bytes): {0}", pc.RawValue);
}
}
If you are interested in C code which provides the performance counter, it can be found here.
A: For those who are using .net Core 3.0 there is no need to use PInvoke platform in order to get the available physical memory. The GC class has added a new method GC.GetGCMemoryInfo that returns a GCMemoryInfo Struct with TotalAvailableMemoryBytes as a property. This property returns the total available memory for the garbage collector.(same value as MEMORYSTATUSEX)
var gcMemoryInfo = GC.GetGCMemoryInfo();
installedMemory = gcMemoryInfo.TotalAvailableMemoryBytes;
// it will give the size of memory in MB
var physicalMemory = (double) installedMemory / 1048576.0;
A: This function (ManagementQuery) works on Windows XP and later:
private static string ManagementQuery(string query, string parameter, string scope = null) {
string result = string.Empty;
var searcher = string.IsNullOrEmpty(scope) ? new ManagementObjectSearcher(query) : new ManagementObjectSearcher(scope, query);
foreach (var os in searcher.Get()) {
try {
result = os[parameter].ToString();
}
catch {
//ignore
}
if (!string.IsNullOrEmpty(result)) {
break;
}
}
return result;
}
Usage:
Console.WriteLine(BytesToMb(Convert.ToInt64(ManagementQuery("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem", "TotalPhysicalMemory", "root\\CIMV2"))));
A: Add a reference to Microsoft.VisualBasic and a using Microsoft.VisualBasic.Devices;.
The ComputerInfo class has all the information that you need.
A: Another way to do this, is by using the .NET System.Management querying facilities:
string Query = "SELECT Capacity FROM Win32_PhysicalMemory";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);
UInt64 Capacity = 0;
foreach (ManagementObject WniPART in searcher.Get())
{
Capacity += Convert.ToUInt64(WniPART.Properties["Capacity"].Value);
}
return Capacity;
A: Compatible with .Net and Mono (tested with Win10/FreeBSD/CentOS)
Using ComputerInfo source code and PerformanceCounters for Mono and as backup for .Net:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
public class SystemMemoryInfo
{
private readonly PerformanceCounter _monoAvailableMemoryCounter;
private readonly PerformanceCounter _monoTotalMemoryCounter;
private readonly PerformanceCounter _netAvailableMemoryCounter;
private ulong _availablePhysicalMemory;
private ulong _totalPhysicalMemory;
public SystemMemoryInfo()
{
try
{
if (PerformanceCounterCategory.Exists("Mono Memory"))
{
_monoAvailableMemoryCounter = new PerformanceCounter("Mono Memory", "Available Physical Memory");
_monoTotalMemoryCounter = new PerformanceCounter("Mono Memory", "Total Physical Memory");
}
else if (PerformanceCounterCategory.Exists("Memory"))
{
_netAvailableMemoryCounter = new PerformanceCounter("Memory", "Available Bytes");
}
}
catch
{
// ignored
}
}
public ulong AvailablePhysicalMemory
{
[SecurityCritical]
get
{
Refresh();
return _availablePhysicalMemory;
}
}
public ulong TotalPhysicalMemory
{
[SecurityCritical]
get
{
Refresh();
return _totalPhysicalMemory;
}
}
[SecurityCritical]
[DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);
[SecurityCritical]
[DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
[SecurityCritical]
private void Refresh()
{
try
{
if (_monoTotalMemoryCounter != null && _monoAvailableMemoryCounter != null)
{
_totalPhysicalMemory = (ulong) _monoTotalMemoryCounter.NextValue();
_availablePhysicalMemory = (ulong) _monoAvailableMemoryCounter.NextValue();
}
else if (Environment.OSVersion.Version.Major < 5)
{
var memoryStatus = MEMORYSTATUS.Init();
GlobalMemoryStatus(ref memoryStatus);
if (memoryStatus.dwTotalPhys > 0)
{
_availablePhysicalMemory = memoryStatus.dwAvailPhys;
_totalPhysicalMemory = memoryStatus.dwTotalPhys;
}
else if (_netAvailableMemoryCounter != null)
{
_availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
}
}
else
{
var memoryStatusEx = MEMORYSTATUSEX.Init();
if (GlobalMemoryStatusEx(ref memoryStatusEx))
{
_availablePhysicalMemory = memoryStatusEx.ullAvailPhys;
_totalPhysicalMemory = memoryStatusEx.ullTotalPhys;
}
else if (_netAvailableMemoryCounter != null)
{
_availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
}
}
}
catch
{
// ignored
}
}
private struct MEMORYSTATUS
{
private uint dwLength;
internal uint dwMemoryLoad;
internal uint dwTotalPhys;
internal uint dwAvailPhys;
internal uint dwTotalPageFile;
internal uint dwAvailPageFile;
internal uint dwTotalVirtual;
internal uint dwAvailVirtual;
public static MEMORYSTATUS Init()
{
return new MEMORYSTATUS
{
dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUS)))
};
}
}
private struct MEMORYSTATUSEX
{
private uint dwLength;
internal uint dwMemoryLoad;
internal ulong ullTotalPhys;
internal ulong ullAvailPhys;
internal ulong ullTotalPageFile;
internal ulong ullAvailPageFile;
internal ulong ullTotalVirtual;
internal ulong ullAvailVirtual;
internal ulong ullAvailExtendedVirtual;
public static MEMORYSTATUSEX Init()
{
return new MEMORYSTATUSEX
{
dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUSEX)))
};
}
}
}
A: .NET has a memory amount limit that it can access.
In Windows XP 2GB was the "hard ceiling".
For instance: You could have 4 GB in it, and it would kill the app when it hit 2GB.
Also in 64 bit mode, there is a percentage of memory you can use out of the system, so I'm not sure if you can ask for the whole thing or if this is specifically guarded against.
A: Nobody has mentioned GetPerformanceInfo yet. PInvoke signatures are available.
This function makes the following system-wide information available:
*
*CommitTotal
*CommitLimit
*CommitPeak
*PhysicalTotal
*PhysicalAvailable
*SystemCache
*KernelTotal
*KernelPaged
*KernelNonpaged
*PageSize
*HandleCount
*ProcessCount
*ThreadCount
PhysicalTotal is what the OP is looking for, although the value is the number of pages, so to convert to bytes, multiply by the PageSize value returned.
A: Solution working on Linux (.Net Core).
Inspired by GitHub/Hardware.Info.
Optimized to have minimal memory allocation and avg retrieval takes 0.020 ms.
private static readonly object _linuxMemoryLock = new();
private static readonly char[] _arrayForMemInfoRead = new char[200];
public static void GetBytesCountOnLinux(out ulong availableBytes, out ulong totalBytes)
{
lock (_linuxMemoryLock) // lock because of reusing static fields due to optimization
{
totalBytes = GetBytesCountFromLinuxMemInfo(token: "MemTotal:", refreshFromFile: true);
availableBytes = GetBytesCountFromLinuxMemInfo(token: "MemAvailable:", refreshFromFile: false);
}
}
private static ulong GetBytesCountFromLinuxMemInfo(string token, bool refreshFromFile)
{
// NOTE: Using the linux file /proc/meminfo which is refreshed frequently and starts with:
//MemTotal: 7837208 kB
//MemFree: 190612 kB
//MemAvailable: 5657580 kB
var readSpan = _arrayForMemInfoRead.AsSpan();
if (refreshFromFile)
{
using var fileStream = new FileStream("/proc/meminfo", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(fileStream, Encoding.UTF8, leaveOpen: true);
reader.ReadBlock(readSpan);
}
var tokenIndex = readSpan.IndexOf(token);
var fromTokenSpan = readSpan.Slice(tokenIndex + token.Length);
var kbIndex = fromTokenSpan.IndexOf("kB");
var notTrimmedSpan = fromTokenSpan.Slice(0, kbIndex);
var trimmedSpan = notTrimmedSpan.Trim(' ');
var kBytesCount = ulong.Parse(trimmedSpan);
var bytesCount = kBytesCount * 1024;
return bytesCount;
}
Linux and Windows together - for easy copy paste. Windows code taken from the accepted answer.
public static void GetRamBytes(out ulong availableBytes, out ulong totalBytes)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
GetBytesCountOnLinux(out availableBytes, out totalBytes);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
GetBytesCountOnWindows(out availableBytes, out totalBytes);
}
else
{
throw new NotImplementedException("Not implemented for OS: " + Environment.OSVersion);
}
}
private static readonly object _winMemoryLock = new();
private static readonly MEMORYSTATUSEX _memStatus = new();
private static void GetBytesCountOnWindows(out ulong availableBytes, out ulong totalBytes)
{
lock (_winMemoryLock) // lock because of reusing the static class _memStatus
{
GlobalMemoryStatusEx(_memStatus);
availableBytes = _memStatus.ullAvailPhys;
totalBytes = _memStatus.ullTotalPhys;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
}
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool GlobalMemoryStatusEx([In] [Out] MEMORYSTATUSEX lpBuffer);
A: /*The simplest way to get/display total physical memory in VB.net (Tested)
public sub get_total_physical_mem()
dim total_physical_memory as integer
total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))
MsgBox("Total Physical Memory" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + "Mb" )
end sub
*/
//The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)
public void get_total_physical_mem()
{
int total_physical_memory = 0;
total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024));
Interaction.MsgBox("Total Physical Memory" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + "Mb");
}
A: var ram = new ManagementObjectSearcher("select * from Win32_PhysicalMemory") .Get().Cast<ManagementObject>().First();
|
var a = Convert.ToInt64(ram["Capacity"]) / 1024 / 1024 / 1024;
(richiede System.Managment.dll come riferimento, testato su C# con Framework 4.7.2)
questa procedura salva in "a" la ram totale presente in GB
ulong memory() { return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory; }
|
var b = Convert.ToDecimal(memory()) / 1024 / 1024 / 1024;
(richiede Microsoft.VisualBasics.dll come riferimento, testato su C# Framework 4.7.2)
questa procedura salva in "b" il valore della ram in GB effettivamente disponibile
A: Here is another, much more simply way, using .net:
// total memory
long totalPhysicalMemory = My.Computer.Info.TotalPhysicalMemory;
// unused memory
long availablePhysicalMemory = My.Computer.Info.AvailablePhysicalMemory;
// used memory
long usedMemory = totalPhysicalMemory - availablePhysicalMemory;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
}
|
Q: How do I create a GUID / UUID? How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.
I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.
A: I really like how clean Broofa's answer is, but it's unfortunate that poor implementations of Math.random leave the chance for collision.
Here's a similar RFC4122 version 4 compliant solution that solves that issue by offsetting the first 13 hex numbers by a hex portion of the timestamp, and once depleted offsets by a hex portion of the microseconds since pageload. That way, even if Math.random is on the same seed, both clients would have to generate the UUID the exact same number of microseconds since pageload (if high-perfomance time is supported) AND at the exact same millisecond (or 10,000+ years later) to get the same UUID:
function generateUUID() { // Public Domain/MIT
var d = new Date().getTime();//Timestamp
var d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16;//random number between 0 and 16
if(d > 0){//Use timestamp until depleted
r = (d + r)%16 | 0;
d = Math.floor(d/16);
} else {//Use microseconds since page-load if supported
r = (d2 + r)%16 | 0;
d2 = Math.floor(d2/16);
}
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
var onClick = function(){
document.getElementById('uuid').textContent = generateUUID();
}
onClick();
#uuid { font-family: monospace; font-size: 1.5em; }
<p id="uuid"></p>
<button id="generateUUID" onclick="onClick();">Generate UUID</button>
Here's a fiddle to test.
Modernized snippet for ES6
const generateUUID = () => {
let
d = new Date().getTime(),
d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now() * 1000)) || 0;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
let r = Math.random() * 16;
if (d > 0) {
r = (d + r) % 16 | 0;
d = Math.floor(d / 16);
} else {
r = (d2 + r) % 16 | 0;
d2 = Math.floor(d2 / 16);
}
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
};
const onClick = (e) => document.getElementById('uuid').textContent = generateUUID();
document.getElementById('generateUUID').addEventListener('click', onClick);
onClick();
#uuid { font-family: monospace; font-size: 1.5em; }
<p id="uuid"></p>
<button id="generateUUID">Generate UUID</button>
A: Here is a totally non-compliant but very performant implementation to generate an ASCII-safe GUID-like unique identifier.
function generateQuickGuid() {
return Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);
}
Generates 26 [a-z0-9] characters, yielding a UID that is both shorter and more unique than RFC compliant GUIDs. Dashes can be trivially added if human-readability matters.
Here are usage examples and timings for this function and several of this question's other answers. The timing was performed under Chrome m25, 10 million iterations each.
>>> generateQuickGuid()
"nvcjf1hs7tf8yyk4lmlijqkuo9"
"yq6gipxqta4kui8z05tgh9qeel"
"36dh5sec7zdj90sk2rx7pjswi2"
runtime: 32.5s
>>> GUID() // John Millikin
"7a342ca2-e79f-528e-6302-8f901b0b6888"
runtime: 57.8s
>>> regexGuid() // broofa
"396e0c46-09e4-4b19-97db-bd423774a4b3"
runtime: 91.2s
>>> createUUID() // Kevin Hakanson
"403aa1ab-9f70-44ec-bc08-5d5ac56bd8a5"
runtime: 65.9s
>>> UUIDv4() // Jed Schmidt
"f4d7d31f-fa83-431a-b30c-3e6cc37cc6ee"
runtime: 282.4s
>>> Math.uuid() // broofa
"5BD52F55-E68F-40FC-93C2-90EE069CE545"
runtime: 225.8s
>>> Math.uuidFast() // broofa
"6CB97A68-23A2-473E-B75B-11263781BBE6"
runtime: 92.0s
>>> Math.uuidCompact() // broofa
"3d7b7a06-0a67-4b67-825c-e5c43ff8c1e8"
runtime: 229.0s
>>> bitwiseGUID() // jablko
"baeaa2f-7587-4ff1-af23-eeab3e92"
runtime: 79.6s
>>>> betterWayGUID() // Andrea Turri
"383585b0-9753-498d-99c3-416582e9662c"
runtime: 60.0s
>>>> UUID() // John Fowler
"855f997b-4369-4cdb-b7c9-7142ceaf39e8"
runtime: 62.2s
Here is the timing code.
var r;
console.time('t');
for (var i = 0; i < 10000000; i++) {
r = FuncToTest();
};
console.timeEnd('t');
A: From sagi shkedy's technical blog:
function generateGuid() {
var result, i, j;
result = '';
for(j=0; j<32; j++) {
if( j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random()*16).toString(16).toUpperCase();
result = result + i;
}
return result;
}
There are other methods that involve using an ActiveX control, but stay away from these!
I thought it was worth pointing out that no GUID generator can guarantee unique keys (check the Wikipedia article). There is always a chance of collisions. A GUID simply offers a large enough universe of keys to reduce the change of collisions to almost nil.
A: It is important to use well-tested code that is maintained by more than one contributor instead of whipping your own stuff for this.
This is one of the places where you probably want to prefer the most stable code than the shortest possible clever version that works in X browser, but doesn't take in to account idiosyncrasies of Y which would often lead to very-hard-to-investigate bugs than manifests only randomly for some users. Personally I use uuid-js at https://github.com/aurigadl/uuid-js which is Bower enabled so I can take updates easily.
A: The most simple function to do this:
function createGuid(){
let S4 = () => Math.floor((1+Math.random())*0x10000).toString(16).substring(1);
let guid = `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
return guid.toLowerCase();
}
A: Here is a combination of the top voted answer, with a workaround for Chrome's collisions:
generateGUID = (typeof(window.crypto) != 'undefined' &&
typeof(window.crypto.getRandomValues) != 'undefined') ?
function() {
// If we have a cryptographically secure PRNG, use that
// https://stackoverflow.com/questions/6906916/collisions-when-generating-uuids-in-javascript
var buf = new Uint16Array(8);
window.crypto.getRandomValues(buf);
var S4 = function(num) {
var ret = num.toString(16);
while(ret.length < 4){
ret = "0"+ret;
}
return ret;
};
return (S4(buf[0])+S4(buf[1])+"-"+S4(buf[2])+"-"+S4(buf[3])+"-"+S4(buf[4])+"-"+S4(buf[5])+S4(buf[6])+S4(buf[7]));
}
:
function() {
// Otherwise, just use Math.random
// https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
It is on jsbin if you want to test it.
A: Here's a solution dated Oct. 9, 2011 from a comment by user jed at https://gist.github.com/982883:
UUIDv4 = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}
This accomplishes the same goal as the current highest-rated answer, but in 50+ fewer bytes by exploiting coercion, recursion, and exponential notation. For those curious how it works, here's the annotated form of an older version of the function:
UUIDv4 =
function b(
a // placeholder
){
return a // if the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
Math.random() // in which case
* 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
b // random hex digits
)
}
A: You could use the npm package guid, a GUID generator and validator.
Example:
Guid.raw();
// -> '6fdf6ffc-ed77-94fa-407e-a7b86ed9e59d'
Note: This package has been deprecated. Use uuid instead.
Example:
const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a'
A: A TypeScript version of broofa's update from 2017-06-28, based on crypto API:
function genUUID() {
// Reference: https://stackoverflow.com/a/2117523/709884
return ("10000000-1000-4000-8000-100000000000").replace(/[018]/g, s => {
const c = Number.parseInt(s, 10)
return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
})
}
Reasons:
*
*Use of + between number[] and number isn't valid
*The conversion from string to number has to be explicit
A: There are many correct answers here, but sadly, included code samples are quite cryptic and difficult to understand. This is how I create version 4 (random) UUIDs.
Note that following pieces of code make use of binary literals for improved readability, thus require ECMAScript 6.
Node.js version
function uuid4() {
let array = new Uint8Array(16)
crypto.randomFillSync(array)
// Manipulate the 9th byte
array[8] &= 0b00111111 // Clear the first two bits
array[8] |= 0b10000000 // Set the first two bits to 10
// Manipulate the 7th byte
array[6] &= 0b00001111 // Clear the first four bits
array[6] |= 0b01000000 // Set the first four bits to 0100
const pattern = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
let idx = 0
return pattern.replace(
/XX/g,
() => array[idx++].toString(16).padStart(2, "0"), // padStart ensures a leading zero, if needed
)
}
Browser version
Only the second line is different.
function uuid4() {
let array = new Uint8Array(16)
crypto.getRandomValues(array)
// Manipulate the 9th byte
array[8] &= 0b00111111 // Clear the first two bits
array[8] |= 0b10000000 // Set the first two bits to 10
// Manipulate the 7th byte
array[6] &= 0b00001111 // Clear the first four bits
array[6] |= 0b01000000 // Set the first four bits to 0100
const pattern = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
let idx = 0
return pattern.replace(
/XX/g,
() => array[idx++].toString(16).padStart(2, "0"), // padStart ensures a leading zero, if needed
)
}
Tests
And finally, corresponding tests (Jasmine).
describe(".uuid4()", function() {
it("returns a UUIDv4 string", function() {
const uuidPattern = "XXXXXXXX-XXXX-4XXX-YXXX-XXXXXXXXXXXX"
const uuidPatternRx = new RegExp(uuidPattern.
replaceAll("X", "[0-9a-f]").
replaceAll("Y", "[89ab]"))
for (let attempt = 0; attempt < 1000; attempt++) {
let retval = uuid4()
expect(retval.length).toEqual(36)
expect(retval).toMatch(uuidPatternRx)
}
})
})
UUID v4 explained
A very good explanation of UUID version 4 is here: Generate a UUID compliant with RFC 4122.
Final notes
Also, there are plenty of third-party packages. However, as long as you have just basic needs, I don't recommend them. Really, there is not much to win and pretty much to lose. Authors may pursue for tiniest bits of performance, "fix" things which aren't supposed to be fixed, and when it comes to security, it is a risky idea. Similarly, they may introduce other bugs or incompatibilities. Careful updates require time.
A: You can use node-uuid. It provides simple, fast generation of RFC4122 UUIDS.
Features:
*
*Generate RFC4122 version 1 or version 4 UUIDs
*Runs in Node.js and browsers.
*Cryptographically strong random # generation on supporting platforms.
*Small footprint (Want something smaller? Check this out!)
Install Using NPM:
npm install uuid
Or using uuid via a browser:
Download Raw File (uuid v1): https://raw.githubusercontent.com/kelektiv/node-uuid/master/v1.js
Download Raw File (uuid v4): https://raw.githubusercontent.com/kelektiv/node-uuid/master/v4.js
Want even smaller? Check this out: https://gist.github.com/jed/982883
Usage:
// Generate a v1 UUID (time-based)
const uuidV1 = require('uuid/v1');
uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
// Generate a v4 UUID (random)
const uuidV4 = require('uuid/v4');
uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
// Generate a v5 UUID (namespace)
const uuidV5 = require('uuid/v5');
// ... using predefined DNS namespace (for domain names)
uuidV5('hello.example.com', v5.DNS)); // -> 'fdda765f-fc57-5604-a269-52a7df8164ec'
// ... using predefined URL namespace (for, well, URLs)
uuidV5('http://example.com/hello', v5.URL); // -> '3bbcee75-cecc-5b56-8031-b6641c1ed1f1'
// ... using a custom namespace
const MY_NAMESPACE = '(previously generated unique uuid string)';
uuidV5('hello', MY_NAMESPACE); // -> '90123e1c-7512-523e-bb28-76fab9f2f73d'
ECMAScript 2015 (ES6):
import uuid from 'uuid/v4';
const id = uuid();
A: broofa's answer is pretty slick, indeed - impressively clever, really... RFC4122 compliant, somewhat readable, and compact. Awesome!
But if you're looking at that regular expression, those many replace() callbacks, toString()'s and Math.random() function calls (where he's only using four bits of the result and wasting the rest), you may start to wonder about performance. Indeed, joelpt even decided to toss out an RFC for generic GUID speed with generateQuickGUID.
But, can we get speed and RFC compliance? I say, YES! Can we maintain readability? Well... Not really, but it's easy if you follow along.
But first, my results, compared to broofa, guid (the accepted answer), and the non-rfc-compliant generateQuickGuid:
Desktop Android
broofa: 1617ms 12869ms
e1: 636ms 5778ms
e2: 606ms 4754ms
e3: 364ms 3003ms
e4: 329ms 2015ms
e5: 147ms 1156ms
e6: 146ms 1035ms
e7: 105ms 726ms
guid: 962ms 10762ms
generateQuickGuid: 292ms 2961ms
- Note: 500k iterations, results will vary by browser/CPU.
So by my 6th iteration of optimizations, I beat the most popular answer by over 12 times, the accepted answer by over 9 times, and the fast-non-compliant answer by 2-3 times. And I'm still RFC 4122 compliant.
Interested in how? I've put the full source on http://jsfiddle.net/jcward/7hyaC/3/ and on https://jsben.ch/xczxS
For an explanation, let's start with broofa's code:
function broofa() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
console.log(broofa())
So it replaces x with any random hexadecimal digit, y with random data (except forcing the top two bits to 10 per the RFC spec), and the regex doesn't match the - or 4 characters, so he doesn't have to deal with them. Very, very slick.
The first thing to know is that function calls are expensive, as are regular expressions (though he only uses 1, it has 32 callbacks, one for each match, and in each of the 32 callbacks it calls Math.random() and v.toString(16)).
The first step toward performance is to eliminate the RegEx and its callback functions and use a simple loop instead. This means we have to deal with the - and 4 characters whereas broofa did not. Also, note that we can use String Array indexing to keep his slick String template architecture:
function e1() {
var u='',i=0;
while(i++<36) {
var c='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'[i-1],r=Math.random()*16|0,v=c=='x'?r:(r&0x3|0x8);
u+=(c=='-'||c=='4')?c:v.toString(16)
}
return u;
}
console.log(e1())
Basically, the same inner logic, except we check for - or 4, and using a while loop (instead of replace() callbacks) gets us an almost 3X improvement!
The next step is a small one on the desktop but makes a decent difference on mobile. Let's make fewer Math.random() calls and utilize all those random bits instead of throwing 87% of them away with a random buffer that gets shifted out each iteration. Let's also move that template definition out of the loop, just in case it helps:
function e2() {
var u='',m='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',i=0,rb=Math.random()*0xffffffff|0;
while(i++<36) {
var c=m[i-1],r=rb&0xf,v=c=='x'?r:(r&0x3|0x8);
u+=(c=='-'||c=='4')?c:v.toString(16);rb=i%8==0?Math.random()*0xffffffff|0:rb>>4
}
return u
}
console.log(e2())
This saves us 10-30% depending on platform. Not bad. But the next big step gets rid of the toString function calls altogether with an optimization classic - the look-up table. A simple 16-element lookup table will perform the job of toString(16) in much less time:
function e3() {
var h='0123456789abcdef';
var k='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
/* same as e4() below */
}
function e4() {
var h=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
var k=['x','x','x','x','x','x','x','x','-','x','x','x','x','-','4','x','x','x','-','y','x','x','x','-','x','x','x','x','x','x','x','x','x','x','x','x'];
var u='',i=0,rb=Math.random()*0xffffffff|0;
while(i++<36) {
var c=k[i-1],r=rb&0xf,v=c=='x'?r:(r&0x3|0x8);
u+=(c=='-'||c=='4')?c:h[v];rb=i%8==0?Math.random()*0xffffffff|0:rb>>4
}
return u
}
console.log(e4())
The next optimization is another classic. Since we're only handling four bits of output in each loop iteration, let's cut the number of loops in half and process eight bits in each iteration. This is tricky since we still have to handle the RFC compliant bit positions, but it's not too hard. We then have to make a larger lookup table (16x16, or 256) to store 0x00 - 0xFF, and we build it only once, outside the e5() function.
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
function e5() {
var k=['x','x','x','x','-','x','x','-','4','x','-','y','x','-','x','x','x','x','x','x'];
var u='',i=0,rb=Math.random()*0xffffffff|0;
while(i++<20) {
var c=k[i-1],r=rb&0xff,v=c=='x'?r:(c=='y'?(r&0x3f|0x80):(r&0xf|0x40));
u+=(c=='-')?c:lut[v];rb=i%4==0?Math.random()*0xffffffff|0:rb>>8
}
return u
}
console.log(e5())
I tried an e6() that processes 16-bits at a time, still using the 256-element LUT, and it showed the diminishing returns of optimization. Though it had fewer iterations, the inner logic was complicated by the increased processing, and it performed the same on desktop, and only ~10% faster on mobile.
The final optimization technique to apply - unroll the loop. Since we're looping a fixed number of times, we can technically write this all out by hand. I tried this once with a single random variable, r, that I kept reassigning, and performance tanked. But with four variables assigned random data up front, then using the lookup table, and applying the proper RFC bits, this version smokes them all:
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
function e7()
{
var d0 = Math.random()*0xffffffff|0;
var d1 = Math.random()*0xffffffff|0;
var d2 = Math.random()*0xffffffff|0;
var d3 = Math.random()*0xffffffff|0;
return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
}
console.log(e7())
Modualized: http://jcward.com/UUID.js - UUID.generate()
The funny thing is, generating 16 bytes of random data is the easy part. The whole trick is expressing it in string format with RFC compliance, and it's most tightly accomplished with 16 bytes of random data, an unrolled loop and lookup table.
I hope my logic is correct -- it's very easy to make a mistake in this kind of tedious bit work. But the outputs look good to me. I hope you enjoyed this mad ride through code optimization!
Be advised: my primary goal was to show and teach potential optimization strategies. Other answers cover important topics such as collisions and truly random numbers, which are important for generating good UUIDs.
A: [Edited 2021-10-16 to reflect latest best-practices for producing RFC4122-compliant UUIDs]
Most readers here will want to use the uuid module. It is well-tested and supported.
The crypto.randomUUID() function is an emerging standard that is supported in Node.js and an increasing number of browsers. However because new browser APIs are restricted to secure contexts this method is only available to pages served locally (localhost or 127.0.0.1) or over HTTPS. If you're interested in seeing this restriction lifted for crypto.randomUUID() you can follow this GitHub issue.
If neither of those work for you, there is this method (based on the original answer to this question):
function uuidv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
console.log(uuidv4());
Note: The use of any UUID generator that relies on Math.random() is strongly discouraged (including snippets featured in previous versions of this answer) for reasons best explained here. TL;DR: solutions based on Math.random() do not provide good uniqueness guarantees.
A: I'm using this below function:
function NewGuid()
{
var sGuid = "";
for (var i=0; i<32; i++)
{
sGuid += Math.floor(Math.random()*0xF).toString(0xF);
}
return sGuid;
}
A: A simple solution to generate a unique identification is to use a time token and add a random number to it. I prefer to prefix it with "uuid-".
The below function will generate a random string of type: uuid-14d93eb1b9b4533e6. One doesn't need to generate a 32-characters random string. A 16-character random string is more than sufficient in this case to provide the unique UUIDs in JavaScript.
var createUUID = function() {
return "uuid-" + ((new Date).getTime().toString(16) + Math.floor(1E7*Math.random()).toString(16));
}
A: This works for Node.js too, if you replace let buffer = new Uint8Array(); crypto.getRandomValues with let buffer = crypto.randomBytes(16)
It should beat most regular expression solutions in performance.
const hex = '0123456789ABCDEF'
let generateToken = function() {
let buffer = new Uint8Array(16)
crypto.getRandomValues(buffer)
buffer[6] = 0x40 | (buffer[6] & 0xF)
buffer[8] = 0x80 | (buffer[8] & 0xF)
let segments = []
for (let i = 0; i < 16; ++i) {
segments.push(hex[(buffer[i] >> 4 & 0xF)])
segments.push(hex[(buffer[i] >> 0 & 0xF)])
if (i == 3 || i == 5 || i == 7 || i == 9) {
segments.push('-')
}
}
return segments.join('')
}
for (let i = 0; i < 100; ++i) {
console.log(generateToken())
}
Performance charts (everybody loves them): jsbench
A: Just in case anyone dropping by Google is seeking a small utility library, ShortId meets all the requirements of this question. It allows specifying allowed characters and length, and guarantees non-sequential, non-repeating strings.
To make this more of a real answer, the core of that library uses the following logic to produce its short ids:
function encode(lookup, number) {
var loopCounter = 0;
var done;
var str = '';
while (!done) {
str = str + lookup( ( (number >> (4 * loopCounter)) & 0x0f ) | randomByte() );
done = number < (Math.pow(16, loopCounter + 1 ) );
loopCounter++;
}
return str;
}
/* Generates the short id */
function generate() {
var str = '';
var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001);
if (seconds === previousSeconds) {
counter++;
} else {
counter = 0;
previousSeconds = seconds;
}
str = str + encode(alphabet.lookup, version);
str = str + encode(alphabet.lookup, clusterWorkerId);
if (counter > 0) {
str = str + encode(alphabet.lookup, counter);
}
str = str + encode(alphabet.lookup, seconds);
return str;
}
I have not edited this to reflect only the most basic parts of this approach, so the above code includes some additional logic from the library. If you are curious about everything it is doing, take a look at the source: https://github.com/dylang/shortid/tree/master/lib
A: I found this script useful for creating GUIDs in JavaScript
https://github.com/addui/GUIDJS
var myGuid = GUID();
A: This creates a version 4 UUID (created from pseudo random numbers):
function uuid()
{
var chars = '0123456789abcdef'.split('');
var uuid = [], rnd = Math.random, r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4'; // version 4
for (var i = 0; i < 36; i++)
{
if (!uuid[i])
{
r = 0 | rnd()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
}
}
return uuid.join('');
}
Here is a sample of the UUIDs generated:
682db637-0f31-4847-9cdf-25ba9613a75c
97d19478-3ab2-4aa1-b8cc-a1c3540f54aa
2eed04c9-2692-456d-a0fd-51012f947136
A: var uuid = function() {
var buf = new Uint32Array(4);
window.crypto.getRandomValues(buf);
var idx = -1;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
idx++;
var r = (buf[idx>>3] >> ((idx%8)*4))&15;
var v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
This version is based on Briguy37's answer and some bitwise operators to extract nibble sized windows from the buffer.
It should adhere to the RFC Type 4 (random) schema, since I had problems last time parsing non-compliant UUIDs with Java's UUID.
A: One line solution using Blobs.
window.URL.createObjectURL(new Blob([])).substring(31);
The value at the end (31) depends on the length of the URL.
EDIT:
A more compact and universal solution, as suggested by rinogo:
URL.createObjectURL(new Blob([])).substr(-36);
A: Simple JavaScript module as a combination of best answers in this question.
var crypto = window.crypto || window.msCrypto || null; // IE11 fix
var Guid = Guid || (function() {
var EMPTY = '00000000-0000-0000-0000-000000000000';
var _padLeft = function(paddingString, width, replacementChar) {
return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' ');
};
var _s4 = function(number) {
var hexadecimalResult = number.toString(16);
return _padLeft(hexadecimalResult, 4, '0');
};
var _cryptoGuid = function() {
var buffer = new window.Uint16Array(8);
crypto.getRandomValues(buffer);
return [_s4(buffer[0]) + _s4(buffer[1]), _s4(buffer[2]), _s4(buffer[3]), _s4(buffer[4]), _s4(buffer[5]) + _s4(buffer[6]) + _s4(buffer[7])].join('-');
};
var _guid = function() {
var currentDateMilliseconds = new Date().getTime();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(currentChar) {
var randomChar = (currentDateMilliseconds + Math.random() * 16) % 16 | 0;
currentDateMilliseconds = Math.floor(currentDateMilliseconds / 16);
return (currentChar === 'x' ? randomChar : (randomChar & 0x7 | 0x8)).toString(16);
});
};
var create = function() {
var hasCrypto = crypto != 'undefined' && crypto !== null,
hasRandomValues = typeof(window.crypto.getRandomValues) != 'undefined';
return (hasCrypto && hasRandomValues) ? _cryptoGuid() : _guid();
};
return {
newGuid: create,
empty: EMPTY
};
})();
// DEMO: Create and show GUID
console.log('1. New Guid: ' + Guid.newGuid());
// DEMO: Show empty GUID
console.log('2. Empty Guid: ' + Guid.empty);
Usage:
Guid.newGuid()
"c6c2d12f-d76b-5739-e551-07e6de5b0807"
Guid.empty
"00000000-0000-0000-0000-000000000000"
A: Here you can find a very small function that generates UUIDs.
One of the final versions is:
function b(
a // Placeholder
){
var cryptoObj = window.crypto || window.msCrypto; // For Internet Explorer 11
return a // If the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
cryptoObj.getRandomValues(new Uint8Array(1))[0] // in which case
% 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // Replacing
/[018]/g, // zeroes, ones, and eights with
b // random hex digits
)
}
A: Based on the work of broofa, I've added some more randomness by adding the timestamp to math.random():
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = parseFloat('0.' + Math.random().toString().replace('0.', '') + new Date().getTime()) * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
A: The UUID currently has a proposal for addition to the standard library and can be supported here ECMAScript proposal: JavaScript standard library UUID
The proposal encompasses having UUID as the following:
// We're not yet certain as to how the API will be accessed (whether it's in the global, or a
// future built-in module), and this will be part of the investigative process as we continue
// working on the proposal.
uuid(); // "52e6953d-edbe-4953-be2e-65ed3836b2f0"
This implementation follows the same layout as the V4 random UUID generation found here: https://www.npmjs.com/package/uuid
const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
I think it's noteworthy to understand how much bandwidth could be saved by this having an official implementation in the standard library. The authors of the proposal have also noted:
The 12 kB uuid module is downloaded from npm > 62,000,000 times a month (June 2019); making it available in the standard library eventually saves TBs of bandwidth globally. If we continue to address user needs, such as uuid, with the standard library, bandwidth savings add up.
A: I've built on everything mentioned here to produce something twice as fast, portable all environments, including node, and upgraded from Math.random() to crypto-strength randomness. You might not think UUID needs crypto strength, but what that means is even less chance of a collision, which is the entire point of a UUID.
function random() {
const
fourBytesOn = 0xffffffff, // 4 bytes, all 32 bits on: 4294967295
c = typeof crypto === "object"
? crypto // Node.js or most browsers
: typeof msCrypto === "object" // Stinky non-standard Internet Explorer
? msCrypto // eslint-disable-line no-undef
: null; // What old or bad environment are we running in?
return c
? c.randomBytes
? parseInt(c.randomBytes(4).toString("hex"), 16) / (fourBytesOn + 1) - Number.EPSILON // Node.js
: c.getRandomValues(new Uint32Array(1))[0] / (fourBytesOn + 1) - Number.EPSILON // Browsers
: Math.random();
}
function uuidV4() { // eslint-disable-line complexity
// If possible, generate a single random value, 128 bits (16 bytes)
// in length. In an environment where that is not possible, generate
// and make use of four 32-bit (4-byte) random values.
// Use crypto-grade randomness when available, else Math.random()
const
c = typeof crypto === "object"
? crypto // Node.js or most browsers
: typeof msCrypto === "object" // Stinky non-standard Internet Explorer
? msCrypto // eslint-disable-line no-undef
: null; // What old or bad environment are we running in?
let
byteArray = c
? c.randomBytes
? c.randomBytes(16) // Node.js
: c.getRandomValues(new Uint8Array(16)) // Browsers
: null,
uuid = [ ];
/* eslint-disable no-bitwise */
if ( ! byteArray) { // No support for generating 16 random bytes
// in one shot -- this will be slower
const
int = [
random() * 0xffffffff | 0,
random() * 0xffffffff | 0,
random() * 0xffffffff | 0,
random() * 0xffffffff | 0
];
byteArray = [ ];
for (let i = 0; i < 256; i++) {
byteArray[i] = int[i < 4 ? 0 : i < 8 ? 1 : i < 12 ? 2 : 3] >> i % 4 * 8 & 0xff;
}
}
byteArray[6] = byteArray[6] & 0x0f | 0x40; // Always 4, per RFC, indicating the version
byteArray[8] = byteArray[8] & 0x3f | 0x80; // Constrained to [89ab], per RFC for version 4
for (let i = 0; i < 16; ++i) {
uuid[i] = (byteArray[i] < 16 ? "0" : "") + byteArray[i].toString(16);
}
uuid =
uuid[ 0] + uuid[ 1] + uuid[ 2] + uuid[ 3] + "-" +
uuid[ 4] + uuid[ 5] + "-" +
uuid[ 6] + uuid[ 7] + "-" +
uuid[ 8] + uuid[ 9] + "-" +
uuid[10] + uuid[11] + uuid[12] + uuid[13] + uuid[14] + uuid[15];
return uuid;
/* eslint-enable no-bitwise */
}
A: Here is a function that generates a static UUID from a string or a random UUID if no string supplied:
function stringToUUID (str)
{
if (str === undefined || !str.length)
str = "" + Math.random() * new Date().getTime() + Math.random();
let c = 0,
r = "";
for (let i = 0; i < str.length; i++)
c = (c + (str.charCodeAt(i) * (i + 1) - 1)) & 0xfffffffffffff;
str = str.substr(str.length / 2) + c.toString(16) + str.substr(0, str.length / 2);
for(let i = 0, p = c + str.length; i < 32; i++)
{
if (i == 8 || i == 12 || i == 16 || i == 20)
r += "-";
c = p = (str[(i ** i + p + 1) % str.length]).charCodeAt(0) + p + i;
if (i == 12)
c = (c % 5) + 1; //1-5
else if (i == 16)
c = (c % 4) + 8; //8-B
else
c %= 16; //0-F
r += c.toString(16);
}
return r;
}
console.log("Random :", stringToUUID());
console.log("Static [1234]:", stringToUUID("1234")); //29c2c73b-52de-4344-9cf6-e6da61cb8656
console.log("Static [test]:", stringToUUID("test")); //e39092c6-1dbb-3ce0-ad3a-2a41db98778c
jsfiddle
A: Easy to do with a simple uuid package
https://www.npmjs.com/package/uuid
const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
A: The version below is an adaptation of broofa's answer, but updated to include a "true" random function that uses crypto libraries where available, and the Alea() function as a fallback.
Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }
Math.trueRandom = (function() {
var crypt = window.crypto || window.msCrypto;
if (crypt && crypt.getRandomValues) {
// If we have a crypto library, use it
var random = function(min, max) {
var rval = 0;
var range = max - min;
if (range < 2) {
return min;
}
var bits_needed = Math.ceil(Math.log2(range));
if (bits_needed > 53) {
throw new Exception("We cannot generate numbers larger than 53 bits.");
}
var bytes_needed = Math.ceil(bits_needed / 8);
var mask = Math.pow(2, bits_needed) - 1;
// 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111
// Create byte array and fill with N random numbers
var byteArray = new Uint8Array(bytes_needed);
crypt.getRandomValues(byteArray);
var p = (bytes_needed - 1) * 8;
for(var i = 0; i < bytes_needed; i++ ) {
rval += byteArray[i] * Math.pow(2, p);
p -= 8;
}
// Use & to apply the mask and reduce the number of recursive lookups
rval = rval & mask;
if (rval >= range) {
// Integer out of acceptable range
return random(min, max);
}
// Return an integer that falls within the range
return min + rval;
}
return function() {
var r = random(0, 1000000000) / 1000000000;
return r;
};
} else {
// From https://web.archive.org/web/20120502223108/http://baagoe.com/en/RandomMusings/javascript/
// Johannes Baagøe <baagoe@baagoe.com>, 2010
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
mash.version = 'Mash 0.9';
return mash;
}
// From http://baagoe.com/en/RandomMusings/javascript/
function Alea() {
return (function(args) {
// Johannes Baagøe <baagoe@baagoe.com>, 2010
var s0 = 0;
var s1 = 0;
var s2 = 0;
var c = 1;
if (args.length == 0) {
args = [+new Date()];
}
var mash = Mash();
s0 = mash(' ');
s1 = mash(' ');
s2 = mash(' ');
for (var i = 0; i < args.length; i++) {
s0 -= mash(args[i]);
if (s0 < 0) {
s0 += 1;
}
s1 -= mash(args[i]);
if (s1 < 0) {
s1 += 1;
}
s2 -= mash(args[i]);
if (s2 < 0) {
s2 += 1;
}
}
mash = null;
var random = function() {
var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
s0 = s1;
s1 = s2;
return s2 = t - (c = t | 0);
};
random.uint32 = function() {
return random() * 0x100000000; // 2^32
};
random.fract53 = function() {
return random() +
(random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
random.version = 'Alea 0.9';
random.args = args;
return random;
}(Array.prototype.slice.call(arguments)));
};
return Alea();
}
}());
Math.guid = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.trueRandom() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
A: JavaScript project on GitHub - https://github.com/LiosK/UUID.js
UUID.js The RFC-compliant UUID generator for JavaScript.
See RFC 4122 http://www.ietf.org/rfc/rfc4122.txt.
Features Generates RFC 4122 compliant UUIDs.
Version 4 UUIDs (UUIDs from random numbers) and version 1 UUIDs
(time-based UUIDs) are available.
UUID object allows a variety of access to the UUID including access to
the UUID fields.
Low timestamp resolution of JavaScript is compensated by random
numbers.
A: UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122, are identifiers designed to provide certain uniqueness guarantees.
While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see @broofa's answer, below) there are several common pitfalls:
*
*Invalid id format (UUIDs must be of the form "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]
*Use of a low-quality source of randomness (such as Math.random)
Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.
A: // RFC 4122
//
// A UUID is 128 bits long
//
// String representation is five fields of 4, 2, 2, 2, and 6 bytes.
// Fields represented as lowercase, zero-filled, hexadecimal strings, and
// are separated by dash characters
//
// A version 4 UUID is generated by setting all but six bits to randomly
// chosen values
var uuid = [
Math.random().toString(16).slice(2, 10),
Math.random().toString(16).slice(2, 6),
// Set the four most significant bits (bits 12 through 15) of the
// time_hi_and_version field to the 4-bit version number from Section
// 4.1.3
(Math.random() * .0625 /* 0x.1 */ + .25 /* 0x.4 */).toString(16).slice(2, 6),
// Set the two most significant bits (bits 6 and 7) of the
// clock_seq_hi_and_reserved to zero and one, respectively
(Math.random() * .25 /* 0x.4 */ + .5 /* 0x.8 */).toString(16).slice(2, 6),
Math.random().toString(16).slice(2, 14)].join('-');
A: Use:
let uniqueId = Date.now().toString(36) + Math.random().toString(36).substring(2);
document.getElementById("unique").innerHTML =
Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
<div id="unique">
</div>
If IDs are generated more than 1 millisecond apart, they are 100% unique.
If two IDs are generated at shorter intervals, and assuming that the random method is truly random, this would generate IDs that are 99.99999999999999% likely to be globally unique (collision in 1 of 10^15).
You can increase this number by adding more digits, but to generate 100% unique IDs you will need to use a global counter.
If you need RFC compatibility, this formatting will pass as a valid version 4 GUID:
let u = Date.now().toString(16) + Math.random().toString(16) + '0'.repeat(16);
let guid = [u.substr(0,8), u.substr(8,4), '4000-8' + u.substr(13,3), u.substr(16,12)].join('-');
let u = Date.now().toString(16)+Math.random().toString(16)+'0'.repeat(16);
let guid = [u.substr(0,8), u.substr(8,4), '4000-8' + u.substr(13,3), u.substr(16,12)].join('-');
document.getElementById("unique").innerHTML = guid;
<div id="unique">
</div>
The above code follow the intention, but not the letter of the RFC. Among other discrepancies it's a few random digits short. (Add more random digits if you need it) The upside is that this is really fast :)
You can test validity of your GUID here
A: Added in: v15.6.0, v14.17.0 there is a built-in crypto.randomUUID() function.
import * as crypto from "crypto";
const uuid = crypto.randomUUID();
In the browser, crypto.randomUUID() is currently supported in Chromium 92+ and Firefox 95+.
A: For my use case, I required id generation that was guaranteed to be unique globally; without exception. I struggled with the problem for a while, and came up with a solution called TUID (truly unique ID). It generates an id with the first 32 characters being system-generated and the remaining digits representing milliseconds since epoch. In situations where I need to generate id's in client-side JavaScript code, it works well.
A: Here is a working example. It generates a 32-digit unique UUID.
function generateUUID() {
var d = new Date();
var k = d.getTime();
var str = k.toString(16).slice(1)
var UUID = 'xxxx-xxxx-4xxx-yxxx-xzx'.replace(/[xy]/g, function (c)
{
var r = Math.random() * 16 | 0;
v = c == 'x' ? r : (r & 3 | 8);
return v.toString(16);
});
var newString = UUID.replace(/[z]/, str)
return newString;
}
var x = generateUUID()
console.log(x, x.length)
A: For those who are using JavaScript on Windows (e.g., Windows Script Host (WSH), CScript, and HTA). One can use ActiveX. Specifically, the Scriptlet.Typelib object:
WScript.Echo((new ActiveXObject("Scriptlet.TypeLib")).Guid)
Note that this answer only works on the technologies I listed. It will not work in any browser, not even Microsoft Edge! So, your mileage will vary with this answer.
A: We can use replace and crypto.getRandomValues to get an output like this:
xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx
If we are looking for an opti solution, we have to replace crypto.getRandomValues(new Uint8Array(1))[0] by an array(32).
const uuidv4 = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
console.log(uuidv4());
To get this code:
function uuidv4() {
let bytes = window.crypto.getRandomValues(new Uint8Array(32));
const randomBytes = () => (bytes = bytes.slice(1)) && bytes[0];
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ randomBytes() & 15 >> c / 4).toString(16)
);
}
for (var i = 0; i < 10; i++)
console.log(uuidv4());
Collision:
We can do like google analytics and add a timestamp with : uuidv4() + "." + (+new Date()).
A: UUID with timestamp built in (emitter/parser)
This is my simple approach to generating a valid UUID v4 with very strong uniqueness and fast runtime.
The basic idea is not new, but the approach is different. I use a timestamp in milliseconds from the date.now() (in the Node.js library, which I'll point later, I use nanoseconds timestamp from process.hrtime.bigint()), and then add a random 5 digit number (10000-90000) to the end of the timestamp string.
After merging the strings, I just form a valid UUID from digits and a pair of special characters, so that my UUID consists only of digits and a few non-numeric characters. Please check it out below:
/*
* uuid-timestamp (emitter)
* UUID v4 based on timestamp
*
* Created by tarkh
* tarkh.com (C) 2020
*/
const uuidEmit = () => {
// Get now time
const n = Date.now();
// Generate random
const r = Math.random();
// Stringify now time and generate additional random number
const s = String(n) + String(~~(r*9e4)+1e4);
// Form UUID and return it
return `${s.slice(0,8)}-${s.slice(8,12)}-4${s.slice(12,15)}-${[8,9,'a','b'][~~(r*3)]}${s.slice(15,18)}-${s.slice(s.length-12)}`;
};
// Generate 5 UUIDs
console.log(`${uuidEmit()}
${uuidEmit()}
${uuidEmit()}
${uuidEmit()}
${uuidEmit()}`);
Looking at the results, you obviously see that the first part of UUIDs is the same, and then comes randomness. This is because I inserted the timestamp into the UUID linearly. The code will produce a new UUID every millisecond (nanosecond in Node.js library) + add a random 5-digit number to the end, so we end up with very approximate collision probability around 1 in 10 million per second. If we use Node.js library, our very approximate collision probability goes to 1 in 10 billion per second.
Timestamp built into the UUID
Since we insert a timestamp into the UUID linearly, we get a feature (good or bad - depends on the task) - ability to easily extract this timestamp back from the UUID. This way we can understand when UUID was released:
/*
* uuid-timestamp (parser)
* UUID v4 based on timestamp
*
* Created by tarkh
* tarkh.com (C) 2020
*/
const uuidParse = (uuid) => {
// Get current timestamp string length
let tl = String(Date.now()).length;
// Strip out timestamp from UUID
let ts = '';
let i = -1;
while(tl--) {
i++;
if(i===8||i===13||i===14||i===18||i===19||i===23) {
tl++;
continue;
}
ts += uuid[i];
}
return Number(ts);
};
// Get the timestamp when UUID was emitted
const time = uuidParse('15970688-7109-4530-8114-887109530114');
// Covert timestamp to date and print it
console.log(new Date(time).toUTCString());
Node.js
The NPM version of my code above available as a Node.js module. This version is even more powerful in generating unique values, because instead of millisecond timestamp it uses nanoseconds from combination of system time and process.hrtime.bigint() diff.
Benchmarks
At the end of my post, I want to do some performance tests based on some of the answers from this topic. Of course, my decision is not the fastest, but it certainly takes the top positions.
Check jsBench here
A: Effectively, a GUID, or UUID as it is called in non-Microsoft-circles, is just a 128-Bit cryptographic random number, with the UUID version number (1-5) being at a fixed location byte.
So when you just generate a bunch of random numbers between 0 and 65535 and hex-encode them, like this:
function guid()
{
function s4()
{
return Math.floor(Math.random() * 65536).toString(16).padStart(4, '0')
} // End Function s4
return s4() + s4() + '-' + s4() + '-' + "4" + s4().substr(1) + '-' + s4() + '-' + s4() + s4() + s4();
} // End Function guid
You get a valid GUID, but due to the random-implementation, it's not cryptographically secure.
To generate a cryptographically secure GUID, you need to use window.crypto (or window.msCrypto for Internet Explorer).
That goes like this:
function cryptGuid()
{
var array = new Uint16Array(8);
(window.crypto || window.msCrypto).getRandomValues(array);
var dataView = new DataView(array.buffer);
var parts = [];
for(var i = 0; i < array.length; ++i)
{
// 0&1,2,3,4,5-7 dataView.getUint16(0-7)
if(i>1 && i<6) parts.push("-");
parts.push(dataView.getUint16(i).toString(16).padStart(4, '0'));
}
parts[5] = "4" + parts[5].substr(1);
// console.log(parts);
return parts.join('').toUpperCase();// .toLowerCase();
}
cryptGuid();
Plus you have to decide, if you return the number as lower-or upper-case character string.
Certain software require lowercase characters (e.g., Reporting Service), while others generate uppercase characters (SQL Server).
A: The following uuid implementation offers a different ES6 2020 solution using BigInt and focuses on "Use case intent for a uuid design pattern"; especially for use with indexedDb primaryKey scenarios where unifying sequencing in time and collation are valuable.
So, noting that this post has over 30 answers, here goes...
This post has:
*
*a "TL;DR" code section w/self-contained es6 class Xuid
*a use-case and motivations discussion section regarding the
es6 class Xuid provided code.
TL;DR class Xuid solution for generic v4 uuid using a monotonic clock
The code-below is extracted from Smallscript's EdgeS web-client library that I wrote and own and is provided here, freely MIT licensed. A GitHub version will be available once EdgeS web-client toolset is released.
Usage example:
eval: console.log(Xuid.v4New)
emits: {1eb4a659-8bdc-4ce0-c002-b1d505d38ea8}
class Xuid {
//@ edges.sm.st, ess.dev: MIT license Smallscript/David Simmons 2020
//! Can't use `static const field = const` xbrowser (thus, const's duped)
static get v4New() {
const ns7Now = this.ns7Now, xnode48 = this.xnode48; let clock_seq13
// monotonic `clock_seq` guarantee (13-bits/time-quantum)
if(ns7Now <= this.ns7Now_prevSeq && this.ns7Now_prevSeq)
clock_seq13 = ((this.ns7Now_prevSeq += 1n) - ns7Now) & 0b1_1111_1111_1111n
else
clock_seq13 = 0n, this.ns7Now_prevSeq = ns7Now
const time60 = ((ns7Now << 4n) & 0xFFFF_FFFF_FFFF_0000n) |
(ns7Now & 0x0000_0000_0000_0FFFn),
v4 = 0x1_00000000_0000_0000_0000_000000000000n |
(time60 << 64n) | (0x00000000_0000_4000_0000_000000000000n) | // M: V4
(0b110n << 61n) | (clock_seq13 << 48n) | // N: Variant-2 time-seq collation
xnode48, s = v4.toString(16)//.substr(1)
return `{${s.substr(1,8)}-${s.substr(9,4)}-${s.substr(13,4)}-${
s.substr(17,4)}-${s.substr(21,12)}}`
}
static get xnode48()/*:<BigInt#48>*/{
if(this.xnode48_) return this.xnode48_
let clockSeqNode; if(typeof URL !== 'undefined' && URL.createObjectURL) {
const url = URL.createObjectURL(new Blob())
const id = (url.toString().split('/').reverse()[0]).split('-')
URL.revokeObjectURL(url)
clockSeqNode = BigInt('0x'+id[3]+id[4])
}
else {
const a4 = this.a4; this.getRandomValues(this.a4);
clockSeqNode = (BigInt(a4[2]) << 32n) | BigInt(a4[3])
}
// simulate the 48-bit node-id and 13-bit clock-seq
// to combine with 3-bit uuid-variant
return this.xnode48_ = clockSeqNode & 0xFFFF_FFFF_FFFFn;
}
static get jdNow()/*:<double#ns7>*/{
// return 2440587.5+Date.now()/864e5 // <- Date-quantum-ms form (7ns form below)
return this.jdFromNs7(this.ns7Now)
}
static get ns7Now()/*:<BigInt#60>*/{
if(typeof performance !== 'undefined' && performance.now)
Reflect.defineProperty(this, 'ns7Now',
Reflect.getOwnPropertyDescriptor(this,'ns7Now_performance'))
else
Reflect.defineProperty(this, 'ns7Now',
Reflect.getOwnPropertyDescriptor(this, 'ns7Now_Date'))
return this.ns7Now
}
static get ns7Now_Date()/*:<BigInt#60>*/{
// const epoch1582Ns7_bias = 0x1b2_1dd2_1381_4000 // V1 1582 Oct 15
// const epoch1601Ns7_bias = 0x19d_b1de_d53e_8000n // FILETIME base
const epoch1970Ns7 = BigInt(Date.now() * 1000_0.0)
return epoch1970Ns7 + 0x1b2_1dd2_1381_4000n
}
static get ns7Now_performance()/*:<BigInt#60>*/{
const epochPgNs7 = BigInt(performance.now()*/*15*/1000_0.0|/*17*/0)
if(!this.epoch1970PgNs7) // performance.timing.navigationStart
this.epoch1970PgNs7 = this.ns7Now_Date - epochPgNs7
return epochPgNs7 + this.epoch1970PgNs7
}
static dateFromJd(jd) {return new Date((jd - 2440587.5) * 864e5)}
static dateFromNs7(ns7) {
return new Date(Number(ns7 - 0x1b2_1dd2_1381_4000n) / 1000_0.0)}
static jdFromNs7(ns7) { // atomic-clock leap-seconds (ignored)
return 2440587.5 + (Number(ns7 - 0x1b2_1dd2_1381_4000n) / 864e9)
}
static ns7FromJd(jd) {
return BigInt((jd - 2440587.5) * 864e9) + 0x1b2_1dd2_1381_4000n
}
static getRandomValues(va/*:<Uint32Array>*/) {
if(typeof crypto !== 'undefined' && crypto.getRandomValues)
crypto.getRandomValues(va)
else for(let i = 0, n = va.length; i < n; i += 1)
va[i] = Math.random() * 0x1_0000_0000 >>> 0
}
static get a4() {return this.a4_ || (this.a4_ = new Uint32Array(4))}
static ntohl(v)/*:<BigInt>*/{
let r = '0x', sign = 1n, s = BigInt(v).toString(16)
if(s[0] == '-') s = s.substr(1), sign = -1n
for(let i = s.length; i > 0; i -= 2)
r += (i == 1) ? ('0' + s[i-1]) : s[i-2] + s[i-1]
return sign*BigInt(r)
}
static ntohl32(v)/*:<Number>*/{return Number(this.ntohl(v))}
}
Motivation
While v4 uuid defines a basically random uuid, it is desirable to have a uuid implementation that can support some additional characteristics.
*
*creates new uuid values quickly and efficiently (using BigInt)
*implemented as stand-alone code with a nominal 80 loc readable class
w/comments
*incorporates uuid uniqueness using monotonic time within a context
*stringifies such that the string form:
*
*collates based on time and then context (using uuid Variant-2)
*converts back to a binary form that correctly identifies and recovers the time
*incorporates JavaScript micro-second clock accuracy where available
*supports cross-environment quantum of 100 nano-second units based on julian-day
epoch year 1582 Oct 15, V1 compatibility. Choices that enable unified time
behavior across a spectrum of environments and use cases consistent with
EdgeS and ESS language model.
Especially suited for database use with facilities like SQLite.
*uses es6 class design to simplify extensibility for nominal work to extend
it to provide other uuid variants
*for this posting, unified and incorporated basic time and related
eswc library APIs.
*
*Julian Day API
*ns7 (100 nano-second quantum) API
*ntohl API for endian convenience re-ordering BigInt string representations
*derived from QKS Smalltalk 1991, AOS® [Agile Object System;Agents Object System]
engine family technology for language, framework and runtimes it preserves
use case compatibility across a wide range of current and historical host OS
models.
*
*specifically where the Xuid curly-brace quoted scalar string format
supports guid, uuid, and uid (git, fossil, SqLite repo-id)
representations, FILETIME, etc.
as in: {1eb4a659-8bdc-4ce0-c002-b1d505d38ea8}
*last, but not least, it provides a desirable solution to working
with indexedDb object stores where using a uuid as the primaryKey
becomes desireable.
*
*enabling auto-sequencing capabilities
*natural string collation
*
*note the subtle use of uuid Variant-2 to reverse time value
of the LHS in its stringified form.
*natural and simple put updating
*natural pattern for efs (EdgeS virtual file-system auto-names)
*service-worker and cloud-server sync and replicate actions
Summary
Although terse, hopefully that is sufficient explanation for now; try it.
And, please feel free to comment, submit feedback or suggestions.
When released as part of the EdgeS web-client eswc library on GitHub
the indexedDb usage patterns with efs will serve as examples of its
design intentions which include addressing efficiencies and usability with
indexedDb and related PWA sync and replicate scenarios.
Related
*
*Julian Day calculation in JavaScript
Benchmarking uuids/sec
const start = Xuid.ns7Now
for(let i = 100000; i; i -=1)
Xuid.v4New
const end = Xuid.ns7Now
console.log(`Delta 7ns: ${(end-start)/100000n}`)
Resulted in: values of 16..20 => ~2 micro-seconds => 500,000 uuids/sec
A: This is just a concept, which most certainly can be improved in many ways, but isn't that slow as I thought it would be.
In general, this code includes hex encoded timestamp in milliseconds (with some hacking it gives 12 digits, so the code will work even after 2527-06-24, but not after 5138-11-16), which means it's sortable. It's not that random, it uses the MAC address for last 12 digits. 13th letter is hard coded 1, to keep it sortable.
After that, next 6 digits come from semi-random string, where first digits come from count of records generated on that millisecond, and other digits are randomly generated. That 6-digit portion contains a dash, and hard coded letter 'a', to keep records sortable.
I know this could be shortened, and performance improved, but I'm happy with results (except the MAC address).
currentNanoseconds = () => {
return nodeMode ? process.hrtime.bigint() : BigInt(Date.now() * 1000000);
}
nodeFindMacAddress = () => {
// Extract MAC address
const interfaces = require('os').networkInterfaces();
let result = null;
for (index in interfaces) {
let entry = interfaces[index];
entry.forEach(item => {
if (item.mac !== '00:00:00:00:00:00') {
result = '-' + item.mac.replace(/:/g, '');
}
});
}
return result;
}
const nodeMode = typeof(process) !== 'undefined';
let macAddress = nodeMode ? nodeFindMacAddress() : '-a52e99ef5efc';
let startTime = currentNanoseconds();
let uuids = []; // Array for storing generated UUIDs, useful for testing
let currentTime = null; // Holds the last value of Date.now(), used as a base for generating the UUID
let timePart = null; // Part of the UUID generated from Date.now()
let counter = 0; // Used for counting records created at certain millisecond
let lastTime = null; // Used for resetting the record counter
const limit = 1000000;
for (let testCounter = 0; testCounter < limit; testCounter++) {
let uuid = testMe();
if (nodeMode || testCounter <= 50) {
uuids.push(uuid);
}
}
const timePassed = Number(currentNanoseconds() - startTime);
if (nodeMode) {
const fs = require('fs');
fs.writeFileSync('temp.txt', JSON.stringify(uuids).replace(/,/g, ',\n'));
} else {
console.log(uuids);
}
console.log({
operationsPerSecond: (1000 * limit / timePassed).toString() + 'm',
nanosecondsPerCycle: timePassed / limit,
milliSecondsPassed: timePassed / 1000000,
microSecondsPassed: timePassed / 1000,
nanosecondsPassed: timePassed
});
function testMe() {
currentTime = Date.now();
let uuid = null; // Function result
if (currentTime !== lastTime) {
// Added a 9 before timestamp, so that the hex-encoded timestamp is 12 digits long. Currently, it is 11 digits long, and it will be until 2527-06-24
// console.log(Date.parse("2527-06-24").toString(16).length)
// Code will stop working on 5138-11-17, because the timestamp will be 15 digits long, and the code only handles up to 14 digit timestamps
// console.log((Date.parse("5138-11-17")).toString().length)
timePart = parseInt(('99999999999999' + currentTime).substr(-14)).toString(16);
timePart = timePart.substr(0, 8) + '-' + timePart.substr(8, 4) + '-1';
counter = 0;
}
randomPart = ('000000' + Math.floor(10 * (counter + Math.random()))).slice(-6);
randomPart = randomPart.substr(0, 3) + '-a' + randomPart.substr(3, 3);
uuid = timePart + randomPart + macAddress;
counter++;
lastTime = currentTime;
return uuid;
}
A: this offering returns 5 groups of 8 digits from a-z,0-9
most of it is random, however incorprates time of day, and has a randomly incrementing counter.
you can specify any base you like (hex, decimal, 36), by default chooses a random base for each group of 8, in the range of base 16 to 36
function newId(base) {
return[
Math.random,
function (){ return (newId.last ? windowId.last + Math.random() : Math.random() ) },
Math.random,
Date.now,
Math.random
].map(function(fn){
return fn().toString(base||(16+(Math.random()*20))).substr(-8);
}).join('-');
}
var demo = function(base){
document.getElementById('uuid').textContent = newId(base);
}
demo(16);
#uuid { font-family: monospace; font-size: 1.5em; }
<p id="uuid"></p>
<button onclick="demo(16);">Hex (base 16)</button>
<button onclick="demo(36);">Base 36</button>
<button onclick="demo(10);">Decimal (base 10)</button>
<button onclick="demo();">Random base</button>
A: The coolest way:
function uuid(){
var u = URL.createObjectURL(new Blob([""]))
URL.revokeObjectURL(u);
return u.split("/").slice(-1)[0]
}
It's probably not fast, efficient, or supported in IE2 but it sure is cool
A: I use this version. It is safe and simple. It is not to generate formatted uids, it is just to generate random strings of chars you need.
export function makeId(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
let letterPos = parseInt(crypto.getRandomValues(new Uint8Array(1))[0] / 255 * charactersLength - 1, 10)
result += characters[letterPos]
}
return result;
}
A: Here's some code based on RFC 4122, section 4.4 (Algorithms for Creating a UUID from Truly Random or Pseudo-Random Number).
function createUUID() {
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
A: For those wanting an RFC 4122 version 4 compliant solution with speed considerations (few calls to Math.random()):
var rand = Math.random;
function UUID() {
var nbr, randStr = "";
do {
randStr += (nbr = rand()).toString(16).substr(3, 6);
} while (randStr.length < 30);
return (
randStr.substr(0, 8) + "-" +
randStr.substr(8, 4) + "-4" +
randStr.substr(12, 3) + "-" +
((nbr*4|0)+8).toString(16) + // [89ab]
randStr.substr(15, 3) + "-" +
randStr.substr(18, 12)
);
}
console.log( UUID() );
The above function should have a decent balance between speed and randomness.
A: I wanted to understand broofa's answer, so I expanded it and added comments:
var uuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (match) {
/*
* Create a random nibble. The two clever bits of this code:
*
* - Bitwise operations will truncate floating point numbers
* - For a bitwise OR of any x, x | 0 = x
*
* So:
*
* Math.random * 16
*
* creates a random floating point number
* between 0 (inclusive) and 16 (exclusive) and
*
* | 0
*
* truncates the floating point number into an integer.
*/
var randomNibble = Math.random() * 16 | 0;
/*
* Resolves the variant field. If the variant field (delineated
* as y in the initial string) is matched, the nibble must
* match the mask (where x is a do-not-care bit):
*
* 10xx
*
* This is achieved by performing the following operations in
* sequence (where x is an intermediate result):
*
* - x & 0x3, which is equivalent to x % 3
* - x | 0x8, which is equivalent to x + 8
*
* This results in a nibble between 8 inclusive and 11 exclusive,
* (or 1000 and 1011 in binary), all of which satisfy the variant
* field mask above.
*/
var nibble = (match == 'y') ?
(randomNibble & 0x3 | 0x8) :
randomNibble;
/*
* Ensure the nibble integer is encoded as base 16 (hexadecimal).
*/
return nibble.toString(16);
}
);
};
A: I adjusted my own UUID/GUID generator with some extras here.
I'm using the following Kybos random number generator to be a bit more cryptographically sound.
Below is my script with the Mash and Kybos methods from baagoe.com excluded.
//UUID/Guid Generator
// use: UUID.create() or UUID.createSequential()
// convenience: UUID.empty, UUID.tryParse(string)
(function(w){
// From http://baagoe.com/en/RandomMusings/javascript/
// Johannes Baagøe <baagoe@baagoe.com>, 2010
//function Mash() {...};
// From http://baagoe.com/en/RandomMusings/javascript/
//function Kybos() {...};
var rnd = Kybos();
//UUID/GUID Implementation from http://frugalcoder.us/post/2012/01/13/javascript-guid-uuid-generator.aspx
var UUID = {
"empty": "00000000-0000-0000-0000-000000000000"
,"parse": function(input) {
var ret = input.toString().trim().toLowerCase().replace(/^[\s\r\n]+|[\{\}]|[\s\r\n]+$/g, "");
if ((/[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}/).test(ret))
return ret;
else
throw new Error("Unable to parse UUID");
}
,"createSequential": function() {
var ret = new Date().valueOf().toString(16).replace("-","")
for (;ret.length < 12; ret = "0" + ret);
ret = ret.substr(ret.length-12,12); //only least significant part
for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));
return [ret.substr(0,8), ret.substr(8,4), "4" + ret.substr(12,3), "89AB"[Math.floor(Math.random()*4)] + ret.substr(16,3), ret.substr(20,12)].join("-");
}
,"create": function() {
var ret = "";
for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));
return [ret.substr(0,8), ret.substr(8,4), "4" + ret.substr(12,3), "89AB"[Math.floor(Math.random()*4)] + ret.substr(16,3), ret.substr(20,12)].join("-");
}
,"random": function() {
return rnd();
}
,"tryParse": function(input) {
try {
return UUID.parse(input);
} catch(ex) {
return UUID.empty;
}
}
};
UUID["new"] = UUID.create;
w.UUID = w.Guid = UUID;
}(window || this));
A: ES6 sample
const guid=()=> {
const s4=()=> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
}
A: The native URL.createObjectURL is generating an UUID. You can take advantage of this.
function uuid() {
const url = URL.createObjectURL(new Blob())
const [id] = url.toString().split('/').reverse()
URL.revokeObjectURL(url)
return id
}
A: The better way:
function(
a, b // Placeholders
){
for( // Loop :)
b = a = ''; // b - result , a - numeric variable
a++ < 36; //
b += a*51&52 // If "a" is not 9 or 14 or 19 or 24
? // return a random number or 4
(
a^15 // If "a" is not 15,
? // generate a random number from 0 to 15
8^Math.random() *
(a^20 ? 16 : 4) // unless "a" is 20, in which case a random number from 8 to 11,
:
4 // otherwise 4
).toString(16)
:
'-' // In other cases, (if "a" is 9,14,19,24) insert "-"
);
return b
}
Minimized:
function(a,b){for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b}
A: The following is simple code that uses crypto.getRandomValues(a) on supported browsers (Internet Explorer 11+, iOS 7+, Firefox 21+, Chrome, and Android Chrome).
It avoids using Math.random(), because that can cause collisions (for example 20 collisions for 4000 generated UUIDs in a real situation by Muxa).
function uuid() {
function randomDigit() {
if (crypto && crypto.getRandomValues) {
var rands = new Uint8Array(1);
crypto.getRandomValues(rands);
return (rands[0] % 16).toString(16);
} else {
return ((Math.random() * 16) | 0).toString(16);
}
}
var crypto = window.crypto || window.msCrypto;
return 'xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx'.replace(/x/g, randomDigit);
}
Notes:
*
*Optimised for code readability, not speed, so it is suitable for, say, a few hundred UUIDs per second. It generates about 10000 uuid() per second in Chromium on my laptop using http://jsbin.com/fuwigo/1 to measure performance.
*It only uses 8 for "y" because that simplifies code readability (y is allowed to be 8, 9, A, or B).
A: If you just need a random 128 bit string in no particular format, you can use:
function uuid() {
return crypto.getRandomValues(new Uint32Array(4)).join('-');
}
Which will return something like 2350143528-4164020887-938913176-2513998651.
A: I couldn't find any answer that uses a single 16-octet TypedArray and a DataView, so I think the following solution for generating a version 4 UUID per the RFC will stand on its own here:
const uuid4 = () => {
const ho = (n, p) => n.toString(16).padStart(p, 0); /// Return the hexadecimal text representation of number `n`, padded with zeroes to be of length `p`
const data = crypto.getRandomValues(new Uint8Array(16)); /// Fill the buffer with random data
data[6] = (data[6] & 0xf) | 0x40; /// Patch the 6th byte to reflect a version 4 UUID
data[8] = (data[8] & 0x3f) | 0x80; /// Patch the 8th byte to reflect a variant 1 UUID (version 4 UUIDs are)
const view = new DataView(data.buffer); /// Create a view backed by a 16-byte buffer
return `${ho(view.getUint32(0), 8)}-${ho(view.getUint16(4), 4)}-${ho(view.getUint16(6), 4)}-${ho(view.getUint16(8), 4)}-${ho(view.getUint32(10), 8)}${ho(view.getUint16(14), 4)}`; /// Compile the canonical textual form from the array data
};
I prefer it because:
*
*it only relies on functions available to the standard ECMAScript platform, where possible -- which is all but one procedure
*it only uses a single buffer, minimizing copying of data, which should in theory yield performance advantages
At the time of writing this, getRandomValues is not something implemented for the crypto object in Node.js. However, it has the equivalent randomBytes function which may be used instead.
A: If your environment is SharePoint, there is a utility function called SP.Guid.newGuid (MSDN link which creates a new GUID. This function is inside the sp.init.js file. If you rewrite this function (to remove some other dependencies from other private functions), and it looks like this:
var newGuid = function () {
var result = '';
var hexcodes = "0123456789abcdef".split("");
for (var index = 0; index < 32; index++) {
var value = Math.floor(Math.random() * 16);
switch (index) {
case 8:
result += '-';
break;
case 12:
value = 4;
result += '-';
break;
case 16:
value = value & 3 | 8;
result += '-';
break;
case 20:
result += '-';
break;
}
result += hexcodes[value];
}
return result;
};
A: This one is based on date, and adds a random suffix to "ensure" uniqueness.
It works well for CSS identifiers, always returns something like, and is easy to hack:
uid-139410573297741
var getUniqueId = function (prefix) {
var d = new Date().getTime();
d += (parseInt(Math.random() * 100)).toString();
if (undefined === prefix) {
prefix = 'uid-';
}
d = prefix + d;
return d;
};
A: Just another more readable variant with just two mutations.
function uuid4()
{
function hex (s, b)
{
return s +
(b >>> 4 ).toString (16) + // high nibble
(b & 0b1111).toString (16); // low nibble
}
let r = crypto.getRandomValues (new Uint8Array (16));
r[6] = r[6] >>> 4 | 0b01000000; // Set type 4: 0100
r[8] = r[8] >>> 3 | 0b10000000; // Set variant: 100
return r.slice ( 0, 4).reduce (hex, '' ) +
r.slice ( 4, 6).reduce (hex, '-') +
r.slice ( 6, 8).reduce (hex, '-') +
r.slice ( 8, 10).reduce (hex, '-') +
r.slice (10, 16).reduce (hex, '-');
}
A: This is the fastest GUID-like string generator method in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. It does not generate a standard-compliant GUID.
Ten million executions of this implementation take just 32.5 seconds, which is the fastest I've ever seen in a browser (the only solution without loops/iterations).
The function is as simple as:
/**
* Generates a GUID string.
* @returns {string} The generated GUID.
* @example af8a8416-6e18-a307-bd9c-f2c947bbb3aa
* @author Slavik Meltser.
* @link http://slavik.meltser.info/?p=142
*/
function guid() {
function _p8(s) {
var p = (Math.random().toString(16)+"000000000").substr(2,8);
return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
}
return _p8() + _p8(true) + _p8(true) + _p8();
}
To test the performance, you can run this code:
console.time('t');
for (var i = 0; i < 10000000; i++) {
guid();
};
console.timeEnd('t');
I'm sure most of you will understand what I did there, but maybe there is at least one person that will need an explanation:
The algorithm:
*
*The Math.random() function returns a decimal number between 0 and 1 with 16 digits after the decimal fraction point (for
example 0.4363923368509859).
*Then we take this number and convert
it to a string with base 16 (from the example above we'll get
0.6fb7687f).
Math.random().toString(16).
*Then we cut off the 0. prefix (0.6fb7687f =>
6fb7687f) and get a string with eight hexadecimal
characters long.
(Math.random().toString(16).substr(2,8).
*Sometimes the Math.random() function will return
shorter number (for example 0.4363), due to zeros at the end (from the example above, actually the number is 0.4363000000000000). That's why I'm appending to this string "000000000" (a string with nine zeros) and then cutting it off with substr() function to make it nine characters exactly (filling zeros to the right).
*The reason for adding exactly nine zeros is because of the worse case scenario, which is when the Math.random() function will return exactly 0 or 1 (probability of 1/10^16 for each one of them). That's why we needed to add nine zeros to it ("0"+"000000000" or "1"+"000000000"), and then cutting it off from the second index (third character) with a length of eight characters. For the rest of the cases, the addition of zeros will not harm the result because it is cutting it off anyway.
Math.random().toString(16)+"000000000").substr(2,8).
The assembly:
*
*The GUID is in the following format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.
*I divided the GUID into four pieces, each piece divided into two types (or formats): XXXXXXXX and -XXXX-XXXX.
*Now I'm building the GUID using these two types to assemble the GUID with call four pieces, as follows: XXXXXXXX -XXXX-XXXX -XXXX-XXXX XXXXXXXX.
*To differ between these two types, I added a flag parameter to a pair creator function _p8(s), the s parameter tells the function whether to add dashes or not.
*Eventually we build the GUID with the following chaining: _p8() + _p8(true) + _p8(true) + _p8(), and return it.
Link to this post on my blog
Enjoy! :-)
A: OK, using the uuid package, and its support for version 1, 3, 4 and 5 UUIDs, do:
yarn add uuid
And then:
const uuidv1 = require('uuid/v1');
uuidv1(); // ⇨ '45745c60-7b1a-11e8-9c9c-2d42b21b1a3e'
You can also do it with fully-specified options:
const v1options = {
node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
clockseq: 0x1234,
msecs: new Date('2011-11-01').getTime(),
nsecs: 5678
};
uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'
For more information, visit the npm page here.
A: Inspired by broofa's answer I had my own take on it:
Here's the cryptographically stronger version using crypto.getRandomValues.
function uuidv4() {
const a = crypto.getRandomValues(new Uint16Array(8));
let i = 0;
return '00-0-4-1-000'.replace(/[^-]/g,
s => (a[i++] + s * 0x10000 >> s).toString(16).padStart(4, '0')
);
}
console.log(uuidv4());
and here's the faster version using Math.random using almost the same principle:
function uuidv4() {
return '00-0-4-1-000'.replace(/[^-]/g,
s => ((Math.random() + ~~s) * 0x10000 >> s).toString(16).padStart(4, '0')
);
}
console.log(uuidv4());
A: Yet another way of doing the same thing:
function guid() {
var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
var str = "";
for(var i=0; i<36; i++) {
var str = str + ((i == 8 || i == 13 || i == 18 || i == 23) ? "-" : chars[Math.floor(Math.random()*chars.length)]);
};
return str;
}
A: Don't use Math.random in any case since it generates a non-cryptographic source of random numbers.
The solution below using crypto.getRandomValues
function uuidv4() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
// tslint:disable-next-line: no-bitwise
const r =
(window.crypto.getRandomValues(new Uint32Array(1))[0] *
Math.pow(2, -32) * 16) |
0;
// tslint:disable-next-line: no-bitwise
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
This link helps you to understand the insecure randomness thrown by Fortify Scanner.
A: This may be of use to someone...
var d = new Date().valueOf();
var n = d.toString();
var result = '';
var length = 32;
var p = 0;
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (var i = length; i > 0; --i){
result += ((i & 1) && n.charAt(p) ? '<b>' + n.charAt(p) + '</b>' : chars[Math.floor(Math.random() * chars.length)]);
if(i & 1) p++;
};
https://jsfiddle.net/j0evrdf1/1/
A: function randomHex(length) {
var random_string = '';
if(!length){
length = 1;
}
for(var i=0; i<length; i+=1){
random_string += Math.floor(Math.random() * 15).toString(16);
}
return random_string;
}
function guid() {
return randomHex(8);
}
A: The following is not v4 compliant, but it could easily be altered to be. It's just an example of extending the Uint8Array type, and using crypto.getRandomValues() to generate the UUID byte values.
class uuid extends Uint8Array {
constructor() {
super(16)
/* Not v4, just some random bytes */
window.crypto.getRandomValues(this)
}
toString() {
let id = new String()
for (let i = 0; i < this.length; i++) {
/* Convert uint8 to hex string */
let hex = this[i].toString(16).toUpperCase()
/* Add zero padding */
while (hex.length < 2) {
hex = String(0).concat(hex)
}
id += hex
/* Add dashes */
if (i == 4 || i == 6 || i == 8 || i == 10 || i == 16) {
id += '-'
}
}
return id
}
}
A: var guid = createMyGuid();
function createMyGuid()
{
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
A: For situations where you already have created a URL for some resource through utilizing the URL.createObjectURL method, you probably won't do faster or shorter than the following:
const uuid = url => url.substr(-36);
The above will work with any compliant implementation of createObjectURL, since the specification explicitly mandates a UUID be added to the end of the URL returned by the former. So you are guaranteed the last 36 characters are the UUID part of the generated URL.
To be clear, sometimes -- heck, perhaps most of the time, everything considered -- you want to generate a UUID for something else than resources you create URLs for with createObjectURL. In those cases, calling the latter method on some new Blob() is going to absolutely tank the performance (and leak memory unless you clean up after yourself using the corresponding revokeObjectURL). It is still quite a "one-liner" though.
I do not recommend you use the above method just for generating UUIDs unless you already have URLs obtained through createObjectURL or something that has a UUID at the end.
I just wanted to mention the above variant for completeness.
A: I Used this function and this is working correctly
function generateUUID(): string {
let d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
d += performance.now(); //use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
console.log(generateUUID())
A: Here's a method that generates RFC4122 using true random via random.org. If the fetch fails it falls back to the browser's inbuilt crypto library which should almost be just as good. And finally, if the user's browser in question doesn't support that, it uses Math.random().
async function UUID() {
//get 31 random hex characters
return (await (async () => {
let output;
try {
//try from random.org
output = (await (
await fetch('https://www.random.org/integers/?num=31&min=0&max=15&col=31&base=16&format=plain&rnd=new')
).text())
//get rid of whitespace
.replace(/[^0-9a-fA-F]+/g, '')
;
if (output.length != 31)
throw '';
}
catch {
output = '';
try {
//failing that, try getting 16 8-bit digits from crypto
for (let num of crypto.getRandomValues(new Uint8Array(16)))
//interpret as 32 4-bit hex numbers
output += (num >> 4).toString(16) + (num & 15).toString(16);
//we only want 31
output = output.substr(1);
}
catch {
//failing THAT, use Math.random
while (output.length < 31)
output += (0 | Math.random() * 16).toString(16);
}
}
return output;
})())
//split into appropriate sections, and set the 15th character to 4
.replace(/^(.{8})(.{4})(.{3})(.{4})/, '$1-$2-4$3-$4-')
//force character 20 to the correct range
.replace(/(?<=-)[^89abAB](?=[^-]+-[^-]+$)/, (num) => (
(parseInt(num, 16) % 4 + 8).toString(16)
))
;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5158"
}
|
Q: How can I associate .sh files with Cygwin? I'd like to run a long rsync command in Cygwin by double clicking on a .sh file in Windows. It must start in the file's containing directory (e.g. /cygdrive/c/scripts/) so that relative paths work. Anyone gotten this to work?
Note: I've just found here, a Cygwin package that manages Windows context menus (Bash Prompt Here). It might have some clues.
A: I've been working with Dragos' solution for some time now and I regard it as the best one because it eleminates the need to use "cygpath -u" inside your shell scripts.
I then wanted to have additional features like drag&drop support for .sh and .bash files. After some digging around I wrote a .bat that associates .sh and .bash files as "bashscript" and activates the Windows Explorer drag&drop handler for them. I had to edit Dragos' command to make it handle 1 argument (the path to the item dropped on a shell script).
The .bat file roughly goes as follows:
echo Registering .sh and .bash files as "bashscript"...
assoc .sh=bashscript
assoc .bash=bashscript
echo.
echo Setting the run command for the file type "bashscript"...
ftype bashscript=C:\cygwin\bin\bash.exe --login -i -c 'cd "$(dirname "$(cygpath -u "%%1")")"; bash "$(cygpath -u "%%1")" "$(/argshandler.sh "%%2")"'
echo.
echo Activating the drag^&drop capability for "bashscript" files (only 1 dropped item
echo will be passed to the script, multiple items are not supported yet)...
reg add HKEY_CLASSES_ROOT\bashscript\shellex\DropHandler /v "" /t REG_SZ /d "{60254CA5-953B-11CF-8C96-00AA00B8708C}" /f
The "argshandler.sh" script in the Cygwin root just cygpaths back the first argument it receives and nothing at all if there aren't any (e.g. if you just double click on a script file):
#!/bin/bash
if [ ! "$1" == "" ]
then
cygpath -u "$1"
fi
All this workes quite nicely so far. However, there are still some drawbacks that would be nice to be resolved:
*
*Dragos' command and my derivative of it fail when it comes to scripts that are located on UNC paths, e.g. \\myserver\myshare\scriptfile.sh
*Only 1 dropped item will be passed to the shell script.
Somehow, concerning the 1-dropped-item-only issue, changing the argument handler script to give back something like
"cygpathed-arg1" "cygpathed-arg2" "cygpathed-arg3"
and changing the setter of Dragos' command to something like
...; bash "$(cygpath -u "%%1")" $(/argshandler.sh "%%2" "%%3" ... "%%9")'
(note that the "" around the argshandler.sh part are gone) does not seem to work properly: If some of the items dragged onto a script contain a blank in their path, said paths will be broken up into multiple arguments at the blanks even though each of them is enclosed in double quotes ... weird.
Are there any command line professionals who feel up to it to solve one or both of these issues?
A: Ok, I've found something that works. Associating a batch file as Vladimir suggested didn't work, but the bash arguments were key.
Short and sweet: associate with this command: "C:\cygwin\bin\bash.exe" -li "%1" %*
Long version if you don't know how:
*
*In Explorer, go to Tools/Folder Options/File Types.
*I already had an SH entry for Bash Script. If you don't have one, click New and enter "SH" to create one.
*With the SH extension selected, click Advanced.
*Choose the "open" action and click edit (or create the action).
*This is the command to use: "C:\cygwin\bin\bash.exe" -li "%1" %*. Note that without the -li, it was returing "command not found" on my scripts.
You may also want to add SH to your PATHEXT environment variable:
WinKey+Pause / Advanced / Environment Variables / System Variables / PATHEXT
Thanks for your help, guys!
A: This doesn't associate .sh files, but it might get you what you want. I started with the cygwin.bat batch file that launches the Cygwin bash shell, and modified it like so:
$ cat test.bat
@echo off
set MYDIR=C:\scripts
C:\cygwin\bin\bash --login -c "cd $MYDIR && echo 'Now in' `pwd`; sleep 15"
That's a toy script but you could modify it to call rsync or call a separate shell script. I admit that it would be nicer if it didn't have MYDIR hard coded. There's probaby a way do get it to automagically set that.
Oh yeah, when I created the .bat file in a bash shell in Cygwin, I noticed I had to actually "chmod +x test.bat" before I could launch it with a double-click. I think it's setting NTFS permissions. You wouldn't need to do that if you just used notepad.
A: This is the command I'm using:
"C:\cygwin\bin\mintty.exe" -w max -h always -t "%1" -e /bin/bash -li -c 'cd "$(dirname "$(cygpath -u "%1")")" && bash "$(cygpath -u "%1")"'
It runs it in mintty, maximised, sets the window title to the script being ran (Windows path to it), changes directory to where the script is, runs it and stays open after it completes.
Alternatively, this will set the title to the cygwin path to the script:
"C:\cygwin\bin\mintty.exe" -w max -h always -t "%1" -e /bin/bash -li -c 'printf "\033]0;$(cygpath -u "%1")\007" && cd "$(dirname "$(cygpath -u "%1")")" && bash "$(cygpath -u "%1")"'
Batch scripts to set the association for you:
Windows path in title:
@echo off
assoc .sh=shellscript
ftype shellscript="C:\cygwin\bin\mintty.exe" -w max -h always -t "%%1" -e /bin/bash -li -c 'cd "$(dirname "$(cygpath -u "%%1")")" ^&^& bash "$(cygpath -u "%%1")"'
pause
And cygwin path in title:
@echo off
assoc .sh=shellscript
ftype shellscript="C:\cygwin\bin\mintty.exe" -w max -h always -t "%%1" -e /bin/bash -li -c 'printf "\033]0;$(cygpath -u "%%1")\007" ^&^& cd "$(dirname "$(cygpath -u "%%1")")" ^&^& bash "$(cygpath -u "%%1")"'
pause
A: After looking around different places. What I have managed to come up with is, first select C:\cygwin64\bin\mintty.exe from the windows "Open with..." dialog
Then edit the registry value of
[Computer\HKEY_CLASSES_ROOT\Applications\mintty.exe\shell\open\command]
to,
C:\cygwin64\bin\mintty.exe -t "%1" /bin/bash -l -i -c "v1=\"$(cygpath -u \"%0\" -a)\" && v2=\"$(dirname \"$v1\")\" && cd \"$v2\" ; exec bash \"%1\" %*"
A: Here is my solution. It works well for my *.sh scripts
regardless of where they are in the directory hierarchy.
Notice that I cd to the cygpath dirname before calling
bash on the cygpath. It just works.
assoc .sh=bashscript
ftype bashscript=C:\cygwin\bin\bash.exe --login -i -c 'cd "$(dirname "$(cygpath -u "%1")")"; bash "$(cygpath -u "%1")"'
A: You should be able to associate .sh files with \CYGWIN\usr\bin\bash.exe. The script will have to change its own working directory, I suggest sticking something like this at the top:
cd `dirname "$0"`
A: I use PuttyCyg (awesome putty in Cygwin window) here's how to get it all going:
Create a batch script, eg. on my machine I used
C:\Dev\scripts\cygbashrun.bat
with contents
SET CYGWIN=nodosfilewarning
C:\Cygwin\bin\putty.exe -cygterm /bin/bash.exe %1
Obviously adapt to contain the paths of your install of PuttyCyg.
Then in Windows File Explorer go to Tools - Folder Options - File Types
Create a ".sh" entry if there isn't already (or .bash depending on what you like your scripts to have).. then Advanced..
[optional step] change the icon and select the Cygwin icon from your install
Then:
*
*New..
*Action = Run Bashscript..
*Application used to perform this action = C:\Dev\scripts\cygbashrun.bat "%1"
Works like a charm for me :O)
A: Windows Registry Editor Version 5.00
;File:ConfigureShToBeRunUnderExplorer.reg v:1.0 docs at the end
[HKEY_CLASSES_ROOT\Applications\bash.exe]
[HKEY_CLASSES_ROOT\Applications\bash.exe\shell]
[HKEY_CLASSES_ROOT\Applications\bash.exe\shell\open]
[HKEY_CLASSES_ROOT\Applications\bash.exe\shell\open\command]
@="C:\\cygwin\\bin\\bash.exe -li \"%1\" %*"
; This is a simple registry file to automate the execution of sh via cygwin on windows 7, might work on other Windows versions ... not tested
; you could add this setting by issueing the following command: reg import ConfigureShToBeRunUnderExplorer.reg
; Note the path of your bash.exe
; Note that you still have to add the .sh to your %PATHTEXT%
; usage: double - click the file or reg import file
A: One solution that works is to create a .bat file that will open cygwin and execute your script.
The script to execute the script go.sh located on my home directory:
@echo off
C:
chdir C:\cygwin\bin
bash --login -i ./go.sh
A: Look at the assoc and ftype commands in a dos box.
Here's an example for .jpg on my machine
c:\>assoc .jpg
.jpg=jpegfile
c:\>ftype jpegfile
jpegfile="C:\Program Files\Common Files\Microsoft Shared\PhotoEd\PHOTOED.EXE" "%1"
assoc .sh=bashscript
ftype bashscript="c:\cygwin\bin\bash.exe" "%1"
Make sure you change the path to bash in the ftype command to match where you have cygwin installed
A: I just didn't bother. I associated .sh files with Crimson Editor (since I spend as much time working out the bugs as I do actually running them). Now it's a matter of getting the right "open with/edit with" combination to work in File Types>Advanced. If I knew what DDE code Crimson Editor used, that would make things easier; as of this post I've not been able to find it, however.
This reminds me of my Mac days (1993-2008) when I used to try and scan applications for more than rudimentary AppleScript scriptability.
BZT
A: I developed a .bat script on my own (not originated from other's answer) to associate a file type (e.g. *.cygwin) to open with this .bat, as follows:
=== file run-script-with-Cygwin-in-same-dir.bat ===
@echo off
REM Info: A script created by Johnny Wong. (last modified on 2014-7-15)
REM It is used to pass a file argument to run a bash script file. The current directory is setting to the path of the script file for convenience.
REM Could be copied to C:\cygwin; and then you manually associate .cygwin file extension to open with this .bat file.
set CYGWIN=nodosfilewarning
C:\cygwin\bin\bash --login -i -c 'cd "`dirname "%~1"`"; exec bash "%~1" %2 %3 %4 %5 %6 %7 %8 %9'
REM finally pause the script (press any key to continue) to keep the window to see result
pause
=== file run-script-with-Cygwin-in-same-dir.bat ===
Detail explanations on syntax used (if you are interested) :
*
*%1 is "..." quoted if associated a file to open with this .bat. For dragging a file to this .bat, it is "..." quoted only if the file's path has spaces.
*%~1 is same as %1 with surrounding double-quotes eliminated, if they exist
*to remove surrounding double-quotes from %p%, use for %%a in (%p%) do set p=%%~a
*you must use "%~1" to force the script file's path double-quoted, so that its folder separators '\' (in %1) won't be removed by bash when being treated as escape characters. Otherwise, it does not work when dragging a file, which has no spaces in its path, to this .bat.
*"exec bash" can be just "bash", the former is for saving resources for one more bash process.
Enjoys :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
}
|
Q: What are some good techniques to convert an Ms Access application to a .Net Application? We have a 12-year-old Ms Access app that we use for our core inventory warehousing and invoicing system. It IS already running on an SQL Server backend, but all the "logic", forms and reports are in Access. After experiencing the massive amounts of maintenance sludge it took to turn inventory transactions from non-temporal to temporal, I realized that I need to someday convert this thing into code so I can better manage the logic in a much more maintainable and testable environment.
What are some techniques that would allow me to convert it into a .Net application in a manageable and efficient manner?
One idea was to convert the queries to stored procedures, then convert the app into an Adp project.But I am still clueless as to how to handle the forms and reports.
Also, I am the only developer for my company, if that matters.
A: Short answer: the migration doesn't seem like something easily automated.
My guess is that your best bet is to rewrite (and install) the system one piece at a time, even if (perhaps) it forces your users to run the old and new versions side-by-side for a while to use different bits of functionality. You can minimize that hassle by careful consideration of which features to migrate and in which order.
For example, you might have one user whose job role requires him or her to use just one screen all day. If you migrate that screen first with accompanying functionality, that user can be on the new system immediately and leave the old one behind, reducing your maintenance load.
So those are just some ideas based on not too much information. I hope this helps anyway.
A: As you already have asp.net with some business logic you could open this up to access as a web service (asmx files). Google for the Microsoft Office Web Services Toolkit for your version of access (xp/2003 etc.) and this will write vba proxy classes for you to call the web service. You can bind web service data to the forms through code (vba to read and write to controls) or create local temp tables with data from the web service and use regular access binding.
Depending on what you are most comfortable with (code/tsql) you can put logic in stored procedures or in a business logic layer or hybrid (both). I find it easier to test code than stored procedures and like not being bound to sql server for business logic i.e. if you want to change the database or want to develop/test components offline without a database. New .net features such as LINQ have pretty good performance so you don't have to rely on stored procedures for database activities.
Keep the access front end user interface until you have refactored all your business logic/data access to web services. You can then create an asp.net app that consumes the web services or a winform app if you want. (Stay clear of wpf, as a ui, for the time being as it is a steep learning curve and doesn't yet have a datagrid that can compare to the access datasheet view.)
Reports
The access reports can can be upsized to sql server reporting services (vba in reports doesn't upsize and it is better to write some tsql in stored procedures). If you don't have the full sql server product you can still use the reportviewer control to write you reports (see http://www.gotreportviewer.com/) in asp.net (or winform with the standard version or up of Visual Studio) binding to ado.net datasets.
Other options:
You can write .net dlls and use com interop. This approach allows you to start writing functionality gradually. Don't use .net ui e.g. a winform as it won't play nicely with access ui. You could write business logic or data access logic and then call these classes from vba. You can then move this code to asp.net or web services if required.
Things to rule out:
I don't like the approach of writing a new app with side by side versions. As a single developer you have enough to worry about. You will probably end up adding features in both versions and debugging two versions rather than one.
The vb6 forms interop does not work for access.
ADP as stated is pretty dead. (I never liked them as I often use local tables to optimize performance and they can only be called through code and not linked)
You may be able to convert your vba modules and class modules to vb.net using The Visual Basic Upgrade Wizard (in visual studio) but it doesn't upsize everything (e.g. dao/ado code to ado.net code) and doesn't create code that is optimized for .net and may not be easy to write unit tests on depending on the design of the vba code. I recommend rewriting the code (try Test Driven Development if you are serious about testing to see if you like it).
A: I would consider looking at the Interop Forms Toolkit. As I understand it, this tool makes it quite easy to use .NET forms from within VB6, so perhaps it can also be used from within Microsoft Access? If so, it may help you migrate the application to .NET in an incremental fashion. Doing a quick search, I was unable to find any guides on using it with Microsoft Access, so I apologise if this turns out to be a blind alley.
A: Converting to an adp will not be a good solution in the long term - this technology is abandoned by Microsoft.
If you want to switch to .net (why? do you have a reason to favour .net?) I suggest you start some reading, try to create some simple apps and then start the task of converting this database to an application.
But...
I think you and the company need to think about the risks involved in this project. What will happen if you get sick, just in the week that management needs some reports that don't already exist? I would suggest that you seek a small local software development company, they will be glad to help you. Maybe you can arrange that you continue to be the 'lead developer' and only use them for back-up.
A: I have a similar problem, and addressed it by creating a versioned deployment system in the Access front end (grab and extract a CAB file), figuring out the required AppDomain manipulation to be able to load the correct CLR version into the Access process, load a .config file, and post data both ways.
It uses standard C DLL calls, so no COM registration required, but also sadly no Unicode support.
Send Command - Generic, I could have done everything with this.
Open Form - Intended to be a "drop in" replacement for DoCmd.OpenForm
Open Report - Intended to be a "drop in" replacement for DoCmd.OpenReport
So make a new report, or migrate an existing one to SSRS, make the format standard, and then change DoCmd.OpenReport to netDoCmd.OpenReport in Access.
Follow a naming convention to know where the reports are to load from, and a standard method for pulling the data needed for the report.
Now I am migrating one form or report as capacity permits, or when a change is requested to it.
Because who can stop feature development for a year to do it all in one hit?
MDI doesn't work properly though. I think there's some work I still need to do around SetParent and UPDATE_UISTYLE
All of this makes the UI in process and in window with Access. I build everything
in DLLs, and the final step will be to create an EXE that loads the "first form" and use that to replace the Access front end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Are locks unnecessary in multi-threaded Python code because of the GIL? If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?
If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?
sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines.
same thing would apply to any other language implementation that has a GIL.
A: The Global Interpreter Lock prevents threads from accessing the interpreter simultaneously (thus CPython only ever uses one core). However, as I understand it, the threads are still interrupted and scheduled preemptively, which means you still need locks on shared data structures, lest your threads stomp on each other's toes.
The answer I've encountered time and time again is that multithreading in Python is rarely worth the overhead, because of this. I've heard good things about the PyProcessing project, which makes running multiple processes as "simple" as multithreading, with shared data structures, queues, etc. (PyProcessing will be introduced into the standard library of the upcoming Python 2.6 as the multiprocessing module.) This gets you around the GIL, as each process has its own interpreter.
A: You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code.
For example:
#!/usr/bin/env python
import threading
shared_balance = 0
class Deposit(threading.Thread):
def run(self):
for _ in xrange(1000000):
global shared_balance
balance = shared_balance
balance += 100
shared_balance = balance
class Withdraw(threading.Thread):
def run(self):
for _ in xrange(1000000):
global shared_balance
balance = shared_balance
balance -= 100
shared_balance = balance
threads = [Deposit(), Withdraw()]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print shared_balance
Here, your code can be interrupted between reading the shared state (balance = shared_balance) and writing the changed result back (shared_balance = balance), causing a lost update. The result is a random value for the shared state.
To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have some way to detect when the shared state had changed since it was read.
A: Think of it this way:
On a single processor computer, multithreading happens by suspending one thread and starting another fast enough to make it appear to be running at the same time. This is like Python with the GIL: only one thread is ever actually running.
The problem is that the thread can be suspended anywhere, for example, if I want to compute b = (a + b) * 3, this might produce instructions something like this:
1 a += b
2 a *= 3
3 b = a
Now, lets say that is running in a thread and that thread is suspended after either line 1 or 2 and then another thread kicks in and runs:
b = 5
Then when the other thread resumes, b is overwritten by the old computed values, which is probably not what was expected.
So you can see that even though they're not ACTUALLY running at the same time, you still need locking.
A: No - the GIL just protects python internals from multiple threads altering their state. This is a very low-level of locking, sufficient only to keep python's own structures in a consistent state. It doesn't cover the application level locking you'll need to do to cover thread safety in your own code.
The essence of locking is to ensure that a particular block of code is only executed by one thread. The GIL enforces this for blocks the size of a single bytecode, but usually you want the lock to span a larger block of code than this.
A: Locks are still needed. I will try explaining why they are needed.
Any operation/instruction is executed in the interpreter. GIL ensures that interpreter is held by a single thread at a particular instant of time. And your program with multiple threads works in a single interpreter. At any particular instant of time, this interpreter is held by a single thread. It means that only thread which is holding the interpreter is running at any instant of time.
Suppose there are two threads,say t1 and t2, and both want to execute two instructions which is reading the value of a global variable and incrementing it.
#increment value
global var
read_var = var
var = read_var + 1
As put above, GIL only ensures that two threads can't execute an instruction simultaneously, which means both threads can't execute read_var = var at any particular instant of time. But they can execute instruction one after another and you can still have problem. Consider this situation:
*
*Suppose read_var is 0.
*GIL is held by thread t1.
*t1 executes read_var = var. So, read_var in t1 is 0. GIL will only ensure that this read operation will not be executed for any other thread at this instant.
*GIL is given to thread t2.
*t2 executes read_var = var. But read_var is still 0. So, read_var in t2 is 0.
*GIL is given to t1.
*t1 executes var = read_var+1 and var becomes 1.
*GIL is given to t2.
*t2 thinks read_var=0, because that's what it read.
*t2 executes var = read_var+1 and var becomes 1.
*Our expectation was that var should become 2.
*So, a lock must be used to keep both reading and incrementing as an atomic operation.
*Will Harris' answer explains it through a code example.
A: Adding to the discussion:
Because the GIL exists, some operations are atomic in Python and do not need a lock.
http://www.python.org/doc/faq/library/#what-kinds-of-global-value-mutation-are-thread-safe
As stated by the other answers, however, you still need to use locks whenever the application logic requires them (such as in a Producer/Consumer problem).
A: This post describes the GIL at a fairly high-level:
*
*https://web.archive.org/web/20080516010343/http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html
Of particular interest are these quotes:
Every ten instructions (this default
can be changed), the core releases the
GIL for the current thread. At that
point, the OS chooses a thread from
all the threads competing for the lock
(possibly choosing the same thread
that just released the GIL – you don't
have any control over which thread
gets chosen); that thread acquires the
GIL and then runs for another ten
bytecodes.
and
Note carefully that the GIL only
restricts pure Python code. Extensions
(external Python libraries usually
written in C) can be written that
release the lock, which then allows
the Python interpreter to run
separately from the extension until
the extension reacquires the lock.
It sounds like the GIL just provides fewer possible instances for a context switch, and makes multi-core/processor systems behave as a single core, with respect to each python interpreter instance, so yes, you still need to use synchronization mechanisms.
A: You still need to use locks (your code could be interrupted at any time to execute another thread and this can cause data inconsistencies). The problem with GIL is that it prevents Python code from using more cores at the same time (or multiple processors if they are available).
A: A little bit of update from Will Harris's example:
class Withdraw(threading.Thread):
def run(self):
for _ in xrange(1000000):
global shared_balance
if shared_balance >= 100:
balance = shared_balance
balance -= 100
shared_balance = balance
Put a value check statement in the withdraw and I don't see negative anymore and updates seems consistent. My question is:
If GIL prevents only one thread can be executed at any atomic time, then where would be the stale value? If no stale value, why we need lock? (Assuming we only talk about pure python code)
If I understand correctly, the above condition check wouldn't work in a real threading environment. When more than one threads are executing concurrently, stale value can be created hence the inconsistency of the share state, then you really need a lock. But if python really only allows just one thread at any time (time slicing threading), then there shouldn't be possible for stale value to exist, right?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
}
|
Q: CSS: Display Properties differences What is the difference between display:block and display:inline
A: Block elements will typically stack vertically whereas inline elements will line up horizontally.
Two Divs will stack on top of each other, but if you set them to display:inline, they will be next to each other horizontally. Vise-versa with Span tags.
A: yes,
display:block makes the element behave like a block eg: <p>
display:inline make and element layout inline.
these can be applied to elements that default to the opposite display type.
Possible Values
* none - no display at all.
* inline - An inline box.
* block - A block box.
* inline-block - effectively a block box inside an inline box. Not supported by Mozilla at time of writing. IE will only apply inline-block to elements that are traditionally inline such as span or a but not p or div. Loopy.
* run-in - Either an inline or block box depending on the context. If a block box follows the run-in box, the run-in box becomes the first inline box of that block box, otherwise it becomes a block box itself. Crazy. Not supported by IE/Win or Mozilla at the time of writing.
* list-item - the equivalent of the default styling of the HTML li element.
* table - a block-level table - the equivalent of the default styling of the HTML table element. Not supported by IE.
* inline-table - an inline-level table. Not supported by IE.
* table-row-group - the equivalent of the default styling of the HTML tbody element. Not supported by IE.
* table-header-group - the equivalent of the default styling of the HTML thead element. Not supported by IE.
* table-footer-group - the equivalent of the default styling of the HTML tfoot element. Not supported by IE.
* table-row - the equivalent of the default styling of the HTML tr element. Not supported by IE.
* table-column-group - the equivalent of the default styling of the HTML colgroup element. Not supported by IE.
* table-column - the equivalent of the default styling of the HTML col element. Not supported by IE.
* table-cell - the equivalent of the default styling of the HTML td or th elements. Not supported by IE.
* table-caption - the equivalent of the default styling of the HTML caption element. Not supported by IE.
*source
A: display: block means that the element is displayed as a block, as paragraphs and headers have always been. A block has some whitespace above and below it and tolerates no HTML elements next to it, except when ordered otherwise (by adding a float declaration to another element, for instance). display: inline means that the element is displayed inline, inside the current block on the same line. Only when it's between two blocks does the element form an 'anonymous block', that however has the smallest possible width.
A: display: block will cause the object to force other objects within a container on to a new line.
display: inline tries to display the object on the same line as other objects.
display:block
Item 1
Item 2
Item 3
display:inline
Item 1 Item 2 Item 3
A: There are two main types of drawing context in CSS that can be assigned to elements. One, display: block, creates positionable boxes. The other, display: inline flows the content as a series of lines within a box.
By default, a block takes up all horizontal space, so a series of blocks will be displayed one beneath the other, stacked vertically. As inline elements flow into lines, they are rendered horizontally, as one word after the other.
In general, you use block to lay out a page, while inline is reserved for textual content that you find within chunks of text, for instance, links.
There are also other types of drawing context, for instance, display: table, however these are more rarely used due to their specialised nature and/or lack of browser support.
More detail is available in the CSS 2.1 specification.
A: It's important to note that inline elements cannot be assigned their own width, height, or vertical whitespace (margin/padding top/bottom).
If you are trying to make block elements behave like inline elements (where they stack next to each other), you should be using float. Floats will stack next to other floats in the same direction. Also, any inline element that is given float will automatically be given become a block.
A: Block uses the full width available, with a new line before and after. Inline uses only the width it needs without forcing new lines.
A: An HTML document is considered a flow, think of a stack of HTML elements piled up to the top.
A block is defined in the flow as a box (by default as large as the page) and is pushed as much as possible to the top without overlapping another block. Examples: div, p, table.
An inline element does not define a box (that's why you cannot set its width and height), it will be appended to other inline elements in the current block. Examples: span, code, a.
A: display: block
The element will take up the the entire container of its parent. Normally starts in a new line.
display: inline-block
This will create an inline element that will only take up as much space as required. Can start anywhere in the line.
Example usage: While creating a menu bar on top of your page (the menu-items wrapper is often assigned display: inline-block)
A: Consider an example below:
By default is a block-level element and will take the entire space horizontally. And are by default inline elements(The next span element will occupy the same line space horizontally)
h1{
background-color:yellow;
}
span{
background-color:lightpink;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<h1>This is heading 1</h1>
<h1> This is heading 2</h1>
<span>Span1</span>
<span>Span2</span>
</body>
</html>
Let's understand better by converting inbuilt inline element to block-level element and vice versa.
h1{
background-color:yellow;
display:inline;
}
span{
background-color:lightpink;
display:block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<h1>This is heading 1</h1>
<h1> This is heading 2</h1>
<span>Span1</span>
<span>Span2</span>
</body>
</html>
A: As per its name,
display block makes the width of the element span full width.
whereas inline tries to use the same width as the width of the inline element.
The display property in CSS works differently on different tags because some tag has a default value for the display property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What is the most interesting design pattern you've ever met? Most of us have already used the casual patterns such as MVC, strategy, etc.
But there must be some unusual solutions to unusual problems, and I'd like to hear about it.
A: It's more of an anti-pattern, but I've seen what I call the "Keep it all in one place" pattern. It was a large application, where all variables that were not local, for every class, EVERY class, were stored in a single class called P (for parameters). As an aside, all static variables were kept in a class called... wait for it... S.
Anyway, some how, this project grew quite large, and all of a sudden, nothing worked. (I got hired around this time). Amazingly, the program didn't crash, it just had tons of side effects that made the application run screwy. As you can imagine, multiple threads, all accessing P and modifying variables, with no locks or synchronization in place.
I tell you, it was truly a sight to behold.
The company opened a new office and hired 3 people to staff it, me being one of them. We weree given the program and told to fix it. We spent days sitting around just slapping our forheads. I have a permenent palm print on my face now.
Other funnies... variable named "fudgeFactor". Still don't know what that did.
Method to get next ascii character...
char getNextChar(char previous) {
switch (previous)
case 'a': return b;
case 'b': return c;
...
case 'z': return a;
}
Anyway, that's my funny pattern... with some extra side funny thrown in.
A: For the last year I've been doing maintenance on a windows application written in LANSA where the focus is managed by having all controls set to tabStop = false except for two hidden buttons (PrevFocus and NextFocus). When a form is loaded, the focus is set to a field, and the name of that field is stored in a tracking variable (apptly named 'FocusField'). When the user tabs (or shift-tabs) to change focus, the GotFocus event of the appropriate button is run. Inside that function is a case statement (select case FocusField). Based on the currently focused field, validation logic is run and, possibly, the focus changes to another field.
The GotFocus events for most controls look at what the current value of FocusField is and then call a LostFocus function that does that same case statement work for FocusField so that the previously focused field will get validated.
As you can probably guess, this makes it impossible to separate the UI from the logic, and an unbelievable chore to maintain. Re-writing these forms to use a simple Validate method that validates ALL the inputs and letting the normal tabbing properties (TabOrder, TabStop, etc) do their magic has usually resulted in 50% reduction in code and vastly more reliable forms.
I have no idea where this pattern originated, though it may have been dreamed up by the RPG/green-screen programmers turned WinForms developers that wrote the application.
A: Visitor stuck me the first time when working on a graph-heavy program, as a very elegant way to do operations on complex structures.
besides mvc (which isn't a pattenr per se), this is the "king of patterns" in regards to its complexity and potential to solve problems.
A: The Fluent Interface by Fowler is quite an interesting pattern. I've always had a soft spot for Abstract Factories, Strategies, and the State Pattern too.
If I may, I recently codified a "pattern" that I call the Friend Class Pattern that some might find interesting or useful for restricting the visibility of private field accessors in languages that don't have C++-style friend classes.
A: Not so much a pattern, but dependency injection and Inversion of control
A: I remember when I first read about the flyweight pattern in the GOF. The example they use is a word processor; they point out the downsides of using an independent object to represent each character. The flyweight pattern encourages the separation of sharable, intrinsic, immutable state from unsharable, extrinsic, mutable state. For me, at the time, it was one of those "Aha!" moments that really broadened my horizons and has affected my designs to this day.
A friend of mine suggested that the Strategy pattern is essentially the progenitor pattern. Many of the other patterns (Bridge, Decorator, Proxy, State, ...) are just more refined applications of Strategy. I remember arguing with him for quite some time that there is indeed a difference between Strategy and State.
A: Crash Only Software:
http://www.usenix.org/events/hotos03/tech/full_papers/candea/candea_html/
Abstract
Crash-only programs crash safely and recover quickly. There is only one way to stop such software -- by crashing it -- and only one way to bring it up -- by initiating recovery. Crash-only systems are built from crash-only components, and the use of transparent component-level retries hides intra-system component crashes from end users. In this paper we advocate a crash-only design for Internet systems, showing that it can lead to more reliable, predictable code and faster, more effective recovery. We present ideas on how to build such crash-only Internet services, taking successful techniques to their logical extreme.
A: No, that's about DP books and this thread is about the particular patterns.
Interpreter and Flyweight comes to mind from the Gang of 4 book.
I consider Bridge and Mediator powerful and deep patterns in the sw developer's toolbox.
A: I never saw the point of the Visitor pattern until I had to manipulate Java bytecode directly using the ASM library. It was amazing how much the pattern simplified what would otherwise have been a really complex task.
The pattern is also used in most Java IDE's when you want to write your own refactoring plugin. You provide a Visitor object and it is passed around the AST to make whatever changes are required.
A: The most interesting design pattern you will ever meet is one that you have created yourself, for obvious reasons.
That's not to say that it will be the best design pattern, just the most interesting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Production Logging in Flex Is there any way to capture the trace statements of your Flex app while not running in debug mode?
Or is there any other way to output logging information when not running a debugger?
Currently I'm trying to fix a bug that only presents itself in very specific deployment scenario, but I could see this being useful in some instances for customers to send logs to tech support when they are reporting bugs or other problems.
A: I suppose you're talking about Adobe Flex, targeting the Flash Player?
If so, you can write your own logging wrapper class that propagates log messages sent to it to several targets (like the trace stack and internal memory so that you can access the log from within the app and e.g. send it to a server when the user agrees to send a bug report). Also see the Flex logging framework for something like this that already exists.
I've actually done something like this -- I have a class called Log with static methods like log(), debug(), error() etc. that I use in my apps, and this class forwards all messages sent to it into the trace stack via trace(), into a "log console" app running on the same host via LocalConnection and/or Socket (a socket connection is obviously a lot faster than LocalConnection) and also saves them locally into an array so that users can send bug reports along with the log output right from within the app.
This sort of a change of course means that you'd have to translate all trace() commands in your code into calls to the logging system, but that can be easily achieved with a regex search & replace.
A: There's a project on Google Code called Thunder Bolt that allows you to write log messages that will appear in FireBug when running the application in Firefox (assuming of course that you have that extension installed.)
Logging with this tool is as simple as:
import org.osflash.thunderbolt.Logger;
var myNumber: int = 5;
var myString: String = "Lorem ipsum";
Logger.error ("Logging two objects: A number typed as int and a string", myNumber, myString);
A: I've used alcon in the past.
http://blog.hexagonstar.com/alcon/
A: You can try XPanel from Farata Systems. This is a native Windows UI that can show log messages using the Flex 3 Logging API even for Flex applications running in a browser. Unfortunately they have redesigned their site and I can't find it anymore... Maybe Google will help you.
We did something different using JavaScript. The customer can open a 'special' page that shows logging and trace statements using DHTML. The Flex application calls a JavaScript function that tells the application, whether this page is opened or not. If it is not, logging is disabled. If it is opened, logging is enabled and all log statements are appended to this page.
Note that there is no way to write logging output to the filesystem all the time due to sandbox restrictions. However a customer can easily copy and paste the output of the logging window as explained above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there an easy way to get Apache Tomcat to reboot automatically after a deployment? Our project uses Cruise Control to both build and hot deploy a web application to a remote server (via FTP) running Tomcat in the form of a .war file. Unfortunately, "hot" deploys don't appear to work properly, causing us to reboot Tomcat in response to each deployment. We would really like to do this auto-magically, much like the build itself. Is there an easy way to do this?
Side note: both machines are running Windows (XP or server, I think).
Side note 2: Performance doesn't really matter. This is an integration box.
A: if you have regularly scheduled builds you could easily put something in the cron like this
crontab -e
then stop tomcat at say 1:30 am
30 1 * * * ./path_to_tamcat/bin/catalina.sh stop
then start it up again 2 mins later
32 1 * * * ./path_to_tamcat/bin/catalina.sh start
granted this isn't the best for irregular deployment, but you could easily have regular deployment with scheduled restart.
A: If you look at the tomcat startup and shutdown .bat (or .sh) scripts in the bin directory, you will see that they actually run a java process to start tomcat or in the case of shutting down, connects to tomcats shutdown port - see server.xml in the conf directory.
You could configure your build ant task to invoke the tomcat jars in the same way as the scripts do.
A: Is tomcat registered as a windows service?
If so, just write a .bat script using netstart and netstop and have the called as the last step of your deployment process.
A: It sounds a bit to me like you are using the little Tomcat deployment manager thing. I basically have no experience with that, just so you know. That said, where I work we use two settings.
In the server.xml file, the context has the attribute reloadable="true".
All we have to do is place the WAR file in the right spot and Tomcat unpacks it and reloads it, no problem.
Now when I looked it up, the official configuration reference says:
"This feature is very useful during application development, but it requires significant runtime overhead and is not recommended for use on deployed production applications."
Like I said, we've never had problems. Our systems process a large number of requests and we don't seem to have a problem. We've never benchmarked the two configurations against each other though.
You might want to give it a try. At least you would learn if it is happy enough to reload things when done that way. You can check the performance as well to see if it's a problem for you.
I should note that every once in a while things just don't go right and we have to restart Tomcat anyway, but that's relatively rare.
If this works, all you need to do is have a script copy the WAR in the right spot and monitor to make sure things work. After enough deploys Tomcat will run out of permgen space, so you have to be aware that you might need to restart Tomcat by hand anyway.
Other random guesses:
*
*Are you FTPing directly into the final WAR location? Maybe Tomcat is just trying to open it too early?
*Are you getting any kind of error message? Maybe that could help you track the problem down?
*Have you tried other versions of Tomcat (if available to you)? Maybe 5.5 doesn't have the problem (or 5.0 if you're on 5.5)? Maybe just a newer point release?
A: What version of tomcat are you using?
What exactly happens to make it appear as if a "hot" deploy doesn't work?
A: reloadable="true"
does not enable re-deployment of war-files (this will work automatically), it enables monitoring of changes of files in WEB-INF/classes and WEB-INF/lib, which is probably not what you want.
Most of the time when re-deployement of war-files in Tomcat freezes, I was able to trace it back to classloader leaks, see see Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception
A: You didn't give much detail why your hot deploys "doesn't work properly", but if it's actually been caused by a resource in /WEB-INF/lib been locked (which is not an uncommon cause; you see this often with the mail.jar of the JavaMail API), then just set the Context's antiResourceLocking attribute to true. Here's an example how the webapp's /META-INF/context.xml would look like:
<Context antiResourceLocking="true">
<!-- Your stuff here. -->
</Context>
A: One way to start the tomcat on the startup is to run it using cron using the @reboot attribute:
open up a terminal and type :
sudo crontab -e
at the end of the file enter the command:
@reboot /`PATH_TO_WHERE_TOMCAT_INSTALLED`/bin/startup.sh
save the file and exit.
The above command will run the command once everytime computer boots up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why use WinDbg vs the Visual Studio (VS) debugger? What are the major reasons for using WinDbg vs the Visual Studio debugger?
And is it commonly used as a complete replacement for the Visual Studio debugger, or more for when the need arises.
A: If you are wondering why you should use windbg over Visual Studio, then you need to read Advanced Windows Debugging. Any time you need to debug a truly ugly problem windbg has better technology to do it with than Visual Studio. Windbg has a more powerful scripting language and allows you to write DLLs to automate difficult problems. It will install gflags.exe, which gives you better control over the heap for debugging memory overwrites.
You don't actually need to run the install, you can just copy the files over and be ready to go. Also it installs adsplus.vb, so you can take mini-dumps of running processes. It is also very easy to setup to perform remote debugging. There is nothing better than being able to debug a problem from your own desk instead of fighting the 15" monitor that flickers on a test PC.
For day to day code writing I use Visual Studio, but once you need to start debugging problems from other computers or find yourself in a very ugly situation, windbg is the only way to go. Spending some time learning windbg is a great investment. Also if you look at crash dumps there are two great resources, http://www.dumpanalysis.org/blog and http://blogs.msdn.com/ntdebugging/default.aspx that do all their debugging using windbg.
A: You don't specify whether you're debugging native or managed code. It doesn't affect the answer, WinDbg is extremely useful for both, but many people believe that WinDbg is somehow less relevant when debugging .NET apps. Not so. As a bonus, you can learn a lot about how the .NET platform works by debugging your .NET app in WinDbg with the SOS extension. Run up (or attach to) your .NET app in WinDbg and type...
.loadby sos mscorwks
...to be sure that you load the right extension for the version of the CLR in use. Then type...
!help
... to see what commands are available in the SOS extension.
I've heard it joked that Microsoft only has one developer tool, and it's WinDbg. Everything you could possibly want for debugging is in there, or in an extension. Sure, a subset of those things are also available in VS with a friendlier UI... :-)
A: I have used it when I've been sent .dmp files from an NT4.0 server - MSVC won't load these old format files.
A: Mixing kernel-debugging plus remote-user-mode-debugging.
AFAIK, visual studio still cannot do remote debugging in the mode I describe as "solution". That's a darn good reason to use windbg.
Problem:
*
*Set up windbg across 1394. Your app runs on the "target". Windbg runs on the "host".
*Run visual studio on the host
*Have visual studio launch your app on the target using the remote tools.
*Break into the kernel mode windbg to halt the target
*Wait long enough for visual studio's TCP connection to timeout
*"g" in windbg to un-halt the target
*observe your app "pop" when the remote monitor realizes the network connection is gone
*restart your app :(
Solution:
*
*Don't use visual studio.
*Run a user mode windbg on the target with "-server"
*Have the target's windbg launch your app.
*On the host, start a 2nd windbg that connects to target with "-remote".
*If the TCP connection dies just start another windbg instance on the host and nothing is lost. Your app didn't die because the controlling user mode windbg process is running on the target.
Also, I find it easier to use the same debugger for both kernel mode and user mode, windbg is very powerful even in user mode, and I can leverage my own windbg extensions
in both kernel mode and user mode instances.
A: Lightweight, can be run without installing it on a client's machine, fast, can debug kernel mode.
A: Is the latest visual studio still missing an equivalent to windbg's "-o" that makes the debugger automatically attach to child processes? Very useful for apps that must be run from a complicated .bat file, or apps that fork and exit the parent process.
A: Here are some further links to help with using WinDbg, most are .NET specific.
*
*John Robbins talks about using cmdtree to create a command window.
*Here is a quick WinDbg/SOS cheat sheet (webarchive).
*If broken it is, fix it you should has a bunch of WinDbg/Sos related articles, mainly around debugging ASP.NET.
*Here is an old overview of SOS from MSDN mag. It is about .NET 1.1 so its age is showing.
A: I always liked the watch and trace feature: 'wt'
-> It prints to the output window all the function calls as they happen. That was pretty cool stuff!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
}
|
Q: How can I check to make sure a window is being actively used, and if not alert the end user that they are about to be logged out? Working on a new back end system for my company, and one of their requests is for a window to become locked down and for the user to be sent to the login screen if they leave it idle for to long.
I figure I'd do this with JavaScript by attaching listeners to clicks, mouse moves and key-ups but I worry about messing with other scripts.
Any suggestions?
A: You could just make it do a log out if the user doesn't change pages after so long. That's what the Angel Learning Courseware system seems to do.
The other problem you'll face, though, is that some users disable JavaScript.
A: If you can put code on the page then there's two things:
*
*Javascript looking for mouse movement, keyboard activity, and scrolling.
*Put a meta refresh tag in the html - if they're on that page for more than X minutes it'll automatically redirect to the login page.
If you can only put code on the server:
*
*Keep a session (cookie or other) that tracks how long between page changes. If a page is requested longer than X minutes since the last request, don't serve the requested page, serve the login page.
You can use the meta refresh and server techniques together. The refreshed page will go to a "your session is about to expire, click here to go back and continue working within 30 seconds".
The button they click resets your server's session, and performs a page back function so any data they had (in most browsers) will still be there. Requires javascript on the refresh page, but none on the original page - just a meta refresh. Javascript activity tracking would be the best though.
-Adam
A: In the load event for the page you can use setTimeout to fire a function warning the user that they will be logged out if they don't refresh the page.
With 5 minute session timeouts you could do warnings after 4 minutes:
setTimeout(timeoutWarning, 240000);
function timeoutWarning() {
if(confirm('You have been idle for a while. Would you like to remain logged in?'))
window.location.refresh();
}
A: Firstly, for this to be effective, you have to make sure users are logged out on the server at the end of this idle time. Otherwise, nothing you do on the client side is effective. If you send them to a login page, they can just click the back button.
Second, the conventional way to do this is to use a "meta refresh" tag. Adding this to the page:
<meta http-equiv="refresh" content="900;url=http://example.com/login"/>
will send them to the login page after 15 minutes (900 seconds). This will send them there even if they are doing something on the page. It doesn't detect activity. It just knows how long the page has been up in the browser. This is usually good enough because people don't take 15 minutes to fill in a page (stackoverflow.com is a notable exception, I guess.)
If you really need to detect activity on the page, then I think your first instinct is correct. You're going to have to add event handlers to several things. If you are worried about messing with other scripting for validation or other things, you should look at adding event handlers programmatically rather than inline. That is, instead of using
<input type="text" onClick="doSomething;">
Access the object model directly with
Mozilla way: element.addEventListener('click' ...)
Microsoft way: element.attachEvent('onclick' ...)
and then make sure you pass along the events after you receive them so existing code still does whatever (validation?) it is supposed to do.
http://www.quirksmode.org/js/introevents.html has a decent write up on how to do this.
--
bmb
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you deal with configuration management of Database Tables? How do you deal with source control management and automated deployment (configuration management) of database tables. I work in a SQL Server environment and it's pretty easy to script out drop and create files for stored procedures/triggers/functions even jobs. It's also easy to handle scripting out the creation of a new db table. However, if at a later point you want to modify that table, you can't necessarily just drop it and recreate it with the new field for fear of losing data. Is there an automated way to deal with this problem? Do you script out a temp table and backfill after updating the new changed table? (could be rough if there is a lot of data)
Any suggestions would be greatly appreciated.
A: Tools like Red-gate's SQL Compare are invaluable in making sure you have a complete script. You still may need to manually adjust it to make sure the objects are scripted in the correct order. Make sure to script triggers and constraints, etc as well as tables.In general you will want to use alter commands instead of drop and create especially if the table is at all large.
All our tables and functions and stored procs are required to be under source control as well, so we can return to old versions if need be. Also our dbas periodically delte anything they find not in Source COntrol, so that keeps developers from forgetting to do it.
Of course all development scripts being promoted to production should be run on a QA or staging server first to ensure the script will run properly (and with no changes required) before it is run on prod. Also the timing of running on prod needs to be considered, you don't want to lock out users especially during busy periods and time has shown that loading scripts to production late on Friday afternoon is usually a bad idea.
A: We had similar experiences working with Oracle DB. We established procedures for adopting SVN and automated scripts (that pull changes from SVN) in order to build patches.
Please see http://www.scmsupport.com/scm.php?go=home.html and http://scmsupport.wordpress.com/ for more details.
A: There are tools available that help you develop your schema, develop changes, version those changes and will help you compare the differences between versions and even generate the SQL to make the DDL changes.
For example, check out Embarcadero Change Manager and other products offered by Embarcardero.
A: You can automatically create the initial creation script, but ALTER scripts really need to be hand-coded on a case-by-case basis, because in practice you need to do custom stuff in them.
In any case, you'll need some way of creating apply and rollback scripts for each change, and have an installer script which runs them (and a rollback which rolls them back of course). Such an installer should probably remember what version the schema is in, and run all the necessary migrations, in the right order.
See my article here:
http://marksverbiage.blogspot.com/2008/07/versioning-your-schema.html
A: It varies, depending on how you want to treat existing data and how extensive the schema changes are, but even in Management Studio, before you commit changes, you can generate a script of all the changes.
For a lot of data or where there are constraints or foreign keys, even simple ALTER operations can take a significant amount of time.
A: Ohh forgot to say, make sure you have a good set of database backups before loading schema changes to production. Better safe than sorry.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Ruby Soap4R Web Service, .NET Consumer How do I generate WSDL from a Web Service in Ruby using Soap4R (SOAP::RPC::StandaloneServer) that would be consumed from .NET?
A: There's not a way to do this through SOAP4R, unfortunately. SOAP4R is more for interacting with SOAP endpoints, or generating your own through a WSDL specification.
The only Ruby code I know that does this comes from ActionWebService, which was part of Rails, pre-Rails 2. If you install the gem actionwebservice (you'll have to force it, most likely), you can look at the method to_wsdl in the file lib/action_web_service/dispatcher/action_controller_dispatcher.rb. This builds WSDL using the Builder library. The definitions for the WSDL are defined using methods in ActionWebService::API. It should not be too hard to extract that code into something you can use for your project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Locking in C# I'm still a little unclear and when to wrap a lock around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge:
class Foo
{
private static readonly string bar = "O_o";
private bool TrySomething()
{
string bar;
lock(Foo.objectToLockOn)
{
bar = Foo.bar;
}
// Do something with bar
}
}
That just doesn't make sense to me--why would there by concurrency issues with READING a register?
Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL...
class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
lock(Foo.objectToLockOn)
{
return Foo.joke;
}
}
}
vs.
class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
string joke;
lock(Foo.objectToLockOn)
{
joke = Foo.joke;
}
return joke;
}
}
A: Reading or writing a 32-bit or smaller field is an atomic operation in C#. There's no need for a lock in the code you presented, as far as I can see.
A: It looks to me that the lock is unnecessary in your first case. Using the static initializer to initialize bar is guaranteed to be thread safe. Since you only ever read the value, there's no need to lock it. If the value's never going to change, there will never be any contention, why lock at all?
A: Since none of the code you've written modifies the static field after initialization, there is no need for any locking. Just replacing the string with a new value won't need synchronization either, unless the new value depends on the results of a read of the old value.
Static fields aren't the only things that need synchronization, any shared reference which could be modified is vulnerable to synchronization issues.
class Foo
{
private int count = 0;
public void TrySomething()
{
count++;
}
}
You might suppose that two threads executing the TrySomething method would be fine. But its not.
*
*Thread A reads the value of count (0) into a register so it can be incremented.
*Context switch! The thread scheduler decides thread A has had enough execution time. Next in line is Thread B.
*Thread B reads the value of count (0) into a register.
*Thread B increments the register.
*Thread B saves the result (1) to count.
*Context switch back to A.
*Thread A reloads the register with the value of count (0) saved on its stack.
*Thread A increments the register.
*Thread A saves the result (1) to count.
So, even though we called count++ twice, the value of count has just gone from 0 to 1. Lets make the code thread-safe:
class Foo
{
private int count = 0;
private readonly object sync = new object();
public void TrySomething()
{
lock(sync)
count++;
}
}
Now when Thread A gets interrupted Thread B cannot mess with count because it will hit the lock statement and then block until Thread A has released sync.
By the way, there is an alternative way to make incrementing Int32s and Int64s thread-safe:
class Foo
{
private int count = 0;
public void TrySomething()
{
System.Threading.Interlocked.Increment(ref count);
}
}
Regarding the second part of your question, I think I would just go with whichever is easier to read, any performance difference there will be negligible. Early optimisation is the root of all evil, etc.
Why threading is hard
A: If you're just writing a value to a pointer, you don't need to lock, since that action is atomic. Generally, you should lock any time you need to do a transaction involving at least two atomic actions (reads or writes) that depend on the state not changing between the beginning and end.
That said – I come from Java land, where all reads and writes of variables are atomic actions. Other answers here suggest that .NET is different.
A: Dirty reads?
A: In my opinion, you should try very hard to not put static variables in a position where they need to be read/written to from different threads. They are essentially free-for-all global variables in that case, and globals are almost always a Bad Thing.
That being said, if you do put a static variable in such a position, you may want to lock during a read, just in case - remember, another thread may have swooped in and changed the value during the read, and if it does, you may end up with corrupt data. Reads are not necessarily atomic operations unless you ensure they are by locking. Same with writes - they are not always atomic operations either.
Edit:
As Mark pointed out, for certain primitives in C# reads are always atomic. But be careful with other data types.
A: As for your "which is better" question, they're the same since the function scope isn't used for anything else.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Recursively list all files in a directory including files in symlink directories Suppose I have a directory /dir inside which there are 3 symlinks to other directories
/dir/dir11, /dir/dir12, and /dir/dir13. I want to list all the files in dir including the ones in dir11, dir12 and dir13.
To be more generic, I want to list all files including the ones in the directories which are symlinks. find ., ls -R, etc stop at the symlink without navigating into them to list further.
A: find /dir -type f -follow -print
-type f means it will display real files (not symlinks)
-follow means it will follow your directory symlinks
-print will cause it to display the filenames.
If you want a ls type display, you can do the following
find /dir -type f -follow -print|xargs ls -l
A: find -L /var/www/ -type l
# man find
-L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the
properties of
the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to
examine the file to
which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is
in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the
symbolic link will
be searched.
A: I knew tree was an appropriate, but I didn't have tree installed. So, I got a pretty close alternate here
find ./ | sed -e 's/[^-][^\/]*\//--/g;s/--/ |-/'
A: ls -R -L
-L dereferences symbolic links. This will also make it impossible to see any symlinks to files, though - they'll look like the pointed-to file.
A: The -L option to ls will accomplish what you want. It dereferences symbolic links.
So your command would be:
ls -LR
You can also accomplish this with
find -follow
The -follow option directs find to follow symbolic links to directories.
On Mac OS X use
find -L
as -follow has been deprecated.
A: How about tree? tree -l will follow symlinks.
Disclaimer: I wrote this package.
A: Using ls:
ls -LR
from 'man ls':
-L, --dereference
when showing file information for a symbolic link, show informa‐
tion for the file the link references rather than for the link
itself
Or, using find:
find -L .
From the find manpage:
-L Follow symbolic links.
If you find you want to only follow a few symbolic links (like maybe just the toplevel ones you mentioned), you should look at the -H option, which only follows symlinks that you pass to it on the commandline.
A: in case you would like to print all file contents:
find . -type f -exec cat {} +
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "186"
}
|
Q: What opensource CMS: generates clean xhtml, is skinable with css, and has a lightweight markup content editor? See title. By lightweight markup I mean something like markdown or wikitext.
A: Well, silverstripe http://www.silverstripe.com/ is thought to be a good option for people who care about web standards , as is modx http://modxcms.com/
For a lighter editor, check out textpattern.com which uses textile (like markdown). If you're on rails, http://webby.rubyforge.org/ might do the trick.
http://www.madebyfrog.com is a port of the ruby CMS radiant that aims to be fast, light, and minimal.
A: WordPress keeps getting better and better.
A: I'm loving modx.
A: I am a user of Joomla. I think Joomla is in the top five CMS.
A: I like Radiant CMS. Simple, easy to use and flexible, and it has markdown filters integrated.
A: Umbraco asp.net c# cms
A: Plone meets all those requirements, although it would be unusual to use markdown. (The underlying Zope platform definitely supports markdown, but in the Plone user interface, it's more usual to use the Kupu editor)
Edit: Since I wrote that, things have changed. Plone still supports Kupu, but these days you also have the option to use tinymce as your markup editor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I convert between big-endian and little-endian values in C++? How do I convert between big-endian and little-endian values in C++?
For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.
Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.
A: From The Byte Order Fallacy by Rob Pike:
Let's say your data stream has a little-endian-encoded 32-bit integer. Here's how to extract it (assuming unsigned bytes):
i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | ((unsigned)data[3]<<24);
If it's big-endian, here's how to extract it:
i = (data[3]<<0) | (data[2]<<8) | (data[1]<<16) | ((unsigned)data[0]<<24);
TL;DR: don't worry about your platform native order, all that counts is the byte order of the stream your are reading from, and you better hope it's well defined.
Note 1: It is expected that int and unsigned int be 32 bits here, types may require adjustment otherwise.
Note 2: The last byte must be explicitly cast to unsigned before shifting, as by default it's promoted to int, and a shift by 24 bits means manipulating the sign bit which is Undefined Behavior.
A: The same way you do in C:
short big = 0xdead;
short little = (((big & 0xff)<<8) | ((big & 0xff00)>>8));
You could also declare a vector of unsigned chars, memcpy the input value into it, reverse the bytes into another vector and memcpy the bytes out, but that'll take orders of magnitude longer than bit-twiddling, especially with 64-bit values.
A: If you're doing this to transfer data between different platforms look at the ntoh and hton functions.
A: On most POSIX systems (through it's not in the POSIX standard) there is the endian.h, which can be used to determine what encoding your system uses. From there it's something like this:
unsigned int change_endian(unsigned int x)
{
unsigned char *ptr = (unsigned char *)&x;
return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
This swaps the order (from big endian to little endian):
If you have the number 0xDEADBEEF (on a little endian system stored as 0xEFBEADDE), ptr[0] will be 0xEF, ptr[1] is 0xBE, etc.
But if you want to use it for networking, then htons, htonl and htonll (and their inverses ntohs, ntohl and ntohll) will be helpful for converting from host order to network order.
A: Note that, at least for Windows, htonl() is much slower than their intrinsic counterpart _byteswap_ulong(). The former is a DLL library call into ws2_32.dll, the latter is one BSWAP assembly instruction. Therefore, if you are writing some platform-dependent code, prefer using the intrinsics for speed:
#define htonl(x) _byteswap_ulong(x)
This may be especially important for .PNG image processing where all integers are saved in Big Endian with explanation "One can use htonl()..." {to slow down typical Windows programs, if you are not prepared}.
A: Seriously... I don't understand why all solutions are that complicated! How about the simplest, most general template function that swaps any type of any size under any circumstances in any operating system????
template <typename T>
void SwapEnd(T& var)
{
static_assert(std::is_pod<T>::value, "Type must be POD type for safety");
std::array<char, sizeof(T)> varArray;
std::memcpy(varArray.data(), &var, sizeof(T));
for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)
std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);
std::memcpy(&var, varArray.data(), sizeof(T));
}
It's the magic power of C and C++ together! Simply swap the original variable character by character.
Point 1: No operators: Remember that I didn't use the simple assignment operator "=" because some objects will be messed up when the endianness is flipped and the copy constructor (or assignment operator) won't work. Therefore, it's more reliable to copy them char by char.
Point 2: Be aware of alignment issues: Notice that we're copying to and from an array, which is the right thing to do because the C++ compiler doesn't guarantee that we can access unaligned memory (this answer was updated from its original form for this). For example, if you allocate uint64_t, your compiler cannot guarantee that you can access the 3rd byte of that as a uint8_t. Therefore, the right thing to do is to copy this to a char array, swap it, then copy it back (so no reinterpret_cast). Notice that compilers are mostly smart enough to convert what you did back to a reinterpret_cast if they're capable of accessing individual bytes regardless of alignment.
To use this function:
double x = 5;
SwapEnd(x);
and now x is different in endianness.
A: If you are doing this for purposes of network/host compatability you should use:
ntohl() //Network to Host byte order (Long)
htonl() //Host to Network byte order (Long)
ntohs() //Network to Host byte order (Short)
htons() //Host to Network byte order (Short)
If you are doing this for some other reason one of the byte_swap solutions presented here would work just fine.
A: Most platforms have a system header file that provides efficient byteswap functions. On Linux it is in <endian.h>. You can wrap it nicely in C++:
#include <iostream>
#include <endian.h>
template<size_t N> struct SizeT {};
#define BYTESWAPS(bits) \
template<class T> inline T htobe(T t, SizeT<bits / 8>) { return htobe ## bits(t); } \
template<class T> inline T htole(T t, SizeT<bits / 8>) { return htole ## bits(t); } \
template<class T> inline T betoh(T t, SizeT<bits / 8>) { return be ## bits ## toh(t); } \
template<class T> inline T letoh(T t, SizeT<bits / 8>) { return le ## bits ## toh(t); }
BYTESWAPS(16)
BYTESWAPS(32)
BYTESWAPS(64)
#undef BYTESWAPS
template<class T> inline T htobe(T t) { return htobe(t, SizeT<sizeof t>()); }
template<class T> inline T htole(T t) { return htole(t, SizeT<sizeof t>()); }
template<class T> inline T betoh(T t) { return betoh(t, SizeT<sizeof t>()); }
template<class T> inline T letoh(T t) { return letoh(t, SizeT<sizeof t>()); }
int main()
{
std::cout << std::hex;
std::cout << htobe(static_cast<unsigned short>(0xfeca)) << '\n';
std::cout << htobe(0xafbeadde) << '\n';
// Use ULL suffix to specify integer constant as unsigned long long
std::cout << htobe(0xfecaefbeafdeedfeULL) << '\n';
}
Output:
cafe
deadbeaf
feeddeafbeefcafe
A: I have this code that allow me to convert from HOST_ENDIAN_ORDER (whatever it is) to LITTLE_ENDIAN_ORDER or BIG_ENDIAN_ORDER. I use a template, so if I try to convert from HOST_ENDIAN_ORDER to LITTLE_ENDIAN_ORDER and they happen to be the same for the machine for wich I compile, no code will be generated.
Here is the code with some comments:
// We define some constant for little, big and host endianess. Here I use
// BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you
// don't want to use boost you will have to modify this part a bit.
enum EEndian
{
LITTLE_ENDIAN_ORDER,
BIG_ENDIAN_ORDER,
#if defined(BOOST_LITTLE_ENDIAN)
HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER
#elif defined(BOOST_BIG_ENDIAN)
HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER
#else
#error "Impossible de determiner l'indianness du systeme cible."
#endif
};
// this function swap the bytes of values given it's size as a template
// parameter (could sizeof be used?).
template <class T, unsigned int size>
inline T SwapBytes(T value)
{
union
{
T value;
char bytes[size];
} in, out;
in.value = value;
for (unsigned int i = 0; i < size / 2; ++i)
{
out.bytes[i] = in.bytes[size - 1 - i];
out.bytes[size - 1 - i] = in.bytes[i];
}
return out.value;
}
// Here is the function you will use. Again there is two compile-time assertion
// that use the boost librarie. You could probably comment them out, but if you
// do be cautious not to use this function for anything else than integers
// types. This function need to be calles like this :
//
// int x = someValue;
// int i = EndianSwapBytes<HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER>(x);
//
template<EEndian from, EEndian to, class T>
inline T EndianSwapBytes(T value)
{
// A : La donnée à swapper à une taille de 2, 4 ou 8 octets
BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);
// A : La donnée à swapper est d'un type arithmetic
BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);
// Si from et to sont du même type on ne swap pas.
if (from == to)
return value;
return SwapBytes<T, sizeof(T)>(value);
}
A: i like this one, just for style :-)
long swap(long i) {
char *c = (char *) &i;
return * (long *) (char[]) {c[3], c[2], c[1], c[0] };
}
A: If a big-endian 32-bit unsigned integer looks like 0xAABBCCDD which is equal to 2864434397, then that same 32-bit unsigned integer looks like 0xDDCCBBAA on a little-endian processor which is also equal to 2864434397.
If a big-endian 16-bit unsigned short looks like 0xAABB which is equal to 43707, then that same 16-bit unsigned short looks like 0xBBAA on a little-endian processor which is also equal to 43707.
Here are a couple of handy #define functions to swap bytes from little-endian to big-endian and vice-versa -->
// can be used for short, unsigned short, word, unsigned word (2-byte types)
#define BYTESWAP16(n) (((n&0xFF00)>>8)|((n&0x00FF)<<8))
// can be used for int or unsigned int or float (4-byte types)
#define BYTESWAP32(n) ((BYTESWAP16((n&0xFFFF0000)>>16))|((BYTESWAP16(n&0x0000FFFF))<<16))
// can be used for unsigned long long or double (8-byte types)
#define BYTESWAP64(n) ((BYTESWAP32((n&0xFFFFFFFF00000000)>>32))|((BYTESWAP32(n&0x00000000FFFFFFFF))<<32))
A: Just thought I added my own solution here since I haven't seen it anywhere. It's a small and portable C++ templated function and portable that only uses bit operations.
template<typename T> inline static T swapByteOrder(const T& val) {
int totalBytes = sizeof(val);
T swapped = (T) 0;
for (int i = 0; i < totalBytes; ++i) {
swapped |= (val >> (8*(totalBytes-i-1)) & 0xFF) << (8*i);
}
return swapped;
}
A: I took a few suggestions from this post and put them together to form this:
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>
#include <boost/detail/endian.hpp>
#include <stdexcept>
#include <cstdint>
enum endianness
{
little_endian,
big_endian,
network_endian = big_endian,
#if defined(BOOST_LITTLE_ENDIAN)
host_endian = little_endian
#elif defined(BOOST_BIG_ENDIAN)
host_endian = big_endian
#else
#error "unable to determine system endianness"
#endif
};
namespace detail {
template<typename T, size_t sz>
struct swap_bytes
{
inline T operator()(T val)
{
throw std::out_of_range("data size");
}
};
template<typename T>
struct swap_bytes<T, 1>
{
inline T operator()(T val)
{
return val;
}
};
template<typename T>
struct swap_bytes<T, 2>
{
inline T operator()(T val)
{
return ((((val) >> 8) & 0xff) | (((val) & 0xff) << 8));
}
};
template<typename T>
struct swap_bytes<T, 4>
{
inline T operator()(T val)
{
return ((((val) & 0xff000000) >> 24) |
(((val) & 0x00ff0000) >> 8) |
(((val) & 0x0000ff00) << 8) |
(((val) & 0x000000ff) << 24));
}
};
template<>
struct swap_bytes<float, 4>
{
inline float operator()(float val)
{
uint32_t mem =swap_bytes<uint32_t, sizeof(uint32_t)>()(*(uint32_t*)&val);
return *(float*)&mem;
}
};
template<typename T>
struct swap_bytes<T, 8>
{
inline T operator()(T val)
{
return ((((val) & 0xff00000000000000ull) >> 56) |
(((val) & 0x00ff000000000000ull) >> 40) |
(((val) & 0x0000ff0000000000ull) >> 24) |
(((val) & 0x000000ff00000000ull) >> 8 ) |
(((val) & 0x00000000ff000000ull) << 8 ) |
(((val) & 0x0000000000ff0000ull) << 24) |
(((val) & 0x000000000000ff00ull) << 40) |
(((val) & 0x00000000000000ffull) << 56));
}
};
template<>
struct swap_bytes<double, 8>
{
inline double operator()(double val)
{
uint64_t mem =swap_bytes<uint64_t, sizeof(uint64_t)>()(*(uint64_t*)&val);
return *(double*)&mem;
}
};
template<endianness from, endianness to, class T>
struct do_byte_swap
{
inline T operator()(T value)
{
return swap_bytes<T, sizeof(T)>()(value);
}
};
// specialisations when attempting to swap to the same endianess
template<class T> struct do_byte_swap<little_endian, little_endian, T> { inline T operator()(T value) { return value; } };
template<class T> struct do_byte_swap<big_endian, big_endian, T> { inline T operator()(T value) { return value; } };
} // namespace detail
template<endianness from, endianness to, class T>
inline T byte_swap(T value)
{
// ensure the data is only 1, 2, 4 or 8 bytes
BOOST_STATIC_ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);
// ensure we're only swapping arithmetic types
BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);
return detail::do_byte_swap<from, to, T>()(value);
}
You would then use it as follows:
// swaps val from host-byte-order to network-byte-order
auto swapped = byte_swap<host_endian, network_endian>(val);
and vice-versa
// swap a value received from the network into host-byte-order
auto val = byte_swap<network_endian, host_endian>(val_from_network);
A: If you're using Visual C++ do the following: You include intrin.h and call the following functions:
For 16 bit numbers:
unsigned short _byteswap_ushort(unsigned short value);
For 32 bit numbers:
unsigned long _byteswap_ulong(unsigned long value);
For 64 bit numbers:
unsigned __int64 _byteswap_uint64(unsigned __int64 value);
8 bit numbers (chars) don't need to be converted.
Also these are only defined for unsigned values they work for signed integers as well.
For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.
Other compilers have similar intrinsics as well.
In GCC for example you can directly call some builtins as documented here:
uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)
(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.
16 bit swap it's just a bit-rotate.
Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..
A: The procedure for going from big-endian to little-endian is the same as going from little-endian to big-endian.
Here's some example code:
void swapByteOrder(unsigned short& us)
{
us = (us >> 8) |
(us << 8);
}
void swapByteOrder(unsigned int& ui)
{
ui = (ui >> 24) |
((ui<<8) & 0x00FF0000) |
((ui>>8) & 0x0000FF00) |
(ui << 24);
}
void swapByteOrder(unsigned long long& ull)
{
ull = (ull >> 56) |
((ull<<40) & 0x00FF000000000000) |
((ull<<24) & 0x0000FF0000000000) |
((ull<<8) & 0x000000FF00000000) |
((ull>>8) & 0x00000000FF000000) |
((ull>>24) & 0x0000000000FF0000) |
((ull>>40) & 0x000000000000FF00) |
(ull << 56);
}
A: Here's a generalized version I came up with off the top of my head, for swapping a value in place. The other suggestions would be better if performance is a problem.
template<typename T>
void ByteSwap(T * p)
{
for (int i = 0; i < sizeof(T)/2; ++i)
std::swap(((char *)p)[i], ((char *)p)[sizeof(T)-1-i]);
}
Disclaimer: I haven't tried to compile this or test it yet.
A: If you take the common pattern for reversing the order of bits in a word, and cull the part that reverses bits within each byte, then you're left with something which only reverses the bytes within a word. For 64-bits:
x = ((x & 0x00000000ffffffff) << 32) ^ ((x >> 32) & 0x00000000ffffffff);
x = ((x & 0x0000ffff0000ffff) << 16) ^ ((x >> 16) & 0x0000ffff0000ffff);
x = ((x & 0x00ff00ff00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff00ff00ff);
The compiler should clean out the superfluous bit-masking operations (I left them in to highlight the pattern), but if it doesn't you can rewrite the first line this way:
x = ( x << 32) ^ (x >> 32);
That should normally simplify down to a single rotate instruction on most architectures (ignoring that the whole operation is probably one instruction).
On a RISC processor the large, complicated constants may cause the compiler difficulties. You can trivially calculate each of the constants from the previous one, though. Like so:
uint64_t k = 0x00000000ffffffff; /* compiler should know a trick for this */
x = ((x & k) << 32) ^ ((x >> 32) & k);
k ^= k << 16;
x = ((x & k) << 16) ^ ((x >> 16) & k);
k ^= k << 8;
x = ((x & k) << 8) ^ ((x >> 8) & k);
If you like, you can write that as a loop. It won't be efficient, but just for fun:
int i = sizeof(x) * CHAR_BIT / 2;
uintmax_t k = (1 << i) - 1;
while (i >= 8)
{
x = ((x & k) << i) ^ ((x >> i) & k);
i >>= 1;
k ^= k << i;
}
And for completeness, here's the simplified 32-bit version of the first form:
x = ( x << 16) ^ (x >> 16);
x = ((x & 0x00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff);
A: Using the codes below, you can swap between BigEndian and LittleEndian easily
#define uint32_t unsigned
#define uint16_t unsigned short
#define swap16(x) ((((uint16_t)(x) & 0x00ff)<<8)| \
(((uint16_t)(x) & 0xff00)>>8))
#define swap32(x) ((((uint32_t)(x) & 0x000000ff)<<24)| \
(((uint32_t)(x) & 0x0000ff00)<<8)| \
(((uint32_t)(x) & 0x00ff0000)>>8)| \
(((uint32_t)(x) & 0xff000000)>>24))
A: I am really surprised no one mentioned htobeXX and betohXX functions. They are defined in endian.h and are very similar to network functions htonXX.
A: There is an assembly instruction called BSWAP that will do the swap for you, extremely fast.
You can read about it here.
Visual Studio, or more precisely the Visual C++ runtime library, has platform intrinsics for this, called _byteswap_ushort(), _byteswap_ulong(), and _byteswap_int64(). Similar should exist for other platforms, but I'm not aware of what they would be called.
A: We've done this with templates. You could do something like this:
// Specialization for 2-byte types.
template<>
inline void endian_byte_swapper< 2 >(char* dest, char const* src)
{
// Use bit manipulations instead of accessing individual bytes from memory, much faster.
ushort* p_dest = reinterpret_cast< ushort* >(dest);
ushort const* const p_src = reinterpret_cast< ushort const* >(src);
*p_dest = (*p_src >> 8) | (*p_src << 8);
}
// Specialization for 4-byte types.
template<>
inline void endian_byte_swapper< 4 >(char* dest, char const* src)
{
// Use bit manipulations instead of accessing individual bytes from memory, much faster.
uint* p_dest = reinterpret_cast< uint* >(dest);
uint const* const p_src = reinterpret_cast< uint const* >(src);
*p_dest = (*p_src >> 24) | ((*p_src & 0x00ff0000) >> 8) | ((*p_src & 0x0000ff00) << 8) | (*p_src << 24);
}
A: Simply put:
#include <climits>
template <typename T>
T swap_endian(T u)
{
static_assert (CHAR_BIT == 8, "CHAR_BIT != 8");
union
{
T u;
unsigned char u8[sizeof(T)];
} source, dest;
source.u = u;
for (size_t k = 0; k < sizeof(T); k++)
dest.u8[k] = source.u8[sizeof(T) - k - 1];
return dest.u;
}
usage: swap_endian<uint32_t>(42).
A: I recently wrote a macro to do this in C, but it's equally valid in C++:
#define REVERSE_BYTES(...) do for(size_t REVERSE_BYTES=0; REVERSE_BYTES<sizeof(__VA_ARGS__)>>1; ++REVERSE_BYTES)\
((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES],\
((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES],\
((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES];\
while(0)
It accepts any type and reverses the bytes in the passed argument.
Example usages:
int main(){
unsigned long long x = 0xABCDEF0123456789;
printf("Before: %llX\n",x);
REVERSE_BYTES(x);
printf("After : %llX\n",x);
char c[7]="nametag";
printf("Before: %c%c%c%c%c%c%c\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);
REVERSE_BYTES(c);
printf("After : %c%c%c%c%c%c%c\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);
}
Which prints:
Before: ABCDEF0123456789
After : 8967452301EFCDAB
Before: nametag
After : gateman
The above is perfectly copy/paste-able, but there's a lot going on here, so I'll break down how it works piece by piece:
The first notable thing is that the entire macro is encased in a do while(0) block. This is a common idiom to allow normal semicolon use after the macro.
Next up is the use of a variable named REVERSE_BYTES as the for loop's counter. The name of the macro itself is used as a variable name to ensure that it doesn't clash with any other symbols that may be in scope wherever the macro is used. Since the name is being used within the macro's expansion, it won't be expanded again when used as a variable name here.
Within the for loop, there are two bytes being referenced and XOR swapped (so a temporary variable name is not required):
((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES]
((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES]
__VA_ARGS__ represents whatever was given to the macro, and is used to increase the flexibility of what may be passed in (albeit not by much). The address of this argument is then taken and cast to an unsigned char pointer to permit the swapping of its bytes via array [] subscripting.
The final peculiar point is the lack of {} braces. They aren't necessary because all of the steps in each swap are joined with the comma operator, making them one statement.
Finally, it's worth noting that this is not the ideal approach if speed is a top priority. If this is an important factor, some of the type-specific macros or platform-specific directives referenced in other answers are likely a better option. This approach, however, is portable to all types, all major platforms, and both the C and C++ languages.
A: If you have C++ 17 then add this header
#include <algorithm>
Use this template function to swap the bytes:
template <typename T>
void swapEndian(T& buffer)
{
static_assert(std::is_pod<T>::value, "swapEndian support POD type only");
char* startIndex = static_cast<char*>((void*)buffer.data());
char* endIndex = startIndex + sizeof(buffer);
std::reverse(startIndex, endIndex);
}
call it like:
swapEndian (stlContainer);
A: Here is a basic function to swap to/from little and big endian. It's basic but it doesn't require supplementary libraries.
void endianness_swap(uint32_t& val) {
uint8_t a, b, c;
a = (val & 0xFF000000) >> 24;
b = (val & 0x00FF0000) >> 16;
c = (val & 0x0000FF00) >> 8;
val=(val & 0x000000FF) << 24;
val = val + (c << 16) + (b << 8) + (a);
}
A: Wow, I couldn't believe some of the answers I've read here. There's actually an instruction in assembly which does this faster than anything else. bswap. You could simply write a function like this...
__declspec(naked) uint32_t EndianSwap(uint32 value)
{
__asm
{
mov eax, dword ptr[esp + 4]
bswap eax
ret
}
}
It is MUCH faster than the intrinsics that have been suggested. I've disassembled them and looked. The above function has no prologue/epilogue so virtually has no overhead at all.
unsigned long _byteswap_ulong(unsigned long value);
Doing 16 bit is just as easy, with the exception that you'd use xchg al, ah. bswap only works on 32-bit registers.
64-bit is a little more tricky, but not overly so. Much better than all of the above examples with loops and templates etc.
There are some caveats here... Firstly bswap is only available on 80x486 CPU's and above. Is anyone planning on running it on a 386?!? If so, you can still replace bswap with...
mov ebx, eax
shr ebx, 16
xchg al, ah
xchg bl, bh
shl eax, 16
or eax, ebx
Also inline assembly is only available in x86 code in Visual Studio. A naked function cannot be lined and also isn't available in x64 builds. I that instance, you're going to have to use the compiler intrinsics.
A: Portable technique for implementing optimizer-friendly unaligned non-inplace endian accessors. They work on every compiler, every boundary alignment and every byte ordering. These unaligned routines are supplemented, or mooted, depending on native endian and alignment. Partial listing but you get the idea. BO* are constant values based on native byte ordering.
uint32_t sw_get_uint32_1234(pu32)
uint32_1234 *pu32;
{
union {
uint32_1234 u32_1234;
uint32_t u32;
} bou32;
bou32.u32_1234[0] = (*pu32)[BO32_0];
bou32.u32_1234[1] = (*pu32)[BO32_1];
bou32.u32_1234[2] = (*pu32)[BO32_2];
bou32.u32_1234[3] = (*pu32)[BO32_3];
return(bou32.u32);
}
void sw_set_uint32_1234(pu32, u32)
uint32_1234 *pu32;
uint32_t u32;
{
union {
uint32_1234 u32_1234;
uint32_t u32;
} bou32;
bou32.u32 = u32;
(*pu32)[BO32_0] = bou32.u32_1234[0];
(*pu32)[BO32_1] = bou32.u32_1234[1];
(*pu32)[BO32_2] = bou32.u32_1234[2];
(*pu32)[BO32_3] = bou32.u32_1234[3];
}
#if HAS_SW_INT64
int64 sw_get_int64_12345678(pi64)
int64_12345678 *pi64;
{
union {
int64_12345678 i64_12345678;
int64 i64;
} boi64;
boi64.i64_12345678[0] = (*pi64)[BO64_0];
boi64.i64_12345678[1] = (*pi64)[BO64_1];
boi64.i64_12345678[2] = (*pi64)[BO64_2];
boi64.i64_12345678[3] = (*pi64)[BO64_3];
boi64.i64_12345678[4] = (*pi64)[BO64_4];
boi64.i64_12345678[5] = (*pi64)[BO64_5];
boi64.i64_12345678[6] = (*pi64)[BO64_6];
boi64.i64_12345678[7] = (*pi64)[BO64_7];
return(boi64.i64);
}
#endif
int32_t sw_get_int32_3412(pi32)
int32_3412 *pi32;
{
union {
int32_3412 i32_3412;
int32_t i32;
} boi32;
boi32.i32_3412[2] = (*pi32)[BO32_0];
boi32.i32_3412[3] = (*pi32)[BO32_1];
boi32.i32_3412[0] = (*pi32)[BO32_2];
boi32.i32_3412[1] = (*pi32)[BO32_3];
return(boi32.i32);
}
void sw_set_int32_3412(pi32, i32)
int32_3412 *pi32;
int32_t i32;
{
union {
int32_3412 i32_3412;
int32_t i32;
} boi32;
boi32.i32 = i32;
(*pi32)[BO32_0] = boi32.i32_3412[2];
(*pi32)[BO32_1] = boi32.i32_3412[3];
(*pi32)[BO32_2] = boi32.i32_3412[0];
(*pi32)[BO32_3] = boi32.i32_3412[1];
}
uint32_t sw_get_uint32_3412(pu32)
uint32_3412 *pu32;
{
union {
uint32_3412 u32_3412;
uint32_t u32;
} bou32;
bou32.u32_3412[2] = (*pu32)[BO32_0];
bou32.u32_3412[3] = (*pu32)[BO32_1];
bou32.u32_3412[0] = (*pu32)[BO32_2];
bou32.u32_3412[1] = (*pu32)[BO32_3];
return(bou32.u32);
}
void sw_set_uint32_3412(pu32, u32)
uint32_3412 *pu32;
uint32_t u32;
{
union {
uint32_3412 u32_3412;
uint32_t u32;
} bou32;
bou32.u32 = u32;
(*pu32)[BO32_0] = bou32.u32_3412[2];
(*pu32)[BO32_1] = bou32.u32_3412[3];
(*pu32)[BO32_2] = bou32.u32_3412[0];
(*pu32)[BO32_3] = bou32.u32_3412[1];
}
float sw_get_float_1234(pf)
float_1234 *pf;
{
union {
float_1234 f_1234;
float f;
} bof;
bof.f_1234[0] = (*pf)[BO32_0];
bof.f_1234[1] = (*pf)[BO32_1];
bof.f_1234[2] = (*pf)[BO32_2];
bof.f_1234[3] = (*pf)[BO32_3];
return(bof.f);
}
void sw_set_float_1234(pf, f)
float_1234 *pf;
float f;
{
union {
float_1234 f_1234;
float f;
} bof;
bof.f = (float)f;
(*pf)[BO32_0] = bof.f_1234[0];
(*pf)[BO32_1] = bof.f_1234[1];
(*pf)[BO32_2] = bof.f_1234[2];
(*pf)[BO32_3] = bof.f_1234[3];
}
double sw_get_double_12345678(pd)
double_12345678 *pd;
{
union {
double_12345678 d_12345678;
double d;
} bod;
bod.d_12345678[0] = (*pd)[BO64_0];
bod.d_12345678[1] = (*pd)[BO64_1];
bod.d_12345678[2] = (*pd)[BO64_2];
bod.d_12345678[3] = (*pd)[BO64_3];
bod.d_12345678[4] = (*pd)[BO64_4];
bod.d_12345678[5] = (*pd)[BO64_5];
bod.d_12345678[6] = (*pd)[BO64_6];
bod.d_12345678[7] = (*pd)[BO64_7];
return(bod.d);
}
void sw_set_double_12345678(pd, d)
double_12345678 *pd;
double d;
{
union {
double_12345678 d_12345678;
double d;
} bod;
bod.d = d;
(*pd)[BO64_0] = bod.d_12345678[0];
(*pd)[BO64_1] = bod.d_12345678[1];
(*pd)[BO64_2] = bod.d_12345678[2];
(*pd)[BO64_3] = bod.d_12345678[3];
(*pd)[BO64_4] = bod.d_12345678[4];
(*pd)[BO64_5] = bod.d_12345678[5];
(*pd)[BO64_6] = bod.d_12345678[6];
(*pd)[BO64_7] = bod.d_12345678[7];
}
These typedefs have the benefit of raising compiler errors if not used with accessors, thus mitigating forgotten accessor bugs.
typedef char int8_1[1], uint8_1[1];
typedef char int16_12[2], uint16_12[2]; /* little endian */
typedef char int16_21[2], uint16_21[2]; /* big endian */
typedef char int24_321[3], uint24_321[3]; /* Alpha Micro, PDP-11 */
typedef char int32_1234[4], uint32_1234[4]; /* little endian */
typedef char int32_3412[4], uint32_3412[4]; /* Alpha Micro, PDP-11 */
typedef char int32_4321[4], uint32_4321[4]; /* big endian */
typedef char int64_12345678[8], uint64_12345678[8]; /* little endian */
typedef char int64_34128756[8], uint64_34128756[8]; /* Alpha Micro, PDP-11 */
typedef char int64_87654321[8], uint64_87654321[8]; /* big endian */
typedef char float_1234[4]; /* little endian */
typedef char float_3412[4]; /* Alpha Micro, PDP-11 */
typedef char float_4321[4]; /* big endian */
typedef char double_12345678[8]; /* little endian */
typedef char double_78563412[8]; /* Alpha Micro? */
typedef char double_87654321[8]; /* big endian */
A: Byte swapping with ye olde 3-step-xor trick around a pivot in a template function gives a flexible, quick O(ln2) solution that does not require a library, the style here also rejects 1 byte types:
template<typename T>void swap(T &t){
for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){
*((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
*((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);
*((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
}
}
A: Seems like the safe way would be to use htons on each word. So, if you have...
std::vector<uint16_t> storage(n); // where n is the number to be converted
// the following would do the trick
std::transform(word_storage.cbegin(), word_storage.cend()
, word_storage.begin(), [](const uint16_t input)->uint16_t {
return htons(input); });
The above would be a no-op if you were on a big-endian system, so I would look for whatever your platform uses as a compile-time condition to decide whether htons is a no-op. It is O(n) after all. On a Mac, it would be something like ...
#if (__DARWIN_BYTE_ORDER != __DARWIN_BIG_ENDIAN)
std::transform(word_storage.cbegin(), word_storage.cend()
, word_storage.begin(), [](const uint16_t input)->uint16_t {
return htons(input); });
#endif
A: Not as efficient as using an intrinsic function, but certainly portable. My answer:
#include <cstdint>
#include <type_traits>
/**
* Perform an endian swap of bytes against a templatized unsigned word.
*
* @tparam value_type The data type to perform the endian swap against.
* @param value The data value to swap.
*
* @return value_type The resulting swapped word.
*/
template <typename value_type>
constexpr inline auto endian_swap(value_type value) -> value_type
{
using half_type = typename std::conditional<
sizeof(value_type) == 8u,
uint32_t,
typename std::conditional<sizeof(value_type) == 4u, uint16_t, uint8_t>::
type>::type;
size_t const half_bits = sizeof(value_type) * 8u / 2u;
half_type const upper_half = static_cast<half_type>(value >> half_bits);
half_type const lower_half = static_cast<half_type>(value);
if (sizeof(value_type) == 2u)
{
return (static_cast<value_type>(lower_half) << half_bits) | upper_half;
}
return ((static_cast<value_type>(endian_swap(lower_half)) << half_bits) |
endian_swap(upper_half));
}
A: A c++20 branchless version now that std::endian exists but before c++23 adds std::byteswap
#include <bit>
#include <type_traits>
#include <concepts>
#include <array>
#include <cstring>
#include <iostream>
#include <bitset>
template <int LEN, int OFF=LEN/2>
class do_swap
{
// FOR 8 bytes:
// LEN=8 (LEN/2==4) <H><G><F><E><D><C><B><A>
// OFF=4: FROM=0, TO=7 => [A]<G><F><E><D><C><B>[H]
// OFF=3: FROM=1, TO=6 => [A][B]<F><E><D><C>[G][H]
// OFF=2: FROM=2, TO=5 => [A][B][C]<E><D>[F][G][H]
// OFF=1: FROM=3, TO=4 => [A][B][C][D][E][F][G][H]
// OFF=0: FROM=4, TO=3 => DONE
public:
enum consts {FROM=LEN/2-OFF, TO=(LEN-1)-FROM};
using NXT=do_swap<LEN, OFF-1>;
// flip the first and last for the current iteration's range
static void flip(std::array<std::byte, LEN>& b)
{
std::byte tmp=b[FROM];
b[FROM]=b[TO];
b[TO]=tmp;
NXT::flip(b);
}
};
template <int LEN>
class do_swap<LEN, 0> // STOP the template recursion
{
public:
static void flip(std::array<std::byte, LEN>&)
{
}
};
template<std::integral T, std::endian TO, std::endian FROM=std::endian::native>
requires ((TO==std::endian::big) || (TO==std::endian::little))
&& ((FROM==std::endian::big) || (FROM==std::endian::little))
class endian_swap
{
public:
enum consts {BYTE_COUNT=sizeof(T)};
static T cvt(const T integral)
{
// if FROM and TO are the same -- nothing to do
if (TO==FROM)
{
return integral;
}
// endian::big --> endian::little is the same as endian::little --> endian::big
// the bytes have to be reversed
// memcpy seems to be the most supported way to do byte swaps in a defined way
std::array<std::byte, BYTE_COUNT> bytes;
std::memcpy(&bytes, &integral, BYTE_COUNT);
do_swap<BYTE_COUNT>::flip(bytes);
T ret;
std::memcpy(&ret, &bytes, BYTE_COUNT);
return ret;
}
};
std::endian big()
{
return std::endian::big;
}
std::endian little()
{
return std::endian::little;
}
std::endian native()
{
return std::endian::native;
}
long long swap_to_big(long long x)
{
return endian_swap<long long, std::endian::big>::cvt(x);
}
long long swap_to_little(long long x)
{
return endian_swap<long long, std::endian::little>::cvt(x);
}
void show(std::string label, long long x)
{
std::cout << label << "\t: " << std::bitset<64>(x) << " (" << x << ")" << std::endl;
}
int main(int argv, char ** argc)
{
long long init=0xF8FCFEFF7F3F1F0;
long long to_big=swap_to_big(init);
long long to_little=swap_to_little(init);
show("Init", init);
show(">big", to_big);
show(">little", to_little);
}
A: Came here looking for a Boost solution and left disappointed, but finally found it elsewhere. You can use boost::endian::endian_reverse. It's templated/overloaded for all the primitive types:
#include <iostream>
#include <iomanip>
#include "boost/endian/conversion.hpp"
int main()
{
uint32_t word = 0x01;
std::cout << std::hex << std::setfill('0') << std::setw(8) << word << std::endl;
// outputs 00000001;
uint32_t word2 = boost::endian::endian_reverse(word);
// there's also a `void ::endian_reverse_inplace(...) function
// that reverses the value passed to it in place and returns nothing
std::cout << std::hex << std::setfill('0') << std::setw(8) << word2 << std::endl;
// outputs 01000000
return 0;
}
Demonstration
Although, it looks like c++23 finally put this to bed with std::byteswap. (I'm using c++17, so this was not an option.)
A: Look up bit shifting, as this is basically all you need to do to swap from little -> big endian. Then depending on the bit size, you change how you do the bit shifting.
A: Here's how to read a double stored in IEEE 754 64 bit format, even if your host computer uses a different system.
/*
* read a double from a stream in ieee754 format regardless of host
* encoding.
* fp - the stream
* bigendian - set to if big bytes first, clear for little bytes
* first
*
*/
double freadieee754(FILE *fp, int bigendian)
{
unsigned char buff[8];
int i;
double fnorm = 0.0;
unsigned char temp;
int sign;
int exponent;
double bitval;
int maski, mask;
int expbits = 11;
int significandbits = 52;
int shift;
double answer;
/* read the data */
for (i = 0; i < 8; i++)
buff[i] = fgetc(fp);
/* just reverse if not big-endian*/
if (!bigendian)
{
for (i = 0; i < 4; i++)
{
temp = buff[i];
buff[i] = buff[8 - i - 1];
buff[8 - i - 1] = temp;
}
}
sign = buff[0] & 0x80 ? -1 : 1;
/* exponet in raw format*/
exponent = ((buff[0] & 0x7F) << 4) | ((buff[1] & 0xF0) >> 4);
/* read inthe mantissa. Top bit is 0.5, the successive bits half*/
bitval = 0.5;
maski = 1;
mask = 0x08;
for (i = 0; i < significandbits; i++)
{
if (buff[maski] & mask)
fnorm += bitval;
bitval /= 2.0;
mask >>= 1;
if (mask == 0)
{
mask = 0x80;
maski++;
}
}
/* handle zero specially */
if (exponent == 0 && fnorm == 0)
return 0.0;
shift = exponent - ((1 << (expbits - 1)) - 1); /* exponent = shift + bias */
/* nans have exp 1024 and non-zero mantissa */
if (shift == 1024 && fnorm != 0)
return sqrt(-1.0);
/*infinity*/
if (shift == 1024 && fnorm == 0)
{
#ifdef INFINITY
return sign == 1 ? INFINITY : -INFINITY;
#endif
return (sign * 1.0) / 0.0;
}
if (shift > -1023)
{
answer = ldexp(fnorm + 1.0, shift);
return answer * sign;
}
else
{
/* denormalised numbers */
if (fnorm == 0.0)
return 0.0;
shift = -1022;
while (fnorm < 1.0)
{
fnorm *= 2;
shift--;
}
answer = ldexp(fnorm, shift);
return answer * sign;
}
}
For the rest of the suite of functions, including the write and the integer routines see my github project
https://github.com/MalcolmMcLean/ieee754
A: void writeLittleEndianToBigEndian(void* ptrLittleEndian, void* ptrBigEndian , size_t bufLen )
{
char *pchLittleEndian = (char*)ptrLittleEndian;
char *pchBigEndian = (char*)ptrBigEndian;
for ( size_t i = 0 ; i < bufLen ; i++ )
pchBigEndian[bufLen-1-i] = pchLittleEndian[i];
}
std::uint32_t row = 0x12345678;
char buf[4];
writeLittleEndianToBigEndian( &row, &buf, sizeof(row) );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "253"
}
|
Q: How to create a custom template for WCSF (.NET 2.0)? I'm new to the WCSF and can't seem to find anything related to "building a custom template" for creating the views/presenters/code-behinds/etc with your own flavor ...
Can anyone point me in the right direction?
A: you can find useful information about how to modifying the guidance package in the Modifying the Guidance Package topic of the WCSF Documentation. There you will find guidelines about how to create/update templates.
Let me know if this helps,
Ezequiel Jadib
http://blogs.southworks.net/ejadib
A: Default Install Location to T4 templates can be found here
C:\Program Files\Microsoft Web Client Factory\WCSF Guidance Package\Templates\T4\
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Thinking of learning Maven I have a side project I do = in Java. It's a pretty straight-forward webapp. It runs in Tomcat on a Linux Server and uses a MySQL database. The majority of the code was written with the Spring Framework. It has a lot of Unit Tests in place. When I'm coding it's in Eclipse. When I deploy the application I run a few shell scripts to move a WAR file to the web server, do Database updates, and make changes to apache configs. I'm the only developer working on it, and right now it's only deployed to 1 environment(production), although some day I might want to have a testing or staging environment as well. I use SVN version control, via the Eclipse plug-in.
I'm always hearing about people using Maven for their projects. Since so many people are using it, I'm saying to myself it must be good. I'd like to learn it in my spare time. The only thing is I'm not quite sold on why I'd want to use Maven? Does my first paragraph sound like a project appropriate for Maven? Does it have any specific advantages for a project that interacts with a Database?
A: Maven would be just fine for what you want to do. Unlike most build tools, maven uses conventions wisely (well, better than many others at least), and it has "plugins" for every area you mentioned:
Unit tests: maven surefire plugin
Eclipse Integration: m2eclipse
Deploying WAR file: WAR plugin and Deploy plugin
Maven can also help you in integration tests on Tomcat (if you have some), since you can start, stop or deploy a war using the cargo plugin.
Anyway if you're planning to read in your spare time, here's a free book (PDF format): Maven the definitive guide
Hope it helps!
A: I'm using maven in anger at work. It's a harsh mistress. It makes things easy as long as you're doing things many other people have and, this is important, as long as you're doing them the way maven thinks you should be doing them. Step off that narrow path and it will fight you every step of the way.
I've been impressed by BuildR from using it on the side. It's flexable like ANT while leveraging maven's dependency system. Also, it's in incubation, so it's a little rough around the edges.
A: Your project does not sound like a project appropriate for Maven. You seem to have a working development environment. Why set up another one? It will just give you one more project file to maintain which breaks the good ol' DRY principle.
A: I once started a new temp job that was using Maven. Burned 2 days trying to figure out how their maven build worked. Turned out they were all using maven 1.01 on windows, and I'd been inadvertently trying to build on 1.02, so it didn't work for me. No one in the place new how it worked, and they'd been using it for months and they were happy with it. A few months later on the same project I had to dig deep into the jelly scripts to change a single build variable. It was not fun.
When I first started using it, I read "convention over configuration", and "uses a standard set of directories". These were not anywhere I could find on the docs. I guess you were supposed to guess.
My opinions:
*
*any tool you use that you don't completely understand is a mistake, and a potential boat anchor to your development process. If the tool is really, really complicated, you're liable to use the simplest parts of it rather than mastering it deeply. If you're not using or shying away from the most powerful parts of the tool, you're likely defeating the purpose of using it.
*Maven is a classic example of something so full of automagic goodness that you don't have a clue what it's doing unless you dedicate far more of your time than a build tool deserves to becoming a maven maven. An over-engineered solution in search of a problem.
*I did not find any instances of things I needed to do that I couldn't do with ant and needed maven for. I know there are some, I just never needed them. If I did I'd probably be more charitable regarding the effort required to deal with maven.
*It makes your build depend on the internet. It's not uncommon now to download a small project, run mvn, and have maven download 10 plugins before it even begins to build what you're trying to build in the first place. What's it doing? No way to know really, but you'd better hope it doesn't break. When it does fail, the complexity of the failure and the piled-on layers of dependencies make it essentially hopeless to debug. I fail to see why this is in any way an improvement on simpler build tools or even desirable for any reason.
In summary, it's almost magic, except that when it doesn't work you'll likely have no idea why. This seems like a bad tradeoff. This was, to be fair, a few years ago. I know I am being unkind, and it's improved in subsequent versions (which I've used as well). Nevertheless, I hated it (can you tell?)
A: We do exactly what you do in our projects, and we use maven. You'd want to use maven to have a standardized layout and way to build your project. You never have to store all those jar dependencies in SVN or keep them somewhere special, maven does that for you. Maven also serves as a means to get other developers to understand your project easily. Once you start using it, you'll never want to look back :)
A: apart from the fact that a lot of oss projects are using (or converting to) maven and some closed source projects are moving to maven, your project does NOT necessarily benefit a lot from using Maven.
However, if you will consider open sourcing it, then the users of your project might benefit from your project employing maven.
Some of the important benefits of maven(jar dependencies) can be had with ivy(http://ant.apache.org/ivy/).
Then again, since you seem to be indicating that you're the only developer. if maven doesn't work for you, you can quickly revert back.
BR,
~A
A: Maven would be a good fit for your project IMO. Maven is an all around build and deployment management tool. It's biggest strength is that it makes build scripts significantly eaiser to maintain than functionally comparable Ant files or shell scripts.
There are a lot of advantages to using maven the biggest being it's preference of convention over configuration. This means that if you have your project laid out using the Maven directory structure there is almost no configuration required to get it building and running your JUnit tests.
The other big win that Maven gives you is dependency management. You can declaratively define your project's dependencies in Maven's config file called the Project Object Model (POM) and Maven does the work of storing all the jars in a local directory structure that it maintains. In the case of publicly available artifacts the jars are automatically downloaded from the Maven central repository and in the case of internal or proprietary 3rd party jars you can install them into your repository with a single command.
In addition to just organizing these artifacts and automatically setting up your build classpath to include all the necessary jars, maven will also manage dependency hierarchies. That means that if your project depends on jar A and A depends on jar B, jar B will automatically be bundled with your WAR even though you don't explicitly list it as a dependency in your build config.
Also, I'll say from a professional development standpoint it makes sense to learn Maven since in my experience Maven has overtaken Ant as the de jure build tool of choice both in open source and proprietary Java projects.
All this being said, if you have a build system that is fast and reliable for you, then it might not be worth the effort to convert over to Maven just for the sake of using the same tool everyone else is.
A: Don't. See what other people are saying, and research carefully. Also consider looking at some of my other comments on Maven here on SO.
A: I used maven for dependency management some time ago, because I was tired of adding all the jars, if I wanted to test it on another box or so. You don't really have to 'learn' it for this, it doesn't take much time until you learn it.
However the easiest thing would be to just ask somebody who already knows mvn, so he can show you how it works and then you learn it quite fast.
A: One of Maven's great strengths is that it does a lot of the build/dependency management without you writing any build scripts or having to even describe your build process. You already have your project setup so you won't benefit from Maven setting up the project shell for you or downloading the dependencies you specify with out you having to download them individually. If your goal is to learn how to use and administer Maven then doing so for a project like this where there are no other developers and the build process is very simple (from what I can tell) is not going to help much either. So I would recommend against using Maven for the existing project.
I would however setup a simple test application similar to yours using Maven and compare it to your project's structure to see if you follow best practices(at least as the Maven developers see them) and if your application follows standard web application conventions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How do I use mod_rewrite to change the path and filename of a URL I want to take the url:
http://www.mydomain.com/signup-12345
And actually give them:
http://www.mydomain.com/signup/?aff=12345
I have NO history with mod_rewrite, HELP!
A: Try this :
RewriteRule ^/signup-(\d+)/$ /signup/?aff=$1 [I]
A: Something that I found relatively hard to find out was how to do the reverse of what you are doing, whereby you need to find out the value of part of the query string.
So for example:
If you wanted to rewrite the Url:
http://www.example.com/signup-old-script.asp?aff=12345
to:
http://www.example.com/signup-new-script.php?affID=12345
you could use:
RewriteCond %{query_string}& ^aff=((.+&)|&)$
RewriteRule ^/signup-old-script.asp$ /signup-new-script.php?affID=%2 [L,R]
Notice the % sign in the rewrite rule instead of the $ sign.
I had to do this so I could support old flash maps in a new site that had links to ".cfm" files with an ID in the query string.
A: As far i know,
flag causes the RewriteCond to be ignored. - for "Ignore case" - from IsapiRewrite version 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Where'd my generic ActionLink go? Moved from preview 2 to preview 5 and now my Html.ActionLink calls are all failing. It appears that the generic version has been replaced with a non-type safe version.
// used to work
<li>
<%= Html.ActionLink<HomeController>(c => c.Index(), "Home")%>
</li>
// what appears I can only do now
<li>
<%= Html.ActionLink<HomeController>("Index", "Home")%>
</li>
Why did The Gu do this? Has it been moved to Microsoft.Web.Mvc or somewhere else as a "future"? Is there a replacement that is generic? Halp!
A: Don't blame the GU, it's my fault. That method has been moved to MvcFutures. Here's a blog post that provides the foundation for why this change was made.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What are table-driven methods? What is a "table-driven method"?
As mentioned by Bill Gates in the second Windows Vista commercial at 1:05.
A: The referenced video has Bill Gates reading from the book Code Complete by Steve McConnell. Jeff Atwood mentioned this in his blog (the YouTube links match up).
From Code Complete, 2nd edition:
A table-driven method is a scheme that allows you to look up information in a table rather than using logic statements (if and case) to figure it out.
McConnell uses an array as his "table" in his examples, but I think the concept can be applied to database tables or anything else that is table-like.
The concept is really best explained through an example.
Let's say you're running a restaurant and have a different number of seats for each table number.
Your logic to get the number of seats for a particular table might look something like
if table number == 1
table has 4 seats
else if table number == 2
table has 8 seats
. . .
so if you have 50 tables you would have 100 lines of code just to determine the number of seats.
Using table-driven methods, you could make an array with the index representing the table number and the value representing the number of seats, so your logic would instead look something like
tables [] = {4, 8, 2, 4, ...}
table seats = tables[table number]
which is simpler, shorter, and easier to maintain.
A: A table-driven method is quite simple. Use data structures instead of if-then statements to drive program logic. For example, if you are processing two types of records (tv versus cable) you might do this:
hash[tv] = process_tv_records
hash[cable] = process_cable_records
In some languages, like Ruby or Perl, this technique is straightforward. In Java, you'd need to use Reflection to find method handles.
If you want to learn about decision tables, investigate the Fitnesse testing framework at http://fitnesse.org/.
A:
Table-driven methods are schemes that allow you to look up information in a table rather than using logic statements (i.e. case, if). In simple cases, it's quicker and easier to use logic statements, but as the logic chain becomes more complex, table-driven code is simpler than complicated logic, easier to modify and more efficient.
Reference: McConnell, Steve. Code Complete, Second Edition. Redmond (Washington): Microsoft, 2004. Print. Page 411, Paragraph 1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Gsoap Error in C++ I am using gsoap to create a soap server in C++. Messages are routed through a bus written in Java. Both the server and the bus are multithreaded. Everything works well sending one message at a time through the system. If I start 3 clients each sending messages as fast as possible everything is fine for about 3500 messages. Then I begin receiving periodic "Only one socket connection allowed at a time." errors from the gsoap code. Typical about 3950 of 4000 messages make it through OK. With all 50 failures happening in the last 500 sends.
*
*Why would these errors occur after many sends, but not at the beginning of the sending? The rate of send does not increase.
*What is it talking about? I cannot find any explanation of the error, and its meaning is not clear to me.
*Anyone successfully multithreaded a gsoap app?
Here is my server code.
long WINAPI threadGO(soap *x);
int main(int argc, char* argv[])
{
HANDLE thread1;
int m, s; /* master and slave sockets */
struct soap *soap = soap_new();
if (argc < 2)
soap_serve(soap); /* serve as CGI application */
else
{
m = soap_bind(soap, NULL, atoi(argv[1]), 100);
if (m < 0)
{
soap_print_fault(soap, stderr);
exit(-1);
}
fprintf(stderr, "Socket connection successful: master socket = %d\n", m);
for (;;)
{
s = soap_accept(soap);
thread1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)threadGO,soap_copy(soap),0,NULL);
}
}
soap_done(soap);
free(soap);
return 0;
}
long WINAPI threadGO(soap *x)
{
soap_serve(x);
soap_end(x);
return 0
;
}
A: I believe you've got a resource leak in threadGO.
After copying the soap struct with soap_copy(), I believe it needs to be freed by calling all of:
soap_destroy(x);
soap_end(x);
soap_free(x);
Specifically, the missing call to soap_done() (which is called from soap_free()) calls soap_closesock(), which closes the socket.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Automated way to detect tests that can't fail, checked in to get by minmum code coverage? I have a dev, that will get around our code coverage by writing tests that never fail.
The code is just atrocious, but the tests never catch it because they assert(true).
I code review, but I can't do everyones work for them, all the time. How do you get people like this motivated to make good software?
Is there a build plugin for detecting tests that can't fail?
C#, mbUnit tests.
A: Real motiviation comes from within. Some people will game the system every chance they get sometimes for no other reason than they can. Others do it simply because they are hacks.
That said, assuming your the manager, have a "come to jesus" meeting with the dev. If that still doesn't work, there's always the door.
If you're not the manager, then take it up the proper channels.
A: I think you've almost answered the question for yourself there. If you have someone work for you or with you (you're not clear no whether you are this dev's manager) then if they are not doing the job properly then surely there are procedures that are available to make it clear to this person that they are not producing work to an acceptable standard.
Is the dev new to TDD? Maybe they need some tuition on writing good tests etc. Otherwise they need a kick up the ass and have it stressed to them that the tests are as if not more important than the code he/she is producing.
Oh yeah, and on the plugin thing, forget that, just the same code reviewing you're doing should be good enough.
A: You should really specify the language / framework you're using.
In the simplest case, I suppose it should be easy to detect assert(true) strings with simple grep-ping.
A: You could always try a test run with garbage for the application configuration values.
Any tests that pass are suspect?
A: Instead of spending time on looking for tests that can't fail, how about extending the tests a bit - make the code fail in many ways. That would
*
*Show him how to write better tests
*Force him to fix his code, and prevent more bad code from being checked in
A piece of buggy code you have to use would be a good starting point -- you must be sure it works...
A: Take the interface he's testing and reduce it to it's simplest form. In other words, take the class/method signatures and only add the code needed to compile beyond that. Run his tests against that. Ask him why his tests are passing when the program does nothing.
A: Code Review, by two or more developers who are already test infected, is probably the best way to get the dev in question to see that automated unit testing is really not that difficult, nor unusual. Having two test infected developers on each review will reinforce the importance of quality unit tests to him.
Also, assigning him reviews of other developer's code which is well tested will help him learn how to unit test.
You should have a look at doing some mutation testing, to detect weak tests. Nester, (the .Net equivalent of Jester) is one tool which you may find useful.
Please let us know how you go!
Update: I came across: "Why do most developers not write unit tests, still?" and thought it would be good reading here as well.
A: I think you need to try to get him to write a failing test first. Try to get him into that habit. Often ppl new to unit tests have a hard time writing them.
Also there are some tools that can help you to "explore all possible code paths". I suggest you take a look at, PEX which will generate automated tests, and it will most likely break his code... While this might not be an optimal soultion, try to promoted the concept of a shared code base.
Get your devs to pair program, it is much harder to "be lazy" when you are working with someone else on the same function, and it will spread the code ownership around. You seem to be not doing this, since you talk about "his" code. It can be supprising how much you can get done if there are 2 persons working on the same job, It will increase the quality by a lot.
Also Unit-Tests are not the holy grail to eradicate all problems... They should be one of the tools you have at your disposal.
Whats your code cover requirement?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a Java-based ray tracing model that can be adapted for use in underwater acoustics? I am looking for an open-source Java-based raytracing system suitable for use in modeling underwater ray-based acoustics. Such a package might be similar to the Comprehensive Acoustic System Simulation (CASS) with the Gaussian Ray Bundle (GRAB) but I would prefer an open-source, free-to-use or free-to-modify model that I can use in presentations to an open forum (e.g., JavaOne).
The best model for my needs would provide ray path modeling based on an environmental model, bathymetry (also known as ocean bottom topography) and emitter frequency spectra. Note: multipath effects (including reflection and refraction) are my primary points of interest so the best package would provide that right out of the box.
Slightly less optimal would be a standard Java-based ray-tracing package (optical or acoustic) that can handle a a varying speed through the medium. Another way of saying this would be that the index of refraction varies in a continuous fashion throughout the medium (though its first derivative might not be continuous).
A: The RaPSor project appears to be a java based ray-tracing simulator. It actually stands for Radio Propagation Simulator and was developed initially to support radio signal propagation for things like projecting dead spots in the WiFi coverage in buildings.
Reading through some of the use case paper for it shows that it does ray tracing and can be extends to support acoustic ray tracing. The blog article that tipped me off refers to the idea of figuring out the acoustic sound field for a room, but I don't see why it needs to be limited to in-air propagation.
Also, it was built using the NetBeans project.
A: Would you consider a very well documented C++ raytracer?
pbrt is a physically based raytracer written in the literate style, it comes with a nice book describing the code in considerable detail. A quick search shows that it has been used for acoustic modelling for a student project.
A: Have you taken a look at the Rings project? I don't know enough about ray tracing to judge whether or not Rings is implemented in the way you need it to be for maximum usefulness. The documentation and examples seem pretty good.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Bash prompt in OS X terminal broken I am using bash in os X Terminal app, and my custom $PS1 breaks when I scroll through my history.
PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\n\[${red}\$${NC}\]"
also tried
PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\r\n[${red}\$${NC}]"
The problem seems to be in the newline. I have used this bash prompt on Slackware no prob.
A: You need the [ and ] arond every escape sequence; do $BLUE and the like include these? If not, they need to be bracketed with these calls.
A: To avoid such 'escaping' difficulties as you prompt needs evole to be more complex, this should be a skeleton to start growing on:
function _my_prompt ()
{
# magic goes here
my_prmpt=....
}
PROMPT_COMMAND='_my_prompt'
PS1="[\$my_prmpt] \$"
A: I was having the same problem when logging on remote (debian) systems. As the escaped values in .bashrc all were nicely bracketed, I did some googling and discovered that the cause might be differences in window size on the local and the remote system. Adding
shopt -s checkwinsize
to .bashrc on the remote systems has fixed the problem for me.
Source: http://forums.macosxhints.com/showthread.php?t=17068
A: If the problem seems to be with the newline, try putting \r\n instead of just \n and see if it makes a difference.
A: I get the same problem (on OS X) with your PS1.
If I remove the \[ and \]
PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\n${red}\$${NC}"
this works fine. Are the sqare brackets needed? I've never used them, but from the docs:
\[
Begin a sequence of non-printing characters. This could be used to
embed a terminal control sequence into
the prompt.
\]
End a sequence of non-printing characters.
A: I have now tried
PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w${RED}\r\n\$\[${blue}\]"
Which seems to work
The brackets needed to make previous commands work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to enumerate an enum? How can you enumerate an enum in C#?
E.g. the following code does not compile:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
And it gives the following compile-time error:
'Suit' is a 'type' but is used like a 'variable'
It fails on the Suit keyword, the second one.
A: You won't get Enum.GetValues() in Silverlight.
Original Blog Post by Einar Ingebrigtsen:
public class EnumHelper
{
public static T[] GetValues<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List<T> values = new List<T>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
values.Add((T)value);
}
return values.ToArray();
}
public static object[] GetValues(Type enumType)
{
if (!enumType.IsEnum)
{
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
}
List<object> values = new List<object>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
values.Add(value);
}
return values.ToArray();
}
}
A: It looks to me like you really want to print out the names of each enum, rather than the values. In which case Enum.GetNames() seems to be the right approach.
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (string name in Enum.GetNames(typeof(Suits)))
{
System.Console.WriteLine(name);
}
}
By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.
I would use Enum.GetValues(typeof(Suit)) instead.
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (var suit in Enum.GetValues(typeof(Suits)))
{
System.Console.WriteLine(suit.ToString());
}
}
A: I think you can use
Enum.GetNames(Suit)
A: My solution works in .NET Compact Framework (3.5) and supports type checking at compile time:
public static List<T> GetEnumValues<T>() where T : new() {
T valueType = new T();
return typeof(T).GetFields()
.Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
.Distinct()
.ToList();
}
public static List<String> GetEnumNames<T>() {
return typeof (T).GetFields()
.Select(info => info.Name)
.Distinct()
.ToList();
}
*
*If anyone knows how to get rid of the T valueType = new T(), I'd be happy to see a solution.
A call would look like this:
List<MyEnum> result = Utils.GetEnumValues<MyEnum>();
A: public void PrintAllSuits()
{
foreach(string suit in Enum.GetNames(typeof(Suits)))
{
Console.WriteLine(suit);
}
}
A:
foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }
I've heard vague rumours that this is
terifically slow. Anyone know? – Orion
Edwards Oct 15 '08 at 1:31 7
I think caching the array would speed it up considerably. It looks like you're getting a new array (through reflection) every time. Rather:
Array enums = Enum.GetValues(typeof(Suit));
foreach (Suit suitEnum in enums)
{
DoSomething(suitEnum);
}
That's at least a little faster, ja?
A: foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}
Note: The cast to (Suit[]) is not strictly necessary, but it does make the code 0.5 ns faster.
A: enum types are called "enumeration types" not because they are containers that "enumerate" values (which they aren't), but because they are defined by enumerating the possible values for a variable of that type.
(Actually, that's a bit more complicated than that - enum types are considered to have an "underlying" integer type, which means each enum value corresponds to an integer value (this is typically implicit, but can be manually specified). C# was designed in a way so that you could stuff any integer of that type into the enum variable, even if it isn't a "named" value.)
The System.Enum.GetNames method can be used to retrieve an array of strings which are the names of the enum values, as the name suggests.
EDIT: Should have suggested the System.Enum.GetValues method instead. Oops.
A: For getting a list of int from an enum, use the following. It works!
List<int> listEnumValues = new List<int>();
YourEnumType[] myEnumMembers = (YourEnumType[])Enum.GetValues(typeof(YourEnumType));
foreach ( YourEnumType enumMember in myEnumMembers)
{
listEnumValues.Add(enumMember.GetHashCode());
}
A: Just by combining the top answers, I threw together a very simple extension:
public static class EnumExtensions
{
/// <summary>
/// Gets all items for an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum
{
return (T[])Enum.GetValues(typeof (T));
}
}
It is clean, simple, and, by @Jeppe-Stig-Nielsen's comment, fast.
A: Three ways:
*
*Enum.GetValues(type) // Since .NET 1.1, not in Silverlight or .NET Compact Framework
*type.GetEnumValues() // Only on .NET 4 and above
*type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null)) // Works everywhere
I am not sure why GetEnumValues was introduced on type instances. It isn't very readable at all for me.
Having a helper class like Enum<T> is what is most readable and memorable for me:
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
public static IEnumerable<T> GetValues()
{
return (T[])Enum.GetValues(typeof(T));
}
public static IEnumerable<string> GetNames()
{
return Enum.GetNames(typeof(T));
}
}
Now you call:
Enum<Suit>.GetValues();
// Or
Enum.GetValues(typeof(Suit)); // Pretty consistent style
One can also use some sort of caching if performance matters, but I don't expect this to be an issue at all.
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
// Lazily loaded
static T[] values;
static string[] names;
public static IEnumerable<T> GetValues()
{
return values ?? (values = (T[])Enum.GetValues(typeof(T)));
}
public static IEnumerable<string> GetNames()
{
return names ?? (names = Enum.GetNames(typeof(T)));
}
}
A: When you have a bit enum like this
enum DemoFlags
{
DemoFlag = 1,
OtherFlag = 2,
TestFlag = 4,
LastFlag = 8,
}
With this assignement
DemoFlags demoFlags = DemoFlags.DemoFlag | DemoFlags.TestFlag;
and need a result like this
"DemoFlag | TestFlag"
this method helps:
public static string ConvertToEnumString<T>(T enumToConvert, string separator = " | ") where T : Enum
{
StringBuilder convertedEnums = new StringBuilder();
foreach (T enumValue in Enum.GetValues(typeof(T)))
{
if (enumToConvert.HasFlag(enumValue)) convertedEnums.Append($"{ enumValue }{separator}");
}
if (convertedEnums.Length > 0) convertedEnums.Length -= separator.Length;
return convertedEnums.ToString();
}
A: A simple Enum.GetNames(EnumType) should work
A: I made some extensions for easy enum usage. Maybe someone can use it...
public static class EnumExtensions
{
/// <summary>
/// Gets all items for an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>(this Enum value)
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
/// <summary>
/// Gets all items for an enum type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static IEnumerable<T> GetAllItems<T>() where T : struct
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
/// <summary>
/// Gets all combined items from an enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <example>
/// Displays ValueA and ValueB.
/// <code>
/// EnumExample dummy = EnumExample.Combi;
/// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
/// {
/// Console.WriteLine(item);
/// }
/// </code>
/// </example>
public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
foreach (object item in Enum.GetValues(typeof(T)))
{
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);
if (itemAsInt == (valueAsInt & itemAsInt))
{
yield return (T)item;
}
}
}
/// <summary>
/// Determines whether the enum value contains a specific value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="request">The request.</param>
/// <returns>
/// <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
/// </returns>
/// <example>
/// <code>
/// EnumExample dummy = EnumExample.Combi;
/// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
/// {
/// Console.WriteLine("dummy contains EnumExample.ValueA");
/// }
/// </code>
/// </example>
public static bool Contains<T>(this Enum value, T request)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);
if (requestAsInt == (valueAsInt & requestAsInt))
{
return true;
}
return false;
}
}
The enum itself must be decorated with the FlagsAttribute:
[Flags]
public enum EnumExample
{
ValueA = 1,
ValueB = 2,
ValueC = 4,
ValueD = 8,
Combi = ValueA | ValueB
}
A: There are two ways to iterate an Enum:
1. var values = Enum.GetValues(typeof(myenum))
2. var values = Enum.GetNames(typeof(myenum))
The first will give you values in form on an array of **object**s, and the second will give you values in form of an array of **String**s.
Use it in a foreach loop as below:
foreach(var value in values)
{
// Do operations here
}
A: I use ToString() then split and parse the spit array in flags.
[Flags]
public enum ABC {
a = 1,
b = 2,
c = 4
};
public IEnumerable<ABC> Getselected (ABC flags)
{
var values = flags.ToString().Split(',');
var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
return enums;
}
ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
Console.WriteLine(item.ToString() + " ID=" + (int)item);
}
A: I do not hold the opinion this is better, or even good. I am just stating yet another solution.
If enum values range strictly from 0 to n - 1, a generic alternative is:
public void EnumerateEnum<T>()
{
int length = Enum.GetValues(typeof(T)).Length;
for (var i = 0; i < length; i++)
{
var @enum = (T)(object)i;
}
}
If enum values are contiguous and you can provide the first and last element of the enum, then:
public void EnumerateEnum()
{
for (var i = Suit.Spade; i <= Suit.Diamond; i++)
{
var @enum = i;
}
}
But that's not strictly enumerating, just looping. The second method is much faster than any other approach though...
A: Some versions of the .NET framework do not support Enum.GetValues. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:
public Enum[] GetValues(Enum enumeration)
{
FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
Enum[] enumerations = new Enum[fields.Length];
for (var i = 0; i < fields.Length; i++)
enumerations[i] = (Enum) fields[i].GetValue(enumeration);
return enumerations;
}
As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.
A: Also you can bind to the public static members of the enum directly by using reflection:
typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)
.ToList().ForEach(x => DoSomething(x.Name));
A: Here is a working example of creating select options for a DDL:
var resman = ViewModelResources.TimeFrame.ResourceManager;
ViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame
in Enum.GetValues(typeof(MapOverlayTimeFrames))
select new SelectListItem
{
Value = timeFrame.ToString(),
Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()
};
A: If you need speed and type checking at build and run time, this helper method is better than using LINQ to cast each element:
public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));
}
return Enum.GetValues(typeof(T)) as T[];
}
And you can use it like below:
static readonly YourEnum[] _values = GetEnumValues<YourEnum>();
Of course you can return IEnumerable<T>, but that buys you nothing here.
A: Add method public static IEnumerable<T> GetValues<T>() to your class, like:
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
Call and pass your enum. Now you can iterate through it using foreach:
public static void EnumerateAllSuitsDemoMethod()
{
// Custom method
var foos = GetValues<Suit>();
foreach (var foo in foos)
{
// Do something
}
}
A: Use Cast<T>:
var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();
There you go, IEnumerable<Suit>.
A: foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}
(The current accepted answer has a cast that I don't think
is needed (although I may be wrong).)
A: I know it is a bit messy, but if you are fan of one-liners, here is one:
((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));
A: New .NET 5 Solution:
.NET 5 has introduced a new generic version for the GetValues method:
Suit[] suitValues = Enum.GetValues<Suit>();
Which is now by far the most convenient way of doing this.
Usage in a foreach loop:
foreach (Suit suit in Enum.GetValues<Suit>())
{
}
And if you just need the enum names as strings, you can use the generic GetNames method:
string[] suitNames = Enum.GetNames<Suit>();
A: This question appears in Chapter 10 of "C# Step by Step 2013"
The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):
class Pack
{
public const int NumSuits = 4;
public const int CardsPerSuit = 13;
private PlayingCard[,] cardPack;
public Pack()
{
this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
{
for (Value value = Value.Two; value <= Value.Ace; value++)
{
cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
}
}
}
}
In this case, Suit and Value are both enumerations:
enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}
and PlayingCard is a card object with a defined Suit and Value:
class PlayingCard
{
private readonly Suit suit;
private readonly Value value;
public PlayingCard(Suit s, Value v)
{
this.suit = s;
this.value = v;
}
}
A: I think this is more efficient than other suggestions because GetValues() is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if Suit is not an enum.
EnumLoop<Suit>.ForEach((suit) => {
DoSomethingWith(suit);
});
EnumLoop has this completely generic definition:
class EnumLoop<Key> where Key : struct, IConvertible {
static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
static internal void ForEach(Action<Key> act) {
for (int i = 0; i < arr.Length; i++) {
act(arr[i]);
}
}
}
A: A simple and generic way to convert an enum to something you can interact:
public static Dictionary<int, string> ToList<T>() where T : struct
{
return ((IEnumerable<T>)Enum
.GetValues(typeof(T)))
.ToDictionary(
item => Convert.ToInt32(item),
item => item.ToString());
}
And then:
var enums = EnumHelper.ToList<MyEnum>();
A: What if you know the type will be an enum, but you don't know what the exact type is at compile time?
public class EnumHelper
{
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
public static IEnumerable getListOfEnum(Type type)
{
MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
return (IEnumerable)getValuesMethod.Invoke(null, null);
}
}
The method getListOfEnum uses reflection to take any enum type and returns an IEnumerable of all enum values.
Usage:
Type myType = someEnumValue.GetType();
IEnumerable resultEnumerable = getListOfEnum(myType);
foreach (var item in resultEnumerable)
{
Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
}
A: If you have:
enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
This:
foreach (var e in Enum.GetValues(typeof(Suit)))
{
Console.WriteLine(e.ToString() + " = " + (int)e);
}
Will output:
Spades = 0
Hearts = 1
Clubs = 2
Diamonds = 3
A: LINQ Generic Way:
public static Dictionary<int, string> ToList<T>() where T : struct =>
((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());
Usage:
var enums = ToList<Enum>();
A: I think its help you try it.
public class Program
{
public static List<T> GetEnamList<T>()
{
var enums = Enum.GetValues(typeof(T)).Cast<T>().Select(v => v).ToList();
return enums;
}
private void LoadEnumList()
{
List<DayofWeek> dayofweeks = GetEnamList<DayofWeek>();
foreach (var item in dayofweeks)
{
dayofweeks.Add(item);
}
}
}
public enum DayofWeek
{
Monday,
Tuesday,
Wensday,
Thursday,
Friday,
Sturday,
Sunday
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4304"
}
|
Q: How do you store/share online your personal documents? For photos, I use Flickr. But for other documents...Which web based online application (hosted or to install on your personal web site) do you use for PDF or word files ? If there is a user management it would be also great (for example you decide that some persons, or everyone, can see some of your documents...).
A: Google Docs?
It is capable of storing PDFs but your word documents will be converted to the the google doc format. (which then can be converted back to Word or RTF or PDF etc'
A: I personally use DropBox, but it doesn't have access control. drop.io has password protection, though, so that could be used for access control.
A: I use a subversion repository. I can browse it on the web if I need to, though I usually use TortoiseSVN to access it on windows machines. It's password protected, and it even has version control! :-)
A: I use :
*
*drop.io
*Dropbox
A: The problem with Google Docs is that it changes the format of uploaded docs in its own format, with catastrophic consequences (page layout, links, summaries...). What I would like is to keep my original documents as is , if I want to .
A: In the past I have created a small TrueCrypt container, zipped up my documents, added them to the TrueCrypt container and then e-mailed them to my GMail account.
Fiddly but effective. You can setup an Ant script on your desktop to create/update the zip and copy to the TrueCrypt folder and then perform the e-mail.
I have also used and am using DropBox for the same thing.
A: I use SkyDrive from Microsoft Live; plenty of space and easy access and I can use my Hotmail login (no need to remember a seperate username/password combo).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What are indexes and how can I use them to optimize queries in my database? I am maintaining a pretty sizable application and database and am noticing some poor database performance in a few of our stored procedures.
I always hear that "adding an index" can be done to help performance. I am certainly no DBA, and I do not understand what indexes are, why they help, and how to create them.
I basically need an indexes 101.
Can anyone give me resources so that I can learn?
A: Indexes is a method which database systems use to quickly find data. The real world analogy are indexes in books. If an author/publisher does a good job at indexing their book, it becomes pretty easy for the reader to directly go to the page they want to read simply by looking at the index. Same goes for a database. If an index is created on a field, the database pre-sorts the data. When a request is made on the data, the database uses the index to identify which location the data is stored in on the hard disk, and directly goes there. If there are no indexes, the database needs to look at every record in order to find out if it meets the criteria(s) of your query.
A simple way to look at indexes is by thinking of a deck of cards. A database which is not indexed is like a deck a cards which have been shuffled. If you want to find the king of spades, you need to look at every card one by one to find it. You might be lucky and it can be the first one, or you might be unlucky and it can be the last one.
A database which is indexed, has all the cards in the deck ordered from ace to king and each suite is set aside in its own pile. Looking for the king of spades is much simpler now because you simply need to look at the bottom of the pile of cards which contains the spades.
I hope this helps. Be warned though that although indexes are necessary in a relational database system, they can counter productive if you write too many of them. There's a ton of great articles on the web that you can read up on indexes. I'd suggest doing some reading before you dive into them.
A: An index basically sorts your data on the given columns and then stores that order, so when you want to find an item, the database can optimize by using binary search (or some other optimized way of searching), rather than looking at each individual row.
Thus, if the amount of data you are searching through is large, you will absolutely want to add some indexes.
Most databases have a tool to explain how your query will work (for db2, it's db2expln, something similar probably for sqlserver), and a tool to suggest indexes and other optimizations (db2advis for db2, again probably something similar for sqlserver).
A: As a rule of thumb, indexes should be on any fields that you use in joins or where clauses (if they have enough different values to make using an index worthwhile, field with only a few possible values doesn't benefit from an index which is why it is pointless to try to index a bit field).
If your structure has formally created primary keys (which it should, I never create a table without a primary key), those are by definition indexed becasue a primary key is required to have a unique index on it. People often forget that they have to index the foreign keys becasue an index is not automatically created when you set up the foreign key relationsship. Since the purpose of a foreign key is to give you a field to join on, most foreign keys should probably be indexed.
Indexes once created need to be maintained. If you have a lot of data change activity, they can get fragmented and slow performance and need to be refreshed. Read in Books online about indexes. You can also find the syntax for the create index statement there.
Indexes are a balancing act, every index you add usually will add time to data inserts, updates and deletes but can potentially speed up selects and joins in complex inserts, updates and deletes. There is no one formula for what are the best indexes although the rule of thumb above is a good place to start.
A: As previously stated, you can have a clustered index and multiple non-clustered indexes. In SQL 2005, you can also add additional columns to a non-clustered index, which can improve performance where a few commonly retrieved columns are included with the index but not part of the key, which eliminates a trip to the table altogether.
Your #1 tool for determining what your SQL Server database is doing is the profiler. You can profile entire workloads and then see what indexes it recommends. You can also look at execution plans to see what effects an index has.
The too-many indexes problem is due to writing into a database, and having to update all the indexes which would have a record for that row. If you're having read performance, it's probably not because of too many indexes, but too few, or too unsuitable.
A: Think of an index similar to a card catalog in the library. An index keeps you from having to search through every isle or shelf for a book. Instead, you may be able to find the items you want from a commonly used field, such as and ID, Name, etc. When you build an index the database basically creates something separate that a query could hit to rather than scanning the entire table. You speed up the query by allowing it to search a smaller subset of data, or an optimized set of data.
A: An index can be explained as a sorted list of the items in a register. It is very quick to lookup the position of the item in the register, by looking for it's key in the index. Next the the key in the index is a pointer to the position in the register where the rest of the record can be found.
You can have many indexes on a register, but the more you have, the slower inserting new records will be (because each index needs a new record as well - in a sorted order, which also adds time).
A: Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries.
Basically, your DBMS will create some sort of tree structure which points to the data (from one column) in a sorted manner. This way it is easier to search for data on that column(s).
http://en.wikipedia.org/wiki/Index_(database)
A: Some more index information!
Clustered indexes are the actual physical layout of the records in the table. Hence, you can only have one per table.
Nonclustered indexes are the aforementioned card catalog. Sure, the books are arranged in a particular order, but you can arrange the cards in the catalog by book size, or maybe by number of pages, or by alphabetical last name.
Something to think about -- creating too many indexes is a common pitfall. Every time your data gets updated your DB has to seek through that index and update it, inserting a record into every index on that table for that new row. In transactional systems (think: NYSE's stock transactions!) that could be an application killer.
A: for mssql (and maybe others) the syntax looks like:
create index <indexname> on <tablename>(<column1>[,<column2>...])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: 3rd party controls for MS SQL 2005 Reporting Services Can anyone recommend a good 3rd party control(s) for MS SQL 2005 Reporting Services. If you know some open library or implementation of such controls that could be very useful too.
A: Dundas do great RS add-ins if you have the budget:
http://www.dundas.com/index.aspx
A: I agree, Dundas has great controls. I used it in one of my projects.
This was the sample which I used to test out the CRI:
http://www.codeplex.com/MSFTRSProdSamples/Wiki/View.aspx?title=SS2005%21Custom%20Report%20Item%20Sample&referringTitle=Home
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What port is a given program using? I want to be able to figure out what port a particular program is using. Are there any programs available online or that come with windows that will tell me which processes are using which ports on my computer?
PS - before you downmod this for not being a programming question, I'm looking for the program to test some networking code.
A: If your prefer a GUI interface CurrPorts is free and works with all versions of windows. Shows ports and what process has them open.
A: "netstat -natp" is what I always use.
A: TCPView can do what you asked for.
A: Windows 8 (and likely 7 + Vista) also provide a view in Resource Monitor. If you select the Network tab, there's a section called 'Listening Ports'. Can sort by port number, and see which process is using it.
A: Windows comes with the netstat utility, which should do exactly what you want.
A: On Vista, you do need elevated privileges to use the -b option with netstat. To get around that, you could run "netstat -ano" which will show all open ports along with the associated process id. You could then use tasklist to lookup which process has the corresponding id.
C:\>netstat -ano
Active Connections
Proto Local Address Foreign Address State PID
...
TCP [::]:49335 [::]:0 LISTENING 1056
...
C:\>tasklist /fi "pid eq 1056"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
sqlservr.exe 1056 Services 0 66,192 K
A: netstat -b -a lists the ports in use and gives you the executable that's using each one. I believe you need to be in the administrator group to do this, and I don't know what security implications there are on Vista.
I usually add -n as well to make it a little faster, but adding -b can make it quite slow.
Edit: If you need more functionality than netstat provides, vasac suggests that you try TCPView.
A: You may already have Process Explorer (from Sysinternals, now part of Microsoft) installed. If not, go ahead and install it now -- it's just that cool.
In Process Explorer: locate the process in question, right-click and select the TCP/IP tab. It will even show you, for each socket, a stack trace representing the code that opened that socket.
A: At a command line, netstat -a will give you lots o' info.
A: You can use the 'netstat' command for this. There's a description of doing this sort of thing here.
A: Open Ports Scanner works for me.
A: most decent firewall programs should allow you to access this information. I know that Agnitum OutpostPro Firewall does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "100"
}
|
Q: Malloc inside a function call appears to be getting freed on return? I think I've got it down to the most basic case:
int main(int argc, char ** argv) {
int * arr;
foo(arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int * arr) {
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
}
The output is this:
> ./a.out
car[3]=-1869558540
a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer
being freed
*** set a breakpoint in malloc_error_break to debug
>
If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.
A: You've allocated arr in foo, but that pointers value is stored in the call stack. If you want to do this, do it like this:
void foo( int ** arr) {
*arr = (int *)malloc( sizeof(int) * 25 );
(*arr)[3] = 69;
}
And in main, simply pass a pointer to foo (like foo(&arr))
A: You pass the pointer by value, not by reference, so whatever you do with arr inside foo will not make a difference outside the foo-function.
As m_pGladiator wrote one way is to declare a reference to pointer like this (only possible in C++ btw. C does not know about references):
int main(int argc, char ** argv) {
int * arr;
foo(arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int * &arr ) {
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
}
Another (better imho) way is to not pass the pointer as an argument but to return a pointer:
int main(int argc, char ** argv) {
int * arr;
arr = foo();
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
int * foo(void ) {
int * arr;
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
return arr;
}
And you can pass a pointer to a pointer. That's the C way to pass by reference. Complicates the syntax a bit but well - that's how C is...
int main(int argc, char ** argv) {
int * arr;
foo(&arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int ** arr ) {
(*arr) = (int*) malloc( sizeof(int)*25 );
(*arr)[3] = 69;
}
A: foo receives a local copy of the int pointer, alloactes memory to it and leaks that memory when it goes out of scope.
One way to fix this to get foo to return the pointer:
int * foo() {
return (int*) malloc( sizeof(int)*25 );
}
int main() {
int* arr = foo();
}
Another is to pass foo a pointer to a pointer
void foo(int ** arr) {
*arr = malloc(...);
}
int main() {
foo(&arr);
}
In C++ it is simpler to modify foo to accept a reference to a pointer. The only change you need in C++ is to change foo to
void foo(int * & arr)
A: Since your are passing the pointer by value, the arr pointer inside main isn't pointing to the allocated memory. This means two thing: you've got yourself a memory leak (NO, the memory isn't freed after the function foo completes), and when you access the arr pointer inside main you are accessing some arbitrary range of memory, hence you don't get 3 printed out and hence free() refuses to work. You're lucky you didn't get a segmentation fault when accessing arr[3] inside main.
A: You cannot change the value of your argument (arr) if it's not passed in by reference (&). In general, you would want to return the pointer, so your method should be:
arr=foo();
It's bad juju to try to reassign arguments; I don't recommend the (&) solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: How do you maintain separate webservices for dev/stage/production We want to maintain 3 webservices for the different steps of deployment, but how do we define in our application which service to use? Do we just maintain 3 web references and ifdef the uses of them somehow?
A: As others have mentioned you'll want to stash this information in a config file. In fact, I'd suggest using a different configuration file for each environment. This will address the inevitable problem of having multiple settings for each environment, e.g. you might have separate settings for the web service URL and web service port or have some extra settings to deal with https/security.
All that said, make sure you address these potential issues:
If the web service does anything particularly essential to the application you might want to marry the application to web services in each environment (i.e. have a version of your application in each environment). Certainly, any changes to the interface are easier when you do it this way.
Make sure it's obvious to someone which version of the web service you are speaking with.
A: My recommendation would be to keep this information in configuration files for the application. Even better would be to inject the appropriate values for a given environment into the configuration during the build process, assuming your build process has some kind of macro-replacement functionality. This way you can create a targeted build for a given environment and not have to change the configuration every time you do a build for a different environment.
A: When I last worked on a project with a web server, we dealt with this problem as follows:
*
*msbuild /t:deploy would build & deploy to a test environment that was partially shared by the team, and partially dev-specific. The default value for $(SERVER) was $(USERNAME).
*msbuild /t:deploy /p:server=test would deploy to the shared test environment, which non-devs could look at.
*msbuild /t:deploy /p:server=live would deploy to live server. I think I added an extra handshake, like an error unless you had /p:secret=foo, just to make sure you didn't do this by accident.
A: Don't maintain the differences in code, but rather through a configuration file. That way they're all running the same code, just with different configuration values (ie. port to bind to, hostname to answer to, etc.)
A: All the stuff that can change from dev to test to prod must be configurable. If you can afford to build the process that updates these variable things during the installation of your product -- do it. (Baking the customizations into the build seems like an inferior idea -- you end up with a bunch of different incompatible builds for the same version of the source code)
A: FYI, this was addressed here yesterday:
How do you maintain java webapps in different staging environments?
A: Put the service address and port into your application's configuration. It's probably a good idea to do the same thing in the service's config, at least for the port, so that your dev service listens on the right port. This way you don't have to modify your code just to change the server/port you're hitting.
Using config rather than code for switching between dev, stage, and production is very valuable for testing. When you deploy to production you want to make sure you're deploying the same exact code that was tested, not something slightly different. All you should change between dev and production is the config.
A: Instead of using web references, generate the proxy classes from the web service WSDL's using wsdl.exe. The generated classes will have a Url property that can be set depending on the step of deployment (dev, qa, production, etc.).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I stop Blend 2.5 June Preview replacing Canvas.ZIndex with Panel.ZIndex on SL1.0 XAML? I have a Silverlight 1.0 application that I edit with Blend 2.5. Whenever I touch a UIElement in the designer that has a Canvas attribute such as Canvas.ZIndex="1", when it updates the XAML, it changes the Canvas prefix to Panel, leaving Panel.ZIndex="1", causing the page to fail to load.
How do I make it stop the insanity!?!
I have uninstalled 2.5 and reinstalled an older Blend 2 preview and that was better, but then compatibility with VS2k8 was not as good, and I'm also working on some SL2.0 projects from time to time, as well as WPF apps, both of which I prefer Blend 2.5 for.
A: Looks like it's a reported bug in 2.5,
http://social.expression.microsoft.com/forums/en-US/blend/thread/db02b75c-922e-4de1-8943-bd525d9862c0/
Their suggested workaround is to use 2.0 for SL1. Still, I expect there will be a new version of Blend released fairly shortly, since SL2 is likely to be released around PDC this year (end of October).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set proxy with credentials to generated WCF client? I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy.
If I use the web service, then it is possible to set proxy.
A: I'm not entirely sure if this is what you are looking for but here you go.
MyClient client = new MyClient();
client.ClientCredentials.UserName.UserName = "u";
client.ClientCredentials.UserName.Password = "p";
A: I resolved this by adding an Active Directory user to the Application Pool>Identity instead of network services. This user is also in a group who has permission to browse internet through proxy server. Also add this user to the IIS_WPG group on the client host server.
In the code below the first bit authenticate the client with the WCF service. The second bit suppose to pass the crendentials to internal proxy server so that the client call a WCF service on the DMZ server. But I don't think the proxy part is works. I am leaving the code anyway.
// username token credentials
var clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = ConfigurationManager.AppSettings["Client.Mpgs.Username"];
clientCredentials.UserName.Password = ConfigurationManager.AppSettings["Client.Mpgs.Password"];
proxy.ChannelFactory.Endpoint.Behaviors.Remove(typeof(ClientCredentials));
proxy.ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);
// proxy credentials
//http://kennyw.com/indigo/143
//http://blogs.msdn.com/b/stcheng/archive/2008/12/03/wcf-how-to-supply-dedicated-credentials-for-webproxy-authentication.aspx
proxy.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential
(
ConfigurationManager.AppSettings["Client.ProxyServer.Username"]
, ConfigurationManager.AppSettings["Client.ProxyServer.Password"]
, ConfigurationManager.AppSettings["Client.ProxyServer.DomainName"]
);
In my web.config I have used the following,
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy usesystemdefault="True" proxyaddress="http://proxyServer:8080/" bypassonlocal="False" autoDetect="False" /> </defaultProxy>
</system.net>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ITest" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
<message clientCredentialType="UserName" negotiateServiceCredential="true" algorithmSuite="Default"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://wcfservice.organisation.com/test/test.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITest" contract="Test.Test" name="WSHttpBinding_ITest"/>
</client>
</system.serviceModel>
The above code works from my local machine. When I upload the code to a dev server it does not work. I looked at the proxy server logs and it shows below,
2011-06-14 05:21:10 2 11.11.11.11 - - authentication_failed DENIED "Organisation/Finance" - 407 TCP_DENIED CONNECT - tcp wcfservice.organisation.com 443 / - - - 11.11.11.11 612 161 -
2011-06-14 05:21:10 6 11.11.11.152 ServerName$ - policy_denied DENIED "Organisation/Finance" - 403 TCP_DENIED CONNECT - tcp wcfservice.organisation.com 443 / - - - 11.11.11.205 185 361 -
Our smart system administrator DF added a Active Directory user to the Application Pool>Identity instead of network services. This user is also in a group who has permission to browse internet through proxy server. Also add this user to the IIS_WPG group on the client host server.
This worked for me.
A: Not sure if this is what you are looking for but the below is a working code sample to authenticate using the client credentials.
Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService")
client.ClientCredentials.UserName.UserName = "username"
client.ClientCredentials.UserName.Password = "password"
Dim ProductList As List(Of Product) = client.GetProducts()
mView.Products = ProductList
client.Close()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Is there any performance benefit with "chaining" statements in .NET? When retrieving a lookup code value from a table, some folks do this...
Dim dtLookupCode As New LookupCodeDataTable()
Dim taLookupCode AS New LookupCodeTableAdapter()
Dim strDescription As String
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
strDescription = dtLookupCode.Item(0).Meaning
...however, I've also seen things done "chained" like this...
strDescription = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL").Item(0).Meaning
...which bypasses having a lookup code data table in the first place since the table adapter knows what the structure of its result set looks like.
Does using the "chained" method save the overhead of creating the data table object, or does it effectively get created anyway in order to properly handle the .Item(0).Meaning statement?
A: Those two lines would compile down to the same thing. I would pick whichever one is easier for you read. Inlining normally refers to something a bit different.
A: Straying from the "inline" part of this, actually, the two sets of code won't compile out to the same thing. The issue comes in with:
Dim dtLookupCode As New LookupCodeDataTable()
Dim taLookupCode AS New LookupCodeTableAdapter()
In VB, this will create new objects with the appropriately-named references. Followed by:
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
We immediately replace the original dtLookupCode reference with a new object, which creates garbage to be collected (an unreachable object in RAM).
In the exact, original scenario, therefore, what's referred to as the "inline" technique is, technically, more performant. (However, you're unlikely to physically see that difference in this small an example.)
The place where the code would essentially be the same is if the original sample read as follows:
Dim taLookupCode AS New LookupCodeTableAdapter
Dim dtLookupCode As LookupCodeDataTable
Dim strDescription As String
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
strDescription = dtLookupCode.Item(0).Meaning
In this world, we only have the existing references, and are not creating junk objects. I reordered the statements slightly for readability, but the gist is the same. Also, you could easily single-line-initialize the references with something like this, and have the same basic idea:
Dim taLookupCode AS New LookupCodeTableAdapter
Dim dtLookupCode As LookupCodeDataTable = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
Dim strDescription As String = dtLookupCode.Item(0).Meaning
A: Yeah, don't say "inline" because that means something specific in other languages. Most likely the performance difference is either zero or so small it doesn't matter, it's just a matter of preference. Do you want to write it out in separate statements to make it more clear, or write it all on one line to type it out quicker?
A: Usually it just makes the code less readable.
And often, when people use this "inlining" (i.e. chaining), they'll re-access a property or field of a class multiple times instead of getting it just once and storing in a local variable. This is generally a bad idea because one doesn't usually know how that field or property is returned. For example, it may be calculated each time, or it may be calculated once and stored privately in the class.
Here are two illustrations. The first snippet is to be avoided:
if (ConfigurationManager.AppSettings("ConnectionString") == null)
{
throw new MissingConfigSettingException("ConnectionString");
}
string connectionString = ConfigurationManager.AppSettings("ConnectionString");
The second is preferable:
string connectionString = ConfigurationManager.AppSettings("ConnectionString")
if (connectionString == null)
{
throw new MissingConfigSettingException("ConnectionString");
}
The problem here is that AppSettings() actually has to unbox the AppSettings collection everytime a value is retrieved:
// Disassembled AppSettings member of ConfigurationManager
public static NameValueCollection AppSettings
{
get
{
object section = GetSection("appSettings");
if ((section == null) || !(section is NameValueCollection))
{
throw new
ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid"));
}
return (NameValueCollection) section;
}
}
A: Debugging the latter is going to be harder if you want to see the intermediate state, and single step through the stages.
I would go for readability over the amount of screen real estate used here since performance is a wash.
A: I call it chaining.
You are asking the wrong question.
What you need to ask is: Which is more readable?
If chaining makes the code easier to read and understand than go ahead and do it.
If however, it obfuscates, then don't.
Any performance optimizations are non-existant. Don't optimize code, optimize algorithms.
So, if you are going to be calling Item(1) and Item(2), then by chaining, You'll be creating the same object over and over again which is a bad algorithm.
In that case, then the first option is better, as you don't need to recreate the adapter each time.
A: One reason against 'chaining' is the Law of Demeter which would suggest that your code is fragile in the face of changes to LookupCodeDataTable.
You should add a function like this:
function getMeaning( lookupCode as LookupCodeDataTable)
getMeaning=lookupCode.Item(0).Meaning
end function
and call it like this:
strDescription=getMeaning(taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL"))
Now getMeaning() is available to be called in many other places and if LookupCodeDataTable changes, then you only have to change getMeaning() to fix it.
A: The structure is still created, you just do not have a reference for it.
A: This:
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
strDescription = dtLookupCode.Item(0).Meaning
and this:
strDescription = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL").Item(0).Meaning
are completely equivalent.
In the first example, you've got an explicit temporary reference (dtLookupTable). In the second example, the temporary reference is implicit. Behind the scenes, the compiler will almost certainly create the same code for both of these. Even if it didn't emit the same code, the extra temporary reference is extremely cheap.
However, I'm not sure if this line:
Dim dtLookupCode As New LookupCodeDataTable()
is efficient. It looks to me like this creates a new LookupCodeDataTable which is then discarded when you overwrite the variable in the later statement. I don't program in VB, but I would expect that this line should be:
Dim dtLookupCode As LookupCodeDataTable
The reference is cheap (probably free), but constructing an extra lookup table may not be.
A: It's the same unless you need to refer to the returned objects by
taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL") or Item(0)
multiple times. Otherwise, you don't know if the runtime for this function is log(n) or n, so for the best bet, I would assign a reference to it.
A: Besides maintainability, here's another reason to avoid chaining: Error checking.
Yes, you can wrap the whole thing in try/catch, and catch every exception that any part of the chain can throw.
But if you want to validate results in between calls without try/catch, you have to split things apart. For instance:
*
*What happens when GetDataByCodeAndValue returns null?
*What if it returns an empty list?
You can't check for these values without try/catch if you're chaining.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: F# and Enterprise Software Being a C# developer since version 1.0, F# has captured my free time for the past few weeks. Computers are now sold with 2, 4 .. Cores and multi-threading is not always simple to accomplish.
At the moment I see that F# has great potential for complicated and or heavy workloads.
Do you think that F# will (once RTM) become an important player in the Enterprise Software market?
A: I think F# has great opportunity to make inroads some of the niche areas of enterprise applications such as mathematical modelling (e.g. for banking/trading applications). Removing side effects from functions also leads to great opportunities for parallelism and memoization. Its hard to say if these languages will ever take off for mainstream development is hard to say, but in my opinion the problems are more likely to be human oriented (i.e. lack of skills and high learning curve for people familiar with more typical languages like c#/java/c++) rather than technical.
A: I think regardless of whether F# becomes import for Enterprise Software being able to isolate pure functional portions of code in any language will be key to using the potential of multi-core computers. For instance Microsoft's Parallel Extensions for .NET are great, but there is still a lot of room to make mistakes by parallelizing code that can't execute in parallel. If the code is in the form of a pure functional language or a subset of your language that is purely functional, then you are assured that you can execute it in parallel. The trick is then figuring out the most efficient way to assign the work.
The role that F# plays in this I would say would be more as a catalyst to get people's feet wet and start thinking in a more declarative way.
A: What I think we'll be seeing is that some functional stuff will migrate into C# such as the increase use of immutable types and the marking functions as pure etc. I can't see F# having a wider role in enterprise development its just too mystifying to the average developer.
A: C#/VB will always be the main languages, but F# is better at complex problems. C# is more general purpose while F# is better at IA, statistics, science (finding the cure of cancer, for example), etc. F# will never replace C#, but it will enable .NET to compete in more fields of computer science. As for data mining and processing large ammounts of data, you are better off developping directly within the database - like SQL Server or oracle.
As for F# being hard to learn, it's only because we got "corrupted" by the imperative way of thinking in most other languages. It's hard to unlearn something you do for 5 years! Also, in my exprience, ocaml and F# is a joy to use. The only complain I have for F#/Ocaml is that most of the time people overuse the type inference which makes the code unreadable. I'd rather declare variable types to make it easier to maintain.
A: I think F# will always be a niche language, compared to VB/C#/Java, because it does require more of a mathematical or computer science background. However the very fact that it is a CLR language means that it will have much bigger exposure than earlier functional languages.
I work in an investment bank and we are already using F# for some ad-hoc scripting purposes, we are pretty keen to see a released version of F# so that we can consider more formal integration into our systems (although they are likely to remain fundamentally C# based).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Compartment items not displayed in DSL diagram OK, so things have progressed significantly with my DSL since I asked this question a few days ago.
As soon as I've refactored my code, I'll post my own answer to that one, but for now, I'm having another problem.
I'm dynamically generating sub-diagrams from a DSL-created model, saving those diagrams as images and then generating a Word document with those images embedded. So far, so good.
But where my shapes have compartments (for examples, Operations on a Service Contract - can you guess what it is, yet?), the compartment header is displayed but none of the items.
If I examine my shape object, it has a single nested child - an ElementListCompartment which in turn, has a number of items that I'm expecting to be displayed. The ElementListCompartment.IsExpanded property is set to true (and the compartment header has a little 'collapse' icon on it) but where, oh where, are my items?
The shape was added to the diagram using
parentShape.FixupChildShapes(modelElement);
So, can anyone guide me on my merry way?
A: I've recently faced a related problem, and managed to make it work, so here's the story.
The task I was implementing was to load and display a domain model and an associated diagram generated by ActiveWriter's DSL package.
Here's how I've implemented the required functionality (all the methods below belong to the Form1 class I've created to play around):
private Store LoadStore()
{
var store = new Store();
store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));
return store;
}
private void LoadDiagram(Store store)
{
using (var tx = store.TransactionManager.BeginTransaction("tx", true))
{
var validator = new ValidationController();
var deserializer = ActiveWriterSerializationHelper.Instance;
deserializer.LoadModelAndDiagram(store,
@"..\..\ActiveWriter1.actiw", @"..\..\ActiveWriter1.actiw.diagram", null, validator);
tx.Commit();
}
}
private DiagramView CreateDiagramView()
{
var store = LoadStore();
LoadDiagram(store);
using (var tx = store.TransactionManager.BeginTransaction("tx2", true))
{
var dir = store.DefaultPartition.ElementDirectory;
var diag = dir.FindElements<ActiveRecordMapping>().SingleOrDefault();
var view = new DiagramView(){Diagram = diag};
diag.Associate(view);
tx.Commit();
view.Dock = DockStyle.Fill;
return view;
}
}
protected override void OnLoad(EventArgs e)
{
var view = CreateDiagramView();
this.Controls.Add(view);
}
This stuff worked mostly finely: it correctly loaded the diagram from files created with Visual Studio, drew the diagram within my custom windows form, supported scrolling the canvas and even allowed me to drag shapes here. However, one thing was bugging me - the compartments were empty and had default name, i.e. "Compartment".
Google didn't help at all, so I had to dig in by myself. It wasn't very easy but with the help of Reflector and after spending a couple of hours I've managed to make this scenario work as expected!
The problem was as follows. To my surprise DSL libraries do not correctly draw certain diagram elements immediately after they are added to the diagram. Sometimes, only stubs of certain shapes are drawn (as it's displayed in the first picture). Thus, sometimes we need to manually ask the library to redraw diagram shapes.
This functionality can be implemented with so called "rules" that in fact are event handlers that get triggered by certain diagram events. Basically what we have to do is attach certain handler to an element-added event of the diagram and ensure shape initialization.
Luckily we don't even have to write any code since DSL designer autogenerates both fixup rules and an utility method that attaches those rules to the diagram (see the EnableDiagramRules below). All we have to do is to call this method right after the store has been created (prior to loading model and diagram).
private Store LoadStore()
{
var store = new Store();
store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));
ActiveWriterDomainModel.EnableDiagramRules(store);
return store;
}
/// <summary>
/// Enables rules in this domain model related to diagram fixup for the given store.
/// If diagram data will be loaded into the store, this method should be called first to ensure
/// that the diagram behaves properly.
/// </summary>
public static void EnableDiagramRules(DslModeling::Store store)
{
if(store == null) throw new global::System.ArgumentNullException("store");
DslModeling::RuleManager ruleManager = store.RuleManager;
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.FixUpDiagram));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.ConnectorRolePlayerChanged));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemAddRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemDeleteRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerChangeRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerPositionChangeRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemChangeRule));
}
The code above works as follows:
*
*Upon new element being added to the diagram (e.g. during deserialization of diagram) the rule "FixUpDiagram" gets triggered.
*The rule then calls Diagram.FixUpDiagram(parentElement, childElement), where childElement stands for an element being added and parentElement stands for its logical parent (determined using tricky conditional logic, so I didn't try to reproduce it by myself).
*Down the stack trace FixUpDiagram method calls EnsureCompartments methods of all class shapes in the diagram.
*The EnsureCompartments method redraws class' compartments turning the stub "[-] Compartment" graphic into full-blown "Properties" shape as displayed in the picture linked above.
P.S. Steve, I've noticed that you did call the fixup but it still didn't work. Well, I'm not a pro in DSL SDK (just started using it a couple of days ago), so cannot explain why you might have troubles.
Maybe, you've called the fixup with wrong arguments. Or maybe Diagram.FixupDiagram(parent, newChild) does something differently from what parent.FixupChildShapes(newChild) does. However here's my variant that just works. Hope this also helps.
A: Maybe my answer is a little bit too late, but did you confirm using DSL Explorer that your compartments have items?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VmWare Primary HDD Expansion I have a VmWare virtual machine that is coming dangerously close to it's primarry HDD's limit and I need to extend it. How do I do this? I'm working with VmWare Workstation 6.0.5
A: This link gives two approaches that should help.
It looks like this is the most straightforward method:
vmware-vdiskmanager -x 12GB path\to\disk.vmdk
where 12GB is the desired size of the expanded volume.
A: I don't know about 6.0.5, but in former versions there used to be a program called vmware-vdiskmanager in VMWare's program directory. You can use this one to extend the virtual disk container.
After you expanded the container, you need to expand the partitions in the guest, you have to do this from "the inside", which depends on the OS you are using on the guest and the filesystem. I often use an Ubuntu Life-CD or a System-Rescue-CD ISO together with qtparted to expand the partitions as needed.n
A: Simplest way for me worked yesterday. My colleague advice me.
*
*Turn of your primary virtual machine, where your primary HDD is attached(if it is running).
*Expand your disk in primary virtual machine preferences.
(Right click Settings, right click your primary hard disk, choose utilities, expand, ...)
*Attach your primary disk to another virtual machine. Boot another virtual machine.
If you go to disk manager, you can see, that your disk is bigger then partition, resize it.
Now it will work, because you are on different other virtual machine and you your expanding disk is not the from which you booted the system, so you can resize the disk in disk manager(win GUI).
*Detach your primary disk from other virtual machine.
*Boot up your primary system, your primary partition is bigger.
Trick is you can not change size of partition, from which Windows booted, so you must attach it to another system, resize it, and it is all.
A: Assuming this is under Windows, there is a program usually in "C:\Program Files\VMWare\VMware Workstation\" called vmware-vdiskmanager.exe that you can use to do this. Open a DOS prompt and CD to that directory. The command to expand the drive is:
vmware-vdiskmanager.exe -x 50Gb NameOfDisk.vmdk
Also, this isn't the only thing you can do with this command. If you just type the command w/o any parameters you will see a bunch of the other available options.
A: I've sometimes had problems when using the vmware-vdiskmanager application (it created the extra space, but I couldn't use it). At which point, I used the GParted live CD, which worked perfectly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Best features of EJB 3 The scenario
*
*You have developed a webapp using EJBs version 3.
*The system is deployed, delivered and is used by the customer.
If you would have to rewrite the system from scratch, would you use EJBs again?
No: Don't answer this question, answer this one instead.
Yes: Provide one important, real problem that EJBs solved, based on your personal experience.
Let the answer contain just one problem. This will let other readers vote up the best feature of EJBs.
A: I think it depends on what version of EJBs you're talking about. Let's discuss the only two relevant (IMO) versions.
EJB 2.1 might still be used by some people in a legacy system. They really have the most use as an RPC abstraction. They also provided a rudimentary ORM (Object-Relational Mapping) system as well. And as you mentioned, transaction support is provided. So if you were building a system where you wanted to communicate with a remote system, transfer object-oriented data and do it transactionally, you might find EJBs to be worth the effort. Otherwise, I'd say stay away.
EJB 3.0, however, has been greatly improved. It has all the features of the previous version, but does it in a more straightforward way. It also provides a fairly simple Inversion-Of-Control framework not unlike Spring, and a pretty decent ORM in the form of the JPA (Java Persistence API.) I have used EJB 3.0 and actually enjoyed it. You could argue for the use of EJB 3.0 the same way you would for Spring, plus it has a few more advanced, or enterprise-y, features available.
A: Well, this really depends on which EJBs we are talking about. I would say that MDBs can still be useful even now. For entity beans and session beans you can surely find a better approach.
Maybe one feature which I still like in EJBs is scalability. Using "remote" option you can deploy EJBs to different servers if necessary. However, I don't think this is really necessary, and I've seen only one huge project where it was really useful.
A: Did lots of work in the past with EJB 2.1, glad to leave it behind.
EJB value proposition remains true for 3.0, and carries a nice lightweight programming model. Transaction management, concurrency, data versioning, state management, these are non-trivial problems to solve correctly and Java EE frameworks continue to do an excellent job.
Admittedly, I use Hibernate and Seam to further build on some of the Java EE features, so it isn't strictly fair for me to say EJB 3.0 itself is the mecca. However I find too many developers throwing the proverbial baby out with the bathwater when they give up on Java entirely and move to something more vogue like Rails.
Seam provides a nice glue framework that keeps the amount of programmer effort quite low. Also lets you decide on a project by project basis when EJB makes sense versus POJOs, WITHOUT having to change your programming style.
A: the main reason to use the java ee platform is by definition. you need a platform that solves the issues of concurrency, availability, transaction management, messaging, and management in a fully vetted, compliant, and compatible platform. yes you can do it all yourself by gluing together a whole host of libraries and slapping it on top of tomcat, but why waste all that time vetting and managing compatibility and feature set when you can write to a standards enforcing, fully vetted platform. any ee container MUST pass the tck or it cannot carry the Java EE monicker.
the things that various people raise about "lightweight", "types" of ejbs, etc. are superfluous. if you don't need the feature set of the platform or the guarantee of complete intra compatibility of your leveraged libraries, then ejb (aka the java ee platform) is overkill. but if you're really solving an enterprise quality problem (see the first paragraph), then the ejb and the java ee platform are going to give you what you need.
A: One thing that has bitten many when using EJBs, or J2EE in general, is the dependency on the application server you're running your EJBs on. The appserver tends to be supported for a particular set of operating system releases and JVM versions. Not having the source code to a significant part of your runtime environment could also turn into a challenge.
While migrating from one vendor to another in principle is possible, you need to be very aware of small differences in how they implement the specification, and to stay away from vendor-specific extensions.
That being said, the appservers I've been exposed to can handle very much abuse from the code running in it and perform very well.
A: Convention over configuration.
The default behaviour of EJB 3 it's more often the desired one. I think the main problem with EJB 2.1 was the necesity of verbose config files, the new annotation-based configuration solve most of this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: XAMPP and WAMP in the LAMP, what's the best? We have got loads of options for php + MySQL + Apache combo... Which is the best pack among these ?
Lets confine our ideas to WAMP vs XAMPP, is there a better option to go for?
I created an online programming contest web app called CodeFire on XAMPP, later I had to switch to WAMP, where none of the php scripts worked properly... what standard should I follow?
A: LAMP seems to be the most common of those options, so on a strictly find solutions to your problems I would recommend LAMP.
It really comes down to whats going to be the best option for you though. If you don't know Linux than maybe running a WAMP setup will make the process easier to maintain. Try and factor in your experiance and the maintenance required on the server into your decision.
Personally I run a LAMP server for my purposes, as I know enough Linux to maintain it and it ended up being the best solution for my purposes.
A: I tried XAMPP and gave up...I faced an issue with backslashes(widows uses forward slashes)..due to this none of my scripts could save any files to folders because the path would be like dir1\dir2\folder/image_folder/image.jpg...I tried WAMP it worked like a charm..it threw no errors and saved the image files as intented...so..I guess I will stick to WAMP...I would appreciate it if someone could tell me how the "madslashes" issue is fixed on XAMPP..I googled furiously..without any luck..thanks
A: Xampp is a self contained package for developments.
the latter two would be full production stacks installed on your server either gnu/linux or windows server 2k*
so if you want a one program install that can be removed go with xampp for development, otherwise you can fully install eash of them on your system. the latter will also (obviously) produce greater performance.
as far as standards go, lamp is more industry wide, the windows servers tend to run IIS instead of apache, though it doesn't mean they can't. thier are books on php over windows but i think easy of use and wide adaptation is in the lamp camp.
A: I like XAMPP, personally. I have an install running on a thumbdrive that I carry around that's pretty much my development environment for LAMP web dev on any machine I happen to be at (I'm mostly on Windows client machines).
Small, fully-functional, and stable - works really well for my needs.
A: It all depends on what you are comfortable administering. Any of these setups can be stable, robust, and secure if its properly set up.
A: I've been using WAMP for a while now, and from what I've gathered its pretty reliable. The installation is a breeze, and user interface is pretty friendly.
A: http://www.formboss.net/blog/2010/02/hosting-php-linux-vs-windows-benchmarks/
He seemed pretty happy with stock mysql/apache/php
A: Using Wamp, the new version has xdebug pre-installed, which is nice for me since the first time I tried to install xdebug, it took me ages <_<
Haven't tried Xampp, but just seeing that it doesn't have xdebug bundled I backed off from trying :P
A: I like WAMP the best, real simple interface and I can easily switch between different versions of PHP 5.26/4.44/4.3.9, MySQL 5/4, and Apache 2/1.3
A: XAMPP is good for development and portability, that's for sure.
LAMP is best for performance and security (and ubiquity).
WAMP...well, that's for if you don't want to learn Linux, I guess.
A: I use WIMP on a project, and it's ok, not anything to write home about:
WIMP: Windows, IIS, MySQL, PHP
A: For me, it depends on your specialization. They are both works great and reliable.
A: I liked WAMP best until I tried to uninstall it, and realized it left behind a ton of junk, so go with XAMPP.
A: I use xampp, because it offers easy upgradeability and portability. You can easily upgrade the version wihtout a hassle.
I use xampp's 7zip installer version which is a very nice when it comes to be upgrading your php and phpmyadmin quite frequently in order to fix the bugs that are introduced in previous versions and have new functionality.
A: I like xampp lite for a development server. I just take an old pc, re install windows and download and install.
Change the Net card to static and turn on Apachie and mysql on startup. They run as services. I set the drive as shared and when I want to use it I copy the files into the htdocs area and turn the browser to that IP.
Very easy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "55"
}
|
Q: What causes java.io.CharConversionException with EOF or isHexDigit messages in Tomcat? This exception peppers our production catalina logs on a simple 'getParameter()' call.
WARNING: Parameters: Character decoding failed. Parameter skipped.
java.io.CharConversionException: EOF
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:82)
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48)
at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509)
at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266)
at org.apache.catalina.connector.Request.parseParameters(Request.java:2361)
at org.apache.catalina.connector.Request.getParameter(Request.java:1005)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
Or Sometimes:
java.io.CharConversionException: isHexDigit
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:87)
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48)
at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509)
at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266)
at org.apache.catalina.connector.Request.parseParameters(Request.java:2361)
at org.apache.catalina.connector.Request.getParameter(Request.java:1005)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
A: Just hypothesizing here. Seems like the URL-decoding of parameters or their values fails (URL-encoding means encoding some characters using the %XX or %XXXX notation where XX or XXXX is the hexadecimal code of the character in ISO-8859-1 or Unicode). In the first case the error might be happening because there aren't enough hexadecimal characters after the % character. In the second case this might be happening because a character after the % character isn't hexadecimal.
A: Another thing to investigate is the URIEncoding in your Tomcat "Connector" configuration. If the link is in a UTF-8 encoded page, it will encode the URL to bytes with UTF-8, then URL encode any of the bytes that need it. However, by default, Tomcat thinks that those bytes are ISO-8859-1, which can lead to problems.
The inverse may also be true: if the page is ISO-8859-1, and Tomcat's URIEncoding has been set to UTF-8, a similar error could result.
Here's a useful discussion about the issues in this area: Charset Pitfalls in JSP/Servlet Containers
A: I started receiving this error when users were sending '%' over an ajax request. Turns out I wasn't escaping the parameters before making the request. A complete write up of this scenario and fix is covered in this blog post
A: It could also be this (from Wikipedia):
There exists a non-standard encoding for Unicode characters: %uxxxx, where xxxx is a Unicode value represented as four hexadecimal digits. This behavior is not specified by any RFC and has been rejected by the W3C. The third edition of ECMA-262 still includes an escape(string) function that uses this syntax, but also an encodeURI(uri) function that converts to UTF-8 and percent-encodes each octet.
So you could be using the old escape function in Javascript, but since later versions of Tomcat are stricter about such things (5.5.17 let this encoding slide), only now are you beginning to see exceptions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Automatically Generating SQL Schema from XML We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents?
A: You could use XSD. No, I'm serious. Go to a command prompt and type xsd and press Enter.
Here's what you will see (truncated):
I:\>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 1.0.3705.0]
Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.
xsd.exe -
Utility to generate schema or class files from given source.
xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]
Just follow the instructions.
A: As XSD in ambiguous in terms of master-detail relations, I doubt an automatic generation is possible.
For example, a declaration such as
<xs:element name="foo" type="footype" minOccurs="0" maxOccurs="unbounded" />
can be interpreted as child table "foo" (1:n) or as an n:m relation.
minOccurs="0" maxOccurs="1" may be a nullable column, or an optional 1:1 relation.
type="xs:string" maxOccurs="1" is a string ((n)varchar) column, or an optional lookup; but type="xs:string" maxOccurs="unbounded" is a detail table with a (n)varchar column.
A: There's a tool called ShreX that can can makes schemas from xsd and inserts from XML. It tries to do this by itself (you can annotade the xsd to steer it). If you want to decide the structure yourself it might not be what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it possible to build following SQL query The original query looks like this (MySQL):
SELECT *
FROM books
WHERE title LIKE "%text%" OR description LIKE "%text%"
ORDER BY date
Would it be possible to rewrite it (without unions or procedures), so that result will look like this:
*
*list of books where title matches query ordered by date, followed by:
*list of books where description matches query ordered by date
So basically just give a higher priority to matching titles over descriptions.
A: select * from books
where title like "%text%" or description like "%text%"
order by date, case when title like "%text%" then 0 else 1 end
A: rjk's suggestion is the right way to go. Bear in mind, though, that this query (with or without a union) can't use indexes, so it's not going to scale well. You might want to check out MySQL's fulltext indexing, which will scale better, allow more sophisticated queries, and even help with result ranking.
A: In sql server I would do the following:
select * from books
where title like '%text%' or description like '%text%'
order by case when title like '%text%' then 1 else 2 end, date
I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well.
A: You could use a case to sort by:
order by case when title like '%text%' then 0 else 1 end
A: How about something like this...
select *
from books
where title like "%text%"
or description like "%text%"
order by case when title like "%text%" then 1 else 0 end desc, date
A: DECLARE @Books TABLE
(
[ID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
[Title] NVARCHAR(MAX) NOT NULL,
[Description] NVARCHAR(MAX) NOT NULL,
[Date] DATETIME NOT NULL
)
INSERT INTO @Books
SELECT 'War and Peace','A Russian Epic','2008-01-01' UNION
SELECT 'Dogs of War','Mercenary Stories','2006-01-01' UNION
SELECT 'World At Arms','A Story of World War Two','2007-01-01' UNION
SELECT 'The B Team','Street Wars','2005-01-01'
SELECT * FROM
(
SELECT *, CASE WHEN [Title] LIKE '%war%' THEN 1 WHEN [Description] LIKE '%war%' THEN 2 END AS Ord
FROM @Books
WHERE [Title] LIKE '%war%' OR [Description] LIKE '%war%'
) AS Derived
ORDER BY Ord ASC, [Date] ASC
I believe this gives you what you want, but due to the extra workload in the derived CASE statment, it may not have good performance.
A: The union command will help you. Something along these lines:
SELECT *, 1 as order from books where title like '%text%'
union
SELECT *, 2 as order from books where description like '%text%'
ORDER BY order, date
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What RTOS is best for working on the same PC with Windows? What RTOS is best for working on the same PC with Windows?
I know about RTX and INtime, but have not used them. Are there any others? Which one is your favorite and why?
A: I would try eCos. It is runs on the i386, is free, has great tool support, and includes board support packages ready made.
A: QNX is used extensively for aircraft electronics. However, pretty much any OS will run inside of Windows using VMWare or dual-booting though.
A: If you are looking to have a lot of fun with real-time systems, why not play around with Ubuntu's real-time patch and turn an old computer you have into a real-time desktop or use virtualbox or something of course. Here is a link you will find useful in getting it setup:
http://viswanathj.wordpress.com/2011/02/15/real-time-operating-system-installation-on-ubuntu-linux/
https://help.ubuntu.com/community/UbuntuStudio/RealTimeKernel
This works with 10.04 LTS , x86 architectures with Intel, AMD & ARM processors, etc.
Cheers!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: A script to change all tables and fields to the utf-8-bin collation in MYSQL Is there a SQL or PHP script that I can run that will change the default collation in all tables and fields in a database?
I can write one myself, but I think that this should be something that readily available at a site like this. If I can come up with one myself before somebody posts one, I will post it myself.
A: Can be done in a single command (rather than 148 of PHP):
mysql --database=dbname -B -N -e "SHOW TABLES" \
| awk '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' \
| mysql --database=dbname &
You've got to love the commandline...
(You might need to employ the --user and --password options for mysql).
EDIT: to avoid foreign key problems, added SET foreign_key_checks = 0; and SET foreign_key_checks = 1;
A: I think it's easy to do this in two steps runin PhpMyAdmin.
Step 1:
SELECT CONCAT('ALTER TABLE `', t.`TABLE_SCHEMA`, '`.`', t.`TABLE_NAME`,
'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') as stmt
FROM `information_schema`.`TABLES` t
WHERE 1
AND t.`TABLE_SCHEMA` = 'database_name'
ORDER BY 1
Step 2:
This query will output a list of queries, one for each table. You have to copy the list of queries, and paste them to the command line or to PhpMyAdmin's SQL tab for the changes to be made.
A: Another approach using command line, based on @david's without the awk
for t in $(mysql --user=root --password=admin --database=DBNAME -e "show tables";);do echo "Altering" $t;mysql --user=root --password=admin --database=DBNAME -e "ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;";done
prettified
for t in $(mysql --user=root --password=admin --database=DBNAME -e "show tables";);
do
echo "Altering" $t;
mysql --user=root --password=admin --database=DBNAME -e "ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
done
A: OK, I wrote this up taking into account what was said in this thread. Thanks for the help, and I hope this script will help out others. I don't have any warranty for its use, so PLEASE BACKUP before running it. It should work with all databases; and it worked great on my own.
EDIT: Added vars at the top for which charset/collate to convert to.
EDIT2: Changes the database's and tables' default charset/collate
<?php
function MysqlError()
{
if (mysql_errno())
{
echo "<b>Mysql Error: " . mysql_error() . "</b>\n";
}
}
$username = "root";
$password = "";
$db = "database";
$host = "localhost";
$target_charset = "utf8";
$target_collate = "utf8_general_ci";
echo "<pre>";
$conn = mysql_connect($host, $username, $password);
mysql_select_db($db, $conn);
$tabs = array();
$res = mysql_query("SHOW TABLES");
MysqlError();
while (($row = mysql_fetch_row($res)) != null)
{
$tabs[] = $row[0];
}
// now, fix tables
foreach ($tabs as $tab)
{
$res = mysql_query("show index from {$tab}");
MysqlError();
$indicies = array();
while (($row = mysql_fetch_array($res)) != null)
{
if ($row[2] != "PRIMARY")
{
$indicies[] = array("name" => $row[2], "unique" => !($row[1] == "1"), "col" => $row[4]);
mysql_query("ALTER TABLE {$tab} DROP INDEX {$row[2]}");
MysqlError();
echo "Dropped index {$row[2]}. Unique: {$row[1]}\n";
}
}
$res = mysql_query("DESCRIBE {$tab}");
MysqlError();
while (($row = mysql_fetch_array($res)) != null)
{
$name = $row[0];
$type = $row[1];
$set = false;
if (preg_match("/^varchar\((\d+)\)$/i", $type, $mat))
{
$size = $mat[1];
mysql_query("ALTER TABLE {$tab} MODIFY {$name} VARBINARY({$size})");
MysqlError();
mysql_query("ALTER TABLE {$tab} MODIFY {$name} VARCHAR({$size}) CHARACTER SET {$target_charset}");
MysqlError();
$set = true;
echo "Altered field {$name} on {$tab} from type {$type}\n";
}
else if (!strcasecmp($type, "CHAR"))
{
mysql_query("ALTER TABLE {$tab} MODIFY {$name} BINARY(1)");
MysqlError();
mysql_query("ALTER TABLE {$tab} MODIFY {$name} VARCHAR(1) CHARACTER SET {$target_charset}");
MysqlError();
$set = true;
echo "Altered field {$name} on {$tab} from type {$type}\n";
}
else if (!strcasecmp($type, "TINYTEXT"))
{
mysql_query("ALTER TABLE {$tab} MODIFY {$name} TINYBLOB");
MysqlError();
mysql_query("ALTER TABLE {$tab} MODIFY {$name} TINYTEXT CHARACTER SET {$target_charset}");
MysqlError();
$set = true;
echo "Altered field {$name} on {$tab} from type {$type}\n";
}
else if (!strcasecmp($type, "MEDIUMTEXT"))
{
mysql_query("ALTER TABLE {$tab} MODIFY {$name} MEDIUMBLOB");
MysqlError();
mysql_query("ALTER TABLE {$tab} MODIFY {$name} MEDIUMTEXT CHARACTER SET {$target_charset}");
MysqlError();
$set = true;
echo "Altered field {$name} on {$tab} from type {$type}\n";
}
else if (!strcasecmp($type, "LONGTEXT"))
{
mysql_query("ALTER TABLE {$tab} MODIFY {$name} LONGBLOB");
MysqlError();
mysql_query("ALTER TABLE {$tab} MODIFY {$name} LONGTEXT CHARACTER SET {$target_charset}");
MysqlError();
$set = true;
echo "Altered field {$name} on {$tab} from type {$type}\n";
}
else if (!strcasecmp($type, "TEXT"))
{
mysql_query("ALTER TABLE {$tab} MODIFY {$name} BLOB");
MysqlError();
mysql_query("ALTER TABLE {$tab} MODIFY {$name} TEXT CHARACTER SET {$target_charset}");
MysqlError();
$set = true;
echo "Altered field {$name} on {$tab} from type {$type}\n";
}
if ($set)
mysql_query("ALTER TABLE {$tab} MODIFY {$name} COLLATE {$target_collate}");
}
// re-build indicies..
foreach ($indicies as $index)
{
if ($index["unique"])
{
mysql_query("CREATE UNIQUE INDEX {$index["name"]} ON {$tab} ({$index["col"]})");
MysqlError();
}
else
{
mysql_query("CREATE INDEX {$index["name"]} ON {$tab} ({$index["col"]})");
MysqlError();
}
echo "Created index {$index["name"]} on {$tab}. Unique: {$index["unique"]}\n";
}
// set default collate
mysql_query("ALTER TABLE {$tab} DEFAULT CHARACTER SET {$target_charset} COLLATE {$target_collate}");
}
// set database charset
mysql_query("ALTER DATABASE {$db} DEFAULT CHARACTER SET {$target_charset} COLLATE {$target_collate}");
mysql_close($conn);
echo "</pre>";
?>
A: Be careful! If you actually have utf stored as another encoding, you could have a real mess on your hands. Back up first. Then try some of the standard methods:
for instance
http://www.cesspit.net/drupal/node/898
http://www.hackszine.com/blog/archive/2007/05/mysql_database_migration_latin.html
I've had to resort to converting all text fields to binary, then back to varchar/text. This has saved my ass.
I had data is UTF8, stored as latin1. What I did:
Drop indexes.
Convert fields to binary.
Convert to utf8-general ci
If your on LAMP, don’t forget to add set NAMES command before interacting with the db, and make sure you set character encoding headers.
A: A more complete version of the script above can be found here:
http://www.zen-cart.com/index.php?main_page=product_contrib_info&products_id=1937
Please leave any feedback about this contribution here:http://www.zen-cart.com/forum/showthread.php?p=1034214
A: This PHP snippet will change the collation on all tables in a db. (It's taken from this site.)
<?php
// your connection
mysql_connect("localhost","root","***");
mysql_select_db("db1");
// convert code
$res = mysql_query("SHOW TABLES");
while ($row = mysql_fetch_array($res))
{
foreach ($row as $key => $table)
{
mysql_query("ALTER TABLE " . $table . " CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci");
echo $key . " => " . $table . " CONVERTED<br />";
}
}
?>
A: Charset and collation are not the same thing. A collation is a set of rules about how to sort strings. A charset is a set of rules about how to represent characters. A collation depends on the charset.
A: In scripts above all tables selected for convertation (with SHOW TABLES), but a more convenient and portable way to check the table collation before converting a table. This query does it:
SELECT table_name
, table_collation
FROM information_schema.tables
A: Use my custom shell collatedb, it should work :
collatedb <username> <password> <database> <collation>
Example :
collatedb root 0000 myDatabase utf8_bin
A: Thanks @nlaq for the code, that got me started on the below solution.
I released a WordPress plugin without realising that WordPress doesn't set the collate automatically. So a lot of people using the plugin ended up with latin1_swedish_ci when it should have been utf8_general_ci.
Here's the code I added to the plugin to detect the latin1_swedish_ci collate and change it to utf8_general_ci.
Test this code before using it in your own plugin!
// list the names of your wordpress plugin database tables (without db prefix)
$tables_to_check = array(
'social_message',
'social_facebook',
'social_facebook_message',
'social_facebook_page',
'social_google',
'social_google_mesage',
'social_twitter',
'social_twitter_message',
);
// choose the collate to search for and replace:
$convert_fields_collate_from = 'latin1_swedish_ci';
$convert_fields_collate_to = 'utf8_general_ci';
$convert_tables_character_set_to = 'utf8';
$show_debug_messages = false;
global $wpdb;
$wpdb->show_errors();
foreach($tables_to_check as $table) {
$table = $wpdb->prefix . $table;
$indicies = $wpdb->get_results( "SHOW INDEX FROM `$table`", ARRAY_A );
$results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" , ARRAY_A );
foreach($results as $result){
if($show_debug_messages)echo "Checking field ".$result['Field'] ." with collat: ".$result['Collation']."\n";
if(isset($result['Field']) && $result['Field'] && isset($result['Collation']) && $result['Collation'] == $convert_fields_collate_from){
if($show_debug_messages)echo "Table: $table - Converting field " .$result['Field'] ." - " .$result['Type']." - from $convert_fields_collate_from to $convert_fields_collate_to \n";
// found a field to convert. check if there's an index on this field.
// we have to remove index before converting field to binary.
$is_there_an_index = false;
foreach($indicies as $index){
if ( isset($index['Column_name']) && $index['Column_name'] == $result['Field']){
// there's an index on this column! store it for adding later on.
$is_there_an_index = $index;
$wpdb->query( $wpdb->prepare( "ALTER TABLE `%s` DROP INDEX %s", $table, $index['Key_name']) );
if($show_debug_messages)echo "Dropped index ".$index['Key_name']." before converting field.. \n";
break;
}
}
$set = false;
if ( preg_match( "/^varchar\((\d+)\)$/i", $result['Type'], $mat ) ) {
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARBINARY({$mat[1]})" );
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARCHAR({$mat[1]}) CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
$set = true;
} else if ( !strcasecmp( $result['Type'], "CHAR" ) ) {
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` BINARY(1)" );
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARCHAR(1) CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
$set = true;
} else if ( !strcasecmp( $result['Type'], "TINYTEXT" ) ) {
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TINYBLOB" );
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TINYTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
$set = true;
} else if ( !strcasecmp( $result['Type'], "MEDIUMTEXT" ) ) {
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` MEDIUMBLOB" );
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` MEDIUMTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
$set = true;
} else if ( !strcasecmp( $result['Type'], "LONGTEXT" ) ) {
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` LONGBLOB" );
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` LONGTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
$set = true;
} else if ( !strcasecmp( $result['Type'], "TEXT" ) ) {
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` BLOB" );
$wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
$set = true;
}else{
if($show_debug_messages)echo "Failed to change field - unsupported type: ".$result['Type']."\n";
}
if($set){
if($show_debug_messages)echo "Altered field success! \n";
$wpdb->query( "ALTER TABLE `$table` MODIFY {$result['Field']} COLLATE $convert_fields_collate_to" );
}
if($is_there_an_index !== false){
// add the index back.
if ( !$is_there_an_index["Non_unique"] ) {
$wpdb->query( "CREATE UNIQUE INDEX `{$is_there_an_index['Key_name']}` ON `{$table}` ({$is_there_an_index['Column_name']})", $is_there_an_index['Key_name'], $table, $is_there_an_index['Column_name'] );
} else {
$wpdb->query( "CREATE UNIQUE INDEX `{$is_there_an_index['Key_name']}` ON `{$table}` ({$is_there_an_index['Column_name']})", $is_there_an_index['Key_name'], $table, $is_there_an_index['Column_name'] );
}
}
}
}
// set default collate
$wpdb->query( "ALTER TABLE `{$table}` DEFAULT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
if($show_debug_messages)echo "Finished with table $table \n";
}
$wpdb->hide_errors();
A: A simple (dumb? :) solution, using multi-select feature of Your IDE:
*
*run "SHOW TABLES;" query and copy results column (table names).
*multi-select beginnings and add "ALTER TABLE ".
*multi-select endings and add " CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"
*run created queries.
A: I think the fastest way is with phpmyadmin and some jQuery on console.
Go to table's structure and open chrome/firefox developer console (normally F12 on keyboard):
*
*run this code to select all fields with incorrect charset and start modify:
var elems = $('dfn'); var lastID = elems.length - 1;
elems.each(function(i) {
if ($(this).html() != 'utf8_general_ci') {
$('input:checkbox', $('td', $(this).parent().parent()).first()).attr('checked','checked');
}
if (i == lastID) {
$("button[name='submit_mult'][value='change']").click();
}
});
*when page is loaded use this code on console to select correct encoding:
$("select[name*='field_collation']" ).val('utf8_general_ci');
*save
*change the table's charset on "Collation" field on "Operation" tab
Tested on phpmyadmin 4.0 and 4.4, but I think work on all 4.x versions
A: Here's an easy way to do this with just phpmyadmin if you don't have command line access or access to edit INFORMATION_SCHEMA.
First, listen to the advice of many of the other answers here - you can really screw things up here, so make a backup. Now make a backup of your backup. Also this is unlikely to work if your data is encoded differently than what you are changing it to.
Note that you will need to find the exact names of the offending schema and character encoding that you need to change from before starting.
*
*Export the database as SQL; Make a copy; Open it in a text editor of your choice
*Find and Replace the schema first, for example - find: latin1_swedish_ci, replace: utf8_general_ci
*Find and Replace the character encodings if you need to, for example - find: latin1, replace: utf8
*Create a new test database and upload your new SQL file into phpmyadmin
This is a super easy way to do it, but again, this will not change the encoding of your data, so it will only work in certain circumstances.
A: I updated nlaq's answer to work with PHP7 and to correctly handle multicolumn indices, binary collated data (e.g. latin1_bin), etc., and cleaned up the code a bit. This is the only code I found/tried that successfully migrated my database from latin1 to utf8.
<?php
/////////// BEGIN CONFIG ////////////////////
$username = "";
$password = "";
$db = "";
$host = "";
$target_charset = "utf8";
$target_collation = "utf8_unicode_ci";
$target_bin_collation = "utf8_bin";
/////////// END CONFIG ////////////////////
function MySQLSafeQuery($conn, $query) {
$res = mysqli_query($conn, $query);
if (mysqli_errno($conn)) {
echo "<b>Mysql Error: " . mysqli_error($conn) . "</b>\n";
echo "<span>This query caused the above error: <i>" . $query . "</i></span>\n";
}
return $res;
}
function binary_typename($type) {
$mysql_type_to_binary_type_map = array(
"VARCHAR" => "VARBINARY",
"CHAR" => "BINARY(1)",
"TINYTEXT" => "TINYBLOB",
"MEDIUMTEXT" => "MEDIUMBLOB",
"LONGTEXT" => "LONGBLOB",
"TEXT" => "BLOB"
);
$typename = "";
if (preg_match("/^varchar\((\d+)\)$/i", $type, $mat))
$typename = $mysql_type_to_binary_type_map["VARCHAR"] . "(" . (2*$mat[1]) . ")";
else if (!strcasecmp($type, "CHAR"))
$typename = $mysql_type_to_binary_type_map["CHAR"] . "(1)";
else if (array_key_exists(strtoupper($type), $mysql_type_to_binary_type_map))
$typename = $mysql_type_to_binary_type_map[strtoupper($type)];
return $typename;
}
echo "<pre>";
// Connect to database
$conn = mysqli_connect($host, $username, $password);
mysqli_select_db($conn, $db);
// Get list of tables
$tabs = array();
$query = "SHOW TABLES";
$res = MySQLSafeQuery($conn, $query);
while (($row = mysqli_fetch_row($res)) != null)
$tabs[] = $row[0];
// Now fix tables
foreach ($tabs as $tab) {
$res = MySQLSafeQuery($conn, "SHOW INDEX FROM `{$tab}`");
$indicies = array();
while (($row = mysqli_fetch_array($res)) != null) {
if ($row[2] != "PRIMARY") {
$append = true;
foreach ($indicies as $index) {
if ($index["name"] == $row[2]) {
$index["col"][] = $row[4];
$append = false;
}
}
if($append)
$indicies[] = array("name" => $row[2], "unique" => !($row[1] == "1"), "col" => array($row[4]));
}
}
foreach ($indicies as $index) {
MySQLSafeQuery($conn, "ALTER TABLE `{$tab}` DROP INDEX `{$index["name"]}`");
echo "Dropped index {$index["name"]}. Unique: {$index["unique"]}\n";
}
$res = MySQLSafeQuery($conn, "SHOW FULL COLUMNS FROM `{$tab}`");
while (($row = mysqli_fetch_array($res)) != null) {
$name = $row[0];
$type = $row[1];
$current_collation = $row[2];
$target_collation_bak = $target_collation;
if(!strcasecmp($current_collation, "latin1_bin"))
$target_collation = $target_bin_collation;
$set = false;
$binary_typename = binary_typename($type);
if ($binary_typename != "") {
MySQLSafeQuery($conn, "ALTER TABLE `{$tab}` MODIFY `{$name}` {$binary_typename}");
MySQLSafeQuery($conn, "ALTER TABLE `{$tab}` MODIFY `{$name}` {$type} CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'");
$set = true;
echo "Altered field {$name} on {$tab} from type {$type}\n";
}
$target_collation = $target_collation_bak;
}
// Rebuild indicies
foreach ($indicies as $index) {
// Handle multi-column indices
$joined_col_str = "";
foreach ($index["col"] as $col)
$joined_col_str = $joined_col_str . ", `" . $col . "`";
$joined_col_str = substr($joined_col_str, 2);
$query = "";
if ($index["unique"])
$query = "CREATE UNIQUE INDEX `{$index["name"]}` ON `{$tab}` ({$joined_col_str})";
else
$query = "CREATE INDEX `{$index["name"]}` ON `{$tab}` ({$joined_col_str})";
MySQLSafeQuery($conn, $query);
echo "Created index {$index["name"]} on {$tab}. Unique: {$index["unique"]}\n";
}
// Set default character set and collation for table
MySQLSafeQuery($conn, "ALTER TABLE `{$tab}` DEFAULT CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'");
}
// Set default character set and collation for database
MySQLSafeQuery($conn, "ALTER DATABASE `{$db}` DEFAULT CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'");
mysqli_close($conn);
echo "</pre>";
?>
A: For Windows Users
In addition to @davidwinterbottom answer,
windows users can use command below:
mysql.exe --database=[database] -u [user] -p[password] -B -N -e "SHOW TABLES" \
| awk.exe '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' \
| mysql.exe -u [user] -p[password] --database=[database] &
Replace [database], [user] and [password] placeholders with actual values.
Git-bash users can download this bash script and run it easily.
A: For what it's worth, here's an extended version of https://stackoverflow.com/a/42545503/6226915 as a Yii2 ConsoleController class, which can also be used standalone: https://gist.github.com/cboulanger/d30c197235a53d9a2331f19a96d6e00d .
The script fixes a few bugs and adds support for fulltext indexes; also it deals with the regular index key length constraint of 3kb. It also converts all tables to InnoDB.
A: For PHP Laravel framework:
*
*Use migration: php artisan make:migration update_character_set_utf8_m4
*Migration file logic
$DBNAME = config('database.connections.mysql.database');
$CHARACTER = 'utf8mb4';
$COLLATE = 'utf8mb4_unicode_ci';
echo "Altering DB $DBNAME\n";
DB::unprepared("ALTER DATABASE $DBNAME CHARACTER SET $CHARACTER COLLATE $COLLATE;");
$tables = DB::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$DBNAME}'");
foreach ($tables as $table) {
echo "Altering $table->table_name\n";
DB::unprepared("ALTER TABLE $table->table_name CONVERT TO CHARACTER SET $CHARACTER COLLATE $COLLATE;");
}
*php artisan migrate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
}
|
Q: Need refactoring ideas for Arrow Anti-Pattern I have inherited a monster.
It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.
To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.
This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.
My question is, what methods would you suggest to refactor or restructure such a thing?
I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.
Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.
Thanks for any and all ideas.
A: I just had some legacy code at work this week that was similar (although not as dire) as what you are describing.
There is no one thing that will get you out of this. The state machine might be the final form your code takes, but thats not going to help you get there, nor should you decide on such a solution before untangling the mess you already have.
First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test.
Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net.
Now Refactor!
A couple things I did that i found useful:
Invert if statements
A huge problem I had was just reading the code when I couldn't find the corresponding else statement, I noticed that a lot of the blocks looked like this
if (someCondition)
{
100+ lines of code
{
...
}
}
else
{
simple statement here
}
By inverting the if I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding.
Extract Method
I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication.
Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood procedural code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work).
Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions.
Refactoring to Patterns is a great book to assist in explainging patterns that are helpful in these situations.
You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck.
A: A state machine seems like the logical place to start, and using WF if you can swing it (sounds like you can't).
You can still implement one without WF, you just have to do it yourself. However, thinking of it like a state machine from the start will probably give you a better implementation then creating a procedural monster that checks internal state on every action.
Diagram out your states, what causes a transition. The actual code to process a record should be factored out, and called when the state executes (if that particular state requires it).
So State1's execute calls your "read a record", then based on that record transitions to another state.
The next state may read multiple records and call record processing instructions, then transition back to State1.
A: One thing I do in these cases is to use the 'Composed Method' pattern. See Jeremy Miller's Blog Post on this subject. The basic idea is to use the refactoring tools in your IDE to extract small meaningful methods. Once you've done that, you may be able to further refactor and extract meaningful classes.
A: I would start with uninhibited use of Extract Method. If you don't have it in your current Visual Studio IDE, you can either get a 3rd-party addin, or load your project in a newer VS. (It'll try to upgrade your project, but you will carefully ignore those changes instead of checking them in.)
You said that you have code indented 15 levels. Start about 1/2-way out, and Extract Method. If you can come up with a good name, use it, but if you can't, extract anyway. Split in half again. You're not going for the ideal structure here; you're trying to break the code in to pieces that will fit in your brain. My brain is not very big, so I'd keep breaking & breaking until it doesn't hurt any more.
As you go, look for any new long methods that seem to be different than the rest; make these in to new classes. Just use a simple class that has only one method for now. Heck, making the method static is fine. Not because you think they're good classes, but because you are so desperate for some organization.
Check in often as you go, so you can checkpoint your work, understand the history later, be ready to do some "real work" without needing to merge, and save your teammates the hassle of hard merging.
Eventually you'll need to go back and make sure the method names are good, that the set of methods you've created make sense, clean up the new classes, etc.
If you have a highly reliable Extract Method tool, you can get away without good automated tests. (I'd trust VS in this, for example.) Otherwise, make sure you're not breaking things, or you'll end up worse than you started: with a program that doesn't work at all.
A pairing partner would be helpful here.
A: Judging by the description, a state machine might be the best way to deal with it. Have an enum variable to store the current state, and implement the processing as a loop over the records, with a switch or if statements to select the action to take based on the current state and the input data. You can also easily dispatch the work to separate functions based on the state using function pointers, too, if it's getting too bulky.
A: There was a pretty good blog post about it at Coding Horror. I've only come across this anti-pattern once, and I pretty much just followed his steps.
A: Sometimes I combine the state pattern with a stack.
It works well for hierarchical structures; a parent element knows what state to push onto the stack to handle a child element, but a child doesn't have to know anything about its parent. In other words, the child doesn't know what the next state is, it simply signals that it is "complete" and gets popped off the stack. This helps to decouple the states from each other by keeping dependencies uni-directional.
It works great for processing XML with a SAX parser (the content handler just pushes and pops states to change its behavior as elements are entered and exited). EDI should lend itself to this approach too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Can I revoke some database privileges from MediaWiki after installation? I've just installed MediaWiki on a web server. Obviously it needs lots of privileges during installation to set up its database correctly. Now that it's installed can I safely revoke some privileges (e.g. create table, drop table?) Or might it need to create more tables later (when they are first needed?) If not then I would prefer to grant it as few privileges as possible.
A: After the installation, MediaWiki doesn't need to create any more tables. I'd suggest giving the user insert, select, and lock permission.
grant select,lock tables,insert on media_wiki_db.* to 'wiki'@'localhost' identified by 'password';
A: Change the user that mediawiki connects as in LocalSettings.php and then using phpMyAdmin, you can edit the privileges of that user (that is, if you aren't comfortable granting and revoking privileges from the mysql console).
http://www.phpmyadmin.net/home_page/index.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do I Extend Blogengine.Net to collect statistics of visitors? I love BlogEngine. But from what I can se it does not collect the standard information about the visitors I would like to see (referrer, browser-type and so on).
When I log in as Admin I have a menu item named "Referrer". I can choose a weekday and then I'll be presented with 1 or 2 rows with
"google.com 4 hits, "itmaskinen.se 6 hits" and so on, But that's not what I want to se, I want to se where my visitors come from, country, IP if possible, how many visitors and so on.
If someone of you are familiar with Blogengine.Net and can point me in the right direction to where I would put my own log-code or if you know any visitor-statistic-extension that can do it for me, I would be really happy to know. I prefer an extension, because if I make changes myself to BlogEngine it may break later updates I install.
Blogengine.Net is a blog software made in .Net found here: http://www.dotnetblogengine.net/
And yes, I prefer to take this question here rather then in the Blogengine.Net forum, you know why. ;)
(Anyone, feel free to edit my (bad) english in this post and after that delete this sentence)
A: This isn't an extension, but it's what I use to collect all my blogengine.net data and it should be upgrade safe.
When you log into the Blogengine.NET admin screens you can go to "Settings> Custome Code > Tracking Script", here you can put your http://www.google.com/analytics/ logging script. Google Analytics provides all the referrer, browser type, etc stuff you were wanting. And what's nice is you can then create additional accounts for other sites if you choose.
A: I use both Google Analytics and StatCounter to track visitor stats. I find that each one provides useful information that the other doesn't. And they're both free to a certain extent.
I place their javascript code int the site.master file of my custom BE.Net skin.
For Google Analytics I go a step further and pass the username of authenticated users as a custom variable. That way I can match users names up with the stats. To do this you can use the _setVar javascript method on the GA pageTracker like so:
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-129049-25");
var userDefinedValue = '<%= System.Web.Security.Membership.GetUser() != null ? System.Web.Security.Membership.GetUser().UserName : "" %>';
pageTracker._setVar(userDefinedValue);
pageTracker._trackPageview();
</script>
A: Anyone noticed that we miss all the hits coming from RSS readers? Syndication.axd does not run the analytics javascripts. So we miss the vast majority of viewers from the statistics. And we happily analyze that is just not impotant - ad-hoc visitors.
A: For the vast majority of cases, Google Analytics does just fine. It all depends on how much data you want. For example, if you want to keep note of IP addresses and resolve them to get domain names, and also highlight all visits to your blog from, say, your coworkers at the company where you work, you'd have to write some custom code yourself. However, it's all fairly primitive - these sorts of things are easily achievable using ASP.NET.
A: I set up gathering statistics on IIS web site of my BlogEngine instance and then analyze the logs using WebLog Expert - http://www.weblogexpert.com.
It is more reliable than google analytics, since I see really ALL requests that are coming to my IIS, no matter if this is a request to axd or to some static content. And, once I've found out that google was fooling me in the number of visits. After that I trust my IIS statistics much more than google.
A: There is a Widget which can be use to display Visits and Online Users Statistics.
You can find it from following links:
http://www.nuget.org/packages/Statistics/
http://www.itnerd.ir/post/2013/07/25/Visits-and-Online-Users-Statistics-widget-for-BlogEngine-2
but to see the instructions go to the second link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: I need a helper method to compare a char Enum and a char boxed to an object I have an enum that looks as follows:
public enum TransactionStatus { Open = 'O', Closed = 'C'};
and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed.
now because the data comes out of the database as an object I am having a heck of a time writing comparison code.
The best I can do is to write:
protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {
return ((char)enum_status).ToString() == obj_status.ToString();
}
However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. Supposedly all enums inherit from System.Enum but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question.
I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing?
A: static void Main(string[] args)
{
object val = 'O';
Console.WriteLine(EnumEqual(TransactionStatus.Open, val));
val = 'R';
Console.WriteLine(EnumEqual(DirectionStatus.Left, val));
Console.ReadLine();
}
public static bool EnumEqual(Enum e, object boxedValue)
{
return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue));
}
public enum TransactionStatus { Open = 'O', Closed = 'C' };
public enum DirectionStatus { Left = 'L', Right = 'R' };
A: Enums are generally messy in C# so when using .NET 2.0 its common to wrap the syntax with generics to avoid having to write such clumsy code.
In .NET 1.1 you can do something like the below, although it's not much tidier than the original snippet:
protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status)
{
return (enum_status == Enum.Parse(typeof(TransactionStatus), obj_status.ToString()));
}
This is about the same amount of code but you are now doing enum rather than string comparison.
You could also use the debugger/documentation to see if obj_status really is an object or whether you can safely cast it to a string.
A: If you just have to compare values you can use something like:
protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {
return (char)enum_status == (char)obj_status;
}
A: I would take a look at Enum.Parse. It will let you parse your char back into the proper enum. I believe it works all the way back to C# 1.0. Your code would look a bit like this:
TransactionStatus status = (TransactionStatus)Enum.Parse(typeof(TransactionStatus), obj.ToString());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: VSTO Excel 2007 PivotTable, having a PivotField in more than one column I am using VSTO with Excel 2007 to generate PivotTables and PivotCharts dynamically.
I am having a problem when I need to have a PivotField in more than one column.
To accomplish this I create a PivotTable in Excel and serialize its properties into an XML document, which I then use to rebuild the PivotTable.
Ie: as a Value and as a Column
This is possible when building the PivotTable in Excel. Has found a way to do this using C# ?
Creating a PivotTable Programmatically
A: If you add a calculated field to a Piviot Table and make the formula simply be the name of the field you need a duplicate of that allows you to use the same field twice, the Calculated Field does have to be a Value field.
Prehaps you can do this programaticly.
A: Once you have your Dataset you can convert it to an object[,] and insert it into an Excel document. Then you can save the document to disk and stream it to the user.
for (int cIndex = 1; cIndex < 1 + columns; cIndex++)
sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption);
if (rows > 0)
{
//select the range where the data will be pasted
Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]);
//Convert the datatable to an object array
object[,] workingValues = new object[rows, columns];
for (int rIndex = 0; rIndex < rows; rIndex++)
for (int cIndex = 0; cIndex < columns; cIndex++)
workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString();
r.Value2 = workingValues;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can XPath return only nodes that have a child of X? Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the lizard and pig elements from this example:
<pets>
<cat>
<foo>don't care about this</foo>
</cat>
<dog>
<foo>not this one either</foo>
</dog>
<lizard>
<bar>lizard should be returned, because it has a child of bar</bar>
</lizard>
<pig>
<bar>return pig, too</bar>
</pig>
</pets>
This Xpath gives me all pets: "/pets/*", but I only want the pets that have a child node of name 'bar'.
A: Here it is, in all its glory
/pets/*[bar]
English: Give me all children of pets that have a child bar
A: Just in case you wanted to be more specific about the children - you can also use selectors on them.
Example:
<pets>
<cat>
<foo>don't care about this</foo>
</cat>
<dog>
<foo>not this one either</foo>
</dog>
<lizard>
<bar att="baz">lizard should be returned, because it has a child of bar</bar>
</lizard>
<pig>
<bar>don't return pig - it has no att=bar </bar>
</pig>
</pets>
Now, you only care about all pets having any child bar that has an attribute att with value baz. You can use the following xpath expression:
//pets/*[descendant::bar[@att='baz']]
Result
<lizard>
<bar att="baz">lizard should be returned, because it has a child of bar</bar>
</lizard>
A: /pets/child::*[child::bar]
My pardon, I did not see the comments to the previous reply.
But in this case I'd rather prefer using the descendant:: axis, which includes all elements down from specified:
/pets[descendant::bar]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: Connection Timeout exception for a query using ADO.Net Update: Looks like the query does not throw any timeout. The connection is timing out.
This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.
I cannot use any of these techniques:
1) Increase timeout.
2) Run it asynchronously with a callback. This needs to run in a synchronous manner.
please suggest any other techinques to keep the connection alive while executing a time consuming query?
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
A: You should first check your query to see if it's optimized and it isn't somehow running on missing indexes. 30 seconds is allot for most queries, even on large databases if they are properly tuned. If you have solid proof using the query plan that the query can't be executed any faster than that, then you should increase the timeout, there's no other way to keep the connection, that's the purpose of the timeout to terminate the connection if the query doesn't complete in that time frame.
A: Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback)
but the application will wait (inside a while loop) until the query is complete. From MSDN. This should solve the timeout problem. Please try it out.
But, I agree with others that you should think more about optimizing the query to perform under 30 seconds.
IAsyncResult result = command.BeginExecuteNonQuery();
int count = 0;
while (!result.IsCompleted)
{
Console.WriteLine("Waiting ({0})", count++);
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Command complete. Affected {0} rows.",
command.EndExecuteNonQuery(result));
A: I have to agree with Terrapin.
You have a few options on how to get your time down. First, if your company employs DBAs, I'd recommend asking them for suggestions.
If that's not an option, or if you want to try some other things first here are your three major options:
*
*Break up the query into components that run under the timeout. This is probably the easiest.
*Change the query to optimize the access path through the database (generally: hitting an index as closely as you can)
*Change or add indices to affect your query's access path.
A: If you are constrained from using the default process of changing the timeout value you will most likely have to do a lot more work. The following options come to mind
*
*Validate with your DBA's and another code review that you have truly optimized the query as best as possible
*Work on the underlying DB structure to see if there is any gain you can get on the DB side, creating/modifying an idex(es).
*Divide it into multiple parts, even if this means running procedures with multiple return parameters that simply call another param. (This option is not elegant, and honestly if your code REALLY is going to take this much time I would be going to management and re-discussing the 30 second timeout)
A: We recently had a similar issue on a SQL Server 2000 database.
During your query, run this query on your master database on the db server and see if there are any locks you should troubleshoot:
select
spid,
db_name(sp.dbid) as DBname,
blocked as BlockedBy,
waittime as WaitInMs,
lastwaittype,
waitresource,
cpu,
physical_io,
memusage,
loginame,
login_time,
last_batch,
hostname,
sql_handle
from sysprocesses sp
where (waittype > 0 and spid > 49) or spid in (select blocked from sysprocesses where blocked > 0)
SQL Server Management Studio 2008 also contains a very cool activity monitor which lets you see the health of your database during your query.
In our case, it was a networkio lock which kept the database busy. It was some legacy VB code which didn't disconnect its result set quick enough.
A: If you are prohibited from using the features of the data access API to allow a query to last more than 30 seconds, then we need to see the SQL.
The performance gains to be made by optimizing the use of ADO.NET are slight in comparison to the gains of optimizing the SQL.
And you already are using the most efficient method of executing SQL. Other techniques would be mind numbingly slower (although, if you did a quick retrieval of your rows and some really slow client side processing using DataSets, you might be able to get the initial retrieval down to less than 30 seconds, but I doubt it.)
If we knew if you were doing inserts, then maybe you should be using bulk insert. But we don't know the content of your sql.
A: This is an UGLY hack, but might help solve your problem temporarily until you can fix the real problem
private static void CreateCommand(string queryString,string connectionString)
{
int maxRetries = 3;
int retries = 0;
while(true)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
break;
}
catch (SqlException se)
{
if (se.Message.IndexOf("Timeout", StringComparison.InvariantCultureIgnoreCase) == -1)
throw; //not a timeout
if (retries >= maxRetries)
throw new Exception( String.Format("Timedout {0} Times", retries),se);
//or break to throw no error
retries++;
}
}
}
A: command.CommandTimeout *= 2;
That will double the default time-out, which is 30 seconds.
Or, put the value for CommandTimeout in a configuration file, so you can adjust it as needed without recompiling.
A: If you absolutely cannot increase the timeout, your only option is to reduce the time of the query to execute within the default 30 second timeout.
A: You should break your query up into multiple chunks that each execute within the timeout period.
A: I tend to dislike increasing the connection/command timeout since in my mind that would be a matter of taking care of the symptom, not the problem
A: just set sqlcommand's CommandTimeout property to 0, this will cause the command to wait until the query finishes...
eg:
SqlCommand cmd = new SqlCommand(spName,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
A: have you thought about breaking the query down into several smaller chunks?
Also, have you ran your query against the Database Engine Tuning Advisor in:
Management Studio > Tools > Database Engine Tuning Advisor
Lastly, could we get a look at the query itself?
cheers
A: Have you tried wrapping your sql inside a stored procedure, they seem to have better memory management. Have seen timeouts like this before in plan sql statement with internal queries using classic ADO. i.e. select * from (select ....) t inner join somthingTable. Where the internal query was returning a very large number of results.
Other tips
1. Performing reads with the with(nolock) execution hint, it's dirty and I don't recommend it but it will tend to be faster.
2. Also look at the execution plan of the sql your trying to run and reduce the row scanning, the order in which you join tables.
3. look at adding some indexes to your tables for faster reads.
4. I've also found that deleting rows is very expensive, you could try and limit the number of rows per call.
5. Swap @table variables with #temporary tables has also worked for me in the past.
6. You may also have saved bad execution plan (heard, never seen).
Hope this helps
A:
Update: Looks like the query does not
throw any timeout. The connection is
timing out.
I.o.w., even if you don't execute a query, the connection times out? because there are two time-outs: connection and query. Everybody seems to focus on the query, but if you get connection timeouts, it's a network problem and has nothing to do with the query: the connection first has to be established before a query can be ran, obviously.
A: It might be worth trying paging the results back.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Injecting a user account into mySQL Tackling a strange scenario here.
We use a proprietary workstation management application which uses mySQL to store its data. Within the application they provide number of reports, such as which user logged into which machine at what time, all the software products installed on the monitored machines, so on and so forth. We are looking to do a different set of reports, however, they do not support custom reports.
Since their data is being stored in mySQL, I gather I can do the reporting manually. I don't have valid credentials to connect to the mySQL server though. Is there anyway for me to create a user account in the mySQL server? I do not want to reset the root password or anything account that might be in there, as it might break the application.
I have full access to the Windows 2003 server. I can stop and restart services, including the mySQL server. To the actual mySQL server, I only have basic access through the GUI provided by the software. I can't connect to it directly through CLI or through another tool (due to the lack of credentials).
I apologize if it came off as if I'm trying to get unauthorized access to the mySQL server. I have contacted the software company, and as of today it's been two weeks without a response from them. I need to get to the data. I have full access to the physical box, I have admin privileges on it.
A: You'll want to use the MySQL password recovery process. Follow these instructions, except replace the password reset query with a query to add a new user. The new user query would be something like:
GRANT ALL ON *.* TO 'myuser'@'localhost' IDENTIFIED BY 'mypassword' WITH GRANT OPTION;
That will create a new user "myuser" with the password "mypassword", who may log in to MySQL through the local system's CLI. You can then use the MySQL Administrator GUI (download here) and update user permissions so you can log in from other systems on the network. Or use the GRANT statement from the CLI, if that's more your style.
A: Do you have access to the MySQL server in question?
As in, what access do you have beyond what a regular user would? You should try to go through those routes before you "hack" your way in there, since that may or may not be feasible with that software.
A: I assume I really should not answer this one, but it's just too much fun.
Look at This page about SQL injections. That should cover your needs.
This page shows how to add user accounts to mySQL
I would try entering the following in random user input fields:
p'; INSERT INTO user VALUES
('localhost','myNewAdmin',PASSWORD('some_pass'),
'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
and then
p'; FLUSH PRIVILEGES;
p'; is intended to close the regular question. e.g -
Normal question is:
"Select Adress from cusomers where custName = ' + $INPUT + ';
becomes
Select Adress from cusomers where custName = 'p'; INSERT INTO user
VALUES('localhost','myNewAdmin',PASSWORD('some_pass'),
'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
A: One thing that comes in mind is sniffing the database communication and hope it's not encrypted. If it is encrypted try changing the configuration not to use SSL and restart mysql. A good sniffer that I use is Wireshark
From mysql 5.0 documentation:
MySQL supports secure (encrypted)
connections between MySQL clients and
the server using the Secure Sockets
Layer (SSL) protocol. This section
discusses how to use SSL connections.
It also describes a way to set up SSH
on Windows. For information on how to
require users to use SSL connections,
see the discussion of the REQUIRE
clause of the GRANT statement in
Section 12.5.1.3, “GRANT Syntax”.
The standard configuration of MySQL is
intended to be as fast as possible, so
encrypted connections are not used by
default. Doing so would make the
client/server protocol much slower.
Encrypting data is a CPU-intensive
operation that requires the computer
to do additional work and can delay
other MySQL tasks. For applications
that require the security provided by
encrypted connections, the extra
computation is warranted.
MySQL allows encryption to be enabled
on a per-connection basis. You can
choose a normal unencrypted connection
or a secure encrypted SSL connection
according the requirements of
individual applications.
Secure connections are based on the
OpenSSL API and are available through
the MySQL C API. Replication uses the
C API, so secure connections can be
used between master and slave servers.
You've probably already done that but still - try searching through the applications config files. If there's nothing - try searching through the executables/source code - maybe it's in plaintext if you're lucky.
A: odds are there are triggers on the database side keeping a log so when you hack yourself into the database they will know when and how you did it. Not a good idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to print wstring in gdb How can I print wstring in gdb?
A: call printf %ls only works sometimes, but to get it to work at all in gdb 6.3 you need the void cast and linefeed \n shown here:
call (void)printf("\"%ls\"\n",str.c_str())
here is a more reliable command you can put in your .gdbinit that also shows non-ASCII code points:
define wc_print
echo "
set $c = (wchar_t*)$arg0
while ( *$c )
if ( *$c > 0x7f )
printf "[%x]", *$c
else
printf "%c", *$c
end
set $c++
end
echo "\n
end
just enter wc (short for wc_print) with either a std::wstring or wchar_t*.
More detail at http://www.firstobject.com/wchar_t-gdb.htm
A: Suppose you've got a std::wstring str. The following should work in gdb:
call printf("%ls", str._M_data())
(The -l option in printf makes it a long string, and I believe you need the "call" statement because the ordinary gdb printf doesn't like that option.)
A: I did some research, and this is gdb PR716, PR1998, PR2264. Apparently this is an often-requested feature that is not yet implemented.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: int matrix with pointers in C - memory allocation confusion I'm having some issues with producing an int matrix without creating memory leaks. I want to be able to make a given (global) matrix into any size dynamically via read_matrix(). But then i want to be able to free the memory later on. So in my main method the second printf should result in a bus error since it should not have any memory allocated to it. How would i go about creating this?
int** first_matrix;
int** second_matrix;
int** result_matrix;
int** read_matrix(int size_x, int size_y)
{
int** matrix;
matrix = calloc(size_x, sizeof(int*));
for(int i = 0;i<size_x;i++) {
matrix[i] = calloc(size_y, sizeof(int));
}
for(int i = 0;i<size_x;i++) {
for(int j = 0;j<size_y;j++) {
matrix[i][j] = i*10+j;
}
}
return matrix;
}
int main(int stackc, char** stack)
{
first_matrix = read_matrix(10,10);
printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]);
free(*first_matrix);
free(first_matrix);
printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]);
}
A: Just because the memory has been free'd doesn't mean you can't access it! Of course, it's a very bad idea to access it after it's been free'd, but that's why it works in your example.
Note that free( *first_matrix ) only free's first_matrix[0], not the other arrays. You probably want some kind of marker to signify the last array (unless you will always know when you free the outer array how many inner arrays you allocated). Something like:
int** read_matrix(int size_x, int size_y)
{
int** matrix;
matrix = calloc(size_x, 1+sizeof(int*)); // alloc one extra ptr
for(int i = 0;i<size_x;i++) {
matrix[i] = calloc(size_y, sizeof(int));
}
matrix[size_x] = NULL; // set the extra ptr to NULL
for(int i = 0;i<size_x;i++) {
for(int j = 0;j<size_y;j++) {
matrix[i][j] = i*10+j;
}
}
return matrix;
}
Then when you're freeing them:
// keep looping until you find the NULL one
for( int i=0; first_matrix[i] != NULL; i++ ) {
free( first_matrix[i] );
}
free( first_matrix );
A: You need to free each row individually:
void free_matrix(int **matrix, int size_x)
{
for(int i = 0; i < size_x; i++)
free(matrix[i]);
free(matrix);
}
A: Freeing the memory doesn't make it go away, it just means that another allocation might grab that same chunk of memory. Whatever you put in it will still be there until something else overwrites it.
Also, you're not freeing everything you allocated. You're only freeing the array of pointers and the first row. But even if you free everything correctly, you would still have the same effect.
If you want to create a "bus error" you need to point to memory that doesn't belong to your process. Why do you want to do that anyway?
A: You only freed the first row (or column) of first_matrix. Write another function like this:
void free_matrix(int **matrix, int rows)
{
int i;
for(i=0; i<rows; i++)
{
free(matrix[i]);
}
free(matrix);
}
You might want to make the matrix into a struct to store it's row and column count.
A: I recommend using valgrind to track down unfree'd memory, as opposed to trying to make a bus error occur. It rocks for lots of other stuff as well.
Sam
A: You're getting memory leaks because you're freeing the first row of the matrix and the list of rows, but none of the 1 to nth rows. You need to call free in a loop.
There are a couple of alternatives, however:
- Allocate sizeof(int*)rows + rowscols*sizeof(int) bytes and use the first bytes for the row pointers. That way, you only have a single chunk of memory to free (and it's easier on the allocator, too)
- Use a struct that contains the number of rows. Then you can avoid the row list altogether (saving memory). The only downside is that you have to use a function, a macro, or some messy notation to address the matrix.
If you go with the second option, you can use a struct like this in any C99 compiler, and again only have to allocate a single block of memory (of size numints*sizeof(int)+sizeof(int)):
struct matrix {
int rows;
int data[0];
}
A: The concept you are missing here, is that for every calloc, there must be a free.
and that free must be applied to the pointer passed back from calloc.
I recommend you create a function (named delete_matrix)
that uses a loop to free all of the pointers that you allocate in here
for(int i = 0;i < size_x;i++) {
matrix[i] = calloc(size_y, sizeof(int));
}
then, once that is done, free the pointer allocated by this.
matrix = calloc(size_x, sizeof(int*));
The way you are doing it now,
free(*first_matrix);
free(first_matrix);
won't do what you want it to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How can one grab a stack trace in C? I know there's no standard C function to do this. I was wondering what are the techniques to to this on Windows and *nix? (Windows XP is my most important OS to do this on right now.)
A: glibc provides backtrace() function.
http://www.gnu.org/software/libc/manual/html_node/Backtraces.html
A: For Windows, CaptureStackBackTrace() is also an option, which requires less preparation code on the user's end than StackWalk64() does. (Also, for a similar scenario I had, CaptureStackBackTrace() ended up working better (more reliably) than StackWalk64().)
A: You should be using the unwind library.
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
unsigned long a[100];
int ctr = 0;
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
if (ctr >= 10) break;
a[ctr++] = ip;
}
Your approach also would work fine unless you make a call from a shared library.
You can use the addr2line command on Linux to get the source function / line number of the corresponding PC.
A: There is no platform independent way to do it.
The nearest thing you can do is to run the code without optimizations. That way you can attach to the process (using the visual c++ debugger or GDB) and get a usable stack trace.
A: There's backtrace(), and backtrace_symbols():
From the man page:
#include <execinfo.h>
#include <stdio.h>
...
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
...
One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols() in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:
class MyException : public std::exception {
char ** strs;
MyException( const std::string & message ) {
int i, frames = backtrace(callstack, 128);
strs = backtrace_symbols(callstack, frames);
}
void printStackTrace() {
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
}
};
...
try {
throw MyException("Oops!");
} catch ( MyException e ) {
e.printStackTrace();
}
Ta da!
Note: enabling optimization flags may make the resulting stack trace inaccurate. Ideally, one would use this capability with debug flags on and optimization flags off.
A: For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.
Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.
Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.
Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).
I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.
A: Solaris has the pstack command, which was also copied into Linux.
A: You can do it by walking the stack backwards. In reality, though, it's frequently easier to add an identifier onto a call stack at the beginning of each function and pop it at the end, then just walk that printing the contents. It's a bit of a PITA, but it works well and will save you time in the end.
A: For the past few years I have been using Ian Lance Taylor's libbacktrace. It is much cleaner than the functions in the GNU C library which require exporting all the symbols. It provides more utility for the generation of backtraces than libunwind. And last but not least, it is not defeated by ASLR as are approaches requiring external tools such as addr2line.
Libbacktrace was initially part of the GCC distribution, but it is now made available by the author as a standalone library under a BSD license:
https://github.com/ianlancetaylor/libbacktrace
At the time of writing, I would not use anything else unless I need to generate backtraces on a platform which is not supported by libbacktrace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "88"
}
|
Q: (any == System.DBNull.Value) vs (any is System.DBNull) Does any one have a preference on how to check if a value is DBNull? I've found these two statements give me the results I want, but just wondering if there's a preference?
if (any is System.DBNull)
same as:
if (any == System.DBNull.Value)
Thanks!
A: is does not use reflection as Kevlar623 says. It maps to the isinst operation in IL. On that level, comparing performance is downright silly, unless you're working on a missile guidance system.
I use value is DBNull. It just sounds right and as a paranoid developer, I can't trust that the only value ever in existence is DBNull.Value. Bugs happen.
A: if (any == System.DBNull.Value) ...
I prefer that one, simply because I read that as comparing values, not types.
A: I tend to use
if (DBNull.Value.Equals(value)) {
//
}
or
if (Convert.IsDBNull(value)) {
//
}
A: if you're in c#, you should use ==; is uses reflection which is more expensive to compute, especially since there's only ever one instance of System.DBNull.
A: This is a good example of form follows function. Whichever one executes more efficiently is the way to go. What it looks like, reads like, or bad names it calls you is irrelevant. Use the language efficiently, don't mold the language into a new one.
A: I like the "is System.DBNull" more because I hate the idea of comparing something to NULL and having it be true. Many other syntaxes (what the hell is the plural of that?) would have anything==NULL return NULL.
I understand that there's DBNull.Value for a reason. I know. I'm listing my PREFERENCE :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Get a list of all computers on a network w/o DNS Greetings,
I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network.
Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work.
A: Nmap is good for this - use the -O option for OS fingerprinting and -oX "filename.xml" for output as xml that you can then parse from c#.
A suitable commandline would be (where 192.168.0.0/24 is the subnet to scan):
nmap -O -oX "filename.xml" 192.168.0.0/24
leave out the -O if you aren't interested in guessing the OS - if you just want a ping sweep use -sP, or read the docs for the myriad other options.
A: To expand on what Unkwntech has said -
You can also do a "broadcast" ping to avoid having to ping each IP address individually.
Immediately after than you can use "arp" to examine the ARP cache and get a list of which IP addresses are on which MAC address.
A: Ping everything in the rage, then you can get netbios info from the systems that respond to identify it's name.
A: In one of my web app I used the NetApi32 function for network browsing.
Code:
http://gist.github.com/11668
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: TCP send queue depth How do I discover how many bytes have been sent to a TCP socket but have not yet been put on the wire?
Looking at the diagram here:
I would like to know the total of Categories 2, 3, and 4 or the total of 3 and 4. This is in C(++) and on both Windows and Linux. Ideally there is a ioctl that I could use, but there doesn't seem to be any.
A: Under Linux, see the man page for tcp(7).
It appears that you can get the number of untransmitted bytes by ioctl(sock,SIOCINQ ...
Other stats might be available from members of the structure given back by the TCP_INFO getsockopt() call.
A: Some Unix flavors may have an API way to do this, but there is no way to do it that is portable across different variants.
A: If you want to determine wheter to add data or not: don't worry, send will block until the data is in the queue. If you don't want it to block, you can tell it to send(2):
send(socket, buf, buflen, MSG_DONTWAIT);
But this only works on Linux.
You can also set the socket to non-blocking:
fcntl(socket, F_SETFD, O_NONBLOCK);
This way write will return an error (EAGAIN) if the data cannot be written to the stream.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What XML do I send for a field thats declared as nillable? I have an application with a REST style interface that takes XML documents via POST from clients. This application is written in Java and uses XML beans to process the posted message.
The XML schema definition for a field in the message looks like this:
<xs:element name="value" type="xs:string" nillable="true" />
How do I send a null value that meets this spec?
I sent <value xsi:nil="true" />
but this caused the XML parser to barf.
A: What about <value xsi:nil="true"></value>? That's what's in the spec.
A: In the past when I've had XML elements that were null I could either not include them or send them empty so, in your case it'd be:
<value />
Have you tried that?
A: That's the right way of sending a nil value (assuming that the default namespace and the xsi namespace are set to the correct values, namely "http://www.w3.org/2001/XMLSchema-instance" for xsi.) so it looks like you might have come up against a bug in the CML parser you're using. What's the error message?
You might try using xsi:nil="1" or using separate open and close tags (<value xsi:nil="true"></value>) to try working around the bug.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any way to enable the mousewheel (for scrolling) in Java apps? Ideally I'd like a way to enable the mouse wheel for scrolling in old compiled java runtime apps, but java code to explicitly utilise it for an individual app would suffice.
A: You shouldn't have to recompile against 1.5 or 1.6 to get mousewheel, unless you wrote custom components. The mousewheel behaviors were added to the swing classes, so just running old java apps against the new JRE should have mousewheel support without having to do anything (at least in scrollable/JScrollPane based stuff)
A: Mousewheel scrolling is supported in current Swing applications. You could try compiling your application using JDK 1.4, 1.5 or 1.6. Depending on the complexity and environment moving to a new version may or may not be a viable option.
This tutorial shows how to write your own mousewheel listener if you want something different to the normal behaviour.
A: Take a look Pushing Pixels blog: http://www.pushing-pixels.org/index.php?s=mouse+wheel
A: Without access to the source code, you can't do it. If you do have access to the source, then do what RichH said.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Making a beta code for a public django site I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django.
I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block.
How should I do this? It's a fairly large project, so adding code to every view is far from ideal.
That solution works well. The Middleware Class I ended up with this this:
from django.http import HttpResponseRedirect
class BetaMiddleware(object):
"""
Require beta code session key in order to view any page.
"""
def process_request(self, request):
if request.path != '/beta/' and not request.session.get('in_beta'):
return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))
A: You can probably restrict access to the entire site via apache with htaccess, taking the problem out of the django's project space entirely.
A: Start with this Django snippet, but modify it to check request.session['has_beta_access']. If they don't have it, then have it return a redirect to a "enter beta code" page that, when posted to with the right code, sets that session variable to True.
Making it a public beta then just consists of removing that middleware from your MIDDLEWARE_CLASSES setting.
A: Do what StackOverflow did.
They had a simple email/password form. It had a single hard-coded password (falkensmaze). When the user gets the password right set a cookie. eg. auth=1
Don't worry about it being unsecure. Who care's if someone hacks into the beta?
Apache/htaccess is also a nice and simple solution.
A: You should be able to add @login_required decorators across the board and be done with it. Unless you have a boat-load of view functions, it shouldn't be too horrible.
A: I'm not sure what version of the Pinax code you're using, but they've built in the ability to close the site off for a private beta so you don't need to do much work yourself.
The link to the specific project template for a private beta site is here: http://github.com/pinax/pinax/tree/3ad73d1ba44f37365333bae17b507668b0eb7e16/pinax/projects/private_beta_project although I think they might have since added that functionality to all the project templates.
A: Great snippet but it resulted lots of problems for me related OpenId sessions. So I end up relying on Cookies instead of the Session:
class BetaMiddleware(object):
"""
Require beta code cookie key in order to view any page.
"""
set_beta = False
def process_request(self, request):
referer = request.META.get('HTTP_REFERER', '')
if request.method == 'GET' and not 'is_in_beta' in request.COOKIES:
return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))
if request.method == 'POST' and 'pass' in request.POST:
code = request.POST['pass']
if code=='beta':
self.set_beta = True
return HttpResponseRedirect('%s' % '/')
def process_response(self, request, response):
if self.set_beta is True:
response.set_cookie('is_in_beta', '1')
return response
It's not secure but that's enough for me. This also works with just a beta html page.
A: use this middleware:
class BetaForm(Form):
beta_pass = CharField(required=True)
def clean_beta_pass(self):
data = self.cleaned_data['beta_pass']
if data != settings.BETA_PASS:
raise forms.ValidationError("Invalid Beta pass!")
return data
class BetaView(FormView):
form_class = BetaForm
template_name = "beta.html"
def form_valid(self, form):
response = HttpResponseRedirect(self.request.GET.get("next", "/"))
response.set_cookie(settings.BETA_PASS, '')
return response
def beta_middleware(get_response):
def middleware(request):
if request.path == reverse("beta"):
return get_response(request)
else:
if settings.BETA_PASS in request.COOKIES:
return get_response(request)
else:
return HttpResponseRedirect(
'%s?%s' % (reverse("beta"), urlencode({"next": request.get_full_path()})))
return middleware
this template:
<!doctype html>
<title>Welcome to the beta!</title>
<style>
body { text-align: center; padding: 150px; }
h1 { font-size: 50px; }
body { font: 20px Helvetica, sans-serif; color: #333; }
article { display: block; text-align: left; width: 650px; margin: 0 auto; }
a { color: #dc8100; text-decoration: none; }
a:hover { color: #333; text-decoration: none; }
</style>
<article>
<h1>>Welcome to the beta lucky user!</h1>
<div>
<form method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
</div>
</article>
this settings:
BETA_PASS="beta"
this path:
path("beta",BetaView.as_view(),name="beta"),
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Web designer for simple reports Users of my web app need to edit and "save as" their reports and then execute and export them to PDF or Excel files.
I need to know if there is a designer (web) for simple reports (open source would be better). Reports are not complex: just data fields, master-detail, labels, simple formulas, lines, static images...
Is there any? (too much to ask?)
Thanks
A: I'd just produce a csv file from the information and save that for the excel side of things.
In PHP, something like this:
<?php
// load info from database into an array
header("Content-type: application/vnd.ms-excel");
header( "Content-disposition: report.csv");
// loop through array and export each entry as so
echo ($item[1].",".$item[2].",".$item[3]."\n");
// end loop
?>
Obviously, that's just the barebones, but you can see what I'm getting at.
Alternatively there are libraries in PEAR for PHP that will let you save as an xls or pdf, but I've always preferred simplicity over complex libraries when I can get away with it!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are some excellent examples of user sign-up forms on the web? I'm trying to get a sampling of what people think are the best sign-up forms. Good design, usability. Smart engineering. Helpful feedback.
A: One of my all-time fave sign-up forms was the original Vox one, which has since been changed; there was a great break-down of it published online, and it goes into the things that made it so great to me. How they implemented the CSS layout of their forms, how they used in-form validation with pop-up tips, etc. -- it was nice.
A: Two good links to start with:
CSS-Based Forms: Modern Solutions
Label Placement in Forms
A: I like Geni's one (www.geni.com). It's an example of a signup form that doesn't feel like one. You can get started straight away with the site, and are able to add further information as an when you want to.
A: I think that Reddit's registration is pretty good. If you attempt to use an action that requires you to be logged in it will pop up in front all Javascripty. It just requires your username and password, and just takes a few second.
A: Surprisingly enough, my all-time favorite, of ones I've encountered in the wild, is Dell's, on their IdeaStorm.
If you click on a control that requires a login (to vote up an idea, for example), it automatically refocuses on the login element. If you don't already have an account you can hit the 'register' tab and no page load is required.
The register form is totally lightweight (four fields I think) and uses AJAX to check if the name is already taken. Once you register you're automatically logged in.
Bottom line, it's visually compact, asks for a minimal amount of information, and lets you login or register without ever leaving the original page.
A: Is it vain to suggest my own? It's not perfect, but I think it's a good mix of simple, friendly, and optionally thorough:
https://www.woot.com/User/Register.aspx
A: 37signals' Screens Around Town column often has interesting ones. Worth a peek.
A: There are some nice shots of sign up forms in the flickr set to go along with Luke Wroblewski's "Web Form Design" book.
(which is jolly good - worth picking up if you're interested in this sort of thing).
A: The perfect example of a login form, in my opinion, is the one on 2chan. Read linked wikipedia article to understand.
A: A couple of examples I find interesting are Tripit, a site for organizing your travel plans. Although there is a link to Sign-up for the service the easiest and quickest way is to forward a confirmation email from a travel service (orbitz, travelocity, united.com, hertz.com etc), doing this will automatically sign you up and get you going (once you log in to the site it will ask for more info).
Another quick and easy registration is Marco Arment's Instapaper. All you need is to fill in your email address or username.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I move to end of line in Vim? I know how to generally move around in command mode, specifically, jumping to lines, etc. But what is the command to jump to the end of the line that I am currently on?
A: Or there's the obvious answer: use the End key to go to the end of the line.
A: The main question - end of line
$ goes to the end of line, remains in command mode
A goes to the end of line, switches to insert mode
Conversely - start of line (technically the first non-whitespace character)
^ goes to the start of line, remains in command mode
I (uppercase i) goes to the start of line, switches to insert mode
Further - start of line (technically the first column irrespective of whitespace)
0 (zero) goes to the start of line, remains in command mode
0i (zero followed by lowercase i) goes the start of line, switches to insert mode
For those starting to learn vi, here is a good introduction to vi by listing side by side vi commands to typical Windows GUI Editor cursor movement and shortcut keys.
vi editor for Windows users
A: Possibly unrelated, but if you want to start a new line after the current line, you can use o anywhere in the line.
A: If your current line wraps around the visible screen onto the next line, you can use g$ to get to the end of the screen line.
A: I can't see hotkey for macbook for use vim in standard terminal. Hope it will help someone.
For macOS users (tested on macbook pro 2018):
fn + ← - move to beginning line
fn + → - move to end line
fn + ↑ - move page up
fn + ↓ - move page down
fn + g - move the cursor to the beginning of the document
fn + shift + g - move the cursor to the end of the document
For the last two commands sometime needs to tap twice.
A: As lots of people have said:
*
*$ gets you to the end of the line
but also:
*
*^ or _ gets you to the first non-whitespace character in the line, and
*0 (zero) gets you to the beginning of the line incl. whitespace
A: The easiest option would be to key in $. If you are working with blocks of text, you might appreciate the command { and } in order to move a paragraph back and forward, respectively.
A: Just the $ (dollar sign) key. You can use A to move to the end of the line and switch to editing mode (Append). To jump to the last non-blank character, you can press g then _ keys.
The opposite of A is I (Insert mode at beginning of line), as an aside. Pressing just the ^ will place your cursor at the first non-white-space character of the line.
A: The dollar sign: $
A: I was used to Home/End getting me to the start and end of lines in Insert mode (from use in Windows and I think Linux), which Mac doesn't support. This is particularly annoying because when I'm using vim on a remote system, I also can't easily do it. After some painful trial and error, I came up with these .vimrc lines which do the same thing, but bound to Ctrl-A for the start of the line and Ctrl-D for the end of the line. (For some reason, Ctrl-E I guess is reserved or at least I couldn't figure a way to bind it.) Enjoy.
:imap <Char-1> <Char-15>:normal 0<Char-13>
:imap <Char-4> <Char-15>:normal $<Char-13>
There's a good chart here for the ASCII control character codes here for others as well:
http://www.physics.udel.edu/~watson/scen103/ascii.html
You can also do Ctrl-V + Ctrl- as well, but that doesn't paste as well to places like this.
A: Press A to enter edit mode starting at the end of the line.
A: *
*$ moves to the last character on the line.
*g _ goes to the last non-whitespace character.
*g $ goes to the end of the screen line (when a buffer line is wrapped across multiple screen lines)
A: The advantage of the 'End' key is it works in both normal and insert modes.
'$' works in normal/command mode only but it also works in the classic vi editor (good to know when vim is not available).
A: Also note the distinction between line (or perhaps physical line) and screen line. A line is terminated by the End Of Line character ("\n"). A screen line is whatever happens to be shown as one row of characters in your terminal or in your screen. The two come apart if you have physical lines longer than the screen width, which is very common when writing emails and such.
The distinction shows up in the end-of-line commands as well.
*
*$ and 0 move to the end or beginning of the physical line or paragraph, respectively:
*g$ and g0 move to the end or beginning of the screen line or paragraph, respectively.
If you always prefer the latter behavior, you can remap the keys like this:
:noremap 0 g0
:noremap $ g$
A: In many cases, when we are inside a string we are enclosed by a double quote, or while writing a statement we don't want to press escape and go to end of that line with arrow key and press the semicolon(;) just to end the line. Write the following line inside your vimrc file:
imap <C-l> <Esc>$a
What does the line say? It maps Ctrl+l to a series of commands. It is equivalent to you pressing Esc (command mode), $ (end of line), a (append) at once.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1387"
}
|
Q: Can't figure out what this SubString.PadLeft is doing In this code I am debugging, I have this code snipit:
ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0');
What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year.
UPDATE: Thanks everyone. I don't do a lot of .NET development so setting up a quick test isn't as quick for me.
A: It takes the last two digits of the year and pads the left side with zeroes to a maximum of 2 characters. Looks like a "just in case" for expiration years ending in 08, 07, etc., making sure that the leading zero is present.
A: This prints "98" to the console.
class Program
{
static void Main(string[] args)
{
Console.Write("1998".Substring(2).PadLeft(2, '0'));
Console.Read();
}
}
A: Of course you can run this. You just can't run it in the application you're debugging. To find out what it's doing, and not just what it looks like it's doing, make a new web application, put in a DropDownList, put a few static years in it, and then put in the code you've mentioned and see what it does. Then you'll know for certain.
A: something stupid. It's getting the value of the selected item and taking the everything after the first two characters. If that is only one character, then it adds a '0' to the beginning of it, and if it is zero characters, the it returns '00'. The reason I say this is stupid is because if you need the value to be two characters long, why not just set it like that to begin with when you are creating the drop down list?
A: It looks like it's grabbing the substring from the 3rd character (if 0 based) to the end, then if the substring has a length less than 2 it's making the length equal to 2 by adding 0 to the left side.
A: PadLeft ensures that you receive at least two characters from the input, padding the input (on the left side) with the appropriate character. So input, in this case, might be 12. You get "12" back. Or input might be 9, in which case, you get "09" back.
This is an example of complex chaining (see "Is there any benefit in Chaining" post) gone awry, and making code appear overly complex.
A: The substring returns the value with the first two characters skipped, the padleft pads the result with leading zeros:
string s = "2014";
MessageBox.Show(s.Substring(2).PadLeft(2, 'x')); //14
string s2 = "14";
MessageBox.Show(s2.Substring(2).PadLeft(2, 'x')); //xx
My guess is the code is trying to convert the year to a 2 digit value.
A: The PadLeft only does something if the user enters a year that is either 2 or 3 digits long.
With a 1-digit year, you get an exception (Subsring errs).
With a 2-digit year (07, 08, etc), it will return 00. I would say this is an error.
With a 3-digit year (207, 208), which the author may have assumed to be typos, it would return the last digit padded with a zero -- 207 -> 07; 208 -> 08.
As long as the user must choose a year and isn't allowed to enter a year, the PadLeft is unnecessary -- the Substring(2) does exactly what you need given a 4-digit year.
A: This code seems to be trying to grab a 2 digit year from a four digit year (ddlexpyear is the hint)
It takes strings and returns strings, so I will eschew the string delimiters:
*
*1998 -> 98
*2000 -> 00
*2001 -> 01
*2012 -> 12
Problem is that it doesn't do a good job. In these cases, the padding doesn't actually help. Removing the pad code does not affect the cases it gets correct.
So the code works (with or without the pad) for 4 digit years, what does it do for strings of other lengths?
*
*null: exception
*0: exception
*1: exception
*2: always returns "00". e.g. the year 49 (when the Jews were expulsed from rome) becomes "00". This is bad.
*3: saves the last digit, and puts a "0" in front of it. Correct in 10% of cases (when the second digit is actually a zero, like 304, or 908), but quite wrong in the remainder (like 915, 423, and 110)
*5: just saves the 3rd and 4th digits, which is also wrong, "10549" should probably be "49" but is instead "54".
*as you can expect the problem continues in higher digits.
A: OK so it's taking the value from the drop down, ABCD
Then it takes the substring from position 2, CD
And then it err, left pads it with 2 zeros if it needs too, CD
Or, if you've just ended X, then it would substring to X and pad to OX
A: It's taking the last two digits of the year, then pad to the left with a "0".
So 2010 would be 10, 2009 would be 09.
Not sure why the developer didn't just set the value on the dropdown to the last two digits, or why you would need to left pad it (unless you were dealing with years 0-9 AD).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write a self reproducing code (prints the source on exec)? I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source.
some solutions --
http://www.cprogramming.com/challenges/solutions/self_print.html
Quine Page solution in many languages
There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...
A: There are a couple of different strategies to writing quines. The obvious one is to just write code that opens the code and prints it out. But the more interesting ones involve language features that allow for self-embedding, like the %s-style printf feature in many languages. You have to figure out how to embed something so that it ends up resolving to the request to be embedded. I suspect, like palindromes, a lot of trial and error is involved.
A: Aside from cheating¹ there is no difference between compiled and interpreted languages.
The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something:
print ...
However, what should it print? Itself. So it needs to print the "print" command:
print "print ..."
What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too:
print "print \"print ...\""
Now the program grew again, so there's again more to print:
print "print \"print \\\"...\\\"\""
And so on.
With every added code there's more code to print.
This approach is getting nowhere,
but it reveals an interesting pattern:
The string "print \"" is repeated over and over again.
It would be nice to put the repeating part
into a variable:
a = "print \""
print a
However, the program just changed,
so we need to adjust a:
a = "a = ...\nprint a"
print a
When we now try to fill in the "...",
we run into the same problems as before.
Ultimately, we want to write something like this:
a = "a = " + (quoted contents of a) + "\nprint a"
print a
But that is not possible,
because even if we had such a function quoted() for quoting,
there's still the problem that we define a in terms of itself:
a = "a = " + quoted(a) + "\nprint a"
print a
So the only thing we can do is putting a place holder into a:
a = "a = @\nprint a"
print a
And that's the whole trick!
Anything else is now clear.
Simply replace the place holder
with the quoted contents of a:
a = "a = @\nprint a"
print a.replace("@", quoted(a))
Since we have changed the code,
we need to adjust the string:
a = "a = @\nprint a.replace(\"@\", quoted(a))"
print a.replace("@", quoted(a))
And that's it!
All quines in all languages work that way
(except the cheating ones).
Well, you should ensure that you replace only
the first occurence of the place holder.
And if you use a second place holder,
you can avoid needing to quote the string.
But those are minor issues
and easy to solve.
If fact, the realization of quoted() and replace()
are the only details in which the various quines really differ.
¹ by making the program read its source file
A: The usual approach (when you can't cheat*) is to write something that encodes its source in a string constant, then prints out that constant twice: Once as a string literal, and once as code. That gets around the "every time I write a line of code, I have to write another to print it out!" problem.
'Cheating' includes:
- Using an interpreted language and simply loading the source and printing it
- 0-byte long files, which are valid in some languages, such as C.
A: For fun, I came up with one in Scheme, which I was pretty proud of for about 5 minutes until I discovered has been discovered before. Anyways, there's a slight modification to the "rules" of the game to better count for the duality of data and code in Lisp: instead of printing out the source of the program, it's an S-expression that returns itself:
((lambda (x) (list x `',x)) '(lambda (x) (list x `',x)))
The one on Wikipedia has the same concept, but with a slightly different (more verbose) mechanism for quoting. I like mine better though.
A: One idea to think about encoding and how to give something a double meaning so that it can be used to output something in a couple of forms. There is also the cavaet that this type of problem comes with restrictions to make it harder as without any rules other than the program output itself, the empty program is a solution.
A: How about actually reading and printing your source code? Its not difficult at all!! Heres one in php:
<?php
{
header("Content-Type: text/plain");
$f=fopen("5.php","r");
while(!feof($f))
{
echo fgetc($f);
}
fclose($f);
}
?>
A: In python, you can write:
s='c=chr(39);print"s="+c+s+c+";"+s';c=chr(39);print"s="+c+s+c+";"+s
inspired from this self printing pseudo-code:
Print the following line twice, the second time with quotes.
"Print the following line twice, the second time with quotes."
A: I've done a AS3 example for those interested in this
var program = "var program = @; function main(){trace(program.replace('@',
String.fromCharCode(34) + program + String.fromCharCode(34)))} main()";
function main(){
trace(program.replace('@', String.fromCharCode(34) + program + String.fromCharCode(34)))
}
main()
A: In ruby:
puts File.read(_ _ FILE _ _)
A: In bash it is really easy
touch test; chmod oug+x test; ./test
Empty file, Empty output
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC? How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC?
I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on.
The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class.
I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either.
Does anyone have a sample of how to get this to work?
A: What's "not working" with the CCommandBar for you? You should be able to add a CCommandBar member to your dialog class, then in teh DIalog's InitDialog you call Create and InsertMenuBar on the command bar - something like this:
m_cmdBar.Create(this);
m_cmdBar.InsertMenuBar(IDR_MENU_RESRC_ID);
Your menu resource might look something like this:
IDR_MENU_RESRC_ID MENU DISCARDABLE
BEGIN
MENUITEM "OK", IDOK
MENUITEM "Cancel", IDCANCEL
END
A: thank you so much... I was going crazy with this...
your code worked exactly as expected...
At first I used it and had the same results, the softkey area would be blank except for the SIP input button.
After an hour or so of debugging I tried putting those 2 lines of code at the END of my OnInitDIalog() and it worked :)
My problem ende dup being that in my OnIitDialog() I am creating some child dialogs. when I put the CCommandBar.InsertMenuBar() before I create child dialogs I do not get my "ok" or "Cancel" soft keys, when I put that line after the creation of child dialogs the softkeys show as expected and work great.
Thanks again
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best practices for configuring Apache / Tomcat We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using mod_proxy_jk as the connector.
Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant). Both Apache and Tomcat are running on separate machines and have copious amounts of ram (4gb each).
Relevant server.xml portions:
<Connector port="8009"
address="${jboss.bind.address}"
protocol="AJP/1.3"
emptySessionPath="true"
enableLookups="false"
redirectPort="8443"
maxThreads="320"
connectionTimeout="45000"
/>
Relevant httpd.conf portions:
<IfModule prefork.c>
StartServers 8
MinSpareServers 5
MaxSpareServers 20
ServerLimit 256
MaxClients 256
MaxRequestsPerChild 0
</IfModule>
A: You should consider the workload the servers might get.
The most important factor might be the number of simultaneously connected clients at peak times. Try to determine it and tune your settings in a way where:
*
*there are enough processing threads in both Apache and Tomcat that they don't need to spawn new threads when the server is heavily loaded
*there are not way more processing threads in the servers than needed as they would waste resources.
With this kind of setup you can minimize the internal maintenance overhead of the servers, that could help a lot, especially when your load is sporadic.
For example consider an application where you have ~300 new requests/second. Each request requires on average 2.5 seconds to serve. It means that at any given time you have ~750 requests that need to be handled simultaneously. In this situation you probably want to tune your servers so that they have ~750 processing threads at startup and you might want to add something like ~1000 processing threads at maximum to handle extremely high loads.
Also consider for exactly what do you require a thread for. In the previous example each request was independent from the others, there was no session tracking used. In a more "web-ish" scenario you might have users logged in to your website, and depending on your software used, Apache and/or Tomcat might need to use the same thread to serve the requests that come in one session. In this case, you might need more threads. However as I know Tomcat at least, you won't really need to consider this as it works with thread pools internally anyways.
A: MaxClients
This is the fundamental cap of parallel client connections your apache should handle at once.
With prefork, only one request can be handled per process. Therefore the whole apache can process at most $MaxClients requests in the time it takes to handle a single request. Of course, this ideal maximum can only be reached if the application needs less than 1/$MaxClients resources per request.
If, for example, the application takes a second of cpu-time to answer a single request, setting MaxClients to four will limit your throughput to four requests per second: Each request uses up an apache connection and apache will only handle four at a time. But if the server has only two CPUs, not even this can be reached, because every wall-clock second only has two cpu seconds, but the requests would need four cpu seconds.
MinSpareServers
This tells apache how many idle processes should hang around. The bigger this number the more burst load apache can swallow before needing to spawn extra processes, which is expensive and thus slows down the current request.
The correct setting of this depends on your workload. If you have pages with many sub-requests (pictures, iframes, javascript, css) then hitting a single page might use up many more processes for a short time.
MaxSpareServers
Having too many unused apache processes hanging around just wastes memory, thus apache uses the MaxSpareServers number to limit the amount of spare processes it is holding in reserve for bursts of requests.
MaxRequestsPerChild
This limits the number of requests a single process will handle throughout its lifetime. If you are very concerned about stability, you should put an actual limit here to continually recycle the apache processes to prevent resource leaks from affecting the system.
StartServers
This is just the amount of processes apache starts by default. Set this to the usual amount of running apache processes to reduce warm-up time of your system. Even if you ignore this setting, apache will use the Min-/MaxSpareServers values to spawn new processes as required.
More information
See also the documentation for apache's multi-processing modules.
A: The default settings are generally decent starting points to see what your applications is really going to need. I don't know how much traffic you're expecting, so guessing at the MaxThreads, MaxClients, and MaxServers is a bit difficult. I can tell you that most of the customers I deal with (work for a linux web host, that deals mainly with customers running Java apps in Tomcat) use the default settings for quite some time without too many tweaks needed.
If you're not expecting much traffic, then these settings being "too high" really shouldn't effect you too much either. Apache's not going to allocate resources for the whole 256 potential clients unless it becomes necessary. The same goes for Tomcat as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: .NET String.Format() to add commas in thousands place for a number I want to add a comma in the thousands place for a number.
Would String.Format() be the correct path to take? What format would I use?
A: Standard formats, with their related outputs,
Console.WriteLine("Standard Numeric Format Specifiers");
String s = String.Format("(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
- 1234, -1234.565F);
Console.WriteLine(s);
Example output (en-us culture):
(C) Currency: . . . . . . . . ($1,234.00)
(D) Decimal:. . . . . . . . . -1234
(E) Scientific: . . . . . . . -1.234565E+003
(F) Fixed point:. . . . . . . -1234.57
(G) General:. . . . . . . . . -1234
(default):. . . . . . . . -1234 (default = 'G')
(N) Number: . . . . . . . . . -1,234.00
(P) Percent:. . . . . . . . . -123,456.50 %
(R) Round-trip: . . . . . . . -1234.565
(X) Hexadecimal:. . . . . . . FFFFFB2E
A: Note that the value that you're formatting should be numeric.
It doesn't look like it will take a string representation of a number and format is with commas.
A: String.Format("0,###.###"); also works with decimal places
A: This is the best format. Works in all of those cases:
String.Format( "{0:#,##0.##}", 0 ); // 0
String.Format( "{0:#,##0.##}", 0.5 ); // 0.5 - some of the formats above fail here.
String.Format( "{0:#,##0.##}", 12314 ); // 12,314
String.Format( "{0:#,##0.##}", 12314.23123 ); // 12,314.23
String.Format( "{0:#,##0.##}", 12314.2 ); // 12,314.2
String.Format( "{0:#,##0.##}", 1231412314.2 ); // 1,231,412,314.2
A: The most voted answer was great and has been helpful for about 7 years. With the introduction of C# 6.0 and specifically the String Interpolation there's a neater and, IMO safer, way to do what has been asked to add commas in thousands place for a number:
var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal
Where the variable i is put in place of the placeholder (i.e. {0}). So there's no need to remember which object goes to which position. The formatting (i.e. :n) hasn't changed. For a complete feature of what's new, you may go to this page.
A: I found this to be the simplest way:
myInteger.ToString("N0")
A: just simple as this:
float num = 23658; // for example
num = num.ToString("N0"); // Returns 23,658
more info is in Here
A: String.Format("{0:#,###,###.##}", MyNumber)
That will give you commas at the relevant points.
A: You can use a function such as this to format numbers and optionally pass in the desired decimal places. If decimal places are not specified it will use two decimal places.
public static string formatNumber(decimal valueIn=0, int decimalPlaces=2)
{
return string.Format("{0:n" + decimalPlaces.ToString() + "}", valueIn);
}
I use decimal but you can change the type to any other or use an anonymous object. You could also add error checking for negative decimal place values.
A: You want same Format value and culture specific.
Double value= 1234567;
value.ToString("#,#.##", CultureInfo.CreateSpecificCulture("hi-IN"));
Output: 12,34,567
A: The following example displays several values that are formatted by using custom format strings that include zero placeholders.
String.Format("{0:N1}", 29255.0);
Or
29255.0.ToString("N1")
result "29,255.0"
String.Format("{0:N2}", 29255.0);
Or
29255.0.ToString("N2")
result "29,255.00"
A: If you wish to force a "," separator regardless of culture (for example in a trace or log message), the following code will work and has the added benefit of telling the next guy who stumbles across it exactly what you are doing.
int integerValue = 19400320;
string formatted = string.Format(CultureInfo.InvariantCulture, "{0:N0}", integerValue);
sets formatted to "19,400,320"
A: C# 7.1 (perhaps earlier?) makes this as easy and nice-looking as it should be, with string interpolation:
var jackpot = 1_000_000; // underscore separators in numeric literals also available since C# 7.0
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";
A: int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000
A: $"{1234:n}"; // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876
A: Simpler, using string interpolation instead of String.Format
$"{12456:n0}"; // 12,456
$"{12456:n2}"; // 12,456.00
or using yourVariable
double yourVariable = 12456.0;
$"{yourVariable:n0}";
$"{yourVariable:n2}";
A: If you want culture specific, you might want to try this:
use namespace:"using System.Globalization;"
(19950000.0).ToString("N",new CultureInfo("en-US")) = 19,950,000.00
(19950000.0).ToString("N",new CultureInfo("is-IS")) = 19.950.000,00
Indian culture:
(19950000.0).ToString("N",new CultureInfo("hi-IN"))= 1,99,50,000.00
Note: Some cultures use , to mean decimal rather than . so be careful.
A: int num = 98765432;
Console.WriteLine(string.Format("{0:#,#}", num));
A: For example String.Format("{0:0,0}", 1); returns 01, for me is not valid
This works for me
19950000.ToString("#,#", CultureInfo.InvariantCulture));
output
19,950,000
A: I tried many of the suggestions above but the below work better for me:
string.Format("{0:##,###.00}", myValue)
but this fails when you have values like 0.2014 where it gives .21 For this I use
string.Format("{0:#,##0.00}", myValue)
A: Try this:
var number = 123456789;
var str = number.ToString("N0");
Result is: "123,456,789"
A: The method I used to not worry anymore about cultures and potential formatting issues is that I formatted it as currency and took out the currency symbol afterwards.
if (decimal.TryParse(tblCell, out result))
{
formattedValue = result.ToString("C").Substring(1);
}
A: If you want to show it in DataGridview , you should change its type , because default is String and since you change it to decimal it considers as Number with floating point
Dim dt As DataTable = New DataTable
dt.Columns.Add("col1", GetType(Decimal))
dt.Rows.Add(1)
dt.Rows.Add(10)
dt.Rows.Add(2)
DataGridView1.DataSource = dt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1003"
}
|
Q: Detecting when ChucK child shred has finished Is it possible to determine when a ChucK child shred has finished executing if you have a reference to the child shred? For example, in this code:
// define function go()
fun void go()
{
// insert code
}
// spork another, store reference to new shred in offspring
spork ~ go() => Shred @ offspring;
Is it possible to determine when offspring is done executing?
A: I'd say so, let me quote from the "VERSIONS" file from the latest release;
- (added) int Shred.done() // is the shred done?
int Shred.running() // is the shred running?
I'm not 100% sure what "running" is supposed to refer to (perhaps I misunderstand it?) but "done" seems to suit your needs;
================== 8<================
fun void foo()
{
second => now;
}
spork ~ foo() @=> Shred bar;
<<<bar.done()>>>;
<<<bar.running()>>>; // why is this 0? Bug?
2::second => now;
<<<bar.done()>>>;
<<<bar.running()>>>;
==========8<======================
Please note that calling these on a Shred object with no shred process attached to it will return more or less random numbers which is probably a bug.
---Answer from Kassen on chuck-users mailing list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I restore a dump file from mysqldump? I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.
I tried using MySQL Administrator, but I got the following error:
The selected file was generated by
mysqldump and cannot be restored by
this application.
How do I get this working?
A: If the database you want to restore doesn't already exist, you need to create it first.
On the command-line, if you're in the same directory that contains the dumped file, use these commands (with appropriate substitutions):
C:\> mysql -u root -p
mysql> create database mydb;
mysql> use mydb;
mysql> source db_backup.dump;
A: It should be as simple as running this:
mysql -u <user> -p < db_backup.dump
If the dump is of a single database you may have to add a line at the top of the file:
USE <database-name-here>;
If it was a dump of many databases, the use statements are already in there.
To run these commands, open up a command prompt (in Windows) and cd to the directory where the mysql.exe executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command as I have it above.
A: mysql -u username -p -h localhost DATA-BASE-NAME < data.sql
look here - step 3: this way you dont need the USE statement
A: You cannot use the Restore menu in MySQL Admin if the backup / dump wasn't created from there. It's worth a shot though. If you choose to "ignore errors" with the checkbox for that, it will say it completed successfully, although it clearly exits with only a fraction of rows imported...this is with a dump, mind you.
A: One-liner command to restore the generated SQL from mysqldump
mysql -u <username> -p<password> -e "source <path to sql file>;"
A: When we make a dump file with mysqldump, what it contains is a big SQL script for recreating the databse contents. So we restore it by using starting up MySQL’s command-line client:
mysql -uroot -p
(where root is our admin user name for MySQL), and once connected to the database we need commands to create the database and read the file in to it:
create database new_db;
use new_db;
\. dumpfile.sql
Details will vary according to which options were used when creating the dump file.
A: You simply need to run this:
mysql -p -u[user] [database] < db_backup.dump
If the dump contains multiple databases you should omit the database name:
mysql -p -u[user] < db_backup.dump
To run these commands, open up a command prompt (in Windows) and cd to the directory where the mysql.exe executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command.
A: Assuming you already have the blank database created, you can also restore a database from the command line like this:
mysql databasename < backup.sql
A: Run the command to enter into the DB
# mysql -u root -p
Enter the password for the user Then Create a New DB
mysql> create database MynewDB;
mysql> exit
And make exit.Afetr that.Run this Command
# mysql -u root -p MynewDB < MynewDB.sql
Then enter into the db and type
mysql> show databases;
mysql> use MynewDB;
mysql> show tables;
mysql> exit
Thats it ........ Your dump will be restored from one DB to another DB
Or else there is an Alternate way for dump restore
# mysql -u root -p
Then enter into the db and type
mysql> create database MynewDB;
mysql> show databases;
mysql> use MynewDB;
mysql> source MynewDB.sql;
mysql> show tables;
mysql> exit
A: If you want to view the progress of the dump try this:
pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME
You'll of course need 'pv' installed. This command works only on *nix.
A: I got it to work following these steps…
*
*Open MySQL Administrator and connect to server
*Select "Catalogs" on the left
*Right click in the lower-left box and choose "Create New Schema"
MySQL Administrator http://img204.imageshack.us/img204/7528/adminsx9.th.gif enlarge image
*Name the new schema (example: "dbn")
MySQL New Schema http://img262.imageshack.us/img262/4374/newwa4.th.gif enlarge image
*Open Windows Command Prompt (cmd)
Windows Command Prompt http://img206.imageshack.us/img206/941/startef7.th.gif enlarge image
*Change directory to MySQL installation folder
*Execute command:
mysql -u root -p dbn < C:\dbn_20080912.dump
…where "root" is the name of the user, "dbn" is the database name, and "C:\dbn_20080912.dump" is the path/filename of the mysqldump .dump file
MySQL dump restore command line http://img388.imageshack.us/img388/2489/cmdjx0.th.gif enlarge image
*Enjoy!
A: As a specific example of a previous answer:
I needed to restore a backup so I could import/migrate it into SQL Server. I installed MySql only, but did not register it as a service or add it to my path as I don't have the need to keep it running.
I used windows explorer to put my dump file in C:\code\dump.sql. Then opened MySql from the start menu item. Created the DB, then ran the source command with the full path like so:
mysql> create database temp
mysql> use temp
mysql> source c:\code\dump.sql
A: You can try SQLyog 'Execute SQL script' tool to import sql/dump files.
A: Using a 200MB dump file created on Linux to restore on Windows w/ mysql 5.5 , I had more success with the
source file.sql
approach from the mysql prompt than with the
mysql < file.sql
approach on the command line, that caused some Error 2006 "server has gone away" (on windows)
Weirdly, the service created during (mysql) install refers to a my.ini file that did not exist. I copied the "large" example file to my.ini
which I already had modified with the advised increases.
My values are
[mysqld]
max_allowed_packet = 64M
interactive_timeout = 250
wait_timeout = 250
A: ./mysql -u <username> -p <password> -h <host-name like localhost> <database-name> < db_dump-file
A: You can also use the restore menu in MySQL Administrator. You just have to open the back-up file, and then click the restore button.
A: If you are already inside mysql prompt and assume your dump file dump.sql, then we can also use command as below to restore the dump
mysql> \. dump.sql
If your dump size is larger set max_allowed_packet value to higher. Setting this value will help you to faster restoring of dump.
A: How to Restore MySQL Database with MySQLWorkbench
You can run the drop and create commands in a query tab.
Drop the Schema if it Currently Exists
DROP DATABASE `your_db_name`;
Create a New Schema
CREATE SCHEMA `your_db_name`;
Open Your Dump File
*
*Click the Open an SQL script in a new query tab icon and choose your db dump file.
*Then Click Run SQL Script...
*It will then let you preview the first lines of the SQL dump script.
*You will then choose the Default Schema Name
*Next choose the Default Character Set utf8 is normally a safe bet, but you may be able to discern it from looking at the preview lines for something like character_set.
*Click Run
*Be patient for large DB restore scripts and watch as your drive space melts away!
A: Local mysql:
mysql -u root --password=YOUR_PASS --database=YOUR_DB < ./dump.sql
And if you use docker:
docker exec -i DOCKER_NAME mysql -u root --password=YOUR_PASS --database=YOUR_DB < ./dump.sql
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "643"
}
|
Q: Why won't an Ajax Script Work Locally? I've an issue with the same piece of code running fine on my live website but not on my local development server.
I've an Ajax function that updates a div. The following code works on the live site:
self.xmlHttpReq.open("POST", PageURL, true);
self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length);
//..update div stuff...
self.xmlHttpReq.send(QueryString);
When I try to run this on my local machine, nothing is passed to the QueryString.
However, to confuse matters, the following code does work locally:
self.xmlHttpReq.open("POST", PageURL+"?"+QueryString, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
//..div update stuff..
self.xmlHttpReq.send(QueryString);
But, I can't use the code that works on my local machine as it doesn't work on the live server (they've changed their policy on querystrings for security reasons)!
I can alert the Querystring out so I know it's passed into the function on my local machine. The only thing I can think of is that it's a hardware/update issue.
Live Site is running IIS 6 (on a WIN 2003 box I think)
Local Site is running IIS 5.1 (On XP Pro)
Are there some updates or something I'm missing or something?
A: Is there a reason you're explicitly setting the Content-Length header in the first example? You... shouldn't need to do this, and i wouldn't be surprised to find it causing problems.
Oh, and check your encoding routine. The rules are not quite the same for querystrings and POSTed form data.
A: I would guess that Shog9 is right, and that IIS 6 i smart enough to ignore your request and send the correct headers, while 5.2 throws an error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the ultimate program to make a drawing of a database model? One of the first things I do when I'm on a new project is design a database model. To visualize the model I use a 7 year old version of Smartdraw. Maybe it's time for something new. What is the ultimate program to make a drawing of a database model. Smartdraw is for Windows only. Is there something that can be used on unix as well?
A: Your brain is the best drawing tool.
I prefer to develop a database schema in a simple text file.
At first it contains just the table names, attributes and foreign keys:
company:
company_name
...
employee:
name
age
company_name -> company
...
...:
The syntax is not important.
It just needs to be clearly arranged and easy to change.
Later I add types and CHECK() constraints,
so the text file gradually transforms into valid SQL code.
Using a drawing tool in that early stage is just distracting,
because it encourages to waste your time with moving reactangles.
Instead, let your brain build a picture of the schema
in the same way it creates fantasy pictures while reading a book.
As the schema grows,
it becomes necessary to support the brain by creating an overview.
Here, however, pencil and paper are faster than any drawing software.
Also note that there is no need to clutter an overview with unimportant details.
Just sketch the table names and the most important relationships (foreign keys).
Any further details will decrease the value of this overview.
However, if you really feel more comfortable with extremely detailed graphics than with text files and overview graphics, you might want to try
DBDesigner4
or
WWW SQL Designer.
A: I'm happy using Sybase PowerDesigner for years now.
A: Did you take a look at Visio 2007 SQL Server Add-In?
You can find it here: http://dbalink.wordpress.com/2008/04/24/microsoft-office-visio-2007-professional-sql-server-add-in/
A: WWW SQL Designer is one of the best that I've seen, which is pretty amazing since it is all javascript. It can also import and export xml and sql code of everything you draw. And they've added nifty bezier curves since I last used it.
A: The best tool is pencil and paper.
Perhaps not the answer you are looking for, but sometimes the most simple solution is the best. :-)
A: I don't know if it's the "ultimate" program for drawing database models, but I use Visio. Unfortunately, it only runs in Windows.
On the upside, I can create my own shapes, or modify existing ones, and save them in collections called stencils. I can also make my shapes "smart" by programming them to do various things when I double click on them.
A: I use a whiteboard and a camera as well. I second the pencil and paper. I keep a pen(cil) and pad of paper with me almost always because I am forever designing something in my head and need to jot it down. I like Visio as well but my favorite software program to use has always been ERWin. The price of that thing is just way out line, but it is great.
A: I like ERWin. Not Cheap, but it can reverse engineer or do initial design + generate CRUD and manipulate db structure. Viso is pretty good for this too, but its not as complete and of course as strong MS SQL leanings is capabilities.
A: I used to use Visio, but if your database server is MySQL, try MySQL Workbench. It has a linux version as well as a win32 version. Like their other GUI products it has its fair share of quirks, but it works quite well and has the ability to create a diagram of a schema and a schema from a diagram.
I also agree that a pencil and paper, or whiteboard and camera is a great way to sketch things out, but I do like the GUI tools for putting down an idea which is a bit more well formed or complicated.
A: I like to use the open-source mind-mapping program Freemind. It's similar to designing with pencil and paper in that there's not a lot of surface complexity to interrupt the design process.
But it has two huge advantages over paper/pencil:
*
*node folding
*easy drag-and-drop re-arranging
It is very easy to navigate the interface without using the mouse within about five minutes. You can add as many or as few details as you like and can always fold up the details to de-clutter your view. Here's a sample screenshot:
The circles at the ends of the Departments, Employees, and Hours tables indicate that there are more nodes that are folded up. You can go crazy with different fonts, background colors, and even HTML formatting. I just did a [Ctrl]-[B] to make my table names Bold.
FreeMind--and mind-mapping software in general--provides its biggest benefit by staying out of the way of the creative process. It's the first tool I turn to when starting a new project from scratch.
NOTE: I've only ever used the program on Windows, but it is available on Linux.
A: A whiteboard (and camera to take a picture afterwards)
A: DIA is not bad, and there are tools to actually generate some code from some types of models. If you are using PostgreSQL, there is even a tool for going the other way, pg-autodoc.
DIA is available for Unix, and I believe Windows as well.
A: I used to use Viso but now, as I'm more Mac based I use Omnigraffle.
I do have to admit though, as andyUK does, I do a rough sketch on paper.
It also depends on what Database you're using. If it's MySQL then there are quite a few visual development tools available, just have a google
A: There may be more technical programs, but I use SmartDraw. I would also like to note that 'ultimate' is up to your circumstances. Find what works best for you or you and your company. What works for you is the 'ultimate'.
A: Brainstorm/sketch the database on paper/whiteboard first, and then go with a diagram tool.
Which tool depends on your target database. We use SQL Server and thus the designer in SQL Server Management Studio works great for us, since we create the database itself at the same time.
A: For linux I use umbrello
A: If you're looking for a cheap solution/tool without any reverse/forward engineering capabilities, MS Visio might be your best bet. However, if you're planning to invest some money toward ERD tool, spend it on ER/Studio.
I used to use and be champion of ERWIN. As soon as I started to use ER/Studio, I became fan of it. I'm an enterprise data architect at one of the Fortune 100 company and I don't know how to get my work done without it.
PS: I don't have no affiliations with any of those products and companies.
A: OpenOffice has a vector drawing tool, and Inkscape is a another good one.
Otherwise, you can use Graphviz (dot language) to generate such diagram out of a textual description.
There are also some tools to generate such diagram out of an existing database (I first thought it was what you were asking).
A: If you don't need much take Dia.
A: I used Power Designer. It's powerful but rather complex.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: good postgresql client for windows? coming back to postgresql after several years of oracle ...
what are the state-of-the art postgresql administrative/ddl generating/data inserting frontends on windows? it would be nice if it had integration for postgis as well. it should be standalone or alternatively a plugin for intellij idea
thinking back, all the windows programs specific for postgresql i have used were crap, especially PGAdmin. had it become better?
A: Actually there is a freeware version of EMS's SQL Manager which is quite powerful
A: I recommend Navicat strongly. What I found particularly excellent are it's import functions - you can import almost any data format (Access, Excel, DBF, Lotus ...), define a mapping between the source and destination which can be saved and is repeatable (I even keep my mappings under version control).
I have tried SQLMaestro and found it buggy (particularly for data import); PGAdmin is limited.
A: For anyone looking for a web-enabled client for Postgres, I'll just put the link out here to TeamPostgreSQL, a very polished AJAX web client for pg:
http://www.teampostgresql.com
A: EMS's SQL Manager is much easier to use and has many more features than either phpPgAdmin or PG Admin III. However, it's windows only and you have to pay for it.
A: do you mean something like pgAdmin for administration?
A: I like Postgresql Maestro. I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.
A: I heartily recommended dbVis. The client runs on Mac, Windows and Linux and supports a variety of database servers, including PostgreSQL.
A: SQLExplorer is a great Eclipse plugin or standalone interface that works with many different database systems, either with dedicated drivers or with ODBC.
A: phpPgAdmin is PostgreSQL web frontend which is quite good.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "84"
}
|
Q: How do I get a string type of a hex value that represents an upper ascii value character Part of our app parses RTF documents and we've come across a special character that is not translating well. When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85).
In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...)
Here's the code in C# - problem is this doesn't work for values above 127. Any ideas?
Calling code :
// S is Hex number!!!
return Convert.ToChar(HexStringToInt(s)).ToString();
Helper method:
private static int HexStringToInt(string hexString)
{
int i;
try
{
i = Int32.Parse(hexString, NumberStyles.HexNumber);
}
catch (Exception ex)
{
throw new ApplicationException("Error trying to convert hex value: " + hexString, ex);
}
return i;
}
A: This looks like a character encoding issue to me. Unicode doesn't include any characters with numbers in the upper-ASCII 128-255 range, so trying to convert character 133 will fail.
Need to convert it first to a character using the proper decoding, Convert.toChar appears to be using UTF-16.
Sometimes there's a manual bit manipulation hack to convert the character from upper ASCII to the appropriate unicode char, but since the ellipsis wasn't in most of the widely used extended ASCII codepages, that's unlikely to work here.
What you really want to do is use the Encoding.GetString(Byte[]) method, with the proper encoding. Put your value into a byte array, then GetString to get the C# native string for the character.
You can learn more about RTF character encodings on the RTF Wikipedia page.
FYI: The horizontal ellipsis is character U+2026 (pdf).
A: Your original code works prefectly fine for me. It is able to convert any Hex from 00 to FF into the appropriate character. Using vs2008.
A: private static int HexStringToInt(string hexString)
{
try
{
return Convert.ToChar(hexString);
}
catch (FormatException ex)
{
throw new ArgumentException("Is not a valid hex character.", "hexString", ex);
}
// Convert.ToChar() will throw an ArgumentException also
// if hexString is bad
}
A: My guess would be that a Char in .NET is actually two bytes (16 bits), as they are UTF-16 encoded. Maybe you are only catching/writing the first byte of the value?
Basically, are you doing something with the char value afterwards that assumes it is 8-bits instead of 16, and is therefore truncating it?
A: You are probably using the default character encoding when reading in the RTF file, which is UTF-8, when the RTF file is actually stored using the "windows-1252" extended ASCII latin encoding.
C# strings use a 16 unicode bit wide character format. Translating windows-1252 character 0x85 to its unicode equivalent involves a complicated mapping, since the the code points (character numbers) are very different. Luckily Windows can do the work for you.
You can change the way the characters are converted when reading in the text by explicitly specifying the source encoding when opening the stream.
using System.IO;
using System.Text.Encoding;
using (TextReader tr = new StreamReader(path_to_RTF_file, Encoding.GetEncoding(1252)))
{
// Read from the file as usual.
}
A: Here's some rough code that should work for you:
// Convert hex number, which represents an RTF code-page escaped character,
// to the desired character (uses '85' from your example as a literal):
var number = int.Parse("85", System.Globalization.NumberStyles.HexNumber);
Debug.Assert(number <= byte.MaxValue);
byte[] bytes = new byte[1] { (byte)number };
char[] chars = Encoding.GetEncoding(1252).GetString(bytes).ToCharArray();
// or, use:
// char[] chars = Encoding.Default.GetString(bytes).ToCharArray();
string result = new string(chars);
A: Just use this function I modified (very slightly) from Chris' website:
private static string charScrubber(string content)
{
StringBuilder sbTemp = new StringBuilder(content.Length);
foreach (char currentChar in content)
{
if ((currentChar != 127 && currentChar > 1))
{
sbTemp.Append(currentChar);
}
}
content = sbTemp.ToString();
return content;
}
You can modify the "current Char" condition to remove whatever character is needed to be eliminated (as appearing here, you will not get any 0x00 characters, or the (char)127, or 0x57 character).
ASCII/Hex table here: http://www.cs.mun.ca/~michael/c/ascii-table.html
Chris' site: http://seattlesoftware.wordpress.com/2008/09/11/hexadecimal-value-0-is-an-invalid-character/
-Tom
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I access a char ** through ffi in plt-scheme? I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char ** (array of strings). If I declare my function as (_fun _pointer -> _pointer), how do I convert the result to a list of strings in scheme?
Here are the relevant C-declarations:
typedef char **MYSQL_ROW; /* return data as array of strings */
// ...
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
A: I think that what you want is the cvector:
http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)
A cvector of _string/utf-8 or whichever encoding you need seems reasanable.
But that's from a quick survey of the docs - I haven't tried this myself. Please let me know if it works!
A: I know it's not exactly what you are looking for, but it might help a little bit. I've done some work on a basic Gambit Scheme FFI for MySQL. I don't know how PLT Scheme and Gambit differ in terms of their FFI implementation (I'd venture with "quite a bit") but maybe you can get something out of it:
http://bunny.jonnay.net/zengarden/trunk/lib/mysql/mysql-ffi.scm
A: Aha, I figured it out myself.
I have to use the _cpointer procedure, described at the page that mike linked to:
(_fun _pointer -> (_cpointer/null 'mysql-row (make-ctype _pointer #f #f)))
It also seems that someone already beat me to creating a ffi to mysqlclient. Not to worry; My main goal is understanding the ffi api, and it's going forward.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SEO and hard links with dynamic URLs With ASP.NET MVC (or using HttpHandlers) you can dynamically generate URLs, like the one in this question, which includes the title.
What happens if the title changes (for example, editing it) and there's a link pointing to the page from another site, or Google's Pagerank was calculated for that URL?
I guess it's all lost right? (The link points to nowhere and the pagerank calculated is lost)
If so, is there a way to avoid it?
A: I use the same system as is in place here, everything after the number in the URL is not used in the db query, then I 301 redirect anything else to be the title.
In other words, if the title changed, then it would redirect to the correct place. I do it in PHP rather than htaccess as it's easier to manage more complex ideas.
A: I think you're generally best off having the server send a permanent redirect to the new location, if possible.
That way any rank which is gained from third party links should, in theory, be transferred to the new location. I'm not convinced whether this happens in practice, but it should.
A: Yes, all SEO is lost upon a url change -- it forks to an entirely new record. The way to handle that is to leave a 301 redirect at the old title to the new one, and some search engines (read: Google) is smart enough to pick that up.
EDIT: Fixed to 301 redirect!
A: The way Stackoverflow seems to be implemented everything after the question number is superfluous as far as linking to the question goes. For instance:
SEO and hard links with dynamic URLs
links to this question, despite the fact that I just made up the 'question title' part out of thin air. So the link will not point to nowhere and the PageRank is not lost (though it may be split between the two URLs, depending on whether or not Google can canonicalize them into a single URL).
A: Have your app redirect the old URL via a 301 Redirect. This will tell Google to transfer the pagerank to the new URL.
A: If a document is moved to a different URL, the server should be configured to return a HTTP status code of 301 (Moved Permanently) for the old URL to tell the client where the document has been moved to. With Apache, this is done using mod_rewrite and RewriteRule.
A: The best thing to help Google in this instance is to return a permanent redirect on the old URL to the new one.
I'm not an ASP.NET hacker - so I can't recommend the best way to implement this - but Googling the topic looks fairly productive :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Does the JVM prevent tail call optimizations? I saw this quote on the question: What is a good functional language on which to build a web service?
Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this is a fundamental limitation of the JVM).
Is this true? If so, what is it about the JVM that creates this fundamental limitation?
A: In addition to the paper linked in Lambda The Ultimate (from the link mmyers posted above), John Rose from Sun has some more to say about tail call optimization.
http://blogs.oracle.com/jrose/entry/tail_calls_in_the_vm
I have heard that it might be implemented on the JVM someday. Tail call support amongst other things are being looked at on the Da Vinci Machine.
http://openjdk.java.net/projects/mlvm/
A: This post: Recursion or Iteration? might help.
In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would probably require a new bytecode (see John Rose's informal proposal).
There is also more discussion in Sun bug #4726340, where the evaluation (from 2002) ends:
I believe this could be done nonetheless, but it is not a small task.
Currently, there is some work going on in the Da Vinci Machine project. The tail call subproject's status is listed as "proto 80%"; it is unlikely to make it into Java 7, but I think it has a very good chance at Java 8.
A: The fundamental limitation is simply that the JVM does not provide tail calls in its byte code and, consequently, there is no direct way for a language built upon the JVM to provide tail calls itself. There are workarounds that can achieve a similar effect (e.g. trampolining) but they come at the grave cost of awful performance and obfuscating the generated intermediate code which makes a debugger useless.
So the JVM cannot support any production-quality functional programming languages until Sun implement tail calls in the JVM itself. They have been discussing it for years but I doubt they will ever implement tail calls: it will be very difficult because they have prematurely optimized their VM before implementing such basic functionality, and Sun's effort is strongly focused on dynamic languages rather than functional languages.
Hence there is a very strong argument that Scala is not a real functional programming language: these languages have regarded tail calls as an essential feature since Scheme was first introduced over 30 years ago.
A: Scala 2.7.x supports tail-call optimization for self-recursion (a function calling itself) of final methods and local functions.
Scala 2.8 might come with library support for trampoline too, which is a technique to optimize mutually recursive functions.
A good deal of information about the state of Scala recursion can be found in Rich Dougherty's blog.
A: All sources point to the JVM being unable to optimize in the case of tail recursion, but upon reading Java performance tuning (2003, O'reilly) I found the author claiming he can achieve greater recursion performance by implementing tail recursion.
You can find his claim on page 212 (search for 'tail recursion' it should be the second result). What gives?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "99"
}
|
Q: Perl JOIN-like behavior in Oracle? I have two tables, let's call them PERSON and NAME.
PERSON
person_id
dob
NAME
name_id
person_id
name
And let's say that the NAME table has data like:
name_id person_id name
1 1 Joe
2 1 Fred
3 1 Sam
4 2 Jane
5 2 Kim
I need a query (Oracle 10g) that will return
name_id names
1 Joe, Fred, Sam
2 Jane, Kim
Is there a simple way to do this?
Update:
According to the article that figs was kind enough to provide, starting in 9i you can do:
SELECT wmsys.wm_concat(dname) departments FROM dept;
For this example, the answer becomes:
SELECT name_id, wmsys.wm_concat(name) from names group by name_id
A: The short answer is to use a PL/SQL function. For more details, have a look in this post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Real-world examples of recursion What are real-world problems where a recursive approach is the natural solution besides depth-first search (DFS)?
(I don't consider Tower of Hanoi, Fibonacci number, or factorial real-world problems. They are a bit contrived in my mind.)
A: Disabling/setting read-only for all children controls in a container control. I needed to do this because some of the children controls were containers themselves.
public static void SetReadOnly(Control ctrl, bool readOnly)
{
//set the control read only
SetControlReadOnly(ctrl, readOnly);
if (ctrl.Controls != null && ctrl.Controls.Count > 0)
{
//recursively loop through all child controls
foreach (Control c in ctrl.Controls)
SetReadOnly(c, readOnly);
}
}
A: People often sort stacks of documents using a recursive method. For example, imagine you are sorting 100 documents with names on them. First place documents into piles by the first letter, then sort each pile.
Looking up words in the dictionary is often performed by a binary-search-like technique, which is recursive.
In organizations, bosses often give commands to department heads, who in turn give commands to managers, and so on.
A: Famous Eval/Apply cycle from SICP
(source: mit.edu)
Here is the definition of eval:
(define (eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp) (lookup-variable-value exp env))
((quoted? exp) (text-of-quotation exp))
((assignment? exp) (eval-assignment exp env))
((definition? exp) (eval-definition exp env))
((if? exp) (eval-if exp env))
((lambda? exp)
(make-procedure (lambda-parameters exp)
(lambda-body exp)
env))
((begin? exp)
(eval-sequence (begin-actions exp) env))
((cond? exp) (eval (cond->if exp) env))
((application? exp)
(apply (eval (operator exp) env)
(list-of-values (operands exp) env)))
(else
(error "Unknown expression type - EVAL" exp))))
Here is the definition of apply:
(define (apply procedure arguments)
(cond ((primitive-procedure? procedure)
(apply-primitive-procedure procedure arguments))
((compound-procedure? procedure)
(eval-sequence
(procedure-body procedure)
(extend-environment
(procedure-parameters procedure)
arguments
(procedure-environment procedure))))
(else
(error
"Unknown procedure type - APPLY" procedure))))
Here is the definition of eval-sequence:
(define (eval-sequence exps env)
(cond ((last-exp? exps) (eval (first-exp exps) env))
(else (eval (first-exp exps) env)
(eval-sequence (rest-exps exps) env))))
eval -> apply -> eval-sequence -> eval
A: Recursion is used in things like BSP trees for collision detection in game development (and other similar areas).
A: Real world requirement I got recently:
Requirement A: Implement this feature after thoroughly understanding Requirement A.
A: How about anything involving a directory structure in the file system. Recursively finding files, deleting files, creating directories, etc.
Here is a Java implementation that recursively prints out the content of a directory and its sub-directories.
import java.io.File;
public class DirectoryContentAnalyserOne implements DirectoryContentAnalyser {
private static StringBuilder indentation = new StringBuilder();
public static void main (String args [] ){
// Here you pass the path to the directory to be scanned
getDirectoryContent("C:\\DirOne\\DirTwo\\AndSoOn");
}
private static void getDirectoryContent(String filePath) {
File currentDirOrFile = new File(filePath);
if ( !currentDirOrFile.exists() ){
return;
}
else if ( currentDirOrFile.isFile() ){
System.out.println(indentation + currentDirOrFile.getName());
return;
}
else{
System.out.println("\n" + indentation + "|_" +currentDirOrFile.getName());
indentation.append(" ");
for ( String currentFileOrDirName : currentDirOrFile.list()){
getPrivateDirectoryContent(currentDirOrFile + "\\" + currentFileOrDirName);
}
if (indentation.length() - 3 > 3 ){
indentation.delete(indentation.length() - 3, indentation.length());
}
}
}
}
A: There are lots of mathy examples here, but you wanted a real world example, so with a bit of thinking, this is possibly the best I can offer:
You find a person who has contracted a given contageous infection, which is non fatal, and fixes itself quickly( Type A) , Except for one in 5 people ( We'll call these type B ) who become permanently infected with it and shows no symptoms and merely acts a spreader.
This creates quite annoying waves of havoc when ever type B infects a multitude of type A.
Your task is to track down all the type Bs and immunise them to stop the backbone of the disease. Unfortunately tho, you cant administer a nationwide cure to all, because the people who are typeAs are also deadly allergic to the cure that works for type B.
The way you would do this, would be social discovery, given an infected person(Type A), choose all their contacts in the last week, marking each contact on a heap. When you test a person is infected, add them to the "follow up" queue. When a person is a type B, add them to the "follow up" at the head ( because you want to stop this fast ).
After processing a given person, select the person from the front of the queue and apply immunization if needed. Get all their contacts previously unvisited, and then test to see if they're infected.
Repeat until the queue of infected people becomes 0, and then wait for another outbreak..
( Ok, this is a bit iterative, but its an iterative way of solving a recursive problem, in this case, breadth first traversal of a population base trying to discover likely paths to problems, and besides, iterative solutions are often faster and more effective, and I compulsively remove recursion everywhere so much its become instinctive. .... dammit! )
A: Recursion is applied to problems (situations) where you can break it up (reduce it) into smaller parts, and each part(s) looks similar to the original problem.
Good examples of where things that contain smaller parts similar to itself are:
*
*tree structure (a branch is like a tree)
*lists (part of a list is still a list)
*containers (Russian dolls)
*sequences (part of a sequence looks like the next)
*groups of objects (a subgroup is a still a group of objects)
Recursion is a technique to keep breaking the problem down into smaller and smaller pieces, until one of those pieces become small enough to be a piece-of-cake. Of course, after you break them up, you then have to "stitch" the results back together in the right order to form a total solution of your original problem.
Some recursive sorting algorithms, tree-walking algorithms, map/reduce algorithms, divide-and-conquer are all examples of this technique.
In computer programming, most stack-based call-return type languages already have the capabilities built in for recursion: i.e.
*
*break the problem down into smaller pieces ==> call itself on a smaller subset of the original data),
*keep track on how the pieces are divided ==> call stack,
*stitch the results back ==> stack-based return
A: Feedback loops in a hierarchical organization.
Top boss tells top executives to collect feedback from everyone in the company.
Each executive gathers his/her direct reports and tells them to gather feedback from their direct reports.
And on down the line.
People with no direct reports -- the leaf nodes in the tree -- give their feedback.
The feedback travels back up the tree with each manager adding his/her own feedback.
Eventually all the feedback makes it back up to the top boss.
This is the natural solution because the recursive method allows filtering at each level -- the collating of duplicates and the removal of offensive feedback. The top boss could send a global email and have each employee report feedback directly back to him/her, but there are the "you can't handle the truth" and the "you're fired" problems, so recursion works best here.
A: Quicksort, merge sort, and most other N-log N sorts.
A: Parsers and compilers may be written in a recursive-descent method. Not the best way to do it, as tools like lex/yacc generate faster and more efficient parsers, but conceptually simple and easy to implement, so they remain common.
A: I have a system that uses pure tail recursion in a few places to simulate a state machine.
A: Some great examples of recursion are found in functional programming languages. In functional programming languages (Erlang, Haskell, ML/OCaml/F#, etc.), it's very common to have any list processing use recursion.
When dealing with lists in typical imperative OOP-style languages, it's very common to see lists implemented as linked lists ([item1 -> item2 -> item3 -> item4]). However, in some functional programming languages, you find that lists themselves are implemented recursively, where the "head" of the list points to the first item in the list, and the "tail" points to a list containing the rest of the items ([item1 -> [item2 -> [item3 -> [item4 -> []]]]]). It's pretty creative in my opinion.
This handling of lists, when combined with pattern matching, is VERY powerful. Let's say I want to sum a list of numbers:
let rec Sum numbers =
match numbers with
| [] -> 0
| head::tail -> head + Sum tail
This essentially says "if we were called with an empty list, return 0" (allowing us to break the recursion), else return the value of head + the value of Sum called with the remaining items (hence, our recursion).
For example, I might have a list of URLs, I think break apart all the URLs each URL links to, and then I reduce the total number of links to/from all URLs to generate "values" for a page (an approach that Google takes with PageRank and that you can find defined in the original MapReduce paper). You can do this to generate word counts in a document also. And many, many, many other things as well.
You can extend this functional pattern to any type of MapReduce code where you can taking a list of something, transforming it, and returning something else (whether another list, or some zip command on the list).
A: XML, or traversing anything that is a tree. Although, to be honest, I pretty much never use recursion in my job.
A: A "real-world" problem solved by recursion would be nesting dolls. Your function is OpenDoll().
Given a stack of them, you would recursilvey open the dolls, calling OpenDoll() if you will, until you've reached the inner-most doll.
A: *
*Parsing an XML file.
*Efficient search in multi-dimensional spaces. E. g. quad-trees in 2D, oct-trees in 3D, kd-trees, etc.
*Hierarchical clustering.
*Come to think of it, traversing any hierarchical structure naturally lends itself to recursion.
*Template metaprogramming in C++, where there are no loops and recursion is the only way.
A: Suppose you are building a CMS for a website, where your pages are in a tree structure, with say the root being the home-page.
Suppose also your {user|client|customer|boss} requests that you place a breadcrumb trail on every page to show where you are in the tree.
For any given page n, you'll may want to walk up to the parent of n, and its parent, and so on, recursively to build a list of nodes back up to the root of page tree.
Of course, you're hitting the db several times per page in that example, so you may want to use some SQL aliasing where you look up page-table as a, and page-table again as b, and join a.id with b.parent so you make the database do the recursive joins. It's been a while, so my syntax is probably not helpful.
Then again, you may just want to only calculate this once and store it with the page record, only updating it if you move the page. That'd probably be more efficient.
Anyway, that's my $.02
A: You have an organization tree that is N levels deep. Several of the nodes are checked, and you want to expand out to only those nodes that have been checked.
This is something that I actually coded.
Its nice and easy with recursion.
A: In my job we have a system with a generic data structure that can be described as a tree. That means that recursion is a very effective technique to work with the data.
Solving it without recursion would require a lot of unnecessary code. The problem with recursion is that it is not easy to follow what happens. You really have to concentrate when following the flow of execution. But when it works the code is elegant and effective.
A: Calculations for finance/physics, such as compound averages.
A: The best example I know is quicksort, it is a lot simpler with recursion. Take a look at:
shop.oreilly.com/product/9780596510046.do
www.amazon.com/Beautiful-Code-Leading-Programmers-Practice/dp/0596510047
(Click on the first subtitle under the chapter 3: "The most beautiful code I ever wrote").
A: Parsing a tree of controls in Windows Forms or WebForms (.NET Windows Forms / ASP.NET).
A: Matt Dillard's example is good. More generally, any walking of a tree can generally be handled by recursion very easily. For instance, compiling parse trees, walking over XML or HTML, etc.
A: Recursion is often used in implementations of the Backtracking algorithm. For a "real-world" application of this, how about a Sudoku solver?
A: Recursion is appropriate whenever a problem can be solved by dividing it into sub-problems, that can use the same algorithm for solving them. Algorithms on trees and sorted lists are a natural fit. Many problems in computational geometry (and 3D games) can be solved recursively using binary space partitioning (BSP) trees, fat subdivisions, or other ways of dividing the world into sub-parts.
Recursion is also appropriate when you are trying to guarantee the correctness of an algorithm. Given a function that takes immutable inputs and returns a result that is a combination of recursive and non-recursive calls on the inputs, it's usually easy to prove the function is correct (or not) using mathematical induction. It's often intractable to do this with an iterative function or with inputs that may mutate. This can be useful when dealing with financial calculations and other applications where correctness is very important.
A: A real world example of recursion
A: Surely that many compilers out there use recursion heavily. Computer languages are inherently recursive themselves (i.e., you can embed 'if' statements inside other 'if' statements, etc.).
A: Phone and cable companies maintain a model of their wiring topology, which in effect is a large network or graph. Recursion is one way to traverse this model when you want to find all parent or all child elements.
Since recursion is expensive from a processing and memory perspective, this step is commonly only performed when the topology is changed and the result is stored in a modified pre-ordered list format.
A: Inductive reasoning, the process of concept-formation, is recursive in nature. Your brain does it all the time, in the real world.
A: Mostly recursion is very natural for dealing with recursive data structures. This basically means list structures, and tree structures. But recursion is also a nice natural way of /creating/ tree structures on the fly in some way, by divide-and-conquer for instance quicksort, or binary search.
I think your question is a bit misguided in one sense. What's not real-world about depth first search? There's a lot you can do with depth-first search.
For instance, another example I thought of giving is recursive descent compilation. It is enough of a real-world problem to have been used in many real-world compilers. But you could argue it is DFS, it is basically a depth-first-search for a valid parse tree.
A: Ditto the comment about compilers. The abstract syntax tree nodes naturally lend themselves to recursion. All recursive data structures (linked lists, trees, graphs, etc.) are also more easily handled with recursion. I do think that most of us don't get to use recursion a lot once we are out of school because of the types of real-world problems, but it's good to be aware of it as an option.
A: Multiplication of natural numbers is a real-world example of recursion:
To multiply x by y
if x is 0
the answer is 0
if x is 1
the answer is y
otherwise
multiply x - 1 by y, and add x
A: Anything program with tree or graph data structures will likely have some recursion.
A: Write a function that translates a number like 12345.67 to "twelve thousand three hundred forty-five dollars and sixty-seven cents."
A: I wrote an XML parser once that would have been much harder to write without recursion.
I suppose you can always use a stack + iteration, but sometimes recursion is just so elegant.
A: Finding the median in average-case O(n). Equivalent to finding the k-th largest item in a list of n things, with k=n/2:
int kthLargest(list, k, first, last) {
j = partition(list, first, last)
if (k == j)
return list[j]
else if (k
Here, partition picks a pivot element, and in one pass through the data, rearranges the list so that items less than the pivot come first, then the pivot, then items bigger than the pivot. The "kthLargest" algorithm is very similar to quicksort, but recurses on only one side of the list.
For me, this is the simplest recursive algorithm that runs faster than an iterative algorithm. It uses 2*n comparisons on average, regardless of k. This is much better than the naive approach of running k passes through the data, finding the minimum each time, and discarding it.
Alejo
A: Everything where you use iteration is done more natural with recursion if it where not for the practical limitation of causing a stack overflow ;-)
But seriously Recursion and Iteration are very interchangeable you can rewrite all algorithm using recursion to use iteration and vise versa.
Mathematicians like recursion and programmers like iteration. That is probably also why you see all these contrived examples you mention.
I think the method of mathematical proof called Mathematical induction has something to do why mathematicians like recursion.
http://en.wikipedia.org/wiki/Mathematical_induction
A: I just wrote a recursive function to figure out if a class needed to be serialized using a DataContractSerializer. The big issue came with templates/generics where a class could contain other types that needed to be datacontract serialized... so it's go through each type, if it's not datacontractserializable check it's types.
A: We use them to do SQL path-finding.
I will also say it's painstaking to debug, and it's very easy for a poor programmer to screw it up.
A: I think that this really depends upon the language. In some languages, Lisp for example, recursion is often the natural response to a problem (and often with languages where this is the case, the compiler is optimized to deal with recursion).
The common pattern in Lisp of performing an operation on the first element of a list and then calling the function on the rest of the list in order to either accumulate a value or a new list is quite elegant and most natural way to do a lot of things in that language. In Java, not so much.
A: I wrote a tree in C# to handle lookups on a table that a 6-segmented key with default cases (if key[0] doesn't exist, use the default case and continue). The lookups were done recursively. I tried a dictionary of dictionaries of dictionaries (etc) and it got way too complex very quickly.
I also wrote a formula evaluator in C# that evaluated equations stored in a tree to get the evaluation order correct. Granted this is likely a case of choosing the incorrect language for the problem but it was an interesting exercise.
I didn't see many examples of what people had done but rather libraries they had used. Hopefully this gives you something to think about.
A: Geometric calculations for GIS or cartography, such as finding the edge of a circle.
A: Methods for finding a square root are recursive. Useful for calculating distances in the real world.
A: Methods for finding prime numbers are recursive. Useful for generating hash keys, for various encryption schemes that use factors of large numbers.
A: You have a building.
The building has 20 rooms.
Legally, you can only have a certain amount of people in each room.
Your job is to automatically assign people to a room. Should I room get full, you need to find an available room.
Given that only certain rooms can hold certain people, you also need to be careful on which room.
For example:
Rooms 1, 2, 3 can roll in to each other. This room is for kids who can't walk on their own, so you want them away from everything else to avoid distraction and other sickness (which isn't a thing to older people, but to a 6mo it can become very bad. Should all three be full, the person must be denied entrance.
Rooms 4, 5, 6 can roll in to each other. This room is for people that are allergic to peanuts and thusly, they can not go in to other rooms (which may have stuff with peanuts). Should all three become full, offer up a warning asking their allergy level and perahsp they can be granted access.
At any given time, rooms can change. So you may allow room 7-14 be no-peanut rooms. You don't know how many rooms to check.
Or, perhaps you want to seperate based on age. Grade, gender, etc.
These are just a couple examples I've come in to.
A: Check if the created image is going to work within a size restricted box.
function check_size($font_size, $font, $text, $width, $height) {
if (!is_string($text)) {
throw new Exception('Invalid type for $text');
}
$box = imagettfbbox($font_size, 0, $font, $text);
$box['width'] = abs($box[2] - $box[0]);
if ($box[0] < -1) {
$box['width'] = abs($box[2]) + abs($box[0]) - 1;
}
$box['height'] = abs($box[7]) - abs($box[1]);
if ($box[3] > 0) {
$box['height'] = abs($box[7] - abs($box[1])) - 1;
}
return ($box['height'] < $height && $box['width'] < $width) ? array($font_size, $box['width'], $height) : $this->check_size($font_size - 1, $font, $text, $width, $height);
}
A: A method to generate a tree structured menu from a database table using subsonic.
public MenuElement(BHSSiteMap node, string role)
{
if (CheckRole(node, role))
{
ParentNode = node;
// get site map collection order by sequence
BHSSiteMapCollection children = new BHSSiteMapCollection();
Query q = BHSSiteMap.CreateQuery()
.WHERE(BHSSiteMap.Columns.Parent, Comparison.Equals, ParentNode.Id)
.ORDER_BY(BHSSiteMap.Columns.Sequence, "ASC");
children.LoadAndCloseReader(q.ExecuteReader());
if (children.Count > 0)
{
ChildNodes = new List<MenuElement>();
foreach (BHSSiteMap child in children)
{
MenuElement childME = new MenuElement(child, role);
ChildNodes.Add(childME);
}
}
}
}
A: The last real world example I have is a pretty frivolous, but it demonstrates how recursion 'just fits' sometimes.
I was using the Chain of Responsibility pattern,so a Handler object either handles a request itself, or delegates it down the chain. It's useful to log the construction of the chain:
public String getChainString() {
cs = this.getClass().toString();
if(this.delegate != null) {
cs += "->" + delegate.getChainString();
}
return cs;
}
You could argue that this isn't the purest recursion, because although the method calls "itself", it is in a different instance each time it's called.
A: Recursion is a very basic programming technique, and it lends itself to so many problems that listing them is like listing all problems that can be solved by using addition of some kind. Just going through my Lisp solutions for Project Euler, I find: a cross total function, a digit matching function, several functions for searching a space, a minimal text parser, a function splitting a number into the list of its decimal digits, a function constructing a graph, and a function traversing an input file.
The problem is that many if not most mainstream programming languages today do not have tail call optimization so that deep recursion is not feasible with them. This inadequacy means that most programmers are forced to unlearn this natural way of thinking and instead rely on other, arguably less elegant looping constructs.
A: If you have two different but similar sequences and want to match the components of each sequence such that large contiguous chunks are favored first followed by identical sequence order, then you can recursively analyze those sequences to form a tree and then recursively process that tree to flatten it.
Reference: Recursion & Memoization Example Code
A: Plug: http://picogen.deviantart.com/gallery/
A: *
*The College Savings Plan: Let A(n) = amount saved for college after n months
A(0) = $500
Each month , $50 is deposited into an account which earns 5% in annual interest.
Then A(n) = A(n-1) + 50 + 0.05*(1/12)* A(N-1)
A: Since you don't seem to like computer science or mathy examples, here is a different one: wire puzzles.
Many wire puzzles involve removing a long closed loop of wire by working it in and out of wire rings. These puzzles are recursive.
One of them is called "arrow dynamics". I am sue you could find it if you google for "arrow dynamics wire puzzle"
These puzzles are a lot like the towers of Hanoi.
A: A real world example of indirect recursion would be asking your parents if you can have that video game for christmas. Dad: "Ask mom."... Mom: "Ask Dad." [In short, "No, but we dont want to tell you that lest you throw a tantrum."]
A: Towers of Hanoi
Here's one you can interact with: http://www.mazeworks.com/hanoi/
Using recurrence relations, the exact number of moves that this solution requires can be calculated by: 2h − 1. This result is obtained by noting that steps 1 and 3 take Th − 1 moves, and step 2 takes one move, giving Th = 2Th − 1 + 1.
See: http://en.wikipedia.org/wiki/Towers_of_hanoi#Recursive_solution
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "113"
}
|
Q: Conditional logging with minimal cyclomatic complexity After reading "What’s your/a good limit for cyclomatic complexity?", I realize many of my colleagues were quite annoyed with this new QA policy on our project: no more 10 cyclomatic complexity per function.
Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in 'Do you test private method?', such a policy has many good side-effects.
But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of 'Aspect-oriented programming' approach for logs).
myLogger.info("A String");
myLogger.fine("A more complicated String");
...
And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the log parameters (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place!
So QA came back and urged our programmers to do conditional logging. Always.
if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String");
if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String");
...
But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity!
So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be really part of said complexity of that function...
How would you address this situation ?
I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first.
Thank you for all the answers.
I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)
So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the obligation to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...)
I now get the 'variadic function' point advanced by some of you (thank you John).
Note: a quick test in java6 shows that my varargs function does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it.
I have now posted my experience on this topic.
I will leave it there until next Tuesday for voting, then I will select one of your answers.
Again, thank you for all the suggestions :)
A: With current logging frameworks, the question is moot
Current logging frameworks like slf4j or log4j 2 don't require guard statements in most cases. They use a parameterized log statement so that an event can be logged unconditionally, but message formatting only occurs if the event is enabled. Message construction is performed as needed by the logger, rather than pre-emptively by the application.
If you have to use an antique logging library, you can read on to get more background and a way to retrofit the old library with parameterized messages.
Are guard statements really adding complexity?
Consider excluding logging guards statements from the cyclomatic complexity calculation.
It could be argued that, due to their predictable form, conditional logging checks really don't contribute to the complexity of the code.
Inflexible metrics can make an otherwise good programmer turn bad. Be careful!
Assuming that your tools for calculating complexity can't be tailored to that degree, the following approach may offer a work-around.
The need for conditional logging
I assume that your guard statements were introduced because you had code like this:
private static final Logger log = Logger.getLogger(MyClass.class);
Connection connect(Widget w, Dongle d, Dongle alt)
throws ConnectionException
{
log.debug("Attempting connection of dongle " + d + " to widget " + w);
Connection c;
try {
c = w.connect(d);
} catch(ConnectionException ex) {
log.warn("Connection failed; attempting alternate dongle " + d, ex);
c = w.connect(alt);
}
log.debug("Connection succeeded: " + c);
return c;
}
In Java, each of the log statements creates a new StringBuilder, and invokes the toString() method on each object concatenated to the string. These toString() methods, in turn, are likely to create StringBuilder instances of their own, and invoke the toString() methods of their members, and so on, across a potentially large object graph. (Before Java 5, it was even more expensive, since StringBuffer was used, and all of its operations are synchronized.)
This can be relatively costly, especially if the log statement is in some heavily-executed code path. And, written as above, that expensive message formatting occurs even if the logger is bound to discard the result because the log level is too high.
This leads to the introduction of guard statements of the form:
if (log.isDebugEnabled())
log.debug("Attempting connection of dongle " + d + " to widget " + w);
With this guard, the evaluation of arguments d and w and the string concatenation is performed only when necessary.
A solution for simple, efficient logging
However, if the logger (or a wrapper that you write around your chosen logging package) takes a formatter and arguments for the formatter, the message construction can be delayed until it is certain that it will be used, while eliminating the guard statements and their cyclomatic complexity.
public final class FormatLogger
{
private final Logger log;
public FormatLogger(Logger log)
{
this.log = log;
}
public void debug(String formatter, Object... args)
{
log(Level.DEBUG, formatter, args);
}
… &c. for info, warn; also add overloads to log an exception …
public void log(Level level, String formatter, Object... args)
{
if (log.isEnabled(level)) {
/*
* Only now is the message constructed, and each "arg"
* evaluated by having its toString() method invoked.
*/
log.log(level, String.format(formatter, args));
}
}
}
class MyClass
{
private static final FormatLogger log =
new FormatLogger(Logger.getLogger(MyClass.class));
Connection connect(Widget w, Dongle d, Dongle alt)
throws ConnectionException
{
log.debug("Attempting connection of dongle %s to widget %s.", d, w);
Connection c;
try {
c = w.connect(d);
} catch(ConnectionException ex) {
log.warn("Connection failed; attempting alternate dongle %s.", d);
c = w.connect(alt);
}
log.debug("Connection succeeded: %s", c);
return c;
}
}
Now, none of the cascading toString() calls with their buffer allocations will occur unless they are necessary! This effectively eliminates the performance hit that led to the guard statements. One small penalty, in Java, would be auto-boxing of any primitive type arguments you pass to the logger.
The code doing the logging is arguably even cleaner than ever, since untidy string concatenation is gone. It can be even cleaner if the format strings are externalized (using a ResourceBundle), which could also assist in maintenance or localization of the software.
Further enhancements
Also note that, in Java, a MessageFormat object could be used in place of a "format" String, which gives you additional capabilities such as a choice format to handle cardinal numbers more neatly. Another alternative would be to implement your own formatting capability that invokes some interface that you define for "evaluation", rather than the basic toString() method.
A: In languages supporting lambda expressions or code blocks as parameters, one solution for this would be to give just that to the logging method. That one could evaluate the configuration and only if needed actually call/execute the provided lambda/code block.
Did not try it yet, though.
Theoretically this is possible. I would not like to use it in production due to performance issues i expect with that heavy use of lamdas/code blocks for logging.
But as always: if in doubt, test it and measure the impact on cpu load and memory.
A: Thank you for all your answers! You guys rock :)
Now my feedback is not as straight-forward as yours:
Yes, for one project (as in 'one program deployed and running on its own on a single production platform'), I suppose you can go all technical on me:
*
*dedicated 'Log Retriever' objects, which can be pass to a Logger wrapper only calling toString() is necessary
*used in conjunction with a logging variadic function (or a plain Object[] array!)
and there you have it, as explained by @John Millikin and @erickson.
However, this issue forced us to think a little about 'Why exactly we were logging in the first place ?'
Our project is actually 30 different projects (5 to 10 people each) deployed on various production platforms, with asynchronous communication needs and central bus architecture.
The simple logging described in the question was fine for each project at the beginning (5 years ago), but since then, we has to step up. Enter the KPI.
Instead of asking to a logger to log anything, we ask to an automatically created object (called KPI) to register an event. It is a simple call (myKPI.I_am_signaling_myself_to_you()), and does not need to be conditional (which solves the 'artificial increase of cyclomatic complexity' issue).
That KPI object knows who calls it and since he runs from the beginning of the application, he is able to retrieve lots of data we were previously computing on the spot when we were logging.
Plus that KPI object can be monitored independently and compute/publish on demand its information on a single and separate publication bus.
That way, each client can ask for the information he actually wants (like, 'has my process begun, and if yes, since when ?'), instead of looking for the correct log file and grepping for a cryptic String...
Indeed, the question 'Why exactly we were logging in the first place ?' made us realize we were not logging just for the programmer and his unit or integration tests, but for a much broader community including some of the final clients themselves. Our 'reporting' mechanism had to be centralized, asynchronous, 24/7.
The specific of that KPI mechanism is way out of the scope of this question. Suffice it to say its proper calibration is by far, hands down, the single most complicated non-functional issue we are facing. It still does bring the system on its knee from time to time! Properly calibrated however, it is a life-saver.
Again, thank you for all the suggestions. We will consider them for some parts of our system when simple logging is still in place.
But the other point of this question was to illustrate to you a specific problem in a much larger and more complicated context.
Hope you liked it. I might ask a question on KPI (which, believe or not, is not in any question on SOF so far!) later next week.
I will leave this answer up for voting until next Tuesday, then I will select an answer (not this one obviously ;) )
A: Maybe this is too simple, but what about using the "extract method" refactoring around the guard clause? Your example code of this:
public void Example()
{
if(myLogger.isLoggable(Level.INFO))
myLogger.info("A String");
if(myLogger.isLoggable(Level.FINE))
myLogger.fine("A more complicated String");
// +1 for each test and log message
}
Becomes this:
public void Example()
{
_LogInfo();
_LogFine();
// +0 for each test and log message
}
private void _LogInfo()
{
if(!myLogger.isLoggable(Level.INFO))
return;
// Do your complex argument calculations/evaluations only when needed.
}
private void _LogFine(){ /* Ditto ... */ }
A: In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting.
log.info ("a = %s, b = %s", a, b)
You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc).
This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing mylist.toString() will take a while to no benefit, as the result will be thrown away. So you pass mylist as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed.
Since the OP's question specifically mentions Java, here's how the above can be used:
I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)
The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination.
Say you have a function get_everything(). It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called LazyGetEverything:
public class MainClass {
private class LazyGetEverything {
@Override
public String toString() {
return getEverything().toString();
}
}
private Object getEverything() {
/* returns what you want to .toString() in the inner class */
}
public void logEverything() {
log.info(new LazyGetEverything());
}
}
In this code, the call to getEverything() is wrapped so that it won't actually be executed until it's needed. The logging function will execute toString() on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full getEverything() call.
A: In C or C++ I'd use the preprocessor instead of the if statements for the conditional logging.
A: Pass the log level to the logger and let it decide whether or not to write the log statement:
//if(myLogger.isLoggable(Level.INFO) {myLogger.info("A String");
myLogger.info(Level.INFO,"A String");
UPDATE: Ah, I see that you want to conditionally create the log string without a conditional statement. Presumably at runtime rather than compile time.
I'll just say that the way we've solved this is to put the formatting code in the logger class so that the formatting only takes place if the level passes. Very similar to a built-in sprintf. For example:
myLogger.info(Level.INFO,"A String %d",some_number);
That should meet your criteria.
A:
(source: scala-lang.org)
Scala has a annontation @elidable() that allows you to remove methods with a compiler flag.
With the scala REPL:
C:>scala
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.
6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scala.annotation.elidable
import scala.annotation.elidable
scala> import scala.annotation.elidable._
import scala.annotation.elidable._
scala> @elidable(FINE) def logDebug(arg :String) = println(arg)
logDebug: (arg: String)Unit
scala> logDebug("testing")
scala>
With elide-beloset
C:>scala -Xelide-below 0
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.
6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scala.annotation.elidable
import scala.annotation.elidable
scala> import scala.annotation.elidable._
import scala.annotation.elidable._
scala> @elidable(FINE) def logDebug(arg :String) = println(arg)
logDebug: (arg: String)Unit
scala> logDebug("testing")
testing
scala>
See also Scala assert definition
A: Conditional logging is evil. It adds unnecessary clutter to your code.
You should always send in the objects you have to the logger:
Logger logger = ...
logger.log(Level.DEBUG,"The foo is {0} and the bar is {1}",new Object[]{foo, bar});
and then have a java.util.logging.Formatter that uses MessageFormat to flatten foo and bar into the string to be output. It will only be called if the logger and handler will log at that level.
For added pleasure you could have some kind of expression language to be able to get fine control over how to format the logged objects (toString may not always be useful).
A: As much as I hate macros in C/C++, at work we have #defines for the if part, which if false ignores (does not evaluate) the following expressions, but if true returns a stream into which stuff can be piped using the '<<' operator.
Like this:
LOGGER(LEVEL_INFO) << "A String";
I assume this would eliminate the extra 'complexity' that your tool sees, and also eliminates any calculating of the string, or any expressions to be logged if the level was not reached.
A: Here is an elegant solution using ternary expression
logger.info(logger.isInfoEnabled() ? "Log Statement goes here..." : null);
A: Consider a logging util function ...
void debugUtil(String s, Object… args) {
if (LOG.isDebugEnabled())
LOG.debug(s, args);
}
);
Then make the call with a "closure" round the expensive evaluation that you want to avoid.
debugUtil(“We got a %s”, new Object() {
@Override String toString() {
// only evaluated if the debug statement is executed
return expensiveCallToGetSomeValue().toString;
}
}
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
}
|
Q: Running an MVC application through IIS results in "Directory listing denied" I have an .Net MVC application which runs fine if I use the build in Visual Studio Webserver. If I use the projects property pages to switch to IIS as the webserver and create a virtual directory for my project, any request I send to the server results in a "Directory listing denied" failure.
Does anyone know a solution for this?
A: Might be the IIS does not have default.aspx set up as a start page.
A: It's an issue with 'extensionless' urls prior to IIS7.
It needs either an ISAPI filter or duplicate routes in the routing table with a .mvc extension. Try ScottGu's blog at weblogs.asp.net.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Implementing IntelliSense-like behavior in custom editors for domain-specific languages I'm creating a DSL with a template-like editor, much like the rule systems in Alice. Users will be able to select relationships from a list as well as the objects to apply the relation to. These two lists should be filtered based on the acceptable types -- for instance, if the relationship is "greater than" then the available objects must be of a type that "greater than" is implemented for.
Similarly, if an object is selected that is not comparable with greater than, then that relation should not be in the list of potential relations. I think the heart of this problem is a type checker, but I'm not certain of the best way to incorporate that type of logic in my application. Is anyone aware of existing type checking libraries for DSLs?
I am specifically interested in open-source and cross-platform technologies. Java is probably the language we will end up using, but that is not fixed.
A: You might look into Scintilla. It's the editing component used by Notepad++, among other tools. It has some support for doing autocompletion, although I haven't tried using it myself, so I'm not sure how well it works. It's open source, so if it doesn't meet your needs, you can extend it without too much hassle, I think.
A: This might help on the intellisense side - CodeTextBox
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to record window position in Windows Forms application settings It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:
*
*Window position same as it was
*
*Unless the screen has resized and the old position is now off screen.
*Splitters should retain their position
*Tab containers should retain their selection
*Some dropdowns should retain their selection
*Window state (maximize, minimize, normal) is the same as it was.
*
*Maybe you should never start minimized, I haven't decided.
I'll add my current solutions as an answer along with the limitations.
A: The sample below shows how I do it
*
*SavePreferences is called when closing the form and saves the form's size, and a flag indicating if it's maximized (in this version I don't save if it's minimized - it will come back up restored or maximized next time).
*LoadPreferences is called from OnLoad.
*First save the design-time WindowState and set it to Normal. You can only successfully set the form size if it's WindowState is Normal.
*Next restore the Size from your persisted settings.
*Now make sure the form fits on your screen (call to FitToScreen). The screen resolution may have changed since you last ran the application.
*Finally set the WindowState back to Maximized (if persisted as such), or to the design-time value saved earlier.
This could obviously be adapted to persist the start position and whether the form was minimized when closed - I didn't need to do that. Other settings for controls on your form such as splitter position and tab container are straightforward.
private void FitToScreen()
{
if (this.Width > Screen.PrimaryScreen.WorkingArea.Width)
{
this.Width = Screen.PrimaryScreen.WorkingArea.Width;
}
if (this.Height > Screen.PrimaryScreen.WorkingArea.Height)
{
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
}
}
private void LoadPreferences()
{
// Called from Form.OnLoad
// Remember the initial window state and set it to Normal before sizing the form
FormWindowState initialWindowState = this.WindowState;
this.WindowState = FormWindowState.Normal;
this.Size = UserPreferencesManager.LoadSetting("_Size", this.Size);
_currentFormSize = Size;
// Fit to the current screen size in case the screen resolution
// has changed since the size was last persisted.
FitToScreen();
bool isMaximized = UserPreferencesManager.LoadSetting("_Max", initialWindowState == FormWindowState.Maximized);
WindowState = isMaximized ? FormWindowState.Maximized : FormWindowState.Normal;
}
private void SavePreferences()
{
// Called from Form.OnClosed
UserPreferencesManager.SaveSetting("_Size", _currentFormSize);
UserPreferencesManager.SaveSetting("_Max", this.WindowState == FormWindowState.Maximized);
... save other settings
}
x
A: The simplest solution I've found is to use data binding with the application settings. I bind the location and clientSize properties on the window along with the splitterDistance on the splitter.
Drawbacks:
*
*If you close the window while minimized, it opens hidden the next time. It's really hard to get the window back.
*If you close the window while maximized, it opens filling the whole screen, but not maximized (minor issue).
*Resizing the window using the top-right corner or the bottom-left corner is just ugly. I guess the two databound properties are fighting each other.
If you'd like to experiment with the strange behaviour, I posted a sample solution using this technique.
A: I make a Setting for each value I want to save, and use code like this:
private void MainForm_Load(object sender, EventArgs e) {
RestoreState();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
SaveState();
}
private void SaveState() {
if (WindowState == FormWindowState.Normal) {
Properties.Settings.Default.MainFormLocation = Location;
Properties.Settings.Default.MainFormSize = Size;
} else {
Properties.Settings.Default.MainFormLocation = RestoreBounds.Location;
Properties.Settings.Default.MainFormSize = RestoreBounds.Size;
}
Properties.Settings.Default.MainFormState = WindowState;
Properties.Settings.Default.SplitterDistance = splitContainer1.SplitterDistance;
Properties.Settings.Default.Save();
}
private void RestoreState() {
if (Properties.Settings.Default.MainFormSize == new Size(0, 0)) {
return; // state has never been saved
}
StartPosition = FormStartPosition.Manual;
Location = Properties.Settings.Default.MainFormLocation;
Size = Properties.Settings.Default.MainFormSize;
// I don't like an app to be restored minimized, even if I closed it that way
WindowState = Properties.Settings.Default.MainFormState ==
FormWindowState.Minimized ? FormWindowState.Normal : Properties.Settings.Default.MainFormState;
splitContainer1.SplitterDistance = Properties.Settings.Default.SplitterDistance;
}
Keep in mind that recompiling wipes the config file where the settings are stored, so test it without making code changes in between a save and a restore.
A: Based on the accepted answer by Don Kirkby and the WindowSettings class he wrote, you could derive a CustomForm from the standard one to reduce the amount of identical code written for each and every form, maybe like this:
using System;
using System.Configuration;
using System.Reflection;
using System.Windows.Forms;
namespace CustomForm
{
public class MyCustomForm : Form
{
private ApplicationSettingsBase _appSettings = null;
private string _settingName = "";
public Form() : base() { }
public Form(ApplicationSettingsBase settings, string settingName)
: base()
{
_appSettings = settings;
_settingName = settingName;
this.Load += new EventHandler(Form_Load);
this.FormClosing += new FormClosingEventHandler(Form_FormClosing);
}
private void Form_Load(object sender, EventArgs e)
{
if (_appSettings == null) return;
PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);
if (settingProperty == null) return;
WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;
if (previousSettings == null) return;
previousSettings.Restore(this);
}
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if (_appSettings == null) return;
PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);
if (settingProperty == null) return;
WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;
if (previousSettings == null)
previousSettings = new WindowSettings();
previousSettings.Record(this);
settingProperty.SetValue(_appSettings, previousSettings, null);
_appSettings.Save();
}
}
}
To use this, pass your application settings class and setting name in the constructor:
CustomForm.MyCustomForm f = new CustomForm.MyCustomForm(Properties.Settings.Default, "formSettings");
This uses Reflection to get/set the previous settings from/to the settings class. It may not be optimal to put the Save call into the Form_Closing routine, one could remove that and save the settings file whenever the main app exits.
To use it as a regular form, just use the parameterless constructor.
A: A hack you can use Settings to store that information. All you have to do is bind the desired property (ex. form.Size and form.Location) to a specific setting and it get saved and updated automatically.
A: You can use the application settings to set which control properties will be persisted, in the Form_closed event you have to use the save method on the application settings to write these to disk:
Properties.Settings.Default.Save();
A: Here is an example of a few I use myself. It only takes into consideration the primary monitor, so it might be better to handle it differently if used on multiple monitors.
Size size;
int x;
int y;
if (WindowState.Equals(FormWindowState.Normal))
{
size = Size;
if (Location.X + size.Width > Screen.PrimaryScreen.Bounds.Width)
x = Screen.PrimaryScreen.Bounds.Width - size.Width;
else
x = Location.X;
if (Location.Y + Size.Height > Screen.PrimaryScreen.Bounds.Height)
y = Screen.PrimaryScreen.Bounds.Height - size.Height;
else
y = Location.Y;
}
else
{
size = RestoreBounds.Size;
x = (Screen.PrimaryScreen.Bounds.Width - size.Width)/2;
y = (Screen.PrimaryScreen.Bounds.Height - size.Height)/2;
}
Properties.Settings.Position.AsPoint = new Point(x, y); // Property setting is type of Point
Properties.Settings.Size.AsSize = size; // Property setting is type of Size
Properties.Settings.SplitterDistance.Value = splitContainer1.SplitterDistance; // Property setting is type of int
Properties.Settings.IsMaximized = WindowState == FormWindowState.Maximized; // Property setting is type of bool
Properties.Settings.DropDownSelection = DropDown1.SelectedValue;
Properties.Settings.Save();
A: My other option is to write more custom code around the application settings and execute it on formLoad and formClosed. This doesn't use data binding.
Drawbacks:
*
*More code to write.
*Very fiddly. The order you set the properties on formLoad is confusing. For example, you have to make sure you've set the window size before you set the splitter distance.
Right now, this is my preferred solution, but it seems like too much work. To reduce the work, I created a WindowSettings class that serializes the window location, size, state, and any splitter positions to a single application setting. Then I can just create a setting of that type for each form in my application, save on close, and restore on load.
I posted the source code, including the WindowSettings class and some forms that use it. Instructions on adding it to a project are included in the WindowSettings.cs file. The trickiest part was figuring out how to add an application setting with a custom type. You choose Browse... from the type dropdown, and then manually enter the namespace and class name. Types from your project don't show up in the list.
Update: I added some static methods to simplify the boilerplate code that you add to each form. Once you've followed the instructions for adding the WindowSettings class to your project and creating an application setting, here's an example of the code that has to be added to each form whose position you want to record and restore.
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.Default.CustomWindowSettings = WindowSettings.Record(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
private void MyForm_Load(object sender, EventArgs e)
{
WindowSettings.Restore(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: Most efficient way to see if an item is or is not in a listbox control This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.
A: Here is a sample function that might be adapted to suit.
Function CheckForItem(strItem, ListB As ListBox) As Boolean
Dim rs As DAO.Recordset
Dim db As Database
Dim tdf As TableDef
Set db = CurrentDb
CheckForItem = False
Select Case ListB.RowSourceType
Case "Value List"
CheckForItem = InStr(ListB.RowSource, strItem) > 0
Case "Table/Query"
Set rs = db.OpenRecordset(ListB.RowSource)
For i = 0 To rs.Fields.Count - 1
strList = strList & " & "","" & " & rs.Fields(i).Name
Next
rs.FindFirst "Instr(" & Mid(strList, 10) & ",'" & strItem & "')>0"
If Not rs.EOF Then CheckForItem = True
Case "Field List"
Set tdf = db.TableDefs(ListB.RowSource)
For Each itm In tdf.Fields
If itm.Name = strItem Then CheckForItem = True
Next
End Select
End Function
A: Unfortunately there is no more efficient way than a linear search, unless you know that your listbox is sorted or indexed in some particular fashion.
For i = 1 To TheComboBoxControl.ListCount
if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something()
Next i
A: If you don't mind resorting to the Windows API you can search for a string like this:
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const LB_FINDSTRINGEXACT = &H1A2
Dim index as Integer
Dim searchString as String
searchString = "Target" & Chr(0)
index = SendMessage(ListBox1.hWnd, LB_FINDSTRINGEXACT , -1, searchString)
Which should return the index of the row that contains the target string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple VB.NET using Google Search API? Can anyone point me to a good, simple, example of a Google API (AJAX Search API I suppose?) that can be implemented in VB.net (2008)? I have tried to sign up for a Google API key but it wants a URL from which the search will be executed from. I dont have a URL for this example. I tried http://localhost but then was told by a colleague that she got a "Invalid Key" error. A simple working example would be awesome. Thank you.
A: If you're running a Google API locally for development or test purposes, you can use an internal IP address - it doesn't have to be URL that's exposed to the Internet. For example, I have development machines running the Google Maps API using addresses in the 192.168.0.xxx range. This allows them to be accessed from any other machine on the internal network. Obviously you need a fixed IP for this.
A: I do not think the Google API TOS allows for .net development. I read that in a newsgroup article recently.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I set the default database in Sql Server from code? I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.
A: ALTER LOGIN should be used for SQL Server 2005 or later:
http://technet.microsoft.com/en-us/library/ms189828.aspx
ALTER LOGIN <login_name> WITH DEFAULT_DATABASE = <default_database>
sp_defaultdb eventually will be removed from SQL Server:
http://technet.microsoft.com/en-us/library/ms181738.aspx
A: Thanks Stephen.
As a note, if you are using Windows Authentication, the @loginname is YourDomain\YourLogin (probably obvious to everybody else, but took me a couple tries.
sp_defaultdb @loginame='YourDomain\YourLogin', @defdb='YourDatabase'
A: from: http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm
sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database'
A: If you're trying to change which database you are using after you are logged in, you can use the USE command. E.g. USE Northwind.
https://www.tutorialspoint.com/sql/sql-select-database.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: What's a Good Resource for Learning XNA? I've been considering experimenting with game development and XNA. I'm already an expert C/C++ programmer. I read through some C# books, but haven't done any development in C# yet.
What's a good resource for learning XNA, from the point of view of someone who's already an expert programmer?
A: I'll second reimers and the creators.xna.com samples as a good way to get a handle on how to quickly whip things up.
On the other side of the spectrum, I highly recommend Nick Gravelyn's Tile Engine tutorials. It's a different approach, as the entire series is presented in video. It seems like a great place for beginners to get started, though new coders might have a bit of trouble with his pace. Having said that, the section on the Content Pipeline (which is an XNA-specific implementation of the pipeline concept) is a good introduction.
Ziggyware also has a good selection of tutorials, some of which are more advanced.
Shawn Hargreaves, one of the XNA's devs, has a great blog that let's you in on the internals of XNA a little more. Check out the archive if there's a topic that interests you in particular.
A: This is good: http://www.riemers.net/, just keep in mind that navigation is through the bar on the right. I must have been tired because it took me a while to figure it out :-O
A: Check out the XNA homepage and the tutorials over there, under Community -> Resources. As an experienced programmer you should be able to take it from there.
For more in-depth infos browse the XNA Team's blogs, also linked from the XNA Creators page.
A: I would say that a library called XNA Debug Terminal should be of some help to you. It is open source and can be setup in seconds. It allows you to see the value of any variable, invoke any method, watch values changing in real-time, and more by simply typing c# code into a terminal-like display that appears atop your game window. Unlike the normal Visual Studio debugger, you can invoke arbitrary code while your game is running. You can find out more about this at http://www.protohacks.net/xna_debug_terminal . This will greatly help you to avoid a lot of frustration while learning XNA.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can I pass an arbitrary block of commands to a bash function? I am working on a bash script where I need to conditionally execute some things if a particular file exists. This is happening multiple times, so I abstracted the following function:
function conditional-do {
if [ -f $1 ]
then
echo "Doing stuff"
$2
else
echo "File doesn't exist!"
end
}
Now, when I want to execute this, I do something like:
function exec-stuff {
echo "do some command"
echo "do another command"
}
conditional-do /path/to/file exec-stuff
The problem is, I am bothered that I am defining 2 things: the function of a group of commands to execute, and then invoking my first function.
I would like to pass this block of commands (often 2 or more) directly to "conditional-do" in a clean manner, but I have no idea how this is doable (or if it is even possible)... does anyone have any ideas?
Note, I need it to be a readable solution... otherwise I would rather stick with what I have.
A: This should be readable to most C programmers:
function file_exists {
if ( [ -e $1 ] ) then
echo "Doing stuff"
else
echo "File $1 doesn't exist"
false
fi
}
file_exists filename && (
echo "Do your stuff..."
)
or the one-liner
file_exists filename && echo "Do your stuff..."
Now, if you really want the code to be run from the function, this is how you can do that:
function file_exists {
if ( [ -e $1 ] ) then
echo "Doing stuff"
shift
$*
else
echo "File $1 doesn't exist"
false
fi
}
file_exists filename echo "Do your stuff..."
I don't like that solution though, because you will eventually end up doing escaping of the command string.
EDIT: Changed "eval $*" to $ *. Eval is not required, actually. As is common with bash scripts, it was written when I had had a couple of beers ;-)
A: One (possibly-hack) solution is to store the separate functions as separate scripts altogether.
A: The cannonical answer:
[ -f $filename ] && echo "it has worked!"
or you can wrap it up if you really want to:
function file-exists {
[ "$1" ] && [ -f $1 ]
}
file-exists $filename && echo "It has worked"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: In OOP, In what cases do you act on an object instead of letting the object act? In what cases,or for what kind of algorithms, do you start using your objects as data structure with methodes outside of the objects (ie : Tree Walking, etc...).
What scheme do you use ? (Visitor ? pattern-matching ?)
Or do you think an object should always be the only one allowed to act on its own data ?
A: Objects should have a single responsibility. If the operation you're doing is acting on an object but has nothing to do with the responsibility of that object. It's better to put it outside that object.
A:
Or do you think an object should always be the only one allowed to act on its own data?
That is my philosophy (except for objects that are only entities; ie: they map something else, like an xml file or something and only contain properties)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/105988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.