• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

In addition to the other responses I think it's good to consider the statement in detail. The statement can be deconstructed into three separate parts:

Code:
i for
i, prime in enumerate(is_prime)
if prime

Thank you very much for breaking this down. In my mind I was seeing
Code:
i for i,
as being part 1, and the rest as part 2. The rest of your explanation is also great.
 
Does anyone here have any experience using Xamarin? I'm considering developing a booking Android app as part of my degree's final year project and seeing I don't have much experience in Java, it looks like a viable alternative. I'm a lot more familiar with C# so it seemed sensible to try it out first.
 

Moosichu

Member
I've just finished my first year in CS at Uni, and starting to really find a flow and rythm to programming so I'm really hoping to start hanging around here more to learn and (hopefully, once I get good enough) help.

At the moment, for my internship I am working on developing a game for the Raspberry Pi foundation to teach people how to program in Python called Pyland. It was started a year ago for 10 weeks ago by another group of interns. At the moment I am trying to implement a system which should allow us to create and program all of our actual game content in Python and Tiled which should allow us not have to recompile C++ code half the time. The only problem is I have never used C++ before and don't really know what I am doing.

This is the link to the current fork/branch that I am working on.

The problem I am encountering now, is that I am trying to make it so that Python methods can be passed to C++ objects, put on the event queue and run. (Which would allow the engine to notify the python code when an event has completed for example)

This is an example of python code you would use:

Code:
boulder_one.callback_test(lambda: print("SSSS"))

The following works fine as expected:

Code:
void Entity::callback_test(PyObject* callback) {
	boost::python::object o(boost::python::handle<>(boost::python::borrowed(callback)));
	o();

But when I try to pass the object to to the event queue and it is run from there, a seg fault occurs, which I assume is because the object is destructed (although I am a C++ newbie so have no idea really what could be going on).

Here is a wiki page on the event system of the game engine.

I've also be using Jason Gregory's book on Game Engines as a reference and it is brilliant.

This is a bit of a long post, if there any workarounds anyone could think of that would be great! If I also work out a fix I will post a follow-up here as well. I really feel like such a beginner and really am trying to code well but am so sure I am doing to much wrong like a clumsy oiled up piece of soap-person in the dark, so I am hoping to learn loads! :)

EDIT: Just discovered Handmade Hero, those videos are awesome!
 
Having a bit of a problem. Let me try and break this down:

Compressed data is held in a database
It is decompressed in a C++ algorithm
I want to display the decompressed data with a Java front-end display.
So I need to transfer via sockets
I am experimenting but don't really know how to work TCP IP sockets
I have an executable booted on my end that is suppose to send a request to the C++, pull the decompressed data, and send it back.
The request is formatted as a String like "Date Time.."
I assume I type my request in the Command Line Prompt

I hope I am clear with this.
 

Acrylic7

Member
Ok, so I'm completely new to programming. And by new I mean I don't even now what I'm looking at. Everything I see is Matrix Hieroglyphics.

After reading some links in the OP it seems as though I should start with C# or Python. But after reading a few pages it seems like some Gaffers recommend starting with C++.

I want to get my foot into Game programming. I'm mostly into art but I'm at the point where I think I should know a thing or two about code instead of just art. I think this would help me out a lot.
Id like to hear more Gaf opinions about where I should start.
Where should I begin and how?
 
But when I try to pass the object to to the event queue and it is run from there, a seg fault occurs, which I assume is because the object is destructed (although I am a C++ newbie so have no idea really what could be going on).

C++ won't destroy (i.e. call the destructor of) an object so long as it's in scope (which basically means there's still some variable representing/pointing to the object). I'm not too familiar with Boost's Python library (go Cython!), but I'd look at how you're returning the object to the event queue, and maybe if/when the PyObject being passed to the function is being freed (Boost's Python library could expect that pointer to be accessible at the time of the actual callback, which might not be true once you're back in the main event handler).

Having a bit of a problem. Let me try and break this down:

Compressed data is held in a database
It is decompressed in a C++ algorithm
I want to display the decompressed data with a Java front-end display.
So I need to transfer via sockets
I am experimenting but don't really know how to work TCP IP sockets
I have an executable booted on my end that is suppose to send a request to the C++, pull the decompressed data, and send it back.
The request is formatted as a String like "Date Time.."
I assume I type my request in the Command Line Prompt

I hope I am clear with this.
Sounds logical; what are you asking for information about? The input method to your Java program is really up to you; you could have it take input from the command line while executing, a list from a file, or even host it as a JSON-RPC server. You could use a cleaner IPC method if the Java/C++ programs will both be run locally, but if you're familiar on how to bind to/listen on a socket just go with that. Alternatively, port the algorithm over to Java (or find a snippet that has) and avoid the pains of message handling entirely.

Id like to hear more Gaf opinions about where I should start.
Where should I begin and how?
Start with Python or C# (I think the latter would be better for UE4 and the like, but I honestly don't know here), and move into C++ once you've got that in your pocket.

Does anyone here have any experience using Xamarin? I'm considering developing a booking Android app as part of my degree's final year project and seeing I don't have much experience in Java, it looks like a viable alternative. I'm a lot more familiar with C# so it seemed sensible to try it out first.
I used it for a semester, it was alright. I think that Eclipse might better serve you for Android development considering all the extra packages it has to support it, but Xamarin might have what you need as well.
 

Moosichu

Member
C++ won't destroy (i.e. call the destructor of) an object so long as it's in scope (which basically means there's still some variable representing/pointing to the object). I'm not too familiar with Boost's Python library (go Cython!), but I'd look at how you're returning the object to the event queue, and maybe if/when the PyObject being passed to the function is being freed (Boost's Python library could expect that pointer to be accessible at the time of the actual callback, which might not be true once you're back in the main event handler).

Thanks, the more I look at solving the problem, the more I think trying to use whatever the hell GilSafeFuture is will make things more difficult than they need to be. Especially when the only comment in those files is:
Code:
// TODO: Comment such that this mess makes sense.
:/ (You can tell which code was written in a rush really easily :p )

I have made some progress though! :)

I have also learnt the magic of GDB a lot, and have now resorted to putting the python callbacks straight onto the event queue.

Now the code looks as follows:

Python:
Code:
boulder_four.callback_test(lambda: print("Hello World!!!!!"))

The C++ implementation:
Code:
void Entity::callback_test(PyObject *callback) {
	boost::python::object boost_callback(boost::python::handle<>(boost::python::borrowed(callback)));
	//GilSafeFuture<void>::execute([boost_callback] (GilSafeFuture<void>) {
	//	PyGILState_STATE state = PyGILState_Ensure();
	//	boost_callback();
	//	PyGILState_Release(state);
	//});
	EventManager::get_instance().add_event([boost_callback] () {
		LOG(INFO) << "PP";
		PyGILState_STATE state = PyGILState_Ensure();
		boost_callback();
		LOG(INFO) << "PPP";
		PyGILState_Release(state);
		LOG(INFO) << "PPPP";
	});
}

How the events are processed (not written by me, except for the temporary log stuff I placed so I could work out what is going on)

Code:
void EventManager::process_events() {
	// We need to process all the events in the queue
	// Problem is that, when events are being processed, they can add
	// further events. If we have the lock on the lock_guard in the
	// process loop when this happens, then we cannot add the new event
	// and so the thread blocks and the lock is never released
	//
	// So, we need to extract an event from the queue, lock the queue
	// to do this. We then release the lock and process the event.
	// We then repeat the process until the entire queue is finished
	//
	while (true) {
		LOG(INFO) << "locating segfault";
		//The callback function we need to process
		std::function<void ()> func;

		//The lock_guard is exception safe and releases the mutex when
		//it goes out of scope. So we introduce scope here to release
		//the mutex once we've pulled the event from it.
		{
			//Lock the list
			std::lock_guard<std::mutex> lock(queue_mutex);

			//If the queue is empty, exit this processing
			if(curr_frame_queue->empty()) {
				//This is safe as we have the lock
				std::swap(curr_frame_queue, next_frame_queue);
				break;
			}

			//Get the first element in the list
			//We've locked the queue so it will definitely have an item
			func = curr_frame_queue->front();
			curr_frame_queue->pop_front();
		} // Lock released

		//Dispatch the callback
		if(func) {
			LOG(INFO) << "Doing Thing!";
			func();
			LOG(INFO) << "Done the Thing!";
		}
		else {
			LOG(ERROR) << "ERROR in event_manager.cpp in processing, no function";
		}
		LOG(INFO) << "Done Done the thing!!!";
	}
}

And finally what is printedby gdb:

Code:
I0722 11:15:03.712662  6395 event_manager.cpp:101] Doing Thing!
I0722 11:15:03.712669  6395 entity.cpp:41] PP
Hello World!!!!!
I0722 11:15:03.712800  6395 entity.cpp:44] PPP
I0722 11:15:03.712816  6395 entity.cpp:46] PPPP
I0722 11:15:03.712827  6395 event_manager.cpp:103] Done the Thing!
I0722 11:15:03.712836  6395 event_manager.cpp:108] Done Done the thing!!!

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff680d900 in ?? () from /usr/lib/x86_64-linux-gnu/libpython3.4m.so.1.0

So as you can see, the callback is succesfully being run to completion, and the end of a pass in the while loop is being reached, but "locating segfault" is never printed from the event manager. On looking up the error, it seems to have something to do with the GIL when the object destructs.

It's also worth pointing out that now the segfault only occurs sometimes now, which is progress!!! :D Let's just hope the next few hours are fruitful :)
 
I used it for a semester, it was alright. I think that Eclipse might better serve you for Android development considering all the extra packages it has to support it, but Xamarin might have what you need as well.

I've actually decided on trying the Android SDK now. I don't have much experience in Java but the Android tutorials have been really useful and I have quite a bit of experience with C++. I also discovered the Xamarin size limit for the free version which could cause problems depending on how large my app ends up being.

Learning another language and creating something I haven't attempted before should hopefully be enough complexity for a final year project. I just need to nail the problem area now and make a final decision on what it should try to solve.
 

Moosichu

Member
Got what I wanted to achieve working!

The segfaults were happening because the python function was going out of scope and destructing without the GIL being held.

My quick hacky workaround was:

Quick class definition (thanks stackoverflow)
Code:
class gil_lock
{
public:
  gil_lock()  { state_ = PyGILState_Ensure(); }
  ~gil_lock() { PyGILState_Release(state_);   }
private:
  PyGILState_STATE state_;
};

Then I just put
Code:
gil_lock lock; //see comments of class defined above

In the while loop :) All is working. Now I can just push arbitary python functions to the C++ event queue :D

There are still some odd quirks, like database connections closing unexpectedly (I think that's what it is anyway), but they can be worked around. :) I'm really happy, now all I need to do is work out the best way to make this code clean.
 

Ether_Snake

安安安安安安安安安安安安安安安
I got the Swiftly app to learn to code in Swift, but I'm on Windows. Any recommendation? I'm guessing I could find a web-based compiler or some such?
 

Anustart

Member
So, I dunno why this is being so damn difficult, but I can't figure it out.

I'm working with c# and trying to get values out of an xml file.

Code:
IEnumerable<XElement> myPlayers =
                from myP in pElements.Elements("Player")
                where (string)myP.Element("Name") == pNameCombo.SelectedItem.ToString()
                select myP;

I use that to select the correct Player element from the file, but then I can't figure out how to get the other data from myPlayers.


Each player has multiple elements with data and I don't know how to get at it. As an example I have <PlayerName>myName</PlayerName> for each player.

How can I get at that from myPlayers? Am I doing this all wrong?

To be more exact:

Code:
<Player>
    <Name>PoopNUG</Name>
    <PlayerTag>DANKMEMES</PlayerTag>
    <StartStats>
      <StartNum>2</StartNum>
      <LastUpdated>2015-07-24T22:21:30.5463885-05:00</LastUpdated>
    </StartStats>
    <CurrentStats>
      <CurrentNum>3</CurrentNum>
      <LastUpdated>2015-07-24T22:21:30.5463885-05:00</LastUpdated>
    </CurrentStats>
  </Player>

With many players. I need to find a player by name, then get each element of that player, by name, and it's value. I've tried so many damn things, it's fucking irritating why this is so damn difficult.
 
So, I dunno why this is being so damn difficult, but I can't figure it out.

I'm working with c# and trying to get values out of an xml file.

Code:
IEnumerable<XElement> myPlayers =
                from myP in pElements.Elements("Player")
                where (string)myP.Element("Name") == pNameCombo.SelectedItem.ToString()
                select myP;

I use that to select the correct Player element from the file, but then I can't figure out how to get the other data from myPlayers.


Each player has multiple elements with data and I don't know how to get at it. As an example I have <PlayerName>myName</PlayerName> for each player.

How can I get at that from myPlayers? Am I doing this all wrong?

To be more exact:

Code:
<Player>
    <Name>PoopNUG</Name>
    <PlayerTag>DANKMEMES</PlayerTag>
    <StartStats>
      <StartNum>2</StartNum>
      <LastUpdated>2015-07-24T22:21:30.5463885-05:00</LastUpdated>
    </StartStats>
    <CurrentStats>
      <CurrentNum>3</CurrentNum>
      <LastUpdated>2015-07-24T22:21:30.5463885-05:00</LastUpdated>
    </CurrentStats>
  </Player>

With many players. I need to find a player by name, then get each element of that player, by name, and it's value. I've tried so many damn things, it's fucking irritating why this is so damn difficult.

It's irritating because XML is fucking garbage. I strongly suggest you quit before you get too far locked into this, and switch to using JSON as your storage format and JSON.NET as the assembly you use to read and write json.
 

Slavik81

Member
It's irritating because XML is fucking garbage. I strongly suggest you quit before you get too far locked into this, and switch to using JSON as your storage format and JSON.NET as the assembly you use to read and write json.
As much as I agree that JSON is a nicer format than XML, I don't really see how it would make a difference here. The data would look basically identical in JSON, and I presume he'd be left with more or less the same question.

What's better about JSON.NET vs whatever he's using?
 

poweld

Member
Spent some time this weekend doing some puzzle solving in Clojure in order to learn the language. It's interesting, but I still don't think that I'd ever be able to be as quick at writing code in Clojure than in Scala.

Also, lispy postfix logic gates become confusing much more quickly to me than infix notation, despite my best efforts.
 
As much as I agree that JSON is a nicer format than XML, I don't really see how it would make a difference here. The data would look basically identical in JSON, and I presume he'd be left with more or less the same question.

What's better about JSON.NET vs whatever he's using?

The difference is that JSON.NET is ridiculously smart. It makes very clever use of reflection and C# attributes to create a library such that for most basic scenarios, you have to write zero parsing code. Really. For example, let's convert his xml fragment to json.

Code:
<players>
  <Player>
    <Name>PoopNUG</Name>
    <PlayerTag>DANKMEMES</PlayerTag>
    <StartStats>
      <StartNum>2</StartNum>
      <LastUpdated>2015-07-24T22:21:30.5463885-05:00</LastUpdated>
    </StartStats>
    <CurrentStats>
      <CurrentNum>3</CurrentNum>
      <LastUpdated>2015-07-24T22:21:30.5463885-05:00</LastUpdated>
    </CurrentStats>
  </Player>
<players>

vvvv

Code:
`players` : [
    {
        'name': 'PoopNUG',
        'tag': 'DANKMEMES',
        'start_stats': {
            'num': 2,
            'last_updated': '2015-07-24T22:21:30.5463885-05:00',
        },
        'current_stats': {
            'num': 3,
            'last_updated': '2015-07-24T22:21:30.5463885-05:00',
        }
    },
]

With JSON.NET, you define a C# class hierarchy to store the data in. Like this:

Code:
class JsonData
{
    [JsonProperty("players")]
    public List<Player> players;
}

class Player
{
    [JsonProperty("name")]
    public string name;

    [JsonProperty("tag")]
    public string tag;

    [JsonProperty("start_stats")]
    public Stats start_stats;

    [JsonProperty("current_stats")]
    public Stats current_stats;
}

class Stats
{
    [JsonProperty("num")]
    public uint number;

    [JsonProperty("last_updated")]
    public string last_updated; 
}

This is something you will probably have to do in some way, shape, or form anyway when using XML unless you plan to do ad-hoc processing of every xml fragment on the fly, which is generally not what you're going to be doing. Notice so far no parsing code. Just some attributes mapping class fields to json fields.

Then, to parse the JSON, is exactly one line of code.

Code:
string JsonText = /*Get the text from a file or something*/;
Data data = JsonConvert.DeserializeObject<Data>(JsonText);

And done.

All the logic of data type conversion, parsing, etc is internal to the library. It is flexible enough to support many different use cases though. For example, you'll see that I stored last_updated as a string. You could instead write something like this:

Code:
    [JsonProperty("last_updated")]
    [JsonConverter(typeof(StringToDateTime))]
    public DateTime last_updated;

Where StringToDateTime is a class you provide which implements a certain interface, so JSON.NET will call back into it to do the conversion before writing the value into last_updated.

The XML library built into .NET *could* have done this. But instead they built the absolute worst interface to XML imaginable that even after being forced to use probably 10-15 times for interoperability, I still stumble on and have to spend an hour or so re-learning the library every time I use it, and littering up my application with shit parsing code. JSON.NET is just easy. The parsing is invisible. Declare your class and you're done.
 

Moosichu

Member
Has anyone here used jsonnet before? That might worth a look into. I've been playing around with it for the current project and it is quite cool.

https://google.github.io/jsonnet/doc/

Although documentation isn't briliant, I'm still trying to work out how to link it into the current project we are working on as I have never used Makefiles before and that is what we are using :p
 
The difference is that JSON.NET is ridiculously smart. It makes very clever use of reflection and C# attributes to create a library such that for most basic scenarios, you have to write zero parsing code. Really. For example, let's convert his xml fragment to json.

...snip...

The XML library built into .NET *could* have done this. But instead they built the absolute worst interface to XML imaginable that even after being forced to use probably 10-15 times for interoperability, I still stumble on and have to spend an hour or so re-learning the library every time I use it, and littering up my application with shit parsing code. JSON.NET is just easy. The parsing is invisible. Declare your class and you're done.

It's very similar to the Jackson ObjectMapper for Java. It's extremely fast, uses POJOs to generate the JSON, and is incredibly easy to use. Once I switched to JSON I never wanted to see XML again in my life.
 
I'm trying to get a scrabble game going in Python.

I randomly generate a hand, and store the hand as a dictionary with integers being paired with the letters. So something like {'a': 1, 'b': 0, 'c': 2', etc...} would represent the hand a,c,c,etc...

Now when a player enters a word, one of the checks for legality of the word goes into the values of the dictionary and changes them by -1. If the value of a letter would go below 0 during this process, then that means the player tried using a letter that they didn't have in hand.

My problem was that this checking process would mutate the hand. So if they entered "cat" and didn't have a t in hand, it would correctly reject the word, but still subtract a c, and an a. Resulting in the hand being c,etc... rather than the a,c,c, etc... I started with.

One solution I found was to have the function that checks for legality perform the check with a copy of the hand made using a hand.copy() function. But how exactly would I go about making a copy without this built-in-function? Setting a new variable equal to hand doesn't help, because if a and b are assigned to the same object and the object is mutable then a change in the value of the object alters it for a and b.
 
deepcopy?

I'm more looking for ways to do this without any sort of function. Or I suppose how do I manually do what .copy() does in python.

Or is this something I don't need to know how to do? Do other programming languages have that feature of python, where a change in a will change b if they are assigned to the same mutable object?
 

luoapp

Member
I'm more looking for ways to do this without any sort of function. Or I suppose how do I manually do what .copy() does in python.

Or is this something I don't need to know how to do? Do other programming languages have that feature of python, where a change in a will change b if they are assigned to the same mutable object?

In C/C++, that's "pass by value", or "by reference". Of course you can write your own deepcopy() as a small exercise, but I think just understanding the concepts and knowing when to use which are good enough.
 

Water

Member
I'm more looking for ways to do this without any sort of function. Or I suppose how do I manually do what .copy() does in python.
I think what you're actually looking for is how to do it on a more fine-grained level than calling a single function? Python code has to call at least some function(s) in order to accomplish anything useful.

A simple answer (for your dictionary example case) is to create a new empty dictionary, go through every key-value pair in the existing dictionary, and add an identical key-value pair in the new dictionary.
 

Admodieus

Member
I'm not a full time developer by any means, but I feel like I have a decent handle of Java (outside of the really advanced stuff) and even shipped an Android app this past year. Looking to get on the C train and eventually build towards Objective-C for iOS stuff.

Anybody have recommendations on books that might be good for this skill level - not a beginner with programming, but definitely haven't messed around with pointers extensively before.
 

injurai

Banned
Alright, tell me about Ruby. I feel it's the language I'm least familiar with. So it's designed by someone who was coming from C++, it's an interpreted oo-scripting language correct?

I've heard there are series issues with it, but I'm not sure if that is referencing rails or the core ruby language. I know it's supposed to be a really nice language to code in, but I guess in the web stack or something (rails?) it becomes a nightmare. Or does the language just have poor hooks for testing and debug frameworks?

I'm not really sure. I'm fascinated by the language. It seems to sit in an interesting place. I often hear it recommended for people to start out programming in. I've usually always put myself into the path of most resistance thinking it would help me. But I'm kind of in the mood to taste from something different.

:edit - To briefly clarify, I tend to prefer compiled languages. But I'd like pick up a good scripting language (python, ruby, etc.) to add to my repertoire. I use bash daily at my job, I kind of hate it.
 

Massa

Member
Ruby is very much Smalltalk influenced. It's the opposite of C++.

Rails is what made it become a popular language. I've worked on a couple of projects (with Rails) and they were great, much better than the web stuff I've had to put myself through in Java.
 

injurai

Banned
Maybe the main thing I've heard is Ruby on Rails has major scalability issues. I guess that is a concern for large corporate enterprises. I guess I had just heard enough cons that I've strayed away from it. And in doing so I feel like I shut myself out from an important facet of the industry.
 
I'm trying to get a scrabble game going in Python.

I randomly generate a hand, and store the hand as a dictionary with integers being paired with the letters. So something like {'a': 1, 'b': 0, 'c': 2', etc...} would represent the hand a,c,c,etc...

Now when a player enters a word, one of the checks for legality of the word goes into the values of the dictionary and changes them by -1. If the value of a letter would go below 0 during this process, then that means the player tried using a letter that they didn't have in hand.

My problem was that this checking process would mutate the hand. So if they entered "cat" and didn't have a t in hand, it would correctly reject the word, but still subtract a c, and an a. Resulting in the hand being c,etc... rather than the a,c,c, etc... I started with.

One solution I found was to have the function that checks for legality perform the check with a copy of the hand made using a hand.copy() function. But how exactly would I go about making a copy without this built-in-function? Setting a new variable equal to hand doesn't help, because if a and b are assigned to the same object and the object is mutable then a change in the value of the object alters it for a and b.

Make a totally new dictionary. Each time you encounter a letter in your word, either create a new key with <letter>: 1 if the letter wasn't in the dictionary, or increment the value by 1. At the end you have 2 dictionaries. One for the hand, and one for the word. Iterate the word dictionary by key, return false as soon as you find a key in the word dictionary whose value is greater than the corresponding value in the hand dictionary (or if the key doesn't exist in the hand dictionary).
 

wolfmat

Confirmed Asshole
But how exactly would I go about making a copy without this built-in-function?

You have a dictionary with only native types in there for both keys and values, so in that case, making a non-referential copy is easy.
Code:
hand = { 'a': 2, 'b': 3}
hand_copy = {}
for k,v in hand.items():
    hand_copy[k] = v
hand_copy['a'] = 3
assert hand_copy['a'] != hand['a']
Native values will be non-referential, so that's how you'd do it in that trivial case of yours. Not so much with deep data though. Or referential structures like objects and shit.

Mind you, a simple copy() call is easier on the reader's eyes. And most likely more efficient.
 
Make a totally new dictionary. Each time you encounter a letter in your word, either create a new key with <letter>: 1 if the letter wasn't in the dictionary, or increment the value by 1. At the end you have 2 dictionaries. One for the hand, and one for the word. Iterate the word dictionary by key, return false as soon as you find a key in the word dictionary whose value is greater than the corresponding value in the hand dictionary (or if the key doesn't exist in the hand dictionary).

You have a dictionary with only native types in there for both keys and values, so in that case, making a non-referential copy is easy.
Code:
hand = { 'a': 2, 'b': 3}
hand_copy = {}
for k,v in hand.items():
    hand_copy[k] = v
hand_copy['a'] = 3
assert hand_copy['a'] != hand['a']
Native values will be non-referential, so that's how you'd do it in that trivial case of yours. Not so much with deep data though. Or referential structures like objects and shit.

Mind you, a simple copy() call is easier on the reader's eyes. And most likely more efficient.

Thanks for the help guys. And yes, I'm going to be using a simple copy() call. I just wanted to know how I would go about doing it if for whatever reason I didn't want to use the function. Basically knowing how to do it the long way.
 

wolfmat

Confirmed Asshole
And before you ask -- making a "clone" of a referential structure is what essentially is meant when one says "deep copy". If it's an object, for instance, you'd create another instance via the constructor and run through the calls, or variable settings, or whatever is needed to be done to create what will be completely equivalent.
The deep_copy stuff in libraries usually copies on the memory level, so it builds new references, follows the references to be copied to determine values to write at the new reference memory location, that sort of thing.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
So I happen to have an iPhone and iPad but no Mac, which apparently you need to develop for the iPhone/Pad. What are the cheapest solutions?

Phonegap or some other middleware solution. (not recommended)

You could build a Hackintosh, but the cost for that would be highly dependent on what hardware you currently have and how much compliant hardware would cost.

Used Mac Mini would probably be the cheapest route.
 

msv

Member
Had a bit of a headache with SCrypt. I didn't realize it was creating different hashes for the same strings sometimes. The strings were probably too long, because I was manually concatenating them and not using the builtin salt function. Used it, now my authentication works perfectly yay :).

Also, I'm trying to monitor a folder and checking when files are changed/moved/created/deleted. The moving seems to be an issue, since Windows sees it as a delete/create. How would I go about detecting a move in that case (in a non-convoluted way)?
 
Alright, tell me about Ruby. I feel it's the language I'm least familiar with. So it's designed by someone who was coming from C++, it's an interpreted oo-scripting language correct?

I've heard there are series issues with it, but I'm not sure if that is referencing rails or the core ruby language. I know it's supposed to be a really nice language to code in, but I guess in the web stack or something (rails?) it becomes a nightmare. Or does the language just have poor hooks for testing and debug frameworks?

I'm not really sure. I'm fascinated by the language. It seems to sit in an interesting place. I often hear it recommended for people to start out programming in. I've usually always put myself into the path of most resistance thinking it would help me. But I'm kind of in the mood to taste from something different.

:edit - To briefly clarify, I tend to prefer compiled languages. But I'd like pick up a good scripting language (python, ruby, etc.) to add to my repertoire. I use bash daily at my job, I kind of hate it.

Ruby is a cool language. I use it a lot at work and it's quite nice to use. The one gripe I have with it is that there's often too many ways of doing the same thing. The language is kind of bloated with syntax. I've never really used Rails, but I've heard good things. If you want to make a small web application, you could take a look at Sinatra, which is a micro-framework similar to Python's Flask.
 
I've found a valid solution to this coding problem by using Python(2.7.9). I'm just looking for input into my style/method since I probably did a lot of unnecessary stuff. Or there might be a better way to go about this.

I have to traverse a 100k long string. I have to then find a single lowercase letter that is surrounded on both sides by EXACTLY 3 capital letters. AAAAaAAAA wouldn't be valid. It needs to be aAAAaAAAa.

I've set the 100k long string to a variable called string.

Code:
lows = ""
for i in xrange(len(string)-8):
        a = string[i:i+1] #first character in the block of 9 must be lowercase 
        guard1 = string[i+1:i+4] #set of 3 characters in the block must be capital 
        b = string[i+4:i+5] #middle letter
        guard2 = string[i+5:i+8]
        c = string[i+8:i+9]
        if a.islower() and c.islower() and guard1.isupper() and guard2.isupper() and b.islower():
            lows += b 
print lows

I feel like there's a better (more readable/faster/impressive) way of doing this all. Perhaps I don't need to take slices out of the string at all.

edit: discovered .islower() and .isupper, which makes things a bit tidier.
 
I've found a valid solution to this coding problem by using Python(2.7.9). I'm just looking for input into my style/method since I probably did a lot of unnecessary stuff. Or there might be a better way to go about this.

I have to traverse a 100k long string. I have to then find a single lowercase letter that is surrounded on both sides by EXACTLY 3 capital letters. AAAAaAAAA wouldn't be valid. It needs to be aAAAaAAAa.

I've set the 100k long string to a variable called string.

Code:
lows = ""
for i in xrange(len(string)-8):
        a = string[i:i+1] #first character in the block of 9 must be lowercase 
        guard1 = string[i+1:i+4] #set of 3 characters in the block must be capital 
        b = string[i+4:i+5] #middle letter
        guard2 = string[i+5:i+8]
        c = string[i+8:i+9]
        if a.islower() and c.islower() and guard1.isupper() and guard2.isupper() and b.islower():
            lows += b 
print lows

I feel like there's a better (more readable/faster/impressive) way of doing this all. Perhaps I don't need to take slices out of the string at all.

edit: discovered .islower() and .isupper, which makes things a bit tidier.

Hint: state machine
 
Special case you don't seem to have accounted for: what if the string starts with AAAaAAAa?

In this case I knew for a fact that it didn't. But you're correct that my solution doesn't account for that case. I think I could fix that by specifically writing a case for xrange(9).

Hint: state machine

I'll read up on this. I found this link with a quick google search and it looks promising enough.

http://blog.markshead.com/869/state-machines-computer-science/
 
Maybe the main thing I've heard is Ruby on Rails has major scalability issues. I guess that is a concern for large corporate enterprises. I guess I had just heard enough cons that I've strayed away from it. And in doing so I feel like I shut myself out from an important facet of the industry.

The scalability issues are mostly going away, Ruby has made great lengths to increase performance in the last few years, so I wouldn't really worry about it.
Many large websites like Github use Ruby on Rails and they are just fine.
I've also seen more and more programs written in Ruby like Vagrant.
It's also very helpful for automating command line tasks, a far better option to writing pure bash scripts.

Rails is nice because it allows you to build things very quickly, through the scaffolding feature and its convention over configuration design paradigm.
Projects that have taken me most of a semester to complete in PHP using Codeigniter have taken me a week in Rails.
 

Droplet

Member
I'll read up on this. I found this link with a quick google search and it looks promising enough.

http://blog.markshead.com/869/state-machines-computer-science/

You should try drawing one out. Rather than use a sliding block as you are right now, you might consider going one letter at a time and using some kind of variable to keep track of if you're fulfilling your condition or not.

Also, you should make it a habit to not name your variables after data types. "test_string", "foo", or really any other name you can come up with will be better.
 

injurai

Banned
Ruby is a cool language. I use it a lot at work and it's quite nice to use. The one gripe I have with it is that there's often too many ways of doing the same thing. The language is kind of bloated with syntax. I've never really used Rails, but I've heard good things. If you want to make a small web application, you could take a look at Sinatra, which is a micro-framework similar to Python's Flask.

The scalability issues are mostly going away, Ruby has made great lengths to increase performance in the last few years, so I wouldn't really worry about it.
Many large websites like Github use Ruby on Rails and they are just fine.
I've also seen more and more programs written in Ruby like Vagrant.
It's also very helpful for automating command line tasks, a far better option to writing pure bash scripts.

Rails is nice because it allows you to build things very quickly, through the scaffolding feature and its convention over configuration design paradigm.
Projects that have taken me most of a semester to complete in PHP using Codeigniter have taken me a week in Rails.

Thanks. Yeah, I haven't had much experience with the web stack. I know I definitely want to avoid PHP, I'm not super keen on getting deep into Javascript and all of it's revolving doors of libraries.

But I do feel I need to round myself, and I want to pick up a new scripting language. Ruby just started sounding more and more interesting to me. I had it pinned differently. But I wanted to make sure it wasn't on it's way out. I guess hearing that Matz was creating a new language sort of made me question it.

Any recommendations for books or websites? I'm not keen on blindly searching around for a heading.
 
You should try drawing one out. Rather than use a sliding block as you are right now, you might consider going one letter at a time and using some kind of variable to keep track of if you're fulfilling your condition or not.

Also, you should make it a habit to not name your variables after data types. "test_string", "foo", or really any other name you can come up with will be better.

Will keep my naming conventions in mind.

As for keeping track of some variable while going through the string I'm not really sure if anything good comes to my mind. Or at least not anything simpler to my mind than just using a sliding block. The condition that needs to be satisfied is that the string has to follow a pattern of aAAAaAAAa. Or if the condition is satisfied within the very first 8 characters of the string: AAAaAAAa.

I did look into the re module in python which allows me to search a string for the appearance of a regular expression. But that isn't the same as keeping track of some single variable.
 

Droplet

Member
Will keep my naming conventions in mind.

As for keeping track of some variable while going through the string I'm not really sure if anything good comes to my mind. Or at least not anything simpler to my mind than just using a sliding block. The condition that needs to be satisfied is that the string has to follow a pattern of aAAAaAAAa. Or if the condition is satisfied within the very first 8 characters of the string: AAAaAAAa.

I did look into the re module in python which allows me to search a string for the appearance of a regular expression. But that isn't the same as keeping track of some single variable.

Try drawing out an fsm (finite state machine) while considering each letter. If you're still stuck after that, I'll help you reason through it.
 

msv

Member
Kind of in dubio on how to design my data structures for persistence at the moment.

I have the following situation - User > Files meta data (could be a whole bunch of files, every file has one piece of meta data associated with it)

I have a client and a server and a persistence back end. Lookups are done as Key > Value. It's possible to store as JSON text to make it searchable, though I'm not in favor of that.

The server has access to the persisted data. Since it must be scalable, the server should be as stateless as possible. The problem is now, that the user will ask for all of the index and meta data with some regularity and change/update it, but also change/update or request meta data of individual files. So essentially files added/deleted (index) but also individual files altered (meta data).

I'm not sure how to persist this best.
- Store the index linking the user to all of the separate files meta data separately.
- Store the meta data combined with the index.

The first would make the lookup of the index + full meta data set much heavier (key lookup for each file, can be a lot of files per user), the second would make individual changes to files a burden (the entire meta data set would need to be changed serialized and persisted whenever any alterations are made).

In the first option, changes to the index would still be annoying. Perhaps a good option would be to prepend the id's with the user id to remove the need to maintain a separate index.

It seems like the first would be the better option to me, but I'm still bothered by the huge amount of lookups whenever the full set is requested. Is there any way to mitigate this?

Maybe it would be a good idea to use a DFS instead, store the file meta data in small individual files in a folder?
 
Kind of in dubio on how to design my data structures for persistence at the moment.

I have the following situation - User > Files meta data (could be a whole bunch of files, every file has one piece of meta data associated with it)

I have a client and a server and a persistence back end. Lookups are done as Key > Value. It's possible to store as JSON text to make it searchable, though I'm not in favor of that.

The server has access to the persisted data. Since it must be scalable, the server should be as stateless as possible. The problem is now, that the user will ask for all of the index and meta data with some regularity and change/update it, but also change/update or request meta data of individual files. So essentially files added/deleted (index) but also individual files altered (meta data).

I'm not sure how to persist this best.
- Store the index linking the user to all of the separate files meta data separately.
- Store the meta data combined with the index.

The first would make the lookup of the index + full meta data set much heavier (key lookup for each file, can be a lot of files per user), the second would make individual changes to files a burden (the entire meta data set would need to be changed serialized and persisted whenever any alterations are made).

In the first option, changes to the index would still be annoying. Perhaps a good option would be to prepend the id's with the user id to remove the need to maintain a separate index.

It seems like the first would be the better option to me, but I'm still bothered by the huge amount of lookups whenever the full set is requested. Is there any way to mitigate this?

Maybe it would be a good idea to use a DFS instead, store the file meta data in small individual files in a folder?

Can two different users be associated with the same file? If so, relational database seems like it would be fine
 
Try drawing out an fsm (finite state machine) while considering each letter. If you're still stuck after that, I'll help you reason through it.

Ok so I'm not sure if I did this correctly, but this is my fsm for checking for "aAAAa". I didn't do the last half just in case this is incorrect. Forgive the mspaint w/mouse look. Red circle is initial start point. Purple is where it ends up if we succeed in getting "aAAAa" as the pattern.

XieZpTu.png
 
Top Bottom