问:
A cube of text ݀
Last time you made a square of text, but now, can you make a cube of text?

The Challenge

Given a string, output the string in the form of a cube.

You can assume the string will always have 2 chars or more, and will only have printable ascii characters.

How to Make a Text Cube

Test Cases

```<code>Input:
Test

Output:
   Test
  e  ss
 s  e e
tseT  T
s  e e
e  ss
Test

Input:
Hello, world!

Output:
            Hello, world!
           e           dd
          l           l l
         l           r  r
        o           o   o
       ,           w    w

     w           ,      ,
    o           o       o
   r           l        l
  l           l         l
 d           e          e
!dlrow ,olleH           H
d           e          e
l           l         l
r           l        l
o           o       o
w           ,      ,

,           w    w
o           o   o
l           r  r
l           l l
e           dd
Hello, world!

Input:
Hi

Output:
 Hi
iHH
Hi
</code>```

Reference Implementation in Python

text = raw_input("Enter a string: ")

print " " * (len(text) - 1) + text

spaces = len(text) - 2
_spaces = spaces

for i in range(1, len(text) - 2 + 1):
    print " " * spaces + text[i] + " " * _spaces + text[(i + 1) * -1] + " " * (_spaces - spaces) + text[(i + 1) * -1]
    spaces -= 1

print text[::-1] + " " * _spaces + text[0]

spaces = _spaces - 1

for i in range(1, len(text) - 2 + 1):
    print text[(i + 1) * -1] + " " * _spaces + text[i] + " " * spaces + text[i]
    spaces -= 1

print text
```

<h2>Rules</h2>

<ul>
<li>This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted.</li>
<li>Standard loopholes are disallowed.</li>
<li>Trailing newline and trailing spaces are allowed.</li>
</ul>

<h2>Leaderboard</h2>

<p>Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* Configuration */

var QUESTION_ID = 92410; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}</code>```

body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>Link</td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>Link</td></tr>
  </tbody>
</table></code>```

答:
Java 7, 283 bytes

```<code>void a(String s){int h=s.length(),n=h*2-1,t=n-h,u=n-1;char[][]c=new char[n][n];for(int i=0;i<h;i++){c[0][t+i]=c[i][t-i]=c[t][t-i]=c[t+i][t]=c[t+i][u-i]=c[t-i][t+i]=c[t-i][u]=c[u][i]=c[u-i][0]=s.charAt(i);}for(int y=0;y<n;y++){System.out.println(new String(c[y]).replace('\0',' '));}}
</code>```

Try it here!

Ungolfed:

```<code>void a(String s) {
    int length=s.length(),
        n=length*2-1,
        mid=n-length,
        doubleMid=n-1;
    char[][]c=new char[n][n];
    for(int i=0;i<length;i++) {
        c[0][mid+i]=
        c[i][mid-i]=
        c[mid][mid-i]=
        c[mid+i][mid]=
        c[mid+i][doubleMid-i]=
        c[mid-i][mid+i]=
        c[mid-i][doubleMid]=
        c[doubleMid][i]=
        c[doubleMid-i][0]=s.charAt(i);
    }
    for(int y=0;y<n;y++){
        System.out.println(new String(c[y]).replace('\0',' '));
    }
}
</code>```

Title: A cube of text ݀

Body:
Java 7, 283 bytes

void a(String s){int h=s.length(),n=h*2-1,t=n-h,u=n-1;char[][]c=new char[n][n];for(int i=0;i<h;i++){c[0][t+i]=c[i][t-i]=c[t][t-i]=c[t+i][t]=c[t+i][u-i]=c[t-i][t+i]=c[t-i][u]=c[u][i]=c[u-i][0]=s.charAt(i);}for(int y=0;y<n;y++){System.out.println(new String(c[y]).replace('\0',' '));}}

Try it here!

Ungolfed:

void a(String s) {
    int length=s.length(),
        n=length*2-1,
        mid=n-length,
        doubleMid=n-1;
    char[][]c=new char[n][n];
    for(int i=0;i<length;i++) {
        c[0][mid+i]=
        c[i][mid-i]=
        c[mid][mid-i]=
        c[mid+i][mid]=
        c[mid+i][doubleMid-i]=
        c[mid-i][mid+i]=
        c[mid-i][doubleMid]=
        c[doubleMid][i]=
        c[doubleMid-i][0]=s.charAt(i);
    }
    for(int y=0;y<n;y++){
        System.out.println(new String(c[y]).replace('\0',' '));
    }
}


问:
My Squiggly Lamp
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.

Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.

Examples:

Input:2

Output:

```
/--\
 ()
 ()
/__\
```

Input:3

Output:

```
/--\
 ()
 ()
 ()
/__\
```

Input:5

Output:

```
/--\
 ()
 ()
 ()
 ()
 ()
/__\
```

Rules:

0 & negative numbers don't matter

To give the lamps (an this challenge) more of a variety, you must change the lamp shade.

They must be 4 characters wide and 1 character high.

They can be in any shape, including non-lamp-shade shapes.

They must not contain whitespace.

The base must stay the same.

You must show an example input & output with your lamp shade.

Shortest code wins!

答:
Straw, 26 bytes (non-competing)

```<code><#~('--'
)>( ()
)-*>(/__\)>
</code>```

Use '--' as lamp shade, <s>take input in unary</s> now in decimal

ContentLicense: CC BY-SA 3.0

Title: My Squiggly Lamp

Body:
Straw, 26 bytes (non-competing)

<#~('--'
)>( ()
)-*>(/__\)>

Use '--' as lamp shade, <s>take input in unary</s> now in decimal


答:
Pyth, 78 bytes

```<code>AtBtlQJ_SH
+*dGQVJs[*Nd@Q-GN*dHK@QN*d-HNK;
++_Q*dHhQVJs[@QN*dH@Q-GN*dtN@Q-GN;
</code>```

With trailing newline.   Inspired by Joshua de Haan's Python 3 answer.

Try it online here!

ContentLicense: CC BY-SA 4.0

Title: A cube of text ݀

Body:
Last time you made a square of text, but now, can you make a cube of text?

The Challenge

Given a string, output the string in the form of a cube.

You can assume the string will always have 2 chars or more, and will only have printable ascii characters.

How to Make a Text Cube

Test Cases

```<code>Input:
Test

Output:
   Test
  e  ss
 s  e e
tseT  T
s  e e
e  ss
Test

Input:
Hello, world!

Output:
            Hello, world!
           e           dd
          l           l l
         l           r  r
        o           o   o
       ,           w    w

     w           ,      ,
    o           o       o
   r           l        l
  l           l         l
 d           e          e
!dlrow ,olleH           H
d           e          e
l           l         l
r           l        l
o           o       o
w           ,      ,

,           w    w
o           o   o
l           r  r
l           l l
e           dd
Hello, world!

Input:
Hi

Output:
 Hi
iHH
Hi
</code>```

Reference Implementation in Python

text = raw_input("Enter a string: ")

print " " * (len(text) - 1) + text

spaces = len(text) - 2
_spaces = spaces

for i in range(1, len(text) - 2 + 1):
    print " " * spaces + text[i] + " " * _spaces + text[(i + 1) * -1] + " " * (_spaces - spaces) + text[(i + 1) * -1]
    spaces -= 1

print text[::-1] + " " * _spaces + text[0]

spaces = _spaces - 1

for i in range(1, len(text) - 2 + 1):
    print text[(i + 1) * -1] + " " * _spaces + text[i] + " " * spaces + text[i]
    spaces -= 1

print text
```

<h2>Rules</h2>

<ul>
<li>This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted.</li>
<li>Standard loopholes are disallowed.</li>
<li>Trailing newline and trailing spaces are allowed.</li>
</ul>

<h2>Leaderboard</h2>

<p>Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* Configuration */

var QUESTION_ID = 92410; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}</code>```

body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>Link</td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>Link</td></tr>
  </tbody>
</table></code>```

Body:
Pyth, 78 bytes

AtBtlQJ_SH
+*dGQVJs[*Nd@Q-GN*dHK@QN*d-HNK;
++_Q*dHhQVJs[@QN*dH@Q-GN*dtN@Q-GN;

With trailing newline.   Inspired by Joshua de Haan's Python 3 answer.

Try it online here!


问:
Counting Goats to Sleep
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

答:
MATL, <s>56</s> 53 bytes

```<code>:"'!!((!((!!#*```).?p0```!!!]'8eP!P]'p(.' '.a-'XE&hqc
</code>```

Try it online!

Explanation

Awake goat

The awake goat can be packed into the string

```<code>  '' ''  ")___(->o/___   \
</code>```

and unpacked as will be explained shortly. However, the single-quote symbols would need to be duplicated in order to escape them, so the string literal would have to be defined as (note the enclosing single-quote symbols and the duplication of the original ones):

```<code>'  '''' ''''  ")___(->o/___   \'
</code>```

To save bytes, we define the string using characters one code point above that, thus avoiding duplication. The string literal becomes

```<code>'!!((!((!!#*```).?p0```!!!]'
</code>```

At the end of the code we will subtract 1 and convert to char. (We could do it now, right after the string literal; but leaving it for the end will save another single-quote duplication, as we will see).

To explain how the string is unpacked, we will work with the original characters (that are produced at the end of the code by subtacting 1), so the explanation is easier to follow. We first reshape the string

```<code>  '' ''  ")___(->o/___   \
</code>```

into an 8-row 2D char array, in column-major order (down, then across). This automatically pads the last column with char 0 (at the end of the code, subtracting 1 will transform it into number −1, which converted to char gives again char 0). Char 0 is displayed as a space. So effectively we are padding with spaces. The result of reshaping is

```<code>  >
 "o\
')/
'__
 __
'__
'(
 -
</code>```

We now flip vertically:

```<code> -
'(
'__
 __
'__
')/
 "o\
  >
</code>```

and then transpose and flip vertically again to produce the awake goat:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

The two flip operations are needed because the original packed string is "in reverse". This is to exploit the fact that the actual 2D char array representing the goat has 6 initial spaces in its first row, which get automatically filled by padding when the string is reshaped into an 8-row 2D array. But the padding is done at the end (not beginning) of the last column (not row), hence the flips and transpose.

Sleeping goat

A sleeping goat is generated from an awake goat by transliterating chars o, ', - into -, `, , respectively. Actually, because of the one-code-point-above transformation, we transliterate chars p, (, ' into ., a, -, which again saves us from having to duplicate the single-quote symbol. This is why the subtract-one operation was left for the end of the program.

Code structure

Generate an awake goat N times, working with code points increased by 1.

Transform the last goat into a sleeping goat.

Concatenate all goats horizontally. Subtract 1 to code points and cast to char.

Commented code

```<code>:                              % (Step 1) Implicitly input N. Push range [1 2 ... N]
"                              % For each (i.e. repeat N times)
  '!!((!((!!#*```).?p0```!!!]' %   Push this string. Quotes are escaped by duplicating
  8e                           %   Reshape into an 8-row 2D array of char, in
                               %   column-major order, padding last column with
                               %   char 0
  P                            %   Flip vertically
  !P                           %   Transpose and flip vertically
]                              % End
'p(.'                          % (Step 2) Push this string: source for transliteration
'.a-'                          % Push this string: target for transliteration
XE                             % Transliterate. Transforms last goat into sleeping
&h                             % (Step 3) Horizontally concat all 2D char arrays
qc                             % Subtract 1 and convert to char. 0 becomes −1, which
                               % is converted to char 0, which is displayed as a space
                               % Implicitly display
</code>```

Title: Counting Goats to Sleep

Body:
MATL, <s>56</s> 53 bytes

:"'!!((!((!!#*```).?p0```!!!]'8eP!P]'p(.' '.a-'XE&hqc

Try it online!

Explanation

Awake goat

The awake goat can be packed into the string

  '' ''  ")___(->o/___   \

and unpacked as will be explained shortly. However, the single-quote symbols would need to be duplicated in order to escape them, so the string literal would have to be defined as (note the enclosing single-quote symbols and the duplication of the original ones):

'  '''' ''''  ")___(->o/___   \'

To save bytes, we define the string using characters one code point above that, thus avoiding duplication. The string literal becomes

'!!((!((!!#*```).?p0```!!!]'

At the end of the code we will subtract 1 and convert to char. (We could do it now, right after the string literal; but leaving it for the end will save another single-quote duplication, as we will see).

To explain how the string is unpacked, we will work with the original characters (that are produced at the end of the code by subtacting 1), so the explanation is easier to follow. We first reshape the string

  '' ''  ")___(->o/___   \

into an 8-row 2D char array, in column-major order (down, then across). This automatically pads the last column with char 0 (at the end of the code, subtracting 1 will transform it into number −1, which converted to char gives again char 0). Char 0 is displayed as a space. So effectively we are padding with spaces. The result of reshaping is

  >
 "o\
')/
'__
 __
'__
'(
 -

We now flip vertically:

 -
'(
'__
 __
'__
')/
 "o\
  >

and then transpose and flip vertically again to produce the awake goat:

      \
  ___/o>
-(___)"
 '' ''

The two flip operations are needed because the original packed string is "in reverse". This is to exploit the fact that the actual 2D char array representing the goat has 6 initial spaces in its first row, which get automatically filled by padding when the string is reshaped into an 8-row 2D array. But the padding is done at the end (not beginning) of the last column (not row), hence the flips and transpose.

Sleeping goat

A sleeping goat is generated from an awake goat by transliterating chars o, ', - into -, `, , respectively. Actually, because of the one-code-point-above transformation, we transliterate chars p, (, ' into ., a, -, which again saves us from having to duplicate the single-quote symbol. This is why the subtract-one operation was left for the end of the program.

Code structure

Generate an awake goat N times, working with code points increased by 1.

Transform the last goat into a sleeping goat.

Concatenate all goats horizontally. Subtract 1 to code points and cast to char.

Commented code

:                              % (Step 1) Implicitly input N. Push range [1 2 ... N]
"                              % For each (i.e. repeat N times)
  '!!((!((!!#*```).?p0```!!!]' %   Push this string. Quotes are escaped by duplicating
  8e                           %   Reshape into an 8-row 2D array of char, in
                               %   column-major order, padding last column with
                               %   char 0
  P                            %   Flip vertically
  !P                           %   Transpose and flip vertically
]                              % End
'p(.'                          % (Step 2) Push this string: source for transliteration
'.a-'                          % Push this string: target for transliteration
XE                             % Transliterate. Transforms last goat into sleeping
&h                             % (Step 3) Horizontally concat all 2D char arrays
qc                             % Subtract 1 and convert to char. 0 becomes −1, which
                               % is converted to char 0, which is displayed as a space
                               % Implicitly display


问:
Slowly turn a string into another

The Challenge

Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string.

You can assume the strings will always start with the same character.

Example

```<code>Input:
"Test", "Testing"

Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
</code>```

First you output the first word:

```<code>Test
</code>```

Then you keep removing one letter until the string is one character long:

```<code>Tes
Te
T
</code>```

Then keep adding one letter of the second word until it's done:

```<code>Te
Tes
Test
Testi
Testin
Testing
</code>```

(if both strings are one character long, then just output one of them once.)

Test Cases

```<code>"Hello!", "Hi."
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

"O", "O"

O

"z", "zz"

z
zz

".vimrc", ".minecraft"

.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

"     ", "   "

SSSSS
SSSS
SSS
SS
S
SS
SSS

"0123456789", "02468"

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
02
024
0246
02468
</code>```

(note: on the space/fourth test case, replace the S with spaces)

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016.

Standard loopholes are forbidden.

答:
brainfuck, 162 bytes

```<code>,[>,]++++++++++[[-<]>[->]<]++++++++++[<[+<]<[+<]>[+>]>[+>]<---]<[<]<[<]>[[.>]++++++++++.----------<[-]<[[->+<]<]>>]>[<+>-]>[[<+>-]<[<]>[.>]++++++++++.---------->]
</code>```

Try it here

Input takes the two strings separated by a linefeed.

First program with brianfuck and first code golf so I'm sure there is plenty of optimization to be done.  Had fun doing it though.

Ungolfed

```<code>,[>,] Read all input
++++++++++ Flag for 10
[                   Subtract 10 from each cell to flag space for blank
    [-<]
    >
        [->]
        <
]
++++++++++ Flag for 10
[                   Add 10 back to each cell with value in it
    <[+<]<[+<]
    >[+>]>[+>]<---
]
<[<]<[<]>               goto first cell in first string string

[                           Print first word subtracting one each time
    [.>]                    Print first string
    ++++++++++.----------   Print new line
    <[-]                    Kill last letter of first string
    <                       Back one
    [                       Move each first string character up one
          [->+<]
          <
    ]>>
]
>[<+>-]>                    Move to first letter of scond string back one goto second letter
[
    [<+>-]                  Move next letter back
    <[<]>                   Move to start of string
    [.>]                    Print string
    ++++++++++.----------   Print new line
    >
]
</code>```

Title: Slowly turn a string into another

Body:
brainfuck, 162 bytes

,[>,]++++++++++[[-<]>[->]<]++++++++++[<[+<]<[+<]>[+>]>[+>]<---]<[<]<[<]>[[.>]++++++++++.----------<[-]<[[->+<]<]>>]>[<+>-]>[[<+>-]<[<]>[.>]++++++++++.---------->]

Try it here

Input takes the two strings separated by a linefeed.

First program with brianfuck and first code golf so I'm sure there is plenty of optimization to be done.  Had fun doing it though.

Ungolfed

,[>,] Read all input
++++++++++ Flag for 10
[                   Subtract 10 from each cell to flag space for blank
    [-<]
    >
        [->]
        <
]
++++++++++ Flag for 10
[                   Add 10 back to each cell with value in it
    <[+<]<[+<]
    >[+>]>[+>]<---
]
<[<]<[<]>               goto first cell in first string string

[                           Print first word subtracting one each time
    [.>]                    Print first string
    ++++++++++.----------   Print new line
    <[-]                    Kill last letter of first string
    <                       Back one
    [                       Move each first string character up one
          [->+<]
          <
    ]>>
]
>[<+>-]>                    Move to first letter of scond string back one goto second letter
[
    [<+>-]                  Move next letter back
    <[<]>                   Move to start of string
    [.>]                    Print string
    ++++++++++.----------   Print new line
    >
]


问:
Output "Lorem ipsum" with minimal number of characters
I remember people saying that code size should be measured in bytes, and not in characters, because it's possible to store information with weird Unicode characters, which have no visual meaning.

How bad can it be?

In this challenge, you should output the following Lorem Ipsum text, taken from Wikipedia:

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</code>```

Please specify the number of characters (not bytes) in your code. Code with the minimal number of characters wins.

Your code should only contain valid Unicode characters, as described here, that is:

Code points up to U+10FFFF

No surrogates (the range D800–DBFF is forbidden)

No characters FFFE and FFFF

No null characters (code 0)

If your code cannot be displayed, provide a version with offending characters redacted, and a hexdump.

Some notes:

The output must be one long line (445 characters). If your system cannot do that (e.g. you're printing it on paper), output a closest approximation. Trailing linebreaks don't matter.

Built-in functions that generate Lorem Ipsum text are not allowed

Please specify a valid text encoding for your code, if relevant

答:
bash + coreutils + gzip + recode, 191 characters

```<code>echo -ne "ᾋࠀ㰟퍗\03㖐셱䌱ࡄ戋⪒宮⦀⃬〣ख़ʏ쬏湂삲מּ浊莎ᔍ얪䴬畐Ꮏ肭⽡តप㩴뇶ᮤ樶鞔岀梬昅⹭盖ꈥ먣Ვ빓ỢꞴꃑ괓꣪㷨삗䎺뛔䛓ﵸ摉篨䊷૤⦓헉픺ꉖ橬ꟲỒꗻ퉋則ใ⢍럴摧耼⒅୴䘺㦳櫇鐱窑駁愵䚞鎴鍉Ⅻक़毽➔脂ힸ⤹喝葁㎋頇㺞ⳃ┶왤惌⒜猜䌋吏젔掚ᛩ鯢⚕䜹鴛皽⨫ꇈ銹믍䄛逦軵융杻龇븁\0"|recode u8..utf16be|tr -d ٣ܣ|gunzip
</code>```

The string is the gzip of the text interpreted as UTF-16BE, plus a few extra bytes to pair with the unpaired surrogate halves. The tr strips off the extra surrogate halves.

This script file (or the shell into which this command is typed) should interpret text as UTF-8, which is why the recode is needed.

Body:
bash + coreutils + gzip + recode, 191 characters

echo -ne "ᾋࠀ㰟퍗\03㖐셱䌱ࡄ戋⪒宮⦀⃬〣ख़ʏ쬏湂삲מּ浊莎ᔍ얪䴬畐Ꮏ肭⽡តप㩴뇶ᮤ樶鞔岀梬昅⹭盖ꈥ먣Ვ빓ỢꞴꃑ괓꣪㷨삗䎺뛔䛓ﵸ摉篨䊷૤⦓헉픺ꉖ橬ꟲỒꗻ퉋則ใ⢍럴摧耼⒅୴䘺㦳櫇鐱窑駁愵䚞鎴鍉Ⅻक़毽➔脂ힸ⤹喝葁㎋頇㺞ⳃ┶왤惌⒜猜䌋吏젔掚ᛩ鯢⚕䜹鴛皽⨫ꇈ銹믍䄛逦軵융杻龇븁\0"|recode u8..utf16be|tr -d ٣ܣ|gunzip

The string is the gzip of the text interpreted as UTF-16BE, plus a few extra bytes to pair with the unpaired surrogate halves. The tr strips off the extra surrogate halves.

This script file (or the shell into which this command is typed) should interpret text as UTF-8, which is why the recode is needed.


问:
C: replace AES FIPS-197 SubBytes table by constant-time code
In FIPS-197 (the Advanced Encryption Standard, known as AES), it is made heavy use of SubBytes, which could be implemented as

```<code>unsigned char SubBytes(unsigned char x) {
static const unsigned char t[256] = {
  0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
  0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
  0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
  0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
  0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
  0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
  0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
  0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
  0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
  0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
  0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
  0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
  0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
  0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
  0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
  0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16};
return t[x];}
</code>```

This function is not arbitrary; it is a reversible mapping, consisting of an inversion in a Galois Field followed by an affine transformation. All the details are in FIPS-197 section 5.1.1 or here section 4.2.1 (under a slightly different name).

One problem with implementation as a table is that it opens to so-called cache-timing attacks.

Thus your mission is to devise an exact replacement for the above SubBytes() function, that exhibits constant-time behavior; we'll assume that's the case when nothing depending on the input x of SubBytes is used  either:

as an array index,

as the control operand of if, while, for, case, or operator ?:;

as any operand of operators &&, ||, !, ==, !=, <, >, <=, >=, *, /, %;

as the right operand of operators >>, <<, *=, /=, %=, <<=, >>=.

The winning entry will be one with the lowest cost, obtained from the number of operators executed in the input-dependent data path, with a weight of 5 for unary operators - and ~ as well as for <<1, >>1, +1, -1; weight of 7 for all other operators, shifts with other counts, or adds/subs of other constants (type casts and promotions are free). By principle, that cost is unchanged by unrolling loops (if any), and independent of the input x. As a tie-breaker, the answer with the shortest code after removing whitespace and comments wins.

I plan to designate an entry as answer as early as I can in year 2013, UTC. I will consider answers in languages that I've some knowledge of, ranking them as a straight translation to C not optimized for size.

Apologies for the initial omission of +1 and -1 in the favored operators, of free casts and promotions, and ranking of size. Note that * is prohibited both when unary, and as multiplication.

答:
Score: 9109, algebraic approach

I'll leave the lookup approach in case anyone can improve it drastically, but it turns out that a good algebraic approach is possible. This implementation finds the multiplicative inverse using Euclid's algorithm. I've written it in Java but in principle it can be ported to C - I've commented the parts which would change if you want to rework it using only 8-bit types.

Thanks to ugoren for pointing out how to shorten the is_nonzero check in a comment on my other answer.

```<code>public class SBox
{
    public static void main(String[] args)
    {
        for (int i = 0; i < 256; i++) {
            int s = SubBytes(i);
            System.out.format("%02x  ", s);
            if (i % 16 == 15) System.out.println();
        }
    }

    // Total cost: 9109
    public static int SubBytes(int x)
    {
        x = inv_euclid(x); // 9041
        x = affine(x);     // 68
        return x;
    }

    // Total cost: 68
    private static int affine(int s0) {
        int s = s0;
        s ^= (s0 << 1) ^ (s0 >> 7); // 5 + 7
        s ^= (s0 << 2) ^ (s0 >> 6); // 7 + 7
        s ^= (s0 << 3) ^ (s0 >> 5); // 7 + 7
        s ^= (s0 << 4) ^ (s0 >> 4); // 7 + 7
        return (s ^ 0x63) & 0xff;   // 7 + 7
    }

    // Does the inverse in the Galois field for a total cost of 24 + 9010 + 7 = 9041
    private static int inv_euclid(int s) {
        // The first part of handling the special case: cost of 24
        int zeromask = is_nonzero(s);

        // NB the special value of r would complicate the unrolling slightly with unsigned bytes
        int r = 0x11b, a = 0, b = 1;

        // Total cost of loop: 7*(29+233+566+503+28) - 503 = 9010
        for (int depth = 0; depth < 7; depth++) { // 7*(
            // Calculate mask to fake out when we're looping further than necessary: cost 29
            int mask = is_nonzero(s >> 1);

            // Cost: 233
            int ord = polynomial_order(s);

            // This next block does div/rem at a total cost of 6*(24+49) + 69 + 59 = 566
            int quot = 0, rem = r;
            for (int i = 7; i > 1; i--) {                   // 6*(
                int divmask = is_nonzero(ord & (rem >> i)); // 24+7+7
                quot ^= (1 << i) & divmask;                 // 7+0+7+ since 1<<i is inlined on unrolling
                rem ^= (s << i) & divmask;                  // 7+7+7) +
            }
            int divmask1 = is_nonzero(ord & (rem >> 1));    // 24+7+5
            quot ^= 2 & divmask1;                           // 7+7+
            rem ^= (s << 1) & divmask1;                     // 7+5+7+
            int divmask0 = is_nonzero(ord & rem);           // 24+7
            quot ^= 1 & divmask0;                           // 7+7+
            rem ^= s & divmask0;                            // 7+7

            // This next block does the rest for the cost of a mul (503) plus 28
            // When depth = 0, b = 1 so we can skip the mul on unrolling
            r = s;
            s = rem;
            quot = mul(quot, b) ^ a;
            a = b;
            b ^= (quot ^ b) & mask;
        }

        // The rest of handling the special case: cost 7
        return b & zeromask;
    }

    // Gets the highest set bit in the input. Assumes that it's always at least 1<<1
    // Cost: 233
    private static int polynomial_order(int s) {
        int ord = 2;
        ord ^= 6 & -((s >> 2) & 1);           // 7+7+5+7+7 = 33 +
        ord ^= (ord ^ 8) & -((s >> 3) & 1);   // 7+7+7+5+7+7 = 40 +
        ord ^= (ord ^ 16) & -((s >> 4) & 1);  // 40 +
        ord ^= (ord ^ 32) & -((s >> 5) & 1);  // 40 +
        ord ^= (ord ^ 64) & -((s >> 6) & 1);  // 40 +
        ord ^= (ord ^ 128) & -((s >> 7) & 1); // 40
        return ord;
    }

    // Returns 0 if c is 0 and -1 otherwise
    // Cost: 24
    private static int is_nonzero(int c) {
        c |= -c;   // 7+5+
        c >>>= 31; // 7+ (simulating a cast to unsigned and right shift by CHAR_BIT)
        c = -c;    // 5+ (could be saved assuming a particular implementation of signed right shift)
        return c;
    }

    // Performs a multiplication in the Rijndael finite field
    // Cost: 503 (496 if working with unsigned bytes)
    private static int mul(int a, int b) {
        int p = 0;
        for (int counter = 0; counter < 8; counter++) { // 8*(_+_
            p ^= a & -(b & 1);                          // +7+7+5+7
            a = (a << 1) ^ (0x1b & -(a >> 7));          // +5+7+7+5+7
            b >>= 1;                                    // +5)
        }
        p &= 0xff;                                      // +7 avoidable with unsigned bytes
        return p;
    }
}
</code>```

Body:
Score: 9109, algebraic approach

I'll leave the lookup approach in case anyone can improve it drastically, but it turns out that a good algebraic approach is possible. This implementation finds the multiplicative inverse using Euclid's algorithm. I've written it in Java but in principle it can be ported to C - I've commented the parts which would change if you want to rework it using only 8-bit types.

Thanks to ugoren for pointing out how to shorten the is_nonzero check in a comment on my other answer.

public class SBox
{
    public static void main(String[] args)
    {
        for (int i = 0; i < 256; i++) {
            int s = SubBytes(i);
            System.out.format("%02x  ", s);
            if (i % 16 == 15) System.out.println();
        }
    }

    // Total cost: 9109
    public static int SubBytes(int x)
    {
        x = inv_euclid(x); // 9041
        x = affine(x);     // 68
        return x;
    }

    // Total cost: 68
    private static int affine(int s0) {
        int s = s0;
        s ^= (s0 << 1) ^ (s0 >> 7); // 5 + 7
        s ^= (s0 << 2) ^ (s0 >> 6); // 7 + 7
        s ^= (s0 << 3) ^ (s0 >> 5); // 7 + 7
        s ^= (s0 << 4) ^ (s0 >> 4); // 7 + 7
        return (s ^ 0x63) & 0xff;   // 7 + 7
    }

    // Does the inverse in the Galois field for a total cost of 24 + 9010 + 7 = 9041
    private static int inv_euclid(int s) {
        // The first part of handling the special case: cost of 24
        int zeromask = is_nonzero(s);

        // NB the special value of r would complicate the unrolling slightly with unsigned bytes
        int r = 0x11b, a = 0, b = 1;

        // Total cost of loop: 7*(29+233+566+503+28) - 503 = 9010
        for (int depth = 0; depth < 7; depth++) { // 7*(
            // Calculate mask to fake out when we're looping further than necessary: cost 29
            int mask = is_nonzero(s >> 1);

            // Cost: 233
            int ord = polynomial_order(s);

            // This next block does div/rem at a total cost of 6*(24+49) + 69 + 59 = 566
            int quot = 0, rem = r;
            for (int i = 7; i > 1; i--) {                   // 6*(
                int divmask = is_nonzero(ord & (rem >> i)); // 24+7+7
                quot ^= (1 << i) & divmask;                 // 7+0+7+ since 1<<i is inlined on unrolling
                rem ^= (s << i) & divmask;                  // 7+7+7) +
            }
            int divmask1 = is_nonzero(ord & (rem >> 1));    // 24+7+5
            quot ^= 2 & divmask1;                           // 7+7+
            rem ^= (s << 1) & divmask1;                     // 7+5+7+
            int divmask0 = is_nonzero(ord & rem);           // 24+7
            quot ^= 1 & divmask0;                           // 7+7+
            rem ^= s & divmask0;                            // 7+7

            // This next block does the rest for the cost of a mul (503) plus 28
            // When depth = 0, b = 1 so we can skip the mul on unrolling
            r = s;
            s = rem;
            quot = mul(quot, b) ^ a;
            a = b;
            b ^= (quot ^ b) & mask;
        }

        // The rest of handling the special case: cost 7
        return b & zeromask;
    }

    // Gets the highest set bit in the input. Assumes that it's always at least 1<<1
    // Cost: 233
    private static int polynomial_order(int s) {
        int ord = 2;
        ord ^= 6 & -((s >> 2) & 1);           // 7+7+5+7+7 = 33 +
        ord ^= (ord ^ 8) & -((s >> 3) & 1);   // 7+7+7+5+7+7 = 40 +
        ord ^= (ord ^ 16) & -((s >> 4) & 1);  // 40 +
        ord ^= (ord ^ 32) & -((s >> 5) & 1);  // 40 +
        ord ^= (ord ^ 64) & -((s >> 6) & 1);  // 40 +
        ord ^= (ord ^ 128) & -((s >> 7) & 1); // 40
        return ord;
    }

    // Returns 0 if c is 0 and -1 otherwise
    // Cost: 24
    private static int is_nonzero(int c) {
        c |= -c;   // 7+5+
        c >>>= 31; // 7+ (simulating a cast to unsigned and right shift by CHAR_BIT)
        c = -c;    // 5+ (could be saved assuming a particular implementation of signed right shift)
        return c;
    }

    // Performs a multiplication in the Rijndael finite field
    // Cost: 503 (496 if working with unsigned bytes)
    private static int mul(int a, int b) {
        int p = 0;
        for (int counter = 0; counter < 8; counter++) { // 8*(_+_
            p ^= a & -(b & 1);                          // +7+7+5+7
            a = (a << 1) ^ (0x1b & -(a >> 7));          // +5+7+7+5+7
            b >>= 1;                                    // +5)
        }
        p &= 0xff;                                      // +7 avoidable with unsigned bytes
        return p;
    }
}


问:
Golff y Côd - Treiglad
Read this yng Nghymraeg

Challenge

Given a word in Welsh, output all of the possible mutated forms of the word.

Mutations

A mutation is a change of the first letter of a word when following certain words or in certain grammatical contexts.

In Welsh, the following are considered "consonants":

```<code>b c ch d dd f ff g ng h l ll m n p ph r rh s t th
</code>```

Note that multiple character consonants such as ch, ng and rh are counted as one letter in Welsh, and therefore one consonant.

The other letters in the Welsh alphabet are vowels, listed below:

```<code>a e i o u w y
</code>```

See below, all of the mutations with the original letter on the left and the resulting mutated letters on the right:

```<code>Original | Mutations
---------+---------------
p        | b mh ph
t        | d nh th
c        | g ngh ch
b        | f m
d        | dd n
g        | [no letter] ng
m        | f
ll       | l
rh       | r
</code>```

Here, [no letter] means that the g is removed from the start of the word.

Note that there are some consonants which do not mutate:

```<code>ch
dd
f
ff
j
l
n
ng
ph
r
s
th
</code>```

Vowels may also be found at the start of words but do not mutate:

```<code>a
e
i
o
u
w
y
</code>```

Examples

Input: dydd

Output:

```<code>dydd
ddydd
nydd
</code>```

Input: pobl

Output:

```<code>pobl
bobl
mhobl
phobl
</code>```

Input: gwernymynydd

Output:

```<code>gwernymynydd
wernymynydd
ngwernymynydd
</code>```

Input: ffrindiau

Output:

```<code>ffrindiau
</code>```

Input: enw

Output:

```<code>enw
</code>```

Input: theatr

Output:

```<code>a e i o u w y
</code>```0

On the request of ArtOfCode ;)

Input: llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch

Output:

```<code>a e i o u w y
</code>```1

Rules

The input will only ever be one word.

There will always be more letters after the leading consonant in your input.

Winning

The shortest code in bytes wins.

答:
Python 3, <s>196,189</s> 185 bytes

Original attempt

```<code>w=input();print(w);[w.startswith(a)and[print(w.replace(a,i,1))for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]
</code>```

Vaultah noted that not w.find(a) would be a replacement for w.startswith(a) that would save 2 characters. But instead of not x and y we can use x or y which saves some characters more:

```<code>w=input();print(w);[w.find(a)or[print(w.replace(a,i,1))for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]
</code>```

Yet further savings by replacing w.replace(a,i,1) with i+w[len(a):]:

```<code>w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]
</code>```

Then I noticed that there was a bug, rh was listed twice; once in my short-circuit list that would take care of those double-letter consonants. Unfortunately dd was missing from there, so no savings, and we have

```<code>w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th ph dd p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]
</code>```

Given any of the sample inputs, it gives the desired output; given

```<code>gorsaf
</code>```

it outputs

```<code>gorsaf
orsaf
ngorsaf
</code>```

and given input

```<code>theatr
</code>```

it prints

```<code>theatr
</code>```

Title: Golff y Côd - Treiglad

Body:
Python 3, <s>196,189</s> 185 bytes

Original attempt

w=input();print(w);[w.startswith(a)and[print(w.replace(a,i,1))for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

Vaultah noted that not w.find(a) would be a replacement for w.startswith(a) that would save 2 characters. But instead of not x and y we can use x or y which saves some characters more:

w=input();print(w);[w.find(a)or[print(w.replace(a,i,1))for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

Yet further savings by replacing w.replace(a,i,1) with i+w[len(a):]:

w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th rh ph p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

Then I noticed that there was a bug, rh was listed twice; once in my short-circuit list that would take care of those double-letter consonants. Unfortunately dd was missing from there, so no savings, and we have

w=input();print(w);[w.find(a)or[print(i+w[len(a):])for i in
r]+exit()for(a,*r)in(j.split(',')for j
in'th ph dd p,b,mh,ph t,d,nh,th c,g,ngh,ch b,f,m d,dd,n g,,ng m,f ll,l rh,r'.split())]

Given any of the sample inputs, it gives the desired output; given

gorsaf

it outputs

gorsaf
orsaf
ngorsaf

and given input

theatr

it prints

theatr


问:
Esolang-Comment-Template-Generator
Lots of people on this site use esoteric languages, and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was

```<code>abcdefghijklmnop
</code>```

And this languages uses # for comments, they would write an explanation like this:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template:

```<code>a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #
</code>```

The Challenge:

You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (|) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input:

```<code>"a|bc|d|e|fgh|ij|k|l|mn|op", "#"
</code>```

Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines.

Hopefully you can infer what to do from the testcases, but I'll try to clarify some things.

You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character".

One trailing newline is allowed.

Here is another example. For the input

```<code>"Hello|World", "/"
</code>```

The first section of code is "Hello" and the second is "World". So it should give the output:

```<code>Hello      /
     World /
</code>```

Here are some more samples:

```<code>Input:
"a|b|c|d|e|f|g", ","

Output:
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

Input:
"abcdefg", ":"

Output:
abcdefg :

Input:
"4|8|15|16|23|42", "%"

Output:
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

Input:
"E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!"

Output:
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

Input:
"This|Code|has||empty||sections", "@"

Output:
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @
</code>```

Rules:

You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is code-golf, so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. Standard loopholes are banned.

答:
Vim, <s>39</s> 38 keystrokes

-1 byte thanks to DJMcMayhem

Expects as input a buffer (e.g. a file) whose first character is the comment delimiter, followed by the code, e.g. #foo|bar|baz.

```<code>"cxqaf|m`Yp<Ctrl+o>v$r jv0r x@aq@a$p<Ctrl+v>gg$C <Ctrl+r>c<Esc>
</code>```

Explanation

("_" denotes a literal space.)

```<code>"cx          " Delete the first character (the comment delimiter) and store in register 'c'
qa           " Start recording macro 'a'
f|m`         " Advance to the first '|' on the line and set mark
Yp<Ctrl+o>   " Duplicate this line and return to mark
v$r_         " Replace everything after the cursor on this line (inclusive) with spaces
jv0r_x       " Go down a line and replace everything before the cursor on this line (inclusive) with
             "   spaces, then delete one space
@a           " Call macro recursively
q@a          " Stop recording and immediately call the macro
$p           " Paste the deleted space at the end of the last line
<Ctrl+v>gg$       " Highlight the column where the comment delimiters will go and all trailing spaces
C_<Ctrl+r>c<Esc>  " Replace the highlighted text on each line with a space and the contents of
                  "   register 'c' (the comment delimiter)
</code>```

Title: Esolang-Comment-Template-Generator

Body:
Vim, <s>39</s> 38 keystrokes

-1 byte thanks to DJMcMayhem

Expects as input a buffer (e.g. a file) whose first character is the comment delimiter, followed by the code, e.g. #foo|bar|baz.

"cxqaf|m`Yp<Ctrl+o>v$r jv0r x@aq@a$p<Ctrl+v>gg$C <Ctrl+r>c<Esc>

Explanation

("_" denotes a literal space.)

"cx          " Delete the first character (the comment delimiter) and store in register 'c'
qa           " Start recording macro 'a'
f|m`         " Advance to the first '|' on the line and set mark
Yp<Ctrl+o>   " Duplicate this line and return to mark
v$r_         " Replace everything after the cursor on this line (inclusive) with spaces
jv0r_x       " Go down a line and replace everything before the cursor on this line (inclusive) with
             "   spaces, then delete one space
@a           " Call macro recursively
q@a          " Stop recording and immediately call the macro
$p           " Paste the deleted space at the end of the last line
<Ctrl+v>gg$       " Highlight the column where the comment delimiters will go and all trailing spaces
C_<Ctrl+r>c<Esc>  " Replace the highlighted text on each line with a space and the contents of
                  "   register 'c' (the comment delimiter)


答:
Javascript, 122 bytes

Answer

f=(n,r='repeat')=>'      \\ '[r](n--)+`
${'  ___/o>'[r](n)}  ___/->
${'-(___)" '[r](n)},(___)"
`+` '' ''  `[r](n)+' `` ``'
```
<hr>
<p><strong>Side note</strong><br />
In the following code (91 bytes) the goats are aligned verticaly.
It does not comply with the output format but i though it could be interesting to note that the horizontal alignment required in the output format needs more bytes:</p>
<pre class="lang-js prettyprint-override"><code>f=n=>`
      \\
  ___/${--n?'o':'-'}>
${n?'-':','}(___)"
 ${n?'`` ``':`'' ''`}`+(n?f(n):'')
</code>```

Title: Counting Goats to Sleep

Body:
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

Body:
Javascript, 122 bytes

Answer

f=(n,r='repeat')=>'      \\ '[r](n--)+`
${'  ___/o>'[r](n)}  ___/->
${'-(___)" '[r](n)},(___)"
`+` '' ''  `[r](n)+' `` ``'

Side note

In the following code (91 bytes) the goats are aligned verticaly.
It does not comply with the output format but i though it could be interesting to note that the horizontal alignment required in the output format needs more bytes:

f=n=>`
      \\
  ___/${--n?'o':'-'}>
${n?'-':','}(___)"
 ${n?'`` ``':`'' ''`}`+(n?f(n):'')


答:
C#, 356 <s>338</s> <s>360</s> bytes

I know that C# is a poor choice for code golf, but it's worth the shot:

Third attempt, all cases now pass, including th- ph- etc. This adjustment cost roughly 18 bytes.

Thanks pinkfloydx33 for the tips saving 24 bytes!

namespace System{using Linq;using S=String;class P{static void Main(S[]a){Action<S>w=Console.WriteLine;w(a[0]);foreach(S r in"th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0])){foreach(S f in b.Skip(1))w(Text.RegularExpressions.Regex.Replace(a[0],$"^{b[0]}",f));break;}}}}}
```

<h2>Output</h2>

```$> ./p gwernymynydd
gwernymynydd
wernymynydd
ngwernymynydd
```

<h2>Formatted Version</h2>

<pre class="lang-cs prettyprint-override"><code>    namespace System {
    using Linq;
    using S = String;

    class P {
        static void Main(S[] a) {
            Action<S> w = Console.WriteLine;
            w(a[0]);
            foreach (S r in "th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r"
                .Split('-')) {
                var b = r.Split('.');
                if (a[0].StartsWith(b[0])) {
                    foreach (S f in b.Skip(1))
                        w(Text.RegularExpressions.Regex.Replace(a[0], $"^{b[0]}", f));
                    break;
                }
            }
        }
    }
}
</code>```

Title: Golff y Côd - Treiglad

Body:
Read this yng Nghymraeg

Challenge

Given a word in Welsh, output all of the possible mutated forms of the word.

Mutations

A mutation is a change of the first letter of a word when following certain words or in certain grammatical contexts.

In Welsh, the following are considered "consonants":

```<code>b c ch d dd f ff g ng h l ll m n p ph r rh s t th
</code>```

Note that multiple character consonants such as ch, ng and rh are counted as one letter in Welsh, and therefore one consonant.

The other letters in the Welsh alphabet are vowels, listed below:

```<code>a e i o u w y
</code>```

See below, all of the mutations with the original letter on the left and the resulting mutated letters on the right:

```<code>Original | Mutations
---------+---------------
p        | b mh ph
t        | d nh th
c        | g ngh ch
b        | f m
d        | dd n
g        | [no letter] ng
m        | f
ll       | l
rh       | r
</code>```

Here, [no letter] means that the g is removed from the start of the word.

Note that there are some consonants which do not mutate:

```<code>ch
dd
f
ff
j
l
n
ng
ph
r
s
th
</code>```

Vowels may also be found at the start of words but do not mutate:

```<code>a
e
i
o
u
w
y
</code>```

Examples

Input: dydd

Output:

```<code>dydd
ddydd
nydd
</code>```

Input: pobl

Output:

```<code>pobl
bobl
mhobl
phobl
</code>```

Input: gwernymynydd

Output:

```<code>gwernymynydd
wernymynydd
ngwernymynydd
</code>```

Input: ffrindiau

Output:

```<code>ffrindiau
</code>```

Input: enw

Output:

```<code>enw
</code>```

Input: theatr

Output:

```<code>a e i o u w y
</code>```0

On the request of ArtOfCode ;)

Input: llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch

Output:

```<code>a e i o u w y
</code>```1

Rules

The input will only ever be one word.

There will always be more letters after the leading consonant in your input.

Winning

The shortest code in bytes wins.

Body:
C#, 356 <s>338</s> <s>360</s> bytes

I know that C# is a poor choice for code golf, but it's worth the shot:

Third attempt, all cases now pass, including th- ph- etc. This adjustment cost roughly 18 bytes.

Thanks pinkfloydx33 for the tips saving 24 bytes!

namespace System{using Linq;using S=String;class P{static void Main(S[]a){Action<S>w=Console.WriteLine;w(a[0]);foreach(S r in"th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0])){foreach(S f in b.Skip(1))w(Text.RegularExpressions.Regex.Replace(a[0],$"^{b[0]}",f));break;}}}}}

Output

$> ./p gwernymynydd
gwernymynydd
wernymynydd
ngwernymynydd

Formatted Version

    namespace System {
    using Linq;
    using S = String;

    class P {
        static void Main(S[] a) {
            Action<S> w = Console.WriteLine;
            w(a[0]);
            foreach (S r in "th-dd-ch-ph-p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r"
                .Split('-')) {
                var b = r.Split('.');
                if (a[0].StartsWith(b[0])) {
                    foreach (S f in b.Skip(1))
                        w(Text.RegularExpressions.Regex.Replace(a[0], $"^{b[0]}", f));
                    break;
                }
            }
        }
    }
}


答:
Batch, 234 bytes

```<code>@echo off
set/pn=
call:l "      \ " "      \"
call:l "  ___/o]" "  ___/-]"
call:l "-(___)@ " ",(___)@"
call:l " '' ''  " " `` ``"
exit/b
:l
set s=%~2
for /l %%i in (2,1,%n%)do call set s=%~1%%s%%
set s=%s:@="%
echo %s:]=^>%
</code>```

Takes input from stdin. Batch has trouble with " and > for various reasons so I have to use placeholders and then switch them at the end.

Title: Counting Goats to Sleep

Body:
Batch, 234 bytes

@echo off
set/pn=
call:l "      \ " "      \"
call:l "  ___/o]" "  ___/-]"
call:l "-(___)@ " ",(___)@"
call:l " '' ''  " " `` ``"
exit/b
:l
set s=%~2
for /l %%i in (2,1,%n%)do call set s=%~1%%s%%
set s=%s:@="%
echo %s:]=^>%

Takes input from stdin. Batch has trouble with " and > for various reasons so I have to use placeholders and then switch them at the end.


答:
JavaScript (ES6), <s>110</s> 109 bytes

f=
n=>`      \\       \\
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `.replace(/^.{8}/gm,"$&".repeat(n-1))+"`` ``"
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o></code>```

Having to support all three kinds of quote characters was annoying, but fortunately @pinkfloydx33's comment gave me the flash of inspiration that I could add the backquotes at the end thus saving me 1 byte.

Title: Counting Goats to Sleep

Body:
JavaScript (ES6), <s>110</s> 109 bytes

f=
n=>`      \\       \\
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `.replace(/^.{8}/gm,"$&".repeat(n-1))+"`` ``"
;

<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

Having to support all three kinds of quote characters was annoying, but fortunately @pinkfloydx33's comment gave me the flash of inspiration that I could add the backquotes at the end thus saving me 1 byte.


问:
The Extreme Voters

Challenge

Output the person on PPCG who has cast the most upvotes and the person who has cast the most downvotes.

Voters

You should only look at the people who have cast more than 1000 votes in total.

To find the person who upvotes the most, you should the find the person with the highest upvotes/total votes value. Similarly, the person who downvotes the most has the highest downvotes/total votes value.

Rules

Your output should be the two users' id (the number found in the URL of the user's page). You must put the upvoter first.

In the case of a tie, you must choose the user whose id is the lowest.

The Stack Exchange API is allowed, but entries in T-SQL using the Stack Exchange Data Explorer are disallowed.

Winning

The shortest code in bytes wins.

答:
Java, 1106 bytes

import java.io.*;import java.util.regex.*;()->{String u="",y="",z="",s,t;float h=0,a,l=0,d;int i=-1,k=-1;Matcher m;Pattern p=null;while(i<=k){try(BufferedReader g=new BufferedReader(new InputStreamReader(new java.net.URL("https://codegolf.stackexchange.com/users"+(k==-1?"?tab=NewUsers&sort=creationdate":"/"+i+"/?tab=topactivity")).openStream()));){while((s=g.readLine())!=null){Integer v=0;if(k==-1&s.contains("users/")&!s.contains("profile-me")){m=p.compile("(?<=users/)(\\d+)").matcher(s);if(m.find()){k=v.parseInt(m.group());break;}}if(s.contains("User")){m=p.compile("(?<=User )(.*)(?= - P)").matcher(s);if(m.find())u=m.group();}if(s.contains("Cast")){m=p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);if(m.find()&&(v=v.parseInt(m.group().replace(",","")))>1000){while(1>0){s=g.readLine();m=p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);if(m.find()){if((t=g.readLine()).contains("up")&&(a=0f+v.parseInt(m.group().replace(",",""))/v)>h){y=""+u;h=a;}if(t.contains("down")){if((d=0f+v.parseInt(m.group().replace(",",""))/v)>l){z=""+u;l=d;}break;}}}}}}}catch(Exception e){}}System.out.print(y+"\n"+z);}
```

<p>As a full class:</p>

<pre class="lang-java prettyprint-override"><code>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.*;

public class C {
    public static void main(String[] args) throws Exception {
        String u="", y="", z="", s, t;
        float h = 0, a, l = 0, d;
        int i = -1, k = -1;
        Matcher m;
        Pattern p = null;
        while (i < k) {
            // System.out.println(i);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL("https://codegolf.stackexchange.com/users" + (k == -1 ? "?tab=NewUsers&sort=creationdate" : "/" + i + "/?tab=topactivity")).openStream()));) {
                while ((s = br.readLine()) != null) {
                    Integer v = 0;
                    if (k == -1 && s.contains("users/") && !s.contains("profile-me")) {
                        m = p.compile("(?<=users/)(\\d+)").matcher(s);
                        if (m.find()) {
                            k = v.parseInt(m.group());
                            break;
                        }
                    }
                    if (s.contains("User")) {
                        m = p.compile("(?<=User )(.*)(?= - P)").matcher(s);
                        if (m.find())
                            u = m.group();
                    }
                    if (s.contains("Cast")) {
                        m = p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);
                        if (m.find() && (v = v.parseInt(m.group().replace(",",""))) > 1000) {
                            while (true) {
                                s = br.readLine();
                                m = p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);
                                if (m.find()) {
                                    if ((t = br.readLine()).contains("up") && (a = 0f + v.parseInt(m.group().replace(",",""))/v)>h) {
                                        y = ""+u;
                                        h = a;
                                    }
                                    if (t.contains("down")) {
                                        if ((d=0f + v.parseInt(m.group().replace(",",""))/v)>l) {
                                            z = ""+u;
                                            l = d;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {}
        }
        System.out.print(y+"\n"+z);
    }
}
</code>```

One word: Damn.

I mean, I've always wanted to do a challenge like this, but boy was it a doozy.

I didn't use the Stack Exchange API (don't know what it is, where to access it, or how to use it :P), so I basically had to do everything on my own; having the program crawl through each of the nearly 60,000 PPCG users' profile pages for the right data, looking up the HTML scripts and accounting for how the vote totals were laid out differently for different users1, and debugging (which was, perhaps unsurprisingly, a huge pain). And let me just say, this code could probably use some serious optimization. It takes well over two hours for the program to finish running on my machine, though most of the time is probably used opening the connections to the sites.

So here's a quick rundown of how it works:

Create String variables to hold the upvotingest and downvotingest users on PPCG.

Figure out the total number of active (and deleted/nonexistent) user accounts there are on the site. The program visits https://codegolf.stackexchange.com/users?tab=NewUsers&sort=creationdate and looks for the first user on the page, who happens to be the most recent addition to the community, and as such has the highest ID number. This ID number is set to be the total number of iterations for the loop.

Start at ID 1 and visit https://codegolf.stackexchange.com/users/#, where the pound symbol represents the ID. Parse the HTML code (with regex͠,̰ nőͣ l͇̪e̐̃s̸͖̚͜͝s̡͍̲̫̋ͯ
) and collect the user's username, vote total, upvote total, and downvote total.

Check to see if the upvotes to total votes ratio is larger than the current largest ratio, and set the current ratio to the new ratio if necessary. Do the same for the downvotes to total votes ratio, and also set the upvotingest and downvotingest user names when needed.

Do steps 3 and 4 another (near) 60,000 times, incrementing the ID each time. (This takes care of the event when there is a tie.) If the user doesn't exist, either nothing matches or an Exception is thrown, and move on.

Print the upvotingest and downvotingest users.

Yes, there are quite a few places where I can shave off a few bytes (especially on the strings where I use the contains method), but I'll save that for later... maybe.

If you decide to run this program, be prepared to wait a couple hours for it to finish execution.

Here's a screenshot of the output:

In case it's difficult to read, at the bottom it says...

gnat
Peter Taylor
```

...and the total time it took for the program to finish: a whopping two hours, forty-eight minutes, and twenty-three seconds!

1 The instance on which this occurred had to do with how recently the user voted. If the user voted at least once within the past week or month, two(?) additional stats showing how many times they voted over the past week or month appear on their activity page.

Title: The Extreme Voters

Body:
Java, 1106 bytes

import java.io.*;import java.util.regex.*;()->{String u="",y="",z="",s,t;float h=0,a,l=0,d;int i=-1,k=-1;Matcher m;Pattern p=null;while(i<=k){try(BufferedReader g=new BufferedReader(new InputStreamReader(new java.net.URL("https://codegolf.stackexchange.com/users"+(k==-1?"?tab=NewUsers&sort=creationdate":"/"+i+"/?tab=topactivity")).openStream()));){while((s=g.readLine())!=null){Integer v=0;if(k==-1&s.contains("users/")&!s.contains("profile-me")){m=p.compile("(?<=users/)(\\d+)").matcher(s);if(m.find()){k=v.parseInt(m.group());break;}}if(s.contains("User")){m=p.compile("(?<=User )(.*)(?= - P)").matcher(s);if(m.find())u=m.group();}if(s.contains("Cast")){m=p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);if(m.find()&&(v=v.parseInt(m.group().replace(",","")))>1000){while(1>0){s=g.readLine();m=p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);if(m.find()){if((t=g.readLine()).contains("up")&&(a=0f+v.parseInt(m.group().replace(",",""))/v)>h){y=""+u;h=a;}if(t.contains("down")){if((d=0f+v.parseInt(m.group().replace(",",""))/v)>l){z=""+u;l=d;}break;}}}}}}}catch(Exception e){}}System.out.print(y+"\n"+z);}

As a full class:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.*;

public class C {
    public static void main(String[] args) throws Exception {
        String u="", y="", z="", s, t;
        float h = 0, a, l = 0, d;
        int i = -1, k = -1;
        Matcher m;
        Pattern p = null;
        while (i < k) {
            // System.out.println(i);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL("https://codegolf.stackexchange.com/users" + (k == -1 ? "?tab=NewUsers&sort=creationdate" : "/" + i + "/?tab=topactivity")).openStream()));) {
                while ((s = br.readLine()) != null) {
                    Integer v = 0;
                    if (k == -1 && s.contains("users/") && !s.contains("profile-me")) {
                        m = p.compile("(?<=users/)(\\d+)").matcher(s);
                        if (m.find()) {
                            k = v.parseInt(m.group());
                            break;
                        }
                    }
                    if (s.contains("User")) {
                        m = p.compile("(?<=User )(.*)(?= - P)").matcher(s);
                        if (m.find())
                            u = m.group();
                    }
                    if (s.contains("Cast")) {
                        m = p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);
                        if (m.find() && (v = v.parseInt(m.group().replace(",",""))) > 1000) {
                            while (true) {
                                s = br.readLine();
                                m = p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);
                                if (m.find()) {
                                    if ((t = br.readLine()).contains("up") && (a = 0f + v.parseInt(m.group().replace(",",""))/v)>h) {
                                        y = ""+u;
                                        h = a;
                                    }
                                    if (t.contains("down")) {
                                        if ((d=0f + v.parseInt(m.group().replace(",",""))/v)>l) {
                                            z = ""+u;
                                            l = d;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {}
        }
        System.out.print(y+"\n"+z);
    }
}

One word: Damn.

I mean, I've always wanted to do a challenge like this, but boy was it a doozy.

I didn't use the Stack Exchange API (don't know what it is, where to access it, or how to use it :P), so I basically had to do everything on my own; having the program crawl through each of the nearly 60,000 PPCG users' profile pages for the right data, looking up the HTML scripts and accounting for how the vote totals were laid out differently for different users1, and debugging (which was, perhaps unsurprisingly, a huge pain). And let me just say, this code could probably use some serious optimization. It takes well over two hours for the program to finish running on my machine, though most of the time is probably used opening the connections to the sites.

So here's a quick rundown of how it works:

Create String variables to hold the upvotingest and downvotingest users on PPCG.

Figure out the total number of active (and deleted/nonexistent) user accounts there are on the site. The program visits https://codegolf.stackexchange.com/users?tab=NewUsers&sort=creationdate and looks for the first user on the page, who happens to be the most recent addition to the community, and as such has the highest ID number. This ID number is set to be the total number of iterations for the loop.

Start at ID 1 and visit https://codegolf.stackexchange.com/users/#, where the pound symbol represents the ID. Parse the HTML code (with regex͠,̰ nőͣ l͇̪e̐̃s̸͖̚͜͝s̡͍̲̫̋ͯ
) and collect the user's username, vote total, upvote total, and downvote total.

Check to see if the upvotes to total votes ratio is larger than the current largest ratio, and set the current ratio to the new ratio if necessary. Do the same for the downvotes to total votes ratio, and also set the upvotingest and downvotingest user names when needed.

Do steps 3 and 4 another (near) 60,000 times, incrementing the ID each time. (This takes care of the event when there is a tie.) If the user doesn't exist, either nothing matches or an Exception is thrown, and move on.

Print the upvotingest and downvotingest users.

Yes, there are quite a few places where I can shave off a few bytes (especially on the strings where I use the contains method), but I'll save that for later... maybe.

If you decide to run this program, be prepared to wait a couple hours for it to finish execution.

Here's a screenshot of the output:

In case it's difficult to read, at the bottom it says...

gnat
Peter Taylor

...and the total time it took for the program to finish: a whopping two hours, forty-eight minutes, and twenty-three seconds!

1 The instance on which this occurred had to do with how recently the user voted. If the user voted at least once within the past week or month, two(?) additional stats showing how many times they voted over the past week or month appear on their activity page.


答:
Pyth, 30 bytes

```<code>VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN
</code>```

or

```<code>jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ
</code>```

Both are full programs that take input on STDIN of the comment string, and then the program string, newline-separated.

Try the first version online

Try the second version online

How they work

```<code>VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN  Program. Inputs: E, Q
  cE\|                          Split E on "|"
 J                              Assign to J
                                Implicit Z=0
V                               For N in that:
       [                )        Create a list with elements:
        *Zd                       Z spaces
           N                      N
               -lsJZ              len(concatenate(J))-Z
              -     lN             -len(N)
             h                     +1
            *         d            spaces
                       Q          Q
      s                          Concatenate the list
                                 Implicitly print
                        =+ZlN    Z=Z+len(N)

jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ  Program. Inputs: E, Q
                       +Ed      Add a trailing space to E
                      c   \|    Split that on "|"
                     J          Assign to J
             .u                 Cumulatively reduce J with:
                            k    starting value empty string and
                                 function N, Y ->
                l+NY              len(N+Y)
               *    d             spaces
            ,                J  Two-element list of that and J
           C                    Transpose
         +M                     Map concatenation over that
       .t                       Transpose, padding with spaces
     .t                         Transpose again
 m+dQ                           Map concatenation with Q over that
j                               Join on newlines
                                Implicitly print
</code>```

Title: Esolang-Comment-Template-Generator

Body:
Lots of people on this site use esoteric languages, and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was

```<code>abcdefghijklmnop
</code>```

And this languages uses # for comments, they would write an explanation like this:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template:

```<code>a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #
</code>```

The Challenge:

You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (|) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input:

```<code>"a|bc|d|e|fgh|ij|k|l|mn|op", "#"
</code>```

Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines.

Hopefully you can infer what to do from the testcases, but I'll try to clarify some things.

You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character".

One trailing newline is allowed.

Here is another example. For the input

```<code>"Hello|World", "/"
</code>```

The first section of code is "Hello" and the second is "World". So it should give the output:

```<code>Hello      /
     World /
</code>```

Here are some more samples:

```<code>Input:
"a|b|c|d|e|f|g", ","

Output:
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

Input:
"abcdefg", ":"

Output:
abcdefg :

Input:
"4|8|15|16|23|42", "%"

Output:
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

Input:
"E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!"

Output:
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

Input:
"This|Code|has||empty||sections", "@"

Output:
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @
</code>```

Rules:

You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is code-golf, so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. Standard loopholes are banned.

Body:
Pyth, 30 bytes

VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN

or

jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ

Both are full programs that take input on STDIN of the comment string, and then the program string, newline-separated.

<a href="https://pyth.herokuapp.com/?code=VJcE%5C%7Cs%5B%2aZdN%2ah--lsJZlNdQ%29%3D%2BZlN&test_suite=1&test_suite_input=%27%23%27%0A%22a%7Cbc%7Cd%7Ce%7Cfgh%7Cij%7Ck%7Cl%7Cmn%7Cop%22%0A%22%2F%22%0A%22Hello%7CWorld%22%0A%22%2C%22%0A%22a%7Cb%7Cc%7Cd%7Ce%7Cf%7Cg%22%0A%22%3A%22%0A%22abcdefg%22%0A%27%25%27%0A%224%7C8%7C15%7C16%7C23%7C42%22%0A%22%21%22%0A%22E%7Cac%7Ch+s%7Cecti%7Con+is%7C+one+c%7Characte%7Cr+longer%7C+than+the%7C+last%21%22%0A%22%40%22%0A%22This%7CCode%7Chas%7C%7Cempty%7C%7Csections%22&debug=0&input_size=2" rel="nofollow noreferrer">Try the first version online

<a href="https://pyth.herokuapp.com/?code=jm%2BdQ.t.t%2BMC%2C.u%2al%2BNYdJc%2BEd%5C%7CkJ&test_suite=1&test_suite_input=%27%23%27%0A%22a%7Cbc%7Cd%7Ce%7Cfgh%7Cij%7Ck%7Cl%7Cmn%7Cop%22%0A%22%2F%22%0A%22Hello%7CWorld%22%0A%22%2C%22%0A%22a%7Cb%7Cc%7Cd%7Ce%7Cf%7Cg%22%0A%22%3A%22%0A%22abcdefg%22%0A%27%25%27%0A%224%7C8%7C15%7C16%7C23%7C42%22%0A%22%21%22%0A%22E%7Cac%7Ch+s%7Cecti%7Con+is%7C+one+c%7Characte%7Cr+longer%7C+than+the%7C+last%21%22%0A%22%40%22%0A%22This%7CCode%7Chas%7C%7Cempty%7C%7Csections%22&debug=0&input_size=2" rel="nofollow noreferrer">Try the second version online

How they work

VJcE\|s[*ZdN*h--lsJZlNdQ)=+ZlN  Program. Inputs: E, Q
  cE\|                          Split E on "|"
 J                              Assign to J
                                Implicit Z=0
V                               For N in that:
       [                )        Create a list with elements:
        *Zd                       Z spaces
           N                      N
               -lsJZ              len(concatenate(J))-Z
              -     lN             -len(N)
             h                     +1
            *         d            spaces
                       Q          Q
      s                          Concatenate the list
                                 Implicitly print
                        =+ZlN    Z=Z+len(N)

jm+dQ.t.t+MC,.u*l+NYdJc+Ed\|kJ  Program. Inputs: E, Q
                       +Ed      Add a trailing space to E
                      c   \|    Split that on "|"
                     J          Assign to J
             .u                 Cumulatively reduce J with:
                            k    starting value empty string and
                                 function N, Y ->
                l+NY              len(N+Y)
               *    d             spaces
            ,                J  Two-element list of that and J
           C                    Transpose
         +M                     Map concatenation over that
       .t                       Transpose, padding with spaces
     .t                         Transpose again
 m+dQ                           Map concatenation with Q over that
j                               Join on newlines
                                Implicitly print