Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
IratelyBlank
Dec 2, 2004
The only easy day was yesterday
I want to write a program for my research group that will let us know which of our workstations are under heavy load so we can tailor our simulations appropriately. The picture I have in my head is a service that runs on each simulation workstation (Windows) and can report who is running how many instances of this simulation software we use and how many cores, gb of ram, etc. they are using and it will all be displayed on a web interface so everyone has access to it.

My main question is what language(s) would most easily facilitate this kind of thing in a Windows environment? I worked as a software engineer for many years but I only used C# and computational languages to make desktop software and I have zero experience with anything web based. I don't mind learning a new language or two if that is the best way to go about it.

Adbot
ADBOT LOVES YOU

omeg
Sep 3, 2012

C# is absolutely fine for both web stuff and desktop.

nielsm
Jun 1, 2009



For that sort of administative-ish task, consider Power Shell.

Hadlock
Nov 9, 2004

IratelyBlank posted:

(Windows) and can report who is running how many instances of this simulation software we use and how many cores, gb of ram, etc. they are using and it will all be displayed on a web interface so everyone has access to it.

You want to do this in powershell, enable psremoting on your remote computers/workstations/servers (command is "Enable-Psremoting" and then hit "a") it would be something like this run on your webserver, with it (the powershell script running what, every 2 minutes via windows task scheduler

code:
$cpu = ICM servername { Get-WmiObject win32_processor | select LoadPercentage  |fl } 
$numberofsims = ICM servername { @(get-process -ea silentlycontinue mysimulation.exe).count }
And then feed $cpu and $numberofsims in to whatever. ICM is valid powershell shorthand for Invoke-Command. You could probably feed it in to a giant string that outputs as static HTML and saves the text file in the folder served as a webpage. Just make the output like,

code:
$htmloutput = for each ($server in $servers){"<b> $server </b> has <b> $numberofsims </b> running and is using <b> $cpu </b> cpu <br>"}
And then like,
code:
Out-File -name c:\wwwroot\mysimsdashboard\simdashboard.html -content $htmloutput -force
That's all psuedocode but about half of it should work or you can google the correct syntax on the out-file.

We have a powershell thread :) http://forums.somethingawful.com/showthread.php?threadid=3286440

double edit: where $servers is an array (basically an ArrayList but powershell lets you get super lazy) of server names imported from a CSV file, $csv = Import-CSV -path c:\wwwroot\mysimsdashboard\myservers.csv; foreach ($line in $csv){$servers += $csv.server}

Hadlock fucked around with this message at 07:35 on Jul 12, 2015

22 Eargesplitten
Oct 10, 2010



Does anyone have a good article explaining the pros and cons of the Single function exit point practice? My teacher for most of my classes had us doing it that way, but she also started coding when they had to reserve time to compile their code. I don't see many other people using it, so I'm wondering why.

nielsm
Jun 1, 2009



Pros:


Cons:
- Need to introduce additional flags and conditionals to prevent flow from entering code not desired
- Incompatible with exceptions
- Pre-condition checks that would cause an early return instead cause pyramid code syndrome

22 Eargesplitten
Oct 10, 2010



Okay, I'll break that habit, then. Why did it originate? Was there some sort of technical limitation decades ago?

JawnV6
Jul 4, 2004

So hot ...
Resource cleanup.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip
I don't have an article handy, but the pros that you will most often see are that it makes error cleanup easier and that it ostensibly makes control flow easier to follow. The cons that you will generally see are that it makes control flow harder to follow by requiring a bunch of conditionals to be added. Consider the following function:

code:
int log_close(LOG log)
{
	/* Closes a datalog and updates metadata appropriately.
	 * Returns SUCCESS on success.
	 */

	if (log == NULL) {
		return SOME_ERROR_CODE;
	}
	 
	begin_critical_region();
	 
	// .. do some work ...
	
	if (update_entry(log->data_addr) != LOG_SUCCESS) {
		return SOME_OTHER_ERROR_CODE;
	}

	if ((write_metadata(log->metadata_addr)) != LOG_SUCCESS) {
		return YET_ANOTHER_ERROR_CODE;
	}
	
	// make sure we don't have a log marked as active
	active_datalog = NULL;
	 
	end_critical_region();
	return SUCCESS;
}
Now obviously this code has some problems - in any of the error cases, you haven't exited the critical region, so your caller is now exiting within that critical region which was not intended. We can fix this either by switching to a single-point-of-return structure (and adding a bunch of conditionals), by adding gotos (in C, which this example code was adapted/redacted from) or by adding something like a try/finally block in a language with error handling built around exceptions.

The single-point-of-return version might look something like this:

code:
int log_close(LOG log)
{
	/* Closes a datalog and updates metadata appropriately.
	 * Returns SUCCESS on success.
	 */

	int ret = SUCCESS;

	if (log == NULL) {
		ret =  SOME_ERROR_CODE;
	}
	 
	begin_critical_region();
	 
	// .. do some work ...
	if (ret == SUCCESS) {
		if (update_entry(log->data_addr) != LOG_SUCCESS) {
			ret =  SOME_OTHER_ERROR_CODE;
		}
	}

	if (ret == SUCCESS) {
		if ((write_metadata(log->metadata_addr)) != LOG_SUCCESS) {
			ret =  YET_ANOTHER_ERROR_CODE;
		}
	}
	
	// make sure we don't have a log marked as active
	active_datalog = NULL;
	 
	end_critical_region();
	return ret;
}
e: as others noted above, often the metadata write would be nested inside the if block for update_entry and any following stuff would be further nested within that block, quickly leading to code scrolling off the right-side edge of your third monitor and making your eyes zigzag left and right to read it

The goto solution might look something like
code:
int log_close(LOG log)
{
	/* Closes a datalog and updates metadata appropriately.
	 * Returns SUCCESS on success.
	 */

	int ret;

	if (log == NULL) {
		return SOME_ERROR_CODE;
	}
	 
	begin_critical_region();
	 
	// .. do some work ...
	
	if (update_entry(log->data_addr) != LOG_SUCCESS) {
		ret =  SOME_OTHER_ERROR_CODE;
		goto error_cleanup;
	}

	if ((write_metadata(log->metadata_addr)) != LOG_SUCCESS) {
		ret = YET_ANOTHER_ERROR_CODE;
		goto error_cleanup;
	}
	
	// make sure we don't have a log marked as active
	active_datalog = NULL;
	 
error_cleanup:
	end_critical_region();
	return LOG_SUCCESS;
}

Blotto Skorzany fucked around with this message at 20:23 on Jul 15, 2015

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
One of the big ideas of Structured Programming was single-entry, single-exit subroutines, where all jumps into a subroutine went to a single entry point, and all jumps out came from a single exit point. The first half was such a good idea that most programming languages don't even support multiple entry points into functions, and the second half got pulled along for the ride despite being much less useful.

sarehu
Apr 20, 2007

(call/cc call/cc)
There's nothing wrong with functions having multiple points of entry either, given reasonable variable scopage and rules about mandatory variable initialization.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I recently got access to a major proprietary codebase from a major hardware vendor that uses single-exit, Yoda style, custom defines for every constant, and requires braces around every block.

C++ code:

if (VENDOR_FALSE == val) {
    ret = VENDOR_ERR;
}

raminasi
Jan 25, 2005

a last drink with no ice

Suspicious Dish posted:

I recently got access to a major proprietary codebase from a major hardware vendor that uses single-exit, Yoda style, custom defines for every constant, and requires braces around every block.

C++ code:
if (VENDOR_FALSE == val) {
    ret = VENDOR_ERR;
}

I don't see anything questionable about forbidding magic numbers or requiring mandatory braces, and Yoda style is hardly a horror.

omeg
Sep 3, 2012

Single point of exit is nice when you're debugging, you can put just one breakpoint to see what the function returns. :v:

Sedro
Dec 31, 2008

omeg posted:

Single point of exit is nice when you're debugging, you can put just one breakpoint to see what the function returns. :v:
I've always wondered why debuggers can't just show me

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

omeg posted:

Single point of exit is nice when you're debugging, you can put just one breakpoint to see what the function returns. :v:

Breakpoint at function entry, step out, inspect returned value?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

GrumpyDoctor posted:

I don't see anything questionable about forbidding magic numbers or requiring mandatory braces, and Yoda style is hardly a horror.

I find it uncomfortable and hard to read. Here's more of their code style (this one is a public function from a GPL source dump, with names changed)

C++ code:
VENDOR_EXPORT VendorBoolean __vendor_platform_init_display_x11(vendor_base_ctx_handle base_ctx)
{
        native_ctx_data *native_ctx;

        VENDOR_IGNORE(base_ctx);

        /* Look up to see if there is already a mapping to this native ctx */
        native_ctx = __vendor_named_list_get(native_data->ctxs, (u32)base_ctx->handle);

        if (NULL == native_ctx)
        {
                /* create new entry for this new ctx */
                native_ctx = (native_ctx_data *)_vendor_sys_calloc(1, sizeof(native_ctx_data));

                if (NULL == native_ctx)
                {
                        DEBUG_DUMP_ERROR();
                }
        }

        if (NULL == native_ctx)
        {
                return VENDOR_FALSE;
        }
        else
        {
                return VENDOR_TRUE;
        }
}

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Sedro posted:

I've always wondered why debuggers can't just show me

Good ones can and do.

Amberskin
Dec 22, 2013

We come in peace! Legit!

Volmarias posted:

Breakpoint at function entry, step out, inspect returned value?

If the returned value is wrong (type wise) you can get yourself stepping into an exception handler before the caller gets control.

ToxicFrog
Apr 26, 2008


22 Eargesplitten posted:

Okay, I'll break that habit, then. Why did it originate? Was there some sort of technical limitation decades ago?

Like "GOTO Considered Harmful", it's a relic of the war between structured and unstructured programming practices -- a war won so completely by the structured programming side that these days it's hard to believe it even happened.

The original argument wasn't "one point of return" vs. "multiple points of return"; it was "functions and blocks" vs. "just use globals everywhere and CMP/JMP for all flow control". A lot of the arguments made by the structured programming camp are rooted in the structured program theorem, which -- among other things -- forbids both multiple entries and exits from a function and "unstructured jumps" (goto/break/continue).

These days we're no longer working in assembler, and most languages have structured programming woven into their design even if they have features -- like multiple return points in a function, coroutines, or "break" -- that mean they don't strictly conform to the Böhm-Jacopini theorem. But you still get people slavishly repeating the arguments of the structured programming war without understanding why they were necessary at the time or why, today, they often are not.

ExcessBLarg!
Sep 1, 2001

Suspicious Dish posted:

Here's more of their code style (this one is a public function from a GPL source dump, with names changed)
Wow that's pretty painful. There's really only four actual lines of code in there.

22 Eargesplitten
Oct 10, 2010



ToxicFrog posted:

Like "GOTO Considered Harmful", it's a relic of the war between structured and unstructured programming practices -- a war won so completely by the structured programming side that these days it's hard to believe it even happened.

Looking that whole thing up, that makes sense. My teacher also taught us never to use GOTOs, and any global variables had to be thoroughly defended as necessary. The one case I remember her allowing it in was when someone used multithreading to clone Pipe Dream for a final project. She seemed old enough to have been in college in the 80s or late 70s,and I think she had taught her whole career.

Are GoTos still considered bad? I read up on Google's Java standards, since I want to start coding in what at least someone would consider best practices, but none of that was brought up.

I am just now realizing how far I have to go before I'm good enough to win anyone over with a portfolio. It's probably not even worth putting any of my current work in the portfolio.

ultrafilter
Aug 23, 2007

It's okay if you have any questions.


22 Eargesplitten posted:

Are GoTos still considered bad? I read up on Google's Java standards, since I want to start coding in what at least someone would consider best practices, but none of that was brought up.

The use of goto isn't going to be addressed in a lot of coding standards documents because the languages in question don't have it. It's a relic of an old time, and will eventually be forgotten.

22 Eargesplitten
Oct 10, 2010



Ah, okay. This is one of those times that starting on C++ gives me a weird outlook, because C++ still has it.

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)

22 Eargesplitten posted:

Looking that whole thing up, that makes sense. My teacher also taught us never to use GOTOs, and any global variables had to be thoroughly defended as necessary. The one case I remember her allowing it in was when someone used multithreading to clone Pipe Dream for a final project. She seemed old enough to have been in college in the 80s or late 70s,and I think she had taught her whole career.

Are GoTos still considered bad? I read up on Google's Java standards, since I want to start coding in what at least someone would consider best practices, but none of that was brought up.

I am just now realizing how far I have to go before I'm good enough to win anyone over with a portfolio. It's probably not even worth putting any of my current work in the portfolio.

As far as Java is concerned, goto doesn't exist. I've never done it, but I imagine that the only arguably sane use for goto today is to explicitly break out of nested loops. It's very complex and confusing for human beings to follow since without some sort of hierarchy we lose the plot real quick.

sarehu
Apr 20, 2007

(call/cc call/cc)

22 Eargesplitten posted:

Are GoTos still considered bad? I read up on Google's Java standards, since I want to start coding in what at least someone would consider best practices, but none of that was brought up.

Goto is not considered bad (by non-morons) at all. For one, goto statements in modern languages are function-local, not the global beasts of yore. Second of all, prohibiting goto is reasonable for a teacher in some CS intro class to do, because students need to learn how to use control structures. They are the right way to structure your code and your thinking, with, perhaps, some exceptions.

One exception is for error cleanup in C. Another is if you've got some tail-recursive function, and you want it to not actually recurse. It can be quite clear to put a label at the top, set the parameters to their new values, and use a goto statement. Sometimes, refactoring that to a while loop is a worse option, like if there'd be nested while loops and you'd need to break out of one. For example, if you're recursing down a tree with arbitrary branching factor.

In general, breaking out of nested while loops is an appropriate choice for goto statements. "Labeled break statements" are possible in some languages, but these are not a better option.

Sometimes also, a "break to success" idiom is appropriate:

code:
  while (...) {
    if (blah_found) {
      goto found;
    }
    ...
  }
  some_stuff_if_not_found();
found:
  all_cases();
You could write that without goto, of course:
code:
  bool found = false;
  while (...) {
    if (blah_found) {
      found = true;
      break;
    }
    ...
  }
  if (!found) {
    some_stuff_if_not_found();
  }
  all_cases();
That's just a more convoluted way to do the same thing, and the only reason to avoid using the goto statement is a braindead religion.

b0lt
Apr 29, 2005
^ :argh:

dougdrums posted:

As far as Java is concerned, goto doesn't exist. I've never done it, but I imagine that the only arguably sane use for goto today is to explicitly break out of nested loops. It's very complex and confusing for human beings to follow since without some sort of hierarchy we lose the plot real quick.

Java's closest thing to goto only works for breaking out of nested loops. You can label loop constructs and break/continue them explicitly.

Another thing goto is reasonable for is resource cleanup in C, since you might allocate a dozen buffers throughout a function, and return early at any point. Instead of returning immediately, you assign a result variable and goto a cleanup section that does all of your frees or whatever and then returns. This is more of an argument as to why you shouldn't use C, though, since C++'s RAII removes all of this nonsense.

Linear Zoetrope
Nov 28, 2011

A hero must cook
I also like Go's defer for the "goto for error cleanup without exceptions" case.

darthbob88
Oct 13, 2011

YOSPOS

ultrafilter posted:

The use of goto isn't going to be addressed in a lot of coding standards documents because the languages in question don't have it. It's a relic of an old time, and will eventually be forgotten.

My favorite thing about goto is that apparently PHP added it in 5.3.0, and before that you had to use a library or something. PHP, the archetype of bad languages, didn't have GOTO initially because even they understood how bad it was.

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord

sarehu posted:

That's just a more convoluted way to do the same thing

Nah it's not. That's perfectly fine code. Using a flag variable is the way that most people will naturally reason about the problem.

Just for the record I don't even hate the goto here, I think that looks ok, but not particularly "whoa that's so amazing, I wish every modern language had goto so I could be expressive like that!".

Hughmoris
Apr 21, 2007
Let's go to the abyss!
This question may be more IT-focused but I'm willing to try any tool/language at this point: Can anyone offer advice on printing PDFs to network printers?

My goal is to regex a text file, get a string, and print a PDF to a specific network printer based off that string. Right now my current solution is having powershell first make the network printer be the Default Printer for my system, then print to default printer. Clunky, slow and prone to hiccups I think.

This will be on a Windows 7 computer.

Hadlock
Nov 9, 2004

Hughmoris posted:

This question may be more IT-focused but I'm willing to try any tool/language at this point: Can anyone offer advice on printing PDFs to network printers?

My goal is to regex a text file, get a string, and print a PDF to a specific network printer based off that string. Right now my current solution is having powershell first make the network printer be the Default Printer for my system, then print to default printer. Clunky, slow and prone to hiccups I think.

This will be on a Windows 7 computer.

powershell?

code:
for each($line in $textfile){ # parse each line of the text file
  if($line -match 'foo.bar"){ # this is your regex
    get-content c:\docstoprint\doc1.pdf | Out-Printer -name $printername # print to a specific printer
    }
  }
http://ss64.com/ps/syntax-regex.html
https://gregcaporale.wordpress.com/2012/01/18/powershell-to-print-files-automatically/
https://technet.microsoft.com/en-us/magazine/2008.09.windowspowershell.aspx

Pie Colony
Dec 8, 2006
I AM SUCH A FUCKUP THAT I CAN'T EVEN POST IN AN E/N THREAD I STARTED

darthbob88 posted:

My favorite thing about goto is that apparently PHP added it in 5.3.0, and before that you had to use a library or something. PHP, the archetype of bad languages, didn't have GOTO initially because even they understood how bad it was.

If anything, this is an argument that GOTOs are good.

ExcessBLarg!
Sep 1, 2001

sarehu posted:

Goto is not considered bad (by non-morons) at all.
These are pretty good examples. Another goto idiom that's common in Linux (and probably elsewhere, but this is where I've seen it most frequently) is retry:
code:
retry:
    do_some_task();
    if (task_failed()) {
        fix_thing_that_caused_task_to_fail();
        goto retry;
    }
    do_more_tasks();
You can do the same thing with a do-while loop, but retry makes more sense if fail-and-retry is the uncommon case, whereas a do-while loop makes more sense if iterating the loop (retry) is the common case.

Honestly it's probably better for a language to have some kind of goto construct and encourage its use sparingly, than not to and force folks to to use flag variables, do-while loops, nested-breaks, or non-exceptional exceptions in situations when none of those things is the most natural way to implement the logic.

Some folks also have a rule that "forward gotos are OK but backwards ones are not", but the retry idiom is a good example of a reasonable backwards goto.

Hughmoris
Apr 21, 2007
Let's go to the abyss!

Hadlock posted:

powershell?

code:
for each($line in $textfile){ # parse each line of the text file
  if($line -match 'foo.bar"){ # this is your regex
    get-content c:\docstoprint\doc1.pdf | Out-Printer -name $printername # print to a specific printer
    }
  }
http://ss64.com/ps/syntax-regex.html
https://gregcaporale.wordpress.com/2012/01/18/powershell-to-print-files-automatically/
https://technet.microsoft.com/en-us/magazine/2008.09.windowspowershell.aspx

Thanks for the resources. Unfortunately, from what I can gather the "get-content" command just returns gibberish when you use it on a PDF. I actually used that Greg Caporale resource for the "switch network printer to be default printer -> then print" idea.

hooah
Feb 6, 2006
WTF?
I'm writing some code to break up a large file into smaller files, but I'm having a hard time wrapping my head around the checks. Here's what the large file's format looks like, with specific markers at the end of each line:
code:
garbage
garbage
garbage
aa1
aa2
aa3
aa4
b1
b1
b1
c1
c1
c1
d1
d1
d1
e1
e1
e1
ab1
ab2
ab3
ab4
b2
b2
b2
c2
c2
c2
d2
d2
d2
e2
e2
e2
I want to group all the aa's together, then the b1's, then c1's, etc. So far, my code works fine until the ab's, which get grouped with the e1's. Here's some pseudocode of what I'm doing:

code:
marker = ''
previous_marker = ''
while(input_line):
    marker = last text in line
    if(marker[0] == 'a'):
        append input_line to data structure

    else if(marker == previous_marker):
        append input_line to data structure

    else:
        write data structure to file
        clear data structure
    
    previous_marker = marker
I tried putting the final else at the top of the if, but that caused the aa1 line to get written to a file, since the aa1 marker was different than the garbage marker.

EAT THE EGGS RICOLA
May 29, 2008

I don't suppose anyone is aware of a free reverse image search API? My friend's photos keep getting taken from his flickr account and used without attribution by commercial websites and it's we'd like to get an idea of just how often this is happening.

kedo
Nov 27, 2007

EAT THE EGGS RICOLA posted:

I don't suppose anyone is aware of a free reverse image search API? My friend's photos keep getting taken from his flickr account and used without attribution by commercial websites and it's we'd like to get an idea of just how often this is happening.

I believe Google's Custom Search API can do this.

EAT THE EGGS RICOLA
May 29, 2008


Yeah, it handles 100/day for free. It's not really a time sensitive thing so it can just run for a week or month or whatever.

Adbot
ADBOT LOVES YOU

ultrafilter
Aug 23, 2007

It's okay if you have any questions.


Not a question, but I ran across a paper that looks interesting, and I don't know of any better place to post it.

Punctuated equilibrium in the large scale evolution of programming languages

quote:

Here we study the large scale historical development of programming languages, which have deeply marked social and technological advances in the last half century. We analyse their historical connections using network theory and reconstructed phylogenetic networks. Using both data analysis and network modelling, it is shown that their evolution is highly uneven, marked by innovation events where new languages are created out of improved combinations of different structural components belonging to previous languages. These radiation events occur in a bursty pattern and are tied to novel technological and social niches. The method can be extrapolated to other systems and consistently captures the major classes of languages and the widespread horizontal design exchanges, revealing a punctuated evolutionary path.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply