« first day (1552 days earlier)      last day (2761 days later) » 

00:00
RELOAD! There are 4235 unanswered questions (90.8337% answered)
-1
Q: Readability of array_* vs foreach in PHP

Greg BellWith functional programming all the rage, I feel I should be using PHP's array_* functions more. But when I compare these two identical implementations, I can't help but think foreach is more readable. Am I just being a dinosaur? (The foreach implementation takes 1/4 the time, but performance ...

00:54
0
Q: Procedural function for prepared MySQL statements in PHP

bartI'm refactoring procedural code, switching to prepared MySQL statements using mysqli_query(). I do understand writing OO would be better, but it's out of scope for this task. Use the below function as follows: list($result, $numrows, $err) = my_mysqli_stmt($db_handler, $query, $params); Return...

01:25
0
Q: PowerShell SharePoint CSOM Folder Class and Scripts

user3899725I am working on a series of scripts to be called by another application, which will keep some sharepoint site data in sync with an external database. EngagementClasses.ps1: Class EngagementFolder { [String]$siteName [String]$listName [String]$folderName [String]$managedPath = $managedPath [Str...

01:40
You might get better answers to this kind of question at codereview.stackexchange.com — ahruss 59 secs ago
02:10
possible answer invalidation by CJ Dennis on question by CJ Dennis: codereview.stackexchange.com/posts/171378/revisions
02:58
0
Q: Generates a bare git repo from existing one and copy it to a central server

marcanuyThis is a bash script that takes the name of a local git repo and a remote server host/path, generates a bare repo, and copies the bare repo to a git server located in another server. Example: centralize-git-repo.sh arepo user@gitserver:/srv/git It generates a folder in server:/srv/git/arepo....

0
Q: Angular 2 Ngrx/Store and Ngrx/Effects example

Sarang ShindeI am new to angular 2 ngrx and built simple application to understand NGRX/store and NGRX/effects: My app.Module.ts file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MainActionReducer } from './actionreducer'; import { StoreModul...

0
Q: Find the minimum value of an array with an odd index

Aleksey BudaevI found odd indexes, but how to find the minimum value from the found indices? I've tried all the controlling operators, but without success. class Data { static void Main() { int[] arrayOne = { 2, 1, -2, 8, 9, 100, 11, 19 }; int z = 0; int [] arra...

03:14
I'm voting to close this question as off-topic because it's not about a programming problem; it's a request for code review. Please read about How to Ask questions here. — Ed Cottrell ♦ 17 secs ago
03:25
@Duga it's fine
BTW.Monking
03:46
0
Q: Character-based transitions (part of a lexer)

CAD97As part of my prep for the CODE REVIEW community-challenge (which looks like it will be Write your own programming language), I've been working on an LL(1) lexer generator in Rust. Yes, lexer generators exist already, and full-on lexer/parser generators as well. My time might've been better spen...

04:17
Monking
Nice, silver .NET badge
0
Q: Java split a string into ArrayList

hadesI want to split the following String into java ArrayList "[\"1-72\",\"1-111\",\"1-4\"]" I had wrote a very rough solution but not sure how to enhance it: String sample = "\"[\"1-72\",\"1-111\",\"157f9d3dfb4-4\"]\""; sample = sample.replaceAll("\"", ""); //to replace double quote ...

05:05
0
Q: My first experiments with writting Angular 2 service

Minor ThreatI have to write a web interface for one of my homebrew projects. Since I'm not familiar with HTML and CSS I've decided to take heavy duty framework such as Angular 2. This is my first experiment - I'm uploading a batch job to a remote servlet with POST request, get tracking ID and start polling t...

05:45
possible answer invalidation by Sam on question by Sam: codereview.stackexchange.com/posts/171769/revisions
06:07
You want to post this on Code Review, to get feedback on any/all aspects of your code and get tips for improving readability, maintainability, performance, etc.. Stack Overflow is for more... specific questions. — Mat's Mug 24 secs ago
possible answer invalidation by Sam on question by Sam: codereview.stackexchange.com/posts/171769/revisions
07:23
0
Q: How to create hiearchial tree structure using array of objects

anivaishuI have a complex json file that I have to handle with javascript to make it hierarchical, in order to later build a tree. Here is my array. var C=[ { "id": 57, "name": "Breaded Chicken Items", "slug": "breaded-chicken-items", "parent": 55, "descri...

0
Q: C# .net webpage LogReader class - Parallel DNS for computers IPs and domains from log scrape

BrunoThis is a namespace to read a bunch of events from a log file and display them in a table on a webpage, some additional data (computer domain and IP address) is also pulled in from DNS. I am mostly interested in the DNS parts as they are the modifications I made to someone else's code to change t...

07:51
I realise now this site is stackoverflow. I was thinking it was codereview.stackexchange when I wrote this. — bdsl 10 secs ago
0
Q: shovelling snow solution not passing in Kattis

GaborHere is the problem: https://open.kattis.com/problems/shovellingcost I don't understand the test case they provide: oooooooo ...ooooB oo#o#### Co#ooooo oo#ooDoo oooooooo ooAooooo oooooooo How is this solvable in 11 steps? To me, it's 12: oooooooo .......B .o#o#### Co#ooooo .o#..Doo ....oooo o...

0
Q: Parsing server request data for visualization in C3.js

omgimanerdThe following is a snippet from a script I have that fetches a list of objects representing requests to a server and graphs them using C3.js. I've only included the relevant code that parses the list of request objects for relevant data. const iterByDay = (min, max, callback) => { var tmp = mo...

Kaz
Kaz
Monking @all
Monking @Kaz
08:10
@CodeCaster thank you for your response and code review notes, but there is a row and the value of the boolean column WanLineDiscconection is false, hence IsExist value is false (not null) and it is the expected result of the query, the problem is inside GetWanLineDisconnectionData() method: the condition (IsExist == null) treat it as null and not as false like it should be and the if block is executed (and it should not be excuted) , i know that sound strange, i have tested it a few times and i cant understand why. — jonathana 11 secs ago
08:26
Monking
Monking
0
Q: Removing duplication in similar methods

user1472672I have two methods which are very similar apart from the method call inside and the return type. I wondered if there was a way to make it neater, I.e not duplicate the boiler plate connection code? I considered putting a flag in the method signature to switch, something like isMultiple but in the...

0
Q: Tiny DBMS in Java

coderoddeIntroduction For my purposes, I have written this simple database management system, that can do the following: Support of 7 data types: int, long, float, double, boolean, String, byte[], manipulating columns, saving the entire database into a file and reading it later into main memory. And ...

0
Q: Division turn into index in this Calculator

Dani ChengFor this simple calculator that turns infix into postfix and then solves it... Why does "/" turn into "^"? e.g. 8.0 / 2 gives an answer of 64 (8^2)? import java.util.*; public class Calculator{ private boolean isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c...

08:54
I'm voting to close this question as off-topic because questions asking to review working code should go to codereview.stackexchange.comGhostCat 17 secs ago
I don't understand people mentality. When i put no code than i get comments show us what have you tried. Now i put something so you are saying not here because its part of code review. Free world :) — Saurabh Kumar 58 secs ago
maybe this should be posted at codereview.stackexchange.comjosh 39 secs ago
0
Q: Is it good way to parse string data like follow in java

Saurabh KumarI have a complex strings like following. $company=>Company(code->MyCompany) $brand=>Brand(code->Brand_1, company->$company) and than i prepare objects out of them as follows Macro [key=$company, type=Company, map={code=MyCompany}] Macro [key=$brand, type=Brand, map={ company=$company, code=B...

Unrelated: this is not a new strategy. It was nothing but feedback telling you that there is a better place for code reviews. Note for example that you didn't receive any downvotes on your question. So please consider that your complaints were neither helpful nor constructive. — GhostCat 23 secs ago
09:20
0
Q: Finding unused dictionary entry

ReviousThe developer before me implemented the code as it follows: Dictionary<string, object> parameters = new Dictionary<string, object> { {"Logo", CouponPrintHelper.GetLogoContent()}, {"CurrencyFormat", Coupon...

09:39
0
Q: Resetting a password

PremI am trying to reset a password when password_reset_token is received in the controller. But it's becoming a long if else ladder of many conditions. Can it be reduced in a better way? def set_new_password if params[:password_reset_token].present? @user = User.find_by(password_reset_tok...

0
Q: Returning multiple values on the basis of size of list

TarunI am using TestNG Data Provider and constituting following data set depending on the elements in the list. Offer list would have either one or at-most 2 elements and I would like to test with all of the available elements, along with one extra data value which I always test with - private Object...

10:11
0
Q: Refactoring code in order to deal with response error through Dynamic Proxy API

Lorenzo BI have a bunch of operations that communicate with a gateway. These operations can be invoked with a request and they return a response. // MovieOperation.java public MovieResponse getMovie(MovieRequest request) { if (!requestValidator.validate(request)) { return new MovieResponse(bu...

10:43
-1
Q: My first Symfony App - todo list

demotywatorkingThis is my first Symfony 3 application. Please someone review my code. I do not want to make same mistakes, errors etc. in next project. To-do-list

11:00
I can't help but notice that time starts lower case, while Amount starts upper case. And "amount" is not exactly a meaningful variable name. What's wrong with something like costPerHour (or cost_per_hour)? Believe me, when you come back to your own code in a few months time, you will not understand it, if you have variable names like that (surely you can think of something better than time too? What kind of time id it? billableHours, hoursWorked, something like that. You might lean a lot if you post some of your code to codereview.stackexchange.comMawg 32 secs ago
MOnking
hey guys. Is it only my icons getting messed up?
the SE icons seem to be wrong and misplaced in almost all cases
@Incomputable Page and where?
@Peilonrayz, anywhere on SE
code review icon shows up as CF
I feel like I should start worrying. Though I didn't visit any new sites in past month
Looks fine for me, try ctrl-f5
11:14
@Incomputable I have troubles rendering profile pics on the chat since ages
It seems to get better recently
It may or may not have to do with having 1100 tabs open though
I suppose that's not the case for you
@skiwi yeah, my problem seems different
@skiwi I have that due to PB, and only affects users that use Facebook for their pictures.
@Peilonrayz didn't work. I'm on chrome, by the way
@Peilonrayz PB?
@skiwi Privacy badger
@Incomputable I checked on Chrome and didn't get it...
11:17
@Peilonrayz Ah okay, AdBlock Plus might also play some role here
does anyone play dark souls 3? There is a glitch which allows players to invade hosts when they are in the boss room. Pretty fun when it is 4 players vs boss + 3 enemy players
0
Q: WebApi2: Error handling in a REST API

evictednoiseI have implemented a small REST API using WebApi 2 and NHibernate for ORM. When non-existent id is supplied, NHibernate will throw an InvalidOperationException. So I thought I would rethrow a custom exception and then handle all the error logging and returning (there is some logic to different e...

@Peilonrayz I get the malfunctions periodically, though once in 4-6 months
probably some hidden bugs inside of chrome or SE
@skiwi Maybe, mine only affects Kaz and Dan's pictures, so if that's the case for you then it may be be the same thing
11:31
0
Q: Creating a logger that wraps around winston and express-winston

NewtonCodeI am trying to create a logger wrapper around winston and express-winston (enables middleware error log) that is configurable . How could i improve this code? //logger.ts import * as winston from "winston"; import * as FileSystem from "fs"; import AppConfig from "../config/app/appConfig"; impo...

possible answer invalidation by Tarun on question by Tarun: codereview.stackexchange.com/posts/171962/revisions
@Peilonrayz It's different people, but usually the same
@Incomputable I'd like to keep my computer and controller and screen in one piece, so I don't play it
@Duga its ok just fixed a typo
@skiwi the 3rd game in the series should be easier, at least according to statistics. I thought lags were a feature of the game, I was so wrong... It turns out that Bugs are actually feature of the game
you can dodge bleed damage, frostbite damage. Block lava damage, while standing on it, lol
@Incomputable wat...
I mean ... sure. but wat?
I found the third hard to play, because my PC just doesn't have quite enough punch
but it's somewhat more upfront than the first and I like it better than the second.
11:46
@Vogel612 that was at the start, now it is fine
Kaz
Kaz
Adblock is starting to fail these days. I'm getting ads I didn't used to. Can anyone recommend a good alternative?
@Vogel612 my caestus damage on enemy got delayed for 12 seconds. Then they all registered once. That was hilarious
@Kaz Usually you get good results from just using ScriptSafe or related
0
Q: How can I make this algorithm more efficient? - Calculating sum of numbers in the fibonacci sequence between two specific points in the series

EnzioQuestion This is an assignment for a Coursera course. This is the algorithm I wrote. import java.util.*; public class FibonacciPartialSum { private static long getFibonacciPartialSumNaive(long from, long to) { if (to <= 1) return to; long prev = 0; ...

animation was like he is been shot from machine gun
11:55
Greetings, Programs.
Greetings, User
@syb0rg Looks like good stuff, I'll see if I can write a Roman numeral problem in Python and check it with Hypothesis. Should be a nice test.
Quite far down on the priority list though...
@Kaz uBlock origin.
That question also needs another close vote by the way.
possible answer invalidation by Sam on question by Sam: codereview.stackexchange.com/posts/171769/revisions
document.evaluate lets you use XPath, wow
12:20
0
Q: Simple grid for simple games

MarcoLucidiAs my first project in C (and also final project for CS50) I made a Tetris clone in C using the library ncurses. This is the grid I wrote for the game. I guess it could be easily reused for similar projects since I tried to make it "not Tetris specific". grid.h #ifndef GRID_HEADER #define GRID...

0
Q: Audit table schema with versioning

AmidzaI have the following schema: The version column(old_version,new_version or just version)in the table belong to a table that just has a auto increment id.And the package_exercise data is not important for now. My goal is to simplify the versions in a way that i have just for the package the ve...

0
Q: Implemented method accepts a concrete parameter instead of the interface

SamLiked question enum MessageFormat: represents all kinds of messages. (XML, JSON, custom) interface Message: represents an abstract Java Object for any kind of message. interface Schema: represents an abstract Java Object for any kind of message descriptor. Contains MessageFormat. enum SchemaF...

Working code should be posted on Code Review not StackOverflow. There is nothing wrong with how you are handling your arrays. Because j = j + 1 is present at the end of each case of your if statement, it should be moved outside of your if statement. But then again j will always be equal to i -1 and j is actually not used. — Thomas Inzina 1 min ago
12:35
0
Q: Making Anagrams

Flynn84Task: given two strings, that may or may not be of the same length, determine the number of characters you must delete to make the two strings anagrams of each other. My solution: a = gets.strip.chars b = gets.strip.chars len = (a+b).length d = [] for i in 0..a.length-1 b.each_with_index do ...

Was anyone here working with .NET Core already? I have trouble getting System.Data.SqlClient to work on .NET Core 2.0 Preview
12:54
@stijn So do I, with the same use case. It just came up during a code review. According to 7.2 and 5.2.9, it should be fine, but I would like to get a second opinion by someone else (or I cross-read the standard again at the end of the next week). — Zeta 38 secs ago
Monking.
Oh, nevermind. My comment got already dragged here by Duga.
Maybe it works now, Visual Studio is buggy at times, Preview builds are buggy, Visual Studio preview build is bugception
Monking
@skiwi Why did you install the preview version of Visual Studio?
That's just asking for trouble.
@Mast I thought I needed it to work with recent Ubuntu versions, but that may be outdated by now already
It can't hurt if it works properly though
13:07
waait... there's visual studio for ubuntu??
@Vogel612 There's Visual Studio Code I think, but that's besides the point, I'm talking an .NET Core application
@skiwi My Visual Studio has some interesting issues.
@EBrown But it's Visual Studio
I'm voting to close this question as off-topic because questions about working code belong on Code Review. — Michael just now
13:22
@skiwi I do have VSCode. It's a pretty neat text editor ... doesn't come to a full-fledged IDE yet, but it's good enough for most of the stuff..
Are you running on Linux or Windows mostly?
Linux...
so much Linux..
my windows machine is basically only for gaming / entertainment
and even there my laptop sometimes is just... more convenient
Ah, I see
I'm still mainly Windows, but I can work a bit with Linux
> Unhandled Exception: Npgsql.PostgresException: 42703: column "year" does not exist
Bashes head into wall
``var command = new NpgsqlCommand("INSERT INTO years (year, url) VALUES (@year, @url) ON CONFLICT DO NOTHING", connection);` <- It's even in the table definition, I'm not sure why it wouldn't exist
/rant
13:41
@Vogel612 What does it have that older editors like Atom don't?
I'm voting to close this question as off-topic because it belongs to codereview.stackexchange.com — CÅ“ur 48 secs ago
github.com/npgsql/npgsql/issues/1656 <- Does anyone spot anything stupid perhaps? I don't know how long I'm going to be waiting until I get a reply there
13:57
@Mast I haven't used atom or sublime text much... but I found it much less complex in a way
@CÅ“ur Doesn't mean it makes sense. You're posting a completely useless comment on an old question with a recommendation which has been proven flawed above it. The OP does have a Code Review account, so OP still wants an answer he'd have posted it by now. Utterly pointless and unhelpful comment. — Mast 54 secs ago
21, 22, 23, 24, 25, 26, 27, 28, 29, 30. Walk away from SO...
@Vogel612 I actually kinda like Atom on my Mac.
> Unhandled Exception: Npgsql.PostgresException: 55000: ON CONFLICT does not support deferrable unique constraints/exclusion constraints as arbiters
Yay, new error
14:14
2
Q: Sklearn: Regularized ridge regression for predicting fantasy football performance from several sources' projections

Eric BrennerI've been working on trying to predict fantasy performance of players in this upcoming NFL season based on projections from several experts/sources. I trained the data on projections from last year and performed cross validation using the actual fantasy points that each player ended up scoring. I...

0
Q: Pretty Printed Tables in Haskell

Philipp KienerPurpose A clean, reusable module to generate pretty tables (much like those in SQL-clients), like so: +--------+--------+--------+ | HEADER | HEADER | HEADER | +--------+--------+--------+ | CELL | CELL | CELL | +--------+--------+--------+ | CELL | CELL | CELL | +--------+--------+...

0
Q: C - Generic Binary Search Tree

NubcakeFirst post here. I'm a novice C programmer (moving onto C++ soon) and I've tried to implement a basic (search,insertion,deletion) generic unbalanced BST whilst adhering to a few OO design principles. I'm looking for some feedback and advice from seasoned C programmers on my code and style. tree...

Finally, I've got it working
14:40
I don't understand what you're asking. If you're issuing a general challenge, you should put this on the Code Golf site, not on Stack Overflow. Alternatively, if you're looking for this to be critiqued, it should go on the Code Review Stack Exchange site. If you leave it here, you'll need to ask a specific question about a specific problem with it. — EJoshuaS 8 secs ago
Few remarks : 1) this question might fare better on the CodeReview SE. 2) it seems weird to handle what is clearly a Set as a String. Using an appropriate data structure sure would help. 3) it might help (if you extend your game in the future) to have one base image over which you apply equipment masks. — Aaron 32 secs ago
15:13
If the code works properly and what you want is a code review or a better way of doing this task, you should go to Code Review and post this doubt there. — David Corral 25 secs ago
This question is more suited for Code Review than Stack Overflow. — CoryKramer 12 secs ago
If you have functioning code then this question may be more appropriate for codereview.stackexchange.com but read the faq to check if it's on-topic there — EdChum 44 secs ago
I don't think this would fit Code Review simply because there are bugs in the code. — MooingRawr 18 secs ago
15:33
0
Q: JavaScript: Cascading (dependent) dropdowns for country, state and city selection

BrunoFaccaI have written the following JS to populate dependent (aka cascading) select boxes for country, city and state selection. The backend is a Rails application, which provides the following: Object literal where each element consists of a state ISO codes and their corresponding names at /states/c...

0
Q: Specializing std::hash for std::array

Willy GoatI want to have an std::unordered_map which uses arrays as a key. As long as there's an operator== and an std::hash for a type, it can be used as a key. Here is my std::hash<std::array> template<class T, size_t N> struct std::hash<std::array<T, N>> { auto operator() (const std::array<T, N>&...

15:45
I'm voting to close this question as off-topic because it refers to working code, and therefore should be posted to the Code Review SE site. — Joe Clay 14 secs ago
0
Q: Guides the User with Prompts to go through a procedure and Records User Input

KeizzerweissI am making a prototype worksheet that follows 9 step problem solving procedure, but I ended up with this really sloppy code. I would like to iterate over some of it instead of making a new code line for every single variant. More or less I need to optimize this code so I can learn how to do th...

This doesn't seem to be asking for a code review though. It is asking how to reduce the chances of getting a draw. But that's more of a maths problem then a programming problem. The restriction to use the same numbers doesn't make sense — if you can't change the rules, then you can't change the odds. It's unclear what the question is really asking. — Quentin 48 secs ago
@Quentin: Yeah, you're right, not sure if Code Review is the right place for this either. Will retract my vote. — Joe Clay 21 secs ago
16:04
@DmitrySalychev Great! Admittedly I wrote the answer without testing my proposal, merely based on Podofo code review, so I'm happy, too, that my analysis was right. — mkl 37 secs ago
0
Q: Basic Nginx server environment creation script

BeniaHere's a script I wrote for raising up a basic Nginx server environment. The script includes an internal script named csb (create Sblock) which is used to create Sblocks in a comfortable way. As I'm new to Linux, I might have had about 2-3 mistakes, especially in that internal script. #!/bin/ba...

16:22
0
Q: Android Kotlin Extension super calling

Gianni Genovesii am a Java Android Developer and i'm approaching to Kotlin I have defined the following class: open class Player : RealmObject() { ... } And i defined the following two extensions, one for the generic RealmObject class and one for the specific Player class: fun RealmObject.store() { ...

16:32
posted on August 03, 2017 by CommitStrip

16:45
LOL
seriously, I haven't gotten any votes on this yet? codereview.stackexchange.com/a/168966/18427
seems like everyone is actually working, that is a scary thought.....
@Malachi Ehhh, I don't like how you used the try/catch, I don't think it should be used as flow-control, and that's exactly what you're doing. The Buy should return an enum instead, with the enum indicating status. (Successful, NotEnoughMoney, etc.)
0
Q: How can I optimize this general primality test even more? C++

Francisco Gallego SalidoI have this code, which I think can be optimized even more, but I can't think of a way of optimizing the main loop to make it faster and more comprehesive. Here's the code: #include <iostream> #include <cstdlib> #include <cmath> template <class Integral> bool IsPrime (const Integral &n){ // ...

17:12
0
Q: Espresso tests that check if Snackbar is displayed and if there is an internet connection

TheLearnerI have recently began writing tests for Android using the espresso library. Here I have three tests. The first test is to check if a snackbar appears when searching with blank text. The second is a search for a restaraunt not in the database. Finally I have a test that checks if there is an inte...

What to do when you make a pull request to another repo and you realized that you've messed up the issue id you were trying to fix in one of your commit messages, and in your branch name?
I think this question of yours will fit much better on codereview. This is more of an open-ended question that codereview is designed to deal with, more so than stack overflow. — Conor Mancone just now
@SimonForsberg Uhoh
@SimonForsberg Can't you withdraw the pull request, rebase locally to change the commit messages and then send a new one?
17:26
@skiwi Well, yeah... but that's almost too easy :P
Well.. ^^
I get the feeling this is an inappropriate use of try/catch - the GameSession.Buy should instead return an enum that indicates the state of the result, so that the caller doesn't need to catch an exception (which is expensive) for something that could be super trivial. — EBrown 8 secs ago
@SimonForsberg ^^ Done. :)
bool added = command.ExecuteNonQuery() == 1;
Does this look like magic?
@EBrown Much better!
@skiwi Absolutely not.
(It returns the number of affected rows), the command is an INSERT query
17:28
@EBrown it should create a popup that says, hey you can't do that. so putting it into an enum and then checking the enum then popping a dialog seems like extra work. I agree for the most part that it should not handle the flow.
@skiwi No, it looks like what I do a lot of.
but not being able to buy something is kind of an exception, isn't it?
Cool, another confirmation then that I'm not going crazy (yet)
@Malachi Not necessarily. In the ideal world one would do CanBuy before Buy in their own ops, so that there's no ambiguity.
But throwing an exception for something that can happen frequently is a bad practice, when it's not actually an exceptional situation. (What makes it require an exception? What state is invalidated if the operation fails halfway through?)
so CanBuy would be part of the BuyItem
17:31
I don't think returning an enum indicating what the buy-state is would be a bad thing, I always look at exceptions as a 'last resort', and only throw if the system truly cannot recover. But if I call buy and am ineligible to do so, that's not an unrecoverable state.
Though I do agree that true/false is inappropriate: there should definitely be a better way to do that.
so the BuyItem would go through its code and output a success or a failure, and then the caller would perform some action on that result, that would be the ideal path, no try/catch
conclusion: method should not be void, but should return a boolean?
new thought forming
@Malachi Yes, ideally. It can output, even, a Task<bool>, and return Task.FromException as well, where it still returns an Exception on failure, but instead of throwing and catching it, we just read it.
Because in reality we don't need the overhead of a thrown exception, that adds a stack trace and all sorts of mean, nasty horrible things, which we only need a small subset of.
Security stuff will get covered in detail by the people at codereview — Conor Mancone 46 secs ago
17:38
I am not Strong on Task Mojo....
I hate to say things like that....lol
@Malachi You don't really need to be interestingly enough, you can use Task<T> without actually doing anything related to tasks and the TPL.
@SimonForsberg Looks good to me :)
And while it is awaitable, it doesn't have to be awaited.
There's also Task.FromResult<T>, so instead of the current Buy we could refactor it and CanBuy.
come to think of it, I don't think that the way I have it written with the Try/Catch would work the way I explained. there wouldn't be an exception if GameSession.Buy((Armor) this.Gear); returned false.
void BuyItem() {
    var result = GameSession.Buy((Armor) this.gear);
    if (!result.IsFaulted) this.ShowMessage('Buy successful'); // Successful buy
}
17:41
Hmm, pgAdmin crashed, maybe it's time to stop ignoring those warnings that I'm accessing a 9.5 database while my current version only supports up to 9.4
public static Task<bool> Buy(Weapon weapon) {
    var canBuy = CanBuy(weapon);
    if (canBuy.IsFaulted) return canBuy;

    data.money -= weapon.price;
    data.weaponsPurchased.Add(weapon);
    return Task.FromResult(true);
}
public static Task<bool> CanBuy(Weapon weapon) {
    if (data.weaponsPurchased.Contains(weapon))
        return Task.FromException<bool>(new AlreadyOwnItemException());

    if (weapon.price > data.money)
        return Task.FromException<bool>(new NotEnoughMoneyException());

    return Task.FromResult(true);
}
0
Q: This class is part of my multi-purpose CLI calculator. This is the class that is responsible for the basic calculator

RibchinskiI have created a calculator that can solve geometric formulas and can do some simple calculations. I would like to expand the simple calculations part a bit more. import java.util.Scanner; public class Calculator { public static void calcMenu(Scanner input){ Scanner oper = new S...

Then, you still 'bubble up' the exceptions, so in BuyItem the result will contain the exception that happened, but you avoid all the overhead of looking into stack frames and such.
You can have your cake, and you can also have time to eat it too. ;)
can't you do that with custom exceptions too?
Do what?
return Task.FromException<bool>(new AlreadyOwnItemException());
17:48
it's been a while since I played with Custom Exception Classes....
I promise the framework doesn't have an AlreadyOwnItemException. ;)
I mean without the task.
but yeah
lol
You could, but how do you plan to return it? You can still throw a custom exception, but that adds a lot of overhead.
i guess I am not versed enough with the Task<T> stuff and am missing vital information to understand exactly how it is different, other than what you have told me. I will have to note this as something I need to read about.
Radarbob's answer looks like a good answer as well....
@Malachi I think the information you are missing is that there is nothing conventionally different between Task<T>, Exception, or normal .NET classes.
18:00
so we are returning an exception without throwing it. we are handing it off instead of throwing it at?
@Malachi Yes, we are returning an exception without throwing it.
Which at that point, means it's a regular old .NET object.
right
There's nothing special about it: it has a constructor (or more), properties, methods, etc.
The same thing happens when we return a Task<T>.
so we could return a task instead of an exception, and the task could be showing the success or failure message?
We're not doing anything special: allocate an object (probably on the stack then moved to the heap) that contains whatever we say. Task.FromException<T> returns a Task<T> with IsFaulted set to true.
@Malachi Exactly.
18:03
Damn, I thought I had lost all my tabs, but they're still here
So if we return a Task<T>, then check IsFaulted, we know if the operation succeeded or not: if IsFaulted == true then it's a failed operation, and Task<T>.Exception will have that information. If IsFaulted == false then it was successful, and Task<T>.Result will have that information.
I updated my answer by the way. not with the Task Stuff though.
Heh. I actually thought about adding an answer demonstrating the Task<T> stuff. Lol
3
@Malachi Free points: rename Buy(Weapon weapon) to TryBuy(Weapon weapon). ;)
Doesn't Try suggest that there's an out variable?
It suggests if you're following a TryParse convention.
It doesn't require.
Any Try... method should return a true/false, but it doesn't have to have an out.
(We just usually see it that way because most of the Try... methods are returning two things: a truthy and a value.)
@VisualStudio Found a bug in C#7 / VS Community 2017: if you create a generic local func it doesn't recognize the t… https://twitter.com/i/web/status/893172663648235520
18:20
This is a new one... Unhandled Exception: Npgsql.NpgsqlOperationInProgressException: A command is already in progress: INSERT INTO years (year, url, inserted_at) VALUES (:year, :url, CURRENT_TIMESTAMP) ON CONFLICT (year) DO NOTHING RETURNING id
Oh I forgot to call a close, that explains
18:57
This type of question may get a better response from codereview.stackexchange.com. — François Andrieux 51 secs ago
@Malachi (And @SimonForsberg) Posted an answer:
0
A: Armor and Weapon classes for a game

EBrownSo Malachi has a great idea with the BuyItem issue, but I want to expand on his (already good) answer. I was recently shown this by someone I look up to considerably: we have a built-in construct that can allow us to return either a Result or a Failure, and with our Buy method I think it's impor...

2
wow... maven is a royal pain ...
at least it's a royal pain to get it to do what I want...
@EBrown good answer! thank you for the mention!
@Paparazzi This isn't Code Review. You need to actually have a problem to solve for a question to be on topic. — Servy 6 secs ago
I actually think I understand what you were saying about the Tasks a lot better after reading that.
19:13
For working code, you should post to codereview.stackexchange.comAlexander 18 secs ago
@DanielLangr Yes, codereview is commonly used. Do be aware that the expected question format is very different from on Stack Overflow, so you'll want to check the help center and maybe try to get guidance from their chat. — Justin 12 secs ago
@Malachi That's the goal. :)
@Vogel612 Which is why I prefer Gradle these days.
alright then how do you make gradle list the URLs of the artifacts it collects?
one of these days I am going to come back with a vengeance towards the C# tag....lol
I need to work on my Game and do some reading.
19:47
I agree with Dan's suggestion... A bit off topic, but some quick code review: I'd recommend not creating cfparameters for BillDate and PaidDate. Just use the database's SysDateTime() or GetDate() functionality for a Now() equivalent. At the very least, don't bother DateFormat() on it, especially if the database datatype is date/datetime. — Shawn 47 secs ago
0
Q: Basic Caesar Cipher in Swift 3.1

LewisI have been learning Swift for the past day and thought I'd try a basic problem where I can do String manipulation. I am only on pg.100 of the Swift Programming Language on iBooks. Compared to python it seems to be quite difficult to actually modify individual characters as Swift is strongly type...

20:04
0
Q: Implementing a dictionary and thesaurus in Python

ROSBOSSWrite code that functions as both a dictionary and a thesaurus. Supported operations: - Add a word and its definition to the dictionary - Add a synonym to a word in the dictionary - Look up the definition of a word in the dictionary - Look up the synonym of a word in the dictionary - Synonyms sho...

20:19
snace.herokuapp.com i will just leave this here (if anyone wants to code review) :-)
(or if anyone wants to play ^_^)
This may be better suited for code review. codereview.stackexchange.comcolecmc 13 secs ago
0
Q: Factory using Structuremap to inject concrete implementation of BaseTask<T>

ChrisBintThe problem statement that I am trying to solve is this; We will retrieve a list of Tasks from an external repository. These tasks will have a type and for each type, there needs to be a specific implementation that defines the Model it needs it order to perform the Task and then the logic neede...

Congrats on the [silver-badge:necromancer] @Malachi. ;)
20:42
@Neal I had a hard time finding the code because this <script nomodule src="dist/bootstrap.js"> made me think it was just the JS code for Bootstrap
@Phrancis new es6 imports, that is the fallback ;-)
the real one is in src
@Neal I tried the game and found it difficult to play because the screen is so tiny. WASD controls would be nice for those of us who are left handed (I am)
@Phrancis ha. I can make it bigger :-)
CTRL + +
;-)
I think I found a bug
Does your code work? If it does and you are just looking to improve your code, this question probably belongs on Code Review Stack Exchange, and not here. Otherwise, what problem are you having, or what error are you seeing? — Tot Zam 26 secs ago
20:49
If the snake is 1 or 2 segments long, if you press the arrow opposite to the direction you are going, it just starts going that direction. If the snake is 3 or more segments long and you do the same thing, it ends the game.
@Neal ^
@Phrancis I believe that is how snake works, as the snake cannot eat himself, but if he is <= 2 sections long he can just turn around
@Neal I thought the snake cannot do a reversal at all?
@EBrown see my above rule.
Maybe I am wrong.
I dunno, I just recall never being able to do a 'reverse' period on the old game I had on Win95 (maybe 98?).
(I could also be wrong.)
That^ would seem more intuitive as well
In any case @Neal if you want a code review you should write a question
20:55
@Phrancis I wanted a game review, not really code. code review I can get to later.
I need to get the rules right.
I'd definitely make some WASD controls, and also show on the screen what the controls are before the game begins (as simple as they are)
@EBrown thank you
"Is there a better way to do this?" If the code works but you want someone to review it, try posting on CodeReview. — csm_dev 13 secs ago
hmmmm
21:15
This is not a code review site. codereview.stackexchange.com is. — Mad Physicist 1 min ago
@MadPhysicist This is not a code review request. Please don't confuse people by making comments that look like referrals to other sites. — 200_success just now
21:50
0
A: A friendly challenge!

Simon ForsbergNo. This will not be a battle between PPCG and CR. In fact, it is not acceptable to post a challenge on PPCG where only some people are allowed to participate. Now you might say "Anyone is welcome to participate, but if they're not a member on CR then they will fight for PPCG!" but that's just c...

0
Q: How to name a slightly different method without changing the signature and without losing its meaning

alexpfxWe have on our code-base a method isSameDate (Date, Date). This method compare two Dates, without taking hours in account. If null is passed it throws an IllegalArgumentException. I need a similar method, but this new method should consider Nulls, so, if null and null is passed, it should ret...

22:07
@SimonForsberg Thank goodness.
0
Q: Formating function that it's able to handle new and to update data

DaAmidzaI'm having issues to format the following function in a way that it can insert data and update it. The request on the function looks like this: { "behaviour":"R", "names":{ "en":{ "name":"Ismir En" }, "gr":{ "name":"Ismir Gr" },...

22:27
It is not a SO topic. Go to the code review — PeterJ 53 secs ago
This answer just screams excellence. May be the best explanation of some advanced topics I've ever read. I rank it up there with blogs of Eric Lippert or Jon Skeet. — Rick Davin 1 min ago
:)
@Malachi ^^^
0
Q: Simple language tokenizer in C#

107MPI had a spare time so I have decided to write a simple tokenizer in C# for my own programming language. The tokenizer is not finished, but it is working and I would like to hear your opinion on things I can change a bit, improve or completely modify. It is lacking FloatLiteral token and it assume...

22:59
0
Q: Inheritance and other

PaparazziAny comment on the code? History is I have document management application licenced to litigation support and it made some money but requirements changed weekly so the code got fractured. Trying to start over with more stable base. I know I will get a lot of break it up and I accept that. So...

0
Q: Java Fight simulation

CoderKliptothis is my second post since I've started coding/joined this site so be ready for some bad code and beginner questions! I am just playing around with Java right now, as I believe this is a fun way to learn the language, so I decided to make a simple fight simulator. The simulator is meant to hav...

0
Q: Find all combinations of a number sequence which is first increasing then decreasing

Himanshu RayGiven an integer N(Natural Number), A program/Algorithm to find the remainder of arrangements that can be obtained by rearranging the numbers 1, 2, ...., N. Input Format: One line containing the integer N Output Format: An integer m, giving the remainder of the number of arrangements that cou...


« first day (1552 days earlier)      last day (2761 days later) »