Let's learn some soil pH chemistry! Andrew is a chemist, interested in the acidity of solutions and in agriculture. After months of research (Google is not his friend), he came up with the following table* regarding the human-readable level of acidity in terms of the pH (potential of Hydrogen):

         Denomination        |         pH range
                             |
    -------------------------+-----------------------------
    Ultra acidic             |          below 3.5
    -------------------------+------------------------------
    Extremely acidic         |    between 3.5 and 4.4
    -------------------------+------------------------------
    Very strongly acidic     |    between 4.5 and 5.0
    -------------------------+------------------------------
    Strongly acidic          |    between 5.1 and 5.5
    -------------------------+------------------------------
    Moderately acidic        |    between 5.6 and 6.0
    -------------------------+------------------------------
    Slightly acidic          |    between 6.1 and 6.5
    -------------------------+------------------------------
    Neutral                  |    between 6.6 and 7.3
    -------------------------+------------------------------
    Slightly alkaline        |    between 7.4 and 7.8
    -------------------------+------------------------------
    Moderately alkaline      |    between 7.9 and 8.4
    -------------------------+------------------------------
    Strongly alkaline        |    between 8.5 and 9.0
    -------------------------+------------------------------
    Very strongly alkaline   |          over 9.0

Given a non-negative decimal number representing the pH of a substance, output its Denomination. You can take input and provide output by any standard method. The data types you are allowed to take input with are:

Float
Double
Your language's standard decimal number data type
String

And you must output a String representing the denomination. Built-ins related to chemistry are forbidden (Sorry, Mathematica!).
Approximation Rule: If the pH you receive is between an upper bound of a denomination and the lower bound of the next one (e.g. between 7.8 and 7.9), it gets approximated to the closest value between the two: if the pH ≥ upperBound of the first + 0.5, then it should receive the second denomination, but if the pH < upperBound of the first + 0.5, then it should receive the first one (e.g 7.85 is approximated to 7.9, but 7.84999 is approximated to 7.8). See the test cases for clarifications.
Test Cases:

Input ->  Output

6.40  ->  Slightly acidic
8.399 ->  Moderately alkaline
3.876 ->  Extremely acidic
10.60 ->  Very strongly alkaline
0.012 ->  Ultra acidic
7.30  ->  Neutral
7.85  ->  Moderately alkaline (the approximation rule is applied)
7.849 ->  Slightly alkaline (the approximation rule is applied)
6.55  ->  Neutral (the approximation rule is applied)

This is code-golf, so the shortest valid submission (in bytes) wins!
*Andrew did not come up with that, it was Wikipedia!

Jelly,  77 73  71 bytes

“£RĿÐƭðṚ°ƲṂṾẒ=ʂXḣsịɠ<»Ḳµ,Ṛ;€"“¡D⁺“a&»j“¿<z»W¤ṙ3
×20<“FYeoy³ƓɗʋṆ‘Sị¢⁾. y

A monadic link taking the number and returning a list of characters; or a full program printing the result.

Try it online!

How?

“ ... »Ḳµ,Ṛ;€"“¡D⁺“a&»j“¿<z»W¤ṙ3 - Link 1, name list: no arguments
“ ... »                          - compression of "Ultra Extremely Very.strongly Strongly Moderately Slightly"
       Ḳ                         - split at spaces
        µ                        - monadic chain separation, call that adjectives
          Ṛ                      - reverse adjectives
         ,                       - pair these two lists
              “¡D⁺“a&»           - compression of [" alkaline"," acidic"]
             "                   - zip with:
           ;€                    -   concatenate for €ach
                             ¤   - nilad followed by links as a nilad
                       “¿<z»     -   compression of "Neutral"
                            W    -   wrap in a list
                      j          - join
                              ṙ3 - rotate left by 3: ["Strongly alkaline","Moderately alkaline","Slightly alkaline","Neutral","Slightly acidic","Moderately acidic","Strongly acidic","Very.strongly acidic","Extremely acidic","Ultra acidic","Ultra alkaline","Extremely alkaline","Very.strongly alkaline"]

×20<“FYeoy³ƓɗʋṆ‘Sị¢⁾. y - Main link: number, pH
×20                     - multiply by 20
    “FYeqy³ƓɗʋṆ‘        - code-page indexes = [70,89,101,111,121,131,147,157,169,180]
   <                    - less than? (vectorises)
                        -   i.e.: pH < [3.5,4.45,5.05,5.55,6.05,6.55,7.35,7.85,8.45,9]
                S       - sum
                  ¢     - call last link (1) as a nilad
                 ị      - index into (1-indexed and modular)
                        - ...note that the sum is never 11 or 12, so "Ultra alkaline" and
                        -    "Extremely alkaline" wont be fetched, but that a sum of 0
                        -    fetches "Very.strongly alkaline", as required.
                   ⁾.   - literal list of characters ['.', ' ']
                      y - translate (replace any '.' with a ' ' i.e. for "Very.strongly")
                        - if running as a full program, implicit print


Woody words, tinny words Note: There are some rude words in this question.

There's an implicit puzzle posed in this classic Monty Python sketch (you can also ready the script online).

Various phrases are described as being 'woody' or 'tinny', and one is described as being 'PVC'.

Given a phrase, respond with its type according to the following lists:

woody:

gone
sausage
seemly
prodding
vacuum
bound
vole
caribou
intercourse
pert
thighs
botty
erogenous zone
ocelot
wasp
yowling

tinny:

litter bin
newspaper
antelope
recidivist
tit
simpkins

PVC:

leap

Rules

If the input belongs to one of the above lists, the output should be woody, tinny or PVC, accordingly.
All input is lower case.
Any behaviour is acceptable for phrases which are not listed above.
The fewest bytes in the answer wins.

Python 2, 99 73 65 64 63 bytes

lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[-2:]in'instperit'::2]

Try it online!

Alternatives also with 63 bytes:

lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[-6::5]in'dtenmsr'::2]
lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[::5]in'lrinaosit'::2]


Square pyramidal numbers A000330 - OEIS

Task

Your task is simple, generate a sequence that, given index i, the value on that position is the sum of squares from 0 upto i where i >= 0.

Example:

Input: 0
Output: 0           (0^2)

Input: 4
Output: 30          (0^2 + 1^2 + 2^2 + 3^2 + 4^2)

Input: 5
Output: 55          (0^2 + 1^2 + 2^2 + 3^2 + 4^2 + 5^2)

Specification:

You may take no input and output the sequence indefinitely;
You may take input N and output the Nth element of the sequence;
You may take input N and output the first N elements of the sequence.

Python 2, 22 bytes

lambda n:n*~n*~(n*2)/6

Try it online!

This uses the closed-form formula n * (n+1) * (2*n+1) / 6. The code performs the following operations:

Multiplies n by (n*):

The bitwise complement of n (~n), which essentially means -1-n.
And by the bitwise complement of 2n (*~(n*2)), which means -1-2n.

Divides by 6 (/6).

Python 2, 27 bytes

f=lambda n:n and f(n-1)+n*n

Try it online!

Saved 1 byte thanks to Rod and 1 thanks to G B.


Get the century of a year Your program has to have an year like 1957 to be the input and then output the century of that year.

For example:

In: 1946
Out: 20
In: 1705
Out: 18
In: 1900
Out: 19
In: 100
Out: 1
In: 2001
Out 21

because 1946 is in the 20th century.

Keep in mind that 2000 should be 20th century or 1900 should be in 19th century.

Therefore, the first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.

Any programming language is allowed and keep your code short and sweet. :)

Additional Challenge: Try to also include float values

ArnoldC, 308 298 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE x
YOU SET US UP 0
GET YOUR ASS TO MARS x
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
GET TO THE CHOPPER x
HERE IS MY INVITATION x
GET UP 99
HE HAD TO SPLIT 100
ENOUGH TALK
TALK TO THE HAND x
YOU HAVE BEEN TERMINATED

Try it online!

This seemed a challenge easy enough to try to write my first answer in ArnoldC...


Draw a times table (also called modular multiplication circle) of a number \$n\$ with \$k\$ vertices Not to be confused with this question.

You need to draw a times table (also known as Cremona's method for cardioid generation) as shown in this video. The number \$n\$ and \$k\$ will be the inputs.

In the video n and k are 2 and 10 respectively.

How to draw?

Draw a circle, divide its perimeter into equal spaced parts with
\$k\$ points and number them with \$0, 1, 2, \dots, k-1\$ .
Draw \$k\$ line segments between \$i\$ and \$i\times n \mod k\$   for all integers \$i\$, \$0 \le i < k\$.

You can use any graphing library that your language allows.

Remember this is a code-golf so keep the answer short and sweet.

Examples

Input : n = 2 and k = 27

Input : n = 5 and k = 10

You can also play around with it here. The modulus/points is \$k\$ while multiplication factor is \$n\$.

Challenge

You need to draw at least the circle and the lines.

You can output any file format (svg, png, jpeg) and HTML rendering is also allowed.

You can also write the image to STDOUT

Best of luck because you are going to need it!

Python 2, 280 241 235 233 bytes

from math import*
n,k=input()
a=2*pi/k
s='<svg viewBox="-49 -49 98 98"><circle r="49"/><path d="'
p=0;exec"s+='M%f,%f L%f,%f '%(49*cos(p),49*sin(p),49*cos(p*n),49*sin(p*n));p+=a;"*k
open('c.svg','w').write(s+'" stroke="red"/></svg>')

Try it online!

Saved 35 bytes due to removing xmlns attribute at the encouragement of qwr; and 4 more since %k was not required. 4 more by using exec instead of for i in range(k).

Writes an SVG file named c.svg. Look, ma! No graphics library! :)


Calculate the Kronecker symbol Relevant links here and here, but here is the short version:
You have an input of two integers \$a\$ and \$b\$ between negative infinity and infinity (though if necessary, I can restrict the range, but the function must still accept negative inputs).
Definition of the Kronecker symbol
You must return the Kronecker symbol \$(a|b)\$ for inputs \$a\$ and \$b\$ where
$$(a|b) = (a|p_1)^{e_1} \cdot (a|p_2)^{e_2} \cdots (a|p_n)^{e_n}$$
where \$b = p_1^{e_1} \cdot p_2^{e_2} \cdots p_n^{e_n}\$, and \$p_i\$ and \$e_i\$ are the primes and exponents in the prime factorization of \$b\$.

For an odd prime \$p\$, \$(a|p)=a^{\frac{p-1}2} \mod p\$ as defined here.

For \$b = 2\$,

$$
(n|2) = \begin{cases}
0    & \text{if } n \equiv   0   \mod 2 \\
1    & \text{if } n \equiv \pm 1 \mod 8 \\
-1   & \text{if } n \equiv \mp 3 \mod 8
\end{cases}
$$

For \$b = -1\$,

$$
(n|-1) = \begin{cases}
-1 & \text{if } n  <  0 \\
1  & \text{if } n \ge 0
\end{cases}
$$

If \$a \ge b\$, \$(a|b) = (z|b)\$ where \$z = a\mod b\$. By this property, and as explained here and here, \$a\$ is a quadratic residue of \$b\$ if \$z\$ is, even though \$a \ge b\$.

\$(-1|b) = 1\$ if \$b \equiv 0,1,2 \mod 4\$ and \$-1\$ if \$b = 3 \mod 4\$.

\$(0|b)\$ is \$0\$ except for \$(0|1)\$ which is \$1\$, because \$(a|1)\$ is always \$1\$ and for negative \$a\$, \$(-a|b) = (-1|b) \times (a|b)\$.

The output of the Kronecker symbol is always \$-1, 0 \text{ or } 1\$, where the output is \$0\$ if \$a\$ and \$b\$ have any common factors. If \$b\$ is an odd prime, \$(a|b) = 1\$ if \$a\$ is a quadratic residue \$\mod b\$, and \$-1\$ if is it is not a quadratic residue.
Rules

Your code must be a program or a function.

The inputs must be in the order a b.

The output must be either \$-1, 0 \text{ or } 1\$.

This is code golf, so your code does not have to be efficient, just short.

No built-ins that directly calculate the Kronecker or the related Jacobi and Legendre symbols. Other built-ins (for prime factorization, for example) are fair game.

Examples
>>> kronecker(1, 5)
1
>>> kronecker(3, 8)
-1
>>> kronecker(15, 22)
1
>>> kronecker(21, 7)
0
>>> kronecker(5, 31)
1
>>> kronecker(31, 5)
1
>>> kronecker(7, 19)
1
>>> kronecker(19, 7)
-1
>>> kronecker(323, 455625)
1
>>> kronecker(0, 12)
0
>>> kronecker(0, 1)
1
>>> kronecker(12, 0)
0
>>> kronecker(1, 0)
1
>>> kronecker(-1, 5)
1
>>> kronecker(1, -5)
1
>>> kronecker(-1, -5)
-1
>>> kronecker(6, 7)
-1
>>> kronecker(-1, -7)
1
>>> kronecker(-6, -7)
-1

This is a complicated function, so please let me know if anything is unclear.

Python 3, 747 369 335 bytes

As an example answer, only slightly golfed, and to give you an idea of what an answer will look like.
And yes, the prime factorization and run-length-encoding bits are cribbed from Pyth with apologies to isaacg.
from itertools import*
def k(d,r):
 if d<0:a=-d;m=1
 else:a=d;m=0
 if r==1:return 1
 p=1;w=r;n=2;f=[]
 while n*n<=w:
  while w%n<1:w//=n;f+=n,
  n+=1
 if w>1:f+=w,
 z=[[k,len(list(g))]for k,g in groupby(f)]
 for i,j in z:
  if i==2:p*=pow(-1,(a*a-1)//8)
  x=pow(a,(i-1)//2,i)
  if x>1:x-=i
  p*=x**j
 if m:p*=pow(-1,(r-1)//2)
 return p


Any digital permutation Task
Your task is to output a single integer, with one restriction: its digits must be a permutation of [1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6].
For example, you could output 653443653152432, 413265345463352, or any of the other 15-digit integers whose digits are a permutation of the list.
Rules

Your code must terminate in a reasonable amount of time (do not just enumerate every integer until you get to 122333344455566).

If your language doesn't support 15-digit integers, or if there is no meaningful distinction between strings and integers in your language, you may output a string.

This is code-golf, shortest answer in bytes wins.


Implement "tac": Print lines from a file in reverse Between the kitten question and seeing this question at U&L about some sed magic, how about implementing tac?

Objective

Implement a program that will reverse and print the lines in a file.

Input

A file, provided as a name or via standard input

Output

The lines, reversed, to standard out.

Scoring

Bytes of source code.

GS2, 3 bytes

* +

The three bytes are, in order, split lines, reverse, and join lines.


Print ASCII histogram The challenge is to give as short code as possible to print an ASCII histogram of a set of data.

Input.  The number of bins followed by a number of integers representing the data. The data are space separated.

Output. An ASCII histogram of the data using the specified number of bins.

Score. Number of characters in the code excluding trailing whitespace at the beginning or end of each line.

Example input.

2    2    3    4    2    2    5

Example output.

*
*
**
**

Update. The answers are all great although I can only ever imagine using the one in R.  No python contribution?

APL 66 51
' *'[1+(⌽⍳b)∘.≤v←+/(⍳b)∘.=⌈x[⍋x]÷(⌈/x←1↓v)÷b←↑v←⍎⍞]

Using the example I quoted in my comment on the question where the bin size is 2.25:
4 1 1 2 2 5 8 9 6 3

*
*
* **
****


Alpha-Numerical Bowtie Output this exact text:

1                i
12              hi
123            ghi
1234          fghi
12345        efghi
123456      defghi
1234567    cdefghi
12345678  bcdefghi
123456789abcdefghi
12345678  bcdefghi
1234567    cdefghi
123456      defghi
12345        efghi
1234          fghi
123            ghi
12              hi
1                i

A single trailing newline is acceptable, but no other formatting changes are allowed.

Rules and I/O

No input
Output can be given by any convenient method.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

C, 87 85 81 80 bytes

j;main(i){for(;++i<19;)for(j=19;j--;)putchar(j?j<i^j<20-i?32:106-j-j/10*39:10);}

Try it online!

Explanation

j; // same as int j;
main(i){ // same as int main(int i){, where i = argc (1 with no arguments)
  for(;++i<19;) // loop over rows, i = 2..18
    for(j=19;j--;) // loop over chars, j = 19..0
      putchar(j?j<i^j<20-i?32:106-j-j/10*39:10); // output characters:
      //      j?                           :10 // on last char (j=0), output \n
      //        j<i                            // check for top/left half
      //            j<20-i                     // check for bottom/left half
      //           ^                           // 1 if only one half matched
      //                  ?32:                 // if so, output space
      //                      106              // char code for j
      //                         -j            // get desired letter
      //                           -j/10*39    // subtract 39 for j>9 (numbers)
}


Factoring factorials Today in my statistics class, I found that some factorials can be simplified when multiplied together! For example: 5! * 3! = 5! *3*2 = 5! *6 = 6!

Your job:

Given a string containing only Arabic numbers and exclamation points, simplify my factorial to its shortest possible string, in the least amount of bytes for your language, code golf style.

Input

A string containing only Arabic numbers and exclamation points. The factorials for the input won't be bigger than 200!. Factorials will not have more than one factorial per number. Input may be taken as a list of integers.

Output

A possibly shortened string, that has the equivalent value on the input. Order is unimportant. Factorial notation is a must,  but you aren't required to use more than one factorial symbol per number.

Test cases

In: 3!2!2!
Out: 4!

In 2!3!2!0!
Out: 4!

In: 7!2!2!7!2!2!2!2!
Out: 8!8!

In: 23!3!2!2!
Out: 24!
Also: 4!!

In: 23!3!2!2!2!
Out: 24!2!

In: 127!2!2!2!2!2!2!2!
Out: 128!

In: 32!56!29!128!
Out: 29!32!56!128!

Best of luck

Jelly,  17  18 bytes

!P
ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F

A monadic link taking and returning a list of the numbers (sticks to the one factorial per number option)

Try it online!

How?

A golfed (although independently written) version of Pietu1998's solution.

!P - Link 1, product of factorials: list
!  - factorial (vectorises)
 P - product

ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F - Main link: list                       e.g. [3,2,2]
Ç               - call the last link (1) as a monad           24
  L             - length                                      3
 ṗ              - Cartesian power      [[1,1,1],[1,1,2],...,[1,1,24],...,[24,24,24]]
        Ç       - call the last link (1) as a monad           24
      Ðf        - filter keep if:
     ¥          -   last two links as a dyad:
   Ç            -     call the last link (1) as a monad     [1,2,...,24!,...,24!^3]
    ⁼           -     equal?
         Ḣ      - head
          ḟ1    - filter out any ones
            ȯ0  - or with zero (for the empty list case)
              F - flatten (to cater for the fact that zero is not yet a list)


Remove Whitespace from a Java Program In this challenge, you will be given the source code of a Java program. Your task is to write a function or full program that will remove the whitespace from this program. The whitespace-removed program should work exactly the same as the original program. Your program can be in any language. In this challenge, every space, tab, and newline will be considered whitespace.
Summary
Input can be through command-line arguments, function parameters, or STDIN/equivalent.
Output will be the input program without whitespace through STDOUT/equivalent, along with an integer representing the amount of whitespace removed. Your score will be determined by (number of bytes) - (whitespace removed in sample program)
Sample Program (You can remove 104 whitespace characters from this)
class Condition {
    public static void main(String[] args) {
        boolean learning = true;

        if (learning == true) {
            System.out.println("Java programmer");
        }
        else {
            System.out.println("What are you doing here?");
        }
    }
}

http://pastebin.com/0kPdqZqZ
Whitespace-free version: class Condition{public static void main(String[]args){boolean learning=true;if(learning==true){System.out.println("Java programmer");}else{System.out.println("What are you doing here?");}}}
Clarifications from Comments (see below)

The programs passed as input will be at the same whitespace complexity as the sample program.
The programs will not contain comments.

Closing question
Due to the amount of confusion involved with the question, I have decided to close the competition and accept @MartinBüttner's answer. Sorry for any misunderstanding. However, I would believe the answers to be good as a tool for java golfers, which is why I did not delete the question.

CJam, 25 bytes - 83 removed = -58

Since Java doesn't have multiline strings nor significant indentation, we can simply remove all leading spaces. Also, since there won't be any comments, and statements will not be split across lines (as per the OP's comments), I think I should be able to remove all newlines as well.

That makes for safe and short code with pretty decent savings for the test file:

q_,\N/{S\+e`1>e~}%_oNos,-

Test it here.

For the test case it yields

class Condition {public static void main(String[] args) {boolean learning = true;if (learning == true) {System.out.println("Java programmer");}else {System.out.println("What are you doing here?");}}}
83


Tell me about my question! I'm a narcissist. (Not Really)

I'm also very lazy... (Not Really)

So I want to know the score of this question, and how many people have viewed it.

But I'm too lazy to check myself...

Challenge

Your challenge is to output the score of this question, and how many views there are. No input may be taken, and output may be given as pretty much anything as long as it's clear where the two numbers are outputted. So, all of the following are valid:

[1, 1]
score 1, 1 view
1 1
1, 1
1........1
HELLO1WORLD1

Note that pluralization matters, so "1 views" is invalid output.

I am very lazy, so I want this code to be as short as possible.
You may assume that there is an internet connection.
You may want to use the SE API. For reference, this question has id 111115.

Rules

No URL shorteners are allowed.
You may assume that votes are not expanded (for users below 1000 rep: users with at least 1000 rep can click on the score of a post to see the upvotes and downvotes individually. You may assume that this was not done).

Scoring

This is a code-golf challenge, so the shortest valid submission by March 14th (Pi Day) wins! Happy golfing!

T-SQL, 49 bytes

According to the FAQ the database will be updated on Sunday 0300 UTC so this is when you'll get your result. So I'm hoping you're a patient lazy (not really) narcissist (not really).

select Score,ViewCount
from Posts
where Id=111115

https://data.stackexchange.com/codegolf/query/632441/tell-me-about-my-question


Stack the Christmas Gifts Someone has been hastily stacking the Christmas presents, and it's quite a mess:

           ========================
           |                      |
           ========================
     =============
     |           |
     |           |
     |           |
     |           |
     |           |
     |           |
     =============
        =======
        |     |
        |     |
        |     |
        =======
  ===================
  |                 |
  |                 |
  |                 |
  ===================
=================
|               |
|               |
|               |
|               |
=================
   =======
   |     |
   |     |
   =======

Like, seriously, how does that top present even balance. It's probably a hammer. To prevent this tower of presents from crumbling, you're to reorder the presents so they stack nicely:

        =======
        |     |
        |     |
        =======
        =======
        |     |
        |     |
        |     |
        =======
     =============
     |           |
     |           |
     |           |
     |           |
     |           |
     |           |
     =============
   =================
   |               |
   |               |
   |               |
   |               |
   =================
  ===================
  |                 |
  |                 |
  |                 |
  ===================
========================
|                      |
========================

The Rules

Each present consists of a top and bottom of = characters, and one or more middle rows, consisting of two | separated by spaces. The width of the present is the same in all its rows.
There are no empty lines.
Consecutive presents will overlap in at least one column.
Presents are to be stacked in order of decreasing width. In the event of a tie, the taller present should go below the flatter present.
Presents should be centred on the present beneath. If the present cannot be placed exactly in the centre (because the difference in widths is odd), you may choose either position that is half a character off the centre.
You may or may not assume that the input has a single trailing newline, but please state your assumption.
Your solution does not have to work for an empty input, but must be able to handle a single present.
You may write a program or function, which takes input via STDIN or function argument and returns the result or prints it to STDOUT.
This is code golf, so the shortest answer (in bytes) wins.

CJam, 81 70 bytes
'"qN/{__Sm0=#>}%N*"=
="/"=\"\"="*'"++~]$_W='=/,f{1$'=/,m4/\N/\f{S*\N}}

So we have to stack the Christmas presents? This code does it like an actual person would do*.
First, we stack all the presents against a wall to easily move them up and down using this code:
'"qN/{__Sm0=#>}%N*

then, we identify each present as a separate item using this code:
"=
="/"=\"\"="*'"++~]

then, we sort the presents based on their heights and widths using this code:
$

Till now, all the gifts have been stacked against a wall in order to have perfect alignment with each other. But as this is Christmas, we want to place the gifts aligned centered like a Christmas tree! This code does that:
_W=Af{1$Am4/\N/\f{S*\N}}

Here is a step by step output of the code for example in the question:
"Step 1 - Stack the presents against a wall";
========================
|                      |
========================
=============
|           |
|           |
|           |
|           |
|           |
|           |
=============
=======
|     |
|     |
|     |
=======
===================
|                 |
|                 |
|                 |
===================
=================
|               |
|               |
|               |
|               |
=================
=======
|     |
|     |
=======

"Step 2 - Identify the presents as a collection of presents";
["========================
|                      |
========================" "=============
|           |
|           |
|           |
|           |
|           |
|           |
=============" "=======
|     |
|     |
|     |
=======" "===================
|                 |
|                 |
|                 |
===================" "=================
|               |
|               |
|               |
|               |
=================" "=======
|     |
|     |
======="]

"Step 3 - Sort on height & width, with presents stacked against a wall to help sort them";
=======
|     |
|     |
=======
=======
|     |
|     |
|     |
=======
=============
|           |
|           |
|           |
|           |
|           |
|           |
=============
=================
|               |
|               |
|               |
|               |
=================
===================
|                 |
|                 |
|                 |
===================
========================
|                      |
========================

"Final step - stack them like a Christmas Tree";
        =======
        |     |
        |     |
        =======
        =======
        |     |
        |     |
        |     |
        =======
     =============
     |           |
     |           |
     |           |
     |           |
     |           |
     |           |
     =============
   =================
   |               |
   |               |
   |               |
   |               |
   =================
  ===================
  |                 |
  |                 |
  |                 |
  ===================
========================
|                      |
========================

Try it online here
* Might differ from person to person though :P


Pointers, pointers, pointers! Introduction

In the error outputs of some languages such as Java, a pointer is shown to give the programmer an idea of exactly where the error went wrong.

Take this example on Ideone:

Main.java:12: error: ';' expected
    Invalid Java!
                ^

Notice the caret shows where the invalid code is?

Challenge

Your challenge is: given number N and string S, place a pointer on the Nth character in S.

Examples

Input: 2, "Lorem ipsum, dollar sit amet."

Output:

Lorem ipsum, dollar sit amet.
 ^

Rules

Input is received via STDIN or function parameters
Output is printed out to the console or returned
Trailing new lines, spaces etc are allowed in the output
The pointer character must be a ^ caret and must be on a new line.
This is code golf, so the shortest answer wins. Good luck!

C 33
If just a function is allowed, then even c can compete.
(For the record, 2 bytes saved thx to @Cool Guy. Mt thx comment is unexpectedly evaporated.)
1 more char saved thx @Mig
f(a,c){printf("%s\n%*c",a,c,94);}


Creating a catalogue index You have a program which creates an index for a catalogue.  The last step is missing: it must find and consolidate page ranges within the list of pages for each entry.

Each entry is currently an array of unique integers in order, e.g:

[18,19,20,21,22,47,56,57,62,67,68,69,70]

Write a function which returns a consolidated array of ranges and individual pages as appropriate.

Individual pages can be converted to strings or remain as integers.  Either of these would be valid results from the example input:

["18-22",47,"56-57",62,"67-70"] // valid
["18-22","47","56-57","62","67-70"] // valid

Mathematica, 74

Assuming that replacing [] with {} in I/O is allowed:

t=ToString;f=Split[#,#2<#+2&]/.{s_Integer,___,e_}:>t@s<>"-"<>t@e/.{x_}:>x&

  f[{18, 19, 20, 21, 22, 47, 56, 57, 62, 67, 68, 69, 70}]

  {"18-22", 47, "56-57", 62, "67-70"}

The Split part should be quite fast (because someone else probably spent a lot of time optimizing) - the pattern matching part might be a bit slower in comparison. If speed is the main criterium, then there will be other ways to process the Split result (let´s see how the Q develops). For an input of 10^6 entries this takes about 2.7s on my (average) laptop (2.2GHz i7), of which about 1s goes to Split.


Nested lists as printable 2D objects I don't know if something like this exists already (and I'm not finding the right key words) but if not, it felt like it could be an interesting coding puzzle.

The challenge is, to take an arbitrarily nested list (no more than 2 deep), and display the content in a terminal in 2 dimensions in a 'pretty' manner. Each 'top level' dictionary element should read left - right, and the nested content for each top level index should be displayed vertically in line with its index position.

Example input:

[["A"], ["B", "C"], ["D"], ["E", "F", "G"], ["H"]]

Expected output (option 1):

 A B D E H
   C   F
       G

Expected output (option 2):

In this case, 'stacks' should be as close to centralised as possible, so there is a similar amount of content above and below the top level left-to-right content.

       E
 A B D F H
   C   G

Example input 2

List contents (for the purpose of this challenge) can be any length, but will always be the same length. e.g.

[["ABC"], ["BCD", "CDE"], ["DEF"], ["EFG", "FGH", "GHI"], ["HIJ"]]

Would also be valid, and should be rendered in similar fashion to example 1:

                                             EFG
ABC BCD DEF EFG HIJ      or      ABC BCD DEF FGH HIJ
    CDE     FGH                      CDE     GHI
            GHI

Other input considerations (updated in response to comments):

The indexes of the top level, and nested lists will never be empty.

Criteria:

The solution should take a list of lists (nested 1 deep).
The format of the output is flexible, but it should be clear which elements of the list are distinct at the top level (left to right, in my example separated by spaces) and which elements of the sublists are which (top to bottom, separated vertically on successive lines in my example).
Each item in a sublist inside the list should be printed aligned with each other in the vertical direction.
I don't care about speed/complexity/byte count, so at the highest level the criteria will be considered met by any code that can produces the desired 2D output. The winner is therefore a popularity-contest, in that most votes wins (edit: now that answers have started being added the winner will be the answer with the most votes 1 week from today, but new answers would always be welcome).

Bonus points:

How 'pretty' the output is, I'll leave to you. Whether you want it to 'cascade' from the top most character as example 1, or a pseudo-centrally aligned output as example 2. Any other creative solutions are also welcomed.
Code which can handle variable length strings in any position.

I'm particularly interested in Python solutions, but anything goes.

JavaScript (Node.js), 112 107 105 bytes

-1 byte thanks to @Kevin

Despite the controversy in the comments, I gave it a shot. It's my first ever codegolf submission and I had a lot of fun making it.

Tips & tricks are more than welcome!

a=>{o=['','',''];for(b of a)for(c=3;c--;)o[c]+=(b[c]?b[c]:' '.repeat(b[0].length))+' ';return o.join`\n`}

Try it online!


Reverse Cat Programme Simple problem, create a programme that takes one input, and the outputs that input in reverse.

Some test cases are [input -> output]:

 Hello World! -> !dlroW olleH
 Code Golf -> floG edoC
 Reverse Cat Programme -> emmarporG taC esreveR

Shortest answer wins

Note: It doesn’t have to support multi-line inputs and it doesn’t matter how input is taken

Keg, 4 1 byte

This is in the documentation:

^

The mechanism is simple: Reverse the whole stack. The stack is in fact a string, and input will trivially be the items in the stack.

There isn't an online implementation; download the Python interpreter and run this program, with the input prepending the ^.


Double, XOR and do it again We define the function g as g(n) = n XOR (n * 2) for any integer n > 0.
Given x > 0, find the smallest integer y > 0 such that gk(y) = x for some k > 0.
Example
x = 549

549 = 483 XOR (483 * 2)     (as binary: 1000100101 = 111100011 XOR 1111000110)
483 = 161 XOR (161 * 2)     (as binary:  111100011 =  10100001 XOR  101000010)

Which means that g2(161) = 549. We can't go any further, as there is no n such that g(n) = 161. So, the expected output for x = 549 is y = 161.
Rules

You are not supposed to support invalid entries. A pair (y, k) is guaranteed to exist for the input value x.
This is code-golf, so the shortest answer in bytes wins!

Test cases
     3 -->     1
     5 -->     1
     6 -->     2
     9 -->     7
    10 -->     2
    23 -->    13
    85 -->     1
   549 -->   161
   960 -->    64
  1023 -->   341
  1155 -->   213
  1542 -->     2
  9999 -->  2819
 57308 --> 19124
 57311 -->   223
983055 -->     1

Java 8, 68 57 53 52 bytes

n->{for(int i=0;i<n;)i-=(i*2^i)==n?n=i:-1;return n;}

-5 bytes thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{                 // Method with integer as both parameter and return-type
  for(int i=0;i<n;)  //  Loop `i` in the range (1,n)
    i-=(i*2^i)==n?   //   If `i*2` XOR-ed with `i` equals `n`
        n=i          //    Set `n` to `i`, and set `i` to 0 to reset the loop
       :             //   Else:
        -1;          //    Increase `i` by 1 to go to the next iteration
  return n;}         //  Return `n` after the entire loop


(Error) quines, hello world, polyglots, oh my! Introduction
A quine is a program that outputs its own source code. For example, a well-known Python quine is _='_=%r;print(end=_%%_)';print(end=_%_). Running it outputs _='_=%r;print(end=_%%_)';print(end=_%_), therefore it is a valid quine. An error quine is similar to a regular quine, however it must output to STDERR. In Python (for example), this could be achieved by replacing both instances of print in the above code with exit. A polyglot is a program that is valid in multiple languages.
Challenge
Write two full programs in two programming languages of your choice. The first one should be a quine, and the second an error quine. When concatenated (in any order, you can pick), it should form a Hello, World! program in a third programming language.
Example
Say you have a language A* in which a valid quine is 123, and another language B* where abc is an error quine. Then, 123abc (or abc123) should be a valid Hello, World! program in language C*. If this is the case, your answer should look similar to the following:

A, B, C, score 3
A, 3 bytes - Quine
123

Try it online!
B, 3 bytes - Error quine
abc

Try it online!
C, 6 bytes - Hello, World!
123abc

Try it online!
Explanation (optional)
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sem mi, dignissim a odio vehicula, tincidunt ultrices tellus. Etiam luctus scelerisque urna, ac sodales nisl rhoncus at. Cras ac accumsan velit. Integer eget mi nec diam suscipit pretium a ac massa. Praesent at enim nec nisl molestie aliquet nec sed lorem. Duis iaculis condimentum dui at ullamcorper. Fusce molestie iaculis dolor. Cras vel metus dictum, aliquam quam sit amet, gravida tortor. Praesent maximus quam porttitor, vulputate magna eu, rhoncus nunc. Sed accumsan dui ut sapien semper finibus. Nulla eget dictum justo.

Scoring
Your score is the arithmetic mean of the lengths of the two quines (i.e. half the length of the Hello, World! program).
Rules

All three programming languages used must be different.
The Hello, World! program should output exactly Hello, World!. A trailing newline is allowed.
Standard loopholes are forbidden, except for storing information in the file name; if done so in either one of the quines, it will add <length of file name> bytes to the length of both that program and the Hello, World! program, therefore adding half of <length of file name> to your score. If done in the Hello, World! program, it adds the same amount to your score and bytecount for it, but not for either one of your quines. Note that, if you're not doing this, the file name will be assumed to be .code.tio even if not running on TIO.
The regular quine must output to STDOUT and the error quine must output to STDERR. If STDOUT and STDERR do not exist in your language(s), use the closest equivalent(s). However, the Hello, World! program may output using any of the standard I/O methods. Also, the quine and Hello, World! programs may output anything to STDERR, and the error quine may output anything to STDOUT.
If possible, please link to an online interpreter (e.g. TIO) to run your program on.
Please explain your answer. This is not necessary, but it makes it easier for others to understand.
Neither one of the quines may output a trailing newline unless that newline also occurs in the source code.
Languages newer than the question are allowed. This means you could create your own language where a is a quine, b is an error quine, and ab is Hello, World!, and post an answer in that language with score 1, but expect many downvotes.
Non-programming languages are allowed. A non-programming language is a language which doesn't satisfy both of these conditions:

Able to take two integers as input and print their sum
Able to take one integer as input and print a truthy value if it is prime, and a falsy value if it is not

Different versions of the same language may be used. For example, your quine could be in Python 2 and your Hello, World! program in Python 3.
This is code-golf, so shortest code in bytes wins!

*Fun fact: these are all actual languages!

C, Bash, C++, score 174.5 175
C, 301 bytes - Quine
#include<stdio.h>
int main(){
#ifdef __cplusplus
printf("Hello, World!"
#else
char*c="#include<stdio.h>%cint main(){%c#ifdef __cplusplus%cprintf(%cHello, World!%c%c#else%cchar*c=%c%s%c;printf(c,10,10,10,34,34,10,10,34,c,34,10,10%c#endif%c);}//";printf(c,10,10,10,34,34,10,10,34,c,34,10,10
#endif
);}//

Try it online!
Bash, 48 49 bytes - Error quine
.code.tio: line 1: .code.tio:: command not found

Try it online! (the trailing newline was added, see comments)
C++, 349 350 bytes - Hello, World!
#include<stdio.h>
int main(){
#ifdef __cplusplus
printf("Hello, World!"
#else
char*c="#include<stdio.h>%cint main(){%c#ifdef __cplusplus%cprintf(%cHello, World!%c%c#else%cchar*c=%c%s%c;printf(c,10,10,10,34,34,10,10,34,c,34,10,10%c#endif%c);}//";printf(c,10,10,10,34,34,10,10,34,c,34,10,10
#endif
);}//.code.tio: line 1: .code.tio:: command not found

Try it online!

Explainations and notes
The C quine is inspired by this C quine (the short version), and contains C++ code for the Hello, World!.
The Bash error quine works due to the TIO implementation, but given that error messages are generally implementation defined, it might be hard to print them in some standard way (other than directly outputting to stderr, which is just like a regular quine... how unoriginal would that be). The submitted Bash program may be an invalid Bash program, but it is still a valid error quine in Bash. (Edit: note the trailing newline that is now legal to output.)
The C++ Hello, World! doesn't output a trailing newline, but the challenge doesn't require it. After the preprocessor preprocessing, the only code source left is the main function with a simple printf call.
What was used in this answer are similarities between C and C++, very useful for polyglots (C is not entirely contained by C++, but it is contained enough) (for example: the usage of the C standard library is almost the same in these two languages which allows for a single #include directive, the main function definition is also similar enough to factorize the beginning and end out of the preprocessor-picked variations). The preprocessor and the __cplusplus macro are almost necessary at this point as they allow the C and C++ interpreters (or compilers, whatever) to pick only a specific subset of the program. The trailing line comment // ensures that the concatenation with a TIO Bash error doesn't upsets the C++ parser as it will completely ignore it.
I didn't find a way to to golf it even further. An other approach or a different set of languages are probably to be considered. For example, maybe using Argh! or INTERCAL for the error quine (or any other language in which error output is part of the language specification (these languages are rare, even among esolangs)). It might also be more interesting to use an other strategy than this """polyglot""" that makes each language ignore the code designed for the other languages instead of actually running most of the code.


[Br]eaking Code Golf [Ba]d Consider the following string:

Tin Snips

This string contains several atomic symbols on the periodic table. We could rewrite this string to identify several of them:

[Ti][N] [Sn][I][P][S]

Of course, we could also write it this way:

T[In] [S][Ni][P][S]

The rules for rewriting the input are as follows:

The case of the input does not matter in terms of matching atomic symbols.
If an element is used in an atomic symbol, its case must change so the symbol is correct. Ex: h would become [H].
All element symbols are encased in ASCII square brackets, [ and ].
Whitespace is preserved: Big ego cannot combine the "g" and "e" into [Ge].
Not all input characters need be combined into an atomic symbol: if an input character is not put into a symbol, it is passed through as-is (case does not matter).
If a symbol can be made, it must be made. In other words, it is not allowed to output Tin in the above example because it is possible to create at least one symbol in that word. The only time a character may be passed through unused is when it cannot be used to construct an atomic symbol.
For the purposes of this challenge, all elements from Hydrogen (1) to Oganesson (118) are valid. No higher elements are valid.
Some of the higher elements have ambiguous names and symbols: for the purposes of this challenge, the version at Wikipedia shall be used. For convenience, the allowable atomic symbols are here: H, He, Li, Be, B, C, N, O, F, Ne, Na, Mg, Al, Si, P, S, Cl, Ar, K, Ca, Sc, Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Ge, As, Se, Br, Kr, Rb, Sr, Y, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Te, I, Xe, Cs, Ba, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu, Hf, Ta, W, Re, Os, Ir, Pt, Au, Hg, Tl, Pb, Bi, Po, At, Rn, Fr, Ra, Ac, Th, Pa, U, Np, Pu, Am, Cm, Bk, Cf, Es, Fm, Md, No, Lr, Rf, Db, Sg, Bh, Hs, Mt, Ds, Rg, Cn, Nh, Fl, Mc, Lv, Ts, Og.

Write a program or function that generates all possible outputs from a single provided input. Both input and output may be in any form of your choosing. This could be a string, array of characters, or some other data structure: whatever is both convenient and clearly represents the input and output. Both input and output may be passed in/out of your code however you choose: standard in/out, function argument/return, or something else.

Input shall be a string (see previous paragraph) of positive length containing only ASCII characters of arbitrary case and the space (0x20) character.
Your code must generate all output strings that can be created using the input rules above.
The order of the output is implementation-defined. The only requirement is that all output strings are present.
If presented with a valid input string that does not contain any atomic symbols, simply output the input string.
If presented with an input string that is not valid per the rules above (null, zero characters, contains illegal characters, etc.) your program may do anything (crash, blank output, etc.)
Output is case-insensitive other than atomic symbols needing to match the periodic table.
Standard loopholes not allowed.

Test cases:

Tin Snips
[Ti][N] [Sn][I][P][S]
[Ti][N] [S][Ni][P][S]
[Ti][N] [S][N][I][P][S]
T[In] [Sn][I][P][S]
T[In] [S][Ni][P][S]
T[In] [S][N][I][P][S]
T[I][N] ...

Quack
Q[U][Ac][K]
Q[U]a[C][K]

hehe
[H]e[H]e
[H]e[He]
[He][H]e
[He][He]

Stack Exchange
[S][Ta][C][K] Ex[C][H]a[N][Ge]
[S]t[Ac][K] Ex[C][H]a[N][Ge]

This is code golf, so let me see your shortest code!

Python 3, 289 263 bytes

Found a more complete library on Pypi: mendeleev

from mendeleev import*
Z={element(i).symbol for i in range(1,119)}
L,R='[]'
def f(h,r=''):t=h.title();return((Z&{t[0]}and f(h[1:],r+L+t[0]+R)or[])+(Z>{(t+L)[:2]}and f(h[2:],r+L+t[:2]+R)or[])+(not{(r[-1:]+t[0]).title(),t[0]}&Z and f(h[1:],r+h[0])or[]))if h else[r]

Old answer:

from elements import*
Z={e.symbol for e in ELEMENTS}|{*'Cn Ds Fl Lv Mc Nh Og Rg Ts'.split()}
L,R='[]'
def f(h,r=''):t=h.title();return((Z&{t[0]}and f(h[1:],r+L+t[0]+R)or[])+(Z>{(t+L)[:2]}and f(h[2:],r+L+t[:2]+R)or[])+(not{(r[-1:]+t[0]).title(),t[0]}&Z and f(h[1:],r+h[0])or[]))if h else[r]

Uses a library elements.py from http://www.lfd.uci.edu/~gohlke/code/elements.py.html.  It is missing elements 110 to 118, but it was the most up to date library I could find. Cost 40 bytes to add the missing elements.

The trickiest part was the logic for when a character can be passed through without being part of an element symbol.


Am I divisible by double the sum of my digits? Given a positive integer as input, your task is to output a truthy value if the number is divisible by the double of the sum of its digits, and a falsy value otherwise (OEIS A134516). In other words:
(sum_of_digits)*2 | number

Instead of truthy / falsy values for the true and false cases, you may instead specify any finite set of values for the true/false case, and their complement the other values. For a simple example, you may use 0 for the true case and all other numbers for the false case (or vice versa, if you like).

Standard input and output rules apply. Default Loopholes also apply.

You can take input as an integer or as the string representation of that integer.

This is code-golf, hence the shortest code in bytes wins!

I am new to PPCG, so I would like you to post an explanation if it's possible.

Test Cases

Input - Output - (Reason)

80  - Truthy - (16 divides 80)
100 - Truthy - (2 divides 100)
60  - Truthy - (12 divides 60)
18 - Truthy - (18 divides 18)
12 - Truthy - (6 divides 12)

4 - Falsy - (8 does not divide 4)
8 - Falsy - (16 does not divide 8)
16  - Falsy  - (14 does not divide 16)
21 - Falsy - (6 does not divide 21)
78  - Falsy  - (30 does not divide 78)
110 - Falsy - (4 does not dide 110)
111 - Falsy - (6 does not divide 111)
390 - Falsy  - (24 does not divide 390)

JavaScript (ES6), 31 29 27 bytes

Takes input as a string. Returns zero for truthy and non-zero for falsy.

n=>n%eval([...n+n].join`+`)

Commented

n => n % eval([...n + n].join`+`)
n =>                                   // take input string n  -> e.g. "80"
                  n + n                // double the input     -> "8080"
              [...     ]               // split                -> ["8", "0", "8", "0"]
                        .join`+`       // join with '+'        -> "8+0+8+0"
         eval(                  )      // evaluate as JS       -> 16
     n %                               // compute n % result   -> 80 % 16 -> 0

Test cases

let f =

n=>n%eval([...n+n].join`+`)

console.log('[Truthy]');
console.log(f("80"))
console.log(f("100"))
console.log(f("60"))
console.log(f("18"))
console.log(f("12"))

console.log('[Falsy]');
console.log(f("4"))
console.log(f("8"))
console.log(f("16"))
console.log(f("21"))
console.log(f("78"))
console.log(f("110"))
console.log(f("111"))
console.log(f("390"))


Self containing logs The "problem"

Define a function log (or other 3 letter name) which when called will log/print/write (whatever is the default for the language in question) both the instruction (as source) and the first argument. In other words:

i=777
j=333
log(i) //outputs: "log(i) 777"
log(i+j+1) //outputs: "log(i+j+1) 1111"

For all practical purposes the output i: 777 would be enough, but in some languages there are very specific reflection libraries for that, and that would be no challenge, so the entire instruction should be outputted.

Inspiration

The inspiration for this was me and another programmer discussing how irritating it is that often (with bad debuggers), you write things like console.log("i:", i), next we made a (pretty crazy) javascript (node only) solution (it outputs i: 777 rather than the entire line of source) which was suprisingly long and reminded me of codegolfing and made me wonder how much better other (especially code golfing) languages would fare.

Bonuses

-10%: No file reading (beyond the compiler)

PS. This is my first 'question' here, so feel free to point out any mistakes I made.

C (40 -10% = 36) (38 -10% = 34.2)
Note that, in C, a log function can only be defined for a specific type. Therefore, this log "function" takes only int arguments.
#define log(x)printf("log("#x") %d",x)

A more general solution specifies how to print the argument, in addition to the argument itself:
#define lg2(f,x)printf("lg2("#x") "f,x)

which would be used as e.g. lg2("%s", "I'm a string"); or lg2("%f", 3.1415).


CipherSaber encryption Implement a CipherSaber encryption program, as described below. Guidelines:

The smallest entry, in bytes, wins.

However, in a departure from code-golf norms, you are welcome to post interesting entries, even if they aren't serious golf entries.

An entry would typically be a program that takes the plaintext from standard input, and writes the ciphertext to standard output, with the key specified (by the user) in some way you prefer.

However, if you wish to implement this as a procedure, that is fine too.

The IV must come from a cryptographically secure pseudorandom number generator. If your language doesn't support that, choose a different one. ;-)
Please do not use any crypto-specific libraries, system calls, or instructions (other than the PRNG, as stipulated above). Of course, generic low-level bitwise operations are okay.

CipherSaber is a variant of RC4/Arcfour, so I'll start by describing the latter, then the changes CipherSaber makes thereto.

0. RC4/Arcfour

Arcfour is fully specified elsewhere, but for completeness, I'll describe it here. (In case of any discrepancies between the Internet-draft and this description, the former is normative.)

Key setup

Set up two arrays, S and S2, both of length 256, where k_1 is the first byte of the key, and k_n is the last.

S = [0, ..., 255]
S2 = [k_1, ..., k_n, k_1, ...]

(S2 is filled with the bytes of the key, again and again, until all 256 bytes are filled up.)

Then, initialise j to 0, and shuffle 256 times:

j = 0
for i in (0 .. 255)
    j = (j + S[i] + S2[i]) mod 256
    swap S[i], S[j]
end

This completes key setup. The S2 array is no longer used here, and can be scrubbed.

Cipher stream generation

Initialise i and j to 0, then generate the key stream as follows:

i = 0
j = 0
while true
    i = (i + 1) mod 256
    j = (j + S[i]) mod 256
    swap S[i], S[j]
    k = (S[i] + S[j]) mod 256
    yield S[k]
end

Encrypting/decrypting data

To encrypt, XOR the keystream output with the plaintext
To decrypt, XOR the keystream output with the ciphertext

1. CipherSaber

CipherSaber (which is what we're implementing in this question) is a variation of RC4/Arcfour in two ways:

10-byte IV/nonce

When encrypting a message, 10 random bytes should be obtained, such as via /dev/urandom, and be written into the first 10 bytes of the encrypted output. When decrypting a message, the first 10 bytes of the input is the IV used to encrypt it.

The RC4/Arcfour key setup stage is run with passphrase || IV as the key, where passphrase is the user-specified passphrase, IV is as described above, and || is concatenation. So, a passphrase of "Hello, world!" and an IV of "supercalif" (however unlikely that is :-P) would result in a key of "Hello, world!supercalif".

Multiple iterations of key setup

In order to help prevent the vulnerability that made WEP encryption completely broken, the shuffling loop of the key setup stage of RC4 is run a user-specified number of times. The value of j should be retained between iterations.

2. Test vectors

Here are some test vectors you can use to test your programs. Furthermore, squeamish ossifrage created a CipherSaber encryption & decryption tool that you can use to validate your results.

You only need to implement the encryption program. You do not need to supply the decryption program, but your encryption program's output must roundtrip correctly to the original input when processed with a correctly-implemented decryption program using the correct key.

Pyth, 100 bytes

$import os$KsM$os.urandom(10)$JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256=Z0sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw

This script uses the $ command, which allows executing Python code. To prevent executing malicious code on the server, the this command is disabled in the online compiler. You have to run it with the off-line compiler which you can find here.

The input is in the format:

secret key
5 (number of repeats)
secret message

The program outputs the encrypted string, which might contain unprintable chars. If you want to verify it using the CipherSaber Encryption & Decryption Tool, you can use the following code, which converts the string to a series of hexadecimal digits.

$import os$KsM$os.urandom(10)$JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256=Z0
jdm.[2.HCd`0
sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw

Pyth doesn't support cryptographically secure pseudorandom numbers and importing them from Python costs 25 bytes. A shorter code, which uses Pyth's/Python's normar pseudorandom-number generator and also works in the online compiler is:

KmO=b256TJuuXN@LN,T=+Z+@NT@+CMzKT)bGQUb=Z0sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw

Try it online: returning a string or a series of hexadecimal digits

The code is nothing special. Just a lot of dirty assignments and immediate reuses of computed results and applying twice the list-swap trick.

Explanation:

                                  implicit: z = 1st input (= key string)
                                  Q = 2nd input (number of repetitions)
$import os$KsM$os.urandom(10)$
$import os$                       import Python's os module
              $os.urandom(10)$    create 10 cryptographically secure
                                  pseudo-random bytes
            sM                    convert them to ints
           K                      store them in K

JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256
                             =b256assign b with 256
 u                         QUb    start with G = [0, 1, ..., 255],
                                  evaluate the following expression Q times and
                                  update G with the result each time:
  u                      bG         start with N = G,
                                    for each T in [0, 1, ..., 255] evaluate the
                                    following expression and update N each time:
                   CMz                convert key to list of ints
                  +   K               extend it with K
                 @     T              take the Tth element (modulo length)
              @NT                     take the Tth element of N
             +                        add these two values
           +Z                         add Z (with is initially 0)
          =                           and update Z with the result
        ,T  Z                         make the pair of indices [T, Z]
     @LN                              look-up their values in N
   XN                   )             and switch these two values in N
J                                 assign the result (the key setup) to J

=Z0                               set Z to 0

sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw
                                w read a string from input (message)
     .e                           map each index k, char b in message to:
                         @Jhk       look-up the (k+1)th element in J
                      =+Z           add it to Z and update Z
                   ,hk  Z           make the pair of indices [k+1,Z]
                @LJ                 look-up their values in J
              =N                    assign the result to N
            XJ N             )      swap these values in J
           =                        and update J with the result
          @  J                sN    take the sum(N)th element of J
        Cb                          convert b to int
       x                            bitwise xor of these two elements
   +K                             insert K at the beginning
 CM                               convert each element to char
s                                 sum them (generate a string)
                                  implicitly print


Old Spanish alphabetical order Before 1994, Spanish dictionaries used alphabetical order with a peculiarity: digraphs ll and ch were considered as if they were single letters. ch immediately followed c , and ll immediately followed l. Adding the letter ñ, which follows n in Spanish, the order was then:
a, b, c, ch, d, e, f, g, h, i, j, k, l, ll, m, n, ñ, o, p, q, r, s, t, u, v, w, x, y, z

Since 1994 ll and ch are considered as groups of two letters (l,l and c,h respectively), and thus alphabetical order is the same as in English, with the exception of the letter ñ.
The old order was definitely more interesting.
The challenge
Input a list of zero or more words and output the list sorted according to the old Spanish alphabetical order. Sorting is between words (not between letters within a word). That is, words are atomic, and the output will contain the same words in a possibly different order.
To simplify, we will not consider letter ñ, or accented vowels á, é, í, ó, ú, or uppercase letters. Each word will be a sequence of one or more characters taken from the inclusive range from ASCII 97 (a) through ASCII 122 (z).
If there are more than two l letters in a row, they should be grouped left to right. That is, lll is ll and then l (not l and then ll).
Input format can be: words separated by spaces, by newlines, or any convenient character. Words may be surrounded  by quotation marks or not, at your choice. A list or array of words is also acceptable. Any reasonable format is valid; just state it in your answer.
In a similar way, output will be any reasonable format (not necessarily the same as the input).
Code golf, shortest wins.
Test cases
In the following examples words are separated by spaces. First line is input, second is output:
llama coche luego cocina caldo callar calma
caldo calma callar cocina coche luego llama

cuchara cuchillo cubiertos cuco cueva
cubiertos cuco cuchara cuchillo cueva

"Words" can be single letters too:
b c a ch ll m l n
a b c ch l ll m n

or unlikely combinations (remember the rule that l's are grouped left to right):
lll llc llz llll lllz
llc lll lllz llll llz

An empty input should give an empty output:

Of course, this order can be applied to other languages as well:
chiaro diventare cucchiaio
cucchiaio chiaro diventare

all alternative almond at ally a amber
a almond alternative all ally amber at

Pyth, 14 13 bytes
Update: saw this got accepted and noticed a trivial 1 byte golf. Whoops.
:D"ll|ch|."1Q

Try it online. Test suite.
For each word, find all non-overlapping matches for the regex ll|ch|.. This splits the word into the "letters". Then, just sort the words by the splitted lists.


Shortest way to strip the commas from column n given a .csv file/input Ok, so the input here is going to be a .csv file and so is the output. Now, given a .csv file/input like so

"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
# 0       1        2              3

strip out all commas for a given nth column's entries (index starts at 0). So, for the input above, the program would output a .csv file like so for n = 2:

"apple","banana","applebanana","orange"
"grape","orange","grapeorange","sprout"

If the particular column's entries do not have commas, then it does nothing. Could have any allowable/manageable number of columns, and if you somehow find that creating a program that takes more than one argument, say, a, b, c, ..., z like this

program(a=1,b=4,c=65, ..., z=0, mycsv.csv)

for respective columns 2, 5, and 66, which all strip out commas for each, to be shorter, then do that.

Shortest code measured in bytes wins, and it doesn't have to be a file that is output/input.

JavaScript (ES6), 95 93 90 bytes
Takes the content of the CSV file as its first parameter and the column index as its second parameter, with currying syntax.

let f =

s=>n=>s.split(/("[^"]*")/).map(c=>(c<' '?(k=0,c):k++-n*2?c:c.split`,`.join``),k=-1).join``

console.log(f(
`"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
`)(2));


List of primes under a million This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines.

The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output.

The aim, as with most code golf submissions, is to minimise code size. Optimising for runtime is also a bonus, but is a secondary objective.

Python 3, 45 bytes

k=P=1
while k<1e6:P%k>0==print(k);P*=k*k;k+=1

Try it online!
By the time the loop reaches testing k, it has iteratively computed the squared-factorial P=(k-1)!^2. If k is prime, then it doesn't appear in the product 1 * 2 * ... * (k-1), so it's not a factor of P. But, if it's composite, all its prime factors are smaller and so in the product. The squaring is only actually needed to stop k=4 from falsely being called prime.
More strongly, it follows from Wilson's Theorem that when k is prime, P%k equals 1. Though we only need that it's nonzero here, it's useful in general that P%k is an indicator variable for whether k is prime.
Thanks to @Sisyphus for 1 byte with P%k>0==print(k) using chained operator short-circuiting in place of P%k and print(k).


Concatenations of powers and their squares At time of writing, my reputation is \$16,256\$. As I noted in chat,

Oh cool my rep is the concatenation of two powers of 2: 16,256
Or even the concatenation of a power of 2 and its square, which is much more interesting

which then spawned a CMC about checking if a number has this property.

Given an integer \$n > 0\$, considered a decimal integer, and a power \$r > 1\$, return two distinct values which determine whether \$n\$ can be expressed as the concatenation of a power of \$r\$ and its square or not. For example, \$n = 16256\$ and \$r = 2\$ returns true (the concatenation of \$2^4\$ and \$(2^4)^2\$), while \$n = 39\$ and \$r = 2\$ does not. Note however that \$n = 39\$, \$r = 3\$ is true. The power of \$r\$ may be \$0\$, meaning that \$n = 11\$ is true for all \$r\$
The power of \$r\$ will always come "before" its square, so \$n = 62525, r = 5\$ is false.
You will never get an input \$n\$ where its validity depends on ignoring leading \$0\$s or not (for example \$101\$ is true for all \$r\$ if ignoring leading \$0\$s and false otherwise). However, you may still get inputs with the digit \$0\$ in (e.g. \$n = 1024, r = 2\$) where leading \$0\$s have no bearing on the validity of \$n\$ being such a concatenation.
Input and output may be in any accepted method and this is code-golf so the shortest code in bytes wins.
Test cases
    n    r    1
   39    3    1
  525    5    1
  864    8    1
16256    2    1
   11    r    1
  416    7    0
   39    2    0
   15    5    0
 1024    4    0
62525    5    0

Feel free to suggest more test cases.

APL (Dyalog Unicode), 21 bytes (SBCS)

Anonymous infix lambda, taking \$r\$ as left argument and \$n\$ as right argument. Requires ⎕IO←0 (zero-based indexing).
{⍵∊(⊢⍎⍤,⍥⍕¨×⍨)⍺*⍳⌊⍟⍵}

Try it online! (Dyalog Extended as polyfill for version 18.0)
{…} "dfn", ⍺ is \$r\$ and ⍵ is \$n\$:
 ⍟⍵ natural log of \$n\$ (to avoid overflow)
 ⌊ round that down
 ⍳ ɩntegers zero through one less than that
 ⍺* raise \$r\$ to those powers
 (…) apply the following monadic function to that:
  ×⍨ multiply those with themselves (i.e. square them)
  ⊢…¨ for each unmodified argument and its corresponding square:
   ⍥⍕… stringify the argument and its square before
    ⍤, concatenating them, and then
     ⍎ evaluating the result
 ⍵∊ is the original argument a member of that?


Is case sensitivity important? Tom is going to implement a new programming language of his invention.  But before actually starting working on it, he wants to know whether his language should be case sensitive or not.

On one hand, case insensitivity seems more easy to implement to him, but he worries that it could cause a lack in the possibilities of combinations of characters that form a variable, meaning that longer variable names should then be used to avoid naming clashes (for an example, you can use Hello, HEllo, heLLo and a bunch of other possibilities if the language is case sensitive, but only HELLO if not).

But Tom is a meticulous person, so just a worry isn't enough for him. He wants to know the numbers.

The challenge

Write a function (or a full program if your language doesn't support them) that, given an integer n as the input, outputs (or returns) the difference in the number of permutations possible for a string of length n with case sensitivity and without.

In Tom's language, variable names can include all alphabet letters, underscores and, starting from the second character, digits.

Testcases

Input (length of the variable) -> Output (difference between the possibilities with case sensitivity and the possibilities with case insensitivity)
0 -> 0
1 -> 26
2 -> 2340
5 -> 784304586
8 -> 206202813193260
9 -> 13057419408922746

Non-competing C++ reference implementation

void diff(int n) {
    long long total[2] = {0, 0}; //array holding the result for case insensivity ([0]) and case sensitivity ([1])

    for (int c = 1; c <= 2; c ++) //1 = insensitivity, 2 = sensitivity
        for (int l = 1; l <= n; l ++) //each character of the name
            if (l == 1)
                total[c - 1] = 26 * c + 1; //first character can't be a number
            else
                total[c - 1] *= 26 * c + 1 + 10; //starting from the second character, characters can include numbers

    std::cout << total[1] - total[0] << std::endl;
}

Scoring

Tom likes golf, so the shortest program in bytes wins.

Note

It's okay if maybe the last two testcases aren't right because of numerical precision. After all, I am not even sure my code handled number 9 correctly.

JavaScript (ES7), 43 bytes

f=(n,a=53,b=27)=>n?--n?f(n,a*63,b*37):a-b:0
<input type=number value=0 min=0 max=9 style=width:4ch oninput=o.textContent=f(+this.value)>
0

Not reduces day today - 55 bytes.


Analyzing Collatz-like sequences We define a Collatz-like sequence s with 4 positive integers:

n starting value
d > 1 divisor
m > 1 multiplier
i increment

(In the original Collatz sequence d = 2 m = 3 and i = 1.)

Given these integers s will be created in the following manner:

s(0) = n
if k > 0 and s(k-1) mod d = 0 then s(k) = s(k-1) / d
if k > 0 and s(k-1) mod d != 0 then s(k) = s(k-1) * m + i

An example sequence with d = 2, m = 3, i = 5 and n = 80 will be s = 80, 40, 20, 10, 5, 20, 10, 5, 20, ....

Every sequence will either reach higher values than any given bound (i.e. the sequence is divergent) or get into an infinite loop if for some t and u (t!=u) the s(t) = s(u) equality will be true.

In our problem if the value of a sequence element is larger than 10^9 or there is no element repetition before the 1000th element the sequence is considered divergent.

The task

You should write a program or function which takes the positive integers d m and i as inputs and outputs all the different ending types of the sequences (infinite loops and divergence) which the starting values n = 1, 2, 3, ... 999, 1000 can produce.

Input details

The input is a string or list (or closest equivalent in your language) representing (in the common way) three positive integers d, m and i in that order. d and m are at least 2. Neither number is larger than 100.

Output details

The output specification is a bit wordy. Might worth to check out the examples first.

You should output to the standard output (or closest alternative) or return a string.
If divergent sequence is possible the first line should be DIVERGENT.
A unique representation of a sequence's loop is it's rotation where the smallest number is the last separated by spaces. E.g. if s = 2 1 4 2 1 4 2 1 the loop is 4 2 1.
In every following line you should output every unique loop exactly once preceded by the word LOOP. E.g. LOOP 4 2 1
The loops should be in ascending order in regard of their last element.
Trailing newline is optional.

Examples:

The first lines are the inputs and the following ones until a blank line are the outputs.

2 3 1
LOOP 4 2 1

2 2 6
LOOP 8 4 2 1
LOOP 12 6 3

3 7 8
DIVERGENT
LOOP 15 5 43 309 103 729 243 81 27 9 3 1
LOOP 22 162 54 18 6 2
LOOP 36 12 4

3 9 1
DIVERGENT

6 9 9
DIVERGENT
LOOP 18 3 36 6 1
LOOP 27 252 42 7 72 12 2
LOOP 45 414 69 630 105 954 159 1440 240 40 369 3330 555 5004 834 139 1260 210 35 324 54 9 90 15 144 24 4
LOOP 81 738 123 1116 186 31 288 48 8
LOOP 99 900 150 25 234 39 360 60 10
LOOP 126 21 198 33 306 51 468 78 13

10 10 10
LOOP 20 2 30 3 40 4 50 5 60 6 70 7 80 8 90 9 100 10 1

93 91 92
DIVERGENT
LOOP 2185 198927 2139 23
LOOP 4278 46

Reference implementation in Python 3 on Ideone.

This is code-golf so shortest entry wins.

Python 3, 269 254 252 246 bytes

d,m,i=eval(input())
S=set()
for n in range(1,1001):
 T=X=()
 while len(T)**3<1e9>=n:
  T=(n,)+T;n=[n//d,n*m+i][n%d>0]
  if n in T:I=T.index;L=T[:I(n)+1];M=I(min(L));X=L[M:]+L[:M]
 S|={X}
for x in sorted(S):print(x and"LOOP"or"DIVERGENT",*x[::-1])

(Now 10 times slower to save a few bytes. Typical code golf.)
Input a list via STDIN (e.g. [2, 3, 1]). I'm thinking that there's got to be a better way of standardising the cycles...
The approach is quite straightforward — test all 1000 numbers and take only the unique outputs. However, there are two little tricks in there:

Loops are represented by nonempty tuples, but more importantly divergence is represented by an empty tuple. This is good because:

It doesn't break sorted, and will even appear before all the loop tuples
It allows us to select a string via x and"LOOP"or"DIVERGENT"
*()[::-1] doesn't affect print

The loops are built backwards to turn "sort ascending by last element" into "sort ascending by first element", which removes the need to pass a lambda into sorted.

Previous submission, 252 bytes
d,m,i=eval(input())
def f(n,T=()):
 x=[n//d,n*m+i][n%d>0];I=T.index
 if x in T:L=T[:I(x)+1];M=I(min(L));return L[M:]+L[:M]
 return()if(T[1000:]or x>1e9)else f(x,(x,)+T)
for x in sorted(set(map(f,range(1,1001)))):print(x and"LOOP"or"DIVERGENT",*x[::-1])

This one's a lot faster.


Put an array into bins In this simple challenge you are given an input array L of non-negative integers and a number of bins b greater than 0 but no more than the length of L. Your code must return a new array M whose length is b and which has binned the array L. This is easiest explained with examples.

L = [1,0,5,1] and b = 2 returns M = [1,6].

L = [0,3,7,2,5,1] and b = 3 returns M = [3,9,6].

So far, so simple.  However in this question b doesn't necessarily have to divide len(L). In this case the last bin will just have fewer numbers to make it up.

Each bin except possibly the last one must have the same number of numbers contributing to its total.  The last bin must have no more numbers contributing to it than the other bins.  The last bin must have as many numbers contributing to it as possible subject to the other rules.

L = [0,3,7,2,5,1] and b = 4 returns M = [3,9,6,0].  M = [10,8,0,0] is not an acceptable output as the third bin does not have the name number of numbers contributing to it as bins 1 and 2.

L = [0,3,7,2,5] and b = 2 returns M = [10,7].  M = [3, 14] is not an acceptable output as the last bin will have 3 elements contributing to it but the first has only 2.

L = [1,1,1,1,1,1,1] and b = 3 returns M = [3,3,1].

As a final rule, your code must run in linear time.

You may use any language or libraries you like and can assume the input is provided in any way you find convenient.

It turns out that there are some inputs which can't be solved.  For example [1,1,1,1,1] and b=4. Your code can output whatever it likes for those inputs.

APL (Dyalog), 19 bytes

{+/⍺(⌈⍺÷⍨≢⍵)⍴⍵,⍺⍴0}

Try it online!

We append b zeros to the array before reshaping it into equal parts of ⌈⍺÷⍨≢⍵ (⌈ length of L ÷ b ⌉) and summing them, as depicted in ,⍺⍴0, since any amount of blank spots (which are not part of the original array) larger than b - 1 would be filled with at least b - 1 elements from other chunks, which makes the balancing point of the last group at maximum b - 1 difference from the rest. We use b > b - 1 because it is code golf.

For example, L with 15 elements and b = 3 wouldn't be grouped as

x x x x x x
x x x x x x
x x x 0 0 0

but rather as (note how the rightmost 2 xs "fills in" the leftmost zeros)

x x x x x
x x x x x
x x x x x

while a 16 elements array would be filled with 2 (3 - 1) blank spots, like

x x x x x x
x x x x x x
x x x x 0 0


Interpret a circuit diagram Your challenge is to interpret a circuit diagram, complete with logic gates.

Logic gates (you don't actually need to know what these do / are to complete this challenge):

and gate: a
or gate: o
nand gate: A
nor gate: O
xor gate: x
xnor gate: X
not gate: ~

Each gate but the last one takes two inputs. Inputs are from a . in the top left and bottom left corners of the 3 by 3 square centered on the gate. For not, the input is directly to its left. Output is to a . directly to the right.

Wires are represented by -|\/.=

- contacts two wires, one to the right, and one to the left: c-c
| contacts two wires, one above, and one below:

c
|
c

/ and \ work as follows:

c        c
 \      /
  c    c

. contacts every surrounding wire:

ccc
c.c
ccc

= is special; it connects adjacent wires across it:

-=-

connects the two wires. In the following

\|/
-=-
/|\

each opposite wire is connected with each other, but not the others (this is where it differs from .).
In order for current to flow, two wires must both be connected to the other one, so in |-, current does not flow.

Example of wiring:

      .-.
     =   \
 .--. .---=---
-.   =     .--
 .--. .-------

the input is split into two wires and then split into three. In this split, the bottom wire moves to the middle, and the downwards split of the top wire appears on the bottom. Next, the top of the three wires is moved to the middle.

Sample wiring with gates:

--.
   o..~..
--.      o.---
   a.---.
--.

Input format:

each input wire will be labeled with a digit. At the end (right before newline), each output will be labeled with : (and the wire will always go right into it, ie -: or .: or =:)
the input will always be valid; there will be no loops or wires joining together without a gate. Note that there can be wires with loose ends.
= will be used only when necessary.

Output format:

each input is referenced with the corresponding number.
an expression is outputted. For example, if the wires compute input 1 and input 2, the output is 1a2.
whatever functions outputted must correspond to the logic gates at the beginning.
to show not, put the ~ before the correct place.
for multiple functions, use parentheses to show the order of execution. Parentheses can also be used when there is only a single function. For example,

1-.~.-.
       A.~.-:
      .
2-.  /
   x.
3-.

has one possible output of ~((2x3)A(~1))
multiple outputs must be separated by a newline (or equivalent)

Sample input:

1--.---.
    x.  \
2--.  x.-=---------.
     .    .~.       X.--.
3---. .      a.----.   /
       O.~.-.       \ /
      .              =
4-.  /              / .-:
   X.              .----:
5-.

One possible corresponding output:

(~1)a(~(3O(4X5))
((1x2)x3)X((~1)a(~(3O(4X5))))

Java: 1523 1512 chars

import java.util.*;class W{int v=99;Map<Integer,String>t;boolean k;public static void main(String[]y){new W().d();}W(){try{java.io.InputStream i=new java.io.File("r").toURL().openStream();t=new HashMap<>();int a=0,x=0,y=0;while((a=i.read())>-1){if(a==10){y++;x=0;continue;}q(x,y,(a>47&a<58?"!":"")+(char)a);x++;}}catch(Exception e){}}void d(){while(!k){k=!k;for(Map.Entry<Integer,String>g:t.entrySet())e(g.getKey(),g.getValue());}for(String b:t.values())if(b.startsWith("$"))System.out.println(b.substring(1));}void e(int a,String s){if(s==null||!s.startsWith("!"))return;int x=a/v,y=a%v;s=s.substring(1);b(s,x,y,x-1,y+1);b(s,x,y,x,y+1);b(s,x,y,x+1,y+1);b(s,x,y,x-1,y);b(s,x,y,x+1,y);b(s,x,y,x-1,y-1);b(s,x,y,x,y-1);b(s,x,y,x+1,y-1);}void b(String p,int m,int n,int x,int y){String s=t.get(x*v+y);if(s==null)return;boolean g=y==n+1;boolean h=y==n-1;boolean i=x==m+1;boolean j=x==m-1;if(z(s,"-=")&n==y){if(i)b(p,x,y,x+1,y);if(j)b(p,x,y,x-1,y);}if(z(s,"|=")&m==x){if(g)b(p,x,y,x,y+1);if(h)b(p,x,y,x,y-1);}if(z(s,"/=")){if(j&g)b(p,x,y,x-1,y+1);if(i&h)b(p,x,y,x+1,y-1);}if(z(s,"\\=")){if(i&g)b(p,x,y,x+1,y+1);if(j&h)b(p,x,y,x-1,y-1);}if(z(s,".")){q(x,y,"!"+p);u();}if(z(s,"~")){q(x,y,"!~("+p+")");u();}if((s.charAt(0)=='%'&n==y-1)|(s.charAt(0)=='&'&n==y+1)){q(x,y,"!("+p+")"+s.charAt(1)+"("+s.substring(2)+")");u();}if(z(s,"OoAaXx")){q(x,y,(n==y+1?"%":"&")+s+p);u();}if(z(s,":")){q(x,y,"$"+p);u();}}void q(int x,int y,String z){t.put(x*v+y,z);}void u(){k=false;}boolean z(String s,String c){return c.indexOf(s)>-1;}}

It gives this output for the sample input:

(~(((5)X(4))O(3)))a(~(1))
((~(((5)X(4))O(3)))a(~(1)))X(((2)x(1))x(3))

In order to squeeze its size:

It does not do any error checking, error handling or input validation, assuming that the input is always valid.
Is limited to 99 lines of input.
Its input file must be called just r, without any file extension in the name.
It does not makes any effort to detect if the parenthesis are or aren't necessary. It assumes that they always are necessary, and since this assumption is false, there is a lot more parenthesis than needed, but since this does not makes it fail the spec anyway, it is no problem.
The order of the parameters to each binary operator is in general unpredictable, as it depends on the velocity that the values are propagated and from cell scanning order. But since all the binary operators are commutative, this should be no problem.

I am sure that it should be possible to reduce it more, but just a bit.

The interpreter is implemented in the form of some sort of cellular automata. It scans the entire field setting values, repeating it as many times as needed until no changes are detected.

Here is an ungolfed version:

import java.util.*;

class Wiring {

    int maxLines = 99;
    Map<Integer, String> circuitState;
    boolean finished;

    public static void main(String[] args) {
        new Wiring().interpret();
    }

    Wiring() {

        try {
            // Always read the input from the "r" file, and do not check if it even
            // exists. BTW, the toURL() method is deprecated, but we don't care about
            // this in code-golfing.
            java.io.InputStream stream = new java.io.File("r").toURL().openStream();

            circuitState = new HashMap<>();
            int byteRead = 0, cellX = 0, cellY = 0;

            while ((byteRead = stream.read()) > -1) {

                // Check for line break;
                if (byteRead == 10) {
                    cellY++;
                    cellX = 0;
                    continue;
                }

                // Populate the circuit cell. Precede numbers with an exclamation mark.
                setCircuitCell(cellX, cellY, (byteRead >= '0' & byteRead <= '9' ? "!" : "") + (char) byteRead);
                cellX++;
        } catch (Exception e) {
        }
    }

    void interpret() {
        while (!finished) {
            finished = !finished; // i.e. finished = false;
            for (Map.Entry<Integer, String> entry : circuitState.entrySet()) {
                analyzeCell(entry.getKey(), entry.getValue());
            }
        }

        // Now print the output. To do that scan for cells marked with "$".
        for (String cell : circuitState.values()) {
            if (cell.startsWith("$")) System.out.println(cell.substring(1));
        }
    }

    void analyzeCell(int cellIndex, String cellValue) {
        // Only the cells with a value marked with "!" are worth to analyze.
        if (cellValue == null || !cellValue.startsWith("!")) return;

        // Convert the cellIndex to a bidimensional coordinate.
        int x = cellIndex / maxLines, y = cellIndex % maxLines;

        // Remove the "!".
        cellValue = cellValue.substring(1);

        // Propagate the cell value to neighbouring cells.
        propagateCellData(cellValue, x, y, x - 1, y + 1);
        propagateCellData(cellValue, x, y, x, y + 1);
        propagateCellData(cellValue, x, y, x + 1, y + 1);
        propagateCellData(cellValue, x, y, x - 1, y);
        propagateCellData(cellValue, x, y, x + 1, y);
        propagateCellData(cellValue, x, y, x - 1, y - 1);
        propagateCellData(cellValue, x, y, x, y - 1);
        propagateCellData(cellValue, x, y, x + 1, y - 1);
    }

    void propagateCellData(String cellValue, int sourceX, int sourceY, int targetX, int targetY) {
        String targetContent = circuitState.get(targetX * maxLines + targetY);

        // If the target cell does not exist, just ignore.
        if (targetContent == null) return;

        boolean targetBelowSource = targetY == sourceY + 1;
        boolean targetAboveSource = targetY == sourceY - 1;
        boolean targetRightToSource = targetX == sourceX + 1;
        boolean targetLeftToSource = targetX == sourceX - 1;

        // Propagate horizontally through wires.
        if (isStringContained(targetContent, "-=") & sourceY == targetY) {
            if (targetRightToSource) propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY);
            if (targetLeftToSource) propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY);
        }

        // Propagate vertically.
        if (isStringContained(targetContent, "|=") & sourceX == targetX) {
            if (targetBelowSource) propagateCellData(cellValue, targetX, targetY, targetX, targetY + 1);
            if (targetAboveSource) propagateCellData(cellValue, targetX, targetY, targetX, targetY - 1);
        }

        // Propagate in the diagonal x=-y.
        if (isStringContained(targetContent, "/=")) {
            if (targetLeftToSource & targetBelowSource) {
                propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY + 1);
            }
            if (targetRightToSource & targetAboveSource) {
                propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY - 1);
            }
        }

        // Propagate in the diagonal x=y.
        if (isStringContained(targetContent, "\\=")) {
            if (targetRightToSource & targetBelowSource) {
                propagateCellData(cellValue, targetX, targetY, targetX + 1, targetY + 1);
            }
            if (targetLeftToSource & targetAboveSource) {
                propagateCellData(cellValue, targetX, targetY, targetX - 1, targetY - 1);
            }
        }

        // If we got a dot, store the value there.
        // Do not forget to mark it with "!", so we can rescan it later.
        if (isStringContained(targetContent, ".")) {
            setCircuitCell(targetX, targetY, "!" + cellValue);
            markThatStateChanged();
        }

        // If we got a "~", store the inverted value there.
        // Do not forget to mark it with "!", so we can rescan it later.
        if (isStringContained(targetContent, "~")) {
            setCircuitCell(targetX, targetY, "!~(" + cellValue + ")");
            markThatStateChanged();
        }

        // If we found a binary logical port with one of the values set and
        // we can set the another value, do it. Use "%" and "&" to know which
        // one was already defined.
        // BTW, do not forget to mark it with "!", so we can rescan it later.
        if ((targetContent.charAt(0) == '%' & sourceY == targetY - 1)
                | (targetContent.charAt(0) == '&' & sourceY == targetY + 1))
        {
            setCircuitCell(targetX, targetY,
                    "!(" + cellValue + ")"
                    + targetContent.charAt(1)
                    + "(" + targetContent.substring(2) + ")");
            markThatStateChanged();
        }

        // Found a binary logical port without any value setted, so set it.
        // Use "%" and "&" to mark which one was setted.
        if (isStringContained(targetContent, "OoAaXx")) {
            setCircuitCell(targetX, targetY, (sourceY == targetY + 1 ? "%" : "&") + targetContent + cellValue);
            markThatStateChanged();
        }

        // If we found an output, store the value there.
        // Mark it with "$", so we will print it in the future.
        if (isStringContained(targetContent, ":")) {
            setCircuitCell(targetX, targetY, "$" + cellValue);
            markThatStateChanged();
        }
    }

    void setCircuitCell(int cellX, int cellY, String cellContents) {
        circuitState.put(cellX * maxLines + cellY, cellContents);
    }

    void markThatStateChanged() {
        finished = false;
    }

    boolean isStringContained(String searchingString, String searchTarget) {
        return searchTarget.indexOf(searchingString) > -1;
    }
}