Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Lounge

Name: Voiden Froze !!Bj5xlFz8N6pmNy3 2011-12-14 9:54

Okay /prog/ let's have a code-off!

The most fun way of carrying text over long lines, typical to that of your favorite    , in the language of your choice.

Let's kick off with some simple FIOCthp:


# -*- coding: cp1252 -*-
MAX_LINE_LENGTH =  60
a="""The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:"""

def cut_lines(words,result,line=''):
    if len(words):
        if len(words[0])>MAX_LINE_LENGTH:
            result.append(words.pop(0))
        else:
            test = line+words[0]+' '
            if len(test)<=MAX_LINE_LENGTH:
                words.pop(0)
                cut_lines(words,result,test)
            else:
                result.append(line)
                cut_lines(words,result)
    else:
        result.append(line)
       
def carry_lines(a):
    words=a.split()
    result=[]
    cut_lines(words,result)
    return result

for element in carry_lines(a):
    print element

Name: Anonymous 2011-12-14 10:42



#include "BatteryShell.h"

#include "base/SingletonHolder.h"

#include "COMv2/BatteryObjClass.h"
#include "COMv2/BatteryInstance.h"

#ifndef NO_SIM_GUI
#include "GUI/BatteryPanel.h"
#endif

//##ModelId=3F219FFC0203
DiscoverPolicy msf::BatteryShell::_policy;

//##ModelId=3FE235FD0272
//##ModelId=3FE235FD0286
//##ModelId=3FE235FD0287
msf::BatteryShell::BatteryShell(string name) :
    SimShell(name, _policy)
{
    Output::debug(DBG_SIM, DBG_CONSTRUC, "BatteryShell::BatteryShell(%s)\n", name.c_str());
    int updates;
    int acquisitions;
    _policy.requestSizes(updates, acquisitions);
    if ( ! updates ) {
    _policy.addUpdateRequest(
        SingletonHolder<msf::BatteryObjClass>::Instance().getAttributeHandle(
        msf::BatteryObjClass::VOLTAGE));
    _policy.addUpdateRequest(
        SingletonHolder<msf::BatteryObjClass>::Instance().getAttributeHandle(
        msf::BatteryObjClass::CAPACITY));
    _policy.addUpdateRequest(
        SingletonHolder<msf::BatteryObjClass>::Instance().getAttributeHandle(
        msf::BatteryObjClass::MAXIMUMCAPACITY));
    }
#ifndef NO_SIM_GUI
    _panel = new BatteryPanel(name);
    if ( getStatus() != GenericObjShell::READY ) {
    _panel->disable();
    }
#endif
}

//##ModelId=3FE235FD027C
msf::BatteryShell::~BatteryShell()
{
#ifndef NO_SIM_GUI
    if ( _panel ) delete _panel;
#endif
    Output::debug(DBG_SIM, DBG_DESTRUC, "~BatteryShell()\n");
}

void BatteryShell::reflect(ftk::HANDLE h)
{
#ifndef NO_SIM_GUI
    static ftk::HANDLE maxCapacity =
        SingletonHolder<BatteryObjClass>::Instance().getAttributeHandle(BatteryObjClass::MAXIMUMCAPACITY);
    static ftk::HANDLE currentCapacity =
        SingletonHolder<BatteryObjClass>::Instance().getAttributeHandle(BatteryObjClass::CAPACITY);
    static ftk::HANDLE currentVoltage =
        SingletonHolder<BatteryObjClass>::Instance().getAttributeHandle(BatteryObjClass::VOLTAGE);
    static ftk::HANDLE nomVoltage =
        SingletonHolder<BatteryObjClass>::Instance().getAttributeHandle(BatteryObjClass::NOMINALVOLTAGE);
   
    BatteryInstance* battery = dynamic_cast<BatteryInstance*>(supplierGet());
    BatteryPanel* panel = dynamic_cast<BatteryPanel*>(_panel);

    if ( battery && panel ) {

    if (h == maxCapacity) {
        panel->setMaximumCapacity(battery->maximumCapacityGet());
        return;
    }
    if (h == currentCapacity) {
        panel->setCurrentCapacity(battery->capacityGet());
        return;
    }
    if (h == nomVoltage) {
        panel->setNominalVoltage(battery->nominalVoltageGet());
        return;
    }
    if (h == currentVoltage) {
        panel->setCurrentVoltage(battery->voltageGet());
        return;
    }
    }
#endif
}

Name: Anonymous 2011-12-14 11:45

word-wrap: break-word;

Name: Anonymous 2011-12-15 4:04

...and the [spoiler][b][u]ZEN PROGRAMMING[/b][/u][/spoiler] goes to
>>2

Name: Anonymous 2011-12-15 4:12

>>4
it's [b][i][o][u] [/u][/o][/i][/b],

``fagget''

Name: Anonymous 2011-12-15 4:33

Name: Anonymous 2011-12-15 4:40

/* fold -- wrap each input line to fit in specified width.
   Copyright (C) 1991, 1995-2006, 2008-2011 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>;.  */

/* Written by David MacKenzie, djm@gnu.ai.mit.edu. */

#include <config.h>

#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>

#include "system.h"
#include "error.h"
#include "fadvise.h"
#include "quote.h"
#include "xstrtol.h"

#define TAB_WIDTH 8

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "fold"

#define AUTHORS proper_name ("David MacKenzie")

/* If nonzero, try to break on whitespace. */
static bool break_spaces;

/* If nonzero, count bytes, not column positions. */
static bool count_bytes;

/* If nonzero, at least one of the files we read was standard input. */
static bool have_read_stdin;

static char const shortopts[] = "bsw:0::1::2::3::4::5::6::7::8::9::";

static struct option const longopts[] =
{
  {"bytes", no_argument, NULL, 'b'},
  {"spaces", no_argument, NULL, 's'},
  {"width", required_argument, NULL, 'w'},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {NULL, 0, NULL, 0}
};

void
usage (int status)
{
  if (status != EXIT_SUCCESS)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
             program_name);
  else
    {
      printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
"),
              program_name);
      fputs (_("\
Wrap input lines in each FILE (standard input by default), writing to\n\
standard output.\n\
\n\
"), stdout);
      fputs (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
"), stdout);
      fputs (_("\
  -b, --bytes         count bytes rather than columns\n\
  -s, --spaces        break at spaces\n\
  -w, --width=WIDTH   use WIDTH columns instead of 80\n\
"), stdout);
      fputs (HELP_OPTION_DESCRIPTION, stdout);
      fputs (VERSION_OPTION_DESCRIPTION, stdout);
      emit_ancillary_info ();
    }
  exit (status);
}

/* Assuming the current column is COLUMN, return the column that
   printing C will move the cursor to.
   The first column is 0. */

static size_t
adjust_column (size_t column, char c)
{
  if (!count_bytes)
    {
      if (c == '\b')
        {
          if (column > 0)
            column--;
        }
      else if (c == '\r')
        column = 0;
      else if (c == '\t')
        column += TAB_WIDTH - column % TAB_WIDTH;
      else /* if (isprint (c)) */
        column++;
    }
  else
    column++;
  return column;
}

/* Fold file FILENAME, or standard input if FILENAME is "-",
   to stdout, with maximum line length WIDTH.
   Return true if successful.  */

static bool
fold_file (char const *filename, size_t width)
{
  FILE *istream;
  int c;
  size_t column = 0;        /* Screen column where next char will go. */
  size_t offset_out = 0;    /* Index in `line_out' for next char. */
  static char *line_out = NULL;
  static size_t allocated_out = 0;
  int saved_errno;

  if (STREQ (filename, "-"))
    {
      istream = stdin;
      have_read_stdin = true;
    }
  else
    istream = fopen (filename, "r");

  if (istream == NULL)
    {
      error (0, errno, "%s", filename);
      return false;
    }

  fadvise (istream, FADVISE_SEQUENTIAL);

  while ((c = getc (istream)) != EOF)
    {
      if (offset_out + 1 >= allocated_out)
        line_out = X2REALLOC (line_out, &allocated_out);

      if (c == '\n')
        {
          line_out[offset_out++] = c;
          fwrite (line_out, sizeof (char), offset_out, stdout);
          column = offset_out = 0;
          continue;
        }

    rescan:
      column = adjust_column (column, c);

      if (column > width)
        {
          /* This character would make the line too long.
             Print the line plus a newline, and make this character
             start the next line. */
          if (break_spaces)
            {
              bool found_blank = false;
              size_t logical_end = offset_out;

              /* Look for the last blank. */
              while (logical_end)
                {
                  --logical_end;
                  if (isblank (to_uchar (line_out[logical_end])))
                    {
                      found_blank = true;
                      break;
                    }
                }

              if (found_blank)
                {
                  size_t i;

                  /* Found a blank.  Don't output the part after it. */
                  logical_end++;
                  fwrite (line_out, sizeof (char), (size_t) logical_end,
                          stdout);
                  putchar ('\n');
                  /* Move the remainder to the beginning of the next line.
                     The areas being copied here might overlap. */
                  memmove (line_out, line_out + logical_end,
                           offset_out - logical_end);
                  offset_out -= logical_end;
                  for (column = i = 0; i < offset_out; i++)
                    column = adjust_column (column, line_out[i]);
                  goto rescan;
                }
            }

          if (offset_out == 0)
            {
              line_out[offset_out++] = c;
              continue;
            }

          line_out[offset_out++] = '\n';
          fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
          column = offset_out = 0;
          goto rescan;
        }

      line_out[offset_out++] = c;
    }

  saved_errno = errno;

  if (offset_out)
    fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);

  if (ferror (istream))
    {
      error (0, saved_errno, "%s", filename);
      if (!STREQ (filename, "-"))
        fclose (istream);
      return false;
    }
  if (!STREQ (filename, "-") && fclose (istream) == EOF)
    {
      error (0, errno, "%s", filename);
      return false;
    }

  return true;
}

int
main (int argc, char **argv)
{
  size_t width = 80;
  int i;
  int optc;
  bool ok;

  initialize_main (&argc, &argv);
  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  atexit (close_stdout);

  break_spaces = count_bytes = have_read_stdin = false;

  while ((optc = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1)
    {
      char optargbuf[2];

      switch (optc)
        {
        case 'b':        /* Count bytes rather than columns. */
          count_bytes = true;
          break;

        case 's':        /* Break at word boundaries. */
          break_spaces = true;
          break;

        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
          if (optarg)
            optarg--;
          else
            {
              optargbuf[0] = optc;
              optargbuf[1] = '\0';
              optarg = optargbuf;
            }
          /* Fall through.  */
        case 'w':        /* Line width. */
          {
            unsigned long int tmp_ulong;
            if (! (xstrtoul (optarg, NULL, 10, &tmp_ulong, "") == LONGINT_OK
                   && 0 < tmp_ulong && tmp_ulong < SIZE_MAX - TAB_WIDTH))
              error (EXIT_FAILURE, 0,
                     _("invalid number of columns: %s"), quote (optarg));
            width = tmp_ulong;
          }
          break;

        case_GETOPT_HELP_CHAR;

        case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);

        default:
          usage (EXIT_FAILURE);
        }
    }

  if (argc == optind)
    ok = fold_file ("-", width);
  else
    {
      ok = true;
      for (i = optind; i < argc; i++)
        ok &= fold_file (argv[i], width);
    }

  if (have_read_stdin && fclose (stdin) == EOF)
    error (EXIT_FAILURE, errno, "-");

  exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
}

Name: Anonymous 2011-12-15 5:39


#lang racket
(define MAX_LINE_LENGTH 60)
(define wordlist "The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:")
(define (everything wrds)
  (define-values (_jk lst rst)
    (for/fold ([cnt 0] [lac '()] [tac '()])
      ([w (regexp-split #rx" +" wrds)])
      (let ([a (+ 1 cnt (string-length w))])
        (if (> a MAX_LINE_LENGTH)
            (values (+ 1 0 (string-length w)) (cons w '()) (cons (reverse lac) tac))
          (values a (cons w lac) tac)))))
  (for ([x (reverse (cons lst rst))])
    (printf "~a~n" (string-append* (add-between x " ")))))
(everything wordlist)

Name: Frozen Maiden 2011-12-15 6:10

>>1

for element in carry_lines(a * 20):
    print element

RuntimeError: maximum recursion depth exceeded

Name: Anonymous 2011-12-15 6:12

Here's a quick hack I just wrote (bad formatting to make it into an "one"-liner, use Emacs to format it if you want to actually read it):

(defun word-wrap (string max-length &aux (tlen max-length)) 
  (reduce #'(lambda (a b) (if b (concatenate 'string a (string (if (< (+ (length a) (length b)) tlen) #\  (prog1 #\Newline (setq tlen (+ max-length (length a)))))) b) a)) (split-sequence #\  string)))


The only major issue with it is that it won't eat excess whitespace if you have any (instead they are added to the line as seen fit).

I usually just write the >>7-equivalent for most of my word-wrapping needs (manually walking through spaces and seeking until the end of the next word), but that's boring and no fun to post on /prog/.

Name: Anonymous 2011-12-15 7:08

check 'em

Name: Rozen Maiden 2011-12-15 7:09

>>1
Also, try a = 'The list methods make me ' + 'x' * 65 + ' hard'
I've never seen a more pathetic "code-off" challenge, I think.

Name: Anonymous 2011-12-15 7:43

drop 1 . concat . snd . mapAccumL (\l x -> let l' = length x in if l + l' > 60 then (l', '\n':x) else (l+l', ' ':x)) 0 . words

Name: Anonymous 2011-12-15 8:27

>>13
Category Theory is shit.

Name: not >>13 2011-12-15 8:37

>>14
Symta-guy, are you hating it merely because it's used in Haskell? Your logic does not hold much water, it's the same kind of 'shun by association' broken logic you're using when hating on various math that people of a certain nationality have worked on.

Name: Anonymous 2011-12-15 8:41

>>15
I hate it because it fallbacks to good old http://en.wikipedia.org/wiki/Proof_by_verbosity

Name: Anonymous 2011-12-15 8:48

>>16
Except you can always verify the results by hand or even verify them formally with a theorem prover (there is quite a lot of formalized Category Theory).

However, it's true that CT is quite an abstract and probably not enough people know/understand it in detail.

Name: Anonymous 2011-12-15 9:12

>>17
If the result depends on "Infinity" (wihch is primary requirement for CT), then the result is false by definition of being false.

Name: Anonymous 2011-12-15 9:14

>>18
I don't know a single mathematical theory that doesn't have some implied infinities lurking around. Even the most finitary systems will tend to have at least up to countable infinities appearing in their models and thus lacking finite consistency proofs.
Even computation which is universal has a countable infinity of programs.

Name: Anonymous 2011-12-15 9:36

>>19
Don't feed the ``finitist'' troll, please. He is boring.

Also, CT does not depend on the notion of "infinity" or "set", so you should probably abstain from defending it, seeing as you are not really qualified for that.

Name: Anonymous 2011-12-15 9:44

>>20
CT can talk about 'Infinity' or some specific 'Set theory', as it can talk about most mathematical structures. I've only read introductory material about CT, and as far as I can tell, it's mostly about morphisms, functions and finding all kinds of regularities within mathematical structures which map well to those concepts (and concepts building upon them).

Name: Anonymous 2011-12-15 9:48

CT does not depend on the notion of "infinity" or "set"
Due to hype around CT and total uselessness of wiki-article, I asked forcer-jews "what is ther category theory good for?" and was pointed to the "categories for the working mathematician" book, which I torrented. The book used notions of "set" and "infinity" from the first pages, so I stopped reading it immidiately. Such books should be burned.

>>19
Mathematics is shit.

>>20
He isn't troll. He seriously proposes ban on mathematics and real holocaust on jews.

Name: Anonymous 2011-12-15 9:56

>>16
The list methods make me xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx hard


def cut_lines(words,result,width,line=''):
    if len(words):
        if len(words[0])>=MAX_LINE_LENGTH:
            result.append(words.pop(0))
            cut_lines(words,result,width)
        else:
            test = line+words[0]+' '
            if len(test)<=MAX_LINE_LENGTH:
                words.pop(0)
                cut_lines(words,result,width,test)
            else:
                result.append(line)
                cut_lines(words,result,width)
    else:
        result.append(line)
       
def carry_lines(a, width=MAX_LINE_LENGTH):
    if len(a)<=width: return[a]
    words  = a.split()
    result = []
    cut_lines(words,result,width)
    return result

for element in carry_lines(a):
    print element

Name: Anonymous 2011-12-15 10:06

>>19
Protip: infinity is made-up bullshit that doesn't exist. Ultrafinitism ftw.

Name: Anonymous 2011-12-15 10:31

>>23
Quoting failure. Also, lrn2python, FFS.
def wrap_lines(words):
    line, line_len = [], 0
    for word in words:
        if line_len:
            line_len += 1 + len(word)
            if line_len <= MAX_LINE_LENGTH:
                line.append(word)
                continue
            yield line
        line, line_len = [word], len(word)
    if line_len: yield line

Name: Anonymous 2011-12-15 10:44

>>24
It's imposible to properly define a formal system that works with ultra-finitism, not only that, it makes sense for me to talk about any finite, but unbounded values (classical finitism), but it makes no sense to pick some particular value and say that that's it and no number exists beyond that. I have no problem with someone rejecting uncountable infinities, but rejecting the potential or countable infinity seems untenable.

Name: Anonymous 2011-12-15 10:54

>>26
What if I pick aleph-null as the last existing number?

Name: Anonymous 2011-12-15 10:57

>>27
You'll break most of the math theorems.

Name: Anonymous 2011-12-15 11:01

>>26
rejecting the potential or countable infinity seems untenable.
It should be banned by the law, like sharia Islam bans usury and alcoholism. All arguing jews should be sent to their "God".

Name: Anonymous 2011-12-15 11:14

>>26
but it makes no sense to pick some particular value and say that that's it and no number exists beyond that
You're absolutely right. Good thing ultrafinitists don't do that!

Name: Anonymous 2011-12-15 12:12

def fold(text, width=80)
  folded = []; line = ""
  text.split().each do |word|
    word.chars.each_slice(width) do |slice|          # slice huge words
      slice = slice.join
      joiner = line.empty? ? "" : " "                # no space at line start
      if (line + joiner + slice).length > width then
        folded << line; line = slice                 # start new line
      else
        line += joiner + slice                       # append to current line
      end
    end
  end
  return (folded << line).join "\n"
end

puts fold ARGF.read

Name: Anonymous 2011-12-16 6:46

>>28
You'll break most of the math theorems.
How so? I wouldn't break any theorems concerned with finite or countable initial segments of N, would I?

Name: Anonymous 2011-12-16 7:19

>>31
what is the purpose of joining lines if 1/3 of them are empty?
      end
    end
  end
  return #...
end


oh ruby, you were sexy until i needed to fix some broken libs...

Name: Anonymous 2011-12-16 8:49

>>27
Except Aleph-Null isn't a number, it's a cardinal.
It may be the cardinal of the natural numbers, but Peano Arithmetic works fine even if you don't consider it within the context of some set theory.
>>30
If you keep the finite numbers unbounded, you still get countable infinity. Even if you limit numbers up to some bound, you'd still get countable infinity when you talk about theorems within the system.


This all depends on what axiomatic system you pick. You're free to pick something that doesn't talk about infinity directly (such as Peano Arithmetic or lesser), but you still get infinity in some forms when you analyze the metamathematical properties of such systems.

Name: Anonymous 2011-12-16 9:20

>>34
Infinity doesn't exist. Get over it. You can analyze literature all you want but elves don't exist.

Name: Anonymous 2011-12-16 9:37

>>35
Defining the finite without touching the infinite is much harder than you think.

Name: Anonymous 2011-12-16 12:29

>>36
A rule for generating the next value has no implied infinity except to someone who wants to beg the question of infinity in the first place.

Infinity and the axiom of choice are the highest levels of bullshit ever imagined by anyone outside Bjarne.

Name: Anonymous 2011-12-16 12:42

>>37
What does the rule operate on? If so, how many elements can it operate on?

Name: Anonymous 2011-12-16 14:17

>>38
What does the rule operate on?
Numbers.
If so, how many elements can it operate on?
Dunno, try it and see.

Name: Anonymous 2011-12-16 15:04

>>39
Dunno, try it and see.
But you're talking about an abstract system that shouldn't depend on physical limits, how much money you have for hardware or how big this universe happens to be. If you refuse to talk about such abstract systems on the virtue of them not always being physically implementable, then just say so. Another thing that might be worth talking about is this: if the universe is computable, you cannot compute it from the inside, thus an ultra-finitist can never seriously talk about physical law in his systems.

Don't change these.
Name: Email:
Entire Thread Thread List