code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func d2d(d float64) float64 { return math.Mod(d, 360) }
func g2g(g float64) float64 { return math.Mod(g, 400) }
func m2m(m float64) float64 { return math.Mod(m, 6400) }
func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }
func d2g(d float64) float64 { return d2d(d) * 400 / 360 }
func d2m(d float64) float64 { return d2d(d) * 6400 / 360 }
func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }
func g2d(g float64) float64 { return g2g(g) * 360 / 400 }
func g2m(g float64) float64 { return g2g(g) * 6400 / 400 }
func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }
func m2d(m float64) float64 { return m2m(m) * 360 / 6400 }
func m2g(m float64) float64 { return m2m(m) * 400 / 6400 }
func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }
func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }
func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }
func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi } | 1,141Angles (geometric), normalization and conversion
| 0go
| onc8q |
void processFile(char* name){
int i,records;
double diff,b1,b2;
FILE* fp = fopen(name,);
fscanf(fp,,&records);
for(i=0;i<records;i++){
fscanf(fp,,&b1,&b2);
diff = fmod(b2-b1,360.0);
printf(,b2,b1,(diff<-180)?diff+360:((diff>=180)?diff-360:diff));
}
fclose(fp);
}
int main(int argC,char* argV[])
{
double diff;
if(argC < 2)
printf(,argV[0]);
else if(argC == 2)
processFile(argV[1]);
else{
diff = fmod(atof(argV[2])-atof(argV[1]),360.0);
printf(,argV[2],argV[1],(diff<-180)?diff+360:((diff>=180)?diff-360:diff));
}
return 0;
} | 1,142Angle difference between two bearings
| 5c
| 5gauk |
import java.lang.reflect.Constructor
abstract class Angle implements Comparable<? extends Angle> {
double value
Angle(double value = 0) { this.value = normalize(value) }
abstract Number unitCircle()
abstract String unitName()
Number normalize(double n) { n % this.unitCircle() }
def <B extends Angle> B asType(Class<B> bClass){
if (bClass == this.class) return this
bClass.getConstructor(Number.class).newInstance(0).tap {
value = this.value * unitCircle() / this.unitCircle()
}
}
String toString() {
"${String.format('%14.8f',value)}${this.unitName()}"
}
int hashCode() {
value.hashCode() + 17 * unit().hashCode()
}
int compareTo(Angle that) {
this.value * that.unitCircle() <=> that.value * this.unitCircle()
}
boolean equals(that) {
this.is(that) ? true
: that instanceof Angle ? (this <=> that) == 0
: that instanceof Number ? this.value == this.normalize(that)
: super.equals(that)
}
}
class Degrees extends Angle {
static final int UNIT_CIRCLE = 360
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = " "
String unitName() { UNIT }
Degrees(Number value = 0) { super(value) }
}
class Gradians extends Angle {
static final int UNIT_CIRCLE = 400
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = " grad"
String unitName() { UNIT }
Gradians(Number value = 0) { super(value) }
}
class Mils extends Angle {
static final int UNIT_CIRCLE = 6400
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = " mil "
String unitName() { UNIT }
Mils(Number value = 0) { super(value) }
}
class Radians extends Angle {
static final double UNIT_CIRCLE = Math.PI*2
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = " rad "
String unitName() { UNIT }
Radians(Number value = 0) { super(value) }
} | 1,141Angles (geometric), normalization and conversion
| 7groovy
| xs3wl |
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow();
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
} | 1,143Animate a pendulum
| 5c
| q0zxc |
import Text.Printf
class (Num a, Fractional a, RealFrac a) => Angle a where
fullTurn :: a
mkAngle :: Double -> a
value :: a -> Double
fromTurn :: Double -> a
toTurn :: a -> Double
normalize :: a -> a
fromTurn t = angle t * fullTurn
toTurn a = value $ a / fullTurn
normalize a = a `modulo` fullTurn
where
modulo x r | x == r = r
| x < 0 = signum x * abs x `modulo` r
| x >= 0 = x - fromInteger (floor (x / r)) * r
angle :: Angle a => Double -> a
angle = normalize . mkAngle
from :: forall a b. (Angle a, Angle b) => a -> b
from = fromTurn . toTurn
to :: forall b a. (Angle a, Angle b) => a -> b
to = fromTurn . toTurn | 1,141Angles (geometric), normalization and conversion
| 8haskell
| 2upll |
import java.text.DecimalFormat; | 1,141Angles (geometric), normalization and conversion
| 9java
| 6mr3z |
typedef unsigned int uint;
int main(int argc, char **argv)
{
uint top = atoi(argv[1]);
uint *divsum = malloc((top + 1) * sizeof(*divsum));
uint pows[32] = {1, 0};
for (uint i = 0; i <= top; i++) divsum[i] = 1;
for (uint p = 2; p+p <= top; p++) {
if (divsum[p] > 1) {
divsum[p] -= p;
continue;}
uint x;
for (x = 1; pows[x - 1] <= top/p; x++)
pows[x] = p*pows[x - 1];
uint k= p-1;
for (uint n = p+p; n <= top; n += p) {
uint s=1+pows[1];
k--;
if ( k==0) {
for (uint i = 2; i < x && !(n%pows[i]); s += pows[i++]);
k = p; }
divsum[n] *= s;
}
}
for (uint p = (top >> 1)+1; p <= top; p++) {
if (divsum[p] > 1){
divsum[p] -= p;}
}
uint cnt = 0;
for (uint a = 1; a <= top; a++) {
uint b = divsum[a];
if (b > a && b <= top && divsum[b] == a){
printf(, a, b);
cnt++;}
}
printf(,top,cnt);
return 0;
} | 1,144Amicable pairs
| 5c
| 3yuza |
(defn angle-difference [a b]
(let [r (mod (- b a) 360)]
(if (>= r 180)
(- r 360)
r)))
(angle-difference 20 45)
(angle-difference -45 45)
(angle-difference -85 90)
(angle-difference -95 90)
(angle-difference -70099.74 29840.67) | 1,142Angle difference between two bearings
| 6clojure
| jks7m |
function angleConv(deg, inp, out) {
inp = inp.toLowerCase();
out = out.toLowerCase();
const D = 360,
G = 400,
M = 6400,
R = 2 * Math.PI; | 1,141Angles (geometric), normalization and conversion
| 10javascript
| lvbcf |
(ns pendulum
(:import
(javax.swing JFrame)
(java.awt Canvas Graphics Color)))
(def length 200)
(def width (* 2 (+ 50 length)))
(def height (* 3 (/ length 2)))
(def dt 0.1)
(def g 9.812)
(def k (- (/ g length)))
(def anchor-x (/ width 2))
(def anchor-y (/ height 8))
(def angle (atom (/ (Math/PI) 2)))
(defn draw [#^Canvas canvas angle]
(let [buffer (.getBufferStrategy canvas)
g (.getDrawGraphics buffer)
ball-x (+ anchor-x (* (Math/sin angle) length))
ball-y (+ anchor-y (* (Math/cos angle) length))]
(try
(doto g
(.setColor Color/BLACK)
(.fillRect 0 0 width height)
(.setColor Color/RED)
(.drawLine anchor-x anchor-y ball-x ball-y)
(.setColor Color/YELLOW)
(.fillOval (- anchor-x 3) (- anchor-y 4) 7 7)
(.fillOval (- ball-x 7) (- ball-y 7) 14 14))
(finally (.dispose g)))
(if-not (.contentsLost buffer)
(.show buffer)) ))
(defn start-renderer [canvas]
(->>
(fn [] (draw canvas @angle) (recur))
(new Thread)
(.start)))
(defn -main [& args]
(let [frame (JFrame. "Pendulum")
canvas (Canvas.)]
(doto frame
(.setSize width height)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setResizable false)
(.add canvas)
(.setVisible true))
(doto canvas
(.createBufferStrategy 2)
(.setVisible true)
(.requestFocus))
(start-renderer canvas)
(loop [v 0]
(swap! angle #(+ % (* v dt)))
(Thread/sleep 15)
(recur (+ v (* k (Math/sin @angle) dt)))) ))
(-main) | 1,143Animate a pendulum
| 6clojure
| id9om |
import java.text.DecimalFormat as DF
const val DEGREE = 360.0
const val GRADIAN = 400.0
const val MIL = 6400.0
const val RADIAN = 2 * Math.PI
fun d2d(a: Double) = a % DEGREE
fun d2g(a: Double) = a * (GRADIAN / DEGREE)
fun d2m(a: Double) = a * (MIL / DEGREE)
fun d2r(a: Double) = a * (RADIAN / 360)
fun g2d(a: Double) = a * (DEGREE / GRADIAN)
fun g2g(a: Double) = a % GRADIAN
fun g2m(a: Double) = a * (MIL / GRADIAN)
fun g2r(a: Double) = a * (RADIAN / GRADIAN)
fun m2d(a: Double) = a * (DEGREE / MIL)
fun m2g(a: Double) = a * (GRADIAN / MIL)
fun m2m(a: Double) = a % MIL
fun m2r(a: Double) = a * (RADIAN / MIL)
fun r2d(a: Double) = a * (DEGREE / RADIAN)
fun r2g(a: Double) = a * (GRADIAN / RADIAN)
fun r2m(a: Double) = a * (MIL / RADIAN)
fun r2r(a: Double) = a % RADIAN
fun main() {
val fa = DF("######0.000000")
val fc = DF("###0.0000")
println(" degrees gradiens mils radians")
for (a in listOf(-2.0, -1.0, 0.0, 1.0, 2.0, 6.2831853, 16.0, 57.2957795, 359.0, 399.0, 6399.0, 1000000.0))
for (units in listOf("degrees", "gradiens", "mils", "radians")) {
val (d,g,m,r) = when (units) {
"degrees" -> {
val d = d2d(a)
listOf(d, d2g(d), d2m(d), d2r(d))
}
"gradiens" -> {
val g = g2g(a)
listOf(g2d(g), g, g2m(g), g2r(g))
}
"mils" -> {
val m = m2m(a)
listOf(m2d(m), m2g(m), m, m2r(m))
}
"radians" -> {
val r = r2r(a)
listOf(r2d(r), r2g(r), r2m(r), r)
}
else -> emptyList()
}
println("%15s %8s =%10s %10s %10s %10s".format(fa.format(a), units, fc.format(d), fc.format(g), fc.format(m), fc.format(r)))
}
} | 1,141Angles (geometric), normalization and conversion
| 11kotlin
| dtvnz |
(ns example
(:gen-class))
(defn factors [n]
" Find the proper factors of a number "
(into (sorted-set)
(mapcat (fn [x] (if (= x 1) [x] [x (/ n x)]))
(filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))) )))
(def find-pairs (into #{}
(for [n (range 2 20000)
:let [f (factors n)
M (apply + f)
g (factors M)
N (apply + g)]
:when (= n N)
:when (not= M N)]
(sorted-set n M))))
(doseq [q find-pairs]
(println q)) | 1,144Amicable pairs
| 6clojure
| c279b |
package main
import (
"log"
"time"
"github.com/gdamore/tcell"
)
const (
msg = "Hello World! "
x0, y0 = 8, 3
shiftsPerSecond = 4
clicksToExit = 5
)
func main() {
s, err := tcell.NewScreen()
if err != nil {
log.Fatal(err)
}
if err = s.Init(); err != nil {
log.Fatal(err)
}
s.Clear()
s.EnableMouse()
tick := time.Tick(time.Second / shiftsPerSecond)
click := make(chan bool)
go func() {
for {
em, ok := s.PollEvent().(*tcell.EventMouse)
if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
continue
}
mx, my := em.Position()
if my == y0 && mx >= x0 && mx < x0+len(msg) {
click <- true
}
}
}()
for inc, shift, clicks := 1, 0, 0; ; {
select {
case <-tick:
shift = (shift + inc) % len(msg)
for i, r := range msg {
s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
}
s.Show()
case <-click:
clicks++
if clicks == clicksToExit {
s.Fini()
return
}
inc = len(msg) - inc
}
}
} | 1,140Animation
| 0go
| awt1f |
range = { degrees=360, gradians=400, mils=6400, radians=2.0*math.pi }
function convert(value, fromunit, tounit)
return math.fmod(value * range[tounit] / range[fromunit], range[tounit])
end
testvalues = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }
testunits = { "degrees", "gradians", "mils", "radians" }
print(string.format("%15s %8s =%15s %15s %15s %15s", "VALUE", "UNIT", "DEGREES", "GRADIANS", "MILS", "RADIANS"))
for _, value in ipairs(testvalues) do
for _, fromunit in ipairs(testunits) do
local d = convert(value, fromunit, "degrees")
local g = convert(value, fromunit, "gradians")
local m = convert(value, fromunit, "mils")
local r = convert(value, fromunit, "radians")
print(string.format("%15.7f %8s =%15.7f %15.7f %15.7f %15.7f", value, fromunit, d, g, m, r))
end
end | 1,141Angles (geometric), normalization and conversion
| 1lua
| fzudp |
import Graphics.HGL.Units (Time, Point, Size, )
import Graphics.HGL.Draw.Monad (Graphic, )
import Graphics.HGL.Draw.Text
import Graphics.HGL.Draw.Font
import Graphics.HGL.Window
import Graphics.HGL.Run
import Graphics.HGL.Utils
import Control.Exception (bracket, )
runAnim = runGraphics $
bracket
(openWindowEx "Basic animation task" Nothing (250,50) DoubleBuffered (Just 110))
closeWindow
(\w -> do
f <- createFont (64,28) 0 False False "courier"
let loop t dir = do
e <- maybeGetWindowEvent w
let d = case e of
Just (Button _ True False) -> -dir
_ -> dir
t' = if d == 1 then last t: init t else tail t ++ [head t]
setGraphic w (withFont f $ text (5,10) t') >> getWindowTick w
loop t' d
loop "Hello world! " 1 ) | 1,140Animation
| 8haskell
| z6gt0 |
package main
import (
"fmt"
"io/ioutil"
"strings"
"sort"
)
func deranged(a, b string) bool {
if len(a) != len(b) {
return false
}
for i := range(a) {
if a[i] == b[i] { return false }
}
return true
}
func main() {
buf, _ := ioutil.ReadFile("unixdict.txt")
words := strings.Split(string(buf), "\n")
m := make(map[string] []string)
best_len, w1, w2 := 0, "", ""
for _, w := range(words) { | 1,139Anagrams/Deranged anagrams
| 0go
| ex3a6 |
use strict;
use warnings;
use feature 'say';
use POSIX 'fmod';
my $tau = 2 * 4*atan2(1, 1);
my @units = (
{ code => 'd', name => 'degrees' , number => 360 },
{ code => 'g', name => 'gradians', number => 400 },
{ code => 'm', name => 'mills' , number => 6400 },
{ code => 'r', name => 'radians' , number => $tau },
);
my %cvt;
for my $a (@units) {
for my $b (@units) {
$cvt{ "${$a}{code}2${$b}{code}" } = sub {
my($angle) = shift;
my $norm = fmod($angle,${$a}{number});
$norm -= ${$a}{number} if $angle < 0;
$norm * ${$b}{number} / ${$a}{number}
}
}
}
printf '%s'. '%12s'x4 . "\n", ' Angle Unit ', <Degrees Gradians Mills Radians>;
for my $angle (-2, -1, 0, 1, 2, $tau, 16, 360/$tau, 360-1, 400-1, 6400-1, 1_000_000) {
print "\n";
for my $from (@units) {
my @sub_keys = map { "${$from}{code}2${$_}{code}" } @units;
my @results = map { &{$cvt{$_}}($angle) } @sub_keys;
printf '%10g%-8s' . '%12g'x4 . "\n", $angle, ${$from}{name}, @results;
}
} | 1,141Angles (geometric), normalization and conversion
| 2perl
| jk07f |
def map = new TreeMap<Integer,Map<String,List<String>>>()
new URL('http: | 1,139Anagrams/Deranged anagrams
| 7groovy
| kpnh7 |
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Rotate {
private static class State {
private final String text = "Hello World! ";
private int startIndex = 0;
private boolean rotateRight = true;
}
public static void main(String[] args) {
State state = new State();
JLabel label = new JLabel(state.text);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
state.rotateRight = !state.rotateRight;
}
});
TimerTask task = new TimerTask() {
public void run() {
int delta = state.rotateRight ? 1 : -1;
state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();
label.setText(rotate(state.text, state.startIndex));
}
};
Timer timer = new Timer(false);
timer.schedule(task, 0, 500);
JFrame rot = new JFrame();
rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
rot.add(label);
rot.pack();
rot.setLocationRelativeTo(null);
rot.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
timer.cancel();
}
});
rot.setVisible(true);
}
private static String rotate(String text, int startIdx) {
char[] rotated = new char[text.length()];
for (int i = 0; i < text.length(); i++) {
rotated[i] = text.charAt((i + startIdx) % text.length());
}
return String.valueOf(rotated);
}
} | 1,140Animation
| 9java
| onl8d |
import Data.List (maximumBy, sort, unfoldr)
import Data.Ord (comparing)
import qualified Data.Map as M
import qualified Data.Set as S
groupBySig :: [String] -> [(String, S.Set String)]
groupBySig = map ((,) . sort <*> S.singleton)
equivs :: [(String, S.Set String)] -> [[String]]
equivs = map (S.toList . snd) . M.toList . M.fromListWith S.union
isDerangement :: (String, String) -> Bool
isDerangement (a, b) = and $ zipWith (/=) a b
pairs :: [t] -> [(t, t)]
pairs = concat . unfoldr step
where
step (x:xs) = Just (map (x, ) xs, xs)
step [] = Nothing
anagrams :: [String] -> [(String, String)]
anagrams = concatMap pairs . equivs . groupBySig
maxDerangedAnagram :: [String] -> Maybe (String, String)
maxDerangedAnagram = maxByLen . filter isDerangement . anagrams
where
maxByLen [] = Nothing
maxByLen xs = Just $ maximumBy (comparing (length . fst)) xs
main :: IO ()
main = do
input <- readFile "unixdict.txt"
case maxDerangedAnagram $ words input of
Nothing -> putStrLn "No deranged anagrams were found."
Just (a, b) -> putStrLn $ "Longest deranged anagrams: " <> a <> " and " <> b | 1,139Anagrams/Deranged anagrams
| 8haskell
| 3y7zj |
PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize2rad(a):
while a < 0: a += TWO_PI
while a >= TWO_PI: a -= TWO_PI
return a
def deg2grad(a): return a * 10.0 / 9.0
def deg2mil(a): return a * 160.0 / 9.0
def deg2rad(a): return a * PI / 180.0
def grad2deg(a): return a * 9.0 / 10.0
def grad2mil(a): return a * 16.0
def grad2rad(a): return a * PI / 200.0
def mil2deg(a): return a * 9.0 / 160.0
def mil2grad(a): return a / 16.0
def mil2rad(a): return a * PI / 3200.0
def rad2deg(a): return a * 180.0 / PI
def rad2grad(a): return a * 200.0 / PI
def rad2mil(a): return a * 3200.0 / PI | 1,141Angles (geometric), normalization and conversion
| 3python
| hb8jw |
null | 1,140Animation
| 11kotlin
| xs6ws |
package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
} | 1,145Almkvist-Giullera formula for pi
| 0go
| nfmi1 |
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DerangedAnagrams {
public static void main(String[] args) throws IOException {
List<String> words = Files.readAllLines(new File("unixdict.txt").toPath());
printLongestDerangedAnagram(words);
}
private static void printLongestDerangedAnagram(List<String> words) {
words.sort(Comparator.comparingInt(String::length).reversed().thenComparing(String::toString));
Map<String, ArrayList<String>> map = new HashMap<>();
for (String word : words) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String key = String.valueOf(chars);
List<String> anagrams = map.computeIfAbsent(key, k -> new ArrayList<>());
for (String anagram : anagrams) {
if (isDeranged(word, anagram)) {
System.out.printf("%s%s%n", anagram, word);
return;
}
}
anagrams.add(word);
}
System.out.println("no result");
}
private static boolean isDeranged(String word1, String word2) {
for (int i = 0; i < word1.length(); i++) {
if (word1.charAt(i) == word2.charAt(i)) {
return false;
}
}
return true;
}
} | 1,139Anagrams/Deranged anagrams
| 9java
| idvos |
package main
import "fmt"
func main() {
for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
f, ok := arFib(n)
if ok {
fmt.Printf("fib%d =%d\n", n, f)
} else {
fmt.Println("fib undefined for negative numbers")
}
}
}
func arFib(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n < 2:
return n, true
}
return yc(func(recurse fn) fn {
return func(left, term1, term2 int) int {
if left == 0 {
return term1+term2
}
return recurse(left-1, term1+term2, term1)
}
})(n-2, 1, 0), true
}
type fn func(int, int, int) int
type ff func(fn) fn
type fx func(fx) fn
func yc(f ff) fn {
return func(x fx) fn {
return x(x)
}(func(x fx) fn {
return f(func(a1, a2, a3 int) int {
return x(x)(a1, a2, a3)
})
})
} | 1,138Anonymous recursion
| 0go
| s8cqa |
module Angles
BASES = { => 360, => 400, => 6400, => Math::PI*2 , => 24 }
def self.method_missing(meth, angle)
from, to = BASES.values_at(*meth.to_s.split())
raise NoMethodError, meth if (from.nil? or to.nil?)
mod = (angle.to_f * to / from) % to
angle < 0? mod - to: mod
end
end
names = Angles::BASES.keys
puts + *names.size % names
test = [-2, -1, 0, 1, 2*Math::PI, 16, 360/(2*Math::PI), 360-1, 400-1, 6400-1, 1_000_000]
test.each do |n|
names.each do |first|
res = names.map{|last| Angles.send((first + + last).to_sym, n)}
puts first + *names.size % res
end
puts
end | 1,141Angles (geometric), normalization and conversion
| 14ruby
| b1ikq |
import Control.Monad
import Data.Number.CReal
import GHC.Integer
import Text.Printf
iterations = 52
main = do
printf "N.%44s%4s%s\n"
"Integral part of Nth term" "10^" "=Actual value of Nth term"
forM_ [0..9] $ \n ->
printf "%d.%44d%4d%s\n" n
(almkvistGiulleraIntegral n)
(tenExponent n)
(showCReal 50 (almkvistGiullera n))
printf "\nPi after%d iterations:\n" iterations
putStrLn $ showCReal 70 $ almkvistGiulleraPi iterations
almkvistGiulleraIntegral n =
let polynomial = (532 `timesInteger` n `timesInteger` n) `plusInteger` (126 `timesInteger` n) `plusInteger` 9
numerator = 32 `timesInteger` (facInteger (6 `timesInteger` n)) `timesInteger` polynomial
denominator = 3 `timesInteger` (powInteger (facInteger n) 6)
in numerator `divInteger` denominator
tenExponent n = 3 `minusInteger` (6 `timesInteger` (1 `plusInteger` n))
almkvistGiullera n = fromInteger (almkvistGiulleraIntegral n) / fromInteger (powInteger 10 (abs (tenExponent n)))
almkvistGiulleraSum n = sum $ map almkvistGiullera [0 .. n]
almkvistGiulleraPi n = sqrt $ 1 / almkvistGiulleraSum n
facInteger n = if n `leInteger` 1 then 1 else n `timesInteger` facInteger (n `minusInteger` 1)
powInteger 1 _ = 1
powInteger _ 0 = 1
powInteger b 1 = b
powInteger b e = b `timesInteger` powInteger b (e `minusInteger` 1) | 1,145Almkvist-Giullera formula for pi
| 8haskell
| u4kv2 |
#!/usr/bin/env js
function main() {
var wordList = read('unixdict.txt').split(/\s+/);
var anagrams = findAnagrams(wordList);
var derangedAnagrams = findDerangedAnagrams(anagrams);
var longestPair = findLongestDerangedPair(derangedAnagrams);
print(longestPair.join(' '));
}
function findLongestDerangedPair(danas) {
var longestLen = danas[0][0].length;
var longestPair = danas[0];
for (var i in danas) {
if (danas[i][0].length > longestLen) {
longestLen = danas[i][0].length;
longestPair = danas[i];
}
}
return longestPair;
}
function findDerangedAnagrams(anagrams) {
var deranged = [];
function isDeranged(w1, w2) {
for (var c = 0; c < w1.length; c++) {
if (w1[c] == w2[c]) {
return false;
}
}
return true;
}
function findDeranged(anas) {
for (var a = 0; a < anas.length; a++) {
for (var b = a + 1; b < anas.length; b++) {
if (isDeranged(anas[a], anas[b])) {
deranged.push([anas[a], anas[b]]);
}
}
}
}
for (var a in anagrams) {
var anas = anagrams[a];
findDeranged(anas);
}
return deranged;
}
function findAnagrams(wordList) {
var anagrams = {};
for (var wordNum in wordList) {
var word = wordList[wordNum];
var key = word.split('').sort().join('');
if (!(key in anagrams)) {
anagrams[key] = [];
}
anagrams[key].push(word);
}
for (var a in anagrams) {
if (anagrams[a].length < 2) {
delete(anagrams[a]);
}
}
return anagrams;
}
main(); | 1,139Anagrams/Deranged anagrams
| 10javascript
| z6rt2 |
def fib = {
assert it > -1
{i -> i < 2 ? i: {j -> owner.call(j)}(i-1) + {k -> owner.call(k)}(i-2)}(it)
} | 1,138Anonymous recursion
| 7groovy
| aw31p |
use std::{
marker::PhantomData,
f64::consts::PI,
};
pub trait AngleUnit: Copy {
const TURN: f64;
const NAME: &'static str;
}
macro_rules! unit {
($name:ident, $value:expr, $string:expr) => (
#[derive(Debug, Copy, Clone)]
struct $name;
impl AngleUnit for $name {
const TURN: f64 = $value;
const NAME: &'static str = $string;
}
);
}
unit!(Degrees, 360.0, "Degrees");
unit!(Radians, PI * 2.0, "Radians");
unit!(Gradians, 400.0, "Gradians");
unit!(Mils, 6400.0, "Mils");
#[derive(Copy, Clone, PartialEq, PartialOrd)]
struct Angle<T: AngleUnit>(f64, PhantomData<T>);
impl<T: AngleUnit> Angle<T> {
pub fn new(val: f64) -> Self {
Self(val, PhantomData)
}
pub fn normalize(self) -> Self {
Self(self.0% T::TURN, PhantomData)
}
pub fn val(self) -> f64 {
self.0
}
pub fn convert<U: AngleUnit>(self) -> Angle<U> {
Angle::new(self.0 * U::TURN / T::TURN)
}
pub fn name(self) -> &'static str {
T::NAME
}
}
fn print_angles<T: AngleUnit>() {
let angles = [-2.0, -1.0, 0.0, 1.0, 2.0, 6.2831853, 16.0, 57.2957795, 359.0, 399.0, 6399.0, 1000000.0];
println!("{:<12} {:<12} {:<12} {:<12} {:<12} {:<12}", "Angle", "Unit", "Degrees", "Gradians", "Mils", "Radians");
for &angle in &angles {
let deg = Angle::<T>::new(angle).normalize();
println!("{:<12} {:<12} {:<12.4} {:<12.4} {:<12.4} {:<12.4}",
angle,
deg.name(),
deg.convert::<Degrees>().val(),
deg.convert::<Gradians>().val(),
deg.convert::<Mils>().val(),
deg.convert::<Radians>().val(),
);
}
println!();
}
fn main() {
print_angles::<Degrees>();
print_angles::<Gradians>();
print_angles::<Mils>();
print_angles::<Radians>();
} | 1,141Angles (geometric), normalization and conversion
| 15rust
| panbu |
import Foundation
func normalize(_ f: Double, N: Double) -> Double {
var a = f
while a < -N { a += N }
while a >= N { a -= N }
return a
}
func normalizeToDeg(_ f: Double) -> Double {
return normalize(f, N: 360)
}
func normalizeToGrad(_ f: Double) -> Double {
return normalize(f, N: 400)
}
func normalizeToMil(_ f: Double) -> Double {
return normalize(f, N: 6400)
}
func normalizeToRad(_ f: Double) -> Double {
return normalize(f, N: 2 * .pi)
}
func d2g(_ f: Double) -> Double { f * 10 / 9 }
func d2m(_ f: Double) -> Double { f * 160 / 9 }
func d2r(_ f: Double) -> Double { f * .pi / 180 }
func g2d(_ f: Double) -> Double { f * 9 / 10 }
func g2m(_ f: Double) -> Double { f * 16 }
func g2r(_ f: Double) -> Double { f * .pi / 200 }
func m2d(_ f: Double) -> Double { f * 9 / 160 }
func m2g(_ f: Double) -> Double { f / 16 }
func m2r(_ f: Double) -> Double { f * .pi / 3200 }
func r2d(_ f: Double) -> Double { f * 180 / .pi }
func r2g(_ f: Double) -> Double { f * 200 / .pi }
func r2m(_ f: Double) -> Double { f * 3200 / .pi }
let angles = [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000]
let names = ["Degrees", "Gradians", "Mils", "Radians"]
let fmt = { String(format: "%.4f", $0) }
let normal = [normalizeToDeg, normalizeToGrad, normalizeToMil, normalizeToRad]
let convert = [
[{ $0 }, d2g, d2m, d2r],
[g2d, { $0 }, g2m, g2r],
[m2d, m2g, { $0 }, m2r],
[r2d, r2g, r2m, { $0 }]
]
let ans =
angles.map({ angle in
(0..<4).map({ ($0, normal[$0](angle)) }).map({
(fmt(angle),
fmt($0.1),
names[$0.0],
fmt(convert[$0.0][0]($0.1)),
fmt(convert[$0.0][1]($0.1)),
fmt(convert[$0.0][2]($0.1)),
fmt(convert[$0.0][3]($0.1))
)
})
})
print("angle", "normalized", "unit", "degrees", "grads", "mils", "radians")
for res in ans {
for unit in res {
print(unit)
}
print()
} | 1,141Angles (geometric), normalization and conversion
| 17swift
| kpohx |
import esMain from 'es-main';
import { BigFloat, set_precision as SetPrecision } from 'bigfloat-esnext';
const Iterations = 52;
export const demo = function() {
SetPrecision(-75);
console.log("N." + "Integral part of Nth term".padStart(45) + " 10^ =Actual value of Nth term");
for (let i=0; i<10; i++) {
let line = `${i}. `;
line += `${integral(i)} `.padStart(45);
line += `${tenExponent(i)} `.padStart(5);
line += nthTerm(i);
console.log(line);
}
let pi = approximatePi(Iterations);
SetPrecision(-70);
pi = pi.dividedBy(100000).times(100000);
console.log(`\nPi after ${Iterations} iterations: ${pi}`)
}
export const bigFactorial = n => n <= 1n ? 1n : n * bigFactorial(n-1n); | 1,145Almkvist-Giullera formula for pi
| 10javascript
| v5h25 |
package main
import "fmt"
type bearing float64
var testCases = []struct{ b1, b2 bearing }{
{20, 45},
{-45, 45},
{-85, 90},
{-95, 90},
{-45, 125},
{-45, 145},
{29.4803, -88.6381},
{-78.3251, -159.036},
}
func main() {
for _, tc := range testCases {
fmt.Println(tc.b2.Sub(tc.b1))
}
}
func (b2 bearing) Sub(b1 bearing) bearing {
switch d := b2 - b1; {
case d < -180:
return d + 360
case d > 180:
return d - 360
default:
return d
}
} | 1,142Angle difference between two bearings
| 0go
| 8im0g |
fib :: Integer -> Maybe Integer
fib n
| n < 0 = Nothing
| otherwise = Just $ real n
where real 0 = 1
real 1 = 1
real n = real (n-1) + real (n-2) | 1,138Anonymous recursion
| 8haskell
| 9lpmo |
function love.load()
text = "Hello World! "
length = string.len(text)
update_time = 0.3
timer = 0
right_direction = true
local width, height = love.graphics.getDimensions( )
local size = 100
local font = love.graphics.setNewFont( size )
local twidth = font:getWidth( text )
local theight = font:getHeight( )
x = width/2 - twidth/2
y = height/2-theight/2
end
function love.update(dt)
timer = timer + dt
if timer > update_time then
timer = timer - update_time
if right_direction then
text = string.sub(text, 2, length) .. string.sub(text, 1, 1)
else
text = string.sub(text, length, length) .. string.sub(text, 1, length-1)
end
end
end
function love.draw()
love.graphics.print (text, x, y)
end
function love.keypressed(key, scancode, isrepeat)
if false then
elseif key == "escape" then
love.event.quit()
end
end
function love.mousepressed( x, y, button, istouch, presses )
right_direction = not right_direction
end | 1,140Animation
| 1lua
| q0yx0 |
def angleDifferenceA(double b1, double b2) {
r = (b2 - b1) % 360.0
(r > 180.0 ? r - 360.0
: r <= -180.0 ? r + 360.0
: r)
} | 1,142Angle difference between two bearings
| 7groovy
| wqtel |
import java.awt.*;
import javax.swing.*;
class Pendulum extends JPanel implements Runnable {
private angle = Math.PI / 2;
private length;
Pendulum(length) {
this.length = length;
setDoubleBuffered(true);
}
@Override
void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
def ballX = anchorX + (Math.sin(angle) * length) as int;
def ballY = anchorY + (Math.cos(angle) * length) as int;
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
}
void run() {
def angleAccel, angleVelocity = 0, dt = 0.1;
while (true) {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try { Thread.sleep(15); } catch (InterruptedException ex) {}
}
}
@Override
Dimension getPreferredSize() {
return new Dimension(2 * length + 50, (length / 2 * 3) as int);
}
static void main(String[] args) {
def f = new JFrame("Pendulum");
def p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
} | 1,143Animate a pendulum
| 7groovy
| y9g6o |
use strict;
use warnings;
use feature qw(say);
use Math::AnyNum qw(:overload factorial);
sub almkvist_giullera_integral {
my($n) = @_;
(32 * (14*$n * (38*$n + 9) + 9) * factorial(6*$n)) / (3*factorial($n)**6);
}
sub almkvist_giullera {
my($n) = @_;
almkvist_giullera_integral($n) / (10**(6*$n + 3));
}
sub almkvist_giullera_pi {
my ($prec) = @_;
local $Math::AnyNum::PREC = 4*($prec+1);
my $sum = 0;
my $target = '';
for (my $n = 0; ; ++$n) {
$sum += almkvist_giullera($n);
my $curr = ($sum**-.5)->as_dec;
return $target if ($curr eq $target);
$target = $curr;
}
}
say 'First 10 integer portions: ';
say "$_ " . almkvist_giullera_integral($_) for 0..9;
my $precision = 70;
printf(" to%s decimal places is:\n%s\n",
$precision, almkvist_giullera_pi($precision)); | 1,145Almkvist-Giullera formula for pi
| 2perl
| kpqhc |
import Control.Monad (join)
import Data.Bifunctor (bimap)
import Text.Printf (printf)
type Radians = Float
type Degrees = Float
bearingDelta :: (Radians, Radians) -> Radians
bearingDelta (a, b)
=
sign * acos ((ax * bx) + (ay * by))
where
(ax, ay) = (sin a, cos a)
(bx, by) = (sin b, cos b)
sign
| ((ay * bx) - (by * ax)) > 0 = 1
| otherwise = -1
angleBetweenDegrees :: (Degrees, Degrees) -> Degrees
angleBetweenDegrees =
degrees
. bearingDelta
. join bimap radians
main :: IO ()
main =
putStrLn . unlines $
fmap
( uncurry (printf "%6.2f -%6.2f -> %7.2f")
<*> angleBetweenDegrees
)
[ (20.0, 45.0),
(-45.0, 45.0),
(-85.0, 90.0),
(-95.0, 90.0),
(-45.0, 125.0),
(-45.0, 145.0)
]
degrees :: Radians -> Degrees
degrees = (/ pi) . (180 *)
radians :: Degrees -> Radians
radians = (/ 180) . (pi *) | 1,142Angle difference between two bearings
| 8haskell
| lvkch |
package main
import (
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/math"
"github.com/google/gxui/themes/dark"
omath "math"
"time"
) | 1,143Animate a pendulum
| 0go
| 2ukl7 |
null | 1,139Anagrams/Deranged anagrams
| 11kotlin
| q0mx1 |
import Graphics.HGL.Draw.Monad (Graphic, )
import Graphics.HGL.Draw.Picture
import Graphics.HGL.Utils
import Graphics.HGL.Window
import Graphics.HGL.Run
import Control.Exception (bracket, )
import Control.Arrow
toInt = fromIntegral.round
pendulum = runGraphics $
bracket
(openWindowEx "Pendulum animation task" Nothing (600,400) DoubleBuffered (Just 30))
closeWindow
(\w -> mapM_ ((\ g -> setGraphic w g >> getWindowTick w).
(\ (x, y) -> overGraphic (line (300, 0) (x, y))
(ellipse (x - 12, y + 12) (x + 12, y - 12)) )) pts)
where
dt = 1/30
t = - pi/4
l = 1
g = 9.812
nextAVT (a,v,t) = (a', v', t + v' * dt) where
a' = - (g / l) * sin t
v' = v + a' * dt
pts = map (\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi/2+0.6*t) )
$ iterate nextAVT (- (g / l) * sin t, t, 0) | 1,143Animate a pendulum
| 8haskell
| awn1g |
import mpmath as mp
with mp.workdps(72):
def integer_term(n):
p = 532 * n * n + 126 * n + 9
return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)
def exponent_term(n):
return -(mp.mpf() * n + 3)
def nthterm(n):
return integer_term(n) * mp.mpf()**exponent_term(n)
for n in range(10):
print(, n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\n to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath is ', end='')
mp.nprint(mp.pi, 71) | 1,145Almkvist-Giullera formula for pi
| 3python
| b1skr |
public class AngleDifference {
public static double getDifference(double b1, double b2) {
double r = (b2 - b1) % 360.0;
if (r < -180.0)
r += 360.0;
if (r >= 180.0)
r -= 360.0;
return r;
}
public static void main(String[] args) {
System.out.println("Input in -180 to +180 range");
System.out.println(getDifference(20.0, 45.0));
System.out.println(getDifference(-45.0, 45.0));
System.out.println(getDifference(-85.0, 90.0));
System.out.println(getDifference(-95.0, 90.0));
System.out.println(getDifference(-45.0, 125.0));
System.out.println(getDifference(-45.0, 145.0));
System.out.println(getDifference(-45.0, 125.0));
System.out.println(getDifference(-45.0, 145.0));
System.out.println(getDifference(29.4803, -88.6381));
System.out.println(getDifference(-78.3251, -159.036));
System.out.println("Input in wider range");
System.out.println(getDifference(-70099.74233810938, 29840.67437876723));
System.out.println(getDifference(-165313.6666297357, 33693.9894517456));
System.out.println(getDifference(1174.8380510598456, -154146.66490124757));
System.out.println(getDifference(60175.77306795546, 42213.07192354373));
}
} | 1,142Angle difference between two bearings
| 9java
| 3y4zg |
public static long fib(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not be a negative number");
return new Object() {
private long fibInner(int n) {
return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));
}
}.fibInner(n);
} | 1,138Anonymous recursion
| 9java
| t3rf9 |
function relativeBearing(b1Rad, b2Rad)
{
b1y = Math.cos(b1Rad);
b1x = Math.sin(b1Rad);
b2y = Math.cos(b2Rad);
b2x = Math.sin(b2Rad);
crossp = b1y * b2x - b2y * b1x;
dotp = b1x * b2x + b1y * b2y;
if(crossp > 0.)
return Math.acos(dotp);
return -Math.acos(dotp);
}
function test()
{
var deg2rad = 3.14159265/180.0;
var rad2deg = 180.0/3.14159265;
return "Input in -180 to +180 range\n"
+relativeBearing(20.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-45.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-85.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-95.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-45.0*deg2rad, 125.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-45.0*deg2rad, 145.0*deg2rad)*rad2deg+"\n"
+relativeBearing(29.4803*deg2rad, -88.6381*deg2rad)*rad2deg+"\n"
+relativeBearing(-78.3251*deg2rad, -159.036*deg2rad)*rad2deg+"\n"
+ "Input in wider range\n"
+relativeBearing(-70099.74233810938*deg2rad, 29840.67437876723*deg2rad)*rad2deg+"\n"
+relativeBearing(-165313.6666297357*deg2rad, 33693.9894517456*deg2rad)*rad2deg+"\n"
+relativeBearing(1174.8380510598456*deg2rad, -154146.66490124757*deg2rad)*rad2deg+"\n"
+relativeBearing(60175.77306795546*deg2rad, 42213.07192354373*deg2rad)*rad2deg+"\n";
} | 1,142Angle difference between two bearings
| 10javascript
| c2h9j |
string.tacnoc = function(str) | 1,139Anagrams/Deranged anagrams
| 1lua
| s89q8 |
function fibo(n) {
if (n < 0) { throw "Argument cannot be negative"; }
return (function(n) {
return (n < 2) ? 1 : arguments.callee(n-1) + arguments.callee(n-2);
})(n);
} | 1,138Anonymous recursion
| 10javascript
| mcbyv |
use Tk;
use Time::HiRes qw(sleep);
my $msg = 'Hello World! ';
my $first = '.+';
my $second = '.';
my $mw = Tk::MainWindow->new(-title => 'Animated side-scroller',-bg=>"white");
$mw->geometry ("400x150+0+0");
$mw->optionAdd('*Label.font', 'Courier 24 bold' );
my $scroller = $mw->Label(-text => "$msg")->grid(-row=>0,-column=>0);
$mw->bind('all'=> '<Key-Escape>' => sub {exit;});
$mw->bind("<Button>" => sub { ($second,$first) = ($first,$second) });
$scroller->after(1, \&display );
MainLoop;
sub display {
while () {
sleep 0.25;
$msg =~ s/($first)($second)/$2$1/;
$scroller->configure(-text=>"$msg");
$mw->update();
}
} | 1,140Animation
| 2perl
| 2u1lf |
(mapc #'use-package '(#:toadstool #:toadstool-system))
(defstruct (red-black-tree (:constructor tree (color left val right)))
color left val right)
(defcomponent tree (operator macro-mixin))
(defexpand tree (color left val right)
`(class red-black-tree red-black-tree-color ,color
red-black-tree-left ,left
red-black-tree-val ,val
red-black-tree-right ,right))
(pushnew 'tree *used-components*)
(defun balance (color left val right)
(toad-ecase (color left val right)
(('black (tree 'red (tree 'red a x b) y c) z d)
(tree 'red (tree 'black a x b) y
(tree 'black c z d)))
(('black (tree 'red a x (tree 'red b y c)) z d)
(tree 'red (tree 'black a x b) y (tree 'black c z d)))
(('black a x (tree 'red (tree 'red b y c) z d))
(tree 'red (tree 'black a x b) y (tree 'black c z d)))
(('black a x (tree 'red b y (tree 'red c z d)))
(tree 'red (tree 'black a x b) y (tree 'black c z d)))
((color a x b)
(tree color a x b))))
(defun %insert (x s)
(toad-ecase1 s
(nil (tree 'red nil x nil))
((tree color a y b)
(cond ((< x y)
(balance color (%insert x a) y b))
((> x y)
(balance color a y (%insert x b)))
(t s)))))
(defun insert (x s)
(toad-ecase1 (%insert x s)
((tree t a y b) (tree 'black a y b)))) | 1,146Algebraic data types
| 6clojure
| fz9dm |
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf(, k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(, i);
c++;
}
putchar('\n');
}
return 0;
} | 1,147Almost prime
| 5c
| s8dq5 |
import java.awt.*;
import javax.swing.*;
public class Pendulum extends JPanel implements Runnable {
private double angle = Math.PI / 2;
private int length;
public Pendulum(int length) {
this.length = length;
setDoubleBuffered(true);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
int ballX = anchorX + (int) (Math.sin(angle) * length);
int ballY = anchorY + (int) (Math.cos(angle) * length);
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
}
public void run() {
double angleAccel, angleVelocity = 0, dt = 0.1;
while (true) {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try { Thread.sleep(15); } catch (InterruptedException ex) {}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(2 * length + 50, length / 2 * 3);
}
public static void main(String[] args) {
JFrame f = new JFrame("Pendulum");
Pendulum p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
} | 1,143Animate a pendulum
| 9java
| jkq7c |
<html><head>
<title>Pendulum</title>
</head><body style="background: gray;">
<canvas id="canvas" width="600" height="600">
<p>Sorry, your browser does not support the <canvas> used to display the pendulum animation.</p>
</canvas>
<script>
function PendulumSim(length_m, gravity_mps2, initialAngle_rad, timestep_ms, callback) {
var velocity = 0;
var angle = initialAngle_rad;
var k = -gravity_mps2/length_m;
var timestep_s = timestep_ms / 1000;
return setInterval(function () {
var acceleration = k * Math.sin(angle);
velocity += acceleration * timestep_s;
angle += velocity * timestep_s;
callback(angle);
}, timestep_ms);
}
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var prev=0;
var sim = PendulumSim(1, 9.80665, Math.PI*99/100, 10, function (angle) {
var rPend = Math.min(canvas.width, canvas.height) * 0.47;
var rBall = Math.min(canvas.width, canvas.height) * 0.02;
var rBar = Math.min(canvas.width, canvas.height) * 0.005;
var ballX = Math.sin(angle) * rPend;
var ballY = Math.cos(angle) * rPend;
context.fillStyle = "rgba(255,255,255,0.51)";
context.globalCompositeOperation = "destination-out";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "yellow";
context.strokeStyle = "rgba(0,0,0,"+Math.max(0,1-Math.abs(prev-angle)*10)+")";
context.globalCompositeOperation = "source-over";
context.save();
context.translate(canvas.width/2, canvas.height/2);
context.rotate(angle);
context.beginPath();
context.rect(-rBar, -rBar, rBar*2, rPend+rBar*2);
context.fill();
context.stroke();
context.beginPath();
context.arc(0, rPend, rBall, 0, Math.PI*2, false);
context.fill();
context.stroke();
context.restore();
prev=angle;
});
</script>
</body></html> | 1,143Animate a pendulum
| 10javascript
| 1eip7 |
(ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
} | 1,147Almost prime
| 6clojure
| nf6ik |
import java.awt.*
import java.util.concurrent.*
import javax.swing.*
class Pendulum(private val length: Int) : JPanel(), Runnable {
init {
val f = JFrame("Pendulum")
f.add(this)
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.pack()
f.isVisible = true
isDoubleBuffered = true
}
override fun paint(g: Graphics) {
with(g) {
color = Color.WHITE
fillRect(0, 0, width, height)
color = Color.BLACK
val anchor = Element(width / 2, height / 4)
val ball = Element((anchor.x + Math.sin(angle) * length).toInt(), (anchor.y + Math.cos(angle) * length).toInt())
drawLine(anchor.x, anchor.y, ball.x, ball.y)
fillOval(anchor.x - 3, anchor.y - 4, 7, 7)
fillOval(ball.x - 7, ball.y - 7, 14, 14)
}
}
override fun run() {
angleVelocity += -9.81 / length * Math.sin(angle) * dt
angle += angleVelocity * dt
repaint()
}
override fun getPreferredSize() = Dimension(2 * length + 50, length / 2 * 3)
private data class Element(val x: Int, val y: Int)
private val dt = 0.1
private var angle = Math.PI / 2
private var angleVelocity = 0.0
}
fun main(a: Array<String>) {
val executor = Executors.newSingleThreadScheduledExecutor()
executor.scheduleAtFixedRate(Pendulum(200), 0, 15, TimeUnit.MILLISECONDS)
} | 1,143Animate a pendulum
| 11kotlin
| 5g1ua |
typedef const char * amb_t;
amb_t amb(size_t argc, ...)
{
amb_t *choices;
va_list ap;
int i;
if(argc) {
choices = malloc(argc*sizeof(amb_t));
va_start(ap, argc);
i = 0;
do { choices[i] = va_arg(ap, amb_t); } while(++i < argc);
va_end(ap);
i = 0;
do { TRY(choices[i]); } while(++i < argc);
free(choices);
}
FAIL;
}
int joins(const char *left, const char *right) { return left[strlen(left)-1] == right[0]; }
int _main() {
const char *w1,*w2,*w3,*w4;
w1 = amb(3, , , );
w2 = amb(3, , , );
w3 = amb(3, , , );
w4 = amb(2, , );
if(!joins(w1, w2)) amb(0);
if(!joins(w2, w3)) amb(0);
if(!joins(w3, w4)) amb(0);
printf(, w1, w2, w3, w4);
return EXIT_SUCCESS;
} | 1,148Amb
| 5c
| ont80 |
import sys
from PyQt5.QtCore import QBasicTimer, Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QLabel
class Marquee(QLabel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.right_to_left_direction = True
self.initUI()
self.timer = QBasicTimer()
self.timer.start(80, self)
def initUI(self):
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setText()
self.setFont(QFont(None, 50, QFont.Bold))
self.setStyleSheet()
def timerEvent(self, event):
i = 1 if self.right_to_left_direction else -1
self.setText(self.text()[i:] + self.text()[:i])
def mouseReleaseEvent(self, event):
self.right_to_left_direction = not self.right_to_left_direction
def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape:
self.close()
app = QApplication(sys.argv)
w = Marquee()
w.adjustSize()
w.move(QApplication.instance().desktop().screen().rect().center()
- w.rect().center())
w.show()
sys.exit(app.exec()) | 1,140Animation
| 3python
| v5a29 |
package main
import "fmt"
type Color string
const (
R Color = "R"
B = "B"
)
type Tree interface {
ins(x int) Tree
}
type E struct{}
func (_ E) ins(x int) Tree {
return T{R, E{}, x, E{}}
}
func (_ E) String() string {
return "E"
}
type T struct {
cl Color
le Tree
aa int
ri Tree
}
func (t T) balance() Tree {
if t.cl != B {
return t
}
le, leIsT := t.le.(T)
ri, riIsT := t.ri.(T)
var lele, leri, rile, riri T
var leleIsT, leriIsT, rileIsT, ririIsT bool
if leIsT {
lele, leleIsT = le.le.(T)
}
if leIsT {
leri, leriIsT = le.ri.(T)
}
if riIsT {
rile, rileIsT = ri.le.(T)
}
if riIsT {
riri, ririIsT = ri.ri.(T)
}
switch {
case leIsT && leleIsT && le.cl == R && lele.cl == R:
_, t2, z, d := t.destruct()
_, t3, y, c := t2.(T).destruct()
_, a, x, b := t3.(T).destruct()
return T{R, T{B, a, x, b}, y, T{B, c, z, d}}
case leIsT && leriIsT && le.cl == R && leri.cl == R:
_, t2, z, d := t.destruct()
_, a, x, t3 := t2.(T).destruct()
_, b, y, c := t3.(T).destruct()
return T{R, T{B, a, x, b}, y, T{B, c, z, d}}
case riIsT && rileIsT && ri.cl == R && rile.cl == R:
_, a, x, t2 := t.destruct()
_, t3, z, d := t2.(T).destruct()
_, b, y, c := t3.(T).destruct()
return T{R, T{B, a, x, b}, y, T{B, c, z, d}}
case riIsT && ririIsT && ri.cl == R && riri.cl == R:
_, a, x, t2 := t.destruct()
_, b, y, t3 := t2.(T).destruct()
_, c, z, d := t3.(T).destruct()
return T{R, T{B, a, x, b}, y, T{B, c, z, d}}
default:
return t
}
}
func (t T) ins(x int) Tree {
switch {
case x < t.aa:
return T{t.cl, t.le.ins(x), t.aa, t.ri}.balance()
case x > t.aa:
return T{t.cl, t.le, t.aa, t.ri.ins(x)}.balance()
default:
return t
}
}
func (t T) destruct() (Color, Tree, int, Tree) {
return t.cl, t.le, t.aa, t.ri
}
func (t T) String() string {
return fmt.Sprintf("T(%s,%v,%d,%v)", t.cl, t.le, t.aa, t.ri)
}
func insert(tr Tree, x int) Tree {
t := tr.ins(x)
switch t.(type) {
case T:
tt := t.(T)
_, a, y, b := tt.destruct()
return T{B, a, y, b}
case E:
return E{}
default:
return nil
}
}
func main() {
var tr Tree = E{}
for i := 1; i <= 16; i++ {
tr = insert(tr, i)
}
fmt.Println(tr)
} | 1,146Algebraic data types
| 0go
| 5gkul |
null | 1,142Angle difference between two bearings
| 11kotlin
| nflij |
package main
import "fmt"
func pfacSum(i int) int {
sum := 0
for p := 1; p <= i/2; p++ {
if i%p == 0 {
sum += p
}
}
return sum
}
func main() {
var a[20000]int
for i := 1; i < 20000; i++ {
a[i] = pfacSum(i)
}
fmt.Println("The amicable pairs below 20,000 are:")
for n := 2; n < 19999; n++ {
m := a[n]
if m > n && m < 20000 && n == a[m] {
fmt.Printf(" %5d and%5d\n", n, m)
}
}
} | 1,144Amicable pairs
| 0go
| b10kh |
char *name, *password;
...
LDAP *ld = ldap_init(, 389);
ldap_simple_bind_s(ld, name, password);
LDAPMessage **result;
ldap_search_s(ld, , LDAP_SCOPE_SUBTREE,
,
NULL,
0,
result);
ldap_msgfree(*result);
ldap_unbind(ld); | 1,149Active Directory/Search for a user
| 5c
| 1expj |
data Color = R | B
data Tree a = E | T Color (Tree a) a (Tree a)
balance :: Color -> Tree a -> a -> Tree a -> Tree a
balance B (T R (T R a x b) y c ) z d = T R (T B a x b) y (T B c z d)
balance B (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d)
balance B a x (T R (T R b y c) z d ) = T R (T B a x b) y (T B c z d)
balance B a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d)
balance col a x b = T col a x b
insert :: Ord a => a -> Tree a -> Tree a
insert x s = T B a y b where
ins E = T R E x E
ins s@(T col a y b)
| x < y = balance col (ins a) y b
| x > y = balance col a y (ins b)
| otherwise = s
T _ a y b = ins s | 1,146Algebraic data types
| 8haskell
| xsnw4 |
bearing = {degrees = 0} | 1,142Angle difference between two bearings
| 1lua
| dt2nq |
fun fib(n: Int): Int {
require(n >= 0)
fun fib1(k: Int, a: Int, b: Int): Int =
if (k == 0) a else fib1(k - 1, b, a + b)
return fib1(n, 0, 1)
}
fun main(args: Array<String>) {
for (i in 0..20) print("${fib(i)} ")
println()
} | 1,138Anonymous recursion
| 11kotlin
| onv8z |
divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
main :: IO ()
main = do
let range = [1 .. 20000 :: Int]
divs = zip range $ map (sum . divisors) range
pairs = [(n, m) | (n, nd) <- divs, (m, md) <- divs,
n < m, nd == m, md == n]
print pairs | 1,144Amicable pairs
| 8haskell
| dtcn4 |
rotate_string <- function(x, forwards)
{
nchx <- nchar(x)
if(forwards)
{
paste(substr(x, nchx, nchx), substr(x, 1, nchx - 1), sep = "")
} else
{
paste(substr(x, 2, nchx), substr(x, 1, 1), sep = "")
}
}
handle_rotate_label <- function(obj, interval = 100)
{
addHandlerIdle(obj,
handler = function(h, ...)
{
svalue(obj) <- rotate_string(svalue(obj), tag(obj, "forwards"))
},
interval = interval
)
}
handle_change_direction_on_click <- function(obj)
{
addHandlerClicked(obj,
handler = function(h, ...)
{
tag(h$obj, "forwards") <-!tag(h$obj, "forwards")
}
)
}
library(gWidgets)
library(gWidgetstcltk)
lab <- glabel("Hello World! ", container = gwindow())
tag(lab, "forwards") <- TRUE
handle_rotate_label(lab)
handle_change_direction_on_click(lab) | 1,140Animation
| 13r
| 9lkmg |
(ns amb
(:use clojure.contrib.monads))
(defn amb [wss]
(let [valid-word (fn [w1 w2]
(if (and w1 (= (last w1) (first w2)))
(str w1 " " w2)))]
(filter #(reduce valid-word %)
(with-monad sequence-m (m-seq wss)))))
amb> (amb '(("the" "that" "a") ("frog" "elephant" "thing") ("walked" "treaded" "grows") ("slowly" "quickly")))
(("that" "thing" "grows" "slowly")) | 1,148Amb
| 6clojure
| t3mfv |
package main
import (
"log"
"github.com/jtblin/go-ldap-client"
)
func main() {
client := &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.example.com",
Port: 389,
GroupFilter: "(memberUid=%s)",
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect:%+v", err)
}
groups, err := client.GetGroupsOfUser("username")
if err != nil {
log.Fatalf("Error getting groups for user%s:%+v", "username", err)
}
log.Printf("Groups:%+v", groups)
} | 1,149Active Directory/Search for a user
| 0go
| y9l64 |
sub deranged {
my @a = split('', shift);
my @b = split('', shift);
for (0 .. $
$a[$_] eq $b[$_] and return;
}
return 1
}
sub find_deranged {
for my $i ( 0 .. $
for my $j ( $i+1 .. $
next unless deranged $_[$i], $_[$j];
print "length ", length($_[$i]), ": $_[$i] => $_[$j]\n";
return 1;
}
}
}
my %letter_list;
open my $in, 'unixdict.txt';
local $/ = undef;
for (split(' ', <$in>)) {
push @{ $letter_list{ join('', sort split('', $_)) } }, $_
}
for ( sort { length($b) <=> length($a) }
grep { @{ $letter_list{$_} } > 1 }
keys %letter_list )
{
last if find_deranged(@{ $letter_list{$_} });
} | 1,139Anagrams/Deranged anagrams
| 2perl
| v5e20 |
function degToRad( d )
return d * 0.01745329251
end
function love.load()
g = love.graphics
rodLen, gravity, velocity, acceleration = 260, 3, 0, 0
halfWid, damp = g.getWidth() / 2, .989
posX, posY, angle = halfWid
TWO_PI, angle = math.pi * 2, degToRad( 90 )
end
function love.update( dt )
acceleration = -gravity / rodLen * math.sin( angle )
angle = angle + velocity; if angle > TWO_PI then angle = 0 end
velocity = velocity + acceleration
velocity = velocity * damp
posX = halfWid + math.sin( angle ) * rodLen
posY = math.cos( angle ) * rodLen
end
function love.draw()
g.setColor( 250, 0, 250 )
g.circle( "fill", halfWid, 0, 8 )
g.line( halfWid, 4, posX, posY )
g.setColor( 250, 100, 20 )
g.circle( "fill", posX, posY, 20 )
end | 1,143Animate a pendulum
| 1lua
| 4ra5c |
module Main (main) where
import Data.Foldable (for_)
import qualified Data.Text.Encoding as Text (encodeUtf8)
import Ldap.Client (Attr(..), Filter(..))
import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)
main :: IO ()
main = do
entries <- Ldap.with (Ldap.Plain "localhost") 389 $ \ldap ->
Ldap.search ldap (Ldap.Dn "o=example.com") (Ldap.typesOnly True) (Attr "uid":= Text.encodeUtf8 "user") []
for_ entries $ \entry ->
print entry | 1,149Active Directory/Search for a user
| 8haskell
| hb1ju |
import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapSearchDemo {
public static void main(String[] args) throws IOException, LdapException, CursorException {
new LdapSearchDemo().demonstrateSearch();
}
private void demonstrateSearch() throws IOException, LdapException, CursorException {
try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) {
conn.bind("uid=admin,ou=system", "********");
search(conn, "*mil*");
conn.unBind();
}
}
private void search(LdapConnection connection, String uid) throws LdapException, CursorException {
String baseDn = "ou=users,o=mojo";
String filter = "(&(objectClass=person)(&(uid=" + uid + ")))";
SearchScope scope = SearchScope.SUBTREE;
String[] attributes = {"dn", "cn", "sn", "uid"};
int ksearch = 0;
EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);
while (cursor.next()) {
ksearch++;
Entry entry = cursor.get();
System.out.printf("Search entry%d =%s%n", ksearch, entry);
}
}
} | 1,149Active Directory/Search for a user
| 9java
| 5g7uf |
null | 1,146Algebraic data types
| 11kotlin
| rj1go |
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
public class AmicablePairs {
public static void main(String[] args) {
int limit = 20_000;
Map<Long, Long> map = LongStream.rangeClosed(1, limit)
.parallel()
.boxed()
.collect(Collectors.toMap(Function.identity(), AmicablePairs::properDivsSum));
LongStream.rangeClosed(1, limit)
.forEach(n -> {
long m = map.get(n);
if (m > n && m <= limit && map.get(m) == n)
System.out.printf("%s%s%n", n, m);
});
}
public static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0).sum();
}
} | 1,144Amicable pairs
| 9java
| s8zq0 |
...
char *name, *password;
...
LDAP *ld = ldap_init(, 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld); | 1,150Active Directory/Connect
| 5c
| t36f4 |
unsigned long long bruteForceProperDivisorSum(unsigned long long n){
unsigned long long i,sum = 0;
for(i=1;i<(n+1)/2;i++)
if(n%i==0 && n!=i)
sum += i;
return sum;
}
void printSeries(unsigned long long* arr,int size,char* type){
int i;
printf(,arr[0],type);
for(i=0;i<size-1;i++)
printf(,arr[i]);
printf(,arr[i]);
}
void aliquotClassifier(unsigned long long n){
unsigned long long arr[16];
int i,j;
arr[0] = n;
for(i=1;i<16;i++){
arr[i] = bruteForceProperDivisorSum(arr[i-1]);
if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){
printSeries(arr,i+1,(arr[i]==0)?:(arr[i]==n && i==1)?:(arr[i]==n && i==2)?:(arr[i]==arr[i-1] && arr[i]!=n)?:);
return;
}
for(j=1;j<i;j++){
if(arr[j]==arr[i]){
printSeries(arr,i+1,);
return;
}
}
}
printSeries(arr,i+1,);
}
void processFile(char* fileName){
FILE* fp = fopen(fileName,);
char str[21];
while(fgets(str,21,fp)!=NULL)
aliquotClassifier(strtoull(str,(char**)NULL,10));
fclose(fp);
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf(,argV[0]);
else{
if(strchr(argV[1],'.')!=NULL)
processFile(argV[1]);
else
aliquotClassifier(strtoull(argV[1],(char**)NULL,10));
}
return 0;
} | 1,151Aliquot sequence classifications
| 5c
| 2uulo |
(function (max) { | 1,144Amicable pairs
| 10javascript
| nf9iy |
use strict;
use warnings;
use Net::LDAP;
my $ldap = Net::LDAP->new( 'ldap://ldap.forumsys.com' ) or die "$@";
my $mesg = $ldap->bind( "cn=read-only-admin,dc=example,dc=com",
password => "password" );
$mesg->code and die $mesg->error;
my $srch = $ldap->search( base => "dc=example,dc=com",
filter => "(|(uid=gauss))" );
$srch->code and die $srch->error;
foreach my $entry ($srch->entries) { $entry->dump }
$mesg = $ldap->unbind; | 1,149Active Directory/Search for a user
| 2perl
| xs8w8 |
char *sortedWord(const char *word, char *wbuf)
{
char *p1, *p2, *endwrd;
char t;
int swaps;
strcpy(wbuf, word);
endwrd = wbuf+strlen(wbuf);
do {
swaps = 0;
p1 = wbuf; p2 = endwrd-1;
while (p1<p2) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2--;
}
p1 = wbuf; p2 = p1+1;
while(p2 < endwrd) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2++;
}
} while (swaps);
return wbuf;
}
static
short cxmap[] = {
0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56,
0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24,
0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03,
0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49,
0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f,
0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36,
0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a,
0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57,
};
int Str_Hash( const char *key, int ix_max )
{
const char *cp;
short mash;
int hash = 33501551;
for (cp = key; *cp; cp++) {
mash = cxmap[*cp % CXMAP_SIZE];
hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash<<1) + (mash<<5));
hash &= 0x3FFFFFFF;
}
return hash % ix_max;
}
typedef struct sDictWord *DictWord;
struct sDictWord {
const char *word;
DictWord next;
};
typedef struct sHashEntry *HashEntry;
struct sHashEntry {
const char *key;
HashEntry next;
DictWord words;
HashEntry link;
short wordCount;
};
HashEntry hashTable[HT_SIZE];
HashEntry mostPerms = NULL;
int buildAnagrams( FILE *fin )
{
char buffer[40];
char bufr2[40];
char *hkey;
int hix;
HashEntry he, *hep;
DictWord we;
int maxPC = 2;
int numWords = 0;
while ( fgets(buffer, 40, fin)) {
for(hkey = buffer; *hkey && (*hkey!='\n'); hkey++);
*hkey = 0;
hkey = sortedWord(buffer, bufr2);
hix = Str_Hash(hkey, HT_SIZE);
he = hashTable[hix]; hep = &hashTable[hix];
while( he && strcmp(he->key , hkey) ) {
hep = &he->next;
he = he->next;
}
if ( ! he ) {
he = malloc(sizeof(struct sHashEntry));
he->next = NULL;
he->key = strdup(hkey);
he->wordCount = 0;
he->words = NULL;
he->link = NULL;
*hep = he;
}
we = malloc(sizeof(struct sDictWord));
we->word = strdup(buffer);
we->next = he->words;
he->words = we;
he->wordCount++;
if ( maxPC < he->wordCount) {
maxPC = he->wordCount;
mostPerms = he;
he->link = NULL;
}
else if (maxPC == he->wordCount) {
he->link = mostPerms;
mostPerms = he;
}
numWords++;
}
printf(, numWords, maxPC);
return maxPC;
}
int main( )
{
HashEntry he;
DictWord we;
FILE *f1;
f1 = fopen(,);
buildAnagrams(f1);
fclose(f1);
f1 = fopen(,);
for (he = mostPerms; he; he = he->link) {
fprintf(f1,, he->wordCount);
for(we = he->words; we; we = we->next) {
fprintf(f1,, we->word);
}
fprintf(f1, );
}
fclose(f1);
return 0;
} | 1,152Anagrams
| 5c
| pa1by |
<?php
$words = file(
'http:
FILE_IGNORE_NEW_LINES
);
$length = 0;
foreach ($words as $word) {
$chars = str_split($word);
sort($chars);
$chars = implode(, $chars);
$length = strlen($chars);
$anagrams[$length][$chars][] = $word;
}
krsort($anagrams);
foreach ($anagrams as $anagram) {
$final_words = array();
foreach ($anagram as $words) {
if (count($words) >= 2) {
$counts = array();
foreach ($words as $word) {
$counts[$word] = array($word);
foreach ($words as $second_word) {
for ($i = 0, $length = strlen($word); $i < $length; $i++) {
if ($word[$i] === $second_word[$i]) continue 2;
}
$counts[$word][] = $second_word;
}
}
$max = 0;
$max_key = '';
foreach ($counts as $name => $count) {
if (count($count) > $max) {
$max = count($count);
$max_key = $name;
}
}
if ($max > 1) {
$final_words[] = $counts[$max_key];
}
}
}
if ($final_words) break;
}
foreach ($final_words as $final_word) {
echo implode(, $final_word), ;
}
?> | 1,139Anagrams/Deranged anagrams
| 12php
| 0ocsp |
local function Y(x) return (function (f) return f(f) end)(function(y) return x(function(z) return y(y)(z) end) end) end
return Y(function(fibs)
return function(n)
return n < 2 and 1 or fibs(n - 1) + fibs(n - 2)
end
end) | 1,138Anonymous recursion
| 1lua
| iduot |
require 'tk'
$str = TkVariable.new()
$dir = :right
def animate
$str.value = shift_char($str.value, $dir)
$root.after(125) {animate}
end
def shift_char(str, dir)
case dir
when :right then str[-1,1] + str[0..-2]
when :left then str[1..-1] + str[0,1]
end
end
$root = TkRoot.new( => )
TkLabel.new($root) do
textvariable $str
font
pack {side 'top'}
bind() {$dir = {:right=>:left,:left=>:right}[$dir]}
end
animate
Tk.mainloop | 1,140Animation
| 14ruby
| 5gwuj |
package main
import (
"log"
"github.com/jtblin/go-ldap-client"
)
func main() {
client := &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.example.com",
Port: 389,
UseSSL: false,
BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com",
BindPassword: "readonlypassword",
UserFilter: "(uid=%s)",
GroupFilter: "(memberUid=%s)",
Attributes: []string{"givenName", "sn", "mail", "uid"},
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect:%+v", err)
} | 1,150Active Directory/Connect
| 0go
| hbpjq |
module Main (main) where
import Data.Foldable (for_)
import qualified Data.Text.Encoding as Text (encodeUtf8)
import Ldap.Client (Attr(..), Filter(..))
import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)
main :: IO ()
main = do
entries <- Ldap.with (Ldap.Plain "localhost") 389 $ \ldap ->
Ldap.search ldap (Ldap.Dn "o=example.com") (Ldap.typesOnly True) (Attr "uid":= Text.encodeUtf8 "user") []
for_ entries $ \entry ->
print entry | 1,150Active Directory/Connect
| 8haskell
| idfor |
import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapConnectionDemo {
public static void main(String[] args) throws LdapException, IOException {
try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
connection.bind();
connection.unBind();
}
}
} | 1,150Active Directory/Connect
| 9java
| xs0wy |
<?php
$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);
$bind = ldap_bind($l, '[email protected]', 'password');
$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('displayName', 'company');
$search = ldap_search($l, $base, $criteria, $attributes);
$entries = ldap_get_entries($l, $search);
var_dump($entries); | 1,149Active Directory/Search for a user
| 12php
| 2u4l4 |
long long c[100];
void coef(int n)
{
int i, j;
if (n < 0 || n > 63) abort();
for (c[i=0] = 1; i < n; c[0] = -c[0], i++)
for (c[1 + (j=i)] = 1; j > 0; j--)
c[j] = c[j-1] - c[j];
}
int is_prime(int n)
{
int i;
coef(n);
c[0] += 1, c[i=n] -= 1;
while (i-- && !(c[i] % n));
return i < 0;
}
void show(int n)
{
do printf(, c[n], n); while (n--);
}
int main(void)
{
int n;
for (n = 0; n < 10; n++) {
coef(n);
printf(, n);
show(n);
putchar('\n');
}
printf();
for (n = 1; n <= 63; n++)
if (is_prime(n))
printf(, n);
putchar('\n');
return 0;
} | 1,153AKS test for primes
| 5c
| wqwec |
void memoizeIsPrime( bool * result, const int N )
{
result[2] = true;
result[3] = true;
int prime[N];
prime[0] = 3;
int end = 1;
for (int n = 5; n < N; n += 2)
{
bool n_is_prime = true;
for (int i = 0; i < end; ++i)
{
const int PRIME = prime[i];
if (n % PRIME == 0)
{
n_is_prime = false;
break;
}
if (PRIME * PRIME > n)
{
break;
}
}
if (n_is_prime)
{
prime[end++] = n;
result[n] = true;
}
}
}
int sumOfDecimalDigits( int n )
{
int sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
int main( void )
{
const int N = 500;
printf( , N );
bool is_prime[N];
memset( is_prime, 0, sizeof(is_prime) );
memoizeIsPrime( is_prime, N );
printf( );
int count = 1;
for (int i = 3; i < N; i += 2)
{
if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])
{
printf( , i );
++count;
if ((count % 10) == 0)
{
printf( );
}
}
}
printf( , count );
return 0;
} | 1,154Additive primes
| 5c
| clm9c |
use 5.010;
use strict;
use warnings qw(FATAL all);
my $balanced = qr{([^<>,]++|<(?-1),(?-1),(?-1),(?-1)>)};
my ($a, $b, $c, $d, $x, $y, $z) = map +qr((?<$_>$balanced)),
'a'..'d', 'x'..'z';
my $col = qr{(?<col>[RB])};
sub balance {
local $_ = shift;
if( /^<B,<R,<R,$a,$x,$b>,$y,$c>,$z,$d>\z/ or
/^<B,<R,$a,$x,<R,$b,$y,$c>>,$z,$d>\z/ or
/^<B,$a,$x,<R,<R,$b,$y,$c>,$z,$d>>\z/ or
/^<B,$a,$x,<R,$b,$y,<R,$c,$z,$d>>>\z/ )
{
my ($aa, $bb, $cc, $dd) = @+{'a'..'d'};
my ($xx, $yy, $zz) = @+{'x'..'z'};
"<R,<B,$aa,$xx,$bb>,$yy,<B,$cc,$zz,$dd>>";
} else {
$_;
}
}
sub ins {
my ($xx, $tree) = @_;
if($tree =~ m{^<$col,$a,$y,$b>\z} ) {
my ($color, $aa, $bb, $yy) = @+{qw(col a b y)};
if( $xx < $yy ) {
return balance "<$color,".ins($xx,$aa).",$yy,$bb>";
} elsif( $xx > $yy ) {
return balance "<$color,$aa,$yy,".ins($xx,$bb).">";
} else {
return $tree;
}
} elsif( $tree !~ /,/) {
return "<R,_,$xx,_>";
} else {
print "Unexpected failure!\n";
print "Tree parts are: \n";
print $_, "\n" for $tree =~ /$balanced/g;
exit;
}
}
sub insert {
my $tree = ins(@_);
$tree =~ m{^<$col,$a,$y,$b>\z} or die;
"<B,$+{a},$+{y},$+{b}>";
}
MAIN: {
my @a = 1..10;
for my $aa ( 1 .. $
my $bb = int rand( 1 + $aa );
@a[$aa, $bb] = @a[$bb, $aa];
}
my $t = "!";
for( @a ) {
$t = insert( $_, $t );
print "Tree: $t.\n";
}
}
print "Done\n"; | 1,146Algebraic data types
| 2perl
| dtmnw |
#[cfg(feature = "gtk")]
mod graphical {
extern crate gtk;
use self::gtk::traits::*;
use self::gtk::{Inhibit, Window, WindowType};
use std::ops::Not;
use std::sync::{Arc, RwLock};
pub fn create_window() {
gtk::init().expect("Failed to initialize GTK");
let window = Window::new(WindowType::Toplevel);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Hello World! ");
window.add(&button);
let lock = Arc::new(RwLock::new(false));
let lock_button = lock.clone();
button.connect_clicked(move |_| {
let mut reverse = lock_button.write().unwrap();
*reverse = reverse.not();
});
let lock_thread = lock.clone();
gtk::timeout_add(100, move || {
let reverse = lock_thread.read().unwrap();
let mut text = button.get_label().unwrap();
let len = &text.len();
if *reverse {
let begin = &text.split_off(1);
text.insert_str(0, begin);
} else {
let end = &text.split_off(len - 1);
text.insert_str(0, end);
}
button.set_label(&text);
gtk::Continue(true)
});
window.show_all();
gtk::main();
}
}
#[cfg(feature = "gtk")]
fn main() {
graphical::create_window();
}
#[cfg(not(feature = "gtk"))]
fn main() {} | 1,140Animation
| 15rust
| 4rx5u |
import scala.actors.Actor.{actor, loop, reactWithin, exit}
import scala.actors.TIMEOUT
import scala.swing.{SimpleSwingApplication, MainFrame, Label}
import scala.swing.event.MouseClicked
case object Revert
object BasicAnimation extends SimpleSwingApplication {
val label = new Label("Hello World! ")
val rotator = actor {
var goingRight = true
loop {
reactWithin(250 ) {
case Revert => goingRight = !goingRight
case TIMEOUT =>
if (goingRight)
label.text = label.text.last + label.text.init
else
label.text = label.text.tail + label.text.head
case unknown => println("Unknown message "+unknown); exit()
}
}
}
def top = new MainFrame {
title = "Basic Animation"
contents = label
}
listenTo(label.mouse.clicks) | 1,140Animation
| 16scala
| 7h0r9 |
import org.apache.directory.api.ldap.model.exception.LdapException
import org.apache.directory.ldap.client.api.LdapNetworkConnection
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger
class LDAP(map: Map<String, String>) {
fun run() {
var connection: LdapNetworkConnection? = null
try {
if (info) log.info("LDAP Connection to $hostname on port $port")
connection = LdapNetworkConnection(hostname, port.toInt())
try {
if (info) log.info("LDAP bind")
connection.bind()
} catch (e: LdapException) {
log.severe(e.toString())
}
try {
if (info) log.info("LDAP unbind")
connection.unBind()
} catch (e: LdapException) {
log.severe(e.toString())
}
} finally {
try {
if (info) log.info("LDAP close connection")
connection!!.close()
} catch (e: IOException) {
log.severe(e.toString())
}
}
}
private val log = Logger.getLogger(LDAP::class.java.name)
private val info = log.isLoggable(Level.INFO)
private val hostname: String by map
private val port: String by map
}
fun main(args: Array<String>) = LDAP(mapOf("hostname" to "localhost", "port" to "10389")).run() | 1,150Active Directory/Connect
| 11kotlin
| paeb6 |
import ldap
l = ldap.initialize()
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s(, )
base =
criteria =
attributes = ['displayName', 'company']
result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)
results = [entry for dn, entry in result if isinstance(entry, dict)]
print results
finally:
l.unbind() | 1,149Active Directory/Search for a user
| 3python
| q0oxi |
package main
import (
"bufio"
"fmt"
"log"
"os"
)
type SomeStruct struct {
runtimeFields map[string]string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
ss := SomeStruct{make(map[string]string)}
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Create two fields at runtime: ")
for i := 1; i <= 2; i++ {
fmt.Printf(" Field #%d:\n", i)
fmt.Print(" Enter name : ")
scanner.Scan()
name := scanner.Text()
fmt.Print(" Enter value: ")
scanner.Scan()
value := scanner.Text()
check(scanner.Err())
ss.runtimeFields[name] = value
fmt.Println()
}
for {
fmt.Print("Which field do you want to inspect? ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
value, ok := ss.runtimeFields[name]
if !ok {
fmt.Println("There is no field of that name, try again")
} else {
fmt.Printf("Its value is '%s'\n", value)
return
}
}
} | 1,155Add a variable to a class instance at runtime
| 0go
| xqawf |
package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address:%p%p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = int64(uintptr(ptr))
fmt.Printf("Pointer stored in int64:%#016x\n", addr64)
}
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) { | 1,156Address of a variable
| 0go
| kbrhz |
use Net::LDAP;
my $ldap = Net::LDAP->new('ldap://ldap.example.com') or die $@;
my $mesg = $ldap->bind( $bind_dn, password => $bind_pass ); | 1,150Active Directory/Connect
| 2perl
| y9c6u |
typedef struct {
double (*func)(double);
struct timeval start;
double v, last_v, last_t;
pthread_t id;
} integ_t, *integ;
void update(integ x)
{
struct timeval tv;
double t, v, (*f)(double);
f = x->func;
gettimeofday(&tv, 0);
t = ((tv.tv_sec - x->start.tv_sec) * 1000000
+ tv.tv_usec - x->start.tv_usec) * 1e-6;
v = f ? f(t) : 0;
x->v += (x->last_v + v) * (t - x->last_t) / 2;
x->last_t = t;
}
void* tick(void *a)
{
integ x = a;
while (1) {
usleep(100000);
update(x);
}
}
void set_input(integ x, double (*func)(double))
{
update(x);
x->func = func;
x->last_t = 0;
x->last_v = func ? func(0) : 0;
}
integ new_integ(double (*func)(double))
{
integ x = malloc(sizeof(integ_t));
x->v = x->last_v = 0;
x->func = 0;
gettimeofday(&x->start, 0);
set_input(x, func);
pthread_create(&x->id, 0, tick, x);
return x;
}
double sine(double t) { return sin(4 * atan2(1, 1) * t); }
int main()
{
integ x = new_integ(sine);
sleep(2);
set_input(x, 0);
usleep(500000);
printf(, x->v);
return 0;
} | 1,157Active object
| 5c
| 6yd32 |
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new(:host => 'hostname', :base => 'base')
ldap.authenticate('bind_dn', 'bind_pass')
filter = Net::LDAP::Filter.pres('objectclass')
filter &= Net::LDAP::Filter.eq('sn','Jackman')
filter = Net::LDAP::Filter.construct('(&(objectclass=*)(sn=Jackman))')
results = ldap.search(:filter => filter)
puts results[0][:sn] | 1,149Active Directory/Search for a user
| 14ruby
| 0onsu |
import org.apache.directory.api.ldap.model.message.SearchScope
import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}
object LdapSearchDemo extends App {
class LdapSearch {
def demonstrateSearch(): Unit = {
val conn = new LdapNetworkConnection("localhost", 11389)
try {
conn.bind("uid=admin,ou=system", "********")
search(conn, "*mil*")
conn.unBind()
} finally if (conn != null) conn.close()
}
private def search(connection: LdapConnection, uid: String): Unit = {
val baseDn = "ou=users,o=mojo"
val filter = "(&(objectClass=person)(&(uid=" + uid + ")))"
val scope = SearchScope.SUBTREE
val attributes = List("dn", "cn", "sn", "uid")
var ksearch = 0
val cursor = connection.search(baseDn, filter, scope, attributes: _*)
while (cursor.next) {
ksearch += 1
val entry = cursor.get
printf("Search entry%d =%s%n", ksearch, entry)
}
}
}
new LdapSearch().demonstrateSearch()
} | 1,149Active Directory/Search for a user
| 16scala
| nfzic |
class A {
final x = { it + 25 }
private map = new HashMap()
Object get(String key) { map[key] }
void set(String key, Object value) { map[key] = value }
} | 1,155Add a variable to a class instance at runtime
| 7groovy
| p1hbo |