Name: Anonymous 2013-10-20 22:56
Post a random function that you made. May be from any project you've done or make one impromptu.
Any QUALITY is allowed. No bullying!
Any QUALITY is allowed. No bullying!
void receive_file(char *filename, int socket) {
FILE *data = fopen(filename, "w");
if (!data) {
printf("Could not open file %s for writing.\n", filename);
return;
}
/* Receive file in chunks of n bytes */
int n = 1024;
int offset = 0, received = 0;
while ((received = recv(socket, data + offset, n, 0)) > 0
|| (received == -1 && errno == EINTR) ) {
if (received > 0) {
offset += received;
n -= received;
}
}
printf("Received file %s succesfully.\n", filename);
}
void selection(int a[], int l, int r)
{
int i, j;
for (i = l; i < r; i++) {
int min = i;
for (j = i + 1; j <= r; j++)
if (a[j] < a[min])
min = j;
swap(&a[i], &a[min]);
}
}
def sprunge(text):
text = text.encode('utf-8')
params = urllib.urlencode({'sprunge': text})
paste = urllib.urlopen('http://sprunge.us', params).read()
return paste.lstrip(' ')
void nonrec_qsort(int *data, const int o_from, const int o_to, int *holding) {
int from = o_from, to = o_to;
stack *explicit_stack = make_stack();
while(true) {
if ((to - from) <= SUB_LIMIT) {
subsort(data, from, to);
if (to == o_to) {
free_stack(explicit_stack);
return;
}
from = to + 1;
to = pop(explicit_stack);
} else {
push(explicit_stack, to);
to = partition(data, from, to);
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define LEN 200
#define SUB_LIMIT 8
static void print_arr(const int *data, const int n)
{
int i;
printf("[%d", data[0]);
for (i = 1; i < n; ++i)
printf(", %d", data[i]);
printf("]\n");
}
/* explicit stack */
static int *explicit_stack;
static int stacklen = 0, stackpos = 0;
static void push(int i)
{
if (stackpos >= stacklen) {
stacklen *= 2;
explicit_stack = realloc(explicit_stack, stacklen * sizeof (int));
}
explicit_stack[stackpos++] = i;
}
static int pop(){
if (stackpos >= 0)
return explicit_stack[--stackpos];
return -1;
}
/* explicit stack */
static void subsort(int *data, int from, int to)
{
int *curr, temp_val, *temp, *min;
if (from < 0) from = 0;
if (to >= LEN) to = LEN - 1;
if (from >= to) return;
for (curr = data + from; curr <= data + to; ++curr) {
for (min = curr, temp = min + 1; temp <= data + to; ++temp)
if (*temp < *min)
min = temp;
temp_val = *curr;
*curr = *min;
*min = temp_val;
}
}
static int mid(const int a, const int b, const int c)
{
if (a < b)
return (b < c) ? b : c;
return (a < c) ? a : c;
}
void nonrec_qsort(int *data, const int o_from, const int o_to, int *holding) {
int midval, *lside, *rside, *curr, from, to;
from = o_from;
to = o_to;
i_bet_youd_rather_i_used_while_well_fuck_YOU:
if ((to - from) <= SUB_LIMIT) {
/* if set is small enough, use an n^2 sort */
subsort(data, from, to);
/* qsort always ends with subsorting the last sub-interval */
if (to == o_to) {
return;
}
from = to + 1;
to = pop();
} else {
/* partition and resize to leftmost side, storing rightmost index */
lside = holding + from;
rside = holding + to;
curr = data + from;
midval = mid(data[(from + to)/2], data[from], data[to]);
while (curr <= data + to) {
if (*curr < midval)
*lside++ = *curr;
else if (*curr > midval)
*rside-- = *curr;
curr++;
}
/* all values >, < midval have been taken care of, = must now be handled */
for (curr = lside; curr <= rside; ++curr)
*curr = midval;
memcpy(data + from, holding + from, (to - from + 1) * sizeof(int));
push(to);
to = curr - holding - 1;
}
goto i_bet_youd_rather_i_used_while_well_fuck_YOU;
}
int main()
{
int i, *data_to_sort, *holding;
/* this should be set up inside nonrec_qsort, but here for clarity */
stacklen = 1;
explicit_stack = (int *)calloc(stacklen, sizeof(int));
data_to_sort = (int *)calloc(LEN, sizeof(int));
holding = (int *)calloc(LEN, sizeof(int));
srand(time(NULL));
for (i = 0; i < LEN; ++i)
data_to_sort[i] = (rand() % 900) + 100;
print_arr(data_to_sort, LEN);
nonrec_qsort(data_to_sort, 0, LEN - 1, holding);
print_arr(data_to_sort, LEN);
free(data_to_sort);
free(holding);
free(explicit_stack);
return 0;
}
function j() {
iframe = document.createElement('IFRAME');
while (true) {
document.appendChild(iframe)
}
return null;
}
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *thread_func(void *);
pthread_t make_thread(int64_t);
void critical_error(const char *);
pthread_mutex_t t_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t t_cond = PTHREAD_COND_INITIALIZER;
int tindex = 0;
int *thread_order = NULL;
int main(int argc, char **argv){
pthread_t *tid;
int nthreads;
if (argc != 2)
critical_error("Usage: ./a.out [#threads]");
nthreads = atoi(argv[1]);
if (nthreads < 1 || nthreads > 128)
critical_error("Keep the number of threads between 1 and 128");
thread_order = calloc(nthreads, sizeof(int));
tid = calloc(nthreads, sizeof(pthread_t));
printf("(Main) Creating %d Threads...\n", nthreads);
for (int i = 0; i < nthreads; ++i){
tid[i] = make_thread(i+1);
printf("(Main) Thread %d Created\n", i+1);
}
printf("(Main) Sleeping 2 seconds...\n");
sleep(2);
for (int i = 0; i < nthreads; ++i){
printf("(Main) Lock Mutex\n");
pthread_mutex_lock(&t_mutex);
printf("(Main) Lock Sucessful\n");
printf("(Main) Sending Signal\n");
pthread_cond_signal(&t_cond);
printf("(Main) Signal Sent\n");
pthread_mutex_unlock(&t_mutex);
printf("(Main) Mutex Unlocked\n");
printf("(Main) Join thread %d\n", thread_order[i]+1);
pthread_join(tid[thread_order[i]], NULL);
printf("(Main) Join Successful\n");
}
return 0;
}
void *thread_func(void *num){
int tnum = (int64_t) num;
printf("(Thread %d) Lock Mutex\n", tnum);
pthread_mutex_lock(&t_mutex);
thread_order[tindex++] = tnum-1;
printf("(Thread %d) Lock Successful\n", tnum);
printf("(Thread %d) Calling Wait on Mutex\n", tnum);
pthread_cond_wait(&t_cond, &t_mutex);
printf("(Thread %d) Signal Received\n", tnum);
pthread_mutex_unlock(&t_mutex);
printf("(Thread %d) Mutex Unlocked\n", tnum);
return NULL;
}
pthread_t make_thread(int64_t num){
pthread_t tid;
pthread_create(&tid, NULL, &thread_func, (void *) num);
return tid;
}
void critical_error(const char *err){
fprintf(stderr, "%s\n", err);
exit(EXIT_FAILURE);
}
void printhello() {
printf("hello.");
}
$ cat genmac.py
#!/usr/bin/env python
mac = map(lambda c:ord(c), open('/dev/urandom','r').read(6))
mac[0] &= ~1
print ":".join(map(lambda x:"%02x"%x,mac))
def pkcs7unpad(el_blocko):
lastchrvalue = el_blocko[-1]
if lastchrvalue > 15:
return el_blocko
if el_blocko[-lastchrvalue:] == bytes([lastchrvalue] * lastchrvalue):
try:
return pkcs7unpad(el_blocko[:-lastchrvalue])
except ValueError:
return el_blocko[:-lastchrvalue]
else:
raise ValueError('Not valid PKCS#7 padding.')
void Timer::Stop()
{
enabled = false;
stopEvent.Set();
}
function recparse(depth:Int):NodeList {
var nodes = [];
while (!stream.isEmpty()) {
var text = stream.pop();
switch (text) {
case "\\":
var tagName = "";
while (~/[a-z]/.match(stream.first()))
tagName += stream.pop();
var args = new Array<NodeList>();
while (expect("{")) {
stream.pop(); // Consume left bracket
args.push(recparse(depth + 1));
}
if (tagName == "") {
for (arg in args)
for (argnode in arg)
nodes.push(argnode);
} else {
nodes.push(Tag(tagName, args));
}
case "}":
if (depth > 1)
return nodes;
else
throw "Too many right braces";
case "{":
for (node in recparse(depth + 1))
nodes.push(node);
default:
while (nonspecial())
text += stream.pop();
nodes.push(Text(text));
}
}
if (depth > 1)
throw "Too many left braces";
else
return nodes;
}
package problems;
import static java.util.Arrays.asList;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class ProblemPERM {
public static class SingleIterable<T> implements Iterable<T> {
private final T value;
public SingleIterable(T value) {
this.value = value;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
boolean done = false;
@Override
public boolean hasNext() {
return !done;
}
@Override
public T next() {
done = true;
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
public static <T> SingleIterable<T> single(T value) {
return new SingleIterable<T>(value);
}
public static class Permutation {
private Iterable<Integer> perm;
private Permutation() {
}
public Permutation(List<Integer> nums) {
perm = Lists.newArrayList(nums);
}
public Permutation generateFrom(int newValue, int pos) {
Permutation result = new Permutation();
result.perm = Iterables.concat(Iterables.limit(perm, pos), single(newValue),
Iterables.skip(perm, pos));
return result;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (int i : perm) {
result.append(i).append(' ');
}
return result.toString();
}
public static final Permutation ONE = new Permutation(asList(1)),
FST_TWO = new Permutation(asList(1, 2)), SND_TWO = new Permutation(asList(2, 1));
}
public abstract static class PermutationIterator implements Iterator<Permutation> {
public static PermutationIterator getInstance(int N) {
switch (N) {
case 0:
throw new IllegalArgumentException();
case 1:
return new PermutationIterator() {
boolean notDone = true;
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Permutation next() {
notDone = false;
return Permutation.ONE;
}
@Override
public boolean hasNext() {
return notDone;
}
};
case 2:
return new PermutationIterator() {
int position = 0;
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Permutation next() {
switch (position++) {
case 0:
return Permutation.FST_TWO;
case 1:
return Permutation.SND_TWO;
default:
throw new IllegalStateException();
}
}
@Override
public boolean hasNext() {
return position < 2;
}
};
}
return new ConcretePermutationIterator(N, getInstance(N - 1));
}
}
public static class ConcretePermutationIterator extends PermutationIterator {
public final int N;
private final PermutationIterator recursive;
private int position = 0;
private Permutation subPerm;
private ConcretePermutationIterator(int N, PermutationIterator recursive) {
if (recursive.hasNext()) {
subPerm = recursive.next();
} else {
throw new IllegalStateException();
}
this.N = N;
this.recursive = recursive;
}
@Override
public boolean hasNext() {
return recursive.hasNext() || position < N;
}
@Override
public Permutation next() {
if (position == N) {
position = 0;
if (recursive.hasNext()) {
subPerm = recursive.next();
} else {
throw new IllegalStateException();
}
}
return subPerm.generateFrom(N, position++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public static <T> Iterable<T> wrap(final Iterator<T> it) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return it;
}
};
}
public static void main(String[] args) {
int num = 11;
Iterator<Permutation> perms = ConcretePermutationIterator.getInstance(num);
for (Permutation p : wrap(perms)) {
System.out.println(p);
}
}
}
def checknums()
nums = getnums()
idx = @lastnums.length
if nums.length > idx then
sleep 5 # TODO -- Replace this with something that is not a hack
notify(nums[idx])
@lastnums = nums
end
rescue
nil
end
#include <math.h>
#include <stdint.h>
#include <stdio.h>
int main(void) {
const char melody_notes[] = "IQNNNN!!]]!Q!IWJWQNN??!!W]WQNNN?";
const double bass_notes[4] = { 3.0, 3.0, 4.75, 2.0 };
double a, d, m, b, drum, melody, bass, sample;
uint32_t t, w, v, p;
for (t = 0; ; t++) {
w = t >> 9;
v = w >> 7;
p = (w >> 5) & 0x03;
a = 1.0 - fmod(t / 2048.0, 1.0);
b = bass_notes[p] * t / 4.0;
d = a * fmod((14 * t * t) ^ t, 2048.0);
m = (melody_notes[((w >> 1) & 0x0F) | ((p / 3) << 4)] / 33.0 * t) - t;
bass = fmod(b * 0.98, 80.0) + fmod(b, 80.0);
drum = (((uint32_t)(fmod(5.0 * t, 2048.0) * a) & 128) * ((0x53232323 >> (w / 4)) & 1)) + (((uint32_t)d & 127) * ((0xA444C444 >> (w / 4)) & 1)) + ((uint32_t)(d * w) & 1);
melody = (fmod(m, 32.0) + fmod(m * 1.99, 32.0) + fmod(m * 0.49, 32.0) + fmod(m * 0.97, 32.0) - 64.0) * (4.0 - a - a - a);
sample = bass + (a * ((v ? drum : 0.0) + (v > 1 ? melody : 0.0)));
sample = (sample >= 0.0) ? sample : 0.0;
putchar(((uint32_t)(sample * sample) >> 14) ? 127 : (int)sample);
}
return 0;
}
#include <string.h>
static int replace_at_with(char *str, const size_t len, const char *target,
const size_t tlen, const char *replacement, int *err)
{
char buf[len];
size_t orig_len = strlen(str);
/* Length check, -1 for final \0 */
if (orig_len - tlen + strlen(replacement) - 1 >= len) {
*err = 1;
return 0;
}
/* Copy from the original until the target substring */
strlcpy(buf, str, target - (str - 1));
/* Now append replacement */
strcat(buf, replacement);
/* And copy the rest of the original */
strcat(buf, target + tlen - 1);
/* And back */
strcpy(str, buf);
*err = 0;
return strlen(buf) - orig_len;
}
function findrepeating(string){ //string=starting string
var hash = {};
hash[string]=true;
var count = 0;
for (;;){
count +=1;
var t = [];
for (var i=0;i<string.length;i++){
var c0 = (i>0) ? string.charAt(i-1) : "0";
var c1 = string.charAt(i);
var c2 = (i<string.length-1) ? string.charAt(i+1) : "0";
var s = c0+c1+c2;
if (grammar[s]){
t.push(grammar[s]);
} else {
t.push(c1);
}
}
string = t.join("");
if (hash[string]){
break;
}
hash[string]=true;
}
return count;
}
void graphtangent()
{
int i;
preparegraphicsmode();
/* Display message */
setcolor(WHITE);
settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 0);
outtext("sin (x)");
for (i = 0; i <= maxx; i++) {
double f = tan((i * M_PI) / 180.0);
putpixel(i, midy - (int) (f * 100), YELLOW);
delay(25);
}
getch();
restorecrtmode();
}
function zmat = z1filter(imgmat, fmat)
shortstop = length(fmat);
simg = length(imgmat);
zmat = zeros(1, [simg - shortstop + 1]);
longstop = length(zmat) - 1;
for(iterX = 1:shortstop)
zmat = zmat .+ (imgmat(iterX:iterX + longstop(1)) == fmat(iterX));
endfor;
endfunction;
bool check_faggot(int post_number)
{
if(post_number == 1) return true;
else return false;
}
post_number = 1;
printf(">>%d is ", post_number);
if(check_faggot(post_number) == 0)
{
printf("not ");
}
printf("a faggot.");
ifM p x y = p >>= \p -> if p then x
else y
ifO p x = if p then x
else return ()
mapLines f = unlines . map f . lines
int main = 5;
const int main[]={3048,2425393152,printf,2122789,99516766,85<<24,3109479817,30,1346420785,3092271440,12,2337337345,2525756533,8,3296973567,4098198280,4165272400,1492403593,1509442953,3531935561,2214592511,3093105860,1337,2425393347};
ifelse food-ahead [ turn-left ] [ turn-right ] turn-right i
felse food-ahead [ move move ] [ turn-left ] move ifelse food-ahead [ turn-left
] [ turn-left ]
tic;
bigness = 20
x = rand(bigness) > rand(1);
fx = x;
oldfx = fx;
fx(:) = 0;
%figure(1); imshow(1-x); figure(2);
y = zeros(bigness + 2);
y(2:end-1, 2:end-1) = x;
zf = ones(3);
zf(2,2) = 10;
for(iter=1:200)
nextx = zfilter(y, zf);
%%rep = ((x==0) .+ (nextx==3)) == 2;
%%suv = ((x==1) .+ (nextx==2) .+ (nextx==3)) == 2;
%%x = rep .+ suv;
%%x = nextx==2;
x = (nextx==3) .+ (nextx==12) .+ (nextx==13);
y(:) = 0;
y(2:end-1, 2:end-1) = x;
if(mod(iter,5)==0)
xdiff = sum(abs(fx(:) .- oldfx(:))) ./ (bigness^2);
col(:,:,1) = fx;
col(:,:,2) = oldfx - fx;
col(:,:,3) = oldoldfx - fx;
imshow(col);
oldoldfx = oldfx;
oldfx = fx;
fx = x; %min(fx .* 0.5 .+ x, 1);
fprintf("%2.4f instability %c", xdiff, 13);
if(xdiff < (1/bigness))
iter
break;
endif;
sleep(0.75);
endif;
endfor;
toc
sub h2z {
my $s = shift;
$s =~ tr/ !"#$%&'()*+,-.// !"#$%&'()*+,-.\//;
$s =~ tr/0-9:;<=>?@A-Z[\]^/0-9:;<=>?@A-Z[\\]^/;
$s =~ tr/_`a-z{|}〜¢£¬ ̄¦¥₩/_`a-z{|}\~¢£¬¯¦¥₩/;
return $s;
}
$s =~ tr/「」『』()。、・/''""()., /;
# and any of these:
# https://en.wikipedia.org/wiki/Japanese_typographic_symbols