[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
/dpt/ - Daily Programming Thread
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 255
Thread images: 28
File: 1464854375930.jpg (70 KB, 1280x720) Image search: [Google]
1464854375930.jpg
70 KB, 1280x720
Anime Forever Edition
Previous - >>55084497


What are you working on, /g/?
>>
File: FizzBuzz.png (13 KB, 578x461) Image search: [Google]
FizzBuzz.png
13 KB, 578x461
MSWLogo is literally the best lisp
>>
>>55092043
I can't get the listener to fire at all. I have the fragment inside a ViewPager on an activity and there's also a custom View for a navigation drawer on top of them. None of them seem to be consuming the click though, so I'm pretty lost here.
>>
>>55092415
First for D
>>
File: Type Iteration.png (10 KB, 568x217) Image search: [Google]
Type Iteration.png
10 KB, 568x217
First for D
>>
>apply for job at this research institute with this awesome project
>get job
>now find out that after 10 years of work nothing of note has come out of it and people are still discussing how to design the self made metamodel because UML is for little kids and we HAVE to make our own
Kill me
>>
I know there are a lot of learners lurking here.

Been studying Python for a series of months now.
Been going through Zelle's Python Programming book and some Code Wars.

Interested in moving to the next level.

Looking for people interested in some
collaborative studying- let's make it vigorous- hit me up at [email protected]
>>
>>55092436
what's the resulting assembly look like?
>>
File: 5-happy-people-thumbs-up-web.jpg (224 KB, 1280x645) Image search: [Google]
5-happy-people-thumbs-up-web.jpg
224 KB, 1280x645
Quick! post some trick/tip you know in a programming language.

Example:

in C :
 array[10] 
is the same as
 10[array] 
.

share your tips and tricks!
>>
>>55092646
I don't know, but you could instead create the entire output string at compile time and it'd just be one writeln
>>
>>55092649
https://en.wikipedia.org/wiki/Uniform_Function_Call_Syntax
>>
File: Programming Shelves.png (952 KB, 2100x1400) Image search: [Google]
Programming Shelves.png
952 KB, 2100x1400
>>
>>55092436
how do I differentiate between a method and an attribute if there's no () to methods?
>>
>>55092415
Thank you for using an anime image.

When I get home from my menial job, I'm going to read through the Scrapy documentation & write a Danbooru scraper in Python. Two more weeks in this hellhole, then I can finally quit & start my internship...We're all gonna make it...
>>
>>55092424
that's not lisp you fucking mongol
>>
>>55092691
You write an unnecessary (), or use __traits(...), or don't in the case of @attribute fields

>>55092703
It's a lisp
>>
>>55092649
in C,
10[array]
is the same as
10<:array:>
>>
>>55092717
yes its true. but what's the purpose?
#include <stdio.h>

int main()
{
int array[9] = {1,2,3,4,5,6,7,8,99};

printf("%d\n", 5<:array:>);
return 0;
}


a.c:7:19: error: expected expression before ‘:’ token

>>
>>55092714
So I need to know the implementation details of a class just to know whether something is a call that can have side-effects or a value copy that generally doesn't have side-effects?
>>
>>55092770
<: is [
:> is ]

/*<>"$4*/{ is {
>>
>>55092770
compile with trigraphs on
>>
>>55092776
You can check for the pure attribute
>>
>>55092781
its must be the pedantic flag
cc a.c -Wall -ansi -pedantic
>>
>>55092776
It's an imperative language
>>
I'm doing some small coding tasks and problems in C, mostly concerning the standard C library, system calls, threads processes and so on. This is one of the rare few courses I had that assert is used. I know what is that, and what do I use it for in a program, but is there a general rule of thumb when should I use assertions or simply check for errors myself?
>>
>>55092847
That doesn't have anything to do with knowing whether a part of a program has side effects.

Did your CS classes even cover Ada or PL/I, not to mention some more obscure languages?
>>
>>55092956
All parts of a program have a side effect on the registers and the cache
>>
>>55092848
at work we kinda do both. we use an assert macro as an if block, and that block is evaluated only if assert is true

y = 0;
safe_assert ( x > 0 )
{
y /= x;
}


kinda like this. if x is not positive, it gives an assert warning and does not execute division by zero.

not sure if this is necessary though. it is too much of an hassle and you should fix asserts anyway.
>>
>>55093014
this could be done with a monad
>>
>>55093124
What's a monad?
>>
>>55093185
Special snowflake's try/catch.
>>
>>55093185
Enjoy

https://en.wikipedia.org/wiki/Monad_(functional_programming)
>>
>>55093206
>imperative programmers actually believe this
>don't realise try/catch is a special snowflake's instance of a monad

>>55093185
return :: a -> M a
fmap :: (a -> b) -> (M a -> M b)
join :: M M a -> M a
>>
>>55093206
I programed in both java and c++. To this day I'm still not sure what try catch blocks are used for .
>>
>>55093240
Sucks to be retarded.
>>
>>55093254
Sucks to be a cunt
>>
>>55093240
...?
...!?
>>
>>55093260
:^)
>>
>>55093221
what
>>
>>55093291
exactly what I said
>>
>>55093240
they are a great way change control flow

try
{
bla bla bla
bla

if (bla)
throw BlaBlaHapenedException;

} catch (BlaBlaHapenedException e) {
do more bla bla
}

pretty clean and you didn't use evil goto s!
>>
>>55093262
>>55093254
Well I think I used it in java only, can't remeber for what though. I mean it looks like an extra precaution if some function or whatever misbehaves, but why complicate things? C doesn't something like that, why would java and c++ have something like that?
>>
>>55093341
kys
>>
>>55093313
So, it's used because instead of getting a fatal error that shuts the program down, you can allow it to continue working?

But then that error doesn't seem that fatal, so why not a regular bunch of if else statements?
>>
>>55093341
In Java you're forced to catch exceptions that do not inherit RuntimeException. It's a way of error handling. C normally uses error codes for that (which is cleaner IMO).
>>
>guy arguing that Rust was right to rename "Either" to "Result" because "Either is an abysmal API"
>>
>>55093374
Proper return types are better than error codes
If you're using C, use an enum for your errors
>>
>>55093386
On the matter of Either, I'd actually say it should be renamed on the basis that Haskell gives it various left biased operators that don't really make sense in an "Either" type
>>
>>55093398
That's only because of currying at the type constructor level, which forces things like Functor, Monad, etc. to work with the final type parameter (without a newtype mess).
>>
>>55093425
Is there no Flip type for Haskell(+GHC)?
>>
>>55093449
That would fall under "newtype mess".
>>
So I created something I think is worth sharing. What do I do?
>>
>>55093483
Share it
>>
>>55093483
Share it
>>
File: 1465700695183.jpg (80 KB, 482x424) Image search: [Google]
1465700695183.jpg
80 KB, 482x424
>>55093488
>>55093489
Which one of us got dubs?

>>55093456
The problem is the lack of gradual or dependent typing
>>
Trying to teach myself python by making a game. I'm trying to turn a dead/surrendered monster into an item you can pick up and put into your inventory but I keep getting this error

File "C:\Users\PC\Desktop\python\roguelike.py", line 330, in pick_up
inventory.append(self.owner)
AttributeError: Item instance has no attribute 'owner'

I thought owner is already defined.

 elif choice > 1:
message('The ' + monster.name +' has surrendered! ' + 'You gain ' + str(monster.fighter.xp) + ' experience points and ' + str(monster.fighter.gold) + ' gold', libtcod.orange)
monster.char = '*'
monster.color = libtcod.dark_red
monster.blocks = False
monster.fighter = None
monster.ai = None
monster.item = Item()
monster.name = 'A surrendering ' + monster.name
monster.send_to_back()


 class Item:
#an item that can be picked up and used.
def __init__(self, use_function=None):
self.use_function = use_function

def pick_up(self):
#add to the player's inventory and remove from the map
if len(inventory) >= 26:
message('Your inventory is full, cannot pick up ' + self.owner.name + '.', libtcod.red)
else:
inventory.append(self.owner)
objects.remove(self.owner)
message('You picked up a ' + self.owner.name + '!', libtcod.green)

#special case: automatically equip, if the corresponding equipment slot is unused
equipment = self.owner.equipment
if equipment and get_equipped_in_slot(equipment.slot) is None:
equipment.equip()
>>
>>55093387
along with setjmp and longjmp
>>
Any android developers lurking here?
Wanted to ask something about data persistence.
>>
>>55093341
>I prefer silent undefined behavior

Thanks DPT
>>
>>55093488
>>55093489

were? not a single person on shithub even viewed it
>>
>>55093540
I don't see it defined anywhere.

The __init__ method is the constructor where object attributes get defined. The only attribute that Item seems to have is "use_function".
It doesn't have an owner, as far as i can see.
>>
>>55093291
A monad has a type constructor M t (t is a type parameter)

A monad defines three operations
return :: t -> M t
fmap :: (a -> b) -> (M a -> M b)
join :: M M a -> M a

An alternative implementation
return :: t -> M t
bind :: (a -> M b) -> (M a -> M b)
>>
>>55093682
I'm reading up on the exception system in Java. for some reason it isn't as complicated as I remember. Maybe I didn't pay attention the first time, maybe we didn't give it nough attention in the practical classes.

I do have a question though. Lets say i make a new exception, What does it need to inherit?

Also, let's say I make a method of a a class I made throw that exception. Does it mean that the program automatically aborts? Which exceptions abort the program, and which do not?
>>
>>55093540

The Item class doesn't have 'owner' defined, you could define it like this depending on how it works:

class Item:
#an item that can be picked up and used.
def __init__(self, owner ,use_function=None):
self.use_function = use_function
self.owner = owner
>>
>>55093790
>new exception, What does it need to inherit?
You should extend Exception.

>Does it mean that the program automatically aborts?
yes, if you do not catch the exception, your program will crash

>Which exceptions abort the program, and which do not?
any uncaught exception will abort your program
>>
>>55091964

I'm not looking for a lib to bind my sepple code in JS, I'm looking for a lib that enables a program in JS or sepples to perform binary analysis on a raw binary, like IDA or radare, but I want to write a perform that automates a certain kind of analysis.
>>
>openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650
>panic: crypto/tls: failed to parse private key
REEEEEEEEEEEEEEE
What am I doing wrong?
>>
>>55093860
you can also extend RuntimeException, which does not need to be caught to compile but will crash the program all the same
>>
>>55093950
you can also extend Throwable so people who try to catch your exceptions with catch (Exception e) get rekd
>>
>>55093291
Trying to assign any more meaning to a monad is laughable.
>>
>>55093860
>>55093950
That's great, that means that I can catch an exception and continue running the program? If so, how do I make it stop running in the catch block?
>>
>>55093900
Are your key/cert decrypted and do they follow the following structure?
key.pem:
-----BEGIN RSA PRIVATE KEY-----
... key ...
-----END RSA PRIVATE KEY-----

cert.crt:
-----BEGIN CERTIFICATE-----
... root ...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... intermediate ca ...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... your cert ...
-----END CERTIFICATE-----

There's loads of guides for Go crypto/tls, by the way.
>>
>>55093898
JS is terrible at handling binary data. Sure, there are typed arrays and Node's Buffer(), but I would still not use them for anything, given a choice.
>>
File: 1405453675071.jpg (17 KB, 411x292) Image search: [Google]
1405453675071.jpg
17 KB, 411x292
Best Book for learning embedded programming on Atmel chips?
>>
>anime
Cringe
>>
>>55093291
>>55094024
Well, technically there's more meaning than just those operations; there's laws to be upheld, too.
return a >>= f = f a
m >>= return = m
(m >>= f) >>= g = m >>= (f >=> g)

Where (>=>) is Kleisli composition:
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
f >=> g = \a -> f a >>= g

It's difficult to write a Monad implementation that breaks these laws unless you're really abusing the interface.
>>
In C, how would you create a macro to zero an array that compiles with the most strict flags (-Wall -Wextra -Werror -ansi -pedantic)?
That means you can't mix variable declarations and code (including variable declarations inside a for-loop), let's also assume you can't use the standard library (no memset etc.). The only "solution" I have is with inline assembly, but that feels wrong as it's not strictly C (even though it compiles and works fine).
>>
>>55094037
what do you mean?
>>
File: 1316142607049.jpg (9 KB, 250x160) Image search: [Google]
1316142607049.jpg
9 KB, 250x160
So I found & fixed a small bug in an open source project. Should I open an issue ticket first or just commit it?
>>
File: categorised monad haskell.png (95 KB, 1463x677) Image search: [Google]
categorised monad haskell.png
95 KB, 1463x677
>>55094091
r8 my monad
>inb4 muh laws
>>
>>55094095
The way I understood is that uncaught exceptions of any kind automatically terminate the program, but if caught you can choose whether to terminate the program, or do some other action, correct?
>>
>>55094112
Maybe you should fork the project with the bug fix and then request a merge.
>>
>>55093758
all of my items are working, can pick them up and use them. I'm only getting trouble trying to turn the monsters into items on death
>>55093837
it glitches out when I try this making the player show up every tile they pass through
>>
>>55094093
I switch to a compiler with newer standard that allows me to declare variable in loops

If not I would implement memset_zero function and call that in macro
>>
>>55094048
cert.pem:
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

key.pem:
-----BEGIN ENCRYPTED PRIVATE KEY-----
...
-----END ENCRYPTED PRIVATE KEY-----
>>
having a bit of a problem with c++ here. currently learning classes and dynamic arrays.
class tut{
int size;
int* dynarray;

public:
tut(int size=0) {
this->size=size;
dynarray=new int[size];
for (int i=0;i<size;i++) dynarray[i]=i;
}


copy constructor:

tut (const tut& t) {
size=t.size;
dynarray = new int;
for (int i=0;i<t.size;i++) dynarray[i] = t.dynarray[i];
}


if i do following in main:
    tut a(10);
tut b = a;
a.print();
b.print();

result is:
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
1041
0
825494064
909128761

what went wrong?
>>
>>55094192
See, your key is encrypted, no wonder crypto/tls can't read it.
Decrypt it.
>>
>>55094223
Thanks senpai. I got it working by not encrypting the key like this:
openssl req -x509 -nodes -newkey rsa:4096 -keyout key.pem -out cert.pem -days 3650 
>>
>>55094220
your copy constructor creates an 'array' of 1 element.
>>
>>55094141
Yeah. For example, you might be conducting a multi-step, error prone process. If an error occurs at any time, you want to roll back to a safe state, tell the user what hapened, or anything else.
try { 
// error prone stuff below
openUpThePatient();
removeHeart();
addNewHeart();
sewBackPatientUp();
} catch (Exception e) {
// error recovery
Doctor.out.println("Fucked that one up!");
putOriginalHeartBackIn();
sewPatientBackUp();
notifyMortician();
}
rollPatientOutOfRoom();
Doctor.out.println("Surgery Finished");

if addNewHeart throws a HeartNotFound exception, everything in the catch block will execute. Then, everything after the catch block will execute. (Note that if rollPatientOutOfRoom() is error prone, you may need to put it in its own try-catch)
>>
File: pepe238.jpg (82 KB, 447x557) Image search: [Google]
pepe238.jpg
82 KB, 447x557
>>55094013
D E V I L I S H
E
V
I
L
I
S
H
>>
>>55092415
Going through binary, the hexadecimal. Going to write a program that converts hex to decimal.
>>
>>55094295
Hides which functions throw an exception and which don't, though.
In (imperative) languages where try-catch is considered good style it's often incredibly annoying to trace error related behaviour when the stack trace wasn't logged.
>>
>>55094295
How would I terminate the program in that catch block? How do I in general force a termination of a program in a catch block?
>>
>>55094351
Rethrow it as a RuntimeException.
>>
Does someone know a good tutorial on how to learn to code in the windows "Command Prompt" ?
>>
>>55094271
how stupid.
thank you!
>>
>>55094351
System.exit(1) will do it.
>>55094355
This will work if you dont catch the runtime exception elsewhere
>>
>>55094351
?? how you terminate your program depends on how you programmed it?

program execution (main thread & deamons) stops when you reach the end of the main() body, how you get there is up to you. or you can force exit the main thread with System.exit()
>>
>>55094351
You don't force termination. You rethrow, which will allow higher callers to potentially recatch.
>>
Rate my first C# program.
I especially need help with coding style, as i come from a Java background.
(The program takes two integers x and y, and maps them to one integer. The number is unique for each pair of integers, so different x and y will always produce a different result.)


using System;

namespace Test
{
class MainClass
{
public static long factorial(int a){
long result = 1;

for (int i = a; i > 0; i--) {
result *= i;
}

return result;
}

public static long binomial(int x, int y){
return factorial (x) / (factorial (y) * factorial (x - y));
}

public static long encrypt(int x, int y){
return binomial (x+y+1, 2) + x;
}

public static void Main (string[] args)
{
long test = encrypt (1, 1); //result = 4
Console.WriteLine (test);
}

}
}


>>
>>55094401
You shouldn't catch RuntimeException.
>>
>>55094430
It is shit. All those overflows you can get rid off and unnecessary multiplications.
>>
>>55094401
>System.exit(1) will do it.
Thank you.

>>55094355
So, just insert a line like
throw new RuntimeException();

in the catch block? What if the method in which all of this happening isn't defined to throw such a type of an exception?

Also, are there exceptions that even if caught will still crash your program, stuff like segmentation faults and so on.
>>
>>55094478
I catch RuntimeExceptions on the daily, deal with it
>>
>>55094541
comment sudoku
>>
>>55094577
>So, just insert a line like
Like this:
throw new RuntimeException(e);
>>
It is safe to call a method in the constructor on C++?
>>
I use DP audio and connect my headphones to the monitor's audio passthrough port. This works fine, but OS X doesn't support volume control for GPU audio, and my monitor's volume control is awful.

Fortunately the tool ddcctl can talk to the monitor to set volume (and backlight brightness/others). It's inconvenient to tap out a CLI command just to tweak the volume, so I made a tiny GUI that just shells out to ddcctl.

Hacky, and not at all impressive, but I'm happy to have solved my problem.
>>
>>55094719
yes? why wouldn't it be
>>
>>55094719
Ye
I remember in my Java class using set() methods in the constructor
>>
>>55094719
It's not safe to use C++.
>>
lseek doesn't seem to care if you seek past the end of a file. So, if I do just that, and read from that position, where the hell am I reading from? somewhere on the disk, somewhere from the memory?
>>
>>55092415
Is it a good idea to use a regex library (PCRE) with C ? I will not use them for complex things (I'll use Perl instead).
>>
>>55094880
what do you want to use regex for?
>>
>>55094846
http://files.cnblogs.com/files/egret-island/the_linux_programming_interface.pdf
Look for lseek() in Chapter 4, should explain it
>>
> The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.
>>
if (condition)
{
method();
}
>>
>>55095168
No.


PROTOTYPE function_name(parameters)
{
if (condition) {
method();
}

// function body

}

>>
>>55092415
Getting there!

C# to Javascript without needing a single extra library file (which all current translators seem to need atm)

Purpuse if to translate to native javascript variants without proxy code on client side
- Say new System.DateTime becomes new Date;
>>
so lets say I have a string in java that is either "test" "5" or "false", is there a way to test if a string is also something else (in this case a number or a bool)? like, not only check for one type but for every datatype if that makes sense?
>>
>>55095264
I doubt so. Why are you asking suck a question
>>
>>55095303
Well, I get string values via the command line and need to insert them into bool/int/whatever variables
>>
>>55095327
what is wrong with checking them seperately?

if bool
insert to bool
else if int
insert to int

etc
>>
>>55095351
because the user can declare them how he wants (think of a database table where the ID is an int and the name is a string), but it will probably have to come down for that
>>
>>55095372
Then use the declaration to determine the type.

Otherwise, your application frontend should be able to differentiate somehow, much like selecting a data type for a column in SSMS.

What you're asking is silly, and shouldn't be handled by arbitrarily deciding which type you'd be most likely to stick it into.

If it's truly open-ended, then set up a series of checks ordered by priority, like the other anon said. Start from smallest to largest datatype.

Can I represent this value in one bit?
Can I represent this value in one byte?
Two bytes?
etc.
>>
show me some of your best code pls
>>
>>55095417
10 GOTO 10
>>
>>55095417
while (1) malloc(1); /* leak all the memory */
>>
>>55095417
>,[>,]<[.<]
>>
File: be6.jpg (13 KB, 224x216) Image search: [Google]
be6.jpg
13 KB, 224x216
>>55092436
>garbage collected
>>
>>55095417
This is a function to print odd numbers from 1-100, utilizing Microsoft SQL Server 2012™ as the computation engine.

static void PrintOddNumbersVerifiedByMicrosoftSQLServer2012()
{
SqlConnection thisConnection = new SqlConnection(@"Data Source=localhost;
Initial Catalog=default;
Persist Security Info=True;
User ID=user;
Password=B1GT1tti3z");
thisConnection.Open();

string Get_Data =
@"DECLARE @start INT = 1;
DECLARE @end INT = 100;

WITH numbers AS (
SELECT @start AS number
UNION ALL
SELECT number + 1
FROM numbers
WHERE number < @end
)
SELECT *
FROM numbers
WHERE number % 2 <> 0
OPTION (MAXRECURSION 0);";

SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;

SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
var ayy = dt.AsEnumerable().ToList();

foreach (var number in ayy)
{
WriteLine(number.ItemArray[0]);
}
}
>>
>>55095417
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
_, (lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
chr(___ % __) + _(_, __, ___ // __) if ___ else
(lambda: _).func_code.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(lambda _, __, ___: _(_, __, ___))(
(lambda _, __, ___:
[__(___[(lambda: _).func_code.co_nlocals])] +
_(_, __, ___[(lambda _: _).func_code.co_nlocals:]) if ___ else []
),
lambda _: _.func_code.co_argcount,
(
lambda _: _,
lambda _, __: _,
lambda _, __, ___: _,
lambda _, __, ___, ____: _,
lambda _, __, ___, ____, _____: _,
lambda _, __, ___, ____, _____, ______: _,
lambda _, __, ___, ____, _____, ______, _______: _,
lambda _, __, ___, ____, _____, ______, _______, ________: _
)
)
)
>>
>>55095529
for python2
>>
>>55095529
what does it do
>>
>>55095548
>>55095529
Hello world!
>>
I'm just learning python and this is killing me right now

print ("How many grams of fat did you eat?")
fat = int(input())
print ("How many grams of carbohyrates did you eat?")
carbs = int(input())
print ("Calories from fat: ")
import fatCalc
print ("Calories from carbohydrates: ")
import carbsCalc

def fatCalc():
fatCal = fat * 7
print (fatCal)

def carbCalc():
carbsCal = carbs * 4
print (carbsCal)


Why is it telling me that there is no module named fatCalc when it's defined right fucking there? Moving it above doesn't help and from my understanding it shouldn't matter, I'm stumped
>>
>>55095504
var ayy = Enumerable.Range(0, 100);


Way to go enterprice there kid ;^)
>>
>>55095580
>import fatCalc
Look at this line and think about how functions work
>>
>>55095571
didn't do anything
>>
>>55095609
am I missing parentheses?
>>
https://katieconf.xyz/
>>
I need some advice.

I have a PostgreSQL database which has a table named "gallery_image". It contains all the images pertaining to a particular gallery.

Periodically, I have tasks that query various API's to retrieve images I want to fill it with. This is the part that is giving me trouble.
While inserting it into the table "gallery_image" is a very simple task, I want to manually check them first and approve their insertion.

Now, you might think:

>so, what, that's easy m8. Just insert them into the table and tick a booleanfield for visibility, and process the invisible ones. Delete if you don't want, set field to true if want.

but here's why I don't do that: I don't want to litter the "gallery_image" table with potentially unwanted images. I only want to insert into this table when I know I want something in there.

I'm using python (Django), and have celery, redis and rabbitmq set up.
>>
>>55095580
fatCalc is a function
you call functions like so:
function()

not
import function


because importing is for modules, not functions.

to fix your code: replace "import fatCalc" and "import carbsCalc" with "fatCalc()" and "carbsCalc()" AND define the functions before you do anything, or else it'll tell you they don't exist
>>
>>55095580
fatCalc is not a module, it's a function.
Buy a programming book and learn what's what
>>
>spend an hour ironing out a bug
>misspelled a variable
time well spent
>>
>>55095644
>>55095630

ffs my professor calls modules functions and vic versa
>>
>>55095629
Process them before inserting them then?
I'm not sure why you have to save them immediately, but if you want to manually look over them or something, you could set up a second database and save them there first for processing, then when approved save them in the original database while deleting the not-approved ones
>>
reminder that people like this https://twitter.com/gizm0_0 exist
>>
>>55095670
That is why you shouldn't use python. I am happy that you learned your mistake
>>
>>55095628
What the was point of this?
>>
>>55095630
well the problem calls for you to make a modular program to calculate the calories, how would I make those modules and not functions?

I keep reading that you just define it and call it with def and import
>>
>>55095685
Because artists and providers of content are fickle, fickle bastards.

They may upload something one hour, and then decide to delete it the next. Someone else might delete it or get it deleted. If I can get hold of it, I need to save it from the clutches of the chaotic and self-destructive web.

A second database seems like a whole load of work, don't you think?
>>
>>55095730
katie stronk and individual
>>
>>55095417

#include <unistd.h>
int main(){int a,b=sysconf(_SC_NPROCESSORS_ONLN);for(a=0;a<b;a++){if(fork()==0)break;}for(;;);}
>>
>>55095417
print ("Python is the best programming language in the world")
>>
>>55095417
instance  Monad Maybe  where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
>>
>>55095629
>I'm using python (Django), and have celery, redis and rabbitmq set up.
lol, you had me up to here
>>
>>55095670
This is why you use statically typed languages.
>>
I'm trying to get a program to write out with just printf to both a file and to the standard output. I can make it rerout into the file, but I can't make it write to stdout again. can anyone tell me where I'm mistaken?
int main(){
int fd;
int d_stdout;

fd = open("out.txt", O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
if(fd == -1)
errExit("open out");

if((d_stdout = dup(STDOUT_FILENO)) == -1)
errExit("dup");

if(dup2(fd, STDOUT_FILENO) == -1)
errExit("First dup2");

printf("Writing from process %d\n", getpid());

if(dup2(d_stdout, STDOUT_FILENO) == -1)
errExit("Second dup2");

printf("Finished writing into the file\n");

if(dup2(fd, STDOUT_FILENO) == -1)
("Third dup2");

printf("Writing into the file again\n");

close(fd);
return 0;
}
>>
print ("How many grams of fat did you eat?")
fat = int(input())
print ("How many grams of carbohyrates did you eat?")
carbs = int(input())
print ("Calories from fat: ")
import fatCalc
print ("Calories from carbohydrates: ")
import carbsCalc

def fatCalc(fat):
fat * 7
print (fatCalc)

def carbsCalc(carbs):
carbs * 4
print (carbsCalc)


Ok so how do I make these modules and not functions? The problem is clearly asking for you to create a modular program by breaking up the fat calculations and carb calculations into seperate modules to be called. Everything I'm reading says this should work by defining the modules with "def" and importing them with "import"

If these are functions and not modules, I don't know, I am so lost
>>
>>55092436
Jai did it better :^)
>>
question from a noob.

i'm learning C and strings ans i use strcmp to compare strings.

Does google use strcmp when i log in my google account? like, i put my password, and whey will do a strcmp(password_i_typed, my_real_password)

or they use a sophisticated method?

thanks guys!
>>
>>55096111
you literally put a.py in your directory, go to another .py in that directory and say "import a"

then u can reference functions by using a.function(32)

it's pretty hard to do it wrong
>>
>>55096133
Google doesn't know your password.
They run your password string plus additional text through a cryptographic hashing algorithm and store that.
Whenever you provide your password again they run it through the same algo and if it matches their hash, then your password matches.
>>
>>55096159
trust me we aren't doing file imports yet, this teacher is pretty shit and calls things interchangably. This has to be a single internal program, so if he means a modular program with FUNCTIONS how would I fix this?

It's pretty clear that he wants a "module" or whatever, defined after the main module and called up.
>>
>>55095417
print $$ /0;        # a legit division by zero

^....some.....^
^....black....^
^....magic....^

|(?{m}(?{"\[\[\)
\.\\\|\`\]\[\[\{
\[\.\@\/\(\^\.\[
\{\;\\\,\[\@\:\?
\+\^\)\("=~s\}[\
\s]\}\}rg^"\+\)\
\@\@\(\^\*\(\(\/
\[\:\@\/\[\@\;\\
\{\+\^\.\@\{\(\[
\\\@\;\[\"\""=~s
\}\s\}\}gr\})},s
\/\/$^R\/esex})|

^....hugs....^
^.....&......^
^...kisses...^

//
//xo//xo//xo//xo//xo//xo//xo//
//
>>
>>55096230
you are having someone TEACH you python? Hahahahahahaha
>>
>>55096133
Yes, but this anon is right. Your password might be 1234, but google has it saved as "a45f9jwk49jrfi4599485jasfa" because it gets hashed before its stored. Hashing is very difficult to reverse, so if someone broke into google's databases, they wouldnt know your password, just the hashed version. When you send a password up to google, they hash it first, then do strcmp on the hash you sent vs the hash they have on the database. Its a bit more secure that way.

>>55096230
>this teacher is pretty shit and calls things interchangeably
you're boned, send the prof an email to clarify what he means. you need to be on top of his terminology, force him to clarify or you're be very confused.
>>
>>55095774
this is a fork bomb right
>>
>>55096014
why?
>>
>>55096230
I know you are trolling because a university professor wouldn't teach python, at least not unless you were taught a more "proper" language first
>>
>>55096014
The problem is very stupid "I dont want my table to have these rows because ????," the solution is very simple "create a staging table that has rows before processing or use views" and then you vomited out a series of technologies that are unrelated to the problem or any situation at all.

You probably want to bolt mongodb to your tech stack as well.
>>
>>55096298
in my college they teach,
1 - python
2 - C
3 - Java
4 - C++
5
>>
File: 198271937.png (564 KB, 496x746) Image search: [Google]
198271937.png
564 KB, 496x746
>>55096298
>you're lying about taking a python course
>>
>>55096325
most real universities would start with java
>>
>>55095529
>>55095548
>>55095571
>>55095619
>>55095560

Explanation: https://benkurtovic.com/2014/06/01/obfuscating-hello-world.html
>>
>>55095469
>I don't know C
it doesn't leak anything
>>
>>55096500
>while (1) malloc(1);
it will alloc all the memory available instead, until the OS kills the process, right?
>>
>>55096528
not necessarily; it's just an infinite loop
>>
Cuda or OpenCL?
>>
>>55096587
I just ran it and the OS killed the process.
It also thrashed my SSD as it pushed away all my other processes into the swap.
>>
>>55096500
not sure if trolling...
>>
>>55096595
>locking yourself to one hardware
OpenCL is the only option because Cuda is not viable.
>>
>>55096632
you're an idiot
>>55096654
not sure if retarded
do you also believe that this keeps setting the value of x to 2, every time it loops?
int x;
while (1) x = 2;

do you even know C?
>>
>>55096745
>do you also believe that this keeps setting the value of x to 2, every time it loops?
yes
>>
>>55096745
>do you also believe that this keeps setting the value of x to 2, every time it loops?

Yes I do. Here's the assembly output of your code:
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
.L2:
movl $2, -4(%rbp)
jmp .L2
.cfi_endproc
>>
>>55096745
The compiler can't elide the call to malloc though. It's an external function which could have any number of unknown side-effects.
>>
>>55096745
10 GOTO 10

I bet you faggot think this will cause an infinite loop
>>
>>55096802
that explains your confusion
>>55096832
>Here's the assembly output
C has no assembly output, that's the output of a compiler; I can show you the output on my compiler:
main:
.L2:
jmp .L2

>>55096850
>can't elide the call to malloc
it can
>an external function
no, it's a standard function, defined in the C language standard
>could have any number of unknown side-effects
wrong
>>
>>55093185
Just a monoid in the category of endofunctors, jeez, kids these days.
>>
>>55096850
It does not even matter what compiler does. C language is very specific about that code and it should set x to 2 on each iteration.

If my custom compiler sets it to 3 instead of 2, that wouldn't make "In C, that code sets x to 2 on each iteration" statement false.
>>
>>55096271
Not really.
It forks into as many processes as processors you have and then just wastes all CPU.
A fork bomb would as simple as
int main(){for(;;)fork()}
>>
>>55096866
>that explains your confusion
you are only one that is confused here mate. you thing compiler optimizations = C. C does not tell anything about what can be optimized. If a compiler optimizes things and break compatibility on a visible way, that it is not compiling C.
>C has no assembly output
If you are not talking about optimizing compilers, what are you talking about? C standard tells us x is set to 2 on each iteration of that loop. why are you arguing otherwise?
>it can elide malloc
it can't. malloc has eventual system calls that asks for memory. It can not optimize those side effects away.
>malloc is on clib only
C standard does not say anything about malloc having no side effects. If it does an implementation, it can't be optimized away
>could have any number of unknown side-effects
but it does you retard
>>
>>55096866
It was a proof by counter-example. There exists a standards-compliant compiler that will "keep setting the value of x to 2". Hence your tacit claim that copy elision will necessarily take place is incorrect.
>>
>>55096977
that wouldn't work because you're missing a semi-colon
>>
>>55096983
>malloc, a function that literally returns different values for same set of inputs has no side affects.
lel, get a load of this retard
>>
>>55097010
This was for >>55096866
>>
File: 1432420144038.png (3 KB, 251x249) Image search: [Google]
1432420144038.png
3 KB, 251x249
This is an advice for all anons learning to program

PROGRAM EVERY DAY, even if it's stupid shit

if you don't, consequences will be extremely painful for you

source: me right now
>>
>>55096995
>proof by counter-example
say what? the claim "X will do Y" (will, not might) is proven by giving an example of X doing Y? that's how your logic works? no, my dumb anon, that's not how you prove something; one instance of X NOT doing Y is a "proof by counter-example" of the falsehood of "X will do Y"
>There exists a standards-compliant compiler
that doesn't prove the statement "this WILL keep setting the value of x to 2", you dumb shit
>tacit claim that copy elision will necessarily take place
>necessarily
I said no such thing
>>
File: QDwH2x0.png (79 KB, 282x386) Image search: [Google]
QDwH2x0.png
79 KB, 282x386
> Tfw this is the Java Ecosystem

https://www.youtube.com/watch?v=CRUa_09IOVU
>>
can I somehow pass variables as arguments to a function say via a for? so like I have i=2 and it calls a function like func(xyz, 1, 2) and with i=3 func(xyz, 1, 2, 3)?
>>
>>55097068
>weapon of durgasoft
lel
>>
>>55097098
with template metaprogramming, yes
>>
>>55097098

replace the last number with i
>>
>>55096983
>compiler optimizes things and break compatibility
eliding malloc doesn't break anything as far as the C standard is concerned
>C standard tells us x is set to 2 on each iteration of that loop
it also tells that it can be elided
>it can't. malloc has eventual system calls
there are no system calls in the C standard
>It can not optimize those side effects away
there are no side effects to malloc in the C standard
>C standard does not say anything about malloc having no side effects
doesn't say anything about malloc having side effect either
>If it does an implementation, it can't be optimized away
why not? the implementation knows better than you
>>55097010
>lel I'm a html programmer!
fuck off, kids should not witness rapes of this magnitude
>>
>>55097144
>>55097148
>>55097098
forgot, the language is java.
I basicly want to pass i variables to a function. dunno if this is even possible
>>
>>55097046
seconded, this is the only way to git gud
>>
>>55096850
>can't elide the call to malloc
>>55096983
>it can't. malloc has eventual system calls
>>55097010
>lel
here's your BTFO, webshits: https://godbolt.org/g/CmediY
>>
>>55097166
>it also tells that it can be elided
please enlighten us where it does say so
>>
>>55097098

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {
myFunc(arrayTo(i));
}

}

private static int[] arrayTo(int x){
int[] a = new int[x];
for (int i = 0; i < x; i++) {
a[i] = i;
}
return a;
}


public static void myFunc(int... a){
System.out.println(a[1]);
}
>>
>>55097226
didn't know gcc.godbolt.org was the new standard
>>
>>55097265
>I didn't consult the aliasing tards
anon...
>>
>>55097098
>>55097194
Have you heard of "arrays"?
If they aren't what you want because they have a fixed size, there's something called an ArrayList (look it up), it's basically an array but without limit
>>
>>55097265
>system calls
>standard
it's like you're mentally ill
>>
http://github.com/deeepaaa/hachidori
>>
>>55097310
no way what is that.
anyway, I finally figured out the name of this shit (varargs) and apparently I can just pass an array because its basicly the same. yay.
>>
>>55097344
> run Hachidori.sh
the file doesn't even exist
>>
>>55097422
You're supposed to download the release package, it's there.
>>
>>55097485
no it's not.
>>
Sorry guys here's the full code.

#include <stdlib.h>
#include <stdio.h>

#undef malloc
#define malloc my_malloc

static void *my_malloc(size_t size)
{
void *mem = malloc(size);
printf("Allocated %p\n", mem);
return mem;
}

int main(int argc, char *argv[])
{
while (1) malloc(1); /* leak all the memory */
return 0;
}
>>
>>55097522
MY FAULT.
thank you for pointing it out, it's actually in the wrong folder

move it from ./resources/app/ to ./ and you're good to go
>>
File: ss+(2016-06-16+at+12.35.34).png (3 KB, 299x135) Image search: [Google]
ss+(2016-06-16+at+12.35.34).png
3 KB, 299x135
help, how do I make my table more cool looking?
>>
>>55097568
>Sorry guys for getting rekt hard
>here's some damage control
:^)
>>
>>55097803
count the id in hexadecimal
>>
>>55097841
that will probably look cool yeah, ill think about it. but I was more refering to the layout itself. I think it can look better than the standard ----+----
>>
Why the hell does this keep coming back as 0% for both?

print "How many males are in the class? "
males = int(input())
print "How many females are in the class? "
females = int(input())
classTotal = males + females
percentMale = males / classTotal * 100
percentFemale = females / classTotal * 100
print "Your class is %", '%.2f'%percentMale, "male and %", '%.2f'%percentFemale, "female."

input()
>>
>>55097980
int / int, cast one to float like

percentMale = float(males) / classTotal * 100
>>
>>55097980
Integer division. Cast the numerator or denominator to float.
>>
>>55097980
males / classTotal * 100

if males = 27, classTotal = 30
the result is 0 and you're multiplying 0 by 100 which is still zero.

look up integer division
>>
>>55098015
>>55098029
>>55098030

danka
>>
File: aleph.png (120 KB, 1284x977) Image search: [Google]
aleph.png
120 KB, 1284x977
I'm writing an RSS/Atom aggregator in Common Lisp. Just implemented RSS 1.0 support so I can follow Debian's shitty security feed.

>security update
t-thanks
>>
File: ds_shit.jpg (40 KB, 600x600) Image search: [Google]
ds_shit.jpg
40 KB, 600x600
>>55098149
>Anime News Network
>>
>>55092415
>What are you working on, /g/?
An expense tracker. I know it's trivial, and there are a lot of options out there, but they all seem overly complicated to me. I am never going to record all my expenses if I always have to fill out a huge form for each one.

Right now working on syncing the data to firebase, so I have a backup.
>>
>>55098199
Is there a better English source for chinese cartoon news?
>>
>>55098225
What's wrong with a ledger?
>>
>>55098228
/a/
>>
>>55092415
>>>/a/ you fucking piece of shit. Kys.
>>
>>55098249
Nothing. That's pretty much exactly what this is, plus a few pretty graphs and shit.

A physical ledger I would lose or forget at home. I pay 80% of my stuff cash, so I can't rely on the bank to tell me what I spent my money on, either.
>>
>>55098293
Why don't you just use an excel document?
>>
Best PERL resources?
>>
>>55098347
Find them yourself you incompetent fuck
>>
>>55098355
Fuck off you filthy pedo. Kys.
>>
>>55098365
I'm looking for recommendations from people who know more than me you autistic prick.
>>
I used to think it was just one hime poster, but now I'm not so sure.
>>
>>55098311
UI improvements, mostly, like loading faster on mobile than a google sheet (and works offline).

Also, this app "learns" about your transactions to make it easier and faster to input stuff.

So, if e.g. you often order Pizza for $25, next time you enter "P" it will suggest the autocompletion to "Pizza" and, if you select it, fill in the amount ($25) and category (Eating out) automatically.

I suppose you could do that in Excel, too, but at that point you are programming anyways, so I might as well roll my own thing.

It has been a learining experience, too (don't use floats for money).
>>
>>55098259
Sure, but the signal/noise ratio on /a/ is too poor to be of any use with an aggregator. I do plan to support aggregating threads on various chans eventually though.
>>
File: 1465164586016.jpg (151 KB, 920x642) Image search: [Google]
1465164586016.jpg
151 KB, 920x642
>>55098382
TRIGGERED
>>
>>55098403
>being so incompetent you can't even do a google search
Why are you even here you autistic prick.
>>
>>55098430
>Google search
Yeah, okay I know that gives me literally every shit thing out there.

I wanna know whats the /dpt/ approved shit you fucking retard.
>>
>>55098418
>
So, if e.g. you often order Pizza for $25, next time you enter "P" it will suggest the autocompletion to "Pizza" and, if you select it, fill in the amount ($25) and category (Eating out) automatically.

Doesn't quicken do that for you?
Or literally any ledger software?
You don't have to reinvent the wheel for this sort of drudge work.
>>
>>55098472
Go sit on your moms dildo.
>>
>>55098456
I have yet to see a single piece of non-trivial software written by a cute programmer.
>>
>>55098472
>this level of autism
I DECLARE YOU SUPER AUTISMO REDDIT KNIGHT

>>55098429
Kys
>>
Simultaneously reading through the Dragon book and practicing D by translating the code from Java to D
Not much of a challenge, but gives me a chance to look at some of the minor details of D
>>
File: 1443025838297[1].jpg (138 KB, 560x480) Image search: [Google]
1443025838297[1].jpg
138 KB, 560x480
>>55098488
Thread replies: 255
Thread images: 28

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.