• 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

Swing is killing me, man. Can someone offer some tips?

I am trying to convert an ArrayList to an array so I can populate a table. My approach is this: every 22 elements, I want to populate a row in the table. However, it's not quite working. One failed attempt had me generate all of the result set but only in the first element of the table, the rest of the columns were blank. Next, my table was repeating the first row over and over, or, the first 22 elements rather than adding a new row after the 22nd element. Any advice?

Also, can I use a thread to update a table periodically, rather than doing it in one lump sum?
 

JeTmAn81

Member
Swing is killing me, man. Can someone offer some tips?

I am trying to convert an ArrayList to an array so I can populate a table. My approach is this: every 22 elements, I want to populate a row in the table. However, it's not quite working. One failed attempt had me generate all of the result set but only in the first element of the table, the rest of the columns were blank. Next, my table was repeating the first row over and over, or, the first 22 elements rather than adding a new row after the 22nd element. Any advice?

Also, can I use a thread to update a table periodically, rather than doing it in one lump sum?

How much of your issue is specific to Swing? Seems like just standard Java stuff. The naive approach would be to create an array of size ArrayList's size / 22, then loop through the ArrayList and add the data from every 22nd ArrayList entry to the array.
 

Pau

Member
Looks like I might be working on a project where the simulation is done in Java. I've worked with C++ and Python; how difficult will the transition be? Anything to watch out for in particular? I also plan on going through some of the resources in the OP before starting.
 

Kieli

Member
I have a question about deep copying in C++. Is there a recipe for deep copy of a user-defined object?
Code:
// copy constructor
MyClass::MyClass(const MyClass& mc) {
     CopyHelper(mc);
}

//assignment operator overload
MyClass& MyClass::operator=(const MyClass& mc) {
     if (this != mc) {
          [delete all member attributes of object stored in dynamic memory]
          CopyHelper(mc);
     }

     return *this;
}

void MyClass::CopyHelper (const MyClass& mc) {
     [copy over all basic member attributes]
     [copy over more complex member attributes]
}
 
Looks like I might be working on a project where the simulation is done in Java. I've worked with C++ and Python; how difficult will the transition be? Anything to watch out for in particular? I also plan on going through some of the resources in the OP before starting.
You can think of Java as C++ without the pointers and operator overloading. Simple, which is one of its main strengths. Everything is virtual (sorry, performance). The memory management that you didn't have to worry about in Python is similarly non-existent in Java.
 

JeTmAn81

Member
Posting this from a PM conversation since I don't really know the answer to this:

esmith08734 said:
Okay, I figured it out. Thanks!

One additional concern is the speed of my application. So, the table is populated by my array that contains data about incoming packets. However, these packets come every 30 seconds. So, the rows need to be dynamic.

Right now, I have it where the table will only populate once all of the packets are received. I would rather have the table appear, blank at load, and then populate as each packet comes in.

I looked up some Swing Workers and I was wondering if I would use a Thread to catch the data and always check for it and then update the table and if so, how would that look? I was struggling a bit with the Runnable method.

I think this should be possible but someone who knows more about Java would have to weigh in. I believe Runnable is not actually a method, but there's the IRunnable interface that your class must adhere to in order to be run by a worker thread. I believe the only requirement to use this interface is to implement a Run() method which calls whatever functions you want to happen on that thread.
 

JesseZao

Member
I really wish C# had an "INumeric" interface for constraining generic functions to operate only on value types/(numbers). Seems rather useful.
 

Makai

Member
I really wish C# had an "INumeric" interface for constraining generic functions to operate only on value types/(numbers). Seems rather useful.
Another common one is being unable to use enums as a constraint. The workaround is to constrain to all of the interfaces that enums define and struct.
 

JesseZao

Member
Does this work?

where T : Int32, UInt32, Int16, UInt16 /* etc etc */

I don't think you can do that. I've found some workarounds, but nothing looks nice.

I was just making some LINQ extensions and came across this issue. I was just surprised that it wasn't something that C# has an explicit type/constraint for after all these years.

There was a solution in the SO question you get funneled to that used T4, but I haven't really dealt much with that. The closest I've come to using it is when Entity Framework generates a model with it.

Here it is (for ints only):
Code:
<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>

<# Type[] types = new[] {
    typeof(Int16), typeof(Int32), typeof(Int64),
    typeof(UInt16), typeof(UInt32), typeof(UInt64)
    };
#>

using System;
public static class MaxMath {
    <# foreach (var type in types) { 
    #>
        public static <#= type.Name #> Max (<#= type.Name #> val1, <#= type.Name #> val2) {
            return val1 > val2 ? val1 : val2;
        }
    <#
    } #>
}
 
I don't think you can do that. I've found some workarounds, but nothing looks nice.

I was just making some LINQ extensions and came across this issue. I was just surprised that it wasn't something that C# has an explicit type/constraint for after all these years.

There was a solution in the SO question you get funneled to that used T4, but I haven't really dealt much with that. The closest I've come to using it is when Entity Framework generates a model with it.

Here it is (for ints only):
Code:
<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>

<# Type[] types = new[] {
    typeof(Int16), typeof(Int32), typeof(Int64),
    typeof(UInt16), typeof(UInt32), typeof(UInt64)
    };
#>

using System;
public static class MaxMath {
    <# foreach (var type in types) { 
    #>
        public static <#= type.Name #> Max (<#= type.Name #> val1, <#= type.Name #> val2) {
            return val1 > val2 ? val1 : val2;
        }
    <#
    } #>
}
Holy shit. Is that all compile time resolved?
 
I don't think you can do that. I've found some workarounds, but nothing looks nice.

I was just making some LINQ extensions and came across this issue. I was just surprised that it wasn't something that C# has an explicit type/constraint for after all these years.

There was a solution in the SO question you get funneled to that used T4, but I haven't really dealt much with that. The closest I've come to using it is when Entity Framework generates a model with it.

Here it is (for ints only):
Code:
<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>

<# Type[] types = new[] {
    typeof(Int16), typeof(Int32), typeof(Int64),
    typeof(UInt16), typeof(UInt32), typeof(UInt64)
    };
#>

using System;
public static class MaxMath {
    <# foreach (var type in types) { 
    #>
        public static <#= type.Name #> Max (<#= type.Name #> val1, <#= type.Name #> val2) {
            return val1 > val2 ? val1 : val2;
        }
    <#
    } #>
}

Yea, C# generics have always been the one thing that has never failed to piss me off when I use it. Everything else about the langauge is great. It's one area where C++ really dominates.
 
Does this work?

where T : Int32, UInt32, Int16, UInt16 /* etc etc */

C# Generics do not let you specify the types you wish to support in such a fashion. You can constrain to classes or structs, you can constrain to interfaces or base classes, you can even specify that T must have a default constructor, but T has to match all of the constraints.

Code:
where T : class, IDisposable, new()

In this case, T must be a reference type that implements the IDisposable interface and supports a default (parameter-less) constructor.

Now it would be obvious that in T in your snippet cannot be all of those integer types.
 
For that T4 solution above, I wouldn't do that, but instead something like

Code:
	public static class MaxMath
	{
		public static T Max<T>(T val1, T val2) where T : struct, IComparable<T>
		{
			return val1.CompareTo(val2) >= 0 ? val1 : val2;
		}
	}

But I'm assuming the T4 code is StackOverflow's, and not necessarily indicative of your need (indeed, the real Math.Max should cover all use cases anyway). But what the T4 template is going to do is basically generate all the overloads for the specified types for you and make them part of your code base.
 

Somnid

Member
Can anyone give me a solid example of why on Earth you would seal/final a class? I swear this exists just to troll downstream devs.
 
Can anyone give me a solid example of why on Earth you would seal/final a class? I swear this exists just to troll downstream devs.

1) Encourage composition.
2) Coming from 1), preventing users of an API from tightly coupling their code to your API. if users rely too much on extending rather than using your classes, massive push back can and will happen later when you have to change something in a class they extend .
3) Optimization. Most JIT compilers more aggressively optimize final classes since they can rely on no children changing the behavior.
4) long chains of inheritance are just cumbersome in general to following leading into needing to do 1). not every design problem is an inheritance problem. careful analysis will reveal 9 times out of 10, composition solves your problem over inheritance and you have less trails to follow down.
 

Somnid

Member
1) Encourage composition.
2) Coming from 1), preventing users of an API from tightly coupling their code to your API. if users rely too much on extending rather than using your classes, massive push back can and will happen later when you have to change something in a class they extend .
3) Optimization. Most JIT compilers more aggressively optimize final classes since they can rely on no children changing the behavior.
4) long chains of inheritance are just cumbersome in general to following leading into needing to do 1). not every design problem is an inheritance problem. careful analysis will reveal 9 times out of 10, composition solves your problem over inheritance and you have less trails to follow down.

1) This is usually a problem with languages that don't have nicer composition (mixins) or when your structures (not the downstreams) were not built in a composable way. I could see bandaiding but it's really heavy handed to presume the downstream doesn't know what they are doing and often you just never considered their use-case.
2) This is just as much a problem the other way. I want to extend so I don't have to re-implement especially where edge-cases are involved. I don't want to maintain more than my own changes. Sometimes breaking changes occur, it's my responsibility to maintain that and then if I don't like that I can maintain my side version but I'd rather start with the former.
3) Valid enough
4) Sorta reiterating the above. Inheritance can get messy but perhaps I don't care or it's not the case here, I just want to reuse code, the upstream code shouldn't govern that.

I find a similar problem with private method overuse. The classic OO ideology is everything private unless it has to be exposed but this is usually an anti-pattern. You should have a good reason not to expose it both so you can test it and so others can use it if they find it suits their needs.
 
Can anyone give me a solid example of why on Earth you would seal/final a class? I swear this exists just to troll downstream devs.
To preserve invariants. You could also get away with simply not having virtual methods. However, sometimes this is inconvenient.. or something.. and you need virtual methods but only you, grand wizard of your library, are knowledgeable enough to be trusted with this overriding power, so you have decided to seal the class to prevent misuse.

It turns out that in this way, inheritance breaks encapsulation, because suddenly you need to become an expert in the implementation details of a class. Oops!

One of the most common reasons I have ever found for using inheritance is to implement an interface on a class. But if your language let you implement interfaces for existing classes, then you wouldn't need to inherit as often.

3) Optimization. Most JIT compilers more aggressively optimize final classes since they can rely on no children changing the behavior.
This is somewhat of an overstatement. Marking a class as final allows the compiler to change a virtual dispatched function into a statically dispatched one. That's all. Also, in general, tracing JITs already make assumptions about which function is going to run and use runtime behavior to justify these predictions, so very often you will not pay for the virtual dispatch for an oft-used function. If it isn't often used.. then the dispatch mechanism is really irrelevant to performance anyway.

Well: I guess static dispatch is better for inlining and optimization in a whole-program context. So there's that. But at this point we are just speculating on the shape of a program.
 
To preserve invariants. You could also get away with simply not having virtual methods. However, sometimes this is inconvenient.. or something.. and you need virtual methods but only you, grand wizard of your library, are knowledgeable enough to be trusted with this overriding power, so you have decided to seal the class to prevent misuse.

It turns out that in this way, inheritance breaks encapsulation, because suddenly you need to become an expert in the implementation details of a class. Oops!

One of the most common reasons I have ever found for using inheritance is to implement an interface on a class. But if your language let you implement interfaces for existing classes, then you wouldn't need to inherit as often.

Inheritance is funny, because the first introduction to inheritance is like "hey use inheritance to re-use a class's implementation". Then 5-10 years down the line, when you have more experience, you want to facepalm, because you eventually come to realize that it's almost always the wrong solution.

I literally almost never use implementation inheritance anymore.
 
My python is really rusty.

What exactly is going on in this code?

Code:
class Battlefield:
	def __init__(self):
		self.field = {}
		cellNumber = 10 
		for code in range(ord('A'), ord('K')):
			self.field[chr(code)] = {}
			for j in range(1, cellNumber + 1):
				 k = {j:False}
                                 self.field[chr(code)][j] = False

field is an empty dictionary.
cell number is 10.
for code in range A to K (converted to integers using ord)
field[turn integer into string] = {}.... ??? Isn't this trying to add the value {} to keys that dont exist? Does python allow for that? I guess it makes the keys? So now we'll have keys A-K that have the value of an empty dictionary?

for j in range(1, 11)
k = {j:false} ??? k doesn't seem to be used anywhere?
self.field[chr(code)][j] = False. ??? not sure on this either.

edit: I think the end result is something like a dictionay that contains dictionaries?

{ A = {1: false, 2, false, 3 false..... 10:false}, B = {etc...} }

?
 

peakish

Member
My python is really rusty.

What exactly is going on in this code?

Code:
class Battlefield:
	def __init__(self):
		self.field = {}
		cellNumber = 10 
		for code in range(ord('A'), ord('K')):
			self.field[chr(code)] = {}
			for j in range(1, cellNumber + 1):
				 k = {j:False}
                                 self.field[chr(code)][j] = False

field is an empty dictionary.
cell number is 10.
for code in range A to K (converted to integers using ord)
field[turn integer into string] = {}.... ??? Isn't this trying to add the value {} to keys that dont exist? Does python allow for that? I guess it makes the keys? So now we'll have keys A-K that have the value of an empty dictionary?

for j in range(1, 11)
k = {j:false} ??? k doesn't seem to be used anywhere?
self.field[chr(code)][j] = False. ??? not sure on this either.

edit: I think the end result is something like a dictionay that contains dictionaries?

{ A = {1: false, 2, false, 3 false..... 10:false}, B = {etc...} }


?
Yup. Pretty convoluted way to do it, though. I'd use a list comprehension, at least for the inner loop.

Code:
self.field[chr(code)] = {j: False for j in range(1, cellNumber + 1)}
 

JeTmAn81

Member
My python is really rusty.

What exactly is going on in this code?

Code:
class Battlefield:
	def __init__(self):
		self.field = {}
		cellNumber = 10 
		for code in range(ord('A'), ord('K')):
			self.field[chr(code)] = {}
			for j in range(1, cellNumber + 1):
				 k = {j:False}
                                 self.field[chr(code)][j] = False

field is an empty dictionary.
cell number is 10.
for code in range A to K (converted to integers using ord)
field[turn integer into string] = {}.... ??? Isn't this trying to add the value {} to keys that dont exist? Does python allow for that? I guess it makes the keys? So now we'll have keys A-K that have the value of an empty dictionary?

for j in range(1, 11)
k = {j:false} ??? k doesn't seem to be used anywhere?
self.field[chr(code)][j] = False. ??? not sure on this either.

edit: I think the end result is something like a dictionay that contains dictionaries?

{ A = {1: false, 2, false, 3 false..... 10:false}, B = {etc...} }

?

I don't know Python.

Looks to me like it creates an object called self.field, adds a property for the numeric value of each letter from A through K, then for each of those properties it adds properties called 1 through 11 with a value of false for each. The variable k seems to be intended to make those latter properties objects with the false properties inside them, but it's not being used and instead the property is assigned directly to the letter object in question.
 

Koren

Member
Yup. Pretty convoluted way to do it, though. I'd use a list comprehension, at least for the inner loop.

Code:
self.field[chr(code)] = {j: False for j in range(1, cellNumber + 1)}
Convoluted is an understatement.

And the k=... line is useless?
 
Inheritance is funny, because the first introduction to inheritance is like "hey use inheritance to re-use a class's implementation". Then 5-10 years down the line, when you have more experience, you want to facepalm, because you eventually come to realize that it's almost always the wrong solution.

I literally almost never use implementation inheritance anymore.
The only time I find it useful is in situations where I dynamically need a collection of different shaped things that all satisfy some common interface and share code. So, uh, inheritance is really just a special case of interface implementation when the prefix of the datatype is equivalent to another! No need to put it on a pedestal.
 
The only time I find it useful is in situations where I dynamically need a collection of different shaped things that all satisfy some common interface and share code. So, uh, inheritance is really just a special case of interface implementation when the prefix of the datatype is equivalent to another! No need to put it on a pedestal.

Even when that's what i need, I often find that having both things implement the interface and having one contain a poiter to the other is better in terms of usability and testability
 

NetMapel

Guilty White Male Mods Gave Me This Tag
Ok guys got a Python questions. I'm trying to use PySide to build a GUI and was testing out some codes in a 3D animation software's internal IDE. Real simple codes like "Hello World"

Code:
import sys
 
import PySide
from PySide.QtGui import QApplication
from PySide.QtGui import QMessageBox
 
# Create the application object
app = QApplication(sys.argv)
 
# Create a simple dialog box
msgBox = QMessageBox()
msgBox.setText("Hello World - using PySide version " + PySide.__version__)
msgBox.exec_()

The result gave me an error that says: "RuntimeError: A QApplication instance already exists."

Can somebody please explain that to me in the simplest way possible ? I really appreciate the help. Thanks :)
 

luoapp

Member
Ok guys got a Python questions. I'm trying to use PySide to build a GUI and was testing out some codes in a 3D animation software's internal IDE. Real simple codes like "Hello World"


The result gave me an error that says: "RuntimeError: A QApplication instance already exists."

Can somebody please explain that to me in the simplest way possible ? I really appreciate the help. Thanks :)

C&P from stackoverflow

Normally one creates a PySide application object in a script using QtGui.QApplication(). However, in 3ds Max, there is already a PySide application running, so you get a handle for that object like this:

QtGui.QApplication.instance()
 

NetMapel

Guilty White Male Mods Gave Me This Tag
C&P from stackoverflow

Unfortunately that still doesn't make much sense to me :( I understand class and inheritance in general, but I don't understand what stack overflow is trying to say there. Sorry I'm just very new to a Python wrapper like PySide.

Removing the "app = QApplication(sys.argv)" line allows the GUI to work though.
 

luoapp

Member
Unfortunately that still doesn't make much sense to me :( I understand class and inheritance in general, but I don't understand what stack overflow is trying to stay there.

try this?

app = QApplication.instance()

in place of

app = QApplication(sys.argv)
 

JeTmAn81

Member
Unfortunately that still doesn't make much sense to me :( I understand class and inheritance in general, but I don't understand what stack overflow is trying to stay there. Sorry I'm just very new to a Python wrapper like PySide.

Removing the "app = QApplication(sys.argv)" line allows the GUI to work though.

Programming equivalent of this

tell-him-weve.jpg
 

NetMapel

Guilty White Male Mods Gave Me This Tag
try this?

app = QApplication.instance()

in place of

app = QApplication(sys.argv)
That works too. So the question is still why. I am unfamiliar with argv other than a brief tutorial I did on that subject in CodeAcademy. Basically it allows for user input at the script startup. I'm not sure what it is doing in that particular line.
 

Koren

Member
I haven't used 3DS, but basically, you can only have one "application" running, and 3DS has already created one.

So you claim accessto the existing one (created by 3DS), instead of creating a new one.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Okay, question:

If I'm putting UTF-18 character codes into an array, how am I to convert them to get a string in Javascript?

It seems like:

Code:
String.fromCharCode(decodeTheseCharacters);

Doesn't work, because that's "dumping the entire array into them"

But trying to make it something like:

Code:
decodeTheseCharacters.join(String.fromCharCode(decodeTheseCharacters[i]));

Doesn't work either even if I can convert the characters into character code by that method (using a loop and iterating through "i" to get all character codes)

Basically:

String->Codes/Numbers->Numbers/Codes->String is what I'm trying to do, but I can't figure out the last bit.
 

Somnid

Member
Okay, question:

If I'm putting UTF-18 character codes into an array, how am I to convert them to get a string in Javascript?

It seems like:

Code:
String.fromCharCode(decodeTheseCharacters);

Doesn't work, because that's "dumping the entire array into them"

But trying to make it something like:

Code:
decodeTheseCharacters.join(String.fromCharCode(decodeTheseCharacters[i]));

Doesn't work either even if I can convert the characters into character code by that method (using a loop and iterating through "i" to get all character codes)

Basically:

String->Codes/Numbers->Numbers/Codes->String is what I'm trying to do, but I can't figure out the last bit.


If I understand:
Code:
decodeTheseCharacters.map(String.fromCharCode).join("");

Although browser support isn't fully fleshed out there's also TextDecoder: https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder

Javascript also supplies some tools for working directly with binary data, you can store in ArrayBuffers and read/write with DataViews.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
If I understand:
Code:
decodeTheseCharacters.map(String.fromCharCode).join("");

Although browser support isn't fully fleshed out there's also TextDecoder: https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder

Javascript also supplies some tools for working directly with binary data, you can store in ArrayBuffers and read/write with DataViews.

Hm... well, FreeCodeCamp specifically wants us to use (or at least recommends) .fromCharCode and .CharCodeAt to calculate the UTF-18 values. I haven't ran across ".map" yet. But I'll look into it.
 

Koren

Member
OK, I think I'll jump into the C++/Xamarin/Android wagon this summer.

Would someone have suggestions about books (french or english) about:
- C# (intermediate/advanced, although I would welcome a book that start near zero* so that I can check I haven't missed anything... my C# is both rusty and far from perfect). Main topics of interest would be Linq, Unicode support, SQLite support...
- C# / Xamarin / Android interaction and app development (virtually newbie on mobile development, except if you count calculators as mobile devices ^_^).

I've found a Xamarin / C# cookbook from M. Nayrolles that seems interesting at first glance...


Anything about F# (linked to Xamarin or not) would also be interesting, since I'll probably try that just after... Not sure about the level, I'm basically new to F#, but at ease with CaML which seems a carbon copy for syntax.

I should also look for a book for C++ X14 and advanced Scala, but that's probably too much for a single summer ^_^


* By "zero", I mean no requirements about C# knowledge, programming knowledge is perfectly OK. I've really enjoyed "Dive into Python" that many despise (it was in fact the book that brought me back into Python development after running from it years ago) but I think that's the kind of book that suits me: clearly explaining all the mechanics, assuming the reader is at ease with other languages.
 

Pau

Member
Thinking about converting my Python program into a website. Any good tutorials on getting started with web development? In particular my program just uses an SQL database and a web scraper, so I'm wondering if just focusing on PHP would be enough?
 

Ke0

Member
Thinking about converting my Python program into a website. Any good tutorials on getting started with web development? In particular my program just uses an SQL database and a web scraper, so I'm wondering if just focusing on PHP would be enough?

You could use python and flask/django since you already know Python and thus you can save yourself from PHP.

A few random tutorials that should help you.

Flask

http://code.tutsplus.com/tutorials/...ratch-using-python-flask-and-mysql--cms-22972
http://flask.pocoo.org/docs/0.11/tutorial/
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
https://stormpath.com/blog/build-a-flask-app-in-30-minutes
https://pythonspot.com/en/create-an-epic-web-app-with-python-and-flask-beginners-tutorial/

Django
http://www.tangowithdjango.com/
https://realpython.com/learn/start-django/
http://www.djangobook.com/en/2.0/chapter01.html
http://www.tdd-django-tutorial.com/
 
Anyone have a good source for thinking like a programmer? Constantly I am always kind of struggling where to start or where to go next. I don't have a hard time looking at code and wondering what's going on but naturally thinking like a problem solver is difficult to me and seems to be the hardest skill to learn.
 

Sliver

Member
Do any of you have any C++ books that you recommend? Looking at C++ Primer 5th edition, but its for 11, anyone a fan?

Need something to read at work to get a leg up on next semester. Should probably just get a discrete math book and pound that shit into my brain instead.
 

Trident

Loaded With Aspartame
Anyone have a good source for thinking like a programmer? Constantly I am always kind of struggling where to start or where to go next. I don't have a hard time looking at code and wondering what's going on but naturally thinking like a problem solver is difficult to me and seems to be the hardest skill to learn.

Try solving the problems on leetcode, then compare your answers against the top voted ones. It should give you a strong understanding of how to approach simple problems, which is the foundation of approaching more complex ones.
 
Top Bottom