[ / / / / / / / / / / / / / ] [ dir / acme / animu / asmr / leftpol / magali / mde / tacos / vg ]

/tech/ - Technology

Winner of the 53rd Attention-Hungry Games
/d/ - egenerates

August 2018 - 8chan Transparency Report
Comment *
Password (Randomized for file and post deletion; you may also set your own.)
* = required field[▶ Show post options & limits]
Confused? See the FAQ.
Show oekaki applet
(replaces files and can be used instead)

Allowed file types:jpg, jpeg, gif, png, webm, mp4, pdf
Max filesize is 16 MB.
Max image dimensions are 15000 x 15000.
You may upload 3 per post.

File: c9ccb69fcd63be3⋯.png (1.61 MB, 3840x2160, 16:9, programming challenges v4.….png)


What are you working on, /tech/? Don't be shy about asking for help or code review. Keep your posts on-topic, please.

Bash script to pick random number for challenges:

echo $(((RANDOM*145>>15)+1))

Post last edited at


I fugged up the script :DDDDDD

echo $(((RANDOM*145>>15)+1))


File: 873bea224218bea⋯.gif (103.67 KB, 774x1457, 774:1457, ANSICONV.GIF)

Working on a website (and web template language) that uses classic CP437 and can into ANSI art.

Goal is to make a website and a BBS analogue from common source data.


Nothing particular, I'm fucking around with a little project in C to summerize a few things of system programming I apprehended from a recently read manual.


Fixed the OP for ya.







Well, the current TempleBot isn't mine... and I don't really see anything wrong with it.

It was written by a k00l k1d in Erlang, iirc. The commands !gw and !god work fine.



source code where?


Very slow implementation of an encryption algorithm I designed using key dependent operations and block sizes.

This is a PoC ...





This doesn't look secure.



I encrypted https://norvig.com/big.txt with this and then compressed it with xz. The compression ratio is 2. This means the encrypted file isn't random.



Hahaha ... Look secure! How do you know? What's your benchmark?


You apparently have no notions of crypto if xz and compression ratio is the way to check XD

Enthropy is not a reliable metric for security of an algorithm, it's a scam check out the enthropy of broken algorithms. Having patterns doesn't mean they are exploitable. I agree thought, the output won't look random but that's the trick also.

Talk is cheap ... PoC or STFU! Proof of Concept or Shut the Fuck Up. None of you gave any serious cryptanalysis, just typical mumbo-jambo ...

Do you even know what's going on in the code?

Do you even understand the basic principle?

Let me remind you that it is a PoC, not the finished algorithm ... That, I'll keep for myself. Yet, if I provide an encrypted file. There's no way any of you can break it.

Let's be a bit methodical and avoid just talking unless you got viable demonstrations.



>immense asspain

Calm down.

>You apparently have no notions of crypto if xz and compression ratio is the way to check XD

If an encryption algorithm isn't able to produce random looking output, it's broken.

>PoC or STFU! Proof of Concept or Shut the Fuck Up. None of you gave any serious cryptanalysis, just typical mumbo-jambo

Where is your security proof? Where is your design rationale?

>That, I'll keep for myself.

Lol ok. You're either insane or trolling. Either way it's pretty funny.



Even AES can be broken if shitty PRNGs are used during the encryption phase, creating patterns that can be used to derive the secret from encrypted data. Some malware in the wild used to take advantage of predictable "random number generator" of Java and stole Bitcoins from Android devices before. It's nice and dandy to make your own crypto and all that but you will just make yourself look like a moron if you don't have any background knowledge of a topic you seem to spout nonsense about.




It's not funny. So far, you seem to be stuck believing in mathematical principles which you cannot demonstrate.

>...produce random looking output, it's broken.

I see no rationale here. Elaborate on that, am interested. What's randomness? What's entropy?

My security proof is my code and the basic principles behind it.

I'm neither insane, nor am I trolling. Maybe you are.



If predictable then it's not random. There's no such thing as randomness, the true key to security is expiration and update.

Dude, I'm not just a "random" dude that came in here to have fun. Look at the work, not the person. I know VERY WELL what I'm talking about.

I'm looking for really open minds, not people, talent that can see beyind what you've been sold.

Breath, reevaluate & let's talk low level then.

Otherwise, it's all pointless.





top kek. keep it up


I wrote a superior encryption algorithm:

use std::{
io::{BufRead, Write}

fn main() {
let stdin = std::io::stdin();
let mut stdin = stdin.lock();

let stdout = std::io::stdout();
let mut stdout = stdout.lock();

// replace with secret key
let mut key: u128 = 0xdeadbeef;

loop {
let len = {
let buf = stdin.fill_buf().unwrap();

if buf.len() == 0 {

for b in buf {
key = key.wrapping_mul(0x12e15e35b500f16e2e714eb2b37916a5);
stdout.write_all(&[b ^ (key >> 120) as u8]).unwrap();


Try to break it. Protip: you can't



I'm not ineterested in securing bitcoin transactions or any of the known BS in nature. That's just rubbish to me. The tech is CRAP, made for profit. Privacy and mindful evolution are my goals!!

Back in the days of the cold war, crypto was done in plain sight through news paper articles. No randomness, just key words from a meaninful set (the article) if arranged in sequence by a person with knowledge of the "key/sequence" communication is established.

That's elegant to my mind. And that's the spirit.

With regard to randomness, if you're weathered enough, you can hijack function calls to crypto primitives (i.e. ptrace & LD_PRELOAD). Another way, you can patch the binary of the crypto software and corrupt the output registers with values seemingly random but coming from a test pool you already know how to break (a bit like feeding a loopback feed to a monitor surveillance system).

I got some other techniques up my sleeve, maybe they'll come out in a discussion at some point.



First mistake: superior.

Do the work, and let the public decide. Don't jump to conclusions yet.



>I got some other techniques up my sleeve, maybe they'll come out in a discussion at some point.

Oh shit. Are you the NSA?


Talk is cheap ... PoC or STFU! Proof of Concept or Shut the Fuck Up. None of you gave any serious cryptanalysis, just typical mumbo-jambo ...

Do you even know what's going on in the code?

Do you even understand the basic principle?

Let me remind you that it is a PoC, not the finished algorithm ... That, I'll keep for myself. Yet, if I provide an encrypted file. There's no way any of you can break it.

Let's be a bit methodical and avoid just talking unless you got viable demonstrations.


File: 384648c2e1203d8⋯.png (2.76 MB, 2548x2548, 1:1, unencrypted.png)

File: 12bd56583f320fd⋯.png (9.82 MB, 2548x2548, 1:1, encrypted.png)


I've visualized your shitty "encryption" algorithm. Looks shit to me.



XD ... You're so irritated and unwilling to go an extra mile and understand the code wanting to prove everybody wrong not even realizing how childish you sound. Your code is stupid. The key operations are known at any point in time: ^, >>. Look closely at my code, check the block size also.

In response to your response by my response: "never give a weapon to an irresponsible person".

Also, replying with a code doesn't validate any of your positions. It shows inexperience in dealing with lower than the surface subjects.



"Looks" isn't an argument. You have no idea of inner workings, you're just talking. What does the code do ... ?



>The key operations are known at any point in time

Oh shit. The key operations for AES/ChaCha20/Keccak are also known at any point in time. All broken by some anon. Impressive.


File: dbccd38d719f5fc⋯.png (9.82 MB, 2548x2548, 1:1, c.png)


You can clearly see the bias in the encrypted output. Pic related is the output of my superior algorithm.



Those algorithms are not part of this discussion. Their sources are obscure, you mentionned one previously.

You still haven't answered any of my valid questionWhat's randomness? What's entropy? What's my code doing?

Superior ... Let's get serious shall we? Enough BS, you're a sheep and you don't even know it.





>You still haven't answered any of my valid question

You still haven't provided a security proof nor a design rationale.

>What's my code doing?

Producing hot garbage by the looks of >>944958

>you're a sheep and you don't even know it.

you're insane and you don't even know it

>muh backdoors

great argument



As I stated before, "READ THE CODE" that's my rationale. I see no anwser from your side though.

"Looks like gabage" isn't an argument when talking about matters such as crypto. See this as an argumentation exercise, it'll sharpen your skills.

What's sanity, how did you learn to put words together to make meaning?



top kek. btw

>reddit spacing



Don't get lost in BS ... concentrate with me and let it resonate, follow the path otherwise you'll roam around like a gold fish ...




Fallacious !


Nothing else to add. Seems like madness is rule in here! :)



You still haven't broken my superior cipher: >>944945



Go to sleep ... You're tired.



I'm a NEET with a fucked up sleeping schedule. I'm constantly tired.



That explains why your neurons are incapable of going beyond a lazy Rust ego construct full of arrogance. Wrap your mind around that.


File: 12bd56583f320fd⋯.png (9.82 MB, 2548x2548, 1:1, 12bd56583f320fdb3c1e50eded….png)


>this is what a secure cipher looks like




Your eyes seem to be enough ... Dig a bit deeper than just looks. Not an argument, you're full of it. Uncapable of proving nothing. Stuck in your little self assertions ... Evolve mortal being, you're not great, greatness isn't for earthlings, you simply exist and you were told how.

If such a picture makes sense to you, it only reflects the state of your mind dear fellow. A random looking cypher which you'll never be able to solve, the riddle of life, the first thread!


File: 57a47b42d89d158⋯.jpg (48.94 KB, 634x566, 317:283, unencrypted.jpg)

File: fbc017cc3d44649⋯.png (316.61 KB, 634x566, 317:283, encrypted.png)





Requesting source code for generating those PNG's, friend, for humanity's knowledge increase.


What algo is that?



see >>944945

He's probably just putting the raw image (as in rgb values) through it.

>What algo is that?

My guess is something that uses AES.


>Requesting source code for generating those PNG's, friend, for humanity's knowledge increase.

I converted the image to raw RGB using ImageMagick , "encrypted" it using this algorithm >>944836 and then converted the "encrypted" RGB file back to a PNG.

convert image.png image.rgb
encrypt image.rgb
convert -size widthxheight -depth 8 image.rgb image.png
>What algo is that?

This one >>944945. It's a Lehmer RNG. Obviously not cryptographically secure but still better than this dumpster fire >>944836



You have no idea what the code does and you have no arguments. Your skills are so below the belt, you compare Lehmer to something you know nothing about.

I mean, WOW!

Again, what's entropy? What's randomness? What's my algorithm doing?

You got two years to learn to talk and the rest of life to learn silence dear fellow.

Quit the BS and focus!



Your "encryption" algorithm fails at encrypting. >>945039

>you compare Lehmer to something you know nothing about

I'm mocking you. Seek help.




You're mocking yourself and behaving like an idiot.

Being mean and irrational for the sake of your ego.

This could've been a fruitful discussion, you turned it into a shit show. You're a circus "animal" ... You like entertainment and you're unable to go to the core of anything. Living on the surface unaware of the layers.



Just look at those images >>945039

The encrypted.png is "encrypted" using your program. Notice how you can discern the original image. Explain that.



An image is not an argument. How would you attack the algorithm, not the output data?

Yes there's a pattern, that doesn't say it's revelatory of anything that can help retrieve the key or the clear text. Random looking output is not a measure of security. Knowing how something looks doesn't tell you what it is in crypto.


File: f8c6f56c55439d4⋯.png (404.87 KB, 500x534, 250:267, not an argument.png)


>not an argument


>How would you attack the algorithm

I don't need to because it fails at encrypting. You can still see the nigger crying. You can still read the text.



You're repeating yourself, can't get beyond a fallacious argument and pictographic non-proofs.

Poor you ...



You see those dark bars on the top? It is a sign that the encryption is having weak states.



How do you define a weak state?

Do a real full analysis and quit goofing ... You're wasting valuable life time and breatable air.

Point at a weakness in the algorithm not just random abstract concepts you interpret from a picture.


I created a superior encryption tool. Here's a JS implementation:


Registered it with BIS & emailed a copy to NSA as required per US export laws.

COINTELPRO tried to ruin my life.

Study it if you want to improve your crypto capabilities. It's quantum computer proof.



Let's not get carried away with all that BS about quantum and mouse movement non sense.

Channel your energy to analyze what I did better rather than waste it on BS.

You have no knowledge of my crypto abilities nor are you aware of your own limitations.



> what's entropy? What's randomness?

Surely you jest. Randomness is the lack of predictable pattern. Entropy in information theory is the tendency for structure to break down over time, for patterns to degrade.

>What's my algorithm doing?

I haven't looked at it, but why don't you tell us what it's doing and why? Then perhaps we can suggest improvements to fix it?



I'm not seeking help nor a fix, rather collaboration on some basic principles exhibited in the code.

I will not explain for a simple reason: read, use the mind and let's be methodical. No hands holding, I am not seeking children !!!

Am seeking analytic minds to see beyond, understand by themselves and exchange lucidly with valuable insight free from the shackles of century old concepts.

Ok for randomness. Does randomness exist and how can you establish that?

Entopy is a metric not a tendency but you're close. Why does it matter for the security of an algorithm? Why are patterns so problematic?


File: 6079db5409dddfa⋯.mp4 (11.98 MB, 292x500, 73:125, encrypted.mp4)


>pictographic non-proofs

I "encrypted" the video stream. Truly amazing. You have dethroned AES.



>BS about quantum

My algorithm uses the property of unknown state, it throws away a large chunk of state and only uses a 1 way cipher to perform 2 way encryption via cyclic block chaining.

Also, each block of input data accumulates more entropy in the running state buffer thus optionally becoming "Authenticated Encryption" if a final null block is processed.

RSA and most other stream ciphers are theoretically reversible via quantum computer. Imagine a quantum computer whereby each input bit could be 1, 0, or a superposition of 1 and 0. The operations done on the bits create an entanglement.

If you feed in 1's and 0's to the algo implemented on such a quantum computer then you get 1's and 0's out.

If you feed in all superpositions for a block of a cipher algorithm, then you get qubits with complex entangled superpositions. Then you can take a known ciphered output and begin collapsing those output superpositions, this will cause a chain reaction and reveal what 1's and 0's were fed into most stream cipher algorithms, like RSA.

My algorithm deliberately generates a large block of intermediary state then throws much of that state away. The smaller block size of data that is combined with the plaintext depends on unknown values that have been thrown away. The next input plaintext block is 'hashed' with all prior plaintext blocks and the key which was stretched and obfuscated via hashed message authentication (HMAC), this output becomes the next block of cipher data. A simple substitution cipher is then applied to the output of the cipherblock in order to ensure chosen plaintext attacks are not possible without foreknowledge of the key. Even if you knew what the plaintext was at a given position you could not reverse the value of the cipherblock due to the substitution cipher. This ensures the following and prior blocks remain secure even if a portion of data at an offset is known.

Because much internal state is thrown away each block (and much is also kept), a quantum computer can not be used to reverse the cipher. Faced with a large batch of "unknown" state each round of the cipher to guess at, the quantum computer can not collapse the superposition structure of the qubits and thus can not be used to break this cipher.

It's quantum computer proof.

The moving of the mouse is just there because Javascript provides no good source of randomness with which to create strong initialization vectors. So, we rely on the user.


you're being an ass. You don't know what your code does, and can't explain why it is secure.




I'm not an ass!! You're too emotional.

My code has no value, what's beyond the code?

I never claimed it is secure I asked what's wrong technically and where?



>I asked what's wrong technically and where?

Read the thread, nigger: >>944852 >>944958 >>945039 >>945225


Refresh ...





I made no claims.



> what's beyond the code?

Either ignorance, or you're a PSYOP to see how competent 8ch /tech/ is at crypto.

Here is your init function:

void init(unsigned char *restrict key, unsigned keylen)
//Randomize with key
for (unsigned i = 0; i < MAX_KEY_LEN; i++)
K[0][i] ^= key[i % keylen];
K[1][i] ^= key[i % keylen];

//Flip key bits and rot - this is the new key
for (unsigned i = 0; i < keylen; i++)
key[i] = rotl(~key[i], K[key[i] % 2][i]);

This mutates a key using two 128 byte (MAX_KEY_LEN) pre initalized buffers.

First, please explain why we should trust your chosen magic values for the contents of those K[1] and K[2] arrays. No one will use crypto that has such unexplained magic numbers on the off chance you've selected the init vars to create some form of backdoor.

Secondly, if you supply a small key, you get a small key back out. Instead you should employ key expansion to generate a larger standard key size from a small key. Additionally, you should perform many iterations of the key expansion (this is called key stretching) which when properly implemented greatly increases the difficulty to crack a key without significantly impacting stream cipher performance.

Finally, you have this little doosy in the code above:

key[i] = rotl(~key[i], K[key[i] % 2][i]);

A big no-no having that modulus 2 to switch banks of the 128 byte buffer. You've created a side-channel attack to leak the key depending on the key directly to access two MAX_KEY_LEN sized buffers.

That's just init()... The rest is equally trash, and isn't worth my time to tear down. It's clear you don't know jack about crypto. Best practices aren't just there because some fools are obsessed with "randomness" or "mathematics", we cryptographers are concerned about preventing known exploit vectors in our code.

Perhaps you should revise your stance on taking advice from children. I wrote better crypto than this when I was 12. Good luck.



Now you're talking sense. You're still twelve though, it's all personal for you.

It's not a stream cypher ... Look closely and avoid the emotional point of view. Remain methodical dear fellow. You're not wasting your time ...

Well, I agree on constants but I can assure you that's just for PoC reasons (similar to Blowfish's Pi or the ECC NSA BS).


File: 663152a8fbd3aa0⋯.png (1.15 MB, 850x567, 850:567, encrypted.png)


>Look closely and avoid the emotional point of view. Remain methodical dear fellow. You're not wasting your time ...

Yes. Look closely. I think I can see a shirtless Alex Jones. But it is encrypted. How can I discern that???????

It is a mystery.



Simple initiation to "magic numbers": https://github.com/yaspr/Encryption-Protocol-0

Another one: https://github.com/yaspr/lp0

A sort of example of what's not to do and how to break it.



Try text, artifacts are not that easy to spot though. Images are a whole other dimension given that it is encoding a signal ... Plus, I never claimed it is as secure, more secure or even secure. I just posted a code.

Keep analyzing the mechanics and forget about what you already know. Just look, structure over details.


File: bcd2cf828c399c8⋯.png (516.02 KB, 601x569, 601:569, encrypted.png)


Amazing. I can barely read it. This is truly the peak of encryption. I hope the CIA niggers don't suicide you for creating this unbreakable encryption algorithm.



Unbreakable? Why are you trying to prove a pointless point. I said look beyond the 12 year old.

Kegel exercises are powerful for a healthy equipment.



>he still unironically believes that he has created an """"""""""encryption"""""""""" algorithm




Just recognize that your implementation is a failure. Learn from your mistakes implement a better algorithm. The one you have created is worthless, and serves no purpose.



You can't see further than your nose. I do not believe anything not am I claiming anything. I'm waiting for something you do not seem to understand given that your are stuck in old fashion paradigms.


File: fde51fbddc0141c⋯.png (5.73 MB, 1920x1080, 16:9, encrypted.png)



You must feel smart with your newspeak. poor fellow. Nothing substancial as of yet. Stop wasting your energy on personal BS.


File: 6725a5ca5fb4bef⋯.png (766.53 KB, 600x439, 600:439, encrypted.png)



Childish as fuck XS


File: 65d61e546dd8314⋯.png (1.41 MB, 1920x1080, 16:9, encrypted.png)



Nicely underlined, but it's the word before that is key in here: CYCLES :]



>You've created a side-channel attack to leak the key depending on the key directly to access two MAX_KEY_LEN sized buffers.

Not him, but can you explain what the problem is here? The pastebin was removed so I lost the context for it.




Let me know what you see, I'm interested.


What the fuck is going on here? Is this some advanced trolling or a genuine pajeet lolcow?


File: 9988e0d2039f5ac⋯.jpg (40.97 KB, 786x537, 262:179, 1526762143866.jpg)


i congratulate you my friend,becasue you are

officialy toasting in epic bread.





tr 'a-zA-Z' 'n-za-mN-ZA-M




For once, a ray of truth. Wrong questions indeed.

The code is a PoC for an attack, the crypto algorithm isn't it, it's just a target : rdtsc & L3 cache.


No pajeet here ... Get out of that mindset and look deeper.


File: 8afa10e767dac2b⋯.png (527.22 KB, 449x401, 449:401, encrypted.png)


>he has updated his "encryption" algorithm



WTF is wrong with you? It's not the encryption that's at stake here, it's its operations. Trying to see if what I found stays even after changes.

You only look at the crypto, you're at the surface dear fellow.


File: 603f341fa453b35⋯.png (84.87 KB, 327x300, 109:100, felix_thonk.png)

>this thread

I can't work out who is trolling who here


File: abddcc8e59263d5⋯.png (154.33 KB, 327x300, 109:100, encrypted.png)


I'm not trolling


kkk roll


CIA roll



Did you even objdump the thing? I mean you're a circus entertainment ...


File: 016d6f2acce8638⋯.png (1.03 MB, 900x560, 45:28, encrypted.png)



My heart's with you dear fellow. I trully wish for you to wake up from your sleep and look. It's all up to you and your fallacious ego.


File: aa9dfacd7b24e9a⋯.jpg (184.57 KB, 864x1024, 27:32, lisp_theory_and_practice.jpg)

>What are you working on, /tech/?

I'm working on a small s-expression toolkit for Python and micro-package for

compling s-expressions into Python functions.

>Don't be shy about asking for help or code review

Cool. If anyone wants to point our some code smells or suggest improvements, I would be obliged. Thanks.

>https://github.com/IwoHerka/sexpr - Toolkit

>https://github.com/IwoHerka/auk - Compiler

(I will be reposting this from time to time as traffic on 8ch is quite low)


File: c951c89df23d1f4⋯.jpg (324.22 KB, 1261x1000, 1261:1000, n00bz.jpg)

>the challen/g/es are too hard for /tech/



kkk roll



Dude take a look at this:


256-bit quantum secure crypto. It can't get better than this. Prove me wrong.



Good for you dude. How is it relevant if it is executed on a shitty CPU ... You can write the best algorithm you want if the basic operations aren't secure at the hardware level, if there's any leakage, you're fucked!

Your algorithm is great, mine is shit but once implemented I can fuck over any of them given that hardware memory will leak ... the actual architectures are shit, and the actual state of physics which allows us to burn those architectures down on a wafer cannot prevent leakages (capacitors & refresh).

What to do about that?



>What to do about that?

either become the next hitler or kill self






nervous roll


int main()
vector<int>v = {5,6,9,4,6,8};
return 0;

[Error] in C++98 'v' must be initialized by constructor, not by '{...}'

[Error] could not convert '{5, 6, 9, 4, 6, 8}' from '<brace-enclosed initializer list>' to 'Vector<int>'

Could someone explain this?

I tried adding -std=c++11 and -std=c++0x to compiler options but it still gives the second error message. I took the line directly from "Programming: Principles and practice using c++"



Get a better compiler anon it werks for me. Anyway here's a real gay... uh I mean cool way to get your shit working.

int main()
int arr[] = {5,6,9,4,6,8};
vector<int>v (arr, arr+sizeof(arr)/sizeof(arr[0]));
return 0;

Also learning c++ from a book is like learning python or java from a book.


Coding a video game.

But since I also want to try something related to animation in the long term, I'm currently coding the engine using C++/OpenGL/GLSL, it's going slowly but it's working fine so far.

Last update was moments ago, about memory management and dynamically adding new object, and looping through animation calculation per model type then sending that to the GPU

Need to fix when sending multiple position data, only the first object uses said data but it should be more about some OpenGL configuration.


I coded something in MATLAB and ran it while away and came back to find it ran out of memory on my 16GB machine. It was using parfor to get parallelized instances in order to speed things up, but that meant multiplying many of the matrices in for each thread, hence the memory issue.

I could probably reduce memory consumption if I used something where I can manage the memory myself, or in which an extra for loop (instead of the vectorized MATLAB notation) isn't as costly as it is in MATLAB.

I'm thinking of implementing this thing in C++ using the Eigen template library. Any better ideas/languages/libraries?

Maybe I should just refactor my MATLAB code so it generates fewer transformations of the entire dataset, and just do it one row at a time? This is my plan on how I could do it well with C++, and the extra required for loop wouldn't be so costly.






Here we go. There are 5 commands.

new: Creates a new canvas

quit: Exits the program

help: Displays help

plot x y c: Plots character c at the point x y

save filename: Saves your canvas in filename

load filename: Loads your canvas from filename

module Paint where

import Data.Array
import Data.Foldable
import Data.List
import Data.List.Split
import System.Exit
import Text.Parsec

data Resolution = Resolution { width :: Int
, height :: Int
} deriving Show

data Canvas = Canvas { dimensions :: Resolution
, pixels :: Array (Int, Int) Char

instance Show Canvas where
show (Canvas dimensions pixels) = (intercalate "\n" . chunksOf (width dimensions) . toList) pixels

data Command = New | Quit | Help | Plot {x :: Int, y :: Int, c :: Char} | Save {filename :: String} | Load {filename :: String}
deriving Show

main :: IO ()
main = do
resolution <- getResolution
mainLoop $ createCanvas resolution

mainLoop :: Canvas -> IO ()
mainLoop canvas = do
print canvas
line <- getLine
case parse command "" line of
Left error -> putStrLn "Invalid Command"
Right x -> case x of
New -> main
Quit -> exitSuccess
Help -> printHelp
Plot x y c ->
case plotCanvas canvas x y c of
Left error -> putStrLn error
Right plotted -> mainLoop plotted
Save filename -> do
saveCanvas filename canvas
putStrLn "Saved"
Load filename -> do
loaded <- loadCanvas filename
putStrLn "Load"
mainLoop loaded
mainLoop canvas

printHelp :: IO ()
printHelp = do
putStrLn "Commands"
putStrLn "===================="
putStrLn "new: Creates a new canvas"
putStrLn "quit: Exits the program"
putStrLn "help: Displays help"
putStrLn "plot x y c: Plots character c at the point x, y"
putStrLn "save filename: Saves your canvas in filename"
putStrLn "load filename: Loads your canvas from filename"
putStrLn "===================="

plotCanvas :: Canvas -> Int -> Int -> Char -> Either String Canvas
plotCanvas canvas x y c
| x < 1 || y < 1 || x > (width . dimensions) canvas || y > (height . dimensions) canvas = Left "Invalid Location"
| otherwise = Right $ Canvas (dimensions canvas) (pixels canvas // [(((height . dimensions) canvas - y + 1, x), c)])

saveCanvas :: String -> Canvas -> IO ()
saveCanvas filename canvas = writeFile filename (show canvas ++ "\n")

loadCanvas :: String -> IO Canvas
loadCanvas filename = do
raw <- readFile filename
let height = length $ elemIndices '\n' raw in
let width = (length raw - height) `div` height in
let as = [((y, x), raw !! ((x - 1) + ((y - 1) * (width + 1)))) | x <- [1..width], y <- [1..height]] in
return $ Canvas (Resolution width height) (array ((1, 1), (height, width)) as)

getResolution :: IO Resolution
getResolution = do
putStrLn "How big do you want your canvas?"
input <- getLine
case parse resolution "" input of
Left error -> getResolution
Right x -> return x

createCanvas :: Resolution -> Canvas
createCanvas resolution =
Canvas resolution (array ((1, 1), (height resolution, width resolution)) [((y, x), ' ') | x <- [1..(width resolution)], y <- [1..(height resolution)]])

command = new <|> quit <|> help <|> plot <|> save <|> load
new = do
string "new"
return New
quit = do
string "quit"
return Quit
help = do
string "help"
return Help
plot = do
string "plot"
many1 space
x <- number
many1 space
y <- number
many1 space
c <- anyChar
return $ Plot (read x) (read y) c
save = do
string "save"
many1 space
saveFile <- many alphaNum
return $ Save saveFile
load = do
string "load"
many1 space
loadFile <- many alphaNum
return $ Load loadFile

resolution = do
width <- number
many space
char 'x'
many space
height <- number
return $ Resolution (read width) (read height)
number = (:) <$> (char '1' <|> char '2' <|> char '3' <|> char '4' <|> char '5' <|> char '6' <|> char '6' <|> char '7' <|> char '8' <|> char '9') <*> many digit
The challenges from the OP seem to be very time consuming.

Rolling for >>945830



Really simple rogue like. You just need to navigate out of a single room.

module Rogue where

import System.Console.ANSI

newtype Player = Player {location :: (Int, Int)}
deriving Show

main :: IO ()
main = mainLoop $ Player (4, 4)

mainLoop player
| checkWin player = do
putStrLn "You made it out alive!"
putStrLn "Game Over"
| otherwise = do
drawPlayer player
line <- getLine
case line of
"w" -> mainLoop $ movePlayer player 0 (-1)
"s" -> mainLoop $ movePlayer player 0 1
"a" -> mainLoop $ movePlayer player (-1) 0
"d" -> mainLoop $ movePlayer player 1 0
_ -> mainLoop player

checkWin :: Player -> Bool
checkWin player = (fst . location) player == 4 && (snd . location) player == 0

printScreen :: IO ()
printScreen = do
setCursorPosition 0 0
putStrLn "#### ####"
putStr $ unlines $ replicate 7 "#.......#"
putStrLn "#########"

drawPlayer :: Player -> IO ()
drawPlayer player = do
setCursorPosition ((snd . location) player) ((fst . location) player)
putStr "@"
setCursorPosition 9 0

movePlayer :: Player -> Int -> Int -> Player
movePlayer player dx dy
| collisionAt newX newY = player
| otherwise = Player (newX, newY)
where newX = (fst . location) player + dx
newY = (snd . location) player + dy

collisionAt :: Int -> Int -> Bool
collisionAt x y = not (x == 4 && y == 0) && (x == 0 || y == 0 || x == 8 || y == 8)

Roll >>945830



Finished the assembler part of the challege. Tomorrow I'll make it acually evaluate the machine code.



hey thanks, what compiler do you use?


Is Codecademy useful as a free service? Starting with Javascript lessons to see if this coding thing's for me and to bolster my resume.



gcc although it seems a lot of people use clang for c++ now.



Part 1

module LMC where

import Control.Monad.State
import Data.List
import Data.Maybe
import Data.Vector hiding ((++), elemIndex, find, head, tail)
import Text.Parsec hiding (Line, State, label)

data Line = Line { label :: String
, rawInstruction :: String
, rawValue :: String
} deriving (Show, Eq)
data ParsedLine = ParsedLine { instruction :: String
, value :: String
} deriving Show

data Instruction = INP
| LDA {x :: Int}
| STA {x :: Int}
| ADD {x :: Int}
| SUB {x :: Int}
| BRA {x :: Int}
| BRZ {x :: Int}
| BRP {x :: Int}
| DAT {x :: Int}
deriving Show

class Assemble a where
assemble :: a -> Int

instance Assemble Instruction where
assemble INP = 901
assemble OUT = 902
assemble HLT = 000
assemble (LDA x) = 500 + x
assemble (STA x) = 300 + x
assemble (ADD x) = 100 + x
assemble (SUB x) = 200 + x
assemble (BRA x) = 600 + x
assemble (BRZ x) = 700 + x
assemble (BRP x) = 800 + x
assemble (DAT x) = x

class Disassemble a where
disassemble :: Int -> a

instance Disassemble Instruction where
disassemble 901 = INP
disassemble 902 = OUT
disassemble 000 = HLT
disassemble x = case div x 100 of
5 -> LDA $ rem x 100
3 -> STA $ rem x 100
1 -> ADD $ rem x 100
2 -> SUB $ rem x 100
6 -> BRA $ rem x 100
7 -> BRZ $ rem x 100
8 -> BRP $ rem x 100
_ -> DAT x

main :: IO ()
main = do
program <- readFile "program"
input <- readFile "input"
case assembleProgram program of
Left error -> do
putStrLn "Error parsing program file"
print error
Right machineCode ->
case parse listP "" input of
Left error -> do
putStrLn "Error parsing input file"
print error
Right inputList -> print $ evaluateProgram machineCode inputList

assembleProgram :: String -> Either ParseError [Int]
assembleProgram program = case parse programP "" program of
Left error -> Left error
Right lines -> Right $ assembleInstructions $ convertToInstructions $ removeLabels lines

evaluateProgram :: [Int] -> [Int] -> [Int]
evaluateProgram machineCode input = evalState evaluate (0, 0, fromListN 100 (machineCode ++ repeat 0), input ++ repeat 0, [], False)

evaluate :: State (Int, Int, Vector Int, [Int], [Int], Bool) [Int]
evaluate = do
(pc, acc, memory, input, output, branched) <- get
if pc < 100
then do
case disassemble $ memory ! pc of
INP -> put (pc + 1, head input, memory, tail input, output, False)
OUT -> put (pc + 1, acc, memory, input, output ++ [acc], False)
HLT -> put (100, acc, memory, input, output, False)
LDA x -> put (pc + 1, memory ! x, memory, input, output, False)
STA x -> put (pc + 1, acc, memory // [(x, acc)], input, output, False)
ADD x -> put (pc + 1, acc + x, memory, input, output, False)
SUB x -> put (pc + 1, acc - x, memory, input, output, False)
BRA x -> put (x, acc, memory, input, output, True)
BRZ x -> put (if acc == 0 || branched then x else pc + 1, acc, memory, input, output, True)
BRP x -> put (if acc >= 0 || branched then x else pc + 1, acc, memory, input, output, True)
DAT x -> put (pc + 1, acc, memory, input, output, False)
else return output

removeLabels :: [Line] -> [ParsedLine]
removeLabels lines =
fmap (\line -> ParsedLine (rawInstruction line) (fromMaybe "" (resolveValue (rawValue line) lines))) lines

resolveValue :: String -> [Line] -> Maybe String
resolveValue value lines =
case parse constantP "" value of
Left error -> case find (\list -> label list == value) lines of
Just line -> show <$> elemIndex line lines
Nothing -> Nothing
Right constant -> Just constant

convertToInstructions :: [ParsedLine] -> [Instruction]
convertToInstructions = fmap convertToInstruction

convertToInstruction :: ParsedLine -> Instruction
convertToInstruction line =
case parse instructionP "" (instruction line ++ value line) of
Left error -> HLT
Right instruction -> instruction

assembleInstructions :: [Instruction] -> [Int]
assembleInstructions = fmap assemble



Part 2

listP = do
numbers <- between (char '[') (char ']') numbersP <|> numbersP
return numbers
numbersP = sepBy numberP (try (string ", ") <|> try (string ",") <|> try (string " "))
numberP = read <$> constantP

programP = many lineP
lineP = do
line <- try line1 <|> try line2 <|> try line3 <|> try line4
optional $ char ' '
optional commentP
many1 newline
return line
line1 = do
instruction <- instruction0
return $ Line "" instruction ""
line2 = do
label <- labelP
char ' '
line <- line1
return $ Line label (rawInstruction line) ""
line3 = do
instruction <- instruction1
char ' '
value <- valueP
return $ Line "" instruction value
line4 = do
label <- labelP
char ' '
line <- line3
return $ Line label (rawInstruction line) (rawValue line)
instruction0 = try (string "INP")
<|> try (string "OUT")
<|> try (string "HLT")
instruction1 = try (string "LDA")
<|> try (string "STA")
<|> try (string "ADD")
<|> try (string "SUB")
<|> try (string "BRA")
<|> try (string "BRZ")
<|> try (string "BRP")
<|> try (string "DAT")
labelP = (return <$> letter) <> many alphaNum
valueP = labelP <|> constantP
constantP = many1 digit
commentP = string "//" <> many (alphaNum <|> char ' ')

instructionP = try inpP
<|> try outP
<|> try hltP
<|> try ldaP
<|> try staP
<|> try addP
<|> try subP
<|> try braP
<|> try brzP
<|> try brpP
<|> try datP
inpP = do
string "INP"
return INP
outP = do
string "OUT"
return OUT
hltP = do
string "HLT"
return HLT
ldaP = do
string "LDA"
value <- constantP
return $ LDA (read value)
staP = do
string "STA"
value <- constantP
return $ STA (read value)
addP = do
string "ADD"
value <- constantP
return $ ADD (read value)
subP = do
string "SUB"
value <- constantP
return $ SUB (read value)
braP = do
string "BRA"
value <- constantP
return $ BRA (read value)
brzP = do
string "BRZ"
value <- constantP
return $ BRZ (read value)
brpP = do
string "BRP"
value <- constantP
return $ BRP (read value)
datP = do
string "DAT"
value <- option "0" constantP
return $ DAT (read value)
It reads the program from a file called program. It reads the input from a file called input. It prints the output to stdout.

Example program

STA length
loopStart INP
LDA length
STA length
BRP loopStart

length DAT 0
Example input
5, 1, 2, 3, 4, 5
Output for example above

Roll >>945830



Going to end on an easy one.

module Tree where

main :: IO ()
main = do
putStrLn "How big would you like your tree?"
size <- getLine
putStr $ tree $ read size

tree :: Int -> String
tree n =concatMap (line n) [1..n]

line :: Int -> Int -> String
line n m = (replicate ((n `div` 2) - (nearestEven m - 1) `div` 2) ' ') ++ "/" ++ (replicate (nearestEven m) ' ') ++ "\\\n"

nearestEven :: Int -> Int
nearestEven n = n - (n `rem` 2)





File: 257554ebf187588⋯.jpg (41.09 KB, 496x311, 496:311, McCarthy.jpg)


Write a function FIRSTZERO that takes a list of three numbers as input and returns a word (one of ‘‘first,’’ ‘‘second,’’ ‘‘third,’’ or ‘‘none’’) indicating where the first zero appears in the list. Example: (FIRSTZERO ’(3 0 4)) should return SECOND. What happens if you try to call FIRSTZERO with three separate numbers instead of a list of three numbers, as in (FIRSTZERO 3 0 4)?

attempted solution

why doesn't it work? why is the variable void? it is declared in defun

(defun firstzero (x y z)

(cond ((equal 0 x) 'first)

((equal 0 y) 'second)

((equal 0 z) 'third)

(t 'nope))

answer in book

(defun firstzero (x)

(cond ((zerop (first x)) ’first)

((zerop (second x)) ’second)

((zerop (third x)) ’third)

(t ’none)))

Calling FIRSTZERO with three separate numbers as input, instead of one list of three numbers, would cause a wrong number of inputs error.



and yes, I know my solution deviated from what the question asked. It's posted here as a curiosity, I ended up arriving at a solution similar to the one in the book, but could not grasp why my attempted solution wouldn't work and why the variables were void.



A list is only one variable.



I know, and I know that I deviated with that attempted solution. But if the function takes 3 variables, as my firstzero does, why are the variables void?



>I know,

*disclaimer: I probably don't



(firstzero 3 0 4) gives me second. Are you getting something else?




My firstzero? this one:

(defun firstzero (x y z)

(cond ((equal 0 x) 'first)

((equal 0 y) 'second)

((equal 0 z) 'third)

(t 'nope))

Because if so, I get an error message when executing this function: (void variable x) in (equal 0 x)




It's kind of a recurring problem I'm having too, it's not just this function. I'm using common lisp, btw.



Yes it works for me apart from a missing paren.


Yeah you need to restart the repl. After a while it can get messed up.



I was actually working within an emacs org mode document, using cntrl-x-e to execute the code locally (if that makes sense). But I'll keep that in mind next time I'm in the repl.

>missing paren

I think this was it, I added a paren at the very end and I think it's fine now. I'm still having some residual issues with a couple other sticky functions, maybe it's the same issue. Thanks!



ok, yeah, just fucked up parens. thanks guys


Someone toss me that shitty code from that sim game that xephaloneva I think?? The one with a shit ton of nesting

Also, I know the game is a meme but someone please explain this shit to me? Never actually paid attention but I need to wean my cousin off of it yes. my cousin is an irl neet Doesn't help that his only friend is textbook tsundere



how about you kill yourself?



File: a45b25cc96f2065⋯.jpg (34.99 KB, 596x596, 1:1, 1532265460033.jpg)


custom algorithmic stock trading platform in python

feedback welcome



How the hell do you not have show-paren enabled? Install smartparen, you dolt.



assembleProgram :: String -> Either ParseError [Int]
assembleProgram program = case parse programP "" program of
Left error -> Left error
Right lines -> Right $ assembleInstructions $ convertToInstructions $ removeLabels lines

You can eliminate the case structure here, since you're returning Either.



#include "share/atspre_staload.hats"
#include "share/atspre_staload_libats_ML.hats"

extern fn replicate: (int, char) -> string = "mac#"

char *replicate(int len, char c) {
char *s = ATS_MALLOC(len+1);
for (int i = 0; i < len; i++)
s[i] = c;
s[len] = '\0';
return s;

fn nearest_even(n: int): int = n - $UNSAFE.cast{int}($UNSAFE.cast{uint}(n) land 1u)

fn line(i: int, width: int): string =
stringlst_concat(g0ofg1($list{string}(left, "/", mid, "\\\n"))) where {
val i = nearest_even(i)
val left = replicate(width/2 - i/2, ' ')
val mid = replicate(i, ' ')

fn tree(size: int): string = stringlst_concat(loop(size, size, list0_nil())) where {
fun loop(i: int, width: int, acc: list0(string)): list0(string) =
if i > 0 then loop(i-1, width, list0_cons(line(i, width), acc)) else

implement main(argc, argv) =
case+ argc of
| 2 => (print!(tree(g0string2int(argv[1]))); 0)
| _ => (fprintln!(stderr_ref, "usage: ", argv[0], " <size of tree>"); 1)



>You can eliminate the case structure here, since you're returning Either.

I don't quite understand what you mean here. The either returned from parse is an Either ParseError [Line] and I'm returning an Either ParseError [Int]. Are you saying there is some way for me to overwrites the right side of the either that's being returned?



how would you "overwrite the right side of" an IO Line to get an IO Int? How would you "overwrite the middle" of a [Line] to get an [Int] ?

you could write a loop that explicitly iterates over each element of the [Line] to apply some code to it, building up an [Int] as you go. which is essentially what you're doing with the Either here.



I mean that you're working in the Either monad with the same Left type, so you can just let >>= take care of the error checks.

assembleProgram program = do
lines <- parse programP "" program
return $ assembleInstructions $ convertToInstructions $ removeLabels lines

To your question, yes, Either is a functor on its Right side, so you can just fmap it. In this case, you could use the infix fmap operator to do something like

assembleProgram program =
assembleInstructions . covertToInstructions . removeLabels <$> parse programP "" program

I'm not positive that's right, consult with your typechecker. And whether it's more or less clear is up to you.


File: 98ee5c04303d05c⋯.gif (1000.63 KB, 350x196, 25:14, 1387295659348.gif)

I am retarded and require a little spoonfeeding.

How exactly does one learn to write bindings for something like QT in another language, let's say C? I figure if I can bind C++ to C, than another language will be the next step. I'm reading the QT documentation and feeling like a retard.


What do you guys think about some addon/bot that gets info from a site's source and shows a short description (mouse rover?), like:

File: html

Charset: utf-8

inline-script: yes

Third-party script: yes

Third-party CSS: no

It could be a userscript, or terminal-based, i dunno.



lol lisp



Most languages have some sort of C ffi.



it's a C++ FFI that he needs.

which is a thing that doesn't exist.



Well, there is the whole C API, but I need just a little bit more info than that to figure out how to actually make the c bindings.



Write an extern "C" interface to QT. One aspect of that will probably be catching all exceptions and calling std::abort in every interface function.



Can you explain the >> part? Is that bit shifting?



The algorithm only gives randomness is wose for the LSB so he is shifting it over.



Yeah I've been digging through qt's source and trying some stuff but I'm too retarded for this project. I'm just going to go back to working through SICP. Maybe I'll revisit it in a few years.



bored gonna do one of these



fucking handwriting crap yeah right.


File: c5e3fa8cb592d28⋯.jpg (4.64 MB, 3840x2160, 16:9, stretched-3840-2160-869615.jpg)

Whats the best assembly to learn that will still be somewhat useful for making stuff on low power platforms?

I've started with the 6502 and it's pretty easy. I'd really like a board I could have to physically mess around with.

That basic limits my options to:





I'm not sure which one to invest my time in. ARM looks like the most complex out of all of them. MIPS seems to be dying. AVR and PowerPC look cool though.




Did you have a board in mind? I looked for one a while back and it was like wading through a swamp of dead links and retired products.




Z80. If you're an amerifat or a frog you might have a TI calculator lying around, and if not they show up used for ~$10 used often. It's also still in production, cheap, and available in DIP package for retard proof prototyping.



ARM for sure.



No I couldn't find any. Was hoping someone could suggest one.


I'd rather stick with going down a risc-y path than looking at x86 ancestors.


Seems to be the way it looks atm.



>Seems to be the way it looks atm

Since you have already mastered 6502 (and the others aren't that different), why not get an FPGA board to create your own 6502 processor and experiment with variations to it. Another option in conjunction with the ARM route would be a Zedboard which marries an FPGA and ARM processor together. You can ignore the ARM altogether if you choose.




I like that idea. I'd say I'm far from mastering the 6502, it's just the full instruction set makes perfect sense to me and I can simulate in my head whats going on in the chip for the most part. I need to actually spend a few days writing programs for it.

But yes after that, I like the idea of going the FPGA route.



Seems OK to me anon.

johnny@macstacub:~/_prj/tests/test_vec$ c++ --version
c++ (Ubuntu 7.3.0-16ubuntu3) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO

johnny@macstacub:~/_prj/tests/test_vec$ cat main.cpp
#include <iostream>
#include <vector>

int main() {
std::vector<int> v = {5, 6, 9, 4, 6, 8};

for (const auto& e : v)
std::cout << e << '\n';

std::cout << "Finished\n";
johnny@macstacub:~/_prj/tests/test_vec$ c++ main.cpp -o test -std=c++11 && ./test

What compiler are you using?



>Also learning c++ from a book

Actually that book is remarkable. Then again, ofc you have to actually do the work...hey it's a textbook.




<necro'ing a month old solved issue



Ehh. Entertain me, I haven't been in one of these for over 6 months.



Yeah right. How many books have you read?


A challenger appears: https://github.com/02sh/add-one

Can you write this program in your pathetic memelang or pre-rust lang?

How costly will be your abstractions?


#46 done

#!/usr/bin/env node

const runes = require("runes")

const compose = (...f) => data => f.reduceRight((d,f) => f(d), data)
const countChars = s =>
runes(s).reduce((data, c) => {data[c] = (data[c] || 0) + 1; return data}, {})
const printCounts = data =>
Object.keys(data).sort().forEach(c => console.log(c+":", data[c]))

compose(printCounts, countChars)(process.argv.slice(2).join(" "))

anon@interjector ~/charcount % ./index.js 🤔🤔🤔😂😂💯💯💯💯👌👌👌👌👌
👌: 5
💯: 4
😂: 2
🤔: 3


>supposed to be small challenges

>some of them will take weeks

Why are ni/g/gers so retarded?



import System.Environment
import Text.Read
import System.Exit
import Data.Maybe
import Control.Monad

main :: IO ()
main = (listToMaybe >=> readMaybe) <$> getArgs
>>= maybe (die "bad input")
(print . (+ (1 :: Int)))

>How costly will be your abstractions?

My cost function is how many variable names I have to use. Zero cost.



pointless style? absolutely disgusting. that ain't Forth. what's more:

$ ./add1 18446744073709551615
$ time for x in {1..1000}; do ./add1 $x >/d
ev/null; done

real 0m1.981s
user 0m0.582s
sys 0m1.525s
#include "share/atspre_staload.hats"

#include <limits.h>

implement main(argc, argv) =
case argc of
| 2 =>
val n = g0string2uint(argv[1])
if n = $extval(uint, "UINT_MAX") then
(prerrln!("n+1 is too large"); 1)
(println!(n+1u); 0)
| _ => (prerrln!("usage: ", argv[0], " <n>"); 1)
$ ./add1 18446744073709551615
n+1 is too large
$ time for x in {1..1000}; do ./add1 $x > /dev/
null; done

real 0m1.144s
user 0m0.407s
sys 0m0.852s
Did you decide to learn Haskell because a real language was too hard for you? ohohohoho no fair seeing how my version responds to non-numeric arguments



Swap Integer for Int and it handles the big case (and gets slower). But proofy languages scare the hell out of me. It fits too well with useless academic meme languages though so I'm sure I'll have to get over it one day.



Can you explain the operators in this one?

captcha: maffei



How much Haskell do you know?





I made a 50 byte hello world. Not that the small size was the goal though.



>=> has the type "Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)"

This lets us combine 2 different functions which make something into the same monad which in this case is the Maybe monad.

listToMaybe >=> readMaybe has the type "Read c => [String] -> Maybe c"

So this function takes a [String] and then reads the first element. If it's empty or can't read it then the maybe is nothing.

getArgs has the type "IO [String]"

If you remember from before, we need a [String] not an IO [String]. To get around this we are just going to apply the function on the [String] inside of the IO using the <$> operator.

<$> has type "Functor f => (a -> b) -> f a -> f b"

This allows us to apply a function on the value inside of the functor (a monad is a functor).

So in total (listToMaybe >=> readMaybe) <$> getArgs gets us a result that has the type "Read c => IO (Maybe c)".

Since we want to access we use the monadic bind operator >>=.

>>= has the type "forall a b . Monad m => m a -> (a -> m b) -> m b"

This is kind of like <$> above, but the arguments are switched an the function returns monad instead of just a regular value.

So using >>= we will have access to the Maybe c but we will need to return an IO monad.

maybe just lets us apply a function to what's inside of the maybe and also lets us give a default result of the maybe is nothing. The IO monad we have to create are created from the die and the print functions.


I worked for a hot second on makeing my meme podcatcher simpler and fixed a bug I was having.



cd ~/pod

while read podcast


filelist=$(ftp -o - "$podcast" | grep -o '<enclosure[^>]*' | grep -o 'http[^"]*')

for file in $filelist


if ! grep -q "$file" .log


ftp -C "$file"

echo $file >> .log



done < podlist


I have a couple things on the grill atm. I have been learning about CB radios, antenna, and the HF brand for the radios.

Also I have been toying with setting up and IRC and email server.

IRC: irc.electronicnexus.com

plain and SSL ports available.



Thanks a lot man!



#include <stdio.h>

char *firstzero(const int *input)
const static char *output[] = {"none", "first", "second", "third"};
int i;
for (i = 0; i < 3; i++) {
if (input[i] == 0) {
return output[(i+1)%4];

int main()
int list[] = {3, 0, 4};
return 0;
Compile with -funroll-loops



You are like little baby. Watch this

import Data.List

findZero :: (Eq a, Num a) => [a] -> [Char]
findZero xs =
let pos = ["first", "second, "third"]
getPos = (pos!!) . (`mod`3) in
case (elemIndex 0 xs) of
Nothing -> "none"
Just x -> getPos x

main = do
putStrLn $ findZero [2,0,3]
putStrLn $ findZero [2,3]



you can change main to

main = do
putStr $ findZero [2,0,3]
putStr " to "
putStrLn $ findZero [2,3]


(define (first-zero xs) 
(lambda (break)
(car (foldl
(lambda (acc x)
(if (= x 0)
(break (car acc))
(cdr acc)))
'(first second third none)



firstZero (0:_) = "First"
firstZero (_:0:_) = "Second"
firstZero (_:_:0:_) = "Third"
firstZero _ = "None"


import firstZero



pham tbh shut up 😂😂😂😂😂😂😂😂😂😂



You have brought shame to Common Lisp.

(defun firstzero (list &optional (n 1))
(cond ((null list)
((zerop (car list))
(intern (string-upcase (format nil "~:R" n))))
(t (firstzero (cdr list) (1+ n)))))
as used:
* (firstzero '(1 2 3 4 0))

* (firstzero (append (loop for i from 1 upto 100 collect i) '(0)))



I'm making a few bash/python scripts to (essentially) wget a few RSS feeds, parse them for video links (including YouTube playlists and channels) to pipe into youtube-dl. Testing the parsing regex now.

This is going to run hourly for possibly a whole week at a time unattended on a raspberry pi. What do I need to consider for this? I plan on extensive logging and error checking, and having the scripts email me if an unexpected error occurs.

Do I need to worry about memory leaks or anything else?


In Common Lisp, is there an easy syntax to make nested hash maps? As an example I'd like an object about the same as this JSON:

"name": "John",
"age": 38,
"parent": {
"name": "Hank",
"age": 63

How do I simply set and get these values? In Racket I think it'd be like this:

(define data (hash
'name "John"
'age 38
'parent (hash
'name "Hank"
'age 63)))


for B in s wx webm gif wsg
wget -q -O - https://8ch.net/$B/catalog.html | grep -Eo '[0-9]{3,5}' > ~/1.txt
while read F; do wget -P delete -np -r -l 1 -H -D media.8ch.net -A png,gif,jpg,jpeg,webm,mp4 https://8ch.net/$B/res/$F.html; done < ~/1.txt

Is there anyway to simplify this? wget -m is not a solution.



fn firstzero(input: &[i32]) -> &'static str {
let output = ["first", "second", "third"];
for x in input.iter().zip(output.iter()) {
if *x.0 == 0 {
return x.1;

fn main() {
let input = [3, 0, 4];
println!("{}", firstzero(&input));


/tech newfag here

I made my first program in python today

It's an age calculator(well, really just a calculator)

It's a start ig



fn main() {
println!("{}", first_zero(&[]));
println!("{}", first_zero(&[3, 0, 4]));
println!("{}", first_zero(&[1, 2, 3, 4, 0]));

fn first_zero(numbers: &[i32]) -> &'static str {
.zip(&["first", "second", "third"])
.find(|&(&n, _)| n == 0)
.map_or("none", |(_, s)| s)



good work mate, never stop learning



There isn't, but if you read your Let Over Lambda you'll see how you can make one. While reading that book I reimplemented all of Clojure's syntax sugar for CL.

>In Racket

or you could just implement that HASH function yourself. That's going to be pretty simple.



age = input("What's ya age, nigger?")
year = int(28) - int(age)
if year > 0:
print("Get back to work, ya still got a few more years ahead of ya, boy!")



Add a space at the end of the string your are passing into input.

You don't need to cast 28 to an int, it is redundent.

Instead of calculating the year variable just do "if int(age) < 28"


How does one learn the Haskell way? I come from a lot of imperative background. How do you think functionally?



firstzero([0, _, _]) -> first;
firstzero([_, 0, _]) -> second;
firstzero([_, _, 0]) -> third;
firstzero([_, _, _]) -> none;
firstzero(_) -> erlang:error(badarg).



Learn Erlang. Imperative (you write program as sequence of actions), but with heavy functional influence (single assignment, pattern matching, recurse-not-iterate)

Also work with Futures/Deferreds/Promises in imperative language. Understand that you can compose asynchronous code synchronously. Look as Haskell. Now you can understand how impure code can be composed in pure code.



Think of it as doing a series of transformations. So if you wanted to take a list of strings, convert them into integers, and add them together, you would use a function for each of those parts. In an imperative language you would probably do this by iterating over the list of strings and keeping a running sum. By this example you can see that functional code likes to break things up and not intertwine things together. Take a look at example implementation for both.


sum $ read <$> list
int sum = 0;
for (String str : list) {
sum += Integer.valueOf(str);
return sum;



>only working on lists of length 3

>explicit badarg when implicit function_argument was fine

firstzero([0|_]) -> first;
firstzero([_, 0|_]) -> second;
firstzero([_, _, 0|_]) -> third;
firstzero(L) when is_list(L) -> none.



>Write a function FIRSTZERO that takes a list of three numbers as input

Three numbers. Not 'at least three numbers'.

> implicit function_argument

It's function_clause. And yes, that would be more correct than badarg indeed



I use ECMAScript 2018 (sue me) and I started looking into writing code in a more functional way. For instance, I started using Ramda (which is a functional library implementing some of Haskell's Data.List/Map functions, and composition) or if I don't want to add a dependency, I just use the arrow syntax to curry. I also define these:

// equalivent of Haskell's `.` (composition)
const comp$ = (...funcs) => data =>
funcs.reduceRight((d, f) => f(d), data)
// pipeline
const pipe$ = (...funcs) => data =>
funcs.reduce((d, f) => f(d), data)
// Data.List.map
const map = f => data => [].map.call(data, i => f(i))
// Data.List.filter
const filter = (f = (x => !!x)) => data =>
[].filter.call(data, f)

Which I use as (for instance):

const toNum = x => +x
const strip = "".strip.call
const split = by => s => s.split(by)

// Get a list of numbers from a file
// In Haskell you'd write (obviously some of these are incorrect)
// getNumbers :: (Num a) => [Char] -> a
// getNumbers = (filter notNaN) . toNum . (map strip) . lines . getFile
// (NaN is falsey in JS)
const getNumbers = comp$(filter(), map(toNum), map(strip), split("\n"), fs.readFileSync)

// Process a comment
// Uses ES2018 object spread operator
const clearName = data =>
name: data["name"].replace("<", "&lt;").replace(">", "&gt;")}

const handleMarkdown = data =>
html: marked(data["body"], {escape: true})}

// ...

const processComment = pipe$(
// ...

In that getNumbers above, wish there was a way to do algebraic data types in JS so I could do the Maybe monad (fs.readFileSync would be Maybe String instead of throwing an exception like it does now).

I fucking love science declarative programming



something like

filter() <- map(toNum <- strip) <- split("\n") <- fs.readFileSync
syntax would be absolute HNNNNG btw.

Polite sage



>wish there was a way to do algebraic data types in JS so I could do the Maybe monad

There's nothing stopping your from making a Maybe monad in JS. Haskell doesn't as language doesn't come with any special to handle Monads other than do notation which is just sytactic sugar for using the bind function without things getting messy.



I think you are confused as that makes no sense as that syntax looks like nothing I'm familiar with. If you wanted to have your readFileSync being of type Maybe String in a more haskell like sntax it would be

contents -> fs.readFileSync(file)
return filter(filterFun, map(toNum . strip, contents.split("\n")))
This function returns a Maybe [String]. Keep in mind that do is not just for making imperative looking code. If readFileSync fails and returns a nothing, execution will stop and the whole thing evaluates to Nothing. Do notation for the Maybe monad is nice since you don't have to worry about explicitly checking if an operation succeeds.



whoops the arrow should be the other way




Ever since I pulled that off I've been obsessively researching so that I can make more complex things.

I wish I started sooner tho.



Update on my "baby's first project"

I added a thing that'll tell you what year you'll be a certain age at.

Anyone have project ideas for a newbie like me? I'm still trying to get familiar w the syntax, language and whatnot, and I figured the best way to learn it all would be to put myself in a situation that requires me looking for particular solutions.



Make a basic version of hangman.



>Anyone have project ideas for a newbie like me?

Before you embark on an entirely new project, I have a few suggestions. One would be to test the limits of the program you've already written. Presumably it can handle normal human lifespans, but just for fun, can it calculate the age you'll be if you live to the year 10,000? How about the year 1,000,000? How about the year 1,000,000,000,000,000,000,000? Do you get any odd output? Error messages? If you get errors, can you fix them? Or at least handle them in a sensible way (i.e. without the interpreter choking or without a segfault)?

Does your program pass user input to a function? If not, try implementing the logic of the calculator part as a function.

I believe you said you wrote your calculator in Python. Try reimplementing it in another language.

It's always helpful to learn some of the tooling around programming. If you don't already know how to use a DVCS, pick one. Git, mercurial, monotone, and bzr are the big ones, but very few people use bzr or monotone, go git or mercurial would probably be a better choice. Initialize a repo. Add your calculator. Commit it. Branch it. Change it. Merge it. Etc.

If you already know a DVCS, try adding a documentation system like Doxygen to your repertoire.


File: 758469e4f916e03⋯.jpg (1.28 MB, 2576x1932, 4:3, 20180829_234923.jpg)


Weeeell.. it functions a little differently than that. Here's a pic of what I've got so far.

Not much at all. If I put anything other than digits into the input field when running the program, it crashes immediately. Idk how to implement an error system. I was thinking about implementing it by giving the input slots a range of applicable results, and a range of results that would result in an error, in which you would be able to go back and try again. Idk how to implement ranges tho. Im sure there's some basic function that I just don't know yet.



Also excuse the fact that it's not a screencap. I have no internet connection available to my PC, so in order to install python and the ide to my pc, I had to dl it to my phone, then transfer it.



Sounds fun. Ig I could make an acsii style hangman, make some assignments and whatnot. I just dont know how I'd implement a range of items. I could do each number or letter individually, but I feel that there's a more effective way.



use strchr() against a copy of your word in a mutable buffer, and mutate it to ensure that you don't find the same letter twice. Easy way: replace letters with ' ' after you find them.




ugh gross, didn't realize you were using Python. I've been programmin for decades and scripting languages still sometimes screw me over with how bad they are. Are you sure you're smart enough to use a language this 'easy'? Are you sure you're disciplined enough to sleep in a box with deadly spiders without provoking them? I'm sure you can get bit lots of times without actually dying.

create a dict with keys = letters from your word, and values = the number of times the letters occur in your word.



>Idk how to implement an error system.

Python has done it for you. Search for "handling python exceptions" or some variation thereof. Or you can find the relevant section in the Python docs. Handling exceptions allows you to choose how your program behaves when it encounters an error instead of just choking and terminating the interpreter.

>I was thinking about implementing it by giving the input slots a range of applicable results, and a range of results that would result in an error, in which you would be able to go back and try again.

You can use conditionals to check whether the user input falls into a certain range.

if (x < 4 or x > 110):
print("I don't believe you.")
#do whatever with x

But you should still handle exceptions.



if not 4 < x < 110:



I pulled it out of my ass. Just thought it would be good.


I tried:

const Nothing = null
const Just = x => {
function _just(x) { this.value = x }
return new _just(x)

const maybeDo = (m, just, nothing) =>
m === Nothing ? nothing() : just(m.value)

const maybeReadFile = (path, options) => {
try {
return Just(fs.readFileSync(path, options))
} catch (e) {
return Nothing

// then
maybeDo(maybeReadFile("input.txt"), x => console.log(x), () => console.log("Error happened"))



I just woke up. Just can Just xD be

const Just = x => ({value:x})



Your maybeDo is much closer to just a regular bind (>>=) than what do does (though bind wouldn't do anything for the failure case). do should return a maybe value, but right now it doesn't return anything. In Haskell/JS mix what that last line would look like would be something like.

case maybeReadFile("input.txt") of
Just x -> console.log(x)
Nothing -> console.log("Error happened")




This has been quite helpful, thanks.


Eh, only reason I use python is because it's been described as a good beginner language by everyone and their mom.

I have no prior experience with programming, and no sense of familiarity with /tech culture. I'm basically learning as I go.


Will definitely try, thanks.



What does >>= do exactly? I read the wikipedia article on monads but didn't get the binding shit.



Prelude> :t (>>=)
(>>=) :: Monad m => m a -> (a -> m b) -> m b

It takes an 'm a' and a function, a -> m b, and then it returns m b.

You think of it as a "do something inside the box" function. You have a box with a spider in it. You have a spider -> squished_spider function. You perform the function in the box, and now you have a box with a squished_spider in it.

There are two points:

1. the box remains

2. the type of the thing in the box may change



const testF = x => {
try { return Just(5 / x) }
catch (e) { return Nothing }

const maybe$ = m => f =>
!(m === Nothing) ? f(m.value) : Nothing

maybe$ (Just(0)) (testF)




What you are describing is more like <$> aka fmap which applies a function to the value inside of a Functor.


It's for chaining computation. Let's take a look at how Maybe defines it's bind method. The type of it is going to be Maybe a -> (a -> Maybe b) -> Maybe b.

(Just x) >>= k      = k x
Nothing >>= _ = Nothing
There are two different cases which can happen. If value you are binding is a Just, then you just return the application of the second aregument with the value you binded. On the otherhand if a Nothing is passed in, then the whole thing resolves to just nothing regarless of the function passed in (in haskell _ is used for garbage variables that aren't going to be used).

Why is this useful you might ask? Why not just use fmap? Let's look at a different problem and then lets first look at how it is similar to a problem bind tries to solve and then how bind is used. Imagine we have 5 functions called add1, add2, add3. Each one takes an Maybe Int adds a value and returns a Maybe Int. Now let's say you wanted to do "add3 $ add2 $ add1 Just 0". The type of that expression is going to be Maybe Maybe Maybe Maybe Int. If you take a moment and look at it, you might notice that a series of Maybes are kind of redundent and can be represent by just a Maybe Int without losing any information. All you really care about is that all Maybes are not Nothing. The goal of bind for Maybe is to program in this behavior of combining two Maybes together. The idea is that you can turn the last value of Just in a chain of maybes into the Just of a single Maybe. If you encounter a Nothing in the chain, you can represent the whole thing with a single Nothing rather than something like Just $ Just $ Nothing. Now lets take a look at actually using >>=. Lets use add1 though add3 again, but now make their type Int -> Maybe. Here is now how we do a similar computation as above: "add1 0 >>= (\x -> add2 x) >>= (\y -> add3 y)" or more idiomatically "add1 0 >>= add2 >>= add3". What you'll see now is that the result of this expression is just a Maybe Int. We've eleminate the problem of chaining redundent Maybes.

Note that Maybes aren't the only monad. Lists are actually also monads. See if you can figure out what this does yourself: "[1, 4, 7] >>= (\x -> [x, x + 1, x + 2])"

Hint: fmap (\x -> [x, x + 1, x + 2]) [1, 4, 7] is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Does the fact that lists are nesting now remind you of what happened with Maybe above



>aka fmap which applies a function to the value inside of a Functor.

what did you just call me, you little bitch?


damn, that was useless information. Haskell has 'artificial learning' the way bad games have 'artificial difficulty'. As you go on you 'learn' more and more but it's all just verbiage-enriched concepts you'd already had a handle on when you started. Example of a language not like this: Shen and its sequent fucking calculus. Just look at this: https://groups.google.com/d/msg/qilang/2O-1kVKwxag/pJiTuRf3AgAJ



>the last thing

I get it's [1..9], but how does >>= "iterate" over it? How are the results inside the RHS of bind combined? I dun get it.



[]'s bind is defined as "xs >>= f = [y | x <- xs, y <- f x]".

The right hand side uses Haskell's list comprehension syntax. If you meant why, it's because that's how the creators wanted to work. It's parallels the way fmap works.


Since the support thread is useless, I'd figure I'd ask here.

What's a good book to learn standard ML? Is the little MLer any good?



>standard ML

... you sure?

not OCaml?

I found ML for the Working Programmer useful, but I already knew OCaml.

I have the Little MLer but didn't find it that interesting.



The idea is that if I learn Standard ML, it will make it easier to pick up OCaml, F#, Elm, and Scala.



if you enter a park from the east, is it then easier to access the swings than if you'd entered from the west? whatever you direction you come from, once you come from it, you're in the park.



It is if the swings are closer to the East entrance.




Thanks m8 I've been looking to cheat off someone else's paper. Just took a quick glance, looks like mostly intraday trading. What are you looking at in terms of signals?


Is this sieve of Eratosthenes implementation any good? It seems far too simple and fast, but it works.

prints a numpy array with composite numbers changed to zero using the sieve of
import numpy as np

def primes(size):
arr = np.arange(1, size+1, 1)

for i in range(1,size):
if arr[i] != 0:
for j in range(arr[i]+i, size, arr[i]):
arr[j] = 0

return arr


Well. The sieve of Eratosthenes worked great. I used it to make this Ulam spiral. I'll post the code tomorrow when I get up. I'm going to keep playing around until I hit the sack.


Here's the damn spiral. Maybe I should just go to bed right now.


Aw damnit, don't fuck with me now, firejail. Let's see if it uploads now


File: b589953b6371c38⋯.png (55.05 KB, 901x901, 1:1, ulam.png)

Last try before I just kill myself already



>What are you working on, /tech/? Don't be shy about asking for help or code review. Keep your posts on-topic, please.

I'm learning Ada. I also did Vigenere's cipher for challenge #64.


with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

with Ada.Text_IO; use Ada.Text_IO;

with Ada.Command_Line; use Ada.Command_Line;

with Ada.Strings; use Ada.Strings;

with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

with Ada.Characters.Handling; use Ada.Characters.Handling;

-- character -> ascii value using Character'Pos
-- ascii value -> character using Character'Val
procedure main is
function encrypt(b : in Character; o : in Character) return Character is
output : Integer;
base : Integer;
offset : Integer;
base := Character'pos(b);
offset := (Character'pos(o) - 97);
output := (base + offset);
if output > 122 then
output := (output mod 123) + 97;
end if;
return Character'val(output);
end encrypt;

function decrypt(b : in Character; o : in Character) return Character is
output : Integer;
base : Integer;
offset : Integer;
base := Character'pos(b);
offset := (Character'pos(o) - 97);
output := (base - offset);
if output < 97 then
output := 123 - (97 - output);
end if;
return Character'val(output);
end decrypt;

-- when the string 'k' is too short, expand it to a length of 'n'
function adjustkeypass(
k : in Unbounded_String;
n : in Integer)
return Unbounded_String is
output : Unbounded_String;
iterations : Integer;
index : Integer;
output := k;
iterations := n - length(k);
for i in Integer range 1 .. iterations loop
-- unbounded strings are 1-indexed.
if i > length(k) then
index := index mod length(k) + 1;
index := i;
end if;
append(output, element(k, index));
end loop;
return output;
end adjustkeypass;

function vigeneres(
p : in Unbounded_String;
k : in out Unbounded_String;
is_encrypt : in Boolean)
return Unbounded_String is
output : Unbounded_String;
newchar : Character range 'a' .. 'z';
-- keypass needs to be truncated or expanded to match phrase's length
output := p;
if length(k) < length(p) then
k := adjustkeypass(k, length(p));
end if;
for i in Integer range 1 .. length(p) loop
if is_letter(element(k, i)) then
if is_encrypt then
newchar := encrypt(to_lower(element(p, i)),
to_lower(element(k, i)));
newchar := decrypt(to_lower(element(p, i)),
to_lower(element(k, i)));
end if;
overwrite(output, i, newchar & "");
end if;
end loop; -- for loop
return output;
end vigeneres;

phrase : Unbounded_String;
keypass : Unbounded_String;
result : Unbounded_String;
if Argument_Count < 2 then
Put_Line("usage: <program> <phrase> <passphrase>");
end if;

phrase := To_Unbounded_String(Argument(1));
keypass := To_Unbounded_String(Argument(2));
result := vigeneres(phrase, keypass, true);
result := vigeneres(result, keypass, false);
if result = phrase then
put_line("Vigenere's basic cipher is working.");
end if;
end main;


Ok. Here's my Ulam spiral code. R8, h8, and masturb8


import numpy as np

def primes(size):
arr = np.arange(1, size+1, 1)

for i in range(1,size):
if arr[i] != 0:
for j in range(arr[i]+i, size, arr[i]):
arr[j] = 0
arr[0] = 0
return arr


Someone please let me know how I can clean this loop up. It's shit with all those fucking breaks, but this is the part I spent the vast majority of my time on.

import numpy as np
import matplotlib.pyplot as plt
from math import sqrt

def uspiralize(inarr):
if sqrt(len(inarr)) % 2 == 0:
print("USPIRALIZE: spiral side length must be an odd number!")
print("USPIRALIZE: (i.e. square root of length of primes array must be odd)")
return 0

side = (sqrt(len(inarr)))
center = (side-1) / 2
arr = np.zeros((side,side))

hwalker = center
vwalker = center

while j < side:
j += 1
for m in range(0,j):
if i == len(inarr):
arr[vwalker][hwalker] = inarr[i]
vwalker += 1
i += 1

for n in range(0,j):
if i == len(inarr):
arr[vwalker][hwalker] = inarr[i]
hwalker += 1
i += 1

j += 1

for m in range(0,j):
if i == len(inarr):
arr[vwalker][hwalker] = inarr[i]
vwalker -= 1
i += 1

for p in range(0,j):
if i == len(inarr):
arr[vwalker][hwalker] = inarr[i]
hwalker -= 1
i += 1

return arr


import numpy as np
from scipy import misc
from math import sqrt
from spiral import uspiralize
from primes import primes

def ulamimg(side):
if side % 2 == 0:
print("Side length must be odd")
return 0

data = primes(side * side)
for i in range(len(data)):
if data[i] > 0:
data[i] = 1

spiral = uspiralize(data)
misc.imsave("ulam.png", spiral)


using map/filter/etc, whats the proper way of converting something like the following loop

for i in range(len(vector)):

vector[i] = vector[i-1] + func(vector[i])

where you need to reference previous or future values in the iterator

I suppose the question is more about iterators in general, than map/filter/etc



use foldl. When using foldl to build a list, the new list is passed as an argument to your function.



for a completely readable example:

#include "share/atspre_staload.hats"

fun {a:t@ype}{b:t@ype} foldl_to_unbox{n:int}(fopr: (a, b) -> a, acc: a, list: list_vt(b, n)): a =
case+ list of
| ~list_vt_nil() => acc
| ~list_vt_cons(x, xs) => foldl_to_unbox<a><b>(fopr, fopr(acc, x), xs)

fun {a:type}{b:t@ype} foldl_to_box{n:int}(fopr: (a, b) -> a, acc: a, list: list_vt(b, n)): a =
case+ list of
| ~list_vt_nil() => acc
| ~list_vt_cons(x, xs) => foldl_to_box<a><b>(fopr, fopr(acc, x), xs)

fun {a:viewtype}{b:t@ype} foldl_to_vbox{n:int}(fopr: (a, b) -> a, acc: a, list: list_vt(b, n)): a =
case+ list of
| ~list_vt_nil() => acc
| ~list_vt_cons(x, xs) => foldl_to_vbox<a><b>(fopr, fopr(acc, x), xs)

symintr foldl
overload foldl with foldl_to_unbox
overload foldl with foldl_to_box
overload foldl with foldl_to_vbox

fun {a:t@ype} dump_list{n:int}(list: list_vt(a, n)): void =
val _ = foldl_to_unbox<int><a>(lam (count, x) => (print_int(count); print_string(": "); fprint_val<a>(stdout_ref, x); print_newline(); count + 1), 0, list)
in () end

implement main0() =
val k1 = $list_vt{int}(1, 1, 1, 1, 1)
val k2 = foldl_to_vbox<List_vt(int)><int>((lam (a, b) =>
case+ a of
| ~list_vt_nil() => list_vt_cons(b, list_vt_nil())
| ~list_vt_cons(x, xs) =>
list_vt_cons(b + x, list_vt_cons(x, xs))
), list_vt_nil(), k1)
val k3 = list_vt_reverse(k2)
outputs, of course:
0: 1
1: 2
2: 3
3: 4
4: 5



I made an enigma in Ada once using arrays with a modular type as index. That worked pretty well iirc.

You could also use modular arithmetic instead of expanding your key string.


I am making a program that will upload files to a file server using Java. How can I store the login credentials securely? I'm making it for a boomer who has trouble typing so requiring the user to log in every time is not an option.



for windows, use the Certificate Manager maybe.

for macOS, use Keychain Access

for linux, there's not much you can do to protect the user from the user' other programs (which is why user-per-app in Android makes so much sense), just store the creds in a file that's at least not world-readable. If you want to be a little obscure, you could keep the file encrypted on disk and have the encrpytion key easily sniffed from your java.



I was hoping there'd be an easy OS-agnostic solution since I'm developing it on macOS but the person who will be using it uses Windows.

Would it be a bad idea to just encrypt a JSON file that contains the username and password and then prompt the user to answer a simple recovery question-style thing (easier for him to remember than a password) to decrypt it (with the answer being the key)? Since boomers can remember things like their mother's maiden name or favorite baseball player or some shit but would struggle to remember a string like "hunter2".



File: 16b524f9d2466b4⋯.webm (8.47 MB, 1920x1080, 16:9, Eye exercise-xn8ki1.mp4.webm)

Remember. Okay?



Had a few minutes so I came back to this and cleaned up that loop a bit. How Pajeet is it now?

#!/usr/bin/env python3

This function takes a numpy array and makes an ulam spiral matrix out of it.
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt

def uspiralize(inarr):
if sqrt(len(inarr)) % 2 == 0:
print("USPIRALIZE: spiral side length must be an odd integer!")
print("USPIRALIZE: (i.e. square root of length of primes array must be odd)")
return 0

side = int((sqrt(len(inarr))))
center = (side-1) / 2
arr = np.zeros((side,side))

hwalker = center
vwalker = center

for j in range(-1, side+1, 2):
for m in range(0,j):
if i < len(inarr):
arr[vwalker][hwalker] = inarr[i]
vwalker += 1
i += 1

for n in range(0,j):
if i < len(inarr):
arr[vwalker][hwalker] = inarr[i]
hwalker += 1
i += 1

for m in range(0,j+1):
if i < len(inarr):
arr[vwalker][hwalker] = inarr[i]
vwalker -= 1
i += 1

for p in range(0,j+1):
if i < len(inarr):
arr[vwalker][hwalker] = inarr[i]
hwalker -= 1
i += 1

return arr


File: 996ff92ed42b310⋯.png (4.45 MB, 9001x9001, 1:1, 9001ulam.png)

Also posting a big ulam spiral for your mathy edification. It's 9901 by 9001. That's 81,018,001 numbers total.


File: 3dcf388ce6afc9f⋯.png (14.2 KB, 801x801, 1:1, twinulam.png)

Ok one more. Here's one I did of just the twin primes. They give it the illusion of motion and it has a weird swirly effect.



oooh, a fellow fan of stegonography :)

I love AES, GPG, etc but I'm not going to pretend that it can't be pwned.

I mean one of the most low key fuckeries I remember was using directional mics to pic up CPU noise to reverse engineer a GPG key. (IDK if they can still do that but that goes to show that "you aren't being paranoid")

Are there any particular apps like stegsnow or seghide?

I've been meaning to make my own method of stegonography too. I've gotten as far as pseudo-code because I'm not convinced my method of stenography is worth shit yet.


Anyone into current-day cracking? Denuvo and shit? I've been out of the game for a long, long time. I'd love to hear your war stories.


I want to make a small program that automatically uninstall itself at a set date or after a certain threshold, as a practical joke. Is there any feasible way to do this?




1. first run, save the date. later runs, check and see if the date is far enough back in the past that you should uninstall now.

2. first run, check and see what daemons are running. if atd is, create an atd job that uninstalls you after the desired time frame. if crond is, create a cron job that periodically performs the logic from #1

there's room for creativity. your program can use the age of its own files in the filesystem to determine when to zap them.

instead of your program calculating the date at all, you could have your download server burn the self-destruct date into downloads when downloaded.



That's cool anon I never thought of doing twin primes. It looks like 3d at that range.


File: e6e7995168469b8⋯.webm (3.64 MB, 1920x1080, 16:9, Category Theory in Life -….webm)


File: 5733ad3f936f12a⋯.webm (4.68 MB, 1920x1080, 16:9, Category Theory in Life -….webm)


but then


File: 356a804a95bcbb3⋯.webm (5.12 MB, 1920x1080, 16:9, Category Theory in Life -….webm)


Well played doctor.



Since I rolled 80.

with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

with Ada.Text_IO; use Ada.Text_IO;

with Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO;

with Ada.Containers.Indefinite_Vectors; use Ada.Containers;


procedure main is

type chars_ptr_ptr is access constant Interfaces.C.Strings.chars_ptr;
pragma Convention (C, chars_ptr_ptr);
function To_Ptr is new Unchecked_Conversion (System.Address, chars_ptr_ptr);

procedure execvp (
path : Interfaces.C.Strings.chars_ptr;
argv : chars_ptr_ptr
pragma Import (C, execvp, "execvp");
use type Interfaces.C.size_t;

function fork return Interfaces.C.int;
pragma Import (C, fork, "fork");

function wait (Status_Ptr : access Interfaces.C.int)
return Interfaces.C.int;
pragma Import (C, wait, "wait");

-- end of C function importing - access POSIX --

package String_Vector is new Indefinite_Vectors (Natural,String);
use String_Vector;

-- split unbounded string into strings inside string vector
function tokenize (input : in Unbounded_String)
return String_Vector.Vector is
is_quoted : Boolean := false;
lastpos : Positive := 1; -- unbounded strings index at 1
ulimit : Positive;
output : String_Vector.Vector;

ulimit := length(input);
for i in 1 .. ulimit loop
if element(input, i) = '"' and is_quoted = false then
is_quoted := true;
elsif element(input, i) = ' ' and is_quoted = false then
output.append(slice(input, lastpos, i));
lastpos := i;
end if;
end loop;
output.append(slice(input, lastpos, ulimit));
return output;
end tokenize;

-- convert ada string to something understoood by execvp()
function convertstrings(input : in String)
return Interfaces.C.Strings.chars_ptr is
output : Interfaces.C.Strings.chars_ptr;
t : Interfaces.C.char_array := Interfaces.C.to_c(input);
output := Interfaces.C.Strings.new_char_array(t);
return output;
end convertstrings;

-- execute user input
procedure execute (input : in Unbounded_String) is
use type Interfaces.C.int;
tokens : String_Vector.Vector;
is_bg : Boolean := false;
tokens := tokenize(input);
argc : Interfaces.C.size_t := Interfaces.C.size_t(length(tokens));
args : Interfaces.C.Strings.chars_ptr_array(0 .. argc);
i : interfaces.C.size_t := 0;
child : Interfaces.C.int;
child_status : aliased Interfaces.C.int;
for each of tokens loop
args(i) := convertstrings(each);
if each = "&" then
is_bg := true;
end if;
end loop;
child := fork;
if child < 0 then
put_line("fork failed");
elsif child = 0 then
execvp(args(0), to_ptr(args'address));
elsif not is_bg then
exit when Wait(child_status'access) = child;
end loop;
end if;
end usetokens;
end execute;

continue : Boolean := true;
userinput : Unbounded_String;
tokens : String_Vector.Vector;
history : String_Vector.Vector;
while continue loop
userinput := get_line;
if userinput = "exit" or userinput = "quit" then
continue := false;
userinput = "history" then
for each of history loop
end loop;
end if;
append(history, to_string(userinput));
end loop;
end main;

Executes binaries and has history. Does not have pipe sytem, redirection, or the full shell grammar. lex and yacc seem to output some thousands lines of C code; doubt it generates code in Ada.





This is why you shouldn't have nontechnical talks, nor invite women to conferences.



I mean, I guess so, but that's a real fuckin complicated way of saying "shit sucks".

[Return][Go to top][Catalog][Nerve Center][Cancer][Post a Reply]
Delete Post [ ]
[ / / / / / / / / / / / / / ] [ dir / acme / animu / asmr / leftpol / magali / mde / tacos / vg ]