-Поиск по дневнику

Поиск сообщений в rss_thedaily_wtf

 -Подписка по e-mail

 

 -Постоянные читатели

 -Статистика

Статистика LiveInternet.ru: показано количество хитов и посетителей
Создан: 06.04.2008
Записей:
Комментариев:
Написано: 0

The Daily WTF





Curious Perversions in Information Technology


Добавить любой RSS - источник (включая журнал LiveJournal) в свою ленту друзей вы можете на странице синдикации.

Исходная информация - http://thedailywtf.com/.
Данный дневник сформирован из открытого RSS-источника по адресу http://syndication.thedailywtf.com/thedailywtf, и дополняется в соответствии с дополнением данного источника. Он может не соответствовать содержимому оригинальной страницы. Трансляция создана автоматически по запросу читателей этой RSS ленты.
По всем вопросам о работе данного сервиса обращаться со страницы контактной информации.

[Обновить трансляцию]

Tales from the Interview: A Sterling Interview

Понедельник, 20 Апреля 2020 г. 09:30 + в цитатник

Greater blue-eared starling (Lamprotornis chalybaeus)

Marissa's not-for-profit organization sought a college graduate with the ability to code and create basic software solutions. Given their organization's financial limitations, they couldn't afford to pay employees as well as many other places could, thus they'd been struggling for over a year to find a qualified entry-level candidate. Finally, a fresh graduate came along who made a strong impression during his interview. Greg was personable and possessed the required fundamentals. There was potential for him to learn more on the job.

Once the interview had ended, while Marissa escorted Greg out of the building, he told her, "Hey, I really didn't do very well today."

Marissa had formed the opposite impression, but didn't interrupt.

"If you really want to see what I'm capable of," Greg continued, "check out my GitHub. That's where you'll see what my code is like."

Marissa was more than happy to do that. She and her whole software team accessed his GitHub to examine their potential coworker's code, assuming they'd be impressed with what they found.

Most of the projects were nothing special. The pi`ece de r'esistance, however, was a comprehensive open-source tool called iStarling. This particular repository had quite a bit more content to sift through than any of the others.

Something struck Marissa as fishy. Acting on instinct, she did some googling and found a similar open-source tool called iWren, made by a completely different person. It wasn't merely similar—a comparison of files showed that Greg had copied the repository wholesale into his own GitHub only a few days earlier, then had done a mass find/replace of the word "Wren" to "Starling."

This bird-brained attempt at plagiarism left Marissa scratching her head. If Greg had never made that parting comment to her, he probably would've been hired. Greg had done the company a solid favor by warning them about what Greg was capable of. The search for a decent employee continued.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!

https://thedailywtf.com/articles/a-sterling-interview


Метки:  

Error'd: Normal 0 False False Errord False EN-US

Пятница, 17 Апреля 2020 г. 09:30 + в цитатник

Andrew G. writes, "In these difficult times, I'm glad NBC News is having a normal O...and...other...stuff."

 

"While I find DevExpress' tools to make up for the clumsiness by being slow, it appears they've gotten a time machine working," Scott wrote.

 

"The fact that Amazon won't let me order their highly reviewed 'not for sale' test game controller only makes me want it more!" wrote Mike H..

 

Sam writes, "You know...I think that I'm going switch to just plastic for a little while until this poor ATM gets itself sorted out."

 

"I guess they tried to indirectly measure the timespan between PHP versions," Martin writes.

 

Tyson T. wrote, "Hopefully Polly is nowhere near counting votes in the upcoming election."

 

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!

https://thedailywtf.com/articles/normal-0-false-false-errord-false-en-us


Метки:  

CodeSOD: A Leap to SQL

Четверг, 16 Апреля 2020 г. 09:30 + в цитатник

When I was a baby programmer, I was taught that part of the power of SQL was that we had a generic, abstract language which meant we could easily change database engines out under our code without having to think about it. In short, I was taught a horrible pack of lies.

For all that SQL has a standard, every database vendor has non-standard features, especially around various built-in functions. The end result is that, if you adopt SQL Server, you’re going to be on SQL Server for the life of the application. If you adopt Oracle, you will suffer that choice for the remainder of your existence on this plane and perhaps the next.

What this means is that it behooves you to learn the standard functions of your chosen RDBMS. For example, in T-SQL, SQL Server’s dialect of SQL, one of the built-in functions is EOMONTH. Given a date, it tells you the last day of the month, useful for a lot of business processes.

You could use that, or you could do what Darrin’s co-worker did:

SET @EDate = (SELECT CAST(CAST(CASE WHEN MONTH(GETDATE())-1 = 0 THEN 12 ELSE MONTH(GETDATE())-1 END AS NVARCHAR) 
	+ 
	'/'
	+
	CASE WHEN MONTH(GETDATE())-1 = 2 THEN '28'
	WHEN MONTH(GETDATE())-1 = 4 THEN '30'
	WHEN MONTH(GETDATE())-1 = 6 THEN '30'
	WHEN MONTH(GETDATE())-1 = 9 THEN '30'
	WHEN MONTH(GETDATE())-1 = 11 THEN '30'
	ELSE '31'
	END
	+
	'/' 
	+ CAST(CASE WHEN MONTH(GETDATE())-1 = 0 THEN YEAR(GETDATE())-1 ELSE YEAR(GETDATE()) END AS NVARCHAR(50)) AS DATETIME))

There’s a lot going on here, and honestly, the most frustrating thing to see isn’t the incorrect date logic, but the string concatenation only to convert it back to a DATETIME at the end. String concatenation in SQL to build a date is some ugly stuff.

But the meat of the WTF, of course, is their “last day of month” logic, specifically around February. It’s correct most of the time. Most.

[Advertisement] ProGet can centralize your organization's software applications and components to provide uniform access to developers and servers. Check it out!

https://thedailywtf.com/articles/a-leap-to-sql


Метки:  

CodeSOD: Highly Paid Entities

Среда, 15 Апреля 2020 г. 09:30 + в цитатник

Years ago, Samuel’s company brought in some Highly Paid Consultants. The HPCs brought with them a binder full of best practices, a dedicated Agile coach, and a slick project plan that promised to accomplish everything the company needed in half the time budgeted.

One of their “best practices” was the advice that “ORMs are considered harmful,” and while the existing codebase already made liberal use of .NET’s Entity Framework, their new code would be “optimized”.

Those optimizations must have thrown off the project timeline- they burned through their “aggressive” project plan’s budget, then the original time-and-cost estimates, and then lingered for months trying to finish their tasks. Eventually, they moved on to the next contract, and Samuel was handed their code and told to fix the bugs and performance issues.

This was HR software, so among other things, it would track employees’ “career plans”. One example query the software needed to answer was to find the one plan that was the greatest number of “challenge units” below a certain threshold.

The “harmful” Entity Framework/LINQ way of answering this question would be code akin to this:

  var selectedLevel = _careerPlanRepository.GetAll()
      .Where(c => c.ChallengeHistoricalUnits <= units)
      .OrderByDescending(t => t.ChallengeHistoricalUnits)
      .FirstOrDefault();

EF/LINQ do a little bit of magic here: the chain of method calls are used to generate an SQL statement, send the SQL statement to the database, and then capture the results. So, for example, in this case, GetAll doesn’t really get all the records- it gets all the records which pass the Where function. And because we explicitly tag a FirstOrDefault on the end, it knows it only needs to fetch one row, and thus doesn’t fetch data we don’t want.

Perhaps it’s the magic or the (in this case) efficiency which is harmful. Here’s how the HPCs cut down on their use of Entity Framework:

var plans = _careerPlanRepository.GetAll().OrderByDescending(t => t.ChallengeHistoricalUnits).ToList();
foreach (var item in plans)
{
	if (item.ChallengeHistoricalUnits <= units)
	{
		selectedLevel = item;
		break;
	}
}

You’ll note that they got rid of the Where call, so their non-harmful approach is to fetch every row from the table into a list. Then they look at every item in that (sorted) list and find the first one which meets the threshold.

The HPCs left behind their binder of best practices. It’s seen a lot of use around the office, as a doorstop, paperweight, or monitor stand. Beyond that, though, Samuel has quite consciously done the “harmful” thing and started using EF and LINQ to streamline his queries.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

https://thedailywtf.com/articles/highly-paid-entities


Метки:  

Better Off Ted

Вторник, 14 Апреля 2020 г. 09:30 + в цитатник

When working on a programming team, you need to make sure everyone on the team is aware of the changes you make. This is to ensure that everyone knows what task they're doing, what feature the rest of the team might not have to worry about, or any potential conflicts - among other reasons.

Once those changes are made, you want them reviewed. Perhaps one other developer does it, perhaps a group, or perhaps the whole team. Once approved, the changes get applied to the live application.

Adam's team has their process and it's not too different from most other software companies. Team-member Ted, however, decided that he can make changes over and over again, without telling anyone.

There were three main reasons Ted wasn't reprimanded in the beginning - the first is Ted is a talented programmer, and on a team with only a handful of programmers, that's valuable. The second reason and probably more important is Ted was programming for this company since the beginning; meaning Ted knows the inside and outside of the app. And finally Ted was the only remote employee – meaning it's harder to be direct when Ted isn't even in the building.

Ted thought he was doing the company a favor by improving the software to meet his needs. In practice, it meant the entire development team would have to fix, correct, or flat out remove everything Ted did. But since Ted didn't tell anyone, didn't correlate changes with any tickets, or even include clear commit comments, it was often difficult to know what exactly were his "just because" changes, and which were "real" features.

During their virtual standups, Ted described himself as "a teacher," showing the younger developers the way, and preparing them for their careers. He was like a teacher, but instead of following the approved curriculum, he taught what he felt best, standards be damned. He might have the best intentions, but Ted wasn't preparing them for anything but frustration.

With Ted being the only remote employee, this meant it was easy for Adam, the team-lead, to meet without Ted, and discuss what to do with Ted's constant changes. Ted couldn't simply be fired- the office politics didn't permit it. But Adam could cut his hours, and put him on tasks that didn't matter if Ted tampered with the requirements and did his own thing.

Even though Ted was warned a number of times, in terms ranging from "gentle" to "this is serious, Ted", he still didn't stop making his own changes. He still let his work interfere with other developers.

The reprimands got to the point where even Ted realized that his job was jeopardy. Still, he insisted on doing things his own way. Adam and the team tried to talk to him about it, tried to offer suggestions, but Ted was too stubborn to take his team's advice.

Adam and the team worked on an e-commerce portal, and Ted was performing these changes on the live site; bypassing all protocol. This means that customers could actually view the changes that Ted made, in real time.

Adam tried giving Ted less work, so the team wouldn't have to worry about his meddling behind the scenes as much, but Ted couldn't be stopped. The breaking point was when Ted made a change, directly merged it into master, and then published it to the live site. The change ruined mobile formatting for the features the other programmers were working on, which was annoying. But it also broke the customer's ability to purchase from the site- customers literally couldn't make purchases because of Ted's "improvements".

The team had to scramble to revert to the previous build, and then unpick Ted's many commits from the history to fully revert that feature. Adam had to let Ted go – everyone on a team needs to work together.

[Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!

https://thedailywtf.com/articles/better-off-ted


Метки:  

Representative Line: The Standard StringBuilder

Понедельник, 13 Апреля 2020 г. 09:30 + в цитатник

At a previous job, I became "The Code Review Guy". It was a big company, with a lot of bureaucracy. They were transitioning from VB6 to VB.NET and didn't trust developers to adapt to this new world, so they positioned code reviews as a "gateway" and the reviewers were guards, tasked with ensuring that any code going past met the standards.

That was already a pretty bad, and pretty hostile approach. Then some code would get submitted which didn't just violate the standards, but was barely comprehensible nonsense which followed no coherent convention and couldn't be tested let alone debugged. But it was mission critical and had a scheduled release date already, so the code review process had to let it pass. "Just make some notes, and they'll fix it in a future release," was the attitude. You can imagine how much of that code got fixed.

In any case, one of our standards was that developers should use a StringBuilder object, not string concatenation. Concatenation produces many, many intermediate strings, which can cause performance and garbage collection issues, while a StringBuilder avoids that.

This standard was commonly violated.

Which brings us to this representative line of C#, which Adeline found in a customer's code-base. I can assume that they had a similar standard: use a StringBuilder. Whoever wrote this followed those instructions to the letter:

StringBuilder body = new StringBuilder(); body.AppendLine("Batch " + name + " batch header sheet " + string.Format("{0:C}", Convert.ToDouble(headerAMT) / 100) + " and Check total " + String.Format("{0:C}", Convert.ToDouble(totAMT) / 100) + " do not balance!\r\r");

Adeline adds: "I wish I could say this code wasn't indicative of the whole."

[Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!

https://thedailywtf.com/articles/the-standard-stringbuilder


Метки:  

Error'd: Google Translate is the Dog's Meow

Пятница, 10 Апреля 2020 г. 09:30 + в цитатник

"When a Brazilian teammate showed me a pet he was looking to adopt, I asked Google Translate for some help. It wasn't very helpful," Craig B. writes.

 

Drew W. wrote, "Yes, TrailLink, I definitely want to subscribe to your TEST_OD_PARTNER_INTEREST newsletter series. I bet it is very TEST_INTERESTING!"

 

"My supermarket has these handy-dandy scanners that speed up scanning and alert you to possible savings...or rather, lack thereof," Vaughn writes.

 

Drake C. writes, "Take my temperature with quantum aluminum? I'm in! Shame it's sold out though..."

 

"Booking an international flight through the Kayak.com site, I was pleased that the site took Discover," wrote David L., "Alas, now my confidence in the process is shaken. I suppose I should see if I can get a new passport in my new name before the flight."

 

"I'm seriously confused here... Feb 29th is day 366? And comes after March 1st but before March 2nd?!" wrote Thomas H.

 

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

https://thedailywtf.com/articles/google-translate-is-the-dog-s-meow


Метки:  

Понравилось: 1 пользователю

CodeSOD: The Date Wrapper

Четверг, 09 Апреля 2020 г. 09:30 + в цитатник

As we’ve harped upon many, many, many, many, many, many times: writing your own date functions is bad. Use the built-ins or a library or anything but your own awful string-mangling date code.

But you can and should wrap the date handling stuff in your own functions as convenient. That’s just good programming.

Krystian S inherited some code, which wraps date handling functions in its own abstractions, with method names like:

convertHHcolonMMtoHHcolonMMcolonSS(value);
convertDDdMMdYYYtoYYYYminusMMminusDD(value);
convertDDdMMdYYYspHHcolonMMtoYYYminusMMminusDDspHHcolonMMcolonSS(value);

That’s a lot of stray date formatting codes mixed with colons. If your colon is getting that jammed up, you might want to talk to a doctor.

[Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!

https://thedailywtf.com/articles/the-date-wrapper


Метки:  

CodeSOD: Did You Null This?

Среда, 08 Апреля 2020 г. 09:30 + в цитатник

If I were to catalog my biggest failings as a developer, it’s a carelessness around defensive programming. It’s tedious, and it takes work and forethought, and honestly, I just want to get the thing working and see the results. But I recognize it’s important, and work on developing that mindset.

Today’s anonymous submitter found some Java code that is extremely defensive.

public String bundle() {
// snip
        if (ISO8583.this == null)
            return null;
// snip
}

This code is deep down in a message parsing/constructing module, responsible for exchanging ISO 8583 messages- transactions for interacting with a payment card provider.

Now, this is the only return null in this method, and the calling code never actually checks for a null. So it’s probably pretty fortunate that this could never actually be null.

Well, “could” is perhaps too strong. It should never be null, but you’ll note here we’re using a “qualified” this. This means there’s a Java outer class involved, something like:

public class ISO8583 {
  public class MyInnerClass {
    public String bundle() {
      //snip
      if (ISO8583.this == null) {
        return null;
      }
      //snip
    }
  }
}

ISO8583.this refers to an instance of the outer class, which should have a value, but if you’re doing fancy reflection things, it might be null. You can reach inside the class and explicitly set it to null, if you wanted to for some reason. But you shouldn’t be doing fancy reflection things, right? Certainly not to muck with built-in behaviors, right? It performs badly, it’s complicated, and is usually YAGNI territory or premature abstractulation.

Our anonymous submitter adds:

My only hope is that this was a result of the fact that before joining this team, a previous developer got fancy into reflection and some how accessed this function from a non-instantiated object, but the reflection code is a WTF for another time.

Of course the previous developer was doing something “clever”. The real WTF is that the null check may have actually been necessary, even if it shouldn’t have been.

The entire ISO 8583 message layer has since been rewritten, but our submitter remains haunted by the implications of this block.

[Advertisement] Ensure your software is built only once and then deployed consistently across environments, by packaging your applications and components. Learn how today!

https://thedailywtf.com/articles/did-you-null-this


Метки:  

CodeSOD: To Repeat Yourself

Вторник, 07 Апреля 2020 г. 09:30 + в цитатник

Java’s history with web applications is, well, complicated. Java, heavily focused on being the True Object Oriented language, went the route of containers and service-providing classes and runtime bindings and dynamic hooks and lookups well before anyone else.

The core layer which underpins a lot of the web interactions is the Servlet specification. Servlets are just classes which are wired up to handle HTTP requests. Do whatever you want there. Slap a bunch of annotations for JAX-RS on there, and it’s a restful web service. Drop a JSP file in there, a it runs as a servlet with a template. Start playing with Java Server Faces? It’s servlets all the way down.

But what happens when you want to be even more Enterprise than Java normally is? What if you want a portal application with drop-in modules that can be configured from the front end? Portlets.

Portlets are servlets for portals. It’s the Java flavor of SharePoint development. Build a CMS. Build an ERP. Build any giant enterprise product, and Portlets are there for you. They inherit huge piles of functionality important to hooking into the portal. They’re a giant mess.

Which is why Jan G was working with a “legacy portlet”. No one ever wants to start a new portlet, so they’re all basically legacy from the minute they’re written. The previous developer didn’t really understand some of the key portlet methods or concepts.

private String getFullURLbyPlid(ThemeDisplay theme, String friendlyURL) {
    Layout selectedLayout = null;
    try {
        selectedLayout = LayoutLocalServiceUtil.getFriendlyURLLayout(theme.getLayout().getGroupId(), false, friendlyURL);
        if(null != selectedLayout) {
            return PortalUtil.getLayoutFriendlyURL(selectedLayout, theme);
        } else {
            return null;
        }
    } catch (PortalException e) {
        System.out.println(e);
        e.printStackTrace();
    } catch (SystemException e) {
        System.out.println(e);
        e.printStackTrace();
    }
    if (null != selectedLayout) {
        String url = ""; //theme.getPortalURL();
        try {
            url += PortalUtil.getLayoutFriendlyURL(selectedLayout, theme);
        } catch (PortalException e) {
            System.out.println(e);
            e.printStackTrace();
        } catch (SystemException e) {
            System.out.println(e);
            e.printStackTrace();
        }
        return url;
    }
    return null;
}

The first thing to note is the method name: getFullURLbyPlid- “Plid” being the “portlet-id”. This is a long integer, and you’ll note that it isn’t a parameter to the method at all.

Skimming through, we can also spot the exception handling blocks- all of which do both a System.out.println and an e.printStackTrace(). So this guarantees that on any error, it logs out the error twice.

But the real interesting thing is this method’s approach to exception handling. In our try block, we check for a selectedLayout, then we use PortalUtil.getLayoutFriendlyURL to look up the URL for this theme.

If we don’t find a correct layout? We return null, which is going to be fun for the calling code. But if we get an exception… we essentially try again.

The second block after the try/catch is just a repeat of the try/catch: if we don’t have a selected layout, try and use PortalUtil.getLayoutFriendlyURL again.

If at first, you don’t succeed, repeat the same call and hope it doesn’t throw an exception this time.

As an added bonus, we log the same errors again, guaranteeing that we’re going to have 4 copies of every error message in the logs, which will help to make sure we really see that error in there.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

https://thedailywtf.com/articles/to-repeat-yourself


Метки:  

CodeSOD: Now I Need an Injection

Понедельник, 06 Апреля 2020 г. 09:30 + в цитатник

Frankie was handed a pile of PHP and told, "Move this to a new host." The process didn't go well- simply copying the code to the server chucked out a 500 error. So Frankie started digging into the code.

Like a lot of PHP code, this code wasn't written. It happened. A long chain of revisions, emergency fixes, quick and dirty hacks, and "I dunno what I did, but that fixes it," meant that it was a twisty pile of spaghetti that wasn't drained properly and now is all sort of sticking together into a starch blob that only vaguely resembles the pasta it once was.

While trying to unpick the mess, Frankie spotted this:

public function executeQuery ($query) { $this->DbConnect(); $this->preventSQLInjection($query); $result=mysql_query($query); $this->DbClose(); return $result; }

The "important" line is preventSQLInjection($query). If you see that statement, you know something is horribly wrong. You're in that case of someone who knows enough to know that SQL injections are a threat, but only understands regexes as the solution.

private function preventSQLInjection($query) { $querySTR = strtoupper($query); $querySTR = str_replace("/**/", "", $querySTR); $querySTR = preg_replace("/\/\*(.+)\*\\//iSU", "", $querySTR); $querySTR = str_replace("/*", "", $querySTR); $querySTR = str_replace("*/", "", $querySTR); if (preg_match("/UNION(.*)SELECT/iSU", rawurldecode($querySTR))) die("erro"); return true; }

There isn't anything correct here. First, we make the string upper case. Of course, regexes can be case insensitive, so we don't need to do that. It's unnecessary, but I suppose not wrong.

Then, we use str_replace- a non-regex replace, to remove any empty comment blocks from the query. Then, we use a case insensitive regex to any "" followed by one or more of any character, followed by another "". Which… again, sounds like they're worried about comments, but this is a greedy operation, so SELECT /* some fields */ x, y, z FROM /* some table */ my_table would become SELECT / / my_table.

Then we strip any comment block indicators.

Finally, we check: if this query UNIONs another SELECT we just die, because we're good capitalists and we hate unions, apparently.

Now, yes, using comment blocks is a common way to break parsing so you can do your SQL injection. So this isn't completely misguided, but it's clearly wrong.

As Frankie sums up: "Just disregard all there is about the subject and implement your own solution. Beware of UNIONS and SELECTS, there may be demons. DROP it all for all I care."

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!

https://thedailywtf.com/articles/now-i-need-an-injection


Метки:  

Error'd: Just Pick Something, Dummy!

Пятница, 03 Апреля 2020 г. 09:30 + в цитатник

Dave L. writes, "Spotted an option on Lenovo's 'Pick Your Laptop by Spec' that seems to be aimed, possibly, at the less than experienced laptop buyer."

 

"Wow! Nothing's better than highlights like these!" wrote Jani P.

 

"You've heard about SOAP? Yeah, well look out world...here comes SOUP!" Paul G. wrote.

 

Chris S. writes, "Welcome to the Birmingham Airport! Courtesy of TeamViewer."

 

"I guess if I really like this movie, I can have it mounted on my wall. I hope the case is decorative," wrote Angela A.

 

Simon T. writes, "Just wondering, is this the same city where little Bobby Tables lives?"

 

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

https://thedailywtf.com/articles/just-pick-something-dummy


Метки:  

CodeSOD: Translatov'ano

Четверг, 02 Апреля 2020 г. 09:30 + в цитатник

Let’s say you’re a native English speaker. Let’s say you’re writing a library which is going to be used by Czech speakers, like our submitter Jan Krynick'y. You’ve been told to make sure the code is usuable by them, so you decided to use C#’s annotations to provide Czech documentation of various fields.

There’s just one problem: you don’t know Czech. You know enough to know that the Czech equivalent of “-ed”, as in “uploaded” is “-ov'ano”, so “uploadov'ano” seems perfectly reasonable to you. Czech documentation, done. It might not be the best choice, but they'll get the point.

There’s just one problem:

    public enum FeedProcessDirection  
    {
        [Description("Uploadov'ano")]  
        Downloaded = 1,

        [Description("Downloadov'ano")]  
        Uploaded = 2  
    }

The “offending person”, in Jan’s words, is no longer working with the organization, but Jan still thinks about ways in which to get revenge.

[Advertisement] Ensure your software is built only once and then deployed consistently across environments, by packaging your applications and components. Learn how today!

https://thedailywtf.com/articles/translatov-no


Метки:  

CodeSOD: Tern Java Into Python

Среда, 01 Апреля 2020 г. 09:30 + в цитатник

Thomas K was browsing around, trying to give folks some technical help. While doing that, he found a poor, belaguered soul who had been given a task: convert some Java code to Python.

This was the code:

if (xGrad * yGrad <= (float) 0 /*(1)*/
    ? Math.abs(xGrad) >= Math.abs(yGrad) /*(2)*/
        ? (tmp = Math.abs(xGrad * gradMag)) >= Math.abs(yGrad * neMag - (xGrad + yGrad) * eMag) /*(3)*/
            && tmp > Math.abs(yGrad * swMag - (xGrad + yGrad) * wMag) /*(4)*/
        : (tmp = Math.abs(yGrad * gradMag)) >= Math.abs(xGrad * neMag - (yGrad + xGrad) * nMag) /*(3)*/
            && tmp > Math.abs(xGrad * swMag - (yGrad + xGrad) * sMag) /*(4)*/
    : Math.abs(xGrad) >= Math.abs(yGrad) /*(2)*/
        ? (tmp = Math.abs(xGrad * gradMag)) >= Math.abs(yGrad * seMag + (xGrad - yGrad) * eMag) /*(3)*/
            && tmp > Math.abs(yGrad * nwMag + (xGrad - yGrad) * wMag) /*(4)*/
        : (tmp = Math.abs(yGrad * gradMag)) >= Math.abs(xGrad * seMag + (yGrad - xGrad) * sMag) /*(3)*/
            && tmp > Math.abs(xGrad * nwMag + (yGrad - xGrad) * nMag) /*(4)*/
    ) {
    magnitude[index] = gradMag >= MAGNITUDE_LIMIT ? MAGNITUDE_MAX : (int) (MAGNITUDE_SCALE * gradMag);
} else {
    magnitude[index] = 0;
}

I want you to note that this stack of ternaries is in the condition clause of an if. Worse, it also has side effects- several spots do an assignment like (tmp = Math.abs(xGrad * gradMag)). In the ternary.

And even in the if statement body, they’re so on the ternary train that they chuck another ternary on as a boundary check before they set the output value in magnitude[index].

I don’t know what help Thomas gave, but I hope it involved nuking the site from orbit. It’s the only way to be sure.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

https://thedailywtf.com/articles/tern-java-into-python


Метки:  

Wrecking the Curve

Вторник, 31 Марта 2020 г. 09:30 + в цитатник

FORTRAN punch card (public domain)

Most of our WTFs are produced on modern hardware, but today we're taking you back to the dawn of computing, back to the 1960s, when our submitter, Robert, was in college. Rob was taking a class in Numerical Analysis, which allowed people to submit their programs to the university computer (singular, as this was before computers were cheap enough to have a whole lab of 30+ of them just lying around for students). This involved using a keypunch machine to punch cards to run a FORTRAN program that might give you the answers to your homework. It was marginally faster than using a slide rule, until you factored in that students had low priority on the queue to submit their programs to be run, so they'd have to wait hours, if not days, to get access. Most students didn't even bother with the expensive machine, simply doing their maths the old-fashioned way and leaving it at that.

Our submitter, however, was clever.

You see, Rob had a part-time programming job in the evenings that made enough to pay for his schooling, something that was entirely possible in the 1960s though it may seem fantastical today. At this job, he had access to a much newer business computer: the IBM 1130, with a whopping memory capacity of 4,096 16-bit words. It was made for scientific purposes, but was also used by small businesses who were "sensitive to price concerns" (aka: frugal) and wanted a cheap machine that would run all their programs. Best of all, Rob had sole access to the machine all evening, meaning nobody would blink if he ran a quick program to do his homework in between batch jobs for the business.

However, he was used to running business programs, not scientific or mathematical ones. One subroutine package the business used frequently allowed for easier currency manipulation, but it required a compiler directive called "*ONE WORD INTEGERS". This limited integers to one word, which was sufficient for currency manipulation. Leaving it out would cause a number of headaches for the subroutine package they used, which expected it to be turned on.

I'm sure you can see where this is going: when Rob did his homework, he put the directive in place, making his answers a couple orders of magnitude less correct, as decimals were rounded far closer than they would've been using a slide rule. But just you wait, dear reader, for the real WTF is yet to come.

The day came for the instructor to return the graded papers, and to Rob's surprise, there was much grumbling and disgust. It seems almost everyone had messed up their homework, receiving markdowns for having incorrect answers. Everyone, that is, except Rob. Rob's paper sported a shiny red A.

"I see most of you had incorrect answers this time around," remarked the teacher, scowling. "One of you was clever enough to turn in a FORTRAN program that solved the problems correctly. I used that to produce the rubric to grade the rest of you, so don't come crying to me about it being a grader error."

Rob, being clever, decided to take his A and slink off in shame once he realized what had happened. Thankfully, the rest of the class never found out who had busted the curve—which was good for Rob's mental health and his kneecaps.

[Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!

https://thedailywtf.com/articles/wrecking-the-curve


Метки:  

CodeSOD: Just a Bit Bad

Понедельник, 30 Марта 2020 г. 09:30 + в цитатник

Eyal N works on some code which relies on "bit matrices": 2D arrays of bits. Since they are working in C, in practice this means that they have one giant array of bytes and methods to handle getting and setting specific entries in the matrix.

One day, Eyal sat down to do a remote pair-programming session with a co-worker. It started out alright, but the hours ticked by, the problem they were dealing with kept showing thornier and thornier edge cases, and instead of calling it a day, they worked late into the night.

The next morning was full of regrets, both in terms of too little sleep and in terms of code artifacts. The code that they'd written over night was tangled, incoherent nonsense. It compiled, and it looked like the outputs were correct, but the actual process was as opaque as lead painted with Vantablack.

Deep inside that pile of sewage-smeared spaghetti code, Eyal found that they had found a special approach to zeroing out a block of memory.

Now, if you've ever worked in C, you know that creating and setting blocks of memory is easy- arguably too easy. If, for example, you want an array of bytes that's initialized to zero, you can do it with one step using the method calloc. If, for some reason, you want to do it in two steps, you can combine malloc with a memset call.

Or, if you want to do it in many, many more steps, you can do this:

static void matrix_set(matrix_t mat, size_t row, size_t col, bool val, size_t dim) { set_bit(mat, row * dim + col, val); } // ... for (size_t i = 0; i < dim; i++) { for (size_t j = 0; j < dim; j++) { matrix_set(mat, i, j, 0, dim); } }

Starting with the for loop, you can see that they call matrix_set once for every bit in the matrix. matrix_set itself just calls out to set_bit after doing a little arithmetic to find the correct 1D index for a given 2D coordinate.

It's a simple enough bit of code. It certainly doesn't exhibit any deep horrors, but it's impressive that they managed to turn a single, high-performance operation into a gruelingly slow operation which needs to set values eight times for every byte in the matrix.

"I was practically sleeping in my chair, struggling just to keep my eyelids open, and wasn't exactly paying attention to what was going on," Eyal adds in defense.

They didn't supply the implementation of set_bit, but the method poses a bit of another problem. No matter how you slice it, you need to & or | a value with the current value of the byte containing the bit. Which means you have to read the current value of the bit. Or, as Eyal explains:

I later realized that this code technically exhibits undefined behavior, since clearing the first bit in every byte involves reading freshly-allocated, uninitialized memory.

The moral of the story: get some sleep.

https://thedailywtf.com/articles/just-a-bit-bad


Метки:  

Error'd: You Must Agree!

Пятница, 27 Марта 2020 г. 09:30 + в цитатник

"Apparently they don't want you to Strongly Agree with everything they say!" wrote David S.

 

"When updating some Logitech software recently, I learned that under the right conditions, you can update that which doesn't exist yet," wrote David N.

 

Eric P. writes, "I guess that’s what I get for requesting Ol’ Dirty Bastard from the jukebox at my local dive bar...which, ironically, was the only sign of any windows in the joint!"

 

"Maybe I really DO need the five minute overview!" Cindy H. wrote.

 

Marius E. writes, "Altough we did make it to Amsterdam in time I wonder how fast we were going?"

 

"I'm going to hibernate for the next couple thousand years so I don't have to wait so long," wrote Erwin.

 

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

https://thedailywtf.com/articles/you-must-agree


Метки:  

Понравилось: 1 пользователю

CodeSOD: An Ugly Mutation

Четверг, 26 Марта 2020 г. 09:30 + в цитатник

If there’s a hell for programmers, it probably involves C-style strings on some level. C’s approach to strings is rooted in arrays, and arrays are rooted in pointers, and now suddenly everything is memory manipulation, and incautious printf and memcpy commands cause buffer overruns. I'm oversimplifying and leaving out some of the better libraries that make this less painful, but the roots remain the same.

Fortunately, most of the time, we’re not working with that sort of string representation. If you’re using a high-level language, like Java, you get all sorts of perks, like abstract string methods, no concerns about null termination, and immutability by default.

In C, a string is just a pointer to a block of memory and you can do anything you like with it. In Java, a string is an object that can’t have its contents changed.

Cid has a co-worker that comes from a C background, and constantly equates “references” in Java to “pointers” in C, which is largely accurate, but highlights certain misunderstandings in this case.

Since, obviously, every non-primitive variable is holding an object reference, and it’s like pointers, and that means if you mutate the object in one place, it mutates everywhere. Much like a C-string, it’s just a pointer to memory and anybody can do anything.

That means, when this developer writes getters and setters for string properties, they want to make sure that nobody’s ever sharing a reference. That means thousands of lines of code like this:

public String getValue() {
  if (value == null) {
    return null;
  }
  else {
    return new String(value);
  }
}

public void setValue(String value) {
  if (value == null) {
    this.value = null;
  }
  else {
    if (value.trim().length == 0) {
      this.value = null;
    }
    else {
      this.value = new String(value);
      }
  }
}

Every string property gets that treatment, and there are a lot of string properties. It’s a great stress test for the garbage collector; there’s no reason to spin up extra instances of these immutable objects, but we do it anyway.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

https://thedailywtf.com/articles/an-ugly-mutation


Метки:  

CodeSOD: String Up Your Replacement

Среда, 25 Марта 2020 г. 09:30 + в цитатник

Generating SQL statements is a necessary feature of many applications. String concatenation is the most obvious, and also the most wrong way to do this. Most APIs these days offer a way to construct SQL statements out of higher-level abstractions, whether we’re talking about .NET’s LINQ, or the QueryBuilder objects in many languages.

But let’s say you’re doing string concatenation. This means you need to have lots of literals in your code. And literal values, as we know, are bad. So we need to avoid these magic values by storing them in variables.

That, at least, seems to be the logic behind this code. Richard G just inherited this C# code from a senior engineer who left:

String SQLstr2;
String cDate = ("'Date'");
String c0 = ("'0'");
String c1 = ("'1'");
String c2 = ("'2'");
String c3 = ("'3'");
String c4 = ("'4'");
String c5 = ("'5'");
String c6 = ("'6'");
String c7 = ("'7'");
String c8 = ("'8'");
String c9 = ("'9'");
String c10 = ("'10'");
String c11 = ("'11'");
String c12 = ("'12'");
String c13 = ("'13'");
String c14 = ("'14'");
String c15 = ("'15'");
String c16 = ("'16'");
String c17 = ("'17'");
String c18 = ("'18'");
String c19 = ("'19'");
String c20 = ("'20'");
String c21 = ("'21'");
String c22 = ("'22'");
String c23 = ("'23'");

// more code

Double[] CancelShiftArray = new Double[24];
String sPGA;
String sDate;

// more code

SQLstr2 = "INSERT INTO TBL_OUTPUT_DAILY (PGA ," + (cDate.Replace("'", "\"")) + "," + (c0.Replace("'", "\"")) + "," +
(c1.Replace("'", "\"")) + "," + (c2.Replace("'", "\"")) + "," + (c3.Replace("'", "\"")) + "," + (c4.Replace("'", "\"")) + "," +
(c5.Replace("'", "\"")) + "," + (c6.Replace("'", "\"")) + "," + (c7.Replace("'", "\"")) + "," + (c8.Replace("'", "\"")) + "," +
(c9.Replace("'", "\"")) + "," + (c10.Replace("'", "\"")) + "," + (c11.Replace("'", "\"")) + "," + (c12.Replace("'", "\"")) + "," +
(c13.Replace("'", "\"")) + "," + (c14.Replace("'", "\"")) + "," + (c15.Replace("'", "\"")) + "," + (c16.Replace("'", "\"")) + "," +
(c17.Replace("'", "\"")) + "," + (c18.Replace("'", "\"")) + "," + (c19.Replace("'", "\"")) + "," + (c20.Replace("'", "\"")) + "," +
(c21.Replace("'", "\"")) + "," + (c22.Replace("'", "\"")) + "," + (c23.Replace("'", "\"")) +
") VALUES ('" + sPGA + "' , to_timestamp('" + sDate + "','dd-mm-yyyy') ,'" + CancelShiftArray[0] + "','" + CancelShiftArray[1] + "','" +
CancelShiftArray[2] + "','" + CancelShiftArray[3] + "','" + CancelShiftArray[4] + "','" + CancelShiftArray[5] + "','" +
CancelShiftArray[6] + "','" + CancelShiftArray[7] + "','" + CancelShiftArray[8] + "','" + CancelShiftArray[9] + "','" +
CancelShiftArray[10] + "','" + CancelShiftArray[11] + "','" + CancelShiftArray[12] + "','" + CancelShiftArray[13] + "','" +
CancelShiftArray[14] + "','" + CancelShiftArray[15] + "','" + CancelShiftArray[16] + "','" + CancelShiftArray[17] + "','" +
CancelShiftArray[18] + "','" + CancelShiftArray[19] + "','" + CancelShiftArray[20] + "','" + CancelShiftArray[21] + "','" +
CancelShiftArray[22] + "','" + CancelShiftArray[23] + "')";

Each one of the cN variables has single quotes in the string. When we use them, we escape the single quote into a double quote. Why not just put the double quote in the original? At a guess, they didn’t know how. They knew how to use Replace to escape them, because they found that code on Stack Overflow once, but didn’t understand how it worked. I think they also didn’t understand how for loops worked.

Or really, how a lot of things worked.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

https://thedailywtf.com/articles/string-up-your-replacement


Метки:  

CodeSOD: Accidental Toast of the Town

Вторник, 24 Марта 2020 г. 09:30 + в цитатник

Don't you just love it when some part of your app just suddenly and magically STOPS working all of a sudden?

Our submitter David sure does (not). While working on his Android app, much to his surprise, he noticed that after one build, it wasn't displaying pop-up toast style notifications.

He was positively stymied. It's not like this functionality is weird and custom with black magic UI coding behind it. No, this is something basic and ancient that one would normally expect to just work. However, upon checking the function behind the notifications below, the reason became immediately clear. At some point, David had accidentally pasted a URL in the middle of the function.

public void showToast(final String msg) {
        // Show small piece of text at the bottom of screen
        runOnUiThread(new Runnable() {
            public void run() {
                CharSequence text = msg;
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(con, text, duration);
                http://example.com/ toast.show();
                Log.d("toast", msg);
            }
        });
    }

Normally, one would expect that a mistake like this would have set off alarms at compilation time but in this case, it's actually valid. In Java, the "http:" acts as a labeled statement, which is logically similar to a "goto" statement in other languages, and the // which follows it commented out the rest of the line which contains the bit of code that actually shows the toast pop-up.

Thankfully this sort of misery only applies to Java...right?

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

https://thedailywtf.com/articles/accidental-toast-of-the-town


Метки:  

Поиск сообщений в rss_thedaily_wtf
Страницы: 124 ... 90 89 [88] 87 86 ..
.. 1 Календарь