In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:
IEnumerable FilteredList() { foreach(object item in FullList) { if(IsItemInPartialList(item)) yield return item; } }What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.
The yield
keyword actually does quite a lot here.
The function returns an object that implements the IEnumerable interface. If a calling function starts foreach
ing over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0 . In earlier versions you had to create your own IEnumerable
and IEnumerator
objects to do stuff like this.
The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:
public void Consumer() { foreach(int i in Integers()) { Console.WriteLine(i.ToString()); } } public IEnumerable Integers() { yield return 1; yield return 2; yield return 4; yield return 8; yield return 16; yield return 16777216; }
When you step through the example, you'll find the first call to Integers()
returns 1
. The second call returns 2
and the line yield return 1
is not executed again.
Here is a real-life example:
public IEnumerable Read(string sql, Func make, params object[] parms) { using (var connection = CreateConnection()) { using (var command = CreateCommand(CommandType.Text, sql, connection, parms)) { command.CommandTimeout = dataBaseSettings.ReadCommandTimeout; using (var reader = command.ExecuteReader()) { while (reader.Read()) { yield return make(reader); } } } } }
I need a different random number for each row in my table. The following seemingly obvious code uses the same random value for each row.
SELECT table_name, RAND() magic_number FROM information_schema.tables
I'd like to get an INT or a FLOAT out of this. The rest of the story is I'm going to use this random number to create a random date offset from a known date, e.g. 1-14 days offset from a start date.
This is for Microsoft SQL Server 2000.
Take a look at SQL Server - Set based random numbers which has a very detailed explanation.
To summarize, the following code generates a random number between 0 and 13 inclusive with a normalized distribution:
ABS(CHECKSUM(NewId())) % 14
To change your range, just change the number at the end of the expression. Be extra careful if you need a range that includes both positive and negative numbers. If you do it wrong, it's possible to double-count the number 0.
A small warning for the math nuts in the room: there is a very slight bias in this code. CHECKSUM()
results in numbers that are uniform across the entire range of the sql Int datatype, or at least as near so as my (the editor) testing can show. However, there will be some bias when CHECKSUM() produces a number at the very top end of that range. Any time you get a number between the maximum possible integer and the last exact multiple of the size of your desired range (14 in this case) before that maximum integer, those results are favored over the remaining portion of your range that cannot be produced from that last multiple of 14.
As an example, imagine the entire range of the Int type is only 19. 19 is the largest possible integer you can hold. When CHECKSUM() results in 14-19, these correspond to results 0-5. Those numbers would be heavily favored over 6-13, because CHECKSUM() is twice as likely to generate them. It's easier to demonstrate this visually. Below is the entire possible set of results for our imaginary integer range:
Checksum Integer: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Range Result: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 0 1 2 3 4 5You can see here that there are more chances to produce some numbers than others: bias. Thankfully, the actual range of the Int type is much larger... so much so that in most cases the bias is nearly undetectable. However, it is something to be aware of if you ever find yourself doing this for serious security code.
I'm working on a bookmarklet (Javascript that is triggered from a bookmark) that overlays an image over a webpage in order to check if the html is consistent with the design. (it uses opacity)
I want to save the reference-image on a per-url-basis. I have three options as far as I know:
save the path in a cookie save the path in local storage save the image in local storage I'm currently planning to use local-storage to save the image. The pros are that It works een if the original image is removed and it syncs between diffrent computers in chrome. I don't know of any cons. I don't need pixel-perfection in IE7, so browser support is fine.
What is the best approach?
Sure, you can save images and/or the url to localStorage
.
However, since localStorage
only takes string
you need to first convert the image to data-url
either by serving the image as such from the server, or convert the image by the use of canvas
(note that canvas can normally only set images from same origin, and of course canvas is not available in IE7 without a polyfill).
A better approach is perhaps to use indexedDB
or the new File API
(currently poorly supported, so far only Chrome) which allow you to request large storage space and it can save the image directly (as a Blob).
The images will be stored as you serve them (unless you rescale and re-compress using jpeg in canvas) so pixelation or quality reduction shouldn't be an issue.
IE7 does not support localStorage
so you would need to revert to UserData
(limited to 4 mb IIRC) or cookies with the url instead, in this case.
Though -
If it's not that important to keep the original image locally I would rather suggest to serve the image with a late expire data in its header.
This way it stays in the cache until the user deletes it or it expires. It you have restriction on traffic to your server then localStorage
/indexedDB
is probably a better option.
Joshua Bloch in "Effective Java " said that
Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition)
Let's see if I understand this correctly.
Here is my understanding of a checked exception:
try{ String userInput = //read in user input Long id = Long.parseLong(userInput); }catch(NumberFormatException e){ id = 0; //recover the situation by setting the id to 0 }
1. Is the above considered a checked exception?
2. Is RuntimeException an unchecked exception?
Here is my understanding of an unchecked exception:
try{ File file = new File("my/file/path"); FileInputStream fis = new FileInputStream(file); }catch(FileNotFoundException e){ //3. What should I do here? //Should I "throw new FileNotFoundException("File not found");"? //Should I log? //Or should I System.exit(0);? }
4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I? (Note: my 3rd question is inside the catch
above)
try{ String filePath = //read in from user input file path File file = new File(filePath); FileInputStream fis = new FileInputStream(file); }catch(FileNotFoundException e){ //Kindly prompt the user an error message //Somehow ask the user to re-enter the file path. }
5. Why do people do this?
public void someMethod throws Exception{ }
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
6. Should I bubble up the exact exception or mask it using Exception?
Below are my readings
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of RuntimeException
(unchecked exception)
However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.
Here's my extended view on the topic .
As for the particular questions:
Is the NumberFormatException
consider a checked exception? No. NumberFormatException
is unchecked (= is subclass of RuntimeException
). Why? I don't know. (but there should have been a method isValidInteger(..)
)
Is RuntimeException
an unchecked exception? Yes, exactly.
What should I do here? It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:
log it and return rethrow it (declare it to be thrown by the method) construct a new exception by passing the current one in constructor Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I? It could've been. But nothing stops you from catching the unchecked exception as well
Why do people add class Exception
in the throws clause? Most often because people are lazy to consider what to catch and what to rethrow. Throwing Exception
is a bad practice and should be avoided.
Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.
I have an element that already has a class:
Now I want to create a JavaScript function that will add a class to the div
(not replace, but add).
How can I do that?
Add a space plus the name of your new class to the className
property of the element. First, put an id
on the element so you can easily get a reference.
Then
var d = document.getElementById("div1"); d.className += " otherclass";
Note the space before otherclass
. It's important to include the space otherwise it compromises existing classes that come before it in the class list.
See also element.className on MDN .
Use element.classList.add to add a class:
element.classList.add("my-class");
And element.classList.remove to remove a class:
element.classList.remove("my-class");
I have a div element which contains text, and I want to align the contents of this div vertically center.
Here is my div style:
#box { height: 170px; width: 270px; background: #000; font-size: 48px; color: #FFF; text-align: center; }
Lorem ipsum dolor sit
What is the best way to do this?
int main () { FILE *in; in = fopen("input.txt","r"); char c = fgetc(in); while(feof(in) != EOF) { printf("%c",c); c = fgetc(in); } }
feof(in) != EOF
doesn't stop the while loop from stopping but something like !feof(in)
seems to work. Any ideas?
feof
doesn't return EOF
on end of file; it returns true
, which is not equal to EOF
.
fgetc
will return EOF
when it hits end-of-file. Your code should be written as
int main () { FILE *in; in = fopen("input.txt","r"); int c = fgetc(in); // note int not char while(c != EOF) // compare c to EOF { printf("%c",c); c = fgetc(in); } }
You should not use feof
as a loop condition, as it won't return true
until after you attempt to read past the end of the file, meaning your loop will execute once too often.
I am getting the following error syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
on this line $this->email->subject($this->core_model->companyDetails()->coreCompanyName 'User Registration Confirmation');
have I make a mistake with the '' and ""
? I have also past the name as $data can I include this in the subject instead of the model call?
You probably forgot a comma: Try this:
$this->email->subject($this->core_model->companyDetails()->coreCompanyName, 'User Registration Confirmation');
instead of
$this->email->subject($this->core_model->companyDetails()->coreCompanyName 'User Registration Confirmation');
I'm trying to get heading info from CLLocationManager but it's not getting called. I did everything as the documentation says, but something is very wrong. I'm using locationManager delegating into my app delegate.
Here is the method to retrieve heading messages:
- (void) locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading { NSLog(@"%@", newHeading); }
Here is the part from main()
locationManager = [[CLLocationManager alloc] init]; [locationManager setDelegate:self]; [locationManager startUpdatingHeading];
But nothing happens! With debugging, NSLog is never getting called. When I do same with [locationManager startUpdatingLocation] everything works fine, shows the location info, using another method (very same looking but using
- (void) locationManager:(CLLocationManager *) manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
but I need heading info here.
Found the deal. Code is perfectly fine, the issue is in Iphone simulator. Somehow it is providing location info just fine, but heading info is not provided thus the message is never sent. Talk about weird things, apple.
I want to ask a question about the multipart/form-data
. In the HTTP header, I find that the Content-Type: multipart/form-data; boundary=???
.
Is the ???
free to be defined by the user? Or is it generated from the HTML? Is it possible for me to define the ??? = abcdefg
?
I am new to python and many constructions blows away my C styled brain. Now I need to understand how some python code works.
#Training inputs for RGBcolors colors = np.array( [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.5], [0.125, 0.529, 1.0], [0.33, 0.4, 0.67], [0.6, 0.5, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.33, 0.33, 0.33], [0.5, 0.5, 0.5], [0.66, 0.66, 0.66]]) for i in range(num_training): rnd_ind = np.random.randint(0, len(colors)) s.train(colors[rnd_ind, :]) //what's going on here?
This is the train
body:
def train(self, input_x): # Compute the winning unit bmu_index, diff = self.session.run([self.bmu_index, self.diff], {self.input_placeholder:[input_x], self.current_iteration:self.num_iterations}) # Update the network's weights self.session.run(self.update_weights, {self.diff_2:diff, self.dist_sliced:self.dist[bmu_index[0],:], self.current_iteration:self.num_iterations}) self.num_iterations = min(self.num_iterations+1, self.num_expected_iterations)
I set breakpoint to train
beginning to see how it's input parameter looks like, but I no see anything unusual. This is just an array.
I tried searching and found this Colon (:) in Python list index question, but it looks like this is something different, because in my case :
written after ,
, but in their cases it follows after some value.
This has nothing to do with standard python arrays. If you use it in python lists you ll get an error.
Traceback (most recent call last): File "asd.py", line 3, in print(x[0, :]) TypeError: list indices must be integers or slices, not tuple
This is specific to numpy. It is an indexing of a multidimensional array. First number is the first dimension, second is the second and so on.
import numpy as np x = np.array([[1,2,3], [3,4,5], [2,3,4], [4,7,8]]) print(x[0, 1:2])
Will output [2]
I have created some little jt code, but it gives me error
function Mind(){ var request = "request"; var reply = "reply"; var words = ''; this.Reply = function(){ if(request == words.nouns[0].noun){ reply = words.nouns[0].noun; } else reply = this.words.nouns[0].noun; } this.SetRequest = function(req){ request = req; } this.GetReply = function(){ return reply; } this.Parse = function(u){ var xmlhttp = new XMLHttpRequest(); var url = u; var result; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { words = JSON.parse(xmlhttp.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(); return result; } this.Construct = function(){ words = this.Parse('mind/words.json'); }} var mind = new Mind(); mind.Parse('mind/words.json');
and here is my json file
{ "nouns": [ {"noun": "child"}, {"noun": "father"} ] }
In command live all goes well, but when I run this code, appears error
Uncaught TypeError: Cannot read property 'nouns' of undefined
Mutliple errors. The most fundamental one is that your code ignores that XMLHttpRequest is async, and wont return a value in the same way as "regular" functions. Read about it here: How to make a function wait until a callback has been called using node.js . The TL;DR is that you have to pass in a "callback-function" to your parse-method and "return" your value using that function, instead of using a return-statement. Google for "javascript callbacks" and read a few tutorials if this concept is new to you!
You also have some minor errors, like returning result
from Parse
, but never actually setting result
to anything. Also words
is being assigned in multiple places in a way that doesn't really make sense. But both of these things will go away when you solve the sync/async issues.
EDIT:
Essentially the fix looks like this:
this.Parse = function(u, callback){ // this "callback" is new var xmlhttp = new XMLHttpRequest(); var url = u; var result; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { words = JSON.parse(xmlhttp.responseText); callback(null, words); // we're "returning" the words here } } xmlhttp.open("GET", url, true); xmlhttp.send(); // no return statement here! } this.Construct = function(){ this.Parse('mind/words.json', function(error, words) { // here you can use your words! }); }}
I am trying to store pointers to vectors of pointers to vectors in a vector. (I hope that wasn't too mind boggling). Basically, I have a vector and I want to store multiple matrices in it, hence the 3 dimensions. There seems to be a problem with the way I am accessing elements. I don't particuarlily understand the error because the 3rd dimension is a pointer to a vector of ints. I don't think that should change the way you access the ints.
using namespace std; vector< vector< vector* >* > matrixHolder; int main() { vector< vector* >* a; a->push_back(new vector(10, 0)); matrixHolder.push_back(a); matrixHolder[0][0][0] = 5; //Line 34 return 0; }
main.cpp:34: error: invalid conversion from ‘int’ to ‘std::vector < int, std::allocator < int> >*’
I am trying to do some authentication with AngularUI Router. $urlRouter.sync()
looks like exactly what I need. However, that's only available when I intercept $locationChangeSuccess
. But when I do that, $state.current.name
is empty, whereas I want it to be the current state.
Here's my code so far:
$rootScope.$on('$locationChangeSuccess', function(event, next, nextParams) { event.preventDefault(); if ($state.current.name === 'login') { return userService.isAuthenticated().then(function(response) { var authenticated; authenticated = response.authenticated; return alert(authenticated); }); } });
Any pointers as to what I'm doing wrong?
I would suggest to go more "UI-Router
way". We should use $rootScope.$on('$stateChangeStart'
event where $state.current
would be properly provided. Here is a working example
Let's observe simple (but not naive) solution, which could be extended to any degree later. Also if you will like this approach, here is much more comprehensive implementation: angular ui-router login authentication
Firstly, let's have our user service defined like this:
.factory('userService', function ($timeout, $q) { var user = undefined; return { // async way how to load user from Server API getAuthObject: function () { var deferred = $q.defer(); // later we can use this quick way - // - once user is already loaded if (user) { return $q.when(user); } // server fake call, in action would be $http $timeout(function () { // server returned UN authenticated user user = {isAuthenticated: false }; // here resolved after 500ms deferred.resolve(user) }, 500) return deferred.promise; }, // sync, quick way how to check IS authenticated... isAuthenticated: function () { return user !== undefined && user.isAuthenticated; } }; })
So, we use async (here $timeout
) to load user
object form a server. In our example it will have a property {isAuthenticated: false }
, which will be used to check if is authenticated.
There is also sync method isAuthenticated()
which, until user is loaded and allowed - always returns false
.
And that would be our listener of the '$stateChangeStart'
event:
.run(['$rootScope', '$state', 'userService', function ($rootScope, $state, userService) { $rootScope.$on('$stateChangeStart', function (event, toState, toParams , fromState, fromParams) { // if already authenticated... var isAuthenticated = userService.isAuthenticated(); // any public action is allowed var isPublicAction = angular.isObject(toState.data) && toState.data.isPublic === true; if (isPublicAction || isAuthenticated) { return; } // stop state change event.preventDefault(); // async load user userService .getAuthObject() .then(function (user) { var isAuthenticated = user.isAuthenticated === true; if (isAuthenticated) { // let's continue, use is allowed $state.go(toState, toParams) return; } // log on / sign in... $state.go("login"); }) ...
What we are checking first, is if user is already loaded and authenticated (var isAuthenticated = ...
) . Next we will give green to any public method. This is done with the data {}
property of the state object definition (see Attach Custom Data to State Objects )
And that's it. In case of states defined like in a below snippet we can experience:
the 'public'
, 'home'
are allowed to anybody the 'private'
, 'private'
will redirect to login if isAuthenticated === false
the 'login'
in this example provides quick way how to switch isAuthenticated on/off
// States $stateProvider // public .state('home', { url: "/home", templateUrl: 'tpl.html', data: { isPublic: true }, }) .state('public', { url: "/public", templateUrl: 'tpl.html', data: { isPublic: true }, }) // private .state('private', { url: "/private", templateUrl: 'tpl.html', }) .state('private2', { url: "/private2", templateUrl: 'tpl.html', }) // login .state('login', { url: "/login", templateUrl: 'tpl.html', data: { isPublic: true }, controller: 'loginCtrl', })
Check that all here
Some other resources:
How does, for example, a button in Java actually listen for an event to occur? I understand button events are handled once they are clicked in a special EDT (Event Dispatching Thread) . But how without "busy waiting" does the button know that it has been actually clicked. The only way I understand this is possible if in a separate thread hidden from the user such as the Event Dispatching Thread there is a constant polling every so often, maybe every few milliseconds to check to see if it was clicked. On top of this, how does a button click invoke code?
I assume people are going to suggest it is the Observer Pattern at work here, but from the examples I have seen, the user more or less explicitly notifies the observers so it's almost no different than calling just a regular method.
s.setName("IceCream"); public void setName(String name) { this.name = name; setChanged(); notifyObservers(); }
and then the update() method is called. This isn't the Observer Pattern from scratch but using the Observable and Observer classes.
Let me know if anything needs to be clarified
This question is sort-of-similar to my last question regarding how to constantly poll a condition without busy waiting. How do you pause a thread until a condition becomes true without busy waiting?
How does, for example, a button in Java actually listen for an event to occur?
The button doesn't do anything. The button only provides a handler (i.e., a java.awt.event.ActionListener
) that the event dispatch thread (EDT) will call when it decides that a given mouse click is intended for that button.
It's the EDT that waits for mouse and keyboard events. How it waits will depend on what operating system is running it. Some operating systems provide a single system call that lets a process wait for input from any one of several different sources. Under Windows it's WaitForMultipleObjects(...)
. Under Linux, it's either select(...)
or poll(...)
.
Given some hypothetical operating system that provides native threads, but no select()
-like function, the JVM could create one thread for each different source of input (e.g., a keyboard thread, a mouse thread, ...) and these could all push events onto a queue that the EDT would consume.
I assume people are going to suggest it is the Observer Pattern at work here,
Basically, yes, but since Java is almost as old as the idea of named patterns, you might not find the word "observer" in the source code.
In the great revelation of The Dark Knight Rises, we are shown it was Talia who escaped The Pit, then brought her father back to rescue her savior, Bane.
However, considering the fact that Talia was born and raised in the prison, how did she know where to find her father or who he was?
One can assume that her mother instructed her on her father's name and nature of his profession, but it is reasonable to believe that her mother didn't know where Ra's was since her incarceration?
I believe it's more about how Ra's Al Ghul found his daughter rather than a matter of her finding him. The news of a child escaping the pit would have spread fast and must have reached to Ra's Al Ghul. He must have tried to contact the person who escaped the pit in order to make her join league of shadows and in that process he may have came to know she is his daughter. I have to admit that I am not familiar with comics and this is the most logical explanation that came to my mind!
I have taken Problem #12 from Project Euler as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first triangle number with more than 1000 divisors instead of 500 as stated in the original problem.
The result is the following:
C:
lorenzo@enzo:~/erlang$ gcc -lm -o euler12.bin euler12.c lorenzo@enzo:~/erlang$ time ./euler12.bin 842161320 real 0m11.074s user 0m11.070s sys 0m0.000s
Python:
lorenzo@enzo:~/erlang$ time ./euler12.py 842161320 real 1m16.632s user 1m16.370s sys 0m0.250s
Python with PyPy:
lorenzo@enzo:~/Downloads/pypy-c-jit-43780-b590cf6de419-linux64/bin$ time ./pypy /home/lorenzo/erlang/euler12.py 842161320 real 0m13.082s user 0m13.050s sys 0m0.020s
Erlang:
lorenzo@enzo:~/erlang$ erlc euler12.erl lorenzo@enzo:~/erlang$ time erl -s euler12 solve Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.7.4 (abort with ^G) 1> 842161320 real 0m48.259s user 0m48.070s sys 0m0.020s
Haskell:
lorenzo@enzo:~/erlang$ ghc euler12.hs -o euler12.hsx [1 of 1] Compiling Main ( euler12.hs, euler12.o ) Linking euler12.hsx ... lorenzo@enzo:~/erlang$ time ./euler12.hsx 842161320 real 2m37.326s user 2m37.240s sys 0m0.080s
Summary:
C: 100% Python: 692% (118% with PyPy) Erlang: 436% (135% thanks to RichardC) Haskell: 1421% I suppose that C has a big advantage as it uses long for the calculations and not arbitrary length integers as the other three. Also it doesn't need to load a runtime first (Do the others?).
Question 1: Do Erlang, Python and Haskell lose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT
?
Question 2: Why is Haskell so slow? Is there a compiler flag that turns off the brakes or is it my implementation? (The latter is quite probable as Haskell is a book with seven seals to me.)
Question 3: Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.
EDIT:
Question 4: Do my functional implementations permit LCO (last call optimization, a.k.a tail recursion elimination) and hence avoid adding unnecessary frames onto the call stack?
I really tried to implement the same algorithm as similar as possible in the four languages, although I have to admit that my Haskell and Erlang knowledge is very limited.
Source codes used:
#include #include int factorCount (long n) { double square = sqrt (n); int isquare = (int) square; int count = isquare == square ? -1 : 0; long candidate; for (candidate = 1; candidate <= isquare; candidate ++) if (0 == n % candidate) count += 2; return count; } int main () { long triangle = 1; int index = 1; while (factorCount (triangle) < 1001) { index ++; triangle += index; } printf ("%ld\n", triangle); }
#! /usr/bin/env python3.2 import math def factorCount (n): square = math.sqrt (n) isquare = int (square) count = -1 if isquare == square else 0 for candidate in range (1, isquare + 1): if not n % candidate: count += 2 return count triangle = 1 index = 1 while factorCount (triangle) < 1001: index += 1 triangle += index print (triangle)
-module (euler12). -compile (export_all). factorCount (Number) -> factorCount (Number, math:sqrt (Number), 1, 0). factorCount (_, Sqrt, Candidate, Count) when Candidate > Sqrt -> Count; factorCount (_, Sqrt, Candidate, Count) when Candidate == Sqrt -> Count + 1; factorCount (Number, Sqrt, Candidate, Count) -> case Number rem Candidate of 0 -> factorCount (Number, Sqrt, Candidate + 1, Count + 2); _ -> factorCount (Number, Sqrt, Candidate + 1, Count) end. nextTriangle (Index, Triangle) -> Count = factorCount (Triangle), if Count > 1000 -> Triangle; true -> nextTriangle (Index + 1, Triangle + Index + 1) end. solve () -> io:format ("~p~n", [nextTriangle (1, 1) ] ), halt (0).
factorCount number = factorCount' number isquare 1 0 - (fromEnum $ square == fromIntegral isquare) where square = sqrt $ fromIntegral number isquare = floor square factorCount' number sqrt candidate count | fromIntegral candidate > sqrt = count | number `mod` candidate == 0 = factorCount' number sqrt (candidate + 1) (count + 2) | otherwise = factorCount' number sqrt (candidate + 1) count nextTriangle index triangle | factorCount triangle > 1000 = triangle | otherwise = nextTriangle (index + 1) (triangle + index + 1) main = print $ nextTriangle 1 1
Using GHC 7.0.3
, gcc 4.4.6
, Linux 2.6.29
on an x86_64 Core2 Duo (2.5GHz) machine, compiling using ghc -O2 -fllvm -fforce-recomp
for Haskell and gcc -O3 -lm
for C.
Your C routine runs in 8.4 seconds (faster than your run probably because of -O3
) The Haskell solution runs in 36 seconds (due to the -O2
flag) Your factorCount'
code isn't explicitly typed and defaulting to Integer
(thanks to Daniel for correcting my misdiagnosis here!). Giving an explicit type signature (which is standard practice anyway) using Int
and the time changes to 11.1 seconds in factorCount'
you have needlessly called fromIntegral
. A fix results in no change though (the compiler is smart, lucky for you). You used mod
where rem
is faster and sufficient. This changes the time to 8.5 seconds . factorCount'
is constantly applying two extra arguments that never change (number
, sqrt
). A worker/wrapper transformation gives us: $ time ./so 842161320 real 0m7.954s user 0m7.944s sys 0m0.004s
That's right, 7.95 seconds . Consistently half a second faster than the C solution . Without the -fllvm
flag I'm still getting 8.182 seconds
, so the NCG backend is doing well in this case too.
Conclusion: Haskell is awesome.
Resulting Code
factorCount number = factorCount' number isquare 1 0 - (fromEnum $ square == fromIntegral isquare) where square = sqrt $ fromIntegral number isquare = floor square factorCount' :: Int -> Int -> Int -> Int -> Int factorCount' number sqrt candidate0 count0 = go candidate0 count0 where go candidate count | candidate > sqrt = count | number `rem` candidate == 0 = go (candidate + 1) (count + 2) | otherwise = go (candidate + 1) count nextTriangle index triangle | factorCount triangle > 1000 = triangle | otherwise = nextTriangle (index + 1) (triangle + index + 1) main = print $ nextTriangle 1 1
EDIT: So now that we've explored that, lets address the questions
Question 1: Do erlang, python and haskell lose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT?
In Haskell, using Integer
is slower than Int
but how much slower depends on the computations performed. Luckily (for 64 bit machines) Int
is sufficient. For portability sake you should probably rewrite my code to use Int64
or Word64
(C isn't the only language with a long
).
Question 2: Why is haskell so slow? Is there a compiler flag that turns off the brakes or is it my implementation? (The latter is quite probable as haskell is a book with seven seals to me.)
Question 3: Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.
That was what I answered above. The answer was
0) Use optimization via -O2
1) Use fast (notably: unbox-able) types when possible 2) rem
not mod
(a frequently forgotten optimization) and 3) worker/wrapper transformation (perhaps the most common optimization). Question 4: Do my functional implementations permit LCO and hence avoid adding unnecessary frames onto the call stack?
Yes, that wasn't the issue. Good work and glad you considered this.
I am using java scanner to read input from System.in. I need to read alpha-numeric line including space/tab but not the new-line and should not allow empty input as well.
For example :
a new name
or
a-new-name-1
Here is my scanner:
Scanner reader = new Scanner(System.in);
I tried these ways:
String name = reader.nextLine();
or
String name = reader.next("^[A-Za-z0-9- ]+$");
or
name = reader.next("/^[a-z\\d\\-_\\s]+$/i");
For last 2 cases with input "a test name 1" , I had error:
Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.next(Scanner.java:1418) ............
And when used reader.nextLine(),it's skips waiting for next input.For example:
For this part of the code:
System.out.println("Do you want to update audience name?[y/n]"); opt = reader.next().trim(); if( opt.equalsIgnoreCase("y") ) { System.out.println("Enter audience name : "); name = reader.nextLine(); } System.out.println("Do you want to update audience description?[y/n]"); opt = reader.next().trim(); if( opt.equalsIgnoreCase("y") ) { System.out.println("Enter audience description : "); description = reader.nextLine(); }
I am seeing this:
Do you want to update audience name?[y/n] y Enter audience name : Do you want to update audience description?[y/n] y Enter audience description : Do you want to update audience rule?[y/n]
May I get any help here?
FOllow Jonny Henly's suggestion. Mixing up of reader.next and reader.nextLine was the problem.
The code below is adapted from the answer here: https://stackoverflow.com/a/17579889/352552
My purpose in asking this question is try to to understand better how C++ handles type resolution around dependent types, versus what's considered to be on the current instantiation, and therefore not needing a typename
qualifier. I've been getting contradictory results from different compilers, so I've come here looking for a more canonical answer.
Consider this code
#include struct B { typedef int result_type; }; template struct C { }; template<> struct C { typedef float result_type; }; template struct D : B, C { std::string show() { //A) Default to current instantiation - ignore dependent type, even if one exists, or so I hope D::result_type r1; //B) What **exactly** does typename add, here? //typename D::result_type r1; return whichType(r1); } std::string whichType (int val){ return "INT"; } std::string whichType (float val){ return "FLOAT"; } }; int main() { D stringD; D floatD; std::cout<<"String initialization "< std::cout<<"Float initialization "<}
line A) in show()
, if I understand correctly, tells the compiler to use the current instantiation, so I should get INT INT. On GCC, I do. So far, so good.
Line B, again if I understand correctly, should either tell the compiler to consider dependent types, which would make that line error out because of the ambiguity; or, if that means only consider dependent types, I should get INT FLOAT. On GCC I get INT INT there, too. Why?
Running this on Clang.
Line A doesn't compile at all.
error: no type named 'result_type' in 'D'; did you mean simply 'result_type'? D::result_type r1;
dropping the D::
does indeed yield INT INT.
Should it have compiled, or is Clang correct here?
Line B does indeed error on the ambiguity
error: member 'result_type' found in multiple base classes of different types typename D::result_type r1
Can anyone here say with authority which compiler (if any!) is canonically correct, and why?
Assuming Clang is correct, it might imply that
MyType::F
is invalid for referencing a type from the current instantiation if it exists on a base type; it's only valid if the type is defined on that class. Ie adding
typedef double dd;
to D
and then
D::dd d = 1.1; std::cout<
in show
would work just fine, which is indeed the case.
Moreover,
typename D::sometype
seems to mean consider dependent types, but not exclusively, and so expect errors if such a type winds up defined in multiple places, either in the current instantiation, and or dependent on a template parameter.
But again, this all assumes Clang's behavior is correct according to spec, which I can't speak to.
Link to GCC repl I was using:https://wandbox.org/
Link to Clang repl I was using:https://repl.it/languages/cpp11
I don't think the heading quite explained it sufficiently.
Basically I have a list containing all of the vowels and another list containing the characters that make up the word.
I need to take the list containing the word and take all of the characters up to the first vowel and add them onto the end in order.
What I can't wrap my head around is how to do it, I had two ideas:
for characters in word: if(character != vowel): vCount += 1 else: break break for i in range(vCount): print(i) wList.append(wList.pop(i))
And another that was basically the same but every time it saw it wasn't a vowel it pop'd it out. The obvious issue I didn't see with these initially is that 'vowel' isn't just a singular entity, character doesn't equal a, pop, character doesn't equal e, pop, etc etc. Or in the case of vCount, it just got far longer than the actual length of wList.
Anyone have a thought on how to solve this?
EDIT: Sorry, that wasnt clear:
cat -> atc
bear -> earb
I just learned how to use the malloc function, and my teacher mentioned that it's necessary to make a type cast when passing the memory address to the pointer. For example, here's a code to get 16 new bytes allocated (4 ints) using malloc:
#include int main(){ int *p; p = (int *)malloc(4*sizeof(int)); return 0; }
My question: is the (int *) cast on the right side of the attribution necessary? After all p is already a pointer to ints, so the pointer arithmetic should work fine even without that cast.
Thanks
You only need the cast if you are using malloc in C++ code.
For C it's preferable to not use the cast as it is (a) unnecessary and (b) can mask problems that would otherwise be reported by the compiler.
select column1,column2,column3 from table1 where column5=0 and column6=0;
select column4 from table2 where column5=0 and column6=0;
These are two sql statements reading data from table1 & table2, is there a way instead of 2 single queries, can i write in a single query?
Thanks.
You could use UNION
to combine the results:
SELECT column1, column2, column3, NULL AS column4 FROM table1 WHERE column5 = 0 AND column6 = 0 UNION SELECT NULL AS column1, NULL AS column2, NULL AS column3, column4 FROM table2 WHERE column5 = 0 AND column6 = 0
I got curious about the 'throws' clause and wrote the following piece of code (I use Eclipse with Java7). Originally I had started with only blocks 1 and 5 (expecting a compilation error, which did not occur...) and then this led me to writing the other blocks.
// 1 public void throwNPE() { throw new NullPointerException(); } // 2 public void throwNPEWithGenericClause() throws Exception { throw new NullPointerException(); } // 3 public void throwNPEWithNPEClause() throws NullPointerException { throw new NullPointerException(); } // 4 public void throwNPEWithIAEClause() throws IllegalArgumentException { throw new NullPointerException(); } // 5 public void callThrowNPE() { throwNPE(); } // 6 public void callThrowNPEWithGenericClause() { throwNPEWithGenericClause(); // COMPILATION ERROR } // 7 public void callThrowNPEWithNPEClause() { throwNPEWithNPEClause(); } // 8 public void callThrowNPEWithIAEClause() { throwNPEWithIAEClause(); }
To be honest I would have expected:
(a) a compilation error in 1. (unhandled exception? shouldn't my method notify any 'subsequent caller' that this is going to throw some kind of exception?)
(b) some kind of problem in 4. (possibly a compilation error? I'm throwing a NPE while the clause says IAE)
(c) compilation errors in 5. 6. 7. and 8. (unhandled exceptions? I'm omitting the 'throws' clause)
(d) perhaps someone could also tell me why 6. is the only one where I got the compilation error...
RuntimeException is unchecked, so compiler does not warn when you throw a exceptions subclass of RuntimeException . If you need compiler to warn you, then you should use Exception or its subclasses.
1) NullPointerException extends RuntimeException
so compiler does not give any error.
2) Even though your method throws NullPointerException, since you marked the method with throws Exception , compiler warns you to catch it in it's callers.
3) Same as 1st answer
4) Same as 1st answerIllegalArgumentException extends RuntimeException
5) throwNPE does not throw anything at all.
6) Eventhough you throw a NullPointerException (RuntimeException) within throwNPEWithGenericClause, since you mark the method as checked exception, compiler does not allow.
7, 8) Same as 1st answer. Both runtime exceptions, no need to check.
I would like to insert a string into an array at a specific index. How can I do that?
I tried to use push()
Well, thats pretty easy. Assuming you have an array with 5 objects inside and you want to insert a string at index 2 you can simply use javascripts array splice method:
var array = ['foo', 'bar', 1, 2, 3], insertAtIndex = 2, stringToBeInserted = 'someString'; // insert string 'someString' into the array at index 2 array.splice( insertAtIndex, 0, stringToBeInserted );
Your result will be now:
['foo', 'bar', 'someString', 1, 2, 3]
FYI: The push() method you used just adds new items to the end of an array (and returns the new length)
I am hoping to receive guidance on how to pass a mySQL stored procedure Javascript form data to use as parameters in a query.
I have been searching for an answer on how to use mySQL stored procedures with javascript form data as parameters.
This is what I have thus far:
var first_name = req.body.firstName, last_name= req.body.lastName, email= req.body.email, password= req.body.password, gpa= req.body.gpa, major = req.body.major, classification= req.body.classification; var query = connection.query("CALL new_student()", function (err, result) { if (err) { res.send(err); } res.json(result); })
Here is the stored procedure:
CREATE DEFINER=`root`@`localhost` PROCEDURE `new_student`(IN first_name VARCHAR(45), IN last_name VARCHAR(45), IN email VARCHAR(45), IN password VARCHAR(45), IN gpa DECIMAL(3,2), IN major INT(10), IN classification VARCHAR(45)) BEGIN INSERT INTO users (first_name, last_name, email, password) VALUES (first_name, last_name, email, password); INSERT INTO student (user_id, gpa, major, classification) VALUES (LAST_INSERT_ID(),gpa, major, classification); END
My intention is to take the variables, or a Javascript object that encapsulates the variables, and pass them in through "new_student()."
I am aware this may seem trivial. I am in the process of learning how to use stored procedures with Javascript.
You need to provide arguments to the function. If you're using the node-mysql-native you can provide the parameters using syntax like a prepared statement.
var query = connection.query("CALL new_student(?, ?, ?, ?, ?, ?, ?)", [first_name, last_name, email, password, gpa, major, classification], function (err, result) { if (err) { res.send(err); } res.json(result); })
For more information about this, see Preventing SQL injection in Node.js
During the course of the film, it is explained that Bane has to wear his mask in order to keep his pain level down to a bare minimum.
During the final fight, we see Batman start to disable this device by disconnecting some of the piping on it.
What kind of device is this exactly and is there a real-world equivalent that causes the same effects?
I don't think I really answered the original question. Regarding real-life variations on Bane's mask, the following snippet can be found on wikipedia:
Other gases or vapors which produce general anesthesia by inhalation include nitrous oxide, cyclopropane and xenon. These are stored in gas cylinders and administered using flow meters, rather than vaporizers
I found a couple of real world images that struck a chord - the first looks like the masks worn in Batman Begins (in shape only, not in function)
and the second image is of a concept mask for firefighters which could be attached to gas cylinders. I have to say though, that no cylinders were apparent on Bane's costume.
PHP 7, which will come out in November this year will introduce the Spaceship (<=>) operator. What is it and how does it work?
This question already has an answer in our general reference question about PHP operators.
The <=>
("Spaceship") operator will offer combined comparison in that it will :
Return 0 if values on either side are equal Return 1 if the value on the left is greater Return -1 if the value on the right is greater
The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <
, <=
, ==
, >=
and >
. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.
//Comparing Integers echo 1 <=> 1; //output 0 echo 3 <=> 4; //output -1 echo 4 <=> 3; //output 1 //String Comparison echo "x" <=> "x"; //output 0 echo "x" <=> "y"; //output -1 echo "y" <=> "x"; //output 1
In addition to labeling a directory as a Python package and defining __all__
, __init__.py
allows you to define any variable at the package level. Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic "flat is better than nested" philosophy.
An example Here is an example from one of my projects, in which I frequently import a sessionmaker
called Session
to interact with my database. I wrote a "database" package with a few modules:
database/ __init__.py schema.py insertions.py queries.py
My __init__.py
contains the following code:
import os from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine(os.environ['DATABASE_URL']) Session = sessionmaker(bind=engine)
Since I define Session
here, I can start a new session using the syntax below. This code would be the same executed from inside or outside of the "database" package directory.
from database import Session session = Session()
Of course, this is a small convenience -- the alternative would be to define Session
in a new file like "create_session.py" in my database package, and start new sessions using:
from database.create_session import Session session = Session()
Further reading There is a pretty interesting reddit thread covering appropriate uses of __init__.py
here:
http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/
The majority opinion seems to be that __init__.py
files should be very thin to avoid violating the "explicit is better than implicit" philosophy.
I have a PHP array as follows:
$messages = [312, 401, 1599, 3, ...];
I want to delete the element containing the value $del_val
(for example, $del_val=401
), but I don't know its key. This might help: each value can only be there once .
I'm looking for the simplest function to perform this task, please.
Using array_search()
and unset
, try the following:
if (($key = array_search($del_val, $messages)) !== false) { unset($messages[$key]); }
array_search()
returns the key of the element it finds, which can be used to remove that element from the original array using unset()
. It will return FALSE
on failure, however it can return a false-y value on success (your key may be 0
for example), which is why the strict comparison !==
operator is used.
The if()
statement will check whether array_search()
returned a value, and will only perform an action if it did.
In The Fountain (2006) there are three separate but related stories told in parallel--Imperial Spain, present day, and .. um, space bubble. Hugh Jackman and Rachel Weisz play the leading lad and lady in each.
Can we consider space bubble "Tom" to be one and the same with present-day "Tommy" after some years have passed? Or is it more symbolic just as Imperial Spain "Tomas" was an envisioning of Izzy's novel?
I ask because it is possible that the doctor/researcher Tommy, who towards the end declares that "Death is a disease", actually manages to find the cure. He could then become immortal and eventually take Izzy's tree in the space bubble to Xibalba.
The linking of these two story threads explains Tom's visions of Izzy amongst other things. However I also feel it betrays the message I got from the film--namely that we cannot win against death--and that at the end Tommy accepted Izzy's passing and stopped his search for a cure for death.
I think that could be reading too much into it and drawing conclusions that are not there. However, that is not to say that isn't the director's intentions as the whole movie is one big symbolic piece.
The way it plays out to me is that the movie is suppose to represent these 2 lovers intertwined in destiny and almost cursed to play out the same role of loving man and dying woman for eternity, no matter the time period.
I need to check the checked
property of a checkbox and perform an action based on the checked property using jQuery.
For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.
But the following code returns false
by default:
How do I successfully query the checked
property?
What is the difference between returning IQueryable
vs. IEnumerable
?
IQueryable custs = from c in db.Customers where c.City == "" select c; IEnumerable custs = from c in db.Customers where c.City == "" select c;
Will both be deferred execution and when should one be preferred over the other?
Yes, both will give you deferred execution .
The difference is that IQueryable
is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable
, that query will be executed in the database, if possible.
For the IEnumerable
case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.
In code:
IQueryable custs = ...; // Later on... var goldCustomers = custs.Where(c => c.IsGold);
That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:
IEnumerable custs = ...; // Later on... var goldCustomers = custs.Where(c => c.IsGold);
This is quite an important difference, and working on IQueryable
can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take
and Skip
on IQueryable
, you will only get the number of rows requested; doing that on an IEnumerable
will cause all of your rows to be loaded in memory.
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
using namespace std; So far in my computer science courses, this is all we have been told to do. Not only that, but it's all tha...