body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I'm working on a legacy C++ project, which is using GLib for its Main Event Loop. This has caused a lot of ugliness because it mixes C++ and C paradigms (no C++ wrapper for GLib had been used).</p>
<p>Anyway, I'd like to generalize some classes that internally use the <a href="https://developer.gnome.org/glib/stable/glib-Asynchronous-Queues.html" rel="nofollow noreferrer">Asynchronous Queue</a> provided by GLib.</p>
<p>This is what I've done:</p>
<pre><code>// File AsyncQueue.h - C++11 required
#include "glib.h"
template<typename T>
class AsyncQueue
{
static gboolean prepare(GSource *source, gint *timeout)
{
auto async_queue_source = reinterpret_cast<AsyncQueueSource*>(source);
if( nullptr == async_queue_source || nullptr == async_queue_source->async_queue )
return FALSE;
if( nullptr != timeout )
*timeout = -1; // Poll timeout
return g_async_queue_length(async_queue_source->async_queue) > 0;
}
static gboolean check(GSource *source)
{
auto async_queue_source = reinterpret_cast<AsyncQueueSource*>(source);
if( nullptr == async_queue_source || nullptr == async_queue_source->async_queue )
return FALSE;
return g_async_queue_length(async_queue_source->async_queue) > 0;
}
static gboolean dispatch(GSource *source, GSourceFunc callback, gpointer user_data)
{
auto async_queue_source = reinterpret_cast<AsyncQueueSource*>(source);
if( nullptr == async_queue_source || nullptr == async_queue_source->async_queue )
return G_SOURCE_REMOVE;
auto item = reinterpret_cast<T*>(g_async_queue_pop(async_queue_source->async_queue));
if( nullptr != item )
{
if( nullptr != async_queue_source->this_object )
async_queue_source->this_object->OnItemPopped(*item);
delete item;
}
return G_SOURCE_CONTINUE;
}
struct AsyncQueueSource
{
GSource source_object;
AsyncQueue<T>* this_object;
GAsyncQueue* async_queue;
};
static_assert(std::is_trivial<AsyncQueueSource>::value, "AsyncQueueSource must be a trivial type");
GSourceFuncs source_funcs;
GMainContext* context;
guint source_id_within_context;
AsyncQueueSource* async_queue_source;
public:
// noncopyable
AsyncQueue(const AsyncQueue&) = delete;
AsyncQueue& operator=(const AsyncQueue&) = delete;
AsyncQueue()
: source_funcs{&AsyncQueue::prepare, nullptr, &AsyncQueue::dispatch, nullptr, nullptr, nullptr}
, context{nullptr}
, source_id_within_context{0}
{
async_queue_source = reinterpret_cast<AsyncQueueSource*>(g_source_new(&source_funcs, sizeof(AsyncQueueSource)));
if( nullptr != async_queue_source )
{
async_queue_source->this_object = this;
async_queue_source->async_queue = g_async_queue_new();
}
}
virtual ~AsyncQueue()
{
if( nullptr != async_queue_source )
{
if( nullptr != async_queue_source->async_queue )
{
g_async_queue_unref(async_queue_source->async_queue);
}
async_queue_source->this_object = nullptr;
g_source_unref(reinterpret_cast<GSource*>(async_queue_source));
}
}
bool Attach(GMainContext* main_context)
{
bool result = false;
if( nullptr != async_queue_source )
{
source_id_within_context = g_source_attach(&async_queue_source->source_object, main_context);
if( source_id_within_context > 0 )
result = true;
}
return result;
}
bool IsAttached() const { return source_id_within_context > 0; }
virtual void OnItemPopped(T& item) = 0;
// item must be allocated with new() and will be owned by AsyncQueue
void PushItem(T* item)
{
if( nullptr != item )
{
if( nullptr != async_queue_source && nullptr != async_queue_source->async_queue )
{
g_async_queue_push(async_queue_source->async_queue, item);
if( IsAttached() )
g_main_context_wakeup(context);
}
else
{
delete item;
}
}
}
void PushItem(const T* item)
{
if( nullptr != item )
{
auto copied_item = new T(*item);
PushItem(copied_item);
}
}
void PushItem(const T& item)
{
auto copied_item = new T(item);
PushItem(copied_item);
}
void PushItem(T&& item)
{
auto moved_item = new T(std::move(item));
PushItem(moved_item);
}
};
</code></pre>
<p><strong>Pointer misuse</strong></p>
<p>This class seems reasonably clean and simple to use, but my main concern is misuse of <code>AsyncQueue::PushItem(T* item)</code> because the caller could pass a pointer to an object on the heap or something allocated with <code>g_new</code> or <code>malloc</code>.</p>
<p>I could give the responsibility to free the memory to the implementer of <code>virtual void OnItemPopped(T& item)</code> by passing a T* instead, but I don't like this option.</p>
<p>What if I accept only smart pointers of type <code>std::unique_ptr<T></code> and therefore I change signatures as <code>AsyncQueue::PushItem(std::unique_ptr<T> item)</code> and <code>virtual void OnItemPopped(std::unique_ptr<T> item)</code>? Anyway, I would still have to pass naked pointers to the asynchronous queue because it works only with trivial types (aka POD types).</p>
<p><strong>Thread safety</strong></p>
<p>Multiple threads should be able to call without issues <code>AsyncQueue::PushItem</code>, all the synchronization is done by GLib inside the async queue. The only thread able to pop elements is the thread running the Main Loop on the GMainContext passed to <code>AsyncQueue::Attach</code>.</p>
<p>Besides this, there are some obvious multithreading flaws that I missed? </p>
<p><strong>Items leaked on class destruction</strong></p>
<p>If the class or the main loop is destroyed when the queue still holds data they will be leaked (see <a href="https://stackoverflow.com/a/52175388/297373">https://stackoverflow.com/a/52175388/297373</a>). I'm not sure how to solve this issue.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T11:27:03.513",
"Id": "204051",
"Score": "3",
"Tags": [
"c++",
"asynchronous",
"queue",
"template-meta-programming",
"glib"
],
"Title": "Templatized GLib asynchronous queue"
} | 204051 |
<p>I have an inherited code base that I am looking to improve. Below is a "variable wrapper" template class and #defines that i would like to replace with a template only solution, or redesign completely with something else. I have not been able to come up with any solution that would not have to leverage macros or are worse in complexity and clarity than this. I lay it out plainly and hopefully that makes it obvious what this code does.</p>
<p>The code uses hopscotch_map for storage, which is actually irrelevant to the question posed here. It could use <code>std::map</code> just as well.</p>
<p>The goal would be to either have a complete template solution or find a "better way"(tm) to have this functionality using modern design patterns.</p>
<p>This is the #define/template code in it's complete form:</p>
<pre><code>template< class T >
class CfgBase
{
private:
T m_val;
public:
explicit CfgBase(T t): m_val{t} {}
inline void set(const T t)
{
m_val = t;
}
inline T get() const
{
return m_val;
}
};
void AddConfigData(const string &p, CfgBase< long > *me){
ConfigVals::m_longMap.insert({p, me});
};
void AddConfigData(const string &p, CfgBase< bool > *me); //these have a similar definition as the long above
void AddConfigData(const string &p, CfgBase< double > *me);
void AddConfigData(const string &p, CfgBase< string > *me);
void AddConfigData(const string &p, CfgBase< unsigned long> *me);
#define CFG_DEF_TYPE( _type, _upper, _key, _dflt ) \
class CFG_##_upper : public CfgBase< _type > \
{ public: \
CFG_##_upper(): CfgBase{_dflt} { AddConfigData( _key, this ); } \
}; \
private: \
CFG_##_upper m_##_upper; \
public: \
_type get##_upper() const { return m_##_upper.get(); } \
void set##_upper( const _type v ) { m_##_upper.set( v ); }
#define CFG_DECL_STR( _upper, _key, _dflt ) CFG_DEF_TYPE( string, _upper, _key, _dflt )
#define CFG_DECL_DBL( _upper, _key, _dflt ) CFG_DEF_TYPE( double, _upper, _key, _dflt )
#define CFG_DECL_BOOL( _upper, _key, _dflt ) CFG_DEF_TYPE( bool, _upper, _key, _dflt )
#define CFG_DECL_LONG( _upper, _key, _dflt ) CFG_DEF_TYPE( long, _upper, _key, _dflt )
#define CFG_DECL_ULONG( _upper, _key, _dflt ) CFG_DEF_TYPE( unsigned long, _upper, _key, _dflt )
using CfgLongMap = bhopscotch_pg_map< string, CfgBase< long > * >;
using CfgBoolMap = bhopscotch_pg_map< string, CfgBase< bool > * >;
using CfgDblMap = bhopscotch_pg_map< string, CfgBase< double > * >;
using CfgStrMap = bhopscotch_pg_map< string, CfgBase< string > * >;
using CfgULongMap = bhopscotch_pg_map< string, CfgBase< unsigned long > * >;
</code></pre>
<p>You then use it in this fashion (only the native "long" type example follows):</p>
<pre><code>class ConfigVals
{
static CfgLongMap m_longMap;
CFG_DECL_LONG(SomeCustomVariable, "A_CUSTOM_VARIABLE", 12345)
}
</code></pre>
<p>For this example, what happens is the <code>CFG_DECL_LONG</code> macro becomes:</p>
<pre><code>CFG_DEF_TYPE( long, SomeCustomVariable, "A_CUSTOM_VARIABLE", 12345)
</code></pre>
<p>which then becomes (remember that macro is contained inside the <code>ConfigVals</code> class):</p>
<pre><code>class CFG_SomeCustomVariable : public CfgBase< long >
{ public:
CFG_SomeCustomVariable(): CfgBase{12345} { AddConfigData("A_CUSTOM_VARIABLE", this ); }
};
private:
CFG_SomeCustomVariable m_SomeCustomVariable;
public:
long getSomeCustomVariable() const { return m_SomeCustomVariable.get(); }
void setSomeCustomVariable( const long v ) { m_SomeCustomVariable.set( v );}
</code></pre>
<p>The end result is a class that looks like this:</p>
<pre><code>class ConfigVals
{
static CfgLongMap m_longMap;
class CFG_SomeCustomVariable : public CfgBase< long >
{ public:
CFG_SomeCustomVariable(): CfgBase{12345} { AddConfigData("A_CUSTOM_VARIABLE", this ); }
};
private:
CFG_SomeCustomVariable m_SomeCustomVariable;
public:
long getSomeCustomVariable() const { return m_SomeCustomVariable.get(); }
void setSomeCustomVariable( const long v ) { m_SomeCustomVariable.set( v );}
}
</code></pre>
<p>The result is that <code>ConfigVals</code> now has a private variable of <code>CfgBase</code> type that holds the value, that variable is in a lookup map (used elsewhere in the codebase) and <code>ConfigVals</code> has custom function calls that incorporate the variable name. </p>
<p>If you have another variable of type long, it's as simple as adding another macro call to the <code>ConfigVals</code> class. If you want another type, you have to make sure you have coverage by manually adding appropriate code in #defines.</p>
<p>Anyone seen anything like this before and is there a better solution?</p>
<p>EDIT:
firda wanted usage elaborated. Here it is.</p>
<p>The <code>ConfigVals</code> class is actually a singleton, it is the centralized source of all configuration variables in a much larger code base:</p>
<pre><code>class ConfigVals{
public:
ConfigVals();
virtual ~ConfigVals();
static ConfigVals& getInstance()
{
static ConfigVals instance_; //lazy init on first access, guaranteed creation
return instance_;
}
// a whole crapload of macros here
// also a "configuration file" loader function
}
</code></pre>
<p>usage is pretty simple, whenever we need to use a particular variable:</p>
<pre><code>#define S_CONFIG ConfigVals::getInstance();
S_CONFIG.getSomeCrucialVariableAtThisMoment();
</code></pre>
<p>There is a lot of these everywhere too:</p>
<pre><code>if (S_CONFIG.getSomeStupidVar() >= S_CONFIG.getSomeOtherStupidVar()){
...// do some stuff//
}
</code></pre>
<p>On instantiation all variables have default values, adjusted by loading a configuration file. The configuration file loader basically does this for every single type (you have to put an additional one of these for every type you want. it sucks, i know):</p>
<pre><code>auto siter = m_strMap.find(key);
if (siter != m_strMap.cend()) {
siter->second->set(f1);
LOG_CONSOLE->debug("CONFIG: {} = {}", key, f1);
return;
}
</code></pre>
<p>the configuration file is in this format:</p>
<pre><code>someValue=2234
someOtherValue=astring
nowaThirdValue=3.4
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T13:23:16.840",
"Id": "393462",
"Score": "1",
"body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/52413404/1014587)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T16:15:15.513",
... | [
{
"body": "<p>I am still waiting for justification of that macro-generated CFG_##_upper class, but I would like to address things I have spotted.</p>\n\n<h1>CfgBase, indentation, excess inline keyword, get/set v.s. operators</h1>\n\n<ul>\n<li>Not sure if that was just copy-paste error, but you should indent the... | {
"AcceptedAnswerId": "204092",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T13:17:42.300",
"Id": "204060",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"design-patterns",
"template-meta-programming",
"macros"
],
"Title": "Replace a #define/template \"Variable Wrapper\" system with a pure template/OOP solution"
} | 204060 |
<p>I'm creating a text-based adventure game using PyGame. I plan on also implementing kind of a Pokemon/Final Fantasy style combat system that works with menus instead of commands, but I haven't started that yet.</p>
<p>The <code>pygame_functions</code> module can be found <a href="https://github.com/StevePaget/Pygame_Functions" rel="nofollow noreferrer">here</a>; I didn't make it.</p>
<p>Issues I know are present: </p>
<ul>
<li><p>I'd like to load in my World dict and Item definitions from a JSON file</p></li>
<li><p>I have a module called "Definitions" that was only created because I needed to move variables out of the main game file. This will be turned into something else, or the variables will be moved somewhere.</p></li>
<li><p>In myinput.py I'm relying on an <code>elif</code> block. I think I should probably change this to check from a dict of commands?</p>
<ul>
<li>In the Items class, the DoorKeys subclass is currently pointless. I <em>might</em> be doing something cool with this later though.</li>
</ul></li>
</ul>
<p>gamefile.py </p>
<pre><code>import myinput
from definitions import *
def main():
while True:
location.bgChange()
myinput.input_loop()
if __name__ == '__main__':
main()
</code></pre>
<p>myinput.py</p>
<pre><code>from pygame import *
from gameworld import *
from display import *
from myoutput import *
from audio import *
from definitions import *
from nltk import tokenize
def input_loop():
command = ' '
while True:
command = textBoxInput(wordBox)
if command in location.room.exits:
location.travel(command, bag)
elif command == 'look':
location.room_desc()
elif command == '':
log.insert(0, 'You have to say what it is you want to do!')
logLimit()
logUpdate()
command = '#'
elif command == 'search':
location.search_room()
elif command.split()[0] == 'take':
try:
location.check_take(command.split()[1], bag, location)
except IndexError:
log.insert(0, 'What do you want to take?')
logLimit()
logUpdate()
elif command == 'inventory':
bag.check_inv()
elif command == 'checklog':
print(log)
else:
log.insert(0, 'Invalid Command')
logLimit()
logUpdate()
if not command:
break
</code></pre>
<p>display.py</p>
<pre><code>from pygame_functions import *
import random
from myoutput import log
screenSize(1800, 800)
wordBox = makeTextBox(50, 700, 700, 0, "Enter Command", 0, 24)
showTextBox(wordBox)
gameLog1 = makeLabel(log[0], 20, 50, 600, "white", "Agency FB", "black")
showLabel(gameLog1)
gameLog2 = makeLabel(log[1], 20, 50, 564, "white", "Agency FB", "black")
showLabel(gameLog2)
gameLog3 = makeLabel(log[2], 20, 50, 528, "white", "Agency FB", "black")
showLabel(gameLog3)
gameLog4 = makeLabel(log[3], 20, 50, 492, "white", "Agency FB", "black")
showLabel(gameLog4)
gameLog5 = makeLabel(log[4], 20, 50, 456, "white", "Agency FB", "black")
showLabel(gameLog5)
def logUpdate():
changeLabel(gameLog1, log[0])
changeLabel(gameLog2, log[1])
changeLabel(gameLog3, log[2])
changeLabel(gameLog4, log[3])
changeLabel(gameLog5, log[4])
</code></pre>
<p>gameitems.py</p>
<pre><code>class Items:
def __init__(self, name, info, weight):
self.name = name
self.info = info
self.weight = weight
class DoorKeys(Items):
def __init__(self, name, info, weight):
super().__init__(name, info, weight)
class Weapon(Items):
def __init__(self, name, info, damage, speed, weight):
super().__init__(name, info, weight)
self.damage = damage
self.speed = speed
Sword = Weapon("Sword", "A sharp looking sword. Good for fighting goblins!", 7, 5, 5)
Knife = Weapon("Knife", "A wicked looking knife, seems sharp!", 5, 7, 3)
Stick = Weapon("Stick", "You could probably hit someone with this stick if you needed to", 2, 3, 3)
Rusty_Key = DoorKeys("Rusty_Key", "A key! I wonder what it opens.", .01)
Ornate_Key = DoorKeys("Ornate_Key", "An ornate key with an engraving of a small cottage on one side", .01)
Moonstone = Items("Moonstone", "A smooth white stone that seems to radiate soft white light", .05)
Flower = Items("Flower", "A beautiful wildflower", .001)
</code></pre>
<p>gameworld.py</p>
<pre><code>from gameitems import *
from display import *
from myoutput import *
class Room:
def __init__(self, name, description, exits, actions, roominv, roomkey, lock, background, music):
self.name = name
self.description = description
self.exits = exits
self.actions = actions
self.roominv = roominv
self.roomkey = roomkey
self.lock = lock
self.background = background
self.music = music
class Player:
def __init__(self, name, health):
self.name = name
self.health = health
class Location:
def __init__(self, room):
self.room = world[room]
def musChange(self):
mus = self.room.music
if self.room.music:
pygame.mixer.music.load(mus)
pygame.mixer.music.play(-1)
else:
pass
def bgChange(self):
bg = self.room.background
if self.room.background:
setBackgroundImage(bg)
else:
pass
def travel(self, direction, bag):
if direction not in self.room.exits:
self.no_exit()
else:
self.set_new_room_name(direction, bag)
self.bgChange()
self.musChange()
def set_new_room_name(self, direction, bag):
new_room_name = self.room.exits[direction]
log.insert(0, "moving to" + ' ' + new_room_name)
logLimit()
logUpdate()
self.key_check(new_room_name, bag)
def key_check(self, new_room_name, bag):
if world[new_room_name].lock and world[new_room_name].roomkey not in bag.inventory:
self.no_key()
else:
world[new_room_name].lock = False
self.set_room(new_room_name)
self.room_desc()
def set_room(self, new_room_name):
self.room = world[new_room_name]
def no_exit(self):
log.insert(0, "You can't go that way!")
logLimit()
logUpdate()
def no_key(self):
log.insert(0, 'The door is locked! You need the right key!')
logLimit()
logUpdate()
def room_desc(self):
log.insert(0, self.room.description + ' You can: ' + ' , '.join(self.room.actions))
logLimit()
logUpdate()
def search_room(self):
if self.room.roominv:
for i in self.room.roominv.keys():
log.insert(0, "you find a" + ' ' + i)
logLimit()
logUpdate()
else:
log.insert(0, "You don't find anything")
logLimit()
logUpdate()
def none_here(self, key):
log.insert(0, "You can't find a" + ' ' + key)
logLimit()
logUpdate()
def check_take(self, key, bag, location):
if key in self.room.roominv:
bag.add_to_inv(key, location)
log.insert(0, 'you take the' + ' ' + key)
logLimit()
logUpdate()
else:
self.none_here(key)
class Bag():
def __init__(self, inventory):
self.inventory = inventory
def add_to_inv(self, key, location):
self.inventory.append(location.room.roominv[key])
del location.room.roominv[key]
def check_inv(self):
if self.inventory:
for item in self.inventory:
log.insert(0, "Your bag contains:" + ' ' + item.name)
logLimit()
logUpdate()
else:
log.insert(0, "Your bag is empty")
logLimit()
logUpdate()
world = {}
world['introd'] = Room('introd', "You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.", {'north': "clearing"}, {"Search the ground", "Go North"}, {'Sword': Sword}, None, False, 'Background.jpg', 'IntroMus.mp3')
world['clearing'] = Room('clearing', "You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. \
To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.", {'s': "introd", 'e': "forest path"}, {"Take flower", "Go south", "Go East"}, {'Flower': Flower}, None, False, 'Background2.jpg', 'IntroMus.mp3')
world['forest path'] = Room('forest path', "You begin walking down a well beaten path. The sounds of the forest surround you. Ahead you can see a fork in the road branching to the South and East.\
You can smell smoke coming from the South, and can hear a stream to the East", {'south': "cottage", 'east': "stream", 'west': "clearing"}, {"Go South", "Go East", "Go West"}, {'Stick': Stick}, None, False, None, None)
world['stream'] = Room('stream', "You come upon a relaxing stream at the edge of the woods. It looks like there is something shiny in the water. To your South is a rickety looking shack, \
to your West is the forest path you came down", {'south': "shack", 'west': "forest path"}, {"Go South", "Go West"}, {'Rusty_Key': Rusty_Key}, None, False, 'bgStream.jpg', 'StreamSong.mp3')
world['shack'] = Room('shack', "In front of you is a shack, possibly used as an outpost for hunting. It looks dilapidated.", {'south': "inside shack", 'north': "stream"}, {"Go South", "Go North"}, None, None, False, None, None)
world['inside shack'] = Room('inside shack', "The inside of the shack is dirty. Bits of ragged fur are scattered about the floor and on a table against the back wall.\
A sharp looking knife is on the table. There is an ornate key hanging on the wall by a string.", {'north': "shack"}, {"Go North", "Take Knife", "Take Key"}, {'Knife': Knife, 'Ornate_Key': Ornate_Key}, Rusty_Key, True, None, None)
world['cottage'] = Room('cottage', "A quaint cottage sits in the middle of a small clearing, smoke drifting lazily from the chimney.", {'north': "forest path", 'south': "inside cottage"}, {"Go North", "Go South"}, None, None, False, None, None)
world['inside cottage'] = Room('inside cottage', "The inside of the cottage is warm and cozy. It reeks like death.", {'north': 'outside cottage'}, {'Go North', 'Search the cottage'}, {'Moonstone': Moonstone}, Ornate_Key, True, None, None)
</code></pre>
<p>myoutput.py</p>
<pre><code>log = ["Welcome my dear friend, to The Woodsman's Tale", "Listen Well, for in my current state I can only say this once", "Command List: search - searches the current room|||, look - describes the current room|||, take *item name* - picks up the item you specify|||, inventory - check your bags", "north, south, east, and west, will guide you", "all commands are currently case-sensitive. Thank you for playing!"]
def logLimit():
if len(log) > 5:
log.pop()
</code></pre>
<p>audio.py</p>
<pre><code>import pygame
def bgMusic():
pygame.mixer.music.load('IntroMus.mp3')
pygame.mixer.music.play(-1)
bgMusic()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T13:43:11.197",
"Id": "204062",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"pygame",
"role-playing-game"
],
"Title": "Text-Based Adventure RPG with PyGame"
} | 204062 |
<p>Given is a list with (possibly) non-unique elements.</p>
<p>My goal is to split this list into multiple lists, in sum containing the same elements, but separated in a way that no sublist contains each element value more than once.</p>
<p>A few examples to show the supposed result:</p>
<pre><code>[1, 2, 2] -> [[1, 2], [2]]
[1, 2, 2, 3, 3, 4, 4, 4] -> [[1, 2, 3, 4], [2, 3, 4], [4]]
[4, 4, 1, 1, 4, 1, 3, 2, 1, 2, 5, 1, 2, 4, 4, 2, 5] ->
[[4, 1, 3, 2, 5], [4, 1, 2, 5], [4, 1, 2], [4, 1, 2], [4, 1]]
</code></pre>
<p>The order of the elements is not important. The fact that is it preserved is just a side-effect of my current implementation, but not needed. So the following would also be valid:</p>
<pre><code>[1, 2, 2] -> [[2, 1], [2]]
</code></pre>
<p>My current implementation looks as follows:</p>
<pre><code>fun <T> ungroupDuplicateValues(values: List<T>): List<List<T>> {
val result: MutableList<List<T>> = mutableListOf()
var counts = values.groupingBy { it }.eachCount().toMutableMap()
while (counts.isNotEmpty()) {
val newCounts: MutableMap<T, Int> = mutableMapOf()
val subResult: MutableList<T> = mutableListOf()
for ((value, count) in counts) {
subResult.add(value)
if (count > 1) {
newCounts[value] = counts.getValue(value) - 1
}
}
result.add(subResult)
counts = newCounts
}
return result
}
</code></pre>
<p>It works, but feels kind of clumsy. Is there a more elegant/idiomatic (maybe functional) solution?</p>
| [] | [
{
"body": "<p>Played a bit with it... how do you like the following?</p>\n\n<pre><code>fun <T> ungroupDuplicateValues(values: List<T>): List<List<T>> {\n val countPerValue = values.groupingBy { it }.eachCount()\n val maxCount = countPerValue.map { it.value }.max() ?: 0\n return (1..ma... | {
"AcceptedAnswerId": "204064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T08:51:48.313",
"Id": "204063",
"Score": "3",
"Tags": [
"algorithm",
"kotlin"
],
"Title": "Ungrouping of values into multiple lists"
} | 204063 |
<p>I've implemented an algorithm found in a book. It adds 2 positive integers of equal size. How can it be improved? It is assumed that inputted data is always positive integers with an equal number of digits.</p>
<p><strong>EDIT</strong>
As there are lots of comments regarding the question, I would like to rephrase it. This program tries (yes it tries, could be wrong) to simulate how humans do manual additions of 2 positive integers. This is similar to the technique students learn in (I hope..) primary schools. It is based on the book "Invitation to Computer Science". One obvious improvement to this program is adding validations. What else can be done to improve it? </p>
<pre><code>class Program
{
static void Main(string[] args)
{
Add2Numbers(97,47);
Console.ReadLine();
}
static void Add2Numbers(int a, int b)
{
int carry = 0,sum=0;
List<int> lstA = new List<int>();
List<int> lstB = new List<int>();
List<int> lstSum = new List<int>();
foreach (var item in GetDigit(a))
{
lstA.Add(item);
}
foreach (var item in GetDigit(b))
{
lstB.Add(item);
}
for (int j = 0; j < lstB.Count;j++ )
{
sum = lstA[j] + lstB[j] + carry;
if (sum > 9)
{
sum = sum - 10;
carry = 1;
}
else
carry = 0;
lstSum.Add(sum);
}
if (carry > 0)
lstSum.Add(carry);
lstSum.Reverse();
foreach (var item in lstSum)
{
Console.Write(item);
}
}
static IEnumerable<int> GetDigit(int number)
{
while (number > 0)
{
yield return number % 10;
number = number / 10;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T14:00:14.303",
"Id": "393476",
"Score": "4",
"body": "The obvious improvement would be `int c = a + b`, therefore some more information on what the goal is would be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creat... | [
{
"body": "<p>If you are looking for ways to 'modernise' the code you might try some linq bits and pieces.</p>\n\n<p>There should be no need for explicit adding to lists.</p>\n\n<p>As the input numbers are both of the same size, we can easily use <code>.Zip()</code> to merge the digits. <strong>Note:</strong> W... | {
"AcceptedAnswerId": "204093",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T13:51:25.197",
"Id": "204065",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"reinventing-the-wheel"
],
"Title": "Addition of 2 integers"
} | 204065 |
<p>I'm putting together a video website for our company, with a working accordion. It works, but it using the same class name for each section creates issues with the expanding and collapsing. I found a solution, but I'm going to need 13 similar sections for 13 lessons, and having to recreate the same code repeatedly in CSS, JS, and HTML, I have to believe there is a better way to do this.</p>
<p>As the "IT Guy" who just got tossed into this stuff, I'd like to create something a bit cleaner.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
//lesson 1
$('.l1-vid').click(function() {
if($(this).next().is(':hidden') != true) {
$(this).removeClass('active');
$(this).next().slideUp("normal");
} else {
$('.l1-vid').removeClass('active');
$('#l1-vidlink').slideUp('normal');
if($(this).next().is(':hidden') == true) {
$(this).addClass('active');
$(this).next().slideDown('normal');
}
}
});
$('.l1').click(function() {
if($(this).next().is(':hidden') != true) {
$(this).removeClass('active');
$(this).next().slideUp("normal");
$('.l1-vid').removeClass('active');
$('#l1-vidlink').slideUp('normal');
} else {
$('.l1').removeClass('active');
$('.l1-info').slideUp('normal');
if($(this).next().is(':hidden') == true) {
$(this).addClass('active');
$(this).next().slideDown('normal');
}
}
});
//lesson 2
$('.l2-vid').click(function() {
if($(this).next().is(':hidden') != true) {
$(this).removeClass('active');
$(this).next().slideUp("normal");
} else {
$('.l2-vid').removeClass('active');
$('#l2-vidlink').slideUp('normal');
if($(this).next().is(':hidden') == true) {
$(this).addClass('active');
$(this).next().slideDown('normal');
}
}
});
$('.l2').click(function() {
if($(this).next().is(':hidden') != true) {
$(this).removeClass('active');
$(this).next().slideUp("normal");
$('.l2-vid').removeClass('active');
$('#l2-vidlink').slideUp('normal');
} else {
$('.l2').removeClass('active');
$('.l2-info').slideUp('normal');
if($(this).next().is(':hidden') == true) {
$(this).addClass('active');
$(this).next().slideDown('normal');
}
}
});
//Collapse all on load
$('.l1-info').hide();
$('#l1-vidlink').hide();
$('.l2-info').hide();
$('#l2-vidlink').hide();
//Expand all link
$('.expand').click(function(event){
$('.l2').next().slideDown('normal');
{$('.l2').addClass('active');}
$('.l1').next().slideDown('normal');
{$('.l1').addClass('active');}
}
);
//collapse all link
$('.collapse').click(function(event){
$('.l2').next().slideUp('normal');
{$('.l2').removeClass('active');}
$('.l2-vid').removeClass('active');
$('#l2-vidlink').slideUp('normal');
$('.l1').next().slideUp('normal');
{$('.l1').removeClass('active');}
$('.l1-vid').removeClass('active');
$('#l1-vidlink').slideUp('normal');
}
);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(//fonts.googleapis.com/css?family=Volkhov:700,700italic,400italic,400);
@import url(http://fonts.googleapis.com/css?family=Oswald);
@font-face {
font-family : "'Oswald'";
font-style : normal;
font-weight : 400;
src : local('Oswald Regular'), local('Oswald-Regular'), url(http://themes.googleusercontent.com/static/fonts/oswald/v8/Y_TKV6o8WovbUd3m_X9aAA.ttf) format('truetype');
}
body{
background-color: #f6f6f6;
font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
color: black;
}
.content{
width: 50%;
margin: auto;
}
ul{
list-style: none;
}
li{
padding-left: inherit;
list-style: circle;
margin-left: 20px;
padding-left: 20px;
padding-bottom: 3px;
padding-top: 3px;
}
/*---------------Lesson 1---------------*/
.l1 {
width: 100%;
float: left;
background: #fff;
padding-left:20px;
padding-top:18px;
cursor: pointer;
color: #0079C1;
display: block;
font-weight: normal;
margin: 1px;
padding: 8px 15px;
border: 1px solid #E5E5E5;
}
.l1::after{
content: "+";
float: left;
padding-right: 15px;
}
.l1-info {
width: 100%;
background-color: #f6f6f6;
border: 1px solid #E5E5E5;
padding-right: 31px;
display: flex;
}
.l1-vid{
background: url('play.png') no-repeat left center !important;
padding-left: inherit;
list-style: none;
margin-left: 0;
}
.l1-vid a{
cursor: pointer;
}
.l1-vid::after{
content: "" !important;
}
#l1-vidlink{
padding-left: inherit;
}
/*---------------End Lesson 1---------------*/
/*---------------Lesson 2---------------*/
.l2 {
width: 100%;
float: left;
background: #fff;
padding-left:20px;
padding-top:18px;
cursor: pointer;
color: #0079C1;
display: block;
font-weight: normal;
margin: 1px;
padding: 8px 15px;
border: 1px solid #E5E5E5;
}
.l2::after{
content: "+";
float: left;
padding-right: 15px;
}
.l2-info {
width: 100%;
background-color: #f6f6f6;
border: 1px solid #E5E5E5;
padding-right: 31px;
display: flex;
}
.l2-vid{
background: url('play.png') no-repeat left center !important;
padding-left: inherit;
list-style: none;
margin-left: 0;
}
.l2-vid a{
cursor: pointer;
}
.l2-vid::after{
content: "" !important;
}
#l2-vidlink{
padding-left: inherit;
}
/*---------------End Lesson 2---------------*/
.active::after{
content: "-";
float: left;
padding-right: 15px;
}
a:hover{
text-decoration:underline
}
@media only screen and (max-device-width: 480px) {
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>AAON Heating and Cooling Products</title>
<link rel="stylesheet" type="text/css" href="test.css">
<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link rel="icon" href="p2tab.png">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="accordionscript.js"></script>
</head>
<body>
<div class="content">
<div>Prism2 - Operator Interface</div>
<div style="float:right;font-size: small;"><a href="javascript:void(0)" class="expand">Expand All</a> | <a href="javascript:void(0)" class="collapse">Collapse All</a></div><br>
<div class="l1">Intro</div>
<div class="l1-info">
<ul>
<li class="l1-vid"><a >Video</a></li>
<div id="l1-vidlink">
<iframe class="desktop" width="560" height="315" src="https://www.youtube.com/embed/H7hGxg92Khc" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></div>
<li>Intro - PDF</li>
<li>Prism 2 Technical Guide</li>
</ul>
</div>
<div class="l2">What is Prism2?</div>
<div class="l2-info">
<ul>
<li class="l2-vid"><a >Video</a></li>
<div id="l2-vidlink">
<iframe class="desktop" width="560" height="315" src="https://www.youtube.com/embed/H7hGxg92Khc" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></div>
<li>What is Prism2 - PDF</li>
</ul>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<ul>\n<li><p>Do not reinvent the wheel and pick up an existing component framework. For instance, <a href=\"https://getbootstrap.com/\" rel=\"nofollow noreferrer\">Bootstrap</a> provides an <a href=\"https://getbootstrap.com/docs/4.1/components/collapse/#accordion-example\" rel=\"nofollow noreferrer\... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T14:07:46.397",
"Id": "204066",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"jquery",
"html",
"css"
],
"Title": "jQuery accordion to serve as table of contents"
} | 204066 |
<p>I've written this rather cumbersome PowerShell script that facilitates a business use case. Because I built it off a PowerShell auditing tool I made, it was formatted differently.</p>
<p>What I'd like to do, in the module that launches the WPF window, is have it launch a runspace for the portion that verifies whether the mailbox is on Exchange onprem or on cloud, then launch another runspace to make the change.</p>
<p>However, some guides I've seen suggest that I write a C# to launch the menu, and then functionalize the actual 2-3 PowerShell sections for the C# based menu to call. (I don't know visual studio or C# well enough to do that without major heart palpitations.)</p>
<pre><code> function proc-input {
Param (
[parameter(ValueFromPipeline)]
[hashtable]$uuer
)
$a = 0
$a = $b = $null
[string]$uuss = $uuer.userooo
[string]$usdo = $uuer.startdateooo
if ($uuer.enddateooo -ne $null){
[string]$uedo = $uuer.enddateooo }
else {$uedo = $null }
[string]$uimo = $uuer.intmesooo
[string]$uemo = $uuer.extmesooo
[bool]$glib = $uuer.halt
$uuss = $uuss.trim()
# update-window "String"
# update-window $uuss -AppendContent
con-main
}
function con-main {
try
{
Get-MsolDomain -ErrorAction Stop > $null
}
catch
{
if ($cred -eq $null){
update-window "Connecting to server to Validate, requires credentials"
$usercredential = Get-Credential
#import-module msonline
import-module azureadpreview
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection #-SessionOption $proxysettings
Import-PSSession $Session -DisableNameChecking -allowclobber
connect-msolservice -Credential $userCredential }
}
eml-valid
}
function eml-valid {
$b = $a = $null
try {
$a = Get-Mailbox $uuss -erroraction stop
}
catch {
$a = 0
}
if ($a -eq 0){
$sam,$max = $uuss.split("{@}")
try {
$b = get-aduser $sam
}
catch {
$b = 0
}
if ($b -eq 0) {
update-window "$uuss,Email NOT Found! TRY: First initial last name?"
proc-input
}
else {
update-window "Legacy Email; Changing connection. Login first initial last name email : bob smith = bsmith@companyco.com"
con-ex $glib
}
}
else {
update-window "Setting mailbox $uuss on cloud"
set-ooomessage $uuss $usdo $glib
if ($glib -ne $true){
update-window "$uuss Success, user updated in Exchange online updated" }
}
}
function set-ooomessage {
#will set out of office message if fed 3 correct strings.
Param (
[parameter(Mandatory,ValueFromPipeline)]
[string]$user,
[parameter(Mandatory,ValueFromPipeline)]
[string]$startdate,
[parameter(ValueFromPipeline)]
[bool]$halt
)
if ($halt -ne $true){
if ($uedo -ne $null){
Set-MailboxAutoReplyConfiguration $user -AutoReplyState Scheduled -StartTime $startdate -EndTime $uedo -ExternalMessage $uemo -InternalMessage $uimo
add-content $ooolog "$user,$startdate,$uedo,$uemo,$uimo"
}
else {
Set-MailboxAutoReplyConfiguration $user -AutoReplyState Scheduled -StartTime $startdate -InternalMessage $uimo -ExternalMessage $uemo
add-content $ooolog "$user,$startdate,$uemo,$uimo"
}
}
else {
add-content $ooolog "$user,$startdate,$uemo,$uimo,test"
update-window "Test occured $uuss NOT UPDATED"
}
}
function con-ex {
#connect exchange on prem
$rmtest = get-pssession
foreach ($line in $rmtest){
$cnr = $line.computername
$cnid = $line.id
if ($cnr -like "outlook.office365.com")
{
remove-pssession $cnid}
}
$UserC = Get-credential
$localEx = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.companyco.com/PowerShell/ -Authentication Kerberos -Credential $UserC
Import-PSSession $localEx -DisableNameChecking
set-ooomessage $uuss $usdo $glib
if ($glib -ne $true) {
update-window "Success: $uuss updated in Exchange On prem"}
}
Function Update-Window {
Param (
$Content,
[switch]$AppendContent
)
If ($PSBoundParameters['AppendContent']) {
$window.results.AppendText($content)
} Else {
$window.results.Text = $Content
}
}
</code></pre>
<p>** xaml.. ** </p>
<pre><code>$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="200"
Width ="440.172"
SizeToContent="Height"
Title="New Out of Office Message"
Topmost="True" Height="313.505">
<Grid Margin="10,40,10,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Margin="5">Please enter user email. If <Bold>BOLD</Bold>, Must be filled out</TextBlock>
<TextBlock Grid.Column="0" Grid.Row="1" Margin="5"><Bold>Email</Bold></TextBlock>
<TextBlock Grid.Column="0" Grid.Row="2" Margin="5"><Bold>Start Date</Bold></TextBlock>
<TextBlock Grid.Column="0" Grid.Row="3" Margin="5">End Date</TextBlock>
<TextBlock Grid.Column="0" Grid.Row="4" Margin="5"><Bold>Internal Message</Bold></TextBlock>
<TextBlock Grid.Column="0" Grid.Row="5" Margin="5"><Bold>External Message</Bold></TextBlock>
<TextBlock Grid.Column="0" Grid.Row="7" Margin="5">Results</TextBlock>
<TextBox Name="TxtEmail" Grid.Column="1" Grid.Row="1" Margin="5"></TextBox>
<DatePicker x:Name="StartDate" Grid.Column="1" Grid.Row="2" Margin="5" />
<DatePicker x:Name="EndDate" Grid.Column="1" Grid.Row="3" Margin="5" />
<TextBox Name="TxtiMesg" Grid.Column="1" Grid.Row="4" Margin="5"></TextBox>
<TextBox Name="TxteMesg" Grid.Column="1" Grid.Row="5" Margin="5"></TextBox>
<TextBox x:Name= "results" Height = "80" Grid.ColumnSpan="2" Grid.Row="8" Width = "500"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,10,0,0" Grid.Row="6" Grid.ColumnSpan="2">
<CheckBox x:Name="Item2" Content = 'Test'/>
<Button Name="ButOk" MinWidth="80" Height="22" Margin="5">OK</Button>
<Button Name="ButDone" MinWidth="80" Height="22" Margin="5">Done</Button>
<Button Name="ButCancel" MinWidth="80" Height="22" Margin="5">Cancel</Button>
</StackPanel>
</Grid>
</Window>
</code></pre>
<p><pre>
function Convert-XAMLtoWindow
{
param
(
[Parameter(Mandatory=$true)]
[string]
$XAML
)
Add-Type -AssemblyName PresentationFramework
$reader = [XML.XMLReader]::Create([IO.StringReader]$XAML)
$result = [Windows.Markup.XAMLReader]::Load($reader)
$reader.Close()
$reader = [XML.XMLReader]::Create([IO.StringReader]$XAML)
while ($reader.Read())
{
$name=$reader.GetAttribute('Name')
if (!$name) { $name=$reader.GetAttribute('x:Name') }
if($name)
{$result | Add-Member NoteProperty -Name $name -Value $result.FindName($name) -Force}
}
$reader.Close()
$result
}
function Show-WPFWindow
{
param
(
[Parameter(Mandatory=$true)]
[Windows.Window]
$Window
)
$result = $null
$null = $window.Dispatcher.InvokeAsync{
$result = $window.ShowDialog()
Set-Variable -Name result -Value $result -Scope 1
}.Wait()
$result
}
#endregion Code Behind
function get-userinp {
#region Convert XAML to Window
$window = Convert-XAMLtoWindow -XAML $xaml
#endregion</p>
<code> #region Define Event Handlers
# Right-Click XAML Text and choose WPF/Attach Events to
# add more handlers
$window.ButCancel.add_Click(
{
$window.DialogResult = $false
}
)
$window.ButOk.add_Click(
{
$window.ButOk.isenabled = $false
$window.ButDone.isenabled = $false
$window.ButCancel.isenabled = $false
# $window.DialogResult = $true
[hashtable]$return = @{}
$return.userooo = $window.TxtEmail.Text
$return.startdateooo = $window.StartDate.SelectedDate.Date.ToShortDateString()
if($window.EndDate.SelectedDate -ne $null){
$return.enddateooo = $window.EndDate.SelectedDate.Date.ToShortDateString()}
$return.extmesooo = $window.TxteMesg.Text
$return.intmesooo = $window.TxtiMesg.Text
if ($window.item2.ischecked){
$return.halt = $true}
proc-input $return
$sescleaner = get-pssession
foreach ($lin in $sescleaner){
$cnid = $lin.id
remove-pssession $cnid
}
$window.ButDone.isenabled = $true
}
)
$window.ButDone.add_Click(
{
$window.DialogResult = $true
}
)
#endregion Event Handlers
#region Manipulate Window Content
$window.TxtiMesg.Text = 'User is out of office'
$window.TxteMesg.Text = 'User is out of office'
$window.TxtEmail.Text = 'test@companyco.com'
$null = $window.TxtEmail.Focus()
#endregion
# Show Window
$result = Show-WPFWindow -Window $window
}
$ooopath = "\ooolog.txt"
$ooolog = $env:temp + $ooopath
get-userinp
#con-main
#eml-valid #uncomment to test data capture loop
#con-ex
</code></pre>
<p></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T15:37:42.200",
"Id": "393508",
"Score": "2",
"body": "Welcome to Code Review! I am uncertain as to whether your code accomplishes what you want it to, could you please clear that up for me?"
},
{
"ContentLicense": "CC BY-SA... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T14:51:10.257",
"Id": "204069",
"Score": "2",
"Tags": [
"email",
"powershell",
"xaml"
],
"Title": "GUI and Powershell script to manage mail accounts"
} | 204069 |
<p>Here is the case of ugly condition for the "if": </p>
<pre><code> private void setRequirementAttributes(List<CarParams> carParamsList) {
Vehicle vehicle = this.getModel();
for (CarParams item : carParamsList) {
if(item.getInfo().getYear().equalsIgnoreCase(vehicle.getYear())
&& item.getInfo().getMark().equalsIgnoreCase(vehicle.getMark())
&& item.getInfo().getSeries().toString().equalsIgnoreCase(vehicle.getSeries().toSting)
&& item.getInfo().getSeries().toString().equalsIgnoreCase(vehicle.getSeries().toSting)
|| (item.getInfo().getCommInfo().toString().equalsIgnoreCase(vehicle.getCommInfo().toSting))){
grabVehicleData();
}
}
}
</code></pre>
<p>so hard to read, but I need to add more details for "if condition". What is the way to refactor it, probably more elegant way for the condition.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T16:28:36.057",
"Id": "393515",
"Score": "0",
"body": "What's `toSting`? This looks like pseudocode. Also, we can't give you good advice without seeing the supporting code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creatio... | [
{
"body": "<p>One solution can be to extract out local variables for each matching condition and use those to calculate the predicate that will actually be passed to the if statement. This way the variable names indicate what you want to match on</p>\n\n<pre><code>private void setRequirementAttributes(List<C... | {
"AcceptedAnswerId": "204076",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T15:20:08.130",
"Id": "204071",
"Score": "-4",
"Tags": [
"java",
"object-oriented"
],
"Title": "Conditionally grab vehicle data depending on criteria specified as key-value pairs"
} | 204071 |
<p>I am writing a program in JavaScript to find all possible words given 7 letters. The words have to be 3 or more characters, and for right now I am limiting it to 7 characters long. The code below works, but takes forever to complete and I would like to speed it up. Would recursion help?</p>
<p>Thanks for any suggestions.</p>
<p>The variable wordList is an array of 60,000 words.</p>
<pre><code> function isWord(word){
var found = wordList.indexOf(word);
if(wordList[found]===word) return true;
else return false;
}
for(var i=0; i<letters.length; i++) {
for(var j=0; j<letters.length; j++) {
for(var k=0;k<letters.length; k++) {
if(isWord(letters[i]+letters[j]+letters[k]))
w.push(letters[i]+letters[j]+letters[k])
}
}
}
for(var i=0; i<letters.length; i++) {
for(var j=0; j<letters.length; j++) {
for(var k=0; k<letters.length; k++) {
for(var l=0; l<letters.length; l++) {
if(isWord(letters[i]+letters[j]+letters[k]+letters[l]))
w.push(letters[i]+letters[j]+letters[k]+letters[l])
}
}
}
}
for(var i=0; i<letters.length; i++) {
for(var j=0; j<letters.length; j++) {
for(var k=0; k<letters.length; k++) {
for(var l=0; l<letters.length; l++) {
for(var m=0; m<letters.length; m++) {
if(isWord(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]))
w.push(letters[i]+letters[j]+letters[k]+letters[l]+letters[m])
}
}
}
}
}
for(var i=0; i<letters.length; i++) {
for(var j=0; j<letters.length; j++) {
for(var k=0; k<letters.length; k++) {
for(var l=0; l<letters.length; l++) {
for(var m=0; m<letters.length; m++) {
for(var n=0; n<letters.length; n++) {
if(isWord(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n]))
w.push(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n])
}
}
}
}
}
}
for(var i=0; i<letters.length; i++) {
for(var j=0; j<letters.length; j++) {
for(var k=0; k<letters.length; k++) {
for(var l=0; l<letters.length; l++) {
for(var m=0; m<letters.length; m++) {
for(var n=0; n<letters.length; n++) {
for(var o=0; o<letters.length; o++) {
if(isWord(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n]+letters[o]))
w.push(letters[i]+letters[j]+letters[k]+letters[l]+letters[m]+letters[n]+letters[o])
}
}
}
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>You are forming each possible combination, and look for it in the dictionary. That indeed takes forever. You'd be in a better shape doing it other way around. Read the dictionary word by word, and for each word check if it is composed by your letters. In pseudocode,</p>\n\n<pre><code> for lette... | {
"AcceptedAnswerId": "204078",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T15:38:29.860",
"Id": "204073",
"Score": "1",
"Tags": [
"javascript",
"performance",
"algorithm",
"recursion"
],
"Title": "When given 7 letters, find all possible words with length 3 to 7"
} | 204073 |
<p>GLib is a <strong>general-purpose and cross-platform</strong> utility library, which provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on. </p>
<p>For many applications, C with GLib and GObject is an alternative to C++ with STL.
It works on many UNIX-like platforms, Windows, OS/2 and BeOS. GLib is released under the GNU Library General Public License (GNU LGPL).</p>
<p>The <a href="http://developer.gnome.org/glib/stable/" rel="nofollow noreferrer">GLib reference manual</a> can be found at the GNOME developer site.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T17:20:23.573",
"Id": "204082",
"Score": "0",
"Tags": null,
"Title": null
} | 204082 |
GLib is a general-purpose and cross-platform utility library, which provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T17:20:23.573",
"Id": "204083",
"Score": "0",
"Tags": null,
"Title": null
} | 204083 |
<p>This is my first attempt at a sizeable amount of code in Python and I've made an attempt to standardize a script into a library so that it can be reused.</p>
<p>However, <code>scraper.scraper</code> (as well as <code>scraper.Scraper</code>?) appears in Idle when you import the module.</p>
<p>Some constructive criticism on the code style/layout would be appreciated.</p>
<pre><code>#!/usr/bin/python
import requests #lib to send requests to url
from bs4 import BeautifulSoup #parse HTML data into python data types
from user_agent import generate_user_agent #user agent spoof
from time import sleep #wait when failing to get url
#Custom Exception that can be caught top level
class ScrapeException(Exception):
__doc__ = '''Exception will be thrown from this module if a standard error occurs
if __debig__ is true it will contain the BeautifulSoup object from the last scrape
'''
def __init__(self, scrape_error, soup = None):
self.scrape_error = scrape_error
self.soup = soup
def __str__(self):
return self.scrape_error
#Retrieve site specified by url, response on success otherwise will throw ScrapeException
def getpage(url, timeout=5, headers=None, retries=10, twait=1):
__doc__ = 'Download a webpage'
if not headers:
headers = {'User-Agent': generate_user_agent(device_type="desktop", os=('mac', 'linux'))}
attempt = 0
while(attempt < retries):
try:
#download page using requests lib
response = requests.get(url, timeout=timeout, headers=headers)
if(response.ok): #If download successful return response
return response
else:
error = 'Error fetching url"{}", "{}"'.format(url, response.reason)
except (requests.ConnectTimeout, requests.ReadTimeout, requests.ConnectionError) as e:
error = 'Timed out fetching url"{}"\n{}'.format(url, e) #Time out
print('Attempt {} failed, retrying....'.format(attempt))
sleep(twait)
attempt += 1
raise ScrapeException('Failed after {} attempts\n{}'.format(retries, error))
#class for scraping a particular element from a webpage
#For any derived classes, scrapenext() must be defined
#For all instances, [instance of ScrapBase].nxt must point to the next scraper or be Null for last instance
class ScrapeBase:
#virtual method, returns scraped soup for next stage or return
def scrape(self, soup):
pass
def scrapenext(self, soup):
#storing soup output at each level is wasteful, but useful for detecting when things have gone wrong!
if __debug__:
self.soup = soup
if self.nxt:
return self.nxt.scrape(soup) #Scrape next stage
else:
return soup #No next stage, return output
#class for retrieveing web page using beautifulsoup
class ScrapePage(ScrapeBase):
#input (url of website to scrape, timeout in seconds (default 5), HTML headers (default destkop linux))
def __init__(self, url, timeout=5, headers=None, retries=10, twait=1):
self.url = url
self.timeout = timeout
self.headers = headers
self.twait = twait
self.retries = retries
#soup argument inherited ScrapBase but is not used, can set to Null
def scrape(self, soup):
print('Scraping page from url "{}"'.format(self.url))
response = getpage(self.url, timeout=self.timeout, headers=self.headers, retries=self.retries, twait=self.twait)
return self.scrapenext(BeautifulSoup(response.content, 'html5lib'))
#Find a tag of type [name], can specify attributes in [attrs]
class ScrapeTag(ScrapeBase):
def __init__(self, name, attrs={}, getAll=False):
self.name = name
self.attrs = attrs
self.getAll = getAll
def scrape(self, soup):
print('Searching for tag type "{}" with attributes "{}"'.format(self.name, self.attrs))
if self.getAll: #Find all tags with name and specified attributes
f = soup.findAll
else: #Find next tag with name and specified attributes
f = soup.find
nextsoup = f(self.name, attrs=self.attrs)
if not nextsoup:
#Error finding tag or tag not exist, throw error
raise ScrapeException('Could not find "{}" with attributes {}'.format(self.name, self.attrs), soup)
return self.scrapenext(nextsoup)
#Retrieve attribute from tag specified by [attr]
class ScrapeHTMLAttribute(ScrapeBase):
def __init__(self, attr):
self.attr = attr
def scrape(self, soup):
print('Retrieving HTML attribute "{}"'.format(self.attr))
#Check if attribute exists
if not soup.has_attr(self.attr):
raise ScrapeException('Could not find "{}" attribute'.format(self.attr), soup)
return self.scrapenext(soup.attrs[self.attr])
#Get array element, can either give [i] as an index or slice
class ScrapeArrayElement(ScrapeBase):
def __init__(self, i):
assert (type(i) == int) or (type(i) == slice)
self.i = i
self.topi = i if type(i)==int else i.stop #if i is int then array index max is i, if slice then i.top
def scrape(self, soup):
print('Getting element {}'.format(self.i))
if len(soup) < self.topi:
raise ScrapeException('List was big enough to index element\slice {}'.format(self.i), soup)
return self.scrapenext(soup[self.i])
#Get an attribute from the python object itself, e.g. for tag.contents input 'contents'
class ScrapeSoupAttribute(ScrapeBase):
def __init__(self, attr):
self.attr = attr
def scrape(self, soup):
print('Retrieving python (soup) attribute "{}"'.format(self.attr))
if not hasattr(soup, self.attr):
raise ScrapeException('Python (soup) object has no attribute "{}"'.format(self.attr))
return self.scrapenext(getattr(soup, self.attr))
#Scrape a full webpage. Pass iterator of derived ScrapeBase instances in order for scraping.
class Scraper:
__doc__ = '''Class for scraping a web page\n
[scrapers]: Array of scraper types with their corresponding arguments passed as a dictionary
[soup]: BeautifulSoup object passed to the first element of [scrapers] - not required if
first element is of type 'page'
type req opt Description
'page' 'url' timeout=5, headers=None Fetch a webpage from a given url, [url]
retries=10, twait=1
'tag' 'name' attrs, getAll Get first HTML tag <[name]> with
attributes [attrs]. If getAll is
true returns array of all matching tags
'HTML attr' 'attr' Get a HTML attribute value
'soup attr' 'attr' Get a python attribute [attr] of
BeautifulSoup object, normally
this is 'contents'
'array' 'i' Get elements array, [i] can be either be
an integer or slice
'''
__author__ = 'the_noobie_programmer'
def __init__(self, scrapes, soup=None):
#assign soup input for passing to first call of scraper
self.soup = soup
#check array passed is not empty
if len(scrapes) < 1:
raise ScrapeException('Need at least 1 scraper to begin!')
#keeping __debug__ on uses more memory as it stores every scrape object which in turns stores the soup object for processing
if __debug__:
self.scrapers = []
#last scraper has no next
nxt = None
#loop from top, i.e. last scraper first
for args in reversed(scrapes):
if len(args) < 1:
raise ScrapeException('Cannot pass an empty scraper!')
#create scraper object - first argument is name, proceeding args ar arguments passed to constructor
s = self._createscraper(args)
#set next scraper to that of previous cycle
s.nxt = nxt
#update next scraper to the current object (looping backwards remember)
nxt = s
#if __debug__ on keep an instance of each scraper so that any errors in scraping can be easily looked up
if __debug__:
self.scrapers.insert(0, s)
self.firstscraper = s
#entry point for user - go!
def scrape(self):
return self.firstscraper.scrape(self.soup)
#Create scraper from string name and arguments
def _createscraper(self, args):
if 'type' not in args:
#type is a required argument
raise ScrapeException('Argument dictionary must contain "type"!')
#get scraper type - remove type from dictionary
name = args.pop('type')
if name not in self._scrapers:
#scraper type not valid
valid_names = [nm for nm in self._scrapers.keys()]
raise ScrapeException('"{}" is not recognised as a valid scraper type\n'
'If you are only user one scraper be sure to put double square brackets!\n'
'Valid types are: {}'.format(name, valid_names))
#lookup in dictionary from name string and pass arguments to constructor
return self._scrapers[name](**args)
#dictionary from strings to scraper class types
_scrapers = {
'page': ScrapePage,
'tag': ScrapeTag,
'HTML attr': ScrapeHTMLAttribute,
'soup attr': ScrapeSoupAttribute,
'array': ScrapeArrayElement }
</code></pre>
<p>The init file import is:</p>
<pre><code>from .scraper import Scraper, ScrapeException, getpage
</code></pre>
<p>An example of it in action:</p>
<pre><code>import scraper
scrapes=[
{'type':'page', 'url':'http://google.co.uk/search?q="What is my ip"'},
{'type':'tag', 'name':'w-answer-desktop'},
{'type':'tag', 'name':'div'},
{'type':'soup attr', 'attr':'contents'},
{'type':'array', 'i':0}]
google = scraper.Scraper(scrapes)
ip = google.scrape()
print(ip)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T06:16:08.270",
"Id": "393963",
"Score": "1",
"body": "Hey Joel, thanks for your post. I actually watched this on the weekend: https://www.youtube.com/watch?v=o9pEzgHorH0 it was quite interesting. Looking at your code, I see many o... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-20T21:41:23.787",
"Id": "204090",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "Python web scraper"
} | 204090 |
<p>I have been programming for a long time. Only recently have I decided to take a stab at Python (I should be working with C# as I am in school for it, but I don't care for Windows, long story).</p>
<p>I was on this site and it showed a source for a calculator. I took it, and put it in PyCharm and started to study. By the time I was done I had changed the source significantly. I had added keyboard binding and reduced a lot of the redundant code in it.</p>
<p>My question is simple: is this code that I wrote efficient from a python standard viewpoint?</p>
<pre><code># -*-coding: utf-8-*-
# !/usr/bin/python3.5
from tkinter import Tk, Button, Entry, END
import math
class Calc:
def getandreplace(self): # replace x, + and % to symbols that can be used in calculations
# we wont re write this to the text box until we are done with calculations
self.txt = self.e.get() # Get value from text box and assign it to the global txt var
self.txt = self.txt.replace('÷', '/')
self.txt = self.txt.replace('x', '*')
self.txt = self.txt.replace('%', '/100')
def evaluation(self, specfunc): # Evaluate the items in the text box for calculation specfunc = eq, sqroot or power
self.getandreplace()
try:
self.txt = eval(str(self.txt)) # evaluate the expression using the eval function
except SyntaxError:
self.displayinvalid()
else:
if any([specfunc == 'sqroot', specfunc == 'power']): # Square Root and Power are special
self.txt = self.evalspecialfunctions(specfunc)
self.refreshtext()
def displayinvalid(self):
self.e.delete(0, END)
self.e.insert(0, 'Invalid Input!')
def refreshtext(self): # Delete current contents of textbox and replace with our completed evaluatioin
self.e.delete(0, END)
self.e.insert(0, self.txt)
def evalspecialfunctions(self, specfunc): # Calculate square root and power if specfunc is sqroot or power
if specfunc == 'sqroot':
return math.sqrt(float(self.txt))
elif specfunc == 'power':
return math.pow(float(self.txt), 2)
def clearall(self): # AC button pressed on form or 'esc" pressed on keyboard
self.e.delete(0, END)
self.e.insert(0, '0')
def clear1(self, event=None):
# C button press on form or backspace press on keyboard event defined on keyboard press
if event is None:
self.txt = self.e.get()[:-1] # Form backspace done by hand
else:
self.txt = self.getvalue() # No need to manually delete when done from keyboard
self.refreshtext()
def action(self, argi: object): # Number or operator button pressed on form and passed in as argi
self.txt = self.getvalue()
self.stripfirstchar()
self.e.insert(END, argi)
def keyaction(self, event=None): # Key pressed on keyboard which defines event
self.txt = self.getvalue()
if any([event.char.isdigit(), event.char in '/*-+%().']):
self.stripfirstchar()
elif event.char == '\x08':
self.clear1(event)
elif event.char == '\x1b':
self.clearall()
elif event.char == '\r':
self.evaluation('eq')
else:
self.displayinvalid()
return 'break'
def stripfirstchar(self): # Strips leading 0 from text box with first key or button is pressed
if self.txt[0] == '0':
self.e.delete(0, 1)
def getvalue(self): # Returns value of the text box
return self.e.get()
def __init__(self, master): # Constructor method
self.txt = 'o' # Global var to work with text box contents
master.title('Calulator')
master.geometry()
self.e = Entry(master)
self.e.grid(row=0, column=0, columnspan=6, pady=3)
self.e.insert(0, '0')
self.e.focus_set() # Sets focus on the text box text area
# Generating Buttons
Button(master, text="=", width=10, command=lambda: self.evaluation('eq')).grid(row=4, column=4, columnspan=2)
Button(master, text='AC', width=3, command=lambda: self.clearall()).grid(row=1, column=4)
Button(master, text='C', width=3, command=lambda: self.clear1()).grid(row=1, column=5)
Button(master, text="+", width=3, command=lambda: self.action('+')).grid(row=4, column=3)
Button(master, text="x", width=3, command=lambda: self.action('x')).grid(row=2, column=3)
Button(master, text="-", width=3, command=lambda: self.action('-')).grid(row=3, column=3)
Button(master, text="÷", width=3, command=lambda: self.action('÷')).grid(row=1, column=3)
Button(master, text="%", width=3, command=lambda: self.action('%')).grid(row=4, column=2)
Button(master, text="7", width=3, command=lambda: self.action('7')).grid(row=1, column=0)
Button(master, text="8", width=3, command=lambda: self.action('8')).grid(row=1, column=1)
Button(master, text="9", width=3, command=lambda: self.action('9')).grid(row=1, column=2)
Button(master, text="4", width=3, command=lambda: self.action('4')).grid(row=2, column=0)
Button(master, text="5", width=3, command=lambda: self.action('5')).grid(row=2, column=1)
Button(master, text="6", width=3, command=lambda: self.action('6')).grid(row=2, column=2)
Button(master, text="1", width=3, command=lambda: self.action('1')).grid(row=3, column=0)
Button(master, text="2", width=3, command=lambda: self.action('2')).grid(row=3, column=1)
Button(master, text="3", width=3, command=lambda: self.action('3')).grid(row=3, column=2)
Button(master, text="0", width=3, command=lambda: self.action('0')).grid(row=4, column=0)
Button(master, text=".", width=3, command=lambda: self.action('.')).grid(row=4, column=1)
Button(master, text="(", width=3, command=lambda: self.action('(')).grid(row=2, column=4)
Button(master, text=")", width=3, command=lambda: self.action(')')).grid(row=2, column=5)
Button(master, text="√", width=3, command=lambda: self.evaluation('sqroot')).grid(row=3, column=4)
Button(master, text="x²", width=3, command=lambda: self.evaluation('power')).grid(row=3, column=5)
# bind key strokes
self.e.bind('<Key>', lambda evt: self.keyaction(evt))
# Main
root = Tk()
obj = Calc(root) # object instantiated
root.mainloop()
</code></pre>
<p>I don't really care for the names of some of the function names and variable names. I like using descriptive names, so names like <code>self.e</code> would have been called <code>self.textbox</code> or something. These things are leftovers from the web copy I found and haven't changed them.</p>
<p>Per request, the original code for this is below.</p>
<blockquote>
<pre><code>#-*-coding: utf-8-*-
from Tkinter import *
import math
class calc:
def getandreplace(self):
"""replace x with * and ÷ with /"""
self.expression = self.e.get()
self.newtext=self.expression.replace(self.newdiv,'/')
self.newtext=self.newtext.replace('x','*')
def equals(self):
"""when the equal button is pressed"""
self.getandreplace()
try:
self.value= eval(self.newtext) #evaluate the expression using the eval function
except SyntaxError or NameErrror:
self.e.delete(0,END)
self.e.insert(0,'Invalid Input!')
else:
self.e.delete(0,END)
self.e.insert(0,self.value)
def squareroot(self):
"""squareroot method"""
self.getandreplace()
try:
self.value= eval(self.newtext) #evaluate the expression using the eval function
except SyntaxError or NameErrror:
self.e.delete(0,END)
self.e.insert(0,'Invalid Input!')
else:
self.sqrtval=math.sqrt(self.value)
self.e.delete(0,END)
self.e.insert(0,self.sqrtval)
def square(self):
"""square method"""
self.getandreplace()
try:
self.value= eval(self.newtext) #evaluate the expression using the eval function
except SyntaxError or NameErrror:
self.e.delete(0,END)
self.e.insert(0,'Invalid Input!')
else:
self.sqval=math.pow(self.value,2)
self.e.delete(0,END)
self.e.insert(0,self.sqval)
def clearall(self):
"""when clear button is pressed,clears the text input area"""
self.e.delete(0,END)
def clear1(self):
self.txt=self.e.get()[:-1]
self.e.delete(0,END)
self.e.insert(0,self.txt)
def action(self,argi):
"""pressed button's value is inserted into the end of the text area"""
self.e.insert(END,argi)
def __init__(self,master):
"""Constructor method"""
master.title('Calulator')
master.geometry()
self.e = Entry(master)
self.e.grid(row=0,column=0,columnspan=6,pady=3)
self.e.focus_set() #Sets focus on the input text area
self.div='÷'
self.newdiv=self.div.decode('utf-8')
#Generating Buttons
Button(master,text="=",width=10,command=lambda:self.equals()).grid(row=4, column=4,columnspan=2)
Button(master,text='AC',width=3,command=lambda:self.clearall()).grid(row=1, column=4)
Button(master,text='C',width=3,command=lambda:self.clear1()).grid(row=1, column=5)
Button(master,text="+",width=3,command=lambda:self.action('+')).grid(row=4, column=3)
Button(master,text="x",width=3,command=lambda:self.action('x')).grid(row=2, column=3)
Button(master,text="-",width=3,command=lambda:self.action('-')).grid(row=3, column=3)
Button(master,text="÷",width=3,command=lambda:self.action(self.newdiv)).grid(row=1, column=3)
Button(master,text="%",width=3,command=lambda:self.action('%')).grid(row=4, column=2)
Button(master,text="7",width=3,command=lambda:self.action('7')).grid(row=1, column=0)
Button(master,text="8",width=3,command=lambda:self.action(8)).grid(row=1, column=1)
Button(master,text="9",width=3,command=lambda:self.action(9)).grid(row=1, column=2)
Button(master,text="4",width=3,command=lambda:self.action(4)).grid(row=2, column=0)
Button(master,text="5",width=3,command=lambda:self.action(5)).grid(row=2, column=1)
Button(master,text="6",width=3,command=lambda:self.action(6)).grid(row=2, column=2)
Button(master,text="1",width=3,command=lambda:self.action(1)).grid(row=3, column=0)
Button(master,text="2",width=3,command=lambda:self.action(2)).grid(row=3, column=1)
Button(master,text="3",width=3,command=lambda:self.action(3)).grid(row=3, column=2)
Button(master,text="0",width=3,command=lambda:self.action(0)).grid(row=4, column=0)
Button(master,text=".",width=3,command=lambda:self.action('.')).grid(row=4, column=1)
Button(master,text="(",width=3,command=lambda:self.action('(')).grid(row=2, column=4)
Button(master,text=")",width=3,command=lambda:self.action(')')).grid(row=2, column=5)
Button(master,text="√",width=3,command=lambda:self.squareroot()).grid(row=3, column=4)
Button(master,text="x²",width=3,command=lambda:self.square()).grid(row=3, column=5)
#Main
root = Tk()
obj=calc(root) #object instantiated
root.mainloop()
</code></pre>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T01:30:41.400",
"Id": "393540",
"Score": "0",
"body": "For comparison, could you add a link to where you got the original code from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T03:07:37.427",
"... | [
{
"body": "<p>\nWhen I was learning Python, I found <a href=\"https://www.python.org/dev/peps/pep-0020/#the-zen-of-python\" rel=\"nofollow noreferrer\">The Zen of Python</a> quite helpful.</p>\n\n<h1>Formatting</h1>\n\n<p>I agree about renaming <code>self.e</code> to <code>self.textbox</code>. Descriptive names... | {
"AcceptedAnswerId": "208324",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T00:13:36.047",
"Id": "204094",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"calculator",
"tkinter"
],
"Title": "Python 3 calculator with tkinter"
} | 204094 |
<p>I was in a code review today and someone said, "Why don't you do an <code>enum</code> on that?" I had started to, but conforming to a bunch of protocols seemed like a gigantic PITA and it seemed more error prone than just writing something simple, readable, and maintainable.</p>
<p>That said, I started to fiddle around with it this evening and I can't figure it out.</p>
<p>This is what I've started with:</p>
<pre><code>typealias PolicyType = (filename: String, text: String)
struct Policy {
static let first = PolicyType(filename: "firstFile.txt", text: "text in first file")
static let second = PolicyType(filename: "secondFile.txt", text: "text in second file")
static let third = PolicyType(filename: "thirdFile.txt", text: "text in third file")
}
let thirdPolicyText = Policy.third.text
</code></pre>
<p>Is there a more memory efficient, maintainable way to do this with an <code>enum</code>? My primary objective is maintainability.</p>
<p>Below is what I've come up with. It feels hacky and looks like...well, you know:</p>
<pre><code>public struct PolicyType : Equatable, ExpressibleByStringLiteral {
var filename: String
var text: String
//MARK:- Equatable Methods
public static func == (lhs: PolicyType, rhs: PolicyType) -> Bool {
return (lhs.filename == rhs.filename && lhs.text == rhs.text)
}
//MARK:- ExpressibleByStringLiteral Methods
public init(stringLiteral value: String) {
let components = value.components(separatedBy: "|")
self.filename = components[0]
self.text = components[1]
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
enum Policy: PolicyType {
case first = "testFile1.txt|This is sample text"
case second = "testFile2.txt|This is more sample text"
case third = "testFile3.txt|This is more sample text"
}
Policy.third.rawValue.text
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T04:10:25.943",
"Id": "393544",
"Score": "0",
"body": "There is a difference between `struct Policy` and `enum Policy`: In the first case you have a type with 3 “predefined” values, but a program can create additional values, with ar... | [
{
"body": "<ol>\n<li><p>The code is using Enum, but it's still using Struct.</p></li>\n<li><p>The program may be buggy if the text value has character <code>|</code>. Suppose that \"testFile1.txt|This is sample text\" to \"testFile1.txt|This is | sample text\".</p></li>\n</ol>\n\n<p>I have another approach with... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T00:28:13.257",
"Id": "204096",
"Score": "2",
"Tags": [
"swift",
"enum"
],
"Title": "Creating an Enum with a Custom Type in Swift 4.x"
} | 204096 |
<h1>Background</h1>
<p>(Feel free to skip; the help center just recommended adding background information :)</p>
<p>A few days ago, I was looking at some code which happened to use a flat array to store a complete binary tree. That got me thinking about calculating some properties of such a tree. The number of nodes in a perfect binary tree of depth <code>n</code> would be <code>2 ** n - 1</code>, the index of the parent node, given a child node <code>i</code> would be <code>(i - 1) >> 1</code> and the level of node <code>i</code> in the tree would be <code>(i + 1).bit_length()</code>.</p>
<p>What if we wanted to extend the data structure to k-ary trees? The number of nodes in a perfect k-ary tree of depth <code>n</code> would be <code>(k ** n - 1) // (k - 1)</code>, the index of the parent node, given a child node <code>i</code> would be <code>(i - 1) // k</code> and the level of node <code>i</code> in the tree would be <code>base_k_digit_length((i + 1) * (k - 1))</code> (which is sort of the inverse of the number of nodes calculation).</p>
<p>So, what does <code>base_k_digit_length(x)</code> really correspond to? Well, conceptually, it's <code>ceil(log(x + 1, k))</code>.</p>
<h1>Integer logarithms</h1>
<p>(Essentially, more background information; Again, feel free to skip)</p>
<p>There are 4 different variants of integer logarithm that I consider interesting, which differ on how the real-valued logarithm is rounded to an integer and correspond to the inequality operators >, ≥, <, and ≤ (based on how the integer return value corresponds to the real return value):</p>
<ul>
<li><code>gt_log(x, k) = ceil(log(x + 1, k))</code></li>
<li><code>ge_log(x, k) = ceil(log(x, k))</code></li>
<li><code>lt_log(x, k) = floor(log(x - 1, k))</code></li>
<li><code>le_log(x, k) = floor(log(x, k))</code></li>
</ul>
<p>Unfortunately, because of the inexactness of floating point, those definitions can't be used directly. For example, at least on my machine, <code>log(125, 5)</code> returns <code>3.0000000000000004</code> instead of <code>3</code>, which means such <code>gt_log(124, 5)</code> would return <code>4</code> instead of the correct <code>3</code>.</p>
<p>Now, said functions could be implemented using very simple loops that would have <code>O(log x)</code> running time, but I wanted to opt for an <code>O(1)</code> implementation based on lookup tables indexed on <code>int.bit_length()</code>. (And I did check - <code>int.bit_length()</code> is <code>O(1)</code>, since Python knows the length of the buffer used to store the data for an integer, so it only has to find the most significant 1-bit in the most significant element)</p>
<p>Busting out lookup tables might sound silly, since even in Python, the loop-based approach will only take a few microseconds with any realistically sized argument, so while the lookup table based approach is 2-10x faster, it's a few microseconds we're talking about. But I see it this way: If I used loops for this, that could make some <code>O(n)</code> algorithm in the future into a <code>O(n log n)</code> algorithm, even if the difference wouldn't really be much time-wise (ie. other operations would probably usually shadow the cost of the logarithm).</p>
<h1>The code</h1>
<pre><code>_lut = {}
def _init_next_power(limits, power, value):
"""Insert LUT entries for all bit lengths between the given power and the previous one
The given power must be exactly one larger than the previous one!
"""
bitlen = value.bit_length()
# All numbers (with previous_bitlen < number.bit_length() <= bitlen) less than the given value have an integer logarithm equal to the given power
while len(limits) <= bitlen:
limits.append((power, value))
return bitlen
def init_upto_power(max_power, base):
"""Initialize or extend the range supported by the integer logarithm functions so that all integers up to base ** max_power are supported for the given base"""
limits = _lut.setdefault(base, [(0, 1), (0, 1)])
min_power, value = limits[-1]
for power in range(min_power + 1, max_power + 1):
value *= base
_init_next_power(limits, power, value)
return power, value
def init_upto_bitlen(max_bitlen, base):
"""Initialize or extend the range supported by the integer logarithm functions so that all integers up to the given bit length are supported for the given base"""
limits = _lut.setdefault(base, [(0, 1), (0, 1)])
power, value = limits[-1]
bitlen = len(limits) - 1
while bitlen < max_bitlen:
value *= base
power += 1
bitlen = _init_next_power(limits, power, value)
return power, value
def gt_log(value, base):
"""Return the minimum power of base greater than value
That is, the returned power satisfies: base ** (power - 1) <= value < base ** power
This is also the exact integer equivalent of: ceil(log(value + 1, base))
"""
assert value > 0, 'Logarithm is only defined for numbers greater than zero (the power approaches negative infinity as the value approaches zero)'
power, limit = _lut[base][value.bit_length()]
return power + (value >= limit)
def ge_log(value, base):
"""Return the minimum power of base greater than or equal to value
That is, the returned power satisfies: base ** (power - 1) < value <= base ** power
This is also the exact integer equivalent of: ceil(log(value, base))
"""
assert value > 0, 'Logarithm is only defined for numbers greater than zero (the power approaches negative infinity as the value approaches zero)'
power, limit = _lut[base][value.bit_length()]
return power + (value > limit)
def lt_log(value, base):
"""Return the maximum power of base less than value
That is, the returned power satisfies: base ** power < value <= base ** (power + 1)
This is also the exact integer equivalent of: floor(log(value - 1, base))
"""
assert value > 0, 'Logarithm is only defined for numbers greater than zero (the power approaches negative infinity as the value approaches zero)'
power, limit = _lut[base][value.bit_length()]
return power - (value <= limit)
def le_log(value, base):
"""Return the maximum power of base less than or equal to value
That is, the returned power satisfies: base ** power <= value < base ** (power + 1)
This is also the exact integer equivalent of: floor(log(value, base))
"""
assert value > 0, 'Logarithm is only defined for numbers greater than zero (the power approaches negative infinity as the value approaches zero)'
power, limit = _lut[base][value.bit_length()]
return power - (value < limit)
if __name__ == '__main__':
import math
# When we say ceil(log(value + 1, base)), we really mean ceil(log(value + epsilon, base)), where 0 < epsilon <= 1
# Since log(0) is undefined, we use epsilon < 1, so we don't get an error in the floor(log(value - epsilon, base)) case
epsilon = 0.5
# Since some of the floating point values returned by log(base ** power, base) are not exactly equal to power, we round
# the return value of log() to the given precision - just enough to get the correct return value with exact powers
precision = 14
max_value = 10**6
for base in range(2, 11):
print(base)
init_upto_bitlen(max_value.bit_length(), base)
for value in range(1, max_value + 1):
power = gt_log(value, base)
assert base ** (power - 1) <= value < base ** power
assert power == math.ceil(round(math.log(value + epsilon, base), precision))
power = ge_log(value, base)
assert base ** (power - 1) < value <= base ** power
assert power == math.ceil(round(math.log(value, base), precision))
power = lt_log(value, base)
assert base ** power < value <= base ** (power + 1)
assert power == math.floor(round(math.log(value - epsilon, base), precision))
power = le_log(value, base)
assert base ** power <= value < base ** (power + 1)
assert power == math.floor(round(math.log(value, base), precision))
</code></pre>
<p>I am mostly concerned about the naming of the initialization functions; I feel like <code>init_upto_*</code> sounds like the functions can only be called once, for initialization. Then again, if the names were something like <code>extend_range_to_*</code>, I wonder if it'd be too non-obvious that one of them <em>has</em> to be called for initialization before using the other functions. (I also considered using "by" or "with" in place of "upto" or "to", in the same way you might have <code>group_by_length</code>)</p>
<p>I also thought about some kind of <code>ceil_log()</code> -style naming for the actual lookup functions, but couldn't figure out a reasonable way to differentiate between the > and ≥ cases. The working name for the module is <code>intlog</code> - for "integer logarithm" - but I'm not perfectly convinced about that either.</p>
<p>I fully expect to get comments along the lines of "The <code>xx_log()</code> functions should just dynamically extend the lookup table!", and that is perfectly valid critique, but since the functions are so small, I feel like the percentual slowdown caused by such logic would be a bit regrettable. Still, I might end up making that the default, and adding a <code>fast_</code> prefix to the current functions. In any case, even if the functions <em>did</em> do the LUT growing automatically, the init functions would still need a good name. (Although the names would be a bit less critical, since they wouldn't be a part of the public API)</p>
<p>While I'm mostly concerned about the naming - since I can see clear problems with it - I'm of course open to any and all possible feedback!</p>
| [] | [
{
"body": "<p>I think this code is pretty good, I like the <strong>docstrings</strong>!</p>\n\n<p>Some things strike me as a bit awkward though,</p>\n\n<ol>\n<li><p>Stay DRY</p>\n\n<p>These log functions are really similar, the only thing that differentiates is the operators</p>\n\n<p>You could make the operato... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T01:39:26.207",
"Id": "204097",
"Score": "4",
"Tags": [
"python",
"lookup"
],
"Title": "Naming initialization functions in a lookup table based implementation of integer logarithms"
} | 204097 |
<p>This is a program I typed up for a project pertaining to GPA calculation. However, I want to find an alternative to if then statements that are NOT conditionals, loops, or arrays. Is there an alternative solution to changing this format?</p>
<pre><code>import java.util.Scanner;
public class Part1 {
public static void main(String args[]) {
String grade = "";
String[] letters = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "F"};
// Creates strings above and the GPA values below
double[] grades = {4.33, 4.00, 3.67, 3.33, 3.00, 2.67, 2.33, 2.00, 1.67, 1.00, 0.00};
double credit1;
double credit2;
double credit3;
double credit4;
double gradeValue = 0;
// Creates 4 credits
double totPtsClass1 = 0;
double totPtsClass2 = 0;
double totPtsClass3 = 0;
double totPtsClass4 = 0;
double totPts = 0;
double totalCredits = 0;
double gpa;
// Points in classes, GPA
System.out.println("Welcome to the UNG GPA Calculator!");
String message;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your first name: ");
message = scan.nextLine();
System.out.println("Enter your last name: ");
message = scan.nextLine();
System.out.println("Enter your major: ");
message = scan.nextLine();
System.out.println("Enter the number of your first class: ");
message = scan.nextLine();
Scanner console = new Scanner(System.in);
System.out.println("Please enter the number of credits of the class 1 (A number)");
credit1 = console.nextDouble();
System.out.println("Please enter your grades for the class 1(Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals("A")) gradeValue = 4.00;
else if (grade.equals("A-")) gradeValue = 3.67;
else if (grade.equals("B+")) gradeValue = 3.33;
else if (grade.equals("B")) gradeValue = 3.00;
else if (grade.equals("B-")) gradeValue = 2.67;
else if (grade.equals("C+")) gradeValue = 2.33;
else if (grade.equals("C")) gradeValue = 2.00;
else if (grade.equals("D+")) gradeValue = 1.33;
else if (grade.equals("D")) gradeValue = 1.00;
else if (grade.equals("F")) gradeValue = 0;
else if (grade.equals("FX")) gradeValue = 0;
else System.out.println("Invalid Grade");
totPtsClass1 = gradeValue * credit1;
System.out.println("Please enter the number of credits of the class 2 (A number)");
credit2 = console.nextDouble();
System.out.println("Please enter your grades for the class 2 (Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals("A")) gradeValue = 4.00;
else if (grade.equals("A-")) gradeValue = 3.67;
else if (grade.equals("B+")) gradeValue = 3.33;
else if (grade.equals("B")) gradeValue = 3.00;
else if (grade.equals("B-")) gradeValue = 2.67;
else if (grade.equals("C+")) gradeValue = 2.33;
else if (grade.equals("C")) gradeValue = 2.00;
else if (grade.equals("D+")) gradeValue = 1.33;
else if (grade.equals("D")) gradeValue = 1.00;
else if (grade.equals("F")) gradeValue = 0;
else if (grade.equals("FX")) gradeValue = 0;
else System.out.println("Invalid Grade");
totPtsClass2 = gradeValue * credit2;
System.out.println("Please enter the number of credits of the class 3 (A number)");
credit3 = console.nextDouble();
System.out.println("Please enter your grades for the class 3 (Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals("A")) gradeValue = 4.00;
else if (grade.equals("A-")) gradeValue = 3.67;
else if (grade.equals("B+")) gradeValue = 3.33;
else if (grade.equals("B")) gradeValue = 3.00;
else if (grade.equals("B-")) gradeValue = 2.67;
else if (grade.equals("C+")) gradeValue = 2.33;
else if (grade.equals("C")) gradeValue = 2.00;
else if (grade.equals("D+")) gradeValue = 1.33;
else if (grade.equals("D")) gradeValue = 1.00;
else if (grade.equals("F")) gradeValue = 0;
else if (grade.equals("FX")) gradeValue = 0;
else System.out.println("Invalid Grade");
totPtsClass3 = gradeValue * credit3;
System.out.println("Please enter the number of credits of the class 4 (A number)");
credit4 = console.nextDouble();
System.out.println("Please enter your grades for the class 4 (Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals("A")) gradeValue = 4.00;
else if (grade.equals("A-")) gradeValue = 3.67;
else if (grade.equals("B+")) gradeValue = 3.33;
else if (grade.equals("B")) gradeValue = 3.00;
else if (grade.equals("B-")) gradeValue = 2.67;
else if (grade.equals("C+")) gradeValue = 2.33;
else if (grade.equals("C")) gradeValue = 2.00;
else if (grade.equals("D+")) gradeValue = 1.33;
else if (grade.equals("D")) gradeValue = 1.00;
else if (grade.equals("F")) gradeValue = 0;
else if (grade.equals("FX")) gradeValue = 0;
else System.out.println("Invalid Grade");
totPtsClass4 = gradeValue * credit4;
totPts = totPtsClass1 + totPtsClass2 + totPtsClass3 + totPtsClass4;
totalCredits = credit1 + credit2 + credit3 + credit4;
gpa = totPts / totalCredits;
System.out.printf("Your GPA is: %.2f\n", +gpa);
}
}
</code></pre>
<p>I would like a solution other than the three above, but I'm unfamiliar with anything to substitute for all those if then statements.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T11:30:37.400",
"Id": "394129",
"Score": "0",
"body": "@Roman [Edits of the code should not be done](https://codereview.meta.stackexchange.com/questions/762/should-you-edit-someone-elses-code-in-a-question) here, in general. Recommen... | [
{
"body": "<p>Put the Grade-Score mapping in a HashMap and read it from there.</p>\n\n<p>Do this once:</p>\n\n<pre><code> Map<String, Double> gradeToScore = new HashMap<>();\n gradeToScore.put(\"A\", 4.00);\n gradeToScore.put(\"A-\", 3.67);\n gradeToScore.put(\"B+\", 3.33);\n gradeToS... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T02:35:57.257",
"Id": "204099",
"Score": "4",
"Tags": [
"java",
"calculator"
],
"Title": "GPA calculator in Java"
} | 204099 |
<p>I wrote a non-cryptographic hash function in C, which I am hoping might be suitable for use in an implementation of hash sets or hash maps.</p>
<pre><code>uint_fast32_t hash_u32(uint_fast32_t x) {
uint_fast32_t h = x;
h = h ^ (h>>16);
h = h * 0xae6a495b;
h = h ^ (h<<16);
h = h * 0xae6a495b;
return h;
}
</code></pre>
<p>I've tested this integrated into a set implementation before, which can be seen <a href="https://gist.github.com/modimore/f9e1d4d43b89bc5d3c6c10fa26aada5e" rel="nofollow noreferrer">here</a>, and it seems to be working fine, but I'm interested in knowing whether this is a good approach to integer hashing, or general hashing assuming all problem domains can be reduced to map the value to an integer and then hash that.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T12:31:55.043",
"Id": "393585",
"Score": "2",
"body": "Could you explain why you're hashing a `uint_fast32_t` to `uint_fast32_t`? That doesn't appear to gain you anything unless you further reduce the range (e.g. by slicing). What'... | [
{
"body": "<blockquote>\n <p>... in knowing whether this is a good approach ...</p>\n</blockquote>\n\n<p>Small improvements</p>\n\n<p><strong>Keep in range</strong></p>\n\n<p><code>uint_fast32_t</code> may be wider than 32 bits. Values outside the 32-bit range in <code>x</code> will have a result that depends... | {
"AcceptedAnswerId": "204128",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T04:03:26.510",
"Id": "204101",
"Score": "0",
"Tags": [
"c",
"integer",
"hashcode"
],
"Title": "Hash function in C for sets and associative arrays"
} | 204101 |
<blockquote>
<p>Given a root of a Binary Search Tree (BST) and a number num, implement
an efficient function findLargestSmallerKey that finds the largest key
in the tree that is smaller than num. If such a number doesn’t exist,
return -1. Assume that all keys in the tree are nonnegative.</p>
</blockquote>
<p>The Bst Class is given to me.</p>
<pre><code>public class BstNode
{
public int key;
public BstNode left;
public BstNode right;
public BstNode parent;
public BstNode(int keyt)
{
key = keyt;
}
}
</code></pre>
<p>you can ignore the unit test code this is a just the demo.</p>
<pre><code> [TestMethod]
public void LargestSmallerKeyBstRecrussionTest()
{
BstNode root = new BstNode(20);
var left0 = new BstNode(9);
var left1 = new BstNode(5);
var right1 = new BstNode(12);
right1.left = new BstNode(11);
right1.right = new BstNode(14);
left0.right = right1;
left0.left = left1;
var right0 = new BstNode(25);
root.right = right0;
root.left = left0;
Assert.AreEqual(14, helper.FindLargestSmallerKeyRecursion(17, root));
}
</code></pre>
<p>this is the code I would like you please to review, comment. </p>
<pre><code> public static int FindLargestSmallerKey(uint num, BstNode root)
{
if (root == null)
{
return -1;
}
int temp = Math.Max( FindLargestSmallerKey(num, root.left), FindLargestSmallerKey(num, root.right));
if (root.key < num)
{
return Math.Max(root.key, temp);
}
return temp;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T09:36:47.670",
"Id": "393571",
"Score": "0",
"body": "@MartinR Hey I changed the code and fixed the issues I had, I seem to have a hard time with those type of questions. can you please explain how do you look at those type of quest... | [
{
"body": "<p>Your code works correctly now (as far as I can tell). But due to </p>\n\n<pre><code>int temp = Math.Max( FindLargestSmallerKey(num, root.left), FindLargestSmallerKey(num, root.right));\n</code></pre>\n\n<p>it always traverses the entire tree. This can be improved:</p>\n\n<ul>\n<li>If <code>root.k... | {
"AcceptedAnswerId": "204116",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T06:41:18.167",
"Id": "204105",
"Score": "4",
"Tags": [
"c#",
"interview-questions",
"binary-search"
],
"Title": "Find largest smaller key in Binary Search Tree"
} | 204105 |
<p>I have written this code for a <strong>color and font checker on a webpage</strong>.</p>
<p>The code is current and not so good. I would really like if I can get comments, reviews or any better approach for my PoC.</p>
<p><strong>PoC:</strong> I want to highlight all the colors or fonts which should not be used on the webpage (the domain is defined by me as of now). I am traversing the DOM and checking the color and font styles and then highlight them if there are values out of my domain.</p>
<p>The current approach is very naive and not optimal because I am traversing and storing element styles, which is bad for duplicated DOM elements.</p>
<p>Any comments are appreciated, please let me know if I should add any more details.</p>
<p><strong>inject.js</strong></p>
<pre><code>var brandColor = [
"rgb(255, 255, 255)",
"rgb(0, 0, 0)",
"rgb(0, 163, 224)",
"rgb(0, 118, 168)",
"rgb(1, 33, 105)"
];
var brandFont = ["Open Sans", "Verdana"];
var fontNotMatch;
// generic walkDOM function - iterate DOM
function walkDom(start_element) {
var arr = []; // we can gather elements here
var loop = function(element) {
do {
// we can do something with element
if (element.nodeType == 1) {
// do not include text nodes
arr.push(element);
}
if (element.hasChildNodes()) loop(element.firstChild);
} while ((element = element.nextSibling));
};
loop(start_element);
//loop(start_elem.firstChild); // do not include siblings of start element
return arr;
}
var arr = walkDom(document.body);
var stylesContainer = {};
var fontChecker = {};
// iterate through DOM array
for (elem in arr) {
// get all colors - [need better approach for this as well]
stylesContainer[arr[elem].tagName] = getComputedStyle(
arr[elem]
).getPropertyValue("color");
// get all fonts
fontChecker[arr[elem].tagName] = getComputedStyle(arr[elem]).getPropertyValue(
"font-family"
);
}
//console.log(stylesContainer);
// iterate styles
Object.keys(stylesContainer).forEach(element => {
if (brandColor.indexOf(stylesContainer[element]) > -1) {
//pass
} else if (document.querySelector(element).childNodes.length == 1) {
document.getElementsByTagName(element)[0].style.border = "2px solid red";
var path =
"https://example.com/icons/favicon.ico";
var img = document.createElement("img");
img.setAttribute("src", path);
img.setAttribute("width", "20");
document.querySelector(element).appendChild(img);
}
// console.log(stylesContainer[element]);
});
// iterate font family
Object.keys(fontChecker).forEach(element => {
// Loop through each element and check the font family
// console.log(fontChecker[element]);
if (fontChecker[element].indexOf("Open Sans") != 1) {
fontNotMatch = true;
}
});
if (fontNotMatch == true) {
// alert("Incorrect font");
var f = document.createElement("h3");
f.classList.add("error");
f.innerHTML = "hey bhansa";
document.querySelector("BODY").appendChild(f);
var pathCSS = chrome.runtime.getURL("demo.css");
var head = document.getElementsByTagName("head")[0];
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = pathCSS;
head.appendChild(link);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T09:13:52.847",
"Id": "393565",
"Score": "0",
"body": "Nah, it works but it's not in the very optimized form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-03T18:13:20.847",
"Id": "395134",
"Sco... | [
{
"body": "<p>Just some random comments from a quick read through:</p>\n\n<p>1) Does this work if someone defines their colors using hex or name style (<code>#fff</code>, <code>#ffffff</code>, <code>white</code>, <code>rgba(255,255,255,1)</code>?</p>\n\n<p>2) Walking the DOM and creating a huge array is probabl... | {
"AcceptedAnswerId": "204134",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T07:22:16.020",
"Id": "204106",
"Score": "1",
"Tags": [
"javascript",
"performance",
"algorithm",
"ecmascript-6",
"userscript"
],
"Title": "Font and color checker chrome extension in JavaScript"
} | 204106 |
<p>In my project, I am getting an array of objects from api, and I want to divide the array into 3 three arrays based on the value of the <code>shelf</code> property of each
array element which is an object. Now for doing that I am using <code>formatBooks</code> function inside the same component.</p>
<p>Later on I am passing this <code>formatBooks</code> function as prop to other component which calls this function.</p>
<p>I was hoping if there is any better by making another component and place the formatBooks inside that. I wanted to know a better and elegant way of doing things like this.</p>
<pre><code>class BooksApp extends React.Component {
state = {
books: [],
searchResults: [],
newBooksFromSearch: [],
}
//format the books array
formatBooks = () => {
const currentlyReading = []
const read = []
const wantToRead = []
this.state.books.forEach( item => {
if(item.shelf === "currentlyReading" || item.shelf === "Currently Reading"){
item.setShelf = "Currently Reading"
currentlyReading.push(item)
}
if(item.shelf === "read" || item.shelf === "Read" ){
item.setShelf = "Read"
read.push(item)
}
if(item.shelf === "wantToRead" || item.shelf === "Want to Read"){
item.setShelf = "Want to Read"
wantToRead.push(item)
}
})
return(
{
currentlyReading: currentlyReading,
read: read,
wantToRead: wantToRead
}
)
}
</code></pre>
| [] | [
{
"body": "<p>You may start to make your code slightly less verbose (and with all the required semicolons):</p>\n\n<pre><code>const result = {\n currentlyReading: [],\n read: [],\n wantToRead: []\n};\n\nthis.state.books.forEach(item => {\n if (...) {\n item.setShelf = \"Currently Reading\"... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T08:08:19.433",
"Id": "204110",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "ReactJS component to classify a list of books"
} | 204110 |
<p>I want to consume api from site. Lets say its url is <code>http://www.example.com</code>, and you can get the user data by sending <code>POST</code> to <code>http://www.example.com/api/users/1</code> (1 is the user's id).</p>
<pre><code>namespace SiteSharp.Endpoints.UserEndpoint
{
public class User
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("fname")]
public string Name { get; set; }
[JsonProperty("lname")]
public string SurrName { get; set; }
}
public class UserEndpoint
{
private const string UsersUrl = "api/users";
private readonly RestClient _requester;
public UserEndpoint(RestClient requester)
{
_requester = requester;
}
public async Task<User> GetUserAsync(int userId)
{
if (userId <= 0) throw new ArgumentException("User id is invalid");
var request = new RestRequest(UsersUrl, Method.POST);
request.AddParameter("Id", userId);
var response = await _requester.ExecutePostTaskAsync(request);
return JsonConvert.DeserializeObject<User>(response.Content);
}
}
public class BookEndpoint { } // TODO
// OTHER ENDPOINTS HERE..
}
namespace SiteSharp
{
public class SiteApi
{
private static SiteApi _instance;
public UserEndpoint User { get; }
public static SiteApi GetInstance()
{
if (_instance == null)
{
_instance = new SiteApi();
}
return _instance;
}
private SiteApi()
{
var restClient = new RestClient("http://www.example.com");
User = new UserEndpoint(restClient);
}
}
}
</code></pre>
<p>My main questions:</p>
<ol>
<li><code>RestClient</code> by default doesn't throw exception when request sending failed (for example when internet connection is terrible). In this case I am getting empty <code>response.Content</code>. Should I throw exception when detecting error codes to avoid <code>JsonSerializationException</code>? This is how it would look:</li>
</ol>
<p>This could be example handler:</p>
<pre><code>protected void HandleRequestFailure(HttpStatusCode statusCode)
{
switch (statusCode)
{
case HttpStatusCode.ServiceUnavailable:
throw new RequestExecutionFailedException("503, Service unavailable", statusCode);
case HttpStatusCode.InternalServerError:
throw new RequestExecutionFailedException("500, Internal server error", statusCode);
case HttpStatusCode.Unauthorized:
throw new RequestExecutionFailedException("401, Unauthorized", statusCode);
case HttpStatusCode.BadRequest:
throw new RequestExecutionFailedException("400, Bad request", statusCode);
case HttpStatusCode.NotFound:
throw new RequestExecutionFailedException("404, Resource not found", statusCode);
case HttpStatusCode.Forbidden:
throw new RequestExecutionFailedException("403, Forbidden", statusCode);
case (HttpStatusCode)429:
throw new RequestExecutionFailedException("429, Rate Limit Exceeded", statusCode);
default:
throw new RequestExecutionFailedException("Unexpeced failure", statusCode);
}
}
</code></pre>
<ol start="2">
<li>Is it ok to store json contracts in <code>SiteSharp.Endpoints.UserEndpoint</code>? Maybe I should store them in <code>SiteSharp.JsonModels</code> in one file and prevent adding <code>using</code> when one json contract contains another.</li>
</ol>
<p>For example when posting to <code>http://www.example.com/api/users</code> I would get:</p>
<pre><code>{
"users":[
{
"lname":"b",
"fname":"d",
"books":[
{
"id":5,
"title":"foo"
},
{
"id":87,
"title":"bar"
}
]
},
{
// another user here
}
]
}
</code></pre>
<p>In this case having all models in one file I can easly reuse classes without having a lot of <code>using</code>. Is it ok?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T09:14:42.970",
"Id": "393566",
"Score": "0",
"body": "The current question title applies to too many questions on this site to be useful. **The site standard is for the title to simply state the task accomplished by the code.** Plea... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T09:12:41.750",
"Id": "204113",
"Score": "1",
"Tags": [
"c#",
"rest"
],
"Title": "Consuming rest api"
} | 204113 |
<p>A couple of years ago I wrote a serialisation library for my project. By the time it worked well, but recently I thought it could be modernised. Back then I needed something that looks similar to Boost's serialiser, but also support polymorphism. I need to serialise and deserialise different types of objects from the same inheriting tree. However I didn't wanted to include Boost library just for this. Also I needed to support different sources besides <code>FILE*</code> (I only included just one here.)</p>
<p>I came across with <a href="http://www.codeproject.com/Tips/495191/Serialization-implementation-in-Cplusplus" rel="nofollow noreferrer">this solution</a>, tweaked a bit, wrote a couple of tests around it, and been using. It's spread across multiple files <a href="https://github.com/industrial-revolutioners/Grafkit2/tree/master/src/framework/utils/persistence" rel="nofollow noreferrer">in my repo</a>, and I do have a <a href="https://github.com/industrial-revolutioners/Grafkit2/blob/master/tests/test_utils/test_persistence.cpp" rel="nofollow noreferrer">couple more tests</a> for it using GTest.</p>
<p>My overall questions are </p>
<ul>
<li>How can I use std some more to make it more compatible with its containers? I think about supporting <code>std::map</code> first</li>
<li>What other possible way are there to improve the way I define and store factories of the different objects?</li>
<li>The most important thing is for me is support more efficiently the serialisation of the parents of the class instances. At this point I only have a terrible solution that is I define a non-virtual <code>_Serialize()</code> method that takes care of it via override. Is there a solution to collect all the parents serialiser method more seamlessly and invoke them?</li>
</ul>
<p>Here's the source code, that I had concatenated together and modified a bit to work single handed. I used clang on MacOS via Cmake to test it.</p>
<pre><code>/*
Dynamics API
*/
#ifndef __DYNAMICS_H__
#define __DYNAMICS_H__
#include <string>
#include <map>
namespace Grafkit
{
class Clonables;
/**
*/
class Clonable
{
friend class Clonables;
public:
virtual ~Clonable() = default;
virtual Clonable *CreateObj() const = 0;
};
/**
*/
class Clonables
{
std::map<std::string, const Clonable *> m_clonables;
Clonables() {}
Clonables(const Clonables &) = delete;
Clonables &operator=(const Clonables &) = delete;
virtual ~Clonables()
{
for (auto it = m_clonables.begin(); it != m_clonables.end(); ++it)
{
const Clonable *clone = it->second;
delete clone;
}
m_clonables.clear();
}
public:
static Clonables &Instance()
{
static Clonables instance;
return instance;
}
void AddClonable(const char *CLASS_NAME, Clonable *clone)
{
std::string name = CLASS_NAME;
auto it = m_clonables.find(name);
if (it == m_clonables.end())
{
m_clonables[name] = clone;
}
}
const Clonable *Find(const char *CLASS_NAME)
{
std::string name = CLASS_NAME;
auto it = m_clonables.find(name);
if (it == m_clonables.end())
return nullptr;
const Clonable *clone = it->second;
return clone;
}
Clonable *Create(const char *CLASS_NAME)
{
const Clonable *clone = Find(CLASS_NAME);
if (clone)
return clone->CreateObj();
return nullptr;
}
};
class AddClonable
{
public:
AddClonable(const char *CLASS_NAME, Clonable *clone)
{
Clonables::Instance().AddClonable(CLASS_NAME, clone);
}
};
} // namespace Grafkit
#define CLONEABLE_DECL(CLASS_NAME) \
public: \
virtual Grafkit::Clonable *CreateObj() const override \
{ \
return new CLASS_NAME(); \
}
#define CLONEABLE_FACTORY_DECL(CLASS_NAME) \
CLONEABLE_DECL(CLASS_NAME) \
public: \
class Factory : public Grafkit::Clonable \
{ \
public: \
virtual Grafkit::Clonable *CreateObj() const \
{ \
return new CLASS_NAME(); \
} \
}; \
\
private: \
static Grafkit::AddClonable _addClonableFactory;
#define CLONEABLE_FACTORY_IMPL(CLASS_NAME) \
Grafkit::AddClonable CLASS_NAME::_addClonableFactory(#CLASS_NAME, new CLASS_NAME::Factory());
#define CLONEABLE_FACTORY_LOCAL_IMPL(CLASS_NAME) \
Grafkit::AddClonable CLASS_NAME##_addClonableFactory(#CLASS_NAME, new CLASS_NAME::Factory());
#endif //__DYNAMICS_H__
/*
Persistence API
*/
#ifndef __PERSISTENCE_H__
#define __PERSISTENCE_H__
#include <cstdlib>
#include <vector>
// Alrady included above
//#include "dynamics.h"
namespace Grafkit
{
class Archive;
class Persistent : public Clonable
{
public:
Persistent() {}
virtual ~Persistent() {}
static Persistent *Load(Archive &ar);
template <class C>
static C *LoadT(Archive &ar) { return dynamic_cast<C *>(Load(ar)); }
void Store(Archive &ar);
protected:
virtual void Serialize(Archive &ar) = 0;
virtual std::string GetClazzName() const = 0;
virtual int GetVersion() const { return 0; }
};
class Archive
{
public:
explicit Archive(int IsStoring = 0);
virtual ~Archive();
/* IO API */
protected:
virtual void Write(const void *buffer, size_t length) = 0;
virtual void Read(void *buffer, size_t length) = 0;
size_t WriteString(const char *input);
size_t ReadString(char *&output);
public:
template <typename T>
void PersistField(T &t)
{
if (m_isStoring)
{
Write(&t, sizeof(T));
}
else
{
Read(&t, sizeof(T));
}
}
template <typename T>
void PersistVector(T *&v, uint32_t &count)
{
if (m_isStoring)
{
Write(&count, sizeof(count));
Write(v, sizeof(T) * count);
}
else
{
uint32_t readCount = 0;
Read(&readCount, sizeof(readCount));
void *p = malloc(sizeof(T) * readCount);
Read(p, sizeof(T) * readCount);
v = reinterpret_cast<T *>(p);
count = readCount;
}
}
template <typename T>
void PersistStdVector(std::vector<T> &v)
{
if (m_isStoring)
{
uint32_t u32count = v.size(); //clamp it down to 32 bit
Write(&u32count, sizeof(u32count));
void *p = v.data();
Write(p, sizeof(T) * u32count);
}
else
{
uint32_t count = 0;
Read(&count, sizeof(count));
void *p = malloc(sizeof(T) * count);
Read(p, sizeof(T) * count);
v.clear();
v.assign(static_cast<T *>(p), static_cast<T *>(p) + count);
}
}
void PersistString(const char *&str);
void PersistString(std::string &str);
void StoreObject(Persistent *object);
Persistent *LoadObject();
int IsStoring() const { return m_isStoring; }
void SetDirection(bool IsStoring) { m_isStoring = IsStoring; }
private:
int m_isStoring;
};
} // namespace Grafkit
// ------------------
#define PERSISTENT_DECL(CLASS_NAME, VERSION_NO) \
public: \
CLONEABLE_FACTORY_DECL(CLASS_NAME) \
public: \
std::string GetClazzName() const override \
{ \
return #CLASS_NAME; \
} \
int GetVersion() const override \
{ \
return VERSION_NO; \
}
#define PERSISTENT_IMPL(CLASS_NAME) \
CLONEABLE_FACTORY_IMPL(CLASS_NAME)
// ---
#define PERSIST_FIELD(AR, FIELD) (AR.PersistField<decltype(FIELD)>((FIELD)))
#define PERSIST_VECTOR(AR, VECTOR, COUNT) (AR.PersistVector<std::remove_pointer<decltype(VECTOR)>::type>(VECTOR, COUNT))
#define PERSIST_STD_VECTOR(AR, VECTOR) (AR.PersistStdVector<decltype(VECTOR)::value_type>(VECTOR))
#define PERSIST_STRING(AR, FIELD) (AR.PersistString((FIELD)))
#define _PERSIST_OBJECT(AR, TYPE, IN_FIELD, OUT_FIELD) \
{ \
if (AR.IsStoring()) \
{ \
AR.StoreObject(dynamic_cast<Persistent *>((IN_FIELD))); \
} \
else \
{ \
(OUT_FIELD) = dynamic_cast<TYPE>(AR.LoadObject()); \
} \
}
#define PERSIST_OBJECT(AR, OBJECT) _PERSIST_OBJECT(AR, decltype(OBJECT), OBJECT, OBJECT)
#define PERSIST_REFOBJECT(AR, REF) _PERSIST_OBJECT(AR, decltype(REF.Get()), REF.Get(), REF)
#endif //__PERSISTENCE_H__
/*
Archive IO layer
*/
#ifndef __ARCHIVE_H__
#define __ARCHIVE_H__
// #include "persistence.h"
namespace Grafkit
{
class ArchiveFile : public Archive
{
public:
ArchiveFile(FILE *stream, bool IsStoring = false);
virtual ~ArchiveFile();
void Write(const void *buffer, size_t length) override;
void Read(void *buffer, size_t length) override;
private:
FILE *_stream;
};
}; // namespace Grafkit
#endif //__ARCHIVE_H__
/***************************************************
Impl
****************************************************/
/*
Persistent layer impl: persistent.cpp
*/
#include <vector>
#include <cassert>
// Already pasted above
//#include "persistence.h"
//#include "dynamics.h"
using namespace Grafkit;
using namespace std;
void Persistent::Store(Archive &ar)
{
string CLASS_NAME = this->GetClazzName();
uint8_t ver = this->GetVersion();
PERSIST_STRING(ar, CLASS_NAME);
PERSIST_FIELD(ar, ver);
this->Serialize(ar);
}
Persistent *Persistent::Load(Archive &ar)
{
string CLASS_NAME;
uint8_t ver = 0;
PERSIST_STRING(ar, CLASS_NAME);
Clonable *clone = Clonables::Instance().Create(CLASS_NAME.c_str());
assert(clone);
Persistent *obj = dynamic_cast<Persistent *>(clone);
assert(obj);
PERSIST_FIELD(ar, ver);
assert(ver == obj->GetVersion());
obj->Serialize(ar);
return obj;
}
/**
Archive
*/
Archive::Archive(int IsStoring) : m_isStoring(IsStoring)
{
}
Archive::~Archive()
{
}
size_t Archive::WriteString(const char *input)
{
uint16_t slen = strlen(input);
this->Write(&slen, sizeof(slen));
this->Write(input, slen + 1);
return slen;
}
size_t Archive::ReadString(char *&output)
{
uint16_t slen = 0;
this->Read(&slen, sizeof(slen));
output = new char[slen + 1];
this->Read(output, slen + 1);
return slen;
}
void Archive::PersistString(const char *&str)
{
if (m_isStoring)
{
WriteString(str);
}
else
{
char *in = nullptr;
ReadString(in);
str = in;
}
}
void Archive::PersistString(string &str)
{
if (m_isStoring)
{
WriteString(str.c_str());
}
else
{
char *in = nullptr;
ReadString(in);
str = in;
delete[] in;
}
}
void Archive::StoreObject(Persistent *object)
{
uint8_t isNotNull = object != nullptr;
PersistField(isNotNull);
if (isNotNull)
object->Store(*this);
}
Persistent *Archive::LoadObject()
{
uint8_t isNotNull = 0;
PersistField(isNotNull);
if (isNotNull)
return Persistent::Load(*this);
return nullptr;
}
/*
Archive IO impl: archive.cpp
*/
// Already included above
// #include "archive.h"
#include <cassert>
using namespace Grafkit;
ArchiveFile::ArchiveFile(FILE *stream, bool IsStoring) : Archive(IsStoring),
_stream(stream)
{
assert(_stream);
}
ArchiveFile::~ArchiveFile()
{
}
void ArchiveFile::Write(const void *buffer, size_t length)
{
assert(_stream);
fwrite(buffer, length, 1, this->_stream);
}
void ArchiveFile::Read(void *buffer, size_t length)
{
assert(_stream);
fread(buffer, length, 1, this->_stream);
}
/**
Test classes, Main
*/
class SimpleClass : public Grafkit::Persistent
{
public:
SimpleClass() : Persistent(), m_i(0)
{
}
void SetParams(const int i, const std::string str)
{
m_i = i;
m_str = str;
}
int GetI() const { return m_i; }
std::string GetStr() const { return m_str; }
PERSISTENT_DECL(SimpleClass, 1);
protected:
void Serialize(Archive &ar) override
{
PERSIST_FIELD(ar, m_i);
PERSIST_STRING(ar, m_str);
}
private:
int m_i;
std::string m_str;
};
class SimpleBaseClass : public Grafkit::Persistent
{
public:
SimpleBaseClass() : Persistent(), m_i(0) {}
void SetParams(const int i, const std::string str)
{
m_i = i;
m_str = str;
}
int GetI() const { return m_i; }
std::string GetStr() const { return m_str; }
virtual std::string GetSomeIntern() const = 0;
protected:
void _Serialize(Archive &ar)
{
PERSIST_FIELD(ar, m_i);
PERSIST_STRING(ar, m_str);
}
private:
int m_i;
std::string m_str;
};
class DerivedClassA : public SimpleBaseClass
{
public:
DerivedClassA() : SimpleBaseClass(), m_str1("This is derived class A") {}
virtual std::string GetSomeIntern() const override { return m_str1; }
PERSISTENT_DECL(DerivedClassA, 1);
protected:
void Serialize(Archive &ar) override
{
SimpleBaseClass::_Serialize(ar);
PERSIST_STRING(ar, m_str1);
}
private:
std::string m_str1;
};
class DerivedClassB : public SimpleBaseClass
{
public:
DerivedClassB() : SimpleBaseClass(), m_str2("This is derived class B") {}
virtual std::string GetSomeIntern() const override { return m_str2; }
PERSISTENT_DECL(DerivedClassB, 1);
protected:
void Serialize(Archive &ar) override
{
SimpleBaseClass::_Serialize(ar);
PERSIST_STRING(ar, m_str2);
}
private:
std::string m_str2;
};
#include <cstdio>
PERSISTENT_IMPL(SimpleClass);
PERSISTENT_IMPL(DerivedClassA);
PERSISTENT_IMPL(DerivedClassB);
int main()
{
FILE *fp;
// -- 1. simple class
// given
SimpleClass *simpleObj = new SimpleClass();
simpleObj->SetParams(42, "Hello Serializer");
SimpleBaseClass *inheritedA = new DerivedClassA();
SimpleBaseClass *inheritedB = new DerivedClassB();
inheritedA->SetParams(314, "Hello Serializer w/ inherited classes");
inheritedA->SetParams(216, "Hello Serializer GLEJD");
// when
fp = fopen("archive.bin", "wb'");
assert(fp);
ArchiveFile arWrite(fp, true);
simpleObj->Store(arWrite);
inheritedA->Store(arWrite);
inheritedB->Store(arWrite);
fflush(fp);
fclose(fp);
fp = nullptr;
// then
fp = fopen("archive.bin", "rb");
assert(fp);
ArchiveFile arRead(fp, false);
SimpleClass *loadedObj = Persistent::LoadT<SimpleClass>(arRead);
SimpleBaseClass *loadedA = Persistent::LoadT<SimpleBaseClass>(arRead);
SimpleBaseClass *loadedB = Persistent::LoadT<SimpleBaseClass>(arRead);
assert(loadedObj);
assert(simpleObj->GetI() == loadedObj->GetI());
assert(simpleObj->GetStr().compare(loadedObj->GetStr()) == 0);
assert(loadedA);
assert(dynamic_cast<DerivedClassA *>(loadedA));
assert(inheritedA->GetI() == loadedA->GetI());
assert(inheritedA->GetStr().compare(loadedA->GetStr()) == 0);
assert(inheritedA->GetSomeIntern().compare(loadedA->GetSomeIntern()) == 0);
assert(loadedB);
assert(dynamic_cast<DerivedClassB *>(loadedB));
assert(inheritedB->GetI() == loadedB->GetI());
assert(inheritedB->GetStr().compare(loadedB->GetStr()) == 0);
assert(inheritedB->GetSomeIntern().compare(loadedB->GetSomeIntern()) == 0);
fclose(fp);
delete simpleObj;
delete inheritedA;
delete inheritedB;
delete loadedObj;
delete loadedA;
delete loadedB;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T10:59:01.930",
"Id": "393837",
"Score": "1",
"body": "What is the purpose of `Cloneables`? It is singleton map wrapper, but creates objects through `Clonable::CreateObj` which does not appear to do cloning. It would make sense in `F... | [
{
"body": "<p>I started reading. </p>\n\n<p>IMO <code>Find</code> should be private and const. </p>\n\n<p>Once you have done this you can replace the map \nwith a map of std::string, unique_ptr. </p>\n\n<p>Doing so you get rid of the destructor of Clonables. </p>\n\n<p>Does this make sense?</p>\n",
"commen... | {
"AcceptedAnswerId": "226342",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T11:45:50.057",
"Id": "204123",
"Score": "5",
"Tags": [
"c++",
"object-oriented",
"c++14",
"serialization"
],
"Title": "Custom serialiser with object factory"
} | 204123 |
<p>I am a fan of <code>f"{strings}"</code> in Python,</p>
<p>However some situations could possibly be dangerous when doing f strings from user input, leaking API keys or even code execution!</p>
<p>So I decided to make something to mitigate these attacks. It works by searching with regex over the input string, and will return an empty string if it detects any evil piece of code.</p>
<p>It uses the <a href="https://github.com/damnever/fmt" rel="nofollow noreferrer">fmt package</a></p>
<pre><code>import fmt as f
import re
import os # This is for checking the system call
import doctest
# Setup
SECRET_GLOBAL = 'this is a secret'
class Error:
def __init__(self):
passs
def a_function():
return SECRET_GLOBAL
# Here is where the code begins
DANGEROUS_CODES = [
re.compile(r'(\.system\(.*\))'), # Any call to system
re.compile(r'(__[\w]+__)'), # Any internals
re.compile(r'([\w\d]+\(\))') # Functions
]
def safe_format(st):
'''
Safe python f-string formatting
this will detect evil code from fstring making formatting safe.
args:
st (str): The f-string
returns:
Empty string, if dangerous code is found
Executes the fstring normally if no dangerous code is found
Test globals acces
>>> safe_format('{Error().__init__.__globals__[SECRET_GLOBAL]}')
''
Test function acces
>>> safe_format('a_function()')
''
Test code execution via import
>>> safe_format('{__import__("os").system("dir")}')
''
Test code execution with imported os
>>> safe_format('{os.system("dir")}')
''
Test no stack trace
>>> safe_format('{0/0}')
''
Test acceptable fstring
>>> safe_format('{6 * 6}')
'36'
'''
if any(re.search(danger, st) for danger in DANGEROUS_CODES):
return ''
try:
return f(st)
except Exception as e:
return ''
if __name__ == '__main__':
doctest.testmod()
</code></pre>
<ul>
<li>Did i miss anything?</li>
<li>Is this approach acceptable?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T14:46:55.410",
"Id": "393603",
"Score": "0",
"body": "Wouldn't the safer solution be to *not* interpolate strings from user input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T14:49:40.440",
"I... | [
{
"body": "<p>If you forbid function calls you cannot use getters which then is a big restriction. If you allow them it is hard to get it safe. Also your regexes will have collateral damages and filter legal expressions. So I think your approach is not so good. Don't allow users to mess with format strings. Use... | {
"AcceptedAnswerId": "204147",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T12:19:49.210",
"Id": "204126",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"strings",
"security"
],
"Title": "Safe string formatting in Python"
} | 204126 |
<p>I've been messing around with arrays as I'm learning them currently in my book and they gave the idea of a chess board using for loops alongside multidimensional arrays to give them individual values which you can therefore print out.</p>
<p>However, I thought of the old console RPG games from way back and wanted to simply add a border around the array so it prints any 0 || 19 value as an X. The code does work however, is there a way of making it more efficient by using if statements or by created a switch statement that reads the current loop variable and change that array value to a 1 for fill or leave it 0 to blank the "tile".</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
int rpgLevelGrid[20][20];
//Co-od decleration
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
switch (i)
{
case 0: case 19:
rpgLevelGrid[i][j] = 1;
break;
default:
rpgLevelGrid[i][j] = 0;
break;
}
switch (j)
{
case 0:
rpgLevelGrid[i][j] = 1;
break;
case 19:
rpgLevelGrid[i][j] = 1;
break;
}
}
}
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
switch (rpgLevelGrid[i][j])
{
case 1:
cout << "X";
break;
default:
cout << "-";
}
}
cout << endl;
}
}
</code></pre>
| [] | [
{
"body": "<h1><code>switch</code> vs. <code>if</code></h1>\n\n<p>In</p>\n\n<pre><code> switch (rpgLevelGrid[i][j])\n {\n case 1:\n cout << \"X\";\n break;\n default:\n cout << \"-\";\n }\n</code></pre>\n\n<p>do not use switch when ... | {
"AcceptedAnswerId": "204151",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T13:14:02.143",
"Id": "204130",
"Score": "3",
"Tags": [
"c++",
"beginner",
"array",
"ascii-art"
],
"Title": "Initializing a tile-like map such that the edges are marked with an 'X'"
} | 204130 |
<p>We had a question in examination to compute <strong><a href="https://en.wikipedia.org/wiki/Determinant" rel="noreferrer">determinant</a></strong> of general square matrix.
Now I had made the normal program using Laplace Formula of determinant, ie, recursive solution.</p>
<p>Now I was thinking of reducing it into <strong>Upper Triangle Matrix</strong> and then the product of diagonal elements gives the determinant. </p>
<p>The code is following.</p>
<pre><code>#include <iostream>
using namespace std;
const int N = 5;
int main()
{
double array[N][N], det = 1;
// initialise
cout << "Enter " << N << "*" << N << " matrix:\n";
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cin >> array[i][j];
}
}
for (int i = 0; i < N; ++i)
{
bool flag = false; // flag := are all entries below a[i][i] including it zero?
if (array[i][i] == 0) // If a[i][i] is zero then check rows below and swap
{
flag = true;
for (int j = i; j < N; ++j)
{
if (array[j][i] != 0) {
det *= -1;
for (int k = 0; k < N; ++k) {
double t = array[i][k]; // swapping
array[i][k] = array[j][k];
array[j][k] = t;
flag = false;
}
}
}
}
if (flag == true) {
det = 0;
break;
}
else {
for (int j = i+1; j < N; ++j)
{
double store = array[j][i];
for (int k = i; k < N; ++k) {
array[j][k] -= (array[i][k]*store)/array[i][i];
}
}
det *= array[i][i];
}
}
cout << "Determinant: " << det;
return 0;
}
</code></pre>
<p>The problems with this approach is that matrix needs to be of floating point datatypes. Worse, it gives wrong result for least significant place (ones digit) for all integral entries if I use datatype of entries as <strong>float</strong>. To overcome that, we can use double.</p>
<p>But still I :</p>
<ul>
<li>need tips on <strong>improving</strong> performance of this method</li>
<li>need to know whether this method is <strong>better</strong> than Simple Laplace Formula?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T09:31:52.790",
"Id": "393819",
"Score": "1",
"body": "Leibnitz / Laplace formula has `O(n!)` complexity, whereas decomposition methods such as the one you chose have `O(n^3)` complexity and are as such much more efficient for larger... | [
{
"body": "<p>Some general remarks:</p>\n\n<ul>\n<li><p>Don't use <code>namespace std;</code>, see for example <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a>.</p></li>\n<li><p>Don't put all the... | {
"AcceptedAnswerId": "204612",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T15:22:12.733",
"Id": "204135",
"Score": "5",
"Tags": [
"c++",
"performance",
"algorithm",
"matrix",
"mathematics"
],
"Title": "Determinant using Gauss Elimination"
} | 204135 |
<p>I needed a reference counted smart pointer for my project, and for some reason early in my project, I decided that I did not like the <code>std::shared_ptr</code>. I can't remember the exact reasons why, but I do remember there was a reason for it. It fell short in some area, but for the life of me I can't remember what it was. Reasons for not using <code>std::shared_ptr</code> aside, I was hoping to get my own implementation reviewed and see if there were any obvious mistakes and errors that you guys could pick out. I used a couple of references to implement this (cited in the file header block) so I'm hoping it's at least somewhat solid, however I know there are some areas that can be improved and some areas where I had to get a little tricky ("clever code... isn't" and all that) and was hoping you guys could show me where that would be.</p>
<p>There is also a <code>weak_ptr</code> implementation as well as a <code>std::hash</code> specialization for the <code>RefPtr</code> and a specialization for the <code>rttr</code> library, which I make use of in my project.</p>
<pre><code>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// RefPtr
//
// Reference counted smart pointer.
// Adapted from http://www.acodersjourney.com/implementing-smart-pointer-using-reference-counting/\
// With some tidbits from https://codereview.stackexchange.com/questions/99087/alternate-weak-pointer-implementation
//
// Season to taste.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Project Firestorm 2018
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef LIBCORE_REFPTR_H_
#define LIBCORE_REFPTR_H_
#pragma once
#include <libCore/libCore.h>
#include <rttr/wrapper_mapper.h>
OPEN_NAMESPACE(Firestorm);
class RefCount
{
template <class T> friend class RefPtr;
template <class T> friend class WeakPtr;
public:
template <class T>
RefCount(T* object)
:_object(static_cast<void*>(object))
{
}
template<class T>
T* _get_ptr() const { return static_cast<T*>(_object); }
private:
uint32_t _strongCount{ 0 };
uint32_t _weakCount{ 0 };
void* _object;
};
// Dummy type that allows the program to compile when the static_assert hits in RefPtr.
struct _RefPtr_DummyType { virtual ~_RefPtr_DummyType() {} };
template<class T>
class RefPtr
{
template <class T> friend class WeakPtr;
/*static_assert(std::has_virtual_destructor<
std::conditional<std::is_polymorphic<T>::value, T, _RefPtr_DummyType>::type
>::value, "Objects used in a RefPtr must have a virtual destructor");*/
public:
using DeleteExpr = std::function<void(T*)>;
typedef T element_type;
typedef T* pointer_type;
RefPtr()
: _object(nullptr)
, _count(nullptr)
, _deleter(nullptr)
{
}
RefPtr(std::nullptr_t)
: _object(nullptr)
, _count(nullptr)
, _deleter(nullptr)
{
}
RefPtr(T* object)
: _object(object)
, _count(new RefCount(object))
, _deleter(nullptr)
{
assert(_count && _count->_object == _object);
++_count->_strongCount;
}
template<class Deleter>
RefPtr(T* object, Deleter deleter)
: _object(object)
, _count(new RefCount(object))
, _deleter(deleter)
{
assert(_count && _count->_object == _object);
++_count->_strongCount;
}
RefPtr(const RefPtr<T>& other)
: _object(other._object)
, _count(other._count)
, _deleter(other._deleter)
{
assert(_count && _count->_object == _object);
++_count->_strongCount;
}
// polymorphic support
template <class Subclass_t>
RefPtr(const RefPtr<Subclass_t>& other)
: _object(other._Get_Ptr())
, _count(other._Get_Count())
{
static_assert(std::is_base_of<T, Subclass_t>::value,
"the RefPtr passed to the casting constructor of RefPtr must hold a type that is a subclass of the held type");
++_count->_strongCount;
// This is IWhatever, other is class Whatever : public IWhatever. ya feel?
auto otherDel = other._Get_Deleter();
if(otherDel)
{
// what has science done?
_deleter = [del = otherDel](T* ptr) {
if(ptr)
// so in order to call the other deleter what the superclass defined, we need to wrap it in our own
// that supports our needs.
del(reinterpret_cast<Subclass_t*>(ptr));
};
}
}
// polymorphic support with provided deleter.
template <class Subclass_t, class Del>
RefPtr(const RefPtr<Subclass_t>& other, Del deleter)
: _object(other._Get_Ptr())
, _count(other._Get_Count())
, _deleter(deleter)
{
static_assert(std::is_base_of<T, Subclass_t>::value,
"the RefPtr passed to the casting constructor of RefPtr must hold a type "
"that is a subclass of the held type");
++_count->_strongCount;
}
// polymorphic support for raw pointer
template <class Subclass_t>
RefPtr(Subclass_t* ptr)
: _object(static_cast<T*>(ptr))
, _count(new RefCount(_object))
{
static_assert(std::is_base_of<T, Subclass_t>::value,
"the RefPtr passed to the casting constructor of RefPtr must hold a type "
"that is a subclass of the held type");
++_count->_strongCount;
}
// polymorphic support for raw pointer
template <class Subclass_t, class Del>
RefPtr(Subclass_t* ptr, Del deleter)
: _object(static_cast<T*>(ptr))
, _count(new RefCount(_object))
, _deleter(deleter)
{
static_assert(std::is_base_of<T, Subclass_t>::value,
"the RefPtr passed to the casting constructor of RefPtr must hold a type "
"that is a subclass of the held type");
++_count->_strongCount;
}
// polymorphic move
template<class Subclass_t>
RefPtr(RefPtr<Subclass_t>&& other)
: _object(other._object)
, _count(other._count)
{
static_assert(std::is_base_of<T, Subclass_t>::value,
"the RefPtr passed to the casting move constructor of RefPtr must hold a type "
"that is a subclass of the held type");
assert(_count && _count->_object == _object);
// This is IWhatever, other is class Whatever : public IWhatever. ya feel?
auto otherDel = other._Get_Deleter();
if(otherDel)
{
// what has science done?
_deleter = [del = otherDel](T* ptr) {
if(ptr)
// so in order to call the other deleter what the superclass defined, we need to wrap it in our own
// that supports our needs.
del(reinterpret_cast<Subclass_t*>(ptr));
};
}
// assumes ownership
other._count = nullptr;
other._object = nullptr;
other._deleter = nullptr;
}
RefPtr(RefPtr<T>&& other)
: _object(other._object)
, _count(other._count)
, _deleter(other._deleter)
{
assert(_count && "counter block was nullptr");
T* o = _count->_get_ptr<T>();
assert(o == _object && "counter block held a different object for some reason");
// assumes ownership
other._count = nullptr;
other._object = nullptr;
other._deleter = nullptr;
}
virtual ~RefPtr()
{
if(_count)
--_count->_strongCount;
DoCleanup();
}
RefPtr<T>& operator=(const RefPtr<T>& other)
{
if(this != &other)
{
// decrement the strong count of the existing counter.
if(_count)
--_count->_strongCount;
DoCleanup();
// any weak pointers that still hold the control block from this RefPtr will clean them up as
// expected.
// copy over the stuff.
_object = other._object;
_count = other._count;
_deleter = other._deleter;
// add a reference for the new counter.
assert(_count);
++_count->_strongCount;
}
return *this;
}
RefPtr<T>& operator=(RefPtr<T>&& other)
{
if(this != &other)
{
_object = other._object;
_count = other._count;
assert(_count && _count->_object == other._object);
other._count = nullptr;
other._object = nullptr;
other._deleter = nullptr;
}
return *this;
}
T* Get() const { return _object; }
T& operator*() { return *_object; }
T* operator->() { return _object; }
const T* operator->() const { return _object; }
bool operator==(const RefPtr<T>& other) const
{
return _object == other._object;
}
bool operator==(std::nullptr_t) const
{
return _object == nullptr;
}
bool operator!=(const RefPtr<T>& other) const
{
return _object != other._object;
}
bool operator!=(std::nullptr_t) const
{
return _object != nullptr;
}
operator bool() const
{
return _object != nullptr;
}
uint32_t GetCount() const
{
FIRE_ASSERT(_count);
return _count->_strongCount;
}
uint32_t GetWeakCount() const
{
FIRE_ASSERT(_count);
return _count->_weakCount;
}
template<class U=T>
U* _Get_Ptr() const { return static_cast<U*>(_object); }
RefCount* _Get_Count() const { return _count; }
DeleteExpr _Get_Deleter() const { return _deleter; }
private:
RefPtr(RefCount* refCount)
: _object(static_cast<T*>(refCount->_object))
, _count(refCount)
{
FIRE_ASSERT(_count);
++_count->_strongCount;
}
void DoCleanup()
{
// if there are no more strong references...
if (_count && _count->_strongCount == 0)
{
// then delete the object.
// _object->~T(); // call the destructor so that we can delete it properly.
// delete _object;
// _object = nullptr;
if(_deleter) _deleter(_object);
else delete _object;
// and null out the counter's pointer as well.
_count->_object = nullptr;
// if there are no more weak references, then we can delete the counter as well.
if(_count->_weakCount == 0)
{
delete _count;
_count = nullptr;
}
}
}
T* _object{ nullptr };
RefCount* _count{ nullptr };
DeleteExpr _deleter{ nullptr };
};
template <class T>
class WeakPtr
{
public:
typedef T* T_ptr;
WeakPtr() : _count(nullptr) {}
WeakPtr(const RefPtr<T>& ptr)
: _count(ptr._count)
{
FIRE_ASSERT(_count);
++_count->_weakCount;
}
WeakPtr(const WeakPtr<T>& ptr)
: _count(ptr._count)
{
FIRE_ASSERT(_count);
++_count->_weakCount;
}
template <class Subclass_t>
WeakPtr(const RefPtr<Subclass_t>& ptr)
: _count(ptr._count)
{
FIRE_ASSERT(_count);
static_assert(std::is_base_of<T, Subclass_t>::value,
"the pointer passed to the casting constructor must be a subclass of the type held by the WeakPtr");
++_count->_weakCount;
}
~WeakPtr()
{
if(_count)
{
// if there are no more weak references and there's no object (released by the RefPtr)
// then we can delete the control block.
if(--_count->_weakCount == 0 && !_count->_object)
{
delete _count;
_count = nullptr;
}
}
}
bool operator==(WeakPtr<T>& other)
{
return other._count == _count;
}
bool operator==(RefPtr<T>& other)
{
return other._count == _count;
}
bool operator==(std::nullptr_t) const
{
return _counter && _counter->_object == nullptr;
}
bool operator!=(std::nullptr_t) const
{
return _counter && _counter->_object != nullptr;
}
template <class Subclass_t>
WeakPtr<T>& operator=(const RefPtr<Subclass_t>& ptr)
{
static_assert(std::is_base_of<T, Subclass_t>::value,
"the RefPtr passed to the casting constructor must hold an instance of a subclass of the type held by the WeakPtr");
// decrement the weak ref count of the current control block if we have it
// and then clean it up if we need to.
if(_count)
{
if(--_count->_weakCount == 0 && !_count->_object)
{
delete _count;
_count = nullptr;
}
}
// increment the weak ref count of the new control block.
_count = ptr._count;
FIRE_ASSERT(_count);
++_count->_weakCount;
return *this;
}
WeakPtr<T>& operator=(const RefPtr<T>& obj)
{
// decrement the weak ref count of the current control block if we have it
// and then clean it up if we need to.
if(_count)
{
if(--_count->_weakCount == 0 && !_count->_object)
{
delete _count;
_count = nullptr;
}
}
// increment the weak ref count of the new control block.
_count = obj._count;
FIRE_ASSERT(_count);
++_count->_weakCount;
return *this;
}
RefPtr<T> Lock() const
{
return RefPtr<T>(_count);
}
operator bool() const
{
return _count->_object != nullptr;
}
private:
RefCount* _count;
};
CLOSE_NAMESPACE(Firestorm);
OPEN_NAMESPACE(rttr);
template<typename T>
struct wrapper_mapper<Firestorm::RefPtr<T>>
{
using wrapped_type = decltype(Firestorm::RefPtr<T>().Get());
using type = Firestorm::RefPtr<T>;
static RTTR_INLINE wrapped_type get(const type& obj)
{
return obj.Get();
}
static RTTR_INLINE type create(const wrapped_type& t)
{
return type(t);
}
template<typename U>
static Firestorm::RefPtr<U> convert(const type& source, bool& ok)
{
if(auto p = rttr_cast<typename Firestorm::RefPtr<U>::element_type*>(source.Get()))
{
ok = true;
return Firestorm::RefPtr<U>(p);
}
else
{
ok = false;
return Firestorm::RefPtr<U>(nullptr);
}
}
};
CLOSE_NAMESPACE(rttr);
OPEN_NAMESPACE(std);
template<class T>
struct hash<Firestorm::RefPtr<T>>
{
size_t operator()(const Firestorm::RefPtr<T>& ptr) const
{
return std::hash<Firestorm::RefPtr<T>::pointer_type>()(ptr.Get());
}
};
CLOSE_NAMESPACE(std);
#endif
</code></pre>
<p>I'm also including my unit tests, however it uses my own unit testing implementation so you'd have to translate it over to whatever unit test framework you fancy. So far it passes all of these unit tests, however I know there are some cases I'd probably want to test for that I haven't thought of yet.</p>
<pre><code>using std::cout;
using std::cin;
using std::endl;
using namespace Firestorm;
struct TestObject
{
TestObject(const Function<void()>& deletionCallback)
: _callback(deletionCallback)
{
}
virtual ~TestObject()
{
_callback();
}
Function<void()> _callback;
};
struct TestPolyObject : public TestObject
{
TestPolyObject(const std::function<void()>& deletionCallback)
: TestObject(deletionCallback)
{
}
};
RefPtr<TestHarness> libCorePrepareHarness(int argc, char** argv)
{
RefPtr<TestHarness> h(new TestHarness("libCore Tests"));
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RefPtr Testing
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
h->It("RefPtr should delete the object when it falls out of scope", [](TestCase& t) {
bool objectDeleted = false;
{
auto callback = [&objectDeleted]() { objectDeleted = true; };
RefPtr<TestObject> object(new TestObject(callback));
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
}
t.Assert(objectDeleted, "the object was not deleted");
});
h->It("RefPtr should use the deleter when one is provided", [](TestCase& t) {
bool objectDeleted = false;
bool deleterCalled = false;
{
auto callback = [&objectDeleted]() { objectDeleted = true; };
RefPtr<TestObject> object(new TestObject(callback), [&deleterCalled](TestObject* ptr) {
if(ptr)
delete ptr;
deleterCalled = true;
});
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
}
t.AssertIsTrue(objectDeleted, "the object was not deleted");
t.AssertIsTrue(deleterCalled, "the deleter was not called");
});
h->It("RefPtr should use the deleter when one is provided, even when polymorphism is in play", [](TestCase& t) {
bool objectDeleted = false;
bool deleterCalled = false;
{
auto callback = [&objectDeleted]() { objectDeleted = true; };
RefPtr<TestObject> object(new TestPolyObject(callback), [&deleterCalled](TestObject* ptr) {
if (ptr)
delete ptr;
deleterCalled = true;
});
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
}
t.AssertIsTrue(objectDeleted, "the object was not deleted");
t.AssertIsTrue(deleterCalled, "the deleter was not called");
});
h->It("RefPtr should use the deleter when one is provided, even when polymorphism is in play "
"and the base ptr was copy constructed", [](TestCase& t) {
{
bool objectDeleted = false;
bool deleterCalled = false;
{
auto callback = [&objectDeleted]() { objectDeleted = true; };
RefPtr<TestPolyObject> object(new TestPolyObject(callback), [&deleterCalled](TestPolyObject* ptr) {
if (ptr)
delete ptr;
deleterCalled = true;
});
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
{
// copy construct.
RefPtr<TestObject> testBaseObject(object);
t.Assert(object.GetCount() == 2, "the ref count was not the expected value");
t.Assert(testBaseObject.GetCount() == 2, "the ref count was not the expected value");
}
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
t.AssertIsFalse(deleterCalled, "the deleter was called prematurely");
RefPtr<TestObject> testBaseObject(object);
t.Assert(object.GetCount() == 2, "the ref count was not the expected value");
t.Assert(testBaseObject.GetCount() == 2, "the ref count was not the expected value");
}
t.AssertIsTrue(objectDeleted, "the object was not deleted");
t.AssertIsTrue(deleterCalled, "the deleter was not called");
}
{
bool objectDeleted = false;
bool deleterCalled = true;
{
auto callback = [&objectDeleted]() { objectDeleted = true; };
RefPtr<TestObject> ptrBase(new TestPolyObject(callback), [&deleterCalled](TestObject* ptr) {
if(ptr)
delete ptr;
deleterCalled = true;
});
}
t.AssertIsTrue(deleterCalled, "the deleter was not called on a polymorphic type");
}
});
h->It("weak pointers should not prolong the lifetime of objects managed by a shared ptr", [](TestCase& t) {
bool objectDeleted = false;
auto callback = [&objectDeleted]() { objectDeleted = true; };
WeakPtr<TestObject> weak;
{
RefPtr<TestObject> object(new TestObject(callback));
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
weak = object;
t.Assert(object.GetWeakCount() == 1, "the weak ref count was not the expected value");
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
}
t.Assert(!weak, "the weak pointer still holds on to a valid object");
t.Assert(objectDeleted, "the object was not deleted");
});
h->It("polymorphic types should be allowable by the RefPtr", [](TestCase& t) {
bool objectDeleted = false;
auto callback = [&objectDeleted]() { objectDeleted = true; };
{
RefPtr<TestObject> object(new TestPolyObject(callback));
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
}
t.Assert(objectDeleted, "the object was not deleted");
});
h->It("weak pointers should also be allowed to hold polymorphic types", [](TestCase& t) {
bool objectDeleted = false;
auto callback = [&objectDeleted]() { objectDeleted = true; };
WeakPtr<TestObject> weak;
{
RefPtr<TestPolyObject> object(new TestPolyObject(callback));
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
weak = object;
t.Assert(object.GetWeakCount() == 1, "the weak ref count was not the expected value");
t.Assert(object.GetCount() == 1, "the ref count was not the expected value");
}
t.Assert(!weak, "the weak pointer still holds on to a valid object");
t.Assert(objectDeleted, "the object was not deleted");
});
return h;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T21:13:38.413",
"Id": "393636",
"Score": "0",
"body": "Why have a copy of `_object` in both `RefCount` and `RefPtr`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T23:07:01.917",
"Id": "393638",
... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T15:50:21.303",
"Id": "204137",
"Score": "2",
"Tags": [
"c++",
"c++11",
"memory-management",
"pointers"
],
"Title": "Yet Another Non-Intrusive Reference Counted Smart Pointer Implementation"
} | 204137 |
<p>I'm writing a toy compiler, which is in a very early stage of development. The lexer contains the <a href="https://github.com/mykolav/fs-coollang/blob/8a9a9428ee09395c8bd27489524338fa043eca75/cool/Lexer/Lexer.fs#L172" rel="nofollow noreferrer">following block of code</a>:</p>
<pre><code> let consumeChar (state: LexerState) =
match state.CurrentChar() with
| End -> state
| _ -> { state with Offset = state.Offset + 1u }
let tryConsume (ch: char) (state: LexerState) =
if state.CurrentChar() = Regular ch
then Success <| consumeChar state
else Failure state
// ...
let onForwardSlash() =
let onUnterminatedMLComment = ...
state |> consumeChar
// Line comment
|> tryConsume '/'
|> andThenSuccess (consumeToEndOfLine >> lexToken)
// Multiline comment
|> orElse (tryConsume '*'
>> andThen (consumeTo "*/"
>> andThenSuccess lexToken
>> orElseSuccess onUnterminatedMLComment))
// Just a forward slash
|> orElseSuccess (LexingResult.T (Punctuator Slash) start)
</code></pre>
<p>Where <code>andThen</code>, <code>orElse</code> and friends are defined like this:</p>
<pre><code>type TryResult<'fail, 'res> =
| Failure of 'fail
| Success of 'res
let orElse next tryResult =
match tryResult with
| Success res -> Success res
| Failure cont -> next cont
let andThen next tryResult =
match tryResult with
| Success cont -> next cont
| Failure fail -> Failure fail
let orElseSuccess f tryResult =
match tryResult with
| Success res -> Success res
| Failure cont -> Success <| f cont
let andThenSuccess f tryResult = ...
</code></pre>
<p>I arrived at this code "naturally" while trying to reduce duplication in the previous version. And the current version is shorter and seems less noisy indeed. </p>
<p>A little later, I stumbled across <a href="https://eiriktsarpalis.wordpress.com/2017/04/02/programming-in-the-point-free-style/" rel="nofollow noreferrer">a blog post</a> which discourages point-free style of programming.<br>
And my code seems to be in a style quite similar to point-free. So it got me thinking. Briefly looking through the sources of FAKE, Paket, Suave, and FSharp compiler itself, they seem to keep function composition usage to a minimum.</p>
<p>Hence the question: Is the <code>onForwardSlash</code> function's code abusing function composition/point-free style?</p>
<p>(I know about FsLexxYacc and FParsec. This question is about code style, not implementing a lexer)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T17:04:24.040",
"Id": "393617",
"Score": "0",
"body": "@200_success Added a link to the github repo with the full code. And added a summary of what the code is supposed to do in the question's text. The code pieces currently present ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T16:27:16.717",
"Id": "204138",
"Score": "2",
"Tags": [
"functional-programming",
"f#",
"lexer"
],
"Title": "Lexer function to handle the '/' character"
} | 204138 |
<p>I am learning Java and would like to get feedback on the code I wrote.</p>
<p>I have written an implementation of an algorithm (found <a href="https://www.geeksforgeeks.org/converting-decimal-number-lying-between-1-to-3999-to-roman-numerals/" rel="nofollow noreferrer">here</a>) for converting any decimal Arabic number to Roman numeral string. My concerns are:</p>
<ul>
<li>The code seems too long for some methods.</li>
<li>It is not clear what is going on in the class (unless you already know what the algorithm is doing).</li>
<li>Correct use of OOP</li>
<li>Tight coupling of methods</li>
<li>Are there Java 8 features that I should be using but not using.</li>
</ul>
<p>I am looking for your input, advice and feedback so that I can get better at writing clean and maintainable code.</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
public class RomanNumeralsConverter {
private final Map<Integer, String> BASE_VALUES_MAP =
new HashMap<Integer, String>() {{
put (1, "I");
put (4, "IV");
put (5, "V");
put (9, "IX");
put (10, "X");
put (40, "XL");
put (50, "L");
put (90, "XC");
put (100, "C");
put (400, "CD");
put (500, "D");
put (900, "CM");
put (1000, "M");
}};
private StringBuilder romanNumeralString;
public RomanNumeralsConverter () {
this.romanNumeralString = new StringBuilder();
}
public String convert (int arabicNumberToConvert) {
return romanNumeral(arabicNumberToConvert);
}
private String romanNumeral(int arabicNumberToConvert) {
int nearestBaseValue = findNearestBaseValue(arabicNumberToConvert);
int numberOfBasesInTheArabicNumber = arabicNumberToConvert / nearestBaseValue;
int numberRemainingAfterLargestBaseHasBeenDeducted =
arabicNumberToConvert % nearestBaseValue;
this.romanNumeralString = buildRomanNumeralString (nearestBaseValue,
numberOfBasesInTheArabicNumber);
return numberRemainingAfterLargestBaseHasBeenDeducted != 0 ?
convert (numberRemainingAfterLargestBaseHasBeenDeducted) :
this.romanNumeralString.toString();
}
private StringBuilder buildRomanNumeralString(int nearestBaseValue,
int numberOfBasesInTheArabicNumber) {
this.romanNumeralString.append(repeatBaseValue(nearestBaseValue,
numberOfBasesInTheArabicNumber));
return this.romanNumeralString;
}
private String repeatBaseValue (int nearestBaseValue,
int numberOfBasesInTheArabicNumber) {
return Stream.generate(() -> BASE_VALUES_MAP.get(nearestBaseValue))
.limit(numberOfBasesInTheArabicNumber)
.collect(joining());
}
private int findNearestBaseValue(int arabicNumberToConvert) {
int nearestBaseValue = 0;
int minimumDifference = Integer.MAX_VALUE;
if (BASE_VALUES_MAP.get (arabicNumberToConvert) != null) {
nearestBaseValue = arabicNumberToConvert;
} else {
for (Integer key : BASE_VALUES_MAP.keySet ()) {
int differenceBetweenBaseValueMapKeyAndArabicNumber = (arabicNumberToConvert - key);
if (differenceBetweenBaseValueMapKeyAndArabicNumber < minimumDifference
&& differenceBetweenBaseValueMapKeyAndArabicNumber > 0) {
nearestBaseValue = key;
minimumDifference = differenceBetweenBaseValueMapKeyAndArabicNumber;
}
}
}
return nearestBaseValue;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T20:11:11.800",
"Id": "421912",
"Score": "0",
"body": "An Arabic number is a number using Arabic characters and digits such as `\"12\"` which is build from digit `'1'` and a digit `'2'`. What you pass is a 32 bit value that makes up ... | [
{
"body": "<pre><code>private final Map<Integer, String> BASE_VALUES_MAP\n</code></pre>\n\n<p>This is missing <code>static</code> modifier</p>\n\n<pre><code>private StringBuilder romanNumeralString;\n</code></pre>\n\n<p>I don't think that should be a member, just pass it as argument where necessary. That ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T16:45:32.793",
"Id": "204140",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"roman-numerals"
],
"Title": "Java converter from Arabic to Roman Numerals"
} | 204140 |
<p>I have written a code that finds whether the entered words are anagrams or not. I tested and it works, but I know that there are some details that I must change or modify. So what do you think I have to change in this code?</p>
<pre><code>function findAnagram (firstWord, secondWord) {
var testWord = "";
var c = 0;
while (c < secondWord.length || c < firstWord.length) {
while (secondWord[c] == " " || firstWord[c] == " ") {
secondWord = secondWord.replace(" ", "");
firstWord = firstWord.replace(" ", "");
}
c++;
}
if (firstWord.length == secondWord.length) {
for (var i = 0; i < firstWord.length; i++) {
for (var k = 0; k < secondWord.length; k++) {
if (firstWord[i] == secondWord[k]) {
testWord += firstWord[i];
secondWord = secondWord.replace(secondWord[k], "")
break;
}
}
}
}
if (firstWord == testWord){
return "Anagram !";
}
else {
return "Not an Anagram";
}
}
console.log(findAnagram("funeral", "real fun"));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T23:24:27.453",
"Id": "394197",
"Score": "0",
"body": "You can also sort the characters of both of these words, and see if they match."
}
] | [
{
"body": "<p>Your function has a high complexity because of the 2 nested loops.</p>\n\n<p>Here is my implementation. I'm not sure if it's more efficient, but I think it's more readable.</p>\n\n<pre><code>function findAndAppendCharacter(countArray, currentChar) {\n let foundAt = -1\n\n countArray.forEach(... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T17:18:17.980",
"Id": "204142",
"Score": "0",
"Tags": [
"javascript",
"programming-challenge"
],
"Title": "JavaScript Anagram checker"
} | 204142 |
<p>I recently appeared for interview for code-pairing round and I was asked following question: Electricity Billing System for home. The corresponding power usage of home appliances (Fan, AC, Fridge, Light) was given:</p>
<pre class="lang-none prettyprint-override"><code>Appliance | Per hour unit consumption
Fan 4
Light 2
AC 10
Fridge 8
</code></pre>
<p>The slab chart was given as:</p>
<pre class="lang-none prettyprint-override"><code>Slab 1 - 0 to 1000 unit: INR Rs 20 per unit
Slab 2 - 1001 to 3000 unit: INR Rs 30 per unit
Slab 3 - 3001 to 6000 unit: INR Rs 40 per unit
Slab 4 - 6001 and above unit: INR Rs 50 per unit
</code></pre>
<p><strong>Input:</strong></p>
<pre class="lang-none prettyprint-override"><code>Appliance | CountOfAppliance | TotalUasgePerDayInHours
Fan 2 4
Light 1 4
AC 1 12
Fridge 1 5
</code></pre>
<p><strong>Output:</strong></p>
<pre class="lang-none prettyprint-override"><code>200000 INR
Units Per Day : (2*4*4 + 1*4*2 +1*12*10 + 1*5*8) = 200
unitsPerMonth = 6000
totalBill = 1000*20 + 2000*30 + 3000*30 + 3000*50 = 200000
</code></pre>
<p>I had modeled the code using "Factory Design Pattern" for appliance. But my Code for Price Slab was something the interviewer was not happy with the hardcoding. Though I modified it by using Constants file for slabs but the interviewer was still expecting something better. Kindly let me know how it can be improved.</p>
<p><code>IElectricComponent</code></p>
<pre class="lang-java prettyprint-override"><code>public interface IElectricComponent {
public enum Unit{
FAN(4), LIGHT(2), AC(10) , FRIDGE(8);
private int value;
private Unit(int value) {
this.value = value;
}
public int getValue(){
return value;
}
}
public int claculateUnitForSingleDay();
}
</code></pre>
<p><code>Fan</code></p>
<pre class="lang-java prettyprint-override"><code>public class Fan implements IElectricComponent{
private int noOfComponents;
private int perDayUsage;
public Fan(int noOfComponents, int perDayUsage){
this.noOfComponents=noOfComponents;
this.perDayUsage=perDayUsage;
}
public int claculateUnitForSingleDay(){
return noOfComponents*perDayUsage*Unit.FAN.getValue();
}
}
</code></pre>
<p>The same way for Fridge, Light and AC</p>
<p>Factory: <code>ApplianceFactory</code></p>
<pre class="lang-java prettyprint-override"><code>public class ApplianceFactory {
public static IElectricComponent getInstance(String appliance, int countOfAppliance ,int perDayUsage ){
switch(appliance){
case ApplianceConstants.FAN:
return new Fan(countOfAppliance,perDayUsage);
case ApplianceConstants.LIGHT:
return new Light(countOfAppliance,perDayUsage);
case ApplianceConstants.AC:
return new AC(countOfAppliance,perDayUsage);
case ApplianceConstants.FRIDGE:
return new Fridge(countOfAppliance,perDayUsage) ;
default :
return new IElectricComponent() {
@Override
public int claculateUnitForSingleDay() {
// TODO Auto-generated method stub
return countOfAppliance*perDayUsage;
}
};
}
}
}
</code></pre>
<p>Constants:</p>
<pre class="lang-java prettyprint-override"><code>public interface ApplianceConstants {
public String FAN = "Fan";
public String LIGHT = "Light";
public String AC = "AC";
public String FRIDGE = "Fridge";
public int Slab1 = 20;
public int Slab2 = 30;
public int Slab3 = 40;
public int Slab4 = 50;
}
</code></pre>
<p><code>PriceSlab</code>:</p>
<pre class="lang-java prettyprint-override"><code>public class PriceSlab {
HashMap<String,Integer> slabs = new HashMap<>();
public int calculateBill(int units){
slabs.put("A", ApplianceConstants.Slab1);
slabs.put("B", ApplianceConstants.Slab2);
slabs.put("C", ApplianceConstants.Slab3);
slabs.put("D", ApplianceConstants.Slab4);
return calculateBillTotal(units);
}
private int calculateBillTotal(int units) {
int total = 0;
if(units <= 1000){
total = units*slabs.get("A") ;
}
else if (units <= 3000){
total = 1000*slabs.get("A") + (units-1000)*slabs.get("B");
}
else if (units <= 6000){
total = 1000*slabs.get("A") + 2000*slabs.get("B") +(units-3000)*slabs.get("C");
}
else{
total = 1000*slabs.get("A") + 2000*slabs.get("B") + 3000*slabs.get("D")
+(units-6000)*slabs.get("C");
}
return total;
}
}
</code></pre>
<p>Main class:</p>
<pre class="lang-java prettyprint-override"><code>public class BillGenerator {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
ApplianceFactory factory = new ApplianceFactory();
int inputOfAppliance = scn.nextInt();
String appliance="";
int countOfAppliance;
int perDayUsage;
int unitsPerDay=0;
for(int t=0 ; t<inputOfAppliance ;t ++){
appliance = scn.next();
countOfAppliance = scn.nextInt();
perDayUsage = scn.nextInt();
IElectricComponent electricComponent = factory.getInstance(appliance, countOfAppliance, perDayUsage);
unitsPerDay += electricComponent.claculateUnitForSingleDay();
}
System.out.println("unitsPerDay = "+unitsPerDay);
int unitsPerMonth = unitsPerDay * 30;
System.out.println("unitsPerMonth = "+unitsPerMonth);
PriceSlab slab= new PriceSlab();
int totalBill = slab.calculateBill(unitsPerMonth);
System.out.println("totalBill = "+totalBill);
}
}
</code></pre>
<p>Please review my code and let me know if anything could be improved.</p>
| [] | [
{
"body": "<p><strong>Attention to Detail</strong></p>\n\n<p>What seem like trivial mistakes can be interpreted as a lack of attention to detail. So whilst your interface has a simple typo <code>claculateUnitForSingleDay</code> vs <code>calculateUnitForSingleDay</code>, it is noticeable. You don't want this s... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T17:26:47.350",
"Id": "204145",
"Score": "4",
"Tags": [
"java",
"interview-questions",
"factory-method"
],
"Title": "Electricity billing system for home in OOP"
} | 204145 |
<p>I am doing a <a href="http://www.gcsecs.com/uploads/2/6/5/0/26505918/gcse_computer_science_1cp1_specimen_nea_april_2017.pdf" rel="nofollow noreferrer">GCSE NEA project</a> for practice.</p>
<blockquote>
<h1>Customer Loyalty Scheme</h1>
<p>The managers of Crawdale Hotel Group have decided to update their customer loyalty
scheme. Customers joining the scheme become silver members. Customers are upgraded
to gold members when they have booked 30 nights’ accommodation and to platinum
once they reach 100 nights.</p>
<p>Silver members receive 2500 loyalty points per night booked, gold members receive
3000 points and platinum members 4000 points. The data is stored as a text file.</p>
<p>The data in this table is provided in the SampleData2017.txt file.</p>
<pre><code>+----------+-----------+------------+------------------+--------------+---------------+
| MemberID | Surname | YearJoined | MembershipStatus | NightsBooked | PointsBalance |
+----------+-----------+------------+------------------+--------------+---------------+
| Gri33415 | Griffiths | 2015 | Gold | 35 | 40000 |
+----------+-----------+------------+------------------+--------------+---------------+
| Smi22316 | Smith | 2016 | Silver | 3 | 7500 |
+----------+-----------+------------+------------------+--------------+---------------+
| Mia56213 | Miah | 2013 | Platinum | 140 | 165000 |
+----------+-----------+------------+------------------+--------------+---------------+
| All78915 | Allen | 2015 | Platinum | 120 | 145000 |
+----------+-----------+------------+------------------+--------------+---------------+
| Hug91714 | Huggett | 2014 | Platinum | 150 | 50000 |
+----------+-----------+------------+------------------+--------------+---------------+
| Sel77617 | Selby | 2017 | Gold | 40 | 45000 |
+----------+-----------+------------+------------------+--------------+---------------+
| San55614 | Santus | 2014 | Silver | 12 | 30000 |
+----------+-----------+------------+------------------+--------------+---------------+
| Lee44213 | Leewah | 2013 | Silver | 15 | 37500 |
+----------+-----------+------------+------------------+--------------+---------------+
</code></pre>
<p>The loyalty points can be redeemed for nights at the hotels. A night costs 25000 points.</p>
<h1>Requirements</h1>
<p>The managers want a computer program to help them operate the scheme efficiently.
The program must allow hotel staff to add new members to the scheme, record nights
booked and points redeemed. It must also update a member’s points balance each time
they book nights or redeem points, upgrade their membership status when appropriate
and allow the number and status of the members to be monitored.</p>
<p>The number of nights in a single booking must be limited to a maximum of 14.</p>
<p>The program must allocate a unique ID to each new member consisting of the first three
letters of their surname, plus a three-digit number, followed by the last two digits of the
current year.</p>
<p>Your task is to analyse these requirements and to design, implement, test and evaluate a
solution. You will need to make some assumptions and decisions of your own. </p>
</blockquote>
<p>Below is my code. Can you please tell me if I need any improvements or anything?</p>
<pre><code>while True:
import random
import time
select = input("=============================\n\nA - Add new user \nB - Book a night \nC - Check everyones account information \nR - Redeem a night \nQ - Quit System \nChoose an option: ")
if select == 'A':
hotelfile = open("SampleData2017.txt", "a+")
membersname = input("What is your surname? ")
eighteen = ("18")
username = membersname[0:3] + str(random.randint(100, 999)) + eighteen
print("Your username is ", username)
comma = (",")
hotelfile.write (username)
hotelfile.write (comma)
hotelfile.write (membersname)
hotelfile.write (comma)
hotelfile.write ("2018")
hotelfile.write (comma)
hotelfile.write ("Silver")
hotelfile.write (comma)
hotelfile.write ("0")
hotelfile.write (comma)
hotelfile.write ("0")
hotelfile.write ("\n")
hotelfile.close()
elif select == 'B':
print("test")
elif select == 'C':
hotelfile = open("SampleData2017.txt", "r+")
for line in hotelfile:
print (line)
hotelfile.close()
elif select == 'Q':
break
else:
break
</code></pre>
<h3>SampleData2017.txt</h3>
<pre><code>Gri33415,Griffiths,2015,Gold,35,40000
Smi22316,Smith,2016,Silver,3,7500
Mia56213,Miah,2013,Platinum,120,145000
Hug91714,Hugget,2014,Platinum,150,50000
Sel77617,Selby,2017,Gold,40,45000
San55614,Santus,2014,Silver,12,30000
Lee44213,Leeway,2013,Silver,150,37500
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T05:57:47.780",
"Id": "393959",
"Score": "0",
"body": "Are you allowed to `import csv`? This would make the exercise very easy (avoids the necessity of you writing the file input/output handling)."
}
] | [
{
"body": "<h2>Move <code>import</code>s outside of loops</h2>\n\n<p>Whether or not Python optimizes this away, it is better to move <code>import</code> statements to the top of the file rather than scattered among the rest of the code.</p>\n\n<h2>Use nouns for variable names, verbs for functions</h2>\n\n<p>Ins... | {
"AcceptedAnswerId": "204156",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T18:04:39.743",
"Id": "204148",
"Score": "3",
"Tags": [
"python",
"beginner",
"csv"
],
"Title": "Hotel booking system help on how to book nights and memberships"
} | 204148 |
<p>I have been typically adding the @transaction.atomic decorator to my endpoints and appreciate if a request fails at any point the data completely rolls back. However, some of my endpoints will make an API call to another API service. If my token for that API service is invalid, I refresh the token. This is all well and good until an exception occurs after the API token has been refreshed. The transaction is rolled back including the token information which then will be stale. This includes the new refresh token information so I'm now unable to refresh the auth token.</p>
<p>I attempted to get around this situation by distributing the token refresh to a celery task and waiting for the result as a way of isolating that database change. Even if the requests fails later on, the token information remains while the rest is rolled back.</p>
<p>Here is a simplified example</p>
<pre><code>@transaction.atomic()
def post(request):
response = api_call()
db_operation(response['result']) # Could potentially have an exception
def api_call(allow_refresh=True)
response = requests.post(url, params)
if response.status_code == 401:
if allow_refresh:
refresh_token_task.delay().get(timeout=10)
response = api_call(allow_refresh=False)
else:
raise Exception('Invalid authorization') # In the case refreshing token doesn't resolve authorization issues, this prevents infinite loop.
return response
</code></pre>
<p>Phew! I thought I was in the clear except... sometimes I distribute api calls. It didn't occur to me but I realized calling celery tasks from celery tasks easily risks locking. So now I've written out a solution that involves chaining.</p>
<pre><code>def post(request):
chain(api_call_task.s(), refresh_token_task.s(), api_call_task.s(), db_operation_task.s())()
@task
def api_call_task(initial_response=None)
if initial_response and initial_response.status_code != 401:
return response
response = requests.post(url, params)
return response
@task
def refresh_token_task(response):
if response.status_code == 401:
refresh_token()
return response
@transaction.atomic()
@task
def db_operation_task(response):
if response.status_code == 401:
raise Exception('Invalid authorization')
db_operation(response['result'])
</code></pre>
<p>I think this works to a degree but gosh what a confusing mess. By chaining the functions, the response is continuously passed through which determines if the token needs to be refreshed and/or if the call needs to be made again and then finally to handle the db operation based upon the response to the api. </p>
<p>Is there a simpler way? Marginal improvement? Bad practice involved? Would it better to just let go of transaction.atomic? Let me know if my simplified pseudo code can use clarification.</p>
| [] | [
{
"body": "<p>Let's start off with what's probably the most important note here: if you are running into issues with atomic transactions, pushing the database work off to Celery (or another worker thread) inherently makes your transactions non-atomic. It sounds like this has been working for you currently, but ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T19:05:41.973",
"Id": "204150",
"Score": "1",
"Tags": [
"python",
"database",
"django",
"authorization",
"transactions"
],
"Title": "Isolate a Database Change Within Django Transaction.Atomic"
} | 204150 |
<p>In my web application, a user will click a button which will call a function that triggers an AJAX call. That function accepts a single argument. I would like to be able to put that function in place of the anonymous function in the jQuery event handler. I suspect that this is a scoping issue...</p>
<p>Here is my working code:</p>
<pre><code>(function () {
'use strict';
var postId;
function userAddFlagToPost (userId) {
return $.ajax({
type: 'POST',
timeout: 1000 * 3;,
url: '/someApi/postId',
data: {
userId: userId
},
}).done(onFlagSubmitDone)
.fail(onFlagSubmitDone);
}
function onLoggedIn() {
var userId = getCookie('some_user_auth') || null;
$(SELECTORS.POST_FLAG).on('click', function() {
postId = $(this).data('postId');
});
$(SELECTORS.SUBMIT_BUTTON).on('click', function() {
userAddFlagToPost(userId);
});
}
function init() {
eventQ.register(onLoggedIn);
}
init();
})();
</code></pre>
<p>I would like to be able to do:</p>
<pre><code>$(SELECTORS.SUBMIT_BUTTON).on('click', userAddFlagToPost(userId));
</code></pre>
<p>I'd appreciate any info or advice on how to go about refactoring this code, thanks! </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T20:04:24.907",
"Id": "393779",
"Score": "0",
"body": "I fear that this is off-topic, it sounds like you are asking how to implement functionality. Please only post code that already accomplishes the task at hand."
},
{
"Con... | [
{
"body": "<p>It seems that what you want is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Partially_applied_functions\" rel=\"nofollow noreferrer\">partially-applied function</a>. One way this can be achieved is using <a href=\"https://developer.mozi... | {
"AcceptedAnswerId": "204155",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T19:25:49.907",
"Id": "204152",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"ajax",
"callback"
],
"Title": "pass argument to jQuery .on() event handler callback"
} | 204152 |
<p>I created a small Javascript elevator simulation that works as expected, however, being pretty new to Javascript I can t help but feel like this code in unnecessarily complex. Honestly any feedback would be appreciated. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const doorOpenSpeed = 3
var Elevator = function() {
this.currentFloor = 1;
// 1 floor ever 3 seconds
this.speed = 3;
this.doorOpenTime = 3;
this.doorsOpen = false;
this.isMoving = false;
this.availableFloors = Array.from({length: 10}, (min, max) => max+1);
this.openDoors = function(doors) {
for (let i = 0; i < doors.length; i++) {
doors[i].classList.add(doors[i].id + "-moved");
}
this.doorsOpen = true;
}
this.closeDoors = function(doors) {
for (let i = 0; i < doors.length; i++) {
doors[i].classList.remove(doors[i].id + "-moved");
}
this.doorsOpen = false;
}
}
var Panel = function(elevator) {
var enter = document.querySelector("#enter");
var inputButtons = document.querySelectorAll(".panel-input-button");
this.updateDisplay = function(floor) {
var floorNumber = document.querySelector("#floor-number");
floorNumber.innerHTML = floor;
}
this.displayInput = function(button) {
var display = document.querySelector("#panel-display");
display.innerHTML = button.id;
}
this.pauseInput = function() {
elevator.isMoving = false;
var arrivalNotification = document.querySelector("#arrived-notification");
arrivalNotification.innerHTML = "*";
}
this.moveElevator = function() {
var requestedFloor = document.querySelector("#panel-display").innerHTML;
if (!elevator.isMoving) {
if (requestedFloor in elevator.availableFloors) {
if (requestedFloor != elevator.currentFloor) {
elevator.isMoving = true;
var arrivalNotification = document.querySelector("#arrived-notification");
var upArrow = document.querySelector("#up-arrow");
var downArrow = document.querySelector("#down-arrow");
arrivalNotification.innerHTML = "";
this.updateDisplay(requestedFloor);
if (requestedFloor > elevator.currentFloor) {
upArrow.classList.remove("hide");
downArrow.classList.add("hide");
}
else {
downArrow.classList.remove("hide");
upArrow.classList.add("hide");
}
var travelTime = (Math.abs(requestedFloor - elevator.currentFloor) *
(elevator.speed * 1000)) +
(doorOpenSpeed * 1000) +
(elevator.doorOpenTime * 1000);
var arrivalTime = (Math.abs(requestedFloor - elevator.currentFloor) *
(elevator.speed * 1000)) +
(doorOpenSpeed * 1000) +
(elevator.doorOpenTime * 2000);
setTimeout(this.pauseInput.bind(this), travelTime);
elevator.currentFloor = requestedFloor;
var elevatorDoors = document.querySelectorAll(".elevator-door");
elevator.openDoors(elevatorDoors);
setTimeout(elevator.closeDoors.bind(this, elevatorDoors), elevator.doorOpenTime * 1000);
setTimeout(elevator.openDoors.bind(this, elevatorDoors), arrivalTime);
setTimeout(elevator.closeDoors.bind(this, elevatorDoors), arrivalTime + (elevator.doorOpenTime * 1000));
}
}
}
}
enter.addEventListener("click", this.moveElevator.bind(this), true);
for (let i = 0; i < inputButtons.length; i++) {
inputButtons[i].addEventListener("click", this.displayInput.bind(this, inputButtons[i]), true);
}
}
var elevator = new Elevator;
var panel = new Panel(elevator);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
width: 100%;
table-layout: fixed;
border-spacing:7px 7px;
}
td {
border: 1px solid black;
border-radius: 50%;
text-align: center;
cursor: pointer;
}
.left-elevator-door-moved {
transform: translate(-125px);
transition: 3s;
}
.right-elevator-door-moved {
transform: translate(125px);
transition: 3s;
}
#container {
height: 500px;
}
#feedback-panel {
width: 100px;
height: 50px;
margin: 10px 10px 10px 75px;
background-color: black;
color: red;
display: flex;
align-items: center;
}
#arrived-notification {
display: inline;
margin-left: 13px;
margin-top: 7px;
font-size: 28px;
flex: 1;
}
#directional-arrows {
flex-direction: column;
margin-left: 10px;
flex: 1;
}
#floor-number {
display: inline;
margin-left: 13px;
font-size: 28px;
flex: 1;
}
#elevator {
width: 250px;
height: 400px;
background-color: #4d4d4d;
display: inline-flex;
overflow: hidden;
}
#left-elevator-door {
justify-content: space-between;
padding: 0px;
margin: 0px;
width: 50%;
height: 100%;
background-color: #bcc6cc;
border-right: 3px solid black;
align-self: left;
transition: 3s;
}
#right-elevator-door {
justify-content: space-between;
padding: 0px;
margin: 0px;
width: 50%;
height: 100%;
background-color: #bcc6cc;
border-left: 3px solid black;
transition: 3s;
}
#panel {
background-color: #bcc6cc;
border: 1px solid black;
width: 60px;
height: 210px;
position: relative;
bottom: 50%;
left: 300px;
}
#panel-display {
background-color: #000000;
height: 15px;
width: 70%;
margin: 5px auto;
text-align: center;
color: red;
padding: 5px;
}
#panel-input {
width: 100%;
display: block;
margin: 0 auto;
}
#enter {
border: 1px solid black;
border-radius: 5px;
text-align: center;
margin: 1px auto;
width: 80%;
cursor: pointer;
}
.hide {
display: none !important;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Jelevator</title>
</head>
<body>
<div id="container">
<div id="feedback-panel">
<div id="directional-arrows">
<img id="up-arrow" src="https://drive.google.com/uc?export=view&id=1qdazZI7Up-xMaidLLorgYtTTzP_pOjAD" height="20px" width="20px">
<img id="down-arrow" src="https://drive.google.com/uc?export=view&id=1bDPC6QDSA9__swiKJr8wLcfLr_GtUPyM" height="20px" width="20px">
</div>
<div id="floor-number">1</div>
<div class="arrived" id="arrived-notification"></div>
</div>
<div id="elevator">
<div class="elevator-door" id="left-elevator-door"></div>
<div class="elevator-door" id="right-elevator-door"></div>
</div>
<div id="panel">
<div id="panel-display"></div>
<div id="panel-input">
<table>
<tr>
<td class="panel-input-button" id="1">1</td>
<td class="panel-input-button" id="2">2</td>
</tr>
<tr>
<td class="panel-input-button" id="3">3</td>
<td class="panel-input-button" id="4">4</td>
</tr>
<tr>
<td class="panel-input-button" id="5">5</td>
<td class="panel-input-button" id="6">6</td>
</tr>
<tr>
<td class="panel-input-button" id="7">7</td>
<td class="panel-input-button" id="8">8</td>
</tr>
<tr>
<td class="panel-input-button" id="9">9</td>
<td class="panel-input-button" id="10">10</td>
</tr>
</table>
<div id="enter">Enter</div>
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Feedback</h2>\n\n<p>The simulator itself looks nice. I like the simple layout of the number pad, as well as the animations on the door. The colors look nice as well. As far as the code goes, there are some suggestions outlined below. I do like the use of partially applied functions in the calls t... | {
"AcceptedAnswerId": "204170",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T19:31:56.750",
"Id": "204154",
"Score": "4",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6"
],
"Title": "Small Javascript elevator simulation"
} | 204154 |
<p>This is a cut-and-dried Fisher-Yates implementation. As not typically a JS developer, I've tried to incorporate as many best practices as I can. I would appreciate any input as to make it conform to more best practices and continue to be maintainable.</p>
<pre><code>(function fisherYates () {
"use strict";
var shuffle = function shuffle (array) {
var beginningIndex = 0,
currentIndex = array.length,
indexDecrement = 1,
randomIndex = 0,
temporaryValue = 0;
// While elements remain to be shuffled...
while (currentIndex !== beginningIndex) {
// Pick an element from the remaining elements...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= indexDecrement;
// Swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
return shuffle;
}());
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T23:08:47.243",
"Id": "393639",
"Score": "1",
"body": "Minor point - having indexDecrement as a variable makes it look like it could change. IMO, \"currentIndex--\" is clear enough on its own, but if you did want it named it should ... | [
{
"body": "<ul>\n<li><p>The docs on \"use strict\" are vague but I'm not entirely sure putting it inside a function makes it apply to the function definition.</p></li>\n<li><p><code>var shuffle = function shuffle (array) {</code> seems unnecessarily redundant. I would just use <code>function shuffle (array) {</... | {
"AcceptedAnswerId": "204169",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T22:39:23.537",
"Id": "204162",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"shuffle"
],
"Title": "Fisher-Yates Shuffle"
} | 204162 |
<p>In answering a question on StackOverflow, it occurred to me that a more generic version of <code>GroupBy</code> for C# that delegated membership in each group to a class could be useful.</p>
<p>This is my attempt, but I am unsatisfied with a few things. I don't particularly like the need to constrain the element type to <code>IOrderable</code> - I feel like it should be possible to delegate ordering to the group type somehow (I really wanted a static method constraint in the <code>IGGrouping</code> interface).</p>
<pre><code>public interface IOrderable<T> {
double ordering();
}
public interface IGGrouping<T> : IEnumerable<T> where T : IOrderable<T> {
bool BelongsToGroup(T aT);
IGGrouping<T> Add(T aT);
}
public static class IEnumerableExt {
public static IEnumerable<IGGrouping<T>> GroupBy<TG,T>(this IEnumerable<T> src) where TG : IGGrouping<T>, new() where T : IOrderable<T> {
var groups = new List<IGGrouping<T>>();
void Add(T aT) {
var found = false;
foreach (var g in groups) {
found = g.BelongsToGroup(aT);
if (found) {
g.Add(aT);
break;
}
}
if (!found)
groups.Add(new TG().Add(aT));
}
foreach (var s in src.OrderBy(s => s.ordering()))
Add(s);
return groups;
}
}
</code></pre>
<p>Here's a sample class to group by distance from center of current groups:</p>
<pre><code>public class gRectangleGroup : IGGrouping<Rectangle> {
List<Rectangle> members;
public Point center;
public gRectangleGroup() {
members = new List<Rectangle>();
}
public gRectangleGroup Add(Rectangle r) {
members.Add(r);
center = new Point(members.Average(m => m.Loc.X), members.Average(m => m.Loc.Y));
return this;
}
public bool BelongsToGroup(Rectangle r) => center.Distance(r.Loc) <= 5;
public Rectangle Middle() => members.OrderBy(m => m.Loc.Distance(center)).First();
public IEnumerator<Rectangle> GetEnumerator() => members.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IGGrouping<Rectangle> IGGrouping<Rectangle>.Add(Rectangle aT) => Add(aT);
}
</code></pre>
<p>You use <code>gRectangleGroup</code> like so:</p>
<pre><code>List<Rectangle> list;
var ans2 = list.GroupBy<gRectangleGroup, Rectangle>().Cast<gRectangleGroup>().Select(rg => rg.Middle());
</code></pre>
<p>I don't like having to list the group type and the element type explicitly in the call to <code>GroupBy</code>. I don't like the <code>Cast</code> to <code>gRectangleGroup</code> when the type is passed to the <code>GroupBy</code>, but if <code>GroupBy</code> returns <code>TG</code> then I have to give up the fluent <code>Add</code> call for new groups.</p>
<p>I also don't like how a class that implements <code>IGGrouping</code> (like <code>gRectangleGroup</code>) and has a fluent <code>Add</code> that returns <code>this</code>, must also have another <code>Add</code> to return <code>IGGrouping<T></code> because of the interface.</p>
<p>Can anyone suggest how this might be improved, or what they would change to solve the same issue?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T00:47:42.083",
"Id": "393642",
"Score": "0",
"body": "Could you post the code for gRectangleGroup? With your current design, it's not clear how BelongsToGroup could be implemented, given that all the groupings will be identical.\n\... | [
{
"body": "<p>You don't need the type parameter on IOrderable:</p>\n\n<pre><code> public interface IOrderable\n {\n double Ordering();\n }\n</code></pre>\n\n<hr>\n\n<p>I don't like that you sort the source vector without notifying the client. In this way mysterious things are going on and the method does ... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-21T23:48:07.147",
"Id": "204163",
"Score": "2",
"Tags": [
"c#",
"linq",
"generics",
"iterator",
"interface"
],
"Title": "Handling related generic type parameters"
} | 204163 |
<p>I could not find the script I was looking for, so I made my own with the knowledge I have at this moment.</p>
<p>This is my custom PHP script to send a single notification/SMS/email when a script or site is either offline or online. It could be set to run by cron every <em>x</em> minutes, but only send a notification after the state has changed from offline to online or vice-versa. The state is remembered/saved in the <code>toggle.txt</code> file in the same directory.</p>
<p>I tested this and it works the way it should. For simplicity, the <code>$site</code> variable is the place where the server/site check would be and output wither ON or OFF (I used AAN/UIT here, to not confuse with ONLINE or OFFLINE written to the <code>toggle.txt</code>). This could also be used for other purposes, with the same construction.</p>
<p>I would like to know what you think of this script and if and how it can be improved. Maybe a version without the external toggle.txt requirement, but to have it stored all in the same php file?</p>
<pre><code><?php
$site = 'AAN';
$file = 'toggle.txt';
$memory = file_get_contents($file);
if (strpos($site,'UIT') !== false) // Site status OFFLINE
{
if (strpos($memory,'OFFLINE') !== false) // when Memory ONLINE
{
// do nothing - send mail/sms script here.
echo "We know server is OFFLINE - No alerts to send.";
}
else // when Memory OFFLINE
{
echo "ALERT: Your Server is OFFLINE"; // send notification
$memory = "OFFLINE";
}
}
else // Site status ONLINE
{
if (strpos($memory,'ONLINE') !== false) // Memory ONLINE
{
// do nothing - send mail/sms script here.
echo "We know server is ONLINE - No alerts to send.";
}
else // when Memory OFFLINE
{
echo "ALERT: Your Server is Online"; // send notification
$memory = "ONLINE";
}
}
file_put_contents($file, $memory);
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T08:55:27.957",
"Id": "393657",
"Score": "0",
"body": "This is quite a tiny bit of code, so there isn't much to work with. You could improve the quality of it, however. Check the comments, do they make sense? Is the code indented in ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T00:07:08.993",
"Id": "204164",
"Score": "1",
"Tags": [
"php"
],
"Title": "Send single notification script until state change"
} | 204164 |
<p><a href="https://unix.stackexchange.com/a/36407/3645">@angus on Unix.SE</a> implemented a tool in C to list upcoming cron jobs in response to a question. I've <a href="https://gitlab.com/victor-engmark/cronlist" rel="nofollow noreferrer">re-implemented the basic functionality</a> (showing only the next cron job) in Rust, using <code>rustfmt</code>, <code>clippy</code> and TDD to keep it reasonably clean, but it's my first non-trivial program:</p>
<pre><code>use std::ops::RangeInclusive;
pub struct DateTimeFieldParser {
range: RangeInclusive<u8>,
wrap_around_at_end: bool,
}
impl DateTimeFieldParser {
pub fn new(min: u8, max: u8) -> DateTimeFieldParser {
DateTimeFieldParser {
range: min..=max,
wrap_around_at_end: false,
}
}
pub fn new_with_wrap_around(min: u8, max: u8) -> DateTimeFieldParser {
DateTimeFieldParser {
range: min..=max,
wrap_around_at_end: true,
}
}
pub fn parse_field(&self, string_value: &str) -> Vec<u8> {
let mut values = Vec::with_capacity((self.range.end() - self.range.start()) as usize);
string_value
.split(',')
.for_each(|part| values.append(&mut self.parse_list_entry(part)));
values.sort_unstable();
values.dedup();
values
}
fn parse_list_entry(&self, string_value: &str) -> Vec<u8> {
let mut parts = string_value.splitn(2, '/');
let values = parts
.next()
.unwrap()
.replace("*", &format!("{}-{}", self.range.start(), self.range.end() - 1));
let values = match values.to_lowercase().as_ref() {
"sun" => "0",
"jan" | "mon" => "1",
"feb" | "tue" => "2",
"mar" | "wed" => "3",
"apr" | "thu" => "4",
"may" | "fri" => "5",
"jun" | "sat" => "6",
"jul" => "7",
"aug" => "8",
"sep" => "9",
"oct" => "10",
"nov" => "11",
"dec" => "12",
_ => &values,
};
let values: RangeInclusive<u8> = self.parse_range(values);
let step = match parts.next() {
Some(string_value) => string_value.parse::<u8>().unwrap(),
None => 1,
};
let mut values: Vec<u8> = values.step_by(step as usize).collect();
let last_value = values.pop().unwrap();
if last_value == *self.range.end() + 1 && self.wrap_around_at_end {
values.push(0);
} else {
values.push(last_value);
}
self.verify_range(values[0]);
self.verify_range(values[values.len() - 1]);
values
}
fn parse_range(&self, values: &str) -> RangeInclusive<u8> {
let mut range_or_value = values.splitn(2, '-').map(|part| part.parse().unwrap());
let first = range_or_value.next().expect("Empty range");
let last = match range_or_value.next() {
Some(value) => value,
None => first,
};
first..=last
}
fn verify_range(&self, value: u8) {
assert!(*self.range.start() <= value);
assert!(*self.range.end() >= value);
}
}
</code></pre>
<p>Tests:</p>
<pre><code>#[cfg(test)]
mod tests {
use super::DateTimeFieldParser;
#[test]
fn should_parse_complex_pattern() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_field("5-9/2,1,*/5"), vec![1, 5, 6, 7, 9, 11]);
}
#[test]
fn should_parse_comma_separated_numbers() {
let parser = DateTimeFieldParser::new(0, 23);
assert_eq!(parser.parse_field("0,23"), vec![0, 23]);
}
#[test]
fn should_parse_range_with_step() {
let parser = DateTimeFieldParser::new(0, 23);
assert_eq!(parser.parse_list_entry("1-7/2"), vec![1, 3, 5, 7]);
}
#[test]
fn should_parse_asterisk() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("*/4"), vec![1, 5, 9]);
}
#[test]
fn should_parse_january_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Jan"), vec![1]);
}
#[test]
fn should_parse_february_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Feb"), vec![2]);
}
#[test]
fn should_parse_march_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Mar"), vec![3]);
}
#[test]
fn should_parse_april_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Apr"), vec![4]);
}
#[test]
fn should_parse_may_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("May"), vec![5]);
}
#[test]
fn should_parse_june_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Jun"), vec![6]);
}
#[test]
fn should_parse_july_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Jul"), vec![7]);
}
#[test]
fn should_parse_august_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Aug"), vec![8]);
}
#[test]
fn should_parse_september_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Sep"), vec![9]);
}
#[test]
fn should_parse_october_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Oct"), vec![10]);
}
#[test]
fn should_parse_november_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Nov"), vec![11]);
}
#[test]
fn should_parse_december_name() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("Dec"), vec![12]);
}
#[test]
fn should_parse_month_name_case_insensitively() {
let parser = DateTimeFieldParser::new(1, 12);
assert_eq!(parser.parse_list_entry("dEC"), vec![12]);
}
#[test]
fn should_parse_sunday_name() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("Sun"), vec![0]);
}
#[test]
fn should_parse_monday_name() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("Mon"), vec![1]);
}
#[test]
fn should_parse_tuesday_name() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("Tue"), vec![2]);
}
#[test]
fn should_parse_wednesday_name() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("Wed"), vec![3]);
}
#[test]
fn should_parse_thursday_name() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("Thu"), vec![4]);
}
#[test]
fn should_parse_friday_name() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("Fri"), vec![5]);
}
#[test]
fn should_parse_saturday_name() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("Sat"), vec![6]);
}
#[test]
fn should_parse_week_day_name_case_insensitively() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_list_entry("sAT"), vec![6]);
}
#[test]
fn should_remove_duplicates() {
let parser = DateTimeFieldParser::new(1, 2);
assert_eq!(parser.parse_field("1,1,2,2,2"), vec![1, 2]);
}
#[test]
fn should_sort_values() {
let parser = DateTimeFieldParser::new(1, 2);
assert_eq!(parser.parse_field("2,1"), vec![1, 2]);
}
#[test]
fn should_parse_wraparound_sunday() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_field("7"), vec![0]);
}
#[test]
fn should_parse_week_range_with_sunday_at_end() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_field("4-7"), vec![0, 4, 5, 6]);
}
#[test]
fn should_parse_week_range_with_sunday_at_both_sides() {
let parser = DateTimeFieldParser::new_with_wrap_around(0, 6);
assert_eq!(parser.parse_field("0-7"), vec![0, 1, 2, 3, 4, 5, 6]);
}
#[test]
fn should_parse_range() {
let parser = DateTimeFieldParser::new(0, 23);
assert_eq!(parser.parse_range("1-3"), { 1..=3 });
}
#[test]
#[should_panic]
fn should_fail_verification_below_min() {
let parser = DateTimeFieldParser::new(1, 12);
parser.verify_range(0)
}
#[test]
fn should_verify_at_min() {
let parser = DateTimeFieldParser::new(0, 23);
parser.verify_range(0);
}
#[test]
fn should_verify_between_min_and_max() {
let parser = DateTimeFieldParser::new(0, 23);
parser.verify_range(12);
}
#[test]
fn should_verify_at_both_min_and_max() {
let parser = DateTimeFieldParser::new(1, 1);
parser.verify_range(1);
}
#[test]
fn should_verify_at_max() {
let parser = DateTimeFieldParser::new(0, 23);
parser.verify_range(23);
}
#[test]
#[should_panic]
fn should_fail_verification_above_max() {
let parser = DateTimeFieldParser::new(0, 23);
parser.verify_range(24);
}
}
</code></pre>
| [] | [
{
"body": "<p>I’d go out on a limb and call this Good Code™️. I’m easily able to follow all the logic. It’s fairly idiomatic, using map/reduce instead of loops and pattern matching. The tests are all super tight and clear. </p>\n\n<p>The only thing that catches my eye are those <code>[should_panic]</code> annot... | {
"AcceptedAnswerId": "204227",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T01:21:19.957",
"Id": "204165",
"Score": "2",
"Tags": [
"parsing",
"datetime",
"rust",
"configuration",
"scheduled-tasks"
],
"Title": "Crontab datetime field pattern parser in Rust"
} | 204165 |
<p>Problem Statement: <a href="https://www.spoj.com/problems/JNEXT/" rel="nofollow noreferrer">JNEXT</a></p>
<blockquote>
<p>DevG was challanged to find the just next greater number which can be formed using digits of a given number. Now DevG needs your help to find that just next greater number and win the challenge.</p>
<h2>Input</h2>
<p>The first line have t number of test cases (1 <= t <= 100). In next 2*t lines for each test case first there is number n (1 <= n <= 1000000) which denotes the number of digits in given number and next line contains n digits of given number separated by space.</p>
<h2>Output</h2>
<p>Print the just next greater number if possible else print -1 in one line for each test case.</p>
<p>Note : There will be no test case which contains zero in starting digits of any given number.</p>
<h2>Example</h2>
<h3>Input:</h3>
<pre><code>2
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6
</code></pre>
<h3>Output:</h3>
<pre><code>15834
1474584162
</code></pre>
</blockquote>
<p>My Solution is</p>
<pre><code>public static void main(String[] argh) throws Exception{
Reader br = new Reader();
int t= br.nextInt();
for(int aa=0; aa<t; aa++){
int n= br.nextInt();
int[] arr= new int[n];
int breakPoint= -1;
int mI= -1;
for(int qq=0; qq<n; qq++){
arr[qq]= br.nextInt();
if(qq !=0 && arr[qq] > arr[qq-1]){
breakPoint= qq-1;
}
if(breakPoint != -1){
if(arr[breakPoint] < arr[qq]){
mI= qq;
}
}
}
if(breakPoint == -1 || n == 1){
System.out.println(-1);
continue;
}
// swap
arr[breakPoint]= arr[breakPoint] + arr[mI];
arr[mI]= arr[breakPoint] - arr[mI];
arr[breakPoint]= arr[breakPoint] - arr[mI];
breakPoint++;
for(int ii=0; ii<breakPoint; ii++){
System.out.print(arr[ii]);
}
for(int ii=n-1; ii>=breakPoint; ii--){
System.out.print(arr[ii]);
}
System.out.println("");
}
}
</code></pre>
<p>My solution is having O(N) time complexity but still I am getting TLE.
Can anyone point out issue?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T07:13:37.370",
"Id": "393650",
"Score": "0",
"body": "\"My solution is having O(N) time complexity\" Are you absolutely sure about that? Please include a link to the original challenge as well."
},
{
"ContentLicense": "CC BY... | [
{
"body": "<pre><code>int[] arr\n</code></pre>\n\n<p>You can probably create it only once, with maximum possible size, outside for for loop.</p>\n\n<pre><code>System.out.print(arr[ii]);\n</code></pre>\n\n<p>You need to use StringBuilder and output only whole string in single <code>println</code> call. Multiple ... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T05:25:44.547",
"Id": "204172",
"Score": "2",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "TLE in JNEXT problem in SPOJ"
} | 204172 |
<p>I'm an undergraduate student and I have this assignment on a Discrete Event simulator. Currently I have completed to the end of v1.2 <a href="https://nus-cs2030.github.io/1718-s2/lab2a/index.html" rel="noreferrer">here</a>. Attached also, is an algorithmic overview.</p>
<p><a href="https://i.stack.imgur.com/VL8OT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VL8OT.png" alt="enter image description here"></a></p>
<p>I have wrote my code as such to solve the problem at hand. Even though the code feels correct according to the test cases used to test the code, I think there is definitely room for improvement in the design aspect. I came up with this code by drawing the problem out and solving it in a procedural manner and then trying to re-design it in OO. Personally I came from a Python background and now I'm learning Java for this module, so I'm still picking up the ropes on OOP design and getting rid of as much "procedural mindset" as much as possible.</p>
<p><strong>Main</strong></p>
<pre><code>import java.util.Scanner;
import cs2030.simulator.Event;
import cs2030.simulator.Customer;
import cs2030.simulator.EventComparator;
import cs2030.simulator.EventManager;
import cs2030.simulator.ArrivalEvent;
/**
* Main class for testing purposes.
*/
public class Main {
/**
* Creates an EventManager to simulate the execution of events.
* This is done by using Scanner object to take in inputs.
* required for a RandomGenerator, then pass those arguments to EventManager.
* @param args String[]
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int seed = sc.nextInt();
int numServers = sc.nextInt();
int numCustomer = sc.nextInt();
double arrivalRate = sc.nextDouble();
double svcRate = sc.nextDouble();
sc.close();
double restRate = 1.0;
EventManager eventManager = new EventManager(numServers, numCustomer,
seed,arrivalRate,svcRate,restRate);
eventManager.doService();
}
}
</code></pre>
<p><strong>EventManager</strong></p>
<pre><code>package cs2030.simulator;
import java.util.PriorityQueue;
/**
* EventManager class that handles the sequence of Event executions.
*/
public class EventManager {
/**
* Array of servers that determines the way ArrivalEvents are processed.
*/
Server [] servers;
/**
* PriorityQueue of events to be cleared by the end of the simulation.
*/
PriorityQueue<Event> events;
/**
* Statistics object to keep track of average waiting time of served customers,
* number of served customers,
* and the number of customers that left without being served.
*/
Statistics statistics = new Statistics();
/**
* RandomGenerator object to randomise arrival time as well as
* service time, which is the time to convert ServedEvent to DoneEvent.
*/
RandomGenerator gen;
/**
* Constructs a EventManager that creates the ArrivalEvents of randomised time.
* from the number of customers, load them into the PriorityQueue.
* @param numServers the number of servers to be created.
* @param numCustomer the number of customers to be served, which is
* also equal to the number of ArrivalEvents preloaded onto PriorityQueue.
* @param seed intialising value where the random values are generated from
* @param arrivalRate arrival rate, mu in RandomGenerator constructor
* @param svcRate service rate, lambda in RandomGenerator constructor
* @param restRate rest rate, rho in RandomGenerator constructor
*/
public EventManager(int numServers, int numCustomer,
int seed, double arrivalRate, double svcRate, double restRate) {
this.events = new PriorityQueue<>(new EventComparator());
this.gen = new RandomGenerator(seed, arrivalRate,svcRate,restRate);
double time = 0;
Customer customer = new Customer(time);
ArrivalEvent tempEvent = new ArrivalEvent(customer,time);
events.add(tempEvent);
for (int i = 0;i < numCustomer - 1;i++) {
double x = gen.genInterArrivalTime();
time += x;
customer = new Customer(time);
tempEvent = new ArrivalEvent(customer,time);
events.add(tempEvent);
}
this.servers = new Server [numServers];
for (int i = 0;i < numServers;i++) {
this.servers[i] = new Server();
}
}
/**
* Processes the full sequence of ArrivalEvents to calculate statistics.
* This process is split into a few stages,
* (i)At the start of each loop, get the first event from the PriorityQueue
* (ii)prints the profile of the event to signal that we start processing it
* (iii)current event creates the next event,
* with some information on the available servers as well as RandomGenerator
* in case a DoneEvent can be created from the current event.
* (iv) If applicable, Statistics are also updated after
* the creation of the new event, which will also be added to the PriorityQueue.
* (v) prints the statistics after the PriorityQueue is cleared.
*/
public void doService() {
while (events.size() > 0) {
Event firstEvent = getFirstEvent();
System.out.println(firstEvent);
Event newEvent = firstEvent.getNextEvent(servers,gen);
if (newEvent != null) {
newEvent.updateStatistics(statistics);
events.add(newEvent);
}
}
System.out.println(statistics);
}
/**
* Accesses an event as well as remove it from the PriorityQueue.
* @return the first event from the PriorityQueue,
* according to the Comparator object it was created with.
*/
public Event getFirstEvent() {
return events.poll();
}
}
</code></pre>
<p><strong>Server</strong></p>
<pre><code>package cs2030.simulator;
/**
* Server class that redirects the service of customers according to availability.
* The status of customer service is seen in terms of events that involves customers.
*/
class Server {
/**
* Counter integer that generates ServerID in a non-repetitive way.
*/
private static int counter = 1;
/**
* CustomerID that allows distinguishing between 2 servers.
*/
private int serverID;
/**
* the first event being resolved by the server.
*/
private Event served = null;
/**
* the second event being resolved by the server.
*/
private Event wait = null;
/**
* Creates a server.
*/
public Server() {
this.serverID = counter;
counter++;
}
public int getServerID() {
return this.serverID;
}
/**
* Causes the first slot inside the Server to be occupied.
* Or updates the service status of the customer in the first slot.
* @param newEvent the status of the customer being served
* in the form of an event.
*/
public void setServedEvent(Event newEvent) {
this.served = newEvent;
}
/**
* Causes the second slot inside the Server to be occupied.
* Or updates the service status of the customer in the second slot.
* @param newEvent the status of the customer being served
* in the form of an event.
*/
public void setWaitEvent(Event newEvent) {
this.wait = newEvent;
}
/**
* Checks whether the first slot inside the Server has been taken.
* @return true if first slot has not been taken, false otherwise.
*/
public boolean canTakeServedEvent() {
return (served == null && wait == null);
}
/**
* Checks whether the second slot inside the Server has been taken.
* @return true if the second slot has not been and the first slot is taken,
* false otherwise.
*/
public boolean canTakeWaitEvent() {
return (served != null && wait == null);
}
/**
* Clears up the 2nd slot of the server.
* This is done by removing up the 2nd customer to the 1st slot.
* and replace the 2nd slot with null status.
*/
public void flushDoneEvent() {
if (served != null) {
served = null;
}
if (wait != null) {
served = wait;
wait = null;
}
}
/**
* Gets the timestamp at which a customer waiting can expect to be served.
* @return earliest possible time at which waiting customer can be served
*/
public double getDoneTime() {
return this.served.getTime();
}
}
</code></pre>
<p><strong>Customer</strong></p>
<pre><code>package cs2030.simulator;
/**
* Customer class that holds customer information.
*/
public class Customer {
/**
* Counter integer that generates CustomerID in a non-repetitive way.
*/
private static int counter = 1;
/**
* CustomerID that allows distinguishing between 2 customers.
*/
private final int customerID;
/**
* Time when the customer first arrives.
*/
private final double time;
/**
* Creates Customer.
* @param time randomised arrival time of customer
*/
public Customer(double time) {
this.customerID = counter;
this.time = time;
counter++;
}
public int getCustomerID() {
return this.customerID;
}
public double getTime() {
return this.time;
}
}
</code></pre>
<p><strong>EventComparator</strong></p>
<pre><code>package cs2030.simulator;
import java.util.Comparator;
/**
* EventComparator class to create a comparison criteria for events.
*/
public class EventComparator implements Comparator<Event> {
/**
* Compares 2 Events and decides which is smaller, equal or greater.
* The first key is to check for the earliest time.
* If there is a tie breaker, customerID is checked instead,
* which also hints on the priority of different type of events.
* @param e1 left event
* @param e2 right event
* @return -1 if left event is prioritised over right event.
* 0 if there isn't a priority, which will not happen in this case.
* 1 if right event is prioritised over left event.
*/
public int compare(Event e1, Event e2) {
if (e1.getTime() < e2.getTime()) {
return -1;
} else if (e1.getTime() > e2.getTime()) {
return 1;
} else if (e1.getCustomerID() < e2.getCustomerID()) {
return -1;
} else if (e1.getCustomerID() > e2.getCustomerID()) {
return 1;
} else {
System.out.println("Bug with code, please check");
return 0;
}
}
}
</code></pre>
<p><strong>Statistics</strong></p>
<pre><code>package cs2030.simulator;
/**
* Statistics class to keep track of total waiting time of customers.
* the number of customers who left without being served.
* the number of customers who are served.
*/
class Statistics {
private double waitingTime = 0;
private int numLeft = 0;
private int numServed = 0;
/**
* Creates Statistics object using the empty constructor.
*/
public Statistics(){}
/**
* Increases the number of customers who are served.
*/
public void increaseServed() {
numServed++;
}
/**
* Increases waiting time of customers.
*/
public void increaseWaitingTime(double time) {
waitingTime += time;
}
/**
* Increases the number of customers who left without being served.
*/
public void increaseLeft() {
numLeft++;
}
/**
* Formats the Statistics to print all information gathered.
*/
public String toString() {
double x = waitingTime / numServed;
return '[' + String.format("%.3f",x) + ' ' +
numServed + ' ' + numLeft + ']';
}
}
</code></pre>
<p><strong>Event</strong></p>
<pre><code>package cs2030.simulator;
/**
* Abstract Event class to enforce polymorphism.
* Forces its subclasses to have the ability to create the next event
* and to update statistics.
*/
public abstract class Event {
/**
* Customer that the event is involving.
*/
private final Customer customer;
/**
* Time at which the event is created,
* which may differ from customer arrival time if
* it is only created when it is caused to wait by another preceeding event.
*/
private final double time;
/**
* Creates an Event.
* @param customer customer that the event is involving
* @param time time at which event is created
*/
public Event(Customer customer, double time) {
this.customer = customer;
this.time = time;
}
/**
* Creates the next event of parent type based on its original type.
*/
public abstract Event getNextEvent(Server [] servers,RandomGenerator gen);
/** Modifies information in statistics if required.
*/
public abstract void updateStatistics(Statistics statistics);
public Customer getCustomer() {
return this.customer;
}
public int getCustomerID() {
return this.customer.getCustomerID();
}
public double getTime() {
return this.time;
}
}
</code></pre>
<p><strong>ArrivalEvent</strong></p>
<pre><code>package cs2030.simulator;
/**
* ArrivalEvent class to simulate the act of a customer arriving.
*/
public class ArrivalEvent extends Event {
/**
* Creates an ArrivalEvent.
* @param customer customer that the event is involving.
* @param time time at which event is created.
*/
public ArrivalEvent(Customer customer, double time) {
super(customer, time);
}
/**
* Creates the next event based on the availability of servers.
* The available server will be updated to hold a field of the event
* and be involved in the creation of new event.
* @param servers Array of servers to be checked
* @param gen RandomGenerator, not used in this case.
* @return parent class Event, which could be in the form of
* LeaveEvent, if there are no available servers.
* ServedEvent, if there exists an available server that is completely free.
* WaitEvent, if there exists available server and there are no empty servers.
* null, which won't be reached as it's a Debugging statement.
*/
public Event getNextEvent(Server [] servers,RandomGenerator gen) {
Server freeServer = getFreeServer(servers);
if (freeServer == null) {
return createLeaveEvent();
} else if (freeServer.canTakeServedEvent()) {
ServedEvent newEvent = createServedEvent(freeServer);
freeServer.setServedEvent(newEvent);
return newEvent;
} else if (freeServer.canTakeWaitEvent()) {
WaitEvent newEvent = createWaitEvent(freeServer);
freeServer.setWaitEvent(newEvent);
return newEvent;
} else {
System.out.println("Bug in ArrivalEvents");
return null;
}
}
/**
* Creates a LeaveEvent not bounded to any server.
* @return LeaveEvent
*/
public LeaveEvent createLeaveEvent() {
return new LeaveEvent(this.getCustomer(),this.getTime());
}
/**
* Creates a ServedEvent bounded to an empty server.
* @param freeServer the server that is empty.
* @return ServedEvent.
*/
public ServedEvent createServedEvent(Server freeServer) {
return new ServedEvent(this.getCustomer(),this.getTime(),freeServer);
}
/**
* Creates a WaitEvent bounded to a partially occupied server.
* @param freeServer the server that is partially occupied.
* @return WaitEvent.
*/
public WaitEvent createWaitEvent(Server freeServer) {
return new WaitEvent(this.getCustomer(),this.getTime(),freeServer);
}
/**
* Modifies information in statistics if required.
* @param statistics Not used in this case.
*/
public void updateStatistics(Statistics statistics) {
return;
}
/**
* Finds the earliest available server based on search results.
* @param servers Array of servers to be checked.
* @return Server if an empty server or partially empty server is found
* null otherwise.
*/
public Server getFreeServer(Server[] servers) {
boolean hasFoundSlots = false;
Server choiceServer = null;
for (int i = 0; i < servers.length;i++) {
Server newServer = servers[i];
if (newServer.canTakeServedEvent()) {
return newServer;
} else if (newServer.canTakeWaitEvent() && !hasFoundSlots) {
choiceServer = newServer;
hasFoundSlots = true;
}
}
if (hasFoundSlots == false) {
return null;
} else {
return choiceServer;
}
}
/**
* Formats the ArrivalEvent to print out its profile.
*/
public String toString() {
return String.format("%.3f",this.getTime()) + ' ' +
this.getCustomerID() + " arrives";
}
}
</code></pre>
<p><strong>WaitEvent</strong></p>
<pre><code>package cs2030.simulator;
/**
* WaitEvent class to simulate the act of customer waiting.
* for another customer to be served by the same server.
*/
class WaitEvent extends Event {
/**
* Server that the WaitEvent belongs to.
*/
private Server server;
/**
* Creates an WaitEvent.
* @param customer customer that the event is involving
* @param time time at which event is created
* @param server server that the WaitEvent belongs to
*/
public WaitEvent(Customer customer, double time, Server server) {
super(customer,time);
this.server = server;
}
/**
* Creates a ServedEvent to signal that the current customer can now be served.
* Timestamp the current customer is being served is taken from the server.
* @param servers Array of servers to be checked, not used in this case
* @param gen RandomGenerator, not used in this case
* @return ServedEvent
*/
public ServedEvent getNextEvent(Server [] servers,RandomGenerator gen) {
if (!this.server.canTakeWaitEvent()) {
ServedEvent newEvent = new ServedEvent(this.getCustomer(),
this.server.getDoneTime(), this.server);
this.server.setWaitEvent(newEvent);
return newEvent;
}
return null;
}
/**
* Modifies information in statistics if required.
* @param statistics Not used in this case
*/
public void updateStatistics(Statistics statistics) {
return;
}
/**
* Formats the WaitEvent to print out its profile.
*/
public String toString() {
return (String.format("%.3f",this.getTime()) +
' ' + this.getCustomerID() + " waits to be served by " +
server.getServerID());
}
}
</code></pre>
<p><strong>ServedEvent</strong></p>
<pre><code>package cs2030.simulator;
/**
* ServedEvent class to simulate the start of service to a customer by a server.
*/
class ServedEvent extends Event {
/**
* Server that the ServedEvent belongs to.
*/
private Server server;
/**
* Creates an ServedEvent.
* @param customer customer that the event is involving
* @param time time at which event is created
* @param server server that the ServedEvent belongs to
*/
public ServedEvent(Customer customer, double time, Server server) {
super(customer,time);
this.server = server;
}
/**
* Creates a DoneEvent to signal that the service has been completed.
* Time taken to complete the service is randomised by RandomGenerator.
* DoneEvent is created at the new timestamp of current time of ServedEvent
* added to the randomised service time.
* @param servers Array of servers to be checked, not used in this case
* @param gen RandomGenerator, to randomise service time
* @return DoneEvent
*/
public DoneEvent getNextEvent(Server [] servers,RandomGenerator gen) {
double x = gen.genServiceTime();
DoneEvent newEvent = new DoneEvent(this.getCustomer(),
this.getTime() + x,this.server);
this.server.setServedEvent(newEvent);
return newEvent;
}
/**
* Increases the customer served count in statistics.
* and increase the waiting time by the customer if any
* @param statistics statistics to be updated
*/
public void updateStatistics(Statistics statistics) {
statistics.increaseServed();
statistics.increaseWaitingTime(this.getTime() - this.getCustomer().getTime());
}
/**
* Formats the ServedEvent to print out its profile.
*/
public String toString() {
return (String.format("%.3f",this.getTime()) + ' ' +
this.getCustomerID() + " served by " + server.getServerID());
}
}
</code></pre>
<p><strong>DoneEvent</strong></p>
<pre><code>package cs2030.simulator;
/**
* DoneEvent class to simulate the completion of service to a customer by a server.
*/
class DoneEvent extends Event {
/**
* Server that the DoneEvent belongs to.
*/
private Server server;
/**
* Creates an DoneEvent.
* @param customer customer that the event is involving.
* @param time time at which event is created.
* @param server server that the DoneEvent belongs to.
*/
public DoneEvent(Customer customer, double time, Server server) {
super(customer,time);
this.server = server;
}
/**
* Creates a null object to signal no actual Event type is created.
* Server is being updated with the service time the
* next event should adhere to if any.
* @param servers Array of servers, not used in this case.
* @param gen RandomGenerator, not used in this case.
* @return null object.
*/
public Event getNextEvent(Server [] servers,RandomGenerator gen) {
this.server.flushDoneEvent();
return null;
}
/**
* Modifies information in statistics if required.
* @param statistics Not used in this case
*/
public void updateStatistics(Statistics statistics) {
return;
}
/**
* Formats the DoneEvent to print out its profile.
*/
public String toString() {
return String.format("%.3f",this.getTime()) +
' ' + this.getCustomerID() + " done serving by " +
server.getServerID();
}
}
</code></pre>
<p><strong>LeaveEvent</strong></p>
<pre><code>package cs2030.simulator;
/**
* LeaveEvent class to simulate the act of customer leaving without being served.
*/
class LeaveEvent extends Event {
private Server server;
/**
* Creates an LeaveEvent.
* @param customer customer that the event is involving.
* @param time time at which event is created.
*/
public LeaveEvent(Customer customer, double time) {
super(customer,time);
}
/**
* Creates a null object to signal no actual Event type is created.
* @param servers Array of servers, not used in this case
* @param gen RandomGenerator, not used in this case
* @return null object
*/
public Event getNextEvent(Server [] servers, RandomGenerator gen) {
return null;
}
/**
* Increases the customer leave count inside statistics.
* @param statistics statistics to be updated
*/
public void updateStatistics(Statistics statistics) {
statistics.increaseLeft();
}
/**
* Formats the LeaveEvent to print out its profile.
*/
public String toString() {
return String.format("%.3f",this.getTime()) +
' ' + this.getCustomerID() + " leaves";
}
}
</code></pre>
<p><strong>Test case: Input and Output style</strong></p>
<pre class="lang-none prettyprint-override"><code>1
1
5
1.0
1.0
0.000 1 arrives
0.000 1 served by 1
0.313 1 done serving by 1
0.314 2 arrives
0.314 2 served by 1
0.417 2 done serving by 1
1.205 3 arrives
1.205 3 served by 1
1.904 3 done serving by 1
2.776 4 arrives
2.776 4 served by 1
2.791 4 done serving by 1
3.877 5 arrives
3.877 5 served by 1
4.031 5 done serving by 1
[0.000 5 0]
1
2
10
1.0
1.0
0.000 1 arrives
0.000 1 served by 1
0.313 1 done serving by 1
0.314 2 arrives
0.314 2 served by 1
0.417 2 done serving by 1
1.205 3 arrives
1.205 3 served by 1
1.904 3 done serving by 1
2.776 4 arrives
2.776 4 served by 1
2.791 4 done serving by 1
3.877 5 arrives
3.877 5 served by 1
3.910 6 arrives
3.910 6 served by 2
3.922 6 done serving by 2
4.031 5 done serving by 1
9.006 7 arrives
9.006 7 served by 1
9.043 8 arrives
9.043 8 served by 2
9.105 9 arrives
9.105 9 waits to be served by 1
9.160 10 arrives
9.160 10 waits to be served by 2
10.484 7 done serving by 1
10.484 9 served by 1
10.781 9 done serving by 1
11.636 8 done serving by 2
11.636 10 served by 2
11.688 10 done serving by 2
[0.386 10 0]
</code></pre>
<p>Is there any improvement that I can make on my code? Some areas I can think of:</p>
<ul>
<li>Coding style</li>
<li>Naming conventions</li>
<li>Design of proper interactions between objects (like what is passed as arguments and what is called)</li>
<li>OOP design principles</li>
<li>Any small recommendations on syntax/implementation of class methods/libraries to make my life slightly easier</li>
</ul>
<p>In particular for the 3rd point, I have two dilemma(s):</p>
<ol>
<li><p>About the link between class responsibilities and what is the best way of invoking a method call between different objects in different scopes.</p>
<p><code>EventManager</code> is deemed to be in charge of holding a <code>Statistics</code> field, and holding a <code>PriorityQueue</code> of <code>Events</code>, since it's the Manager. In my implementation I could have written one of the following:</p>
<p>A: <code>newEvent.updateStatistics(statistics)</code></p>
<p>B: <code>statistics.updateStatistics(newEvent)</code></p>
<p>In A, to make a method for the Event class, feels easier and more accessible in terms of code length. Each subclass of Event will have their own version of updating the statistics and hence avoid some dispatching on type of the different classes, which I believe is the principle of OOP if I'm not wrong on this.</p>
<p>On the other hand, in B feels like its more fulfilling to responsibility. The object <code>newEvent</code> is the provider of the information, hence should be placed in the arguments.</p>
<p>I chose A in the end as during the time I found B logical, I realised I have to do ugly dispatching and I am tempted to pass back statistics as arguments to Events, in the form of <code>newEvent.f(this)</code>, in Statistics method <code>updateStatistics</code>. This just defeats my purpose of sending <code>Event</code>s in as arguments from the start. What is your view on this dilemma of responsibility design vs the ease of coding to the programmer?</p></li>
<li><p>I was kind of forced to put a property of <code>Server</code> into <code>Event</code> so that events could print the profile easily, but I was also forced to put a property of <code>Event</code> into <code>Server</code>, as I find that it would save me a lot of work to communicate to the <code>WaitEvent</code> in Server of what time to switch to when becoming a <code>ServedEvent</code>. Is this a form of cyclical dependency(a bad practice), and if it is, is it justifiable to do so?</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T07:55:58.667",
"Id": "393654",
"Score": "0",
"body": "It's very good that you've posted all you code but could you describe it a little bit more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T03:07:... | [
{
"body": "<p>please close the scanner after finishing using it just for saving the memory like this :</p>\n<pre><code>import java.util.Scanner;\nimport cs2030.`enter code here`simulator.Event;\nimport cs2030.simulator.Customer;\nimport cs2030.simulator.EventComparator;\nimport cs2030.simulator.EventManager;\ni... | {
"AcceptedAnswerId": "215457",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T06:13:38.410",
"Id": "204175",
"Score": "7",
"Tags": [
"java",
"object-oriented",
"simulation"
],
"Title": "Discrete Event Simulator"
} | 204175 |
<p>I load an array from an API that is available throughout the user's whole session. This data is unlikely to change, so it can be cached safely. I have a <code>DataService</code> that works like this:</p>
<ul>
<li>get <code>data</code> from the class property (<em>scenario: going to a new route</em>)</li>
<li>if nothing is there, get <code>data</code> from local storage (<em>scenario: reload</em>)</li>
<li>if nothing is there, fetch <code>data</code> from API (<em>scenario: new session</em>)</li>
</ul>
<p>This is what I've come up with:</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class DataService {
protected data: Array<any> = null;
constructor(private http: HttpClient) { }
public getData(): Observable<Array<any>> {
if (this.data === null) {
this.data = JSON.parse(localStorage.getItem('data'));
}
if (this.datas !== null) {
return of(this.data);
}
return this.http.get<Object>(this.url + this.route).pipe(
retry(3),
map(response => {
this.data = response as Array<any>;
localStorage.setItem('data', JSON.stringify(this.data));
return this.data;
}),
catchError(error => {
this.handleError(error);
return [];
})
);
}
</code></pre>
<p>The service is registered in the <code>app.component.ts</code> and used like this in other components:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/service/data.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.less'],
providers: []
})
export class ExampleComponent implements OnInit {
protected subscribers: Subscription[] = [];
public data: Array<any> = [];
constructor(public data: DataService) { }
ngOnInit() {
this.subscribers.push(
this.data.getData().subscribe((data) => { this.data = data })
);
}
ngOnDestroy() {
for (let subscriber of this.subscribers) {
subscriber.unsubscribe();
}
}
}
</code></pre>
<p>Is it a good approach? Is this "<em>the Angular way</em>"? Can it be improved? Is it readable? Does this indeed increase performance? At least it uses fewer HTTP requests.</p>
<p><sup>This class is shortened a bit for the review, so don't worry that there's no <code>handleError</code> method.</sup></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T18:34:42.727",
"Id": "393901",
"Score": "1",
"body": "_This class is shortened a bit for the review_ - I hope you have a good reason for doing this because we usually don't like shortened code ;-]"
},
{
"ContentLicense": "CC... | [
{
"body": "<p>If you have configured caching headers (both on request and response) correctly, the browser will do caching for you. You can have your code just do the request and the browser will decide whether to pull data from the server or use a cached response. You may need to look up on what your library (... | {
"AcceptedAnswerId": "204350",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T08:19:06.740",
"Id": "204177",
"Score": "2",
"Tags": [
"javascript",
"cache",
"typescript",
"angular-2+",
"browser-storage"
],
"Title": "DataService that fetches data not loaded already or loads cached values"
} | 204177 |
<p>I've made this implementation of a classroom with teacher and students using mediator pattern. Mediator is the teacher and colleague are studends.</p>
<p>Main function is the following. Main function creates a teacher and then she says will teach to some students. Finally, she try to spread a concept and a student will tell what he (or she) have learned.</p>
<pre><code>func NewClassMate(name string) Student {
return &ClassMate{name, "meeting 1", ""}
}
func main() {
teacher := Teacher{}
student := NewClassMate("Mario")
teacher.TeachesTo(student)
teacher.TeachesTo(NewClassMate("Demo"))
teacher.TeachesTo(NewClassMate("Mattia"))
teacher.TeachesTo(NewClassMate("Simone"))
fmt.Println(len(teacher.attendees))
fmt.Println(student.Forum())
teacher.Spread("Message sent to everyone")
fmt.Println(student.Learned())
}
</code></pre>
<h2>Teacher</h2>
<p>Teacher implementation is trivial. Teacher knows all students and spread lessons.</p>
<pre><code>type Teacher struct {
students []Student
}
func (m *Teacher) TeachesTo(c Student) {
m.students = append(m.students, c)
}
func (m *Teacher) Spread(message string) {
for _, a := range m.students {
a.Learn(message)
}
}
</code></pre>
<h2>Student</h2>
<p>Also student is very simple. It take part in a class, learns and say what he have learned.</p>
<pre><code>type ClassMate struct {
lastMessage string
forum string
}
func (a *ClassMate) Class() string {
return a.forum
}
func (a *ClassMate) Learn(message string) {
a.lastMessage = message
}
func (a *ClassMate) Learned() string {
return a.lastMessage
}
</code></pre>
<h2>Mediator and Colleagues</h2>
<p>Finally here we can see interface I chosenm according to the pattern.</p>
<pre><code>type Student interface {
Class() string
Learn(message string)
Learned() string
}
type Mediator interface {
TeachesTo(c *Student)
Spread(messqger string)
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T10:21:13.110",
"Id": "393662",
"Score": "0",
"body": "\"Is this a valid implementation\" Did you test it? Did it work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T10:25:48.823",
"Id": "393663"... | [
{
"body": "<p>Ok, let's start from the top: Is this a mediator pattern?</p>\n\n<p>I'd argue what you have is 2 components of a mediator pattern (2 objects that interact) <em>without</em> an actual mediator. To just quote the first line of the wiki entry for the mediator pattern:</p>\n\n<blockquote>\n <p>In sof... | {
"AcceptedAnswerId": "204237",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T10:07:12.123",
"Id": "204179",
"Score": "0",
"Tags": [
"go",
"mediator"
],
"Title": "Modeling a classroom with teacher and students using the mediator pattern in Go"
} | 204179 |
<p>I tried to implement a stack using Linked Lists. How could I make it more efficient? Any other suggestions will be greatly appreciated. I am a beginner C programmer.</p>
<p>Any other tips to clean up my code? </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
typedef struct NODE {
int data;
struct NODE* next;
}node;
node* top = NULL;
// Push Function
void push(int x)
{
node *temp;
temp = (node *) malloc(sizeof(node));
temp -> data = x;
temp -> next = top;
top = temp;
}
// Pop function
int pop()
{
node* temp;
int num=0;
temp = top;
num = temp -> data;
top = top -> next;
free(temp);
return num;
}
int Top()
{
return top -> data;
}
void display(node *head)
{
if(head == NULL) printf("NULL!\n");
else
{
printf("%d\n", head -> data);
display(head->next);
}
}
int main() {
int element,choice,val,tp;
do
{
printf("---Stack Operations---\n");
printf("1.PUSH\n");
printf("2.POP\n");
printf("3.DISPLAY\n");
printf("4.Top element\n");
printf("5.EXIT\n");
printf("Enter an option\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the element to push\n");
scanf("%d",&val);
push(val);
break;
case 2:
element = pop();
printf("Popped element is: %d\n",element);
break;
case 3:
display(top);
break;
case 4:
tp = Top();
printf("Top element is:%d\n",tp);
break;
case 5:
exit(0);
default:
printf("Enter a valid option\n");
}
}while(choice != 5);
}
</code></pre>
| [] | [
{
"body": "<h2>Consider alternatives to linked lists</h2>\n\n<p>You are wondering whether this is the most efficient way to implement a stack. If you store <code>int</code>s, then the overhead of maintaining a linked list is quite large. Another option would be to keep the integer values in a dynamically alloca... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T12:03:04.020",
"Id": "204181",
"Score": "4",
"Tags": [
"beginner",
"c",
"linked-list"
],
"Title": "Stacks using Linked Lists in C"
} | 204181 |
<p>I have just started learning Rust, and in order to try to get the hang of references, ownership and mutability, I have attempted to make a doubly linked list. It now compiles, and the <code>add</code> function seems to be working as intended.</p>
<p>There is one implementation detail that I am curious about, and in general I'm wondering whether my code violates any good practice. Also, related to this, have I painted myself into any kind of corner if I want to extend this code? (Making <code>add()</code> keep the list ordered, using generics, implementing <code>Iterator</code>, and so on.)</p>
<pre><code>use std::rc::{Rc, Weak};
use std::cell::RefCell;
#[derive(Debug)]
struct Node {
value: i32,
next: RefCell<Option<Rc<Node>>>,
prev: RefCell<Weak<Node>>,
}
impl Node {
pub fn add(&self, this: &Rc<Node>, i: i32) {
if let Some(ref r) = *self.next.borrow() {
r.add(r, i);
return;
};
*self.next.borrow_mut() = Some(Rc::new(Node {
value: i,
next: RefCell::new(None),
prev: RefCell::new(Rc::downgrade(&this)),
}));
}
}
#[derive(Debug)]
struct List {
head: RefCell<Option<Rc<Node>>>,
}
impl List {
pub fn add(&self, i: i32) {
if let Some(ref r) = *self.head.borrow() {
r.add(r, i);
return;
};
*self.head.borrow_mut() = Some(Rc::new(Node {
value: i,
next: RefCell::new(None),
prev: RefCell::new(Weak::new()),
}));
}
}
fn main() {
let list = List {
head: RefCell::new(None),
};
println!("{:?}", list);
list.add(1);
list.add(2);
println!("{:?}", list);
}
</code></pre>
<p>The detail I'm curious about is whether the <code>if let</code> parts can be done with a <code>match</code>. Or, more specifically, can it be done without the extra <code>return</code> call. No matter what I tried (both <code>match</code> and <code>if let</code> with <code>else</code>), the <code>borrow()</code> got in the way of the <code>borrow_mut()</code> in the <code>None</code> arm, and I couldn't get the pattern matching to work without the <code>borrow()</code>.</p>
| [] | [
{
"body": "<p>Before looking at your code, I want to give a general notice: don't use linked lists. They are almost always the wrong choice of data structure. They are useful primarily pedagogically. </p>\n\n<p>Furthermore, I should warn you that implementing a doubly-linked list will not look like typical Rust... | {
"AcceptedAnswerId": "204255",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T12:36:21.533",
"Id": "204183",
"Score": "4",
"Tags": [
"linked-list",
"rust"
],
"Title": "Doubly linked list in Rust"
} | 204183 |
<p>I started learning Python and I am preparing Sudoku Solver as my first small project. I am also trying to learn unit testing. I thought it is a good idea to ask for suggestions before I start with GUI. I would appreciate any help.</p>
<p>There are several classes:</p>
<ul>
<li><code>Cell</code> - one cell of sudoku board.</li>
<li><code>Region</code> - holds several cells (normally 9) that should have unique values. It can be row, column or rectangle.</li>
<li><code>UndoRedo</code> - contains lists of actions performed on Sudoku.</li>
<li><code>Sudoku</code> - contains cells, regions and UndoRedo</li>
<li><code>SudokuSolver</code> - class solving Sudoku by applying patterns.</li>
<li><code>Pattern</code> - Base class for patterns.</li>
<li><code>OnePossibility</code>, <code>Exclusion</code>, <code>BruteForce</code> - patterns for solving Sudoku.</li>
<li><code>SudokuFactory</code> - Factory creating Sudoku.</li>
</ul>
<p>I have doubts about the following issue: There is a <code>Sudoku</code> class that contains <code>Cell</code>s (normally 9x9 board). In Cell class I added static value <code>MAX_VALUE = 9</code>. It helps me check if value written to the Cell is in a correct range (and raise errors). But when I create Sudoku with different size I am modifying the <code>MAX_VALUE</code>. It works fine. If I operate only on one Sudoku it works fine and it might be enough for my project. But isn't it better to do it another way? For example changing <code>MAX_VALUE</code> not to be static, but written in <code>self.__init__</code>? Or is it better to move <code>MAX_VALUE</code> to Sudoku class? But what about checking values? Would it be better to move it to Sudoku class?</p>
<p><strong>sudoku.py:</strong></p>
<pre><code>import copy
from typing import List, Set, Tuple
class Cell(object):
"""Basic class to store data of one cell.
Attributes:
_row (int): Row parameter of a cell.
_column (int): Column parameter of a cell.
_editable (bool): Defines if object's value can be edited or is permanent.
_value (int): Value of the cell between 0 (empty) and MAX_VALUE.
_possible_values (set[int]): A set of values that are possible to write to the cell.
"""
MAX_VALUE = 9 # TODO rethink if it should be class static
def __init__(self, row: int, column: int, editable=True, value=0):
"""Initiate a cell. Write arguments to instance attributes and create a set of possible values. Populate the set
with values from range <1, MAX_VALUE> if the cell is editable.
Args:
row (int): Row parameter of a cell.
column (int): Column parameter of a cell.
editable (bool): Defines if object's value can be edited or is permanent. Defaults to True.
value (int): Value of the cell between 0 (empty) and MAX_VALUE. Defaults to 0.
Raises:
AttributeError: Raise if:
- editable is False and value is 0, or
- value is not in a range <0, MAX_VALUE>, or
- row or column is not in a range <0, MAX_VALUE).
"""
if editable is False and value == 0:
raise AttributeError("Cell not editable and without value")
elif value < 0 or value > self.MAX_VALUE:
raise AttributeError("Incorrect value ({} not in <0,{}>)".format(value, self.MAX_VALUE))
elif not(0 <= row < self.MAX_VALUE) or not(0 <= column < self.MAX_VALUE):
raise AttributeError("Incorrect row or column ({},{} not in <0,{}>".format(row, column, self.MAX_VALUE))
self._editable = editable
self._value = value
self._row = row
self._column = column
if editable:
self._possible_values = set(range(1, self.MAX_VALUE + 1))
else:
self._possible_values = set()
@property
def row(self) -> int:
"""Return row as integer. Row should be in a range <0, MAX_VALUE-1>."""
return self._row
@property
def column(self) -> int:
"""Return column as integer. Column should be in a range <0, MAX_VALUE-1>."""
return self._column
@property
def editable(self) -> bool:
"""Return bool value if cell is editable."""
return self._editable
@property
def possible_values(self) -> Set[int]:
"""Return a set of cell's possible values."""
return self._possible_values
@property
def value(self) -> int:
"""Cell's value as integer.
Write value if a cell is editable and the value is in a correct range (<0, MAX_VALUE>).
Clear a set of possible values if value is not 0.
Raises:
Attribute Error: Raise if:
- editable attribute is False
- value is not in a range <0, MAX_VALUE>
"""
return self._value
@value.setter
def value(self, value: int):
if self._editable is False:
raise AttributeError("Cell not editable")
elif value < 0 or value > self.MAX_VALUE:
raise AttributeError("Incorrect value ({} not in <0,{}>)".format(value, self.MAX_VALUE))
elif value == 0:
self._value = value
else:
self._value = value
self._possible_values.clear()
def init_possible_values(self):
"""Fill the set of possible values with full range <1, MAX_VALUE>."""
self._possible_values = set(range(1, 1+self.MAX_VALUE))
def intersect_possible_values(self, values: set):
"""Intersect cell's possible values with given set (i.e. set of possible values from region)
Args:
values (set[int]): Set to intersect with instance's possible values.
"""
self._possible_values = self._possible_values.intersection(values)
def clear(self):
"""Clear the cell's value if the cell is editable"""
if self.editable:
self.value = 0
def remove_possible_value(self, value: int):
"""Remove possible value from a set (if present)
Args:
value (int): Remove value from possible values set.
"""
if value in self._possible_values:
self._possible_values.remove(value)
def to_string(self) -> str:
"""Print cell's attributes for diagnostic purpose.
Returns:
str: Diagnostic string.
"""
return "[{0._row},{0._column}]: editable: {0._editable}: {0._value} / {0._possible_values}".format(self)
class Region(object):
"""Class holding a list of cells that have to have unique values. It might be:
- row,
- column,
- rectangle.
Attributes:
_cells[Cell]: A list of objects of type Cell.
"""
def __init__(self):
self._cells = []
@property
def cells(self):
"""List of cells in a region"""
return self._cells
def add(self, cell: Cell):
"""Add a cell to a list of cells if the list does not contain it.
Args:
cell (Cell): Cell to be added to the list.
"""
if cell not in self._cells:
self._cells.append(cell)
def remove_possible_value_if_cell_is_in_region(self, cell: Cell, value: int):
"""Remove value from cell's possible values if the cell is in region.
Args:
cell (Cell): Cell instance to check if it is in a region and to remove possible value from.
value (int): Possible value.
"""
if cell in self._cells:
for cell in self._cells:
cell.remove_possible_value(value)
def update_possible_values(self):
"""Update possible values in all cells that the region contains.
Create a set of possible values in a range <1, number of cells in a region>. Go through all cells and read their
values. Remove read values from prepared set. Go through each cell and intersect cell's possible values with
the set.
Each cell belongs to 3 regions (row, column, rectangle), so its possible values should be intersected 3 times
(by calling 'update_possible_values' method for all regions.
"""
values = set(range(1, 1+len(self._cells)))
for cell in self._cells:
v = cell.value
if v in values:
values.remove(v)
for cell in self._cells:
if cell.value == 0:
cell.intersect_possible_values(values)
def is_solved(self) -> bool:
"""Check if the region is solved.
The region is solved if all cells have non-zero value, and all possible values from range
<1, number of cells in a region> are used.
Returns:
bool: True if the region is solved. False otherwise.
"""
values = set()
for cell in self._cells:
values.add(cell.value)
expected_values = set(range(1, len(self._cells)+1))
return values == expected_values
def is_not_possible_to_solve(self):
"""Check if a region is not possible to solve in a current configuration.
Returns:
bool: True if there is a cell with no value (zero) and it has zero possible values or if there are at least
two cells with the same value.
"""
a_set = set()
for cell in self._cells:
if cell.value == 0 and len(cell.possible_values) == 0:
return True
elif cell.value in a_set:
return True
elif cell.value != 0:
a_set.add(cell.value)
return False
class UndoRedo(object):
"""
Class storing actions of setting values to Sudoku's cells in order to perform 'undo' and 'redo' actions.
Attributes:
_undo (List[ Tuple[int, int, int, str] ]): Performed actions as list of tuples with row, column, value
and method.
_redo (List[ Tuple[int, int, int, str] ]): Actions after 'undo' operation are moved to 'redo' list.
"""
def __init__(self):
self._undo = []
self._redo = []
def add_action(self, row: int, column: int, old_value: int, value: int, method: str = ''):
"""Store data of action performed on a cell. When new data is inserted, 'redo' list is cleared.
Args:
row (int): Cell's row parameter.
column (int): Cell's column parameter.
old_value (int): Cell's value before writing a new value.
value (int): Value written to the cell.
method (str): Name of the method writing value (optional). Defaults to ''.
"""
self._undo.append((row, column, old_value, value, method))
self._redo.clear()
def undo_length(self):
"""Return length of undo list."""
return len(self._undo)
def redo_length(self):
"""Return length of redo list."""
return len(self._redo)
def undo(self) -> Tuple[int, int, int, int, str, int, int]:
"""Get last action performed on Sudoku as: row, column, value before writing, value written, method, number of
remaining actions in undo list and number of actions in redo list. Returned action is also written to redo list.
It means that updating Cell's value with returned data should be performed without calling add_action function,
because it clears redo list.
Returns:
Tuple[int, int, int, int, str, int, int]: row, column, old_value, value, method, length_of_undo_list,
length_of_redo_list.
"""
last_action = self._undo.pop()
self._redo.append(last_action)
return (*last_action), len(self._undo), len(self._redo)
def redo(self):
"""Get undone action. Returned action is also written to undo list. If you want to write value to a cell, do not
call add_action function, because it clears redo list and adds action to undo list (you would get two the same
actions in a row).
Returns:
Tuple[int, int, int, int, str, int, int]: row, column, old_value, value, method, length_of_undo_list,
length_of_redo_list.
"""
redo_action = self._redo.pop()
self._undo.append(redo_action)
return (*redo_action), len(self._undo), len(self._redo)
class Sudoku(object):
"""Class that contains Sudoku board - two dimensional array of cells.
Attributes:
cells (List[List[Cell]]): List of cells in Sudoku.
_size (int): size of the Sudoku.
_rect_width (int): Width of each rectangle region (3 for Sudoku 9x9).
_rect_height (int): Height of each rectangle region (3 for Sudoku 9x9).
_undo_redo (UndoRedo): Container storing actions done on Sudoku.
__regions (List[Region]): List of regions (rows, columns, rectangles).
"""
def __init__(self, size=9, cells=None, rect_width=3, rect_height=3):
if cells is None:
self.cells = [[Cell(r, c) for c in range(size)] for r in range(size)]
self._size = size
else:
self.cells = cells
self._size = len(cells)
self._undo_redo = UndoRedo()
self._rect_width = rect_width
self._rect_height = rect_height
rows = columns = self._size
rectangles = (self._size ** 2) // (self._rect_width * self._rect_height) # number of rectangles = board size / rect_size
self._regions = [Region() for x in range(rows + columns + rectangles)] # generate regions for rows, cols, rects
for row in range(self._size):
for col in range(self._size):
self._regions[row].add(self.cells[row][col]) # populate row regions
self._regions[rows+col].add(self.cells[row][col]) # populate column regions
# populate rectangle regions
width_size = self._size // self._rect_width
height_size = self._size // self._rect_height
reg = self._size * 2 - 1
for x_start in range(height_size):
for y_start in range(width_size):
reg += 1
for x in range(x_start * width_size, (x_start+1) * width_size):
for y in range((y_start * height_size), (y_start+1) * height_size):
self._regions[reg].add(self.cells[x][y])
self.update_possible_values_in_all_regions()
@property
def size(self) -> int:
"""Sudoku board size (number of cells per row / column / rectangle)."""
return self._size
@property
def regions(self) -> List[Region]:
"""List of regions."""
return self._regions
def _is_row_and_column_in_range(self, row: int, column: int) -> bool:
"""Check if row and integer are in range <0, size-1>.
Args:
row (int): A row number (<0, size-1>).
column (int): A column number (<0, size-1>).
Returns:
True if a row and column are in the correct range.
Raises:
AttributeError: Raise if row or column is outside <0, size-1> range.
"""
if (0 <= row < self.size) and (0 <= column < self.size):
return True
else:
raise AttributeError("Row or column out of range: <0,{}>, ({},{})".format(self.size - 1, row, column))
def get_cell_value(self, row: int, column: int) -> int:
"""Return a value of a cell.
Args:
row (int): A row number.
column (int): A column number.
Returns:
Value of a cell placed in [row, column].
"""
if self._is_row_and_column_in_range(row, column):
return self.cells[row][column].value
def set_cell_value(self, row: int, column: int, value: int, method: str = ''):
"""Set a value of a cell. Remove the value from possible values of ranges that the cell belongs to (row, column,
rectangle). Add action to _undo_redo.
Args:
row (int): A row number (<0, size-1>).
column (int): A column number (<0, size-1>).
value (int): Value to write to a cell.
method (str): Optional method identifier. Defaults to ''.
Raises:
Attribute Error: Raise if:
- editable attribute is False
- value is not in a range <0, MAX_VALUE>
"""
if self._is_row_and_column_in_range(row, column):
cell = self.cells[row][column]
old_value = cell.value
cell.value = value
self._remove_possible_value(cell, value)
self._undo_redo.add_action(row, column, old_value, value, method)
def _remove_possible_value(self, cell: Cell, value: int):
"""Remove value from cells' possible values in the same region as given cell (row, column, rectangle).
Args:
cell (Cell): Cell object.
value (int): Value to remove from possible values.
"""
for region in self._regions:
region.remove_possible_value_if_cell_is_in_region(cell, value)
def get_cell_possibilities(self, row: int, column: int) -> Set[int]:
"""Return a set of possible values that can be written to the cell from given row and column.
Args:
row (int): A row number (<0, size-1>).
column (int): A column number (<0, size-1>).
Returns:
Set[int]: Possible values that can be written to the cell.
"""
if self._is_row_and_column_in_range(row, column):
return self.cells[row][column].possible_values
def is_editable(self, row: int, column: int) -> bool:
"""Check if a cell from given row and column is editable.
Args:
row: A row number (<0, size-1>).
column: A column number (<0, size-1>).
Returns:
bool: True if the cell is editable.
"""
if self._is_row_and_column_in_range:
return self.cells[row][column].editable
def update_possible_values_in_all_regions(self):
"""Update (refresh) possible values in all regions (meaning all cells).
Use the function after modifying cell's value, clearing its value or undoing action.
"""
for region in self._regions:
region.update_possible_values()
def is_solved(self) -> bool:
"""Check if Sudoku is solved.
Returns:
True if Sudoku is solved correctly. False otherwise.
"""
for region in self._regions:
if not region.is_solved():
return False
return True
def is_wrong(self) -> bool:
"""Check if Sudoku is not possible to solve.
Sudoku is not possible to solve if there is a region (row, column, rectangle) containing a cell with no value
(zero) and zero possible values to write or if there are at least two cells with the same value.
Returns:
True if there is a region with no solution.
"""
for region in self._regions:
if region.is_not_possible_to_solve():
return True
return False
def to_string(self) -> str:
"""Print Sudoku for diagnostic purpose.
Returns:
str: Diagnostic string.
"""
sudoku = ""
for row in self.cells:
for cell in row:
sudoku += str(cell.value)
sudoku += "\n"
return sudoku
def copy_from(self, sudoku: 'Sudoku'):
"""Copy data from given argument 'sudoku' to current instance by repeating actions of sudoku's undo list.
Args:
sudoku (Sudoku): Sudoku instance to copy actions from.
"""
for i in range(self._undo_redo.undo_length(), sudoku._undo_redo.undo_length()):
row, column, old_value, value, method = sudoku._undo_redo._undo[i]
self.set_cell_value(row, column, value, method)
class SudokuSolver(object):
"""Class holding sudoku board and solving it.
Attributes:
sudoku (Sudoku): Sudoku board.
patterns (Pattern): List of patterns for solving sudoku board.
"""
def __init__(self, sudoku: Sudoku = None):
"""Initiate a SudokuSolver with sudoku.
Args:
sudoku (Sudoku): Initiated sudoku object.
"""
self.sudoku = sudoku
self.patterns = Pattern.get_patterns_without_brute_force()
def solve(self) -> bool:
"""Solve sudoku using patterns. If typical patterns do not solve sudoku, use Brute Force.
Returns:
bool: True if sudoku is solved. Otherwise sudoku is wrong.
"""
restart = True
while restart:
restart = False
for pattern in self.patterns:
solve_again = pattern.solve(self.sudoku, False)
if self.sudoku.is_solved():
restart = False
break
elif solve_again:
restart = True
# If not solved by means of typical patterns - use Brute Force.
if not self.sudoku.is_solved():
pattern = BruteForce()
pattern.solve(self.sudoku, False)
return self.sudoku.is_solved()
def to_string(self) -> str:
"""Print Sudoku for diagnostic purpose.
Returns:
str: Diagnostic string.
"""
return self.sudoku.to_string()
class Pattern(object):
def solve(self, sudoku: Sudoku, solve_one: bool = False) -> bool:
"""Solve sudoku with a implemented pattern and return True if any Cell was changed. If not, return false.
Args:
sudoku (Sudoku): Sudoku class to which apply solution algorithm.
solve_one (bool): If True, finish solving after modifying one Cell. Defaults to False.
Returns:
bool: Value determining if any Cell was modified. False means that algorithm is no longer able to find
solution to any Cell.
"""
return False
def name(self) -> str:
"""Return a name of the pattern.
Returns:
str: Name of the pattern.
"""
return self.__class__.__name__
@staticmethod
def get_patterns_without_brute_force() -> List['Pattern']:
"""Get a list of all patterns except Brute Force.
Returns:
List[Pattern]: A list of Pattern objects.
"""
return [OnePossibility(), Exclusion()]
@staticmethod
def get_patterns_with_brute_force() -> List['Pattern']:
"""Get a list off all patterns (including Brute Force).
Returns:
List[Pattern]: A list of Pattern objects.
"""
return [*Pattern.get_patterns_without_brute_force(), BruteForce()]
class OnePossibility(Pattern):
"""A class solving sudoku by One Possibility pattern. Extends Pattern class.
The pattern looks for cells with only one possible value and writes it to the cell.
"""
def solve(self, sudoku: Sudoku, solve_one: bool = False) -> bool:
"""Solve sudoku with OnePossibility pattern.
The pattern goes through all the cells in sudoku and checks if there is only one possible value to write. If it
is True then function writes that value to a cell. It checks following cells until the end unless argument
solve_one is True. In this situation it finishes operating on sudoku after first write.
Args:
sudoku (Sudoku): Sudoku object to solve.
solve_one (bool): Parameter to enable finishing function after writing one value to a cell.
Returns:
bool: True if functions wrote value to at least one cell.
"""
size = sudoku.size
was_changed = False
for row in range(0, size):
for column in range(0, size):
possibilities = sudoku.get_cell_possibilities(row, column)
if len(possibilities) == 1:
sudoku.set_cell_value(row, column, list(possibilities)[0], self.name())
was_changed = True
if solve_one:
return True
return was_changed
class Exclusion(Pattern):
"""A class solving sudoku by Exclusion pattern. Extends Pattern class.
The pattern checks cells in Region of sudoku and excludes possible values that exists in multiple cells. If there is
remaining possible value it is written to the cell.
"""
def solve(self, sudoku: Sudoku, solve_one=False) -> bool:
"""Solve sudoku with Exclusion pattern.
The pattern checks cells in Region of sudoku. If there is a cell that has multiple possibilities but one of them
does not exist in other cells then the function writes the possible value to the cell.
Algorithm:
Go through each region of the sudoku. Then go though each cell of the region. Check possible values of each
cell. Update dictionary where a key is possible value and item is a tuple consisting of:
- number of times each possible value exists in cells of the region,
- a list of cells that have the possible value.
After the region is checked and possible values are counted, go though the dictionary and check if there is
the possible value that exists only in one cell. If it is present, write the value to the cell.
Args:
sudoku (Sudoku): Sudoku object to solve.
solve_one (bool): Parameter to enable finishing function after writing one value to a cell.
Returns:
bool: True if functions wrote value to at least one cell.
"""
count_possibilities_dict = dict()
was_changed = False
for region in sudoku.regions:
count_possibilities_dict.clear()
for cell in region.cells:
for possible_value in cell.possible_values:
count, cells_list = count_possibilities_dict.get(possible_value, (0, []))
cells_list.append(cell)
count_possibilities_dict[possible_value] = ((count+1), cells_list)
for value, (count, cells_list) in count_possibilities_dict.items():
if count == 1:
sudoku.set_cell_value(cells_list[0].row, cells_list[0].column, value, self.name())
was_changed = True
return was_changed
class BruteForce(Pattern):
"""A class solving sudoku by Brute Force (recursively). Extends Pattern class.
Attributes:
_root (SudokuNode): Object of internal class SudokuNode.
"""
def __init__(self):
self._root = None
def solve(self, sudoku: Sudoku, solve_one=False) -> bool:
"""Solve sudoku by Brute Force (recursively).
Algorithm:
Create object of internal class SudokuNode as a root of recursive method. If the sudoku is not wrong call
'solve' method the root object.
Args:
sudoku (Sudoku): Sudoku object to solve.
solve_one (bool): Parameter to enable finishing function after writing one value to a cell.
Returns:
bool: True if sudoku was solved. Otherwise False.
"""
self._root = self.SudokuNode(sudoku)
self.SudokuNode.sudoku_solved = None
if not sudoku.is_wrong():
self._root.solve()
if self.SudokuNode.sudoku_solved is not None:
sudoku.copy_from(self.SudokuNode.sudoku_solved)
return True
return False
class SudokuNode(object):
"""Class representing variation of sudoku as a node of the tree in a recursive method of solving sudoku.
Class static attributes:
sudoku_solved (Sudoku): Static object of Sudoku to which solved sudoku is written.
patterns (List[Pattern]): Static list of patterns for solving sudoku.
METHOD (str): Static string with the name of the method ('BruteForce')
Attributes:
_sudoku (Sudoku): Sudoku in a current node.
_children (List[SudokuNode]): List of children SudokuNode objects for BruteForce.
"""
sudoku_solved = None
patterns = Pattern.get_patterns_without_brute_force()
METHOD = 'BruteForce'
def __init__(self, sudoku: Sudoku, row=-1, column=-1, value=-1):
"""Initiate the SudokuNode with sudoku and optional arguments for writing value to a cell.
Write the value to a cell of row and column if the arguments are specified and different than -1.
Args:
sudoku (Sudoku): Sudoku variation.
row (int): A row number of a cell to which value should be written. Defaults to -1.
column (int): A column number of a cell to which value should be written. Defaults to -1.
value (int): Value to write to a cell. Defaults to -1.
"""
self._sudoku = copy.deepcopy(sudoku)
self._children = []
if row != -1 and column != -1 and value > 0:
self._sudoku.set_cell_value(row, column, value, self.METHOD)
def solve(self) -> bool:
"""Solve sudoku with BruteForce.
Algorithm:
First use typical patterns like OnePossibility and Exclusion in order to minimize recursion.
If sudoku is solved - finish. If it is unsolvable return False.
Go through each row and column and if there is a cell with no value (zero), create children, each with one
of the possible values written to the cell.
Go through children and call solve method.
Returns:
bool: True if sudoku is solved. Otherwise False.
"""
for pattern in self.patterns:
solve_again = True
while solve_again:
solve_again = pattern.solve(self._sudoku, False)
if self._sudoku.is_solved():
BruteForce.SudokuNode.sudoku_solved = self._sudoku
return True
elif self._sudoku.is_wrong():
return False
is_done = False
for row in range(self._sudoku.size):
for column in range(self._sudoku.size):
if self._sudoku.get_cell_value(row, column) == 0:
for possibility in self._sudoku.get_cell_possibilities(row, column):
sudoku_node = BruteForce.SudokuNode(self._sudoku, row, column, possibility)
self._children.append(sudoku_node)
is_done = True
break
if is_done:
break
for child in self._children:
return child.solve()
# result = child.solve()
# if result:
# return True
class SudokuFactory(object):
"""Sudoku factory class.
Static attributes:
POSSIBLE_SIZES (dict(int: Tuple(int, int))): dictionary holding possible sizes of Sudoku as keys and size of
rectangle as values.
"""
POSSIBLE_SIZES = {4: (2, 2), 6: (3, 2), 9: (3, 3)}
@staticmethod
def create_from_string(sudoku: str):
"""Create sudoku instance from multiline string.
Correct format of sudoku is:
'293040100
516230740
847156000
354002690
600415000
000900000
000394802
000600005
000521000'
or:
'134265
526134
243516
615423
461352
352641'
Args:
sudoku (str): Sudoku written as a string.
Raises:
ValueError: raise if string is in incorrect format or size of sudoku is not included in POSSIBLE_SIZES.
"""
lines = []
for line in sudoku.splitlines():
line = line.strip()
if line.isdigit():
lines.append(line)
size = len(lines)
for line in lines:
if len(line) != size or size not in SudokuFactory.POSSIBLE_SIZES:
raise ValueError("Incorrect input string")
Cell.MAX_VALUE = size
cells = [[None for _ in range(0, size)] for _ in range(0, size)]
for row in range(0, size):
for col in range(0, size):
value = int(lines[row][col])
cells[row][col] = Cell(row, col, False, value) if value else Cell(row, col)
# is it ok to shorten it to:
# cells = [[Cell(row, col, False, int(lines[row][col])) if int(lines[row][col])
# else Cell(row, col) for col in range(0, 9)] for row in range(0, 9)]
return Sudoku(size=size, cells=cells, rect_width=SudokuFactory.POSSIBLE_SIZES[size][0],
rect_height=SudokuFactory.POSSIBLE_SIZES[size][1])
if __name__ == '__main__':
sud = """
293040100
516230740
847156000
354002690
600415000
000900000
000394802
000600005
000521000
"""
sudoku = SudokuFactory.create_from_string(sud)
sudoku_solver = SudokuSolver(sudoku)
sudoku_solver.solve()
print(sudoku_solver.to_string())
</code></pre>
<p><strong>sudoku_test.py</strong></p>
<pre><code>import unittest
from sudoku import *
class CellTests(unittest.TestCase):
def set_up(self):
pass
def test_cell_not_editable_and_value_0(self):
with self.assertRaises(AttributeError) as cm:
cell = Cell(0, 0, editable=False, value=0)
self.assertTrue("Cell not editable and without value" in str(cm.exception))
def test_cell_value_below_0(self):
with self.assertRaises(AttributeError) as cm:
cell = Cell(0, 0, value=-1)
self.assertTrue("Incorrect value (-1 not in <0,{}>)".format(Cell.MAX_VALUE) in str(cm.exception))
def test_cell_value_over_MAX(self):
value = Cell.MAX_VALUE
with self.assertRaises(AttributeError) as cm:
cell = Cell(0, 0, value=value+1)
self.assertTrue("Incorrect value ({} not in <0,{}>)".format(value+1, value) in str(cm.exception))
def test_cell_not_editable_and_correct_value(self):
cell = Cell(0, 0, editable=False, value=1)
self.assertFalse(cell.editable)
self.assertEqual(cell.value, 1)
self.assertTrue(cell.possible_values == set())
def test_cell_editable_and_correct_value(self):
cell = Cell(0, 0, editable=True, value=1)
self.assertTrue(cell.editable)
self.assertEqual(cell.value, 1)
self.assertTrue(cell.possible_values == set(range(1, Cell.MAX_VALUE + 1)))
def test_cell_set_value(self):
cell = Cell(0, 0, editable=True, value=0)
cell.value = 1
self.assertEqual(cell.value, 1)
def test_cell_not_editable_set_value(self):
cell = Cell(0, 0, editable=False, value=1)
with self.assertRaises(AttributeError) as cm:
cell.value = 2
self.assertTrue("Cell not editable" in str(cm.exception))
def test_cell_set_incorrect_value(self):
value = Cell.MAX_VALUE
incorrect_values = [-1, value+1]
for v in incorrect_values:
cell = Cell(0, 0, editable=True, value=1)
with self.assertRaises(AttributeError) as cm:
cell.value = v
msg = "Incorrect value ({} not in <0,{}>)".format(v, value)
self.assertTrue(msg in str(cm.exception))
def test_clear_value(self):
cell = Cell(0, 0, editable=True, value=1)
self.assertEqual(cell.value, 1)
cell.clear()
self.assertEqual(cell.value, 0)
def test_cell_not_editable_clear_value(self):
cell = Cell(0, 0, editable=False, value=1)
self.assertEqual(cell.value, 1)
cell.clear()
self.assertEqual(cell.value, 1)
def test_cell_possible_values(self):
cell = Cell(0, 0, editable=True, value=0)
possible_values = set(range(1, Cell.MAX_VALUE + 1))
self.assertEqual(cell.possible_values, possible_values)
cell.value = 1
self.assertEqual(cell.possible_values, set())
cell.value = 0
cell.init_possible_values()
self.assertEqual(cell.possible_values, possible_values)
def test_intersect_possible_values(self):
cell = Cell(0, 0, True, 0)
intersect_values = set(range(1, Cell.MAX_VALUE + 1))
self.assertEqual(cell.possible_values, intersect_values)
intersect_values.remove(1)
cell.intersect_possible_values(intersect_values)
self.assertEqual(cell.possible_values, intersect_values)
intersect_values.remove(2)
cell.intersect_possible_values(intersect_values)
self.assertEqual(cell.possible_values, intersect_values)
intersect_values.remove(3)
cell.intersect_possible_values(intersect_values)
self.assertEqual(cell.possible_values, intersect_values)
cell.init_possible_values()
self.assertEqual(cell.possible_values, set(range(1, cell.MAX_VALUE + 1)))
def test_remove_possible_value(self):
cell = Cell(0, 0, True, 0)
self.assertEqual(cell.possible_values, set(range(1, cell.MAX_VALUE + 1)))
cell.remove_possible_value(1)
self.assertEqual(cell.possible_values, set(range(2, cell.MAX_VALUE + 1)))
class RegionTest(unittest.TestCase):
def SetUp(self):
pass
def test_init(self):
region = Region()
self.assertEqual(region.cells, [])
def test_add_cell(self):
region = Region()
cell_1 = Cell(0, 0, True, 0)
cell_2 = Cell(0, 0, True, 0)
region.add(cell_1)
self.assertEqual(region.cells, [cell_1])
self.assertNotEqual(region.cells, [cell_2])
def test_remove_possible_values_if_cell_is_in_region(self):
region = Region()
cell_1 = Cell(0, 0, True, 0)
cell_2 = Cell(0, 0, True, 0)
region.add(cell_1)
possible_values = set(range(1, Cell.MAX_VALUE + 1))
possible_values_without_1 = set(range(2, Cell.MAX_VALUE + 1))
self.assertEqual(cell_1.possible_values, possible_values)
self.assertEqual(cell_1.possible_values, possible_values)
region.remove_possible_value_if_cell_is_in_region(cell_1, 1)
self.assertNotEqual(cell_1, possible_values)
self.assertEqual(cell_1.possible_values, possible_values_without_1)
region.remove_possible_value_if_cell_is_in_region(cell_2, 1)
self.assertEqual(cell_2.possible_values, possible_values)
region.remove_possible_value_if_cell_is_in_region(cell_2, 2)
self.assertEqual(cell_2.possible_values, possible_values)
self.assertEqual(cell_1.possible_values, possible_values_without_1)
def test_update_possible_values(self):
region = Region()
cells = [Cell(0, 0, True, 0), Cell(0, 1, True, 0), Cell(0, 2, True, 0), Cell(0, 3, False, 1)]
count = len(cells)
for cell in cells:
region.add(cell)
region.update_possible_values()
for cell in region.cells:
if cell.value == 0:
self.assertEqual(cell.possible_values, set(range(2, count+1)))
else:
self.assertEqual(cell.possible_values, set())
def test_is_not_solved(self):
region = Region()
cells = [Cell(0, 0, True, 0), Cell(0, 1, True, 2), Cell(0, 2, True, 3), Cell(0, 3, False, 4)]
for cell in cells:
region.add(cell)
self.assertFalse(region.is_solved())
def test_is_solved(self):
region = Region()
cells = [Cell(0, 0, True, 1), Cell(0, 1, True, 2), Cell(0, 2, True, 3), Cell(0, 3, False, 4)]
for cell in cells:
region.add(cell)
self.assertTrue(region.is_solved())
def test_is_wrong(self):
region = Region()
cells = [Cell(0, 0, True, 2), Cell(0, 1, True, 2), Cell(0, 2, True, 3), Cell(0, 3, False, 4)]
for cell in cells:
region.add(cell)
self.assertFalse(region.is_solved())
def test_is_not_possible_to_solve(self):
region = Region()
cells = [Cell(0, 0, True, 0), Cell(0, 1, True, 2), Cell(0, 2, True, 3), Cell(0, 3, False, 4)]
for cell in cells:
region.add(cell)
cell = region.cells[0]
cell.intersect_possible_values(set())
self.assertTrue(region.is_not_possible_to_solve())
class UndoRedoTest(unittest.TestCase):
def test_action_added(self):
row = 1
column = 2
old_value = 0
value = 3
method = 'manual'
undo_redo = UndoRedo()
undo_redo.add_action(row, column, old_value, value, method)
self.assertTrue(undo_redo.undo_length() == 1)
action = (1, 3, 0, 4, 'manual')
undo_redo.add_action(*action)
self.assertTrue(undo_redo.undo_length() == 2)
def test_undo_redo(self):
undo_redo = UndoRedo()
action_1 = (1, 2, 3, 4, 'manual')
action_2 = (2, 3, 4, 5, 'manually')
undo_redo.add_action(*action_1)
undo_redo.add_action(*action_2)
self.assertTrue(undo_redo.undo_length() == 2)
self.assertTrue(undo_redo.redo_length() == 0)
row, column, old_value, value, method, undo_length, redo_length = undo_redo.undo()
self.assertEqual(row, 2)
self.assertEqual(column, 3)
self.assertEqual(old_value, 4)
self.assertEqual(value, 5)
self.assertEqual(method, 'manually')
self.assertEqual(undo_length, 1)
self.assertEqual(redo_length, 1)
row, column, old_value, value, method, undo_length, redo_length = undo_redo.undo()
self.assertEqual(row, 1)
self.assertEqual(column, 2)
self.assertEqual(old_value, 3)
self.assertEqual(value, 4)
self.assertEqual(method, 'manual')
self.assertEqual(undo_length, 0)
self.assertEqual(redo_length, 2)
row, column, old_value, value, method, undo_length, redo_length = undo_redo.redo()
self.assertEqual(row, 1)
self.assertEqual(column, 2)
self.assertEqual(old_value, 3)
self.assertEqual(value, 4)
self.assertEqual(method, 'manual')
self.assertEqual(undo_length, 1)
self.assertEqual(redo_length, 1)
row, column, old_value, value, method, undo_length, redo_length = undo_redo.redo()
self.assertEqual(row, 2)
self.assertEqual(column, 3)
self.assertEqual(old_value, 4)
self.assertEqual(value, 5)
self.assertEqual(method, 'manually')
self.assertEqual(undo_length, 2)
self.assertEqual(redo_length, 0)
class SudokuTest(unittest.TestCase):
def setUp(self):
Cell.MAX_VALUE = 9
def test_empty_sudoku(self):
sudoku = Sudoku()
for row in sudoku.cells:
for cell in row:
self.assertTrue(cell.editable)
self.assertEqual(cell.value, 0)
def test_creation_of_sudoku_from_cells(self):
cells = [[Cell(x, y, editable=False, value=x+1) if x == y else Cell(x, y) for x in range(9)] for y in range(9)]
sudoku = Sudoku(cells=cells)
for r in range(len(sudoku.cells)):
for c in range(len(sudoku.cells[0])):
if r == c:
self.assertFalse(sudoku.cells[r][c].editable)
self.assertEqual(sudoku.cells[r][c].value, r + 1)
else:
self.assertTrue(sudoku.cells[r][c].editable)
self.assertEqual(sudoku.cells[r][c].value, 0)
def test_get_cell_value(self):
cells = [[Cell(x, y, editable=False, value=x+1) if x == y else Cell(x, y) for x in range(9)] for y in range(9)]
sudoku = Sudoku(cells=cells)
self.assertEqual(sudoku.get_cell_value(3, 3), 4)
self.assertEqual(sudoku.get_cell_value(3, 4), 0)
def test_get_cell_value_index_out_of_range(self):
sudoku = Sudoku()
with self.assertRaises(AttributeError) as cm:
sudoku.get_cell_value(0, -1)
self.assertTrue("Row or column out of range: <0,{}>".format(sudoku.size - 1) in str(cm.exception))
def test_editable(self):
cells = [[Cell(x, y, editable=False, value=x+1) if x == y else Cell(x, y) for x in range(9)] for y in range(9)]
sudoku = Sudoku(cells=cells)
rang = range(len(cells))
for row in rang:
for col in rang:
if row == col:
self.assertFalse(sudoku.is_editable(row, col))
else:
self.assertTrue(sudoku.is_editable(row, col))
def test_test(self):
cells = [[Cell(x, y, editable=False, value=x+1) if x == y else Cell(x, y) for x in range(9)] for y in range(9)]
sudoku = Sudoku(cells=cells)
sudoku.set_cell_value(0, 1, 4)
sudoku.set_cell_value(0, 2, 5)
sudoku.set_cell_value(1, 0, 6)
sudoku.set_cell_value(1, 2, 7)
sudoku.set_cell_value(2, 1, 8)
sudoku.set_cell_value(0, 1, 9)
for region in sudoku._regions:
region.update_possible_values()
for r in sudoku._regions:
r.update_possible_values()
def test_solve(self):
sudoku = Sudoku()
sudoku.set_cell_value(0, 0, 1)
sudoku.set_cell_value(0, 5, 8)
sudoku.set_cell_value(0, 6, 4)
sudoku.set_cell_value(1, 1, 2)
sudoku.set_cell_value(1, 5, 4)
sudoku.set_cell_value(1, 6, 9)
sudoku.set_cell_value(2, 0, 9)
sudoku.set_cell_value(2, 2, 3)
sudoku.set_cell_value(2, 3, 2)
sudoku.set_cell_value(2, 4, 5)
sudoku.set_cell_value(2, 5, 6)
sudoku.set_cell_value(3, 0, 6)
sudoku.set_cell_value(3, 6, 5)
sudoku.set_cell_value(3, 7, 7)
sudoku.set_cell_value(3, 8, 1)
sudoku.set_cell_value(4, 0, 4)
sudoku.set_cell_value(4, 1, 1)
sudoku.set_cell_value(4, 3, 8)
sudoku.set_cell_value(4, 5, 5)
sudoku.set_cell_value(4, 7, 6)
sudoku.set_cell_value(4, 8, 2)
sudoku.set_cell_value(5, 0, 5)
sudoku.set_cell_value(5, 1, 3)
sudoku.set_cell_value(5, 2, 2)
sudoku.set_cell_value(5, 8, 4)
sudoku.set_cell_value(6, 3, 5)
sudoku.set_cell_value(6, 4, 8)
sudoku.set_cell_value(6, 5, 2)
sudoku.set_cell_value(6, 6, 7)
sudoku.set_cell_value(6, 8, 9)
sudoku.set_cell_value(7, 2, 1)
sudoku.set_cell_value(7, 3, 3)
sudoku.set_cell_value(7, 7, 4)
sudoku.set_cell_value(8, 2, 8)
sudoku.set_cell_value(8, 3, 1)
sudoku.set_cell_value(8, 8, 5)
puzzle = """100008400
020004900
903256000
600000571
410805062
532000004
000582709
001300040
008100005
""".replace(' ', '')
self.assertEqual(sudoku.to_string(), puzzle)
solver = SudokuSolver(sudoku)
solver.solve()
solution = """175938426
826714953
943256187
689423571
417895362
532671894
364582719
751369248
298147635
""".replace(' ', '')
self.assertEqual(solver.sudoku.to_string(), solution)
def test_solve2(self):
sudoku = Sudoku()
sudoku.set_cell_value(0, 0, 1)
sudoku.set_cell_value(0, 5, 8)
sudoku.set_cell_value(0, 6, 4)
sudoku.set_cell_value(1, 1, 2)
sudoku.set_cell_value(1, 5, 4)
sudoku.set_cell_value(1, 6, 9)
sudoku.set_cell_value(2, 0, 9)
sudoku.set_cell_value(2, 2, 3)
sudoku.set_cell_value(2, 3, 2)
sudoku.set_cell_value(2, 4, 5)
sudoku.set_cell_value(2, 5, 6)
sudoku.set_cell_value(3, 0, 6)
sudoku.set_cell_value(3, 6, 5)
sudoku.set_cell_value(3, 7, 7)
sudoku.set_cell_value(3, 8, 1)
sudoku.set_cell_value(4, 0, 4)
sudoku.set_cell_value(4, 1, 1)
sudoku.set_cell_value(4, 3, 8)
sudoku.set_cell_value(4, 5, 5)
sudoku.set_cell_value(4, 7, 6)
sudoku.set_cell_value(4, 8, 2)
sudoku.set_cell_value(5, 0, 5)
sudoku.set_cell_value(5, 1, 3)
sudoku.set_cell_value(5, 2, 2)
sudoku.set_cell_value(5, 8, 4)
sudoku.set_cell_value(6, 3, 5)
sudoku.set_cell_value(6, 4, 8)
sudoku.set_cell_value(6, 5, 2)
sudoku.set_cell_value(6, 6, 7)
sudoku.set_cell_value(6, 8, 9)
sudoku.set_cell_value(7, 2, 1)
sudoku.set_cell_value(7, 3, 3)
sudoku.set_cell_value(7, 7, 4)
sudoku.set_cell_value(8, 2, 8)
sudoku.set_cell_value(8, 3, 1)
sudoku.set_cell_value(8, 8, 5)
puzzle = """100008400
020004900
903256000
600000571
410805062
532000004
000582709
001300040
008100005
""".replace(' ', '')
self.assertEqual(sudoku.to_string(), puzzle)
solver = SudokuSolver(sudoku)
solver.solve()
solution = """175938426
826714953
943256187
689423571
417895362
532671894
364582719
751369248
298147635
""".replace(' ', '')
self.assertEqual(solver.sudoku.to_string(), solution)
def test_solve3(self):
puzzle = """
293040100
516230740
847156000
354002690
600415000
000900000
000394802
000600005
000521000
""".replace(' ', '').replace('\n', '', 1)
sudoku = SudokuFactory.create_from_string(puzzle)
self.assertEqual(sudoku.to_string(), puzzle)
solver = SudokuSolver(sudoku)
solver.solve()
solution = """
293847156
516239748
847156923
354782691
689415237
721963584
165394872
932678415
478521369
""".replace(' ', '').replace('\n', '', 1)
self.assertEqual(solver.sudoku.to_string(), solution)
def test_solve_6x6(self):
puzzle = """
100000
020000
003000
000400
000050
000000
""".replace(' ', '').replace('\n', '', 1)
sudoku = SudokuFactory.create_from_string(puzzle)
self.assertEqual(sudoku.to_string(), puzzle)
solver = SudokuSolver(sudoku)
solver.solve()
solution = """
134265
526134
243516
615423
461352
352641
""".replace(' ', '').replace('\n', '', 1)
self.assertEqual(solver.sudoku.to_string(), solution)
def test_solve_4x4(self):
puzzle = """
1000
0200
0030
0004
""".replace(' ', '').replace('\n', '', 1)
sudoku = SudokuFactory.create_from_string(puzzle)
self.assertEqual(sudoku.to_string(), puzzle)
solver = SudokuSolver(sudoku)
solver.solve()
solution = """
1342
4213
2431
3124
""".replace(' ', '').replace('\n', '', 1)
self.assertEqual(solver.sudoku.to_string(), solution)
if __name__ == '__main__':
unittest.main()
</code></pre>
| [] | [
{
"body": "<p>Why should your <code>Cell</code> check against <code>MAX_VALUE</code> anyway? Do you expect some solver to set a value of <code>42</code> in a 9x9 Sudoku? So leave this constant to the <code>Sudoku</code> class. If you want to init a cell simply pass a list of allowed values (you could do a 9x9 S... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T13:45:44.210",
"Id": "204187",
"Score": "3",
"Tags": [
"python",
"sudoku"
],
"Title": "Object Oriented Sudoku Solver in Python"
} | 204187 |
<p><strong>Find the length of the longest line with given square (MxM) matrix. (vertical, horizontal, or diagonal allowed) (Length of the longest line = number of consecutive 1's)</strong></p>
<p>i.e.)
input:</p>
<pre><code>{
{0,0,0,0,0,0,0,0},
{0,0,1,0,1,0,0,0},
{0,1,0,1,0,0,0,0},
{1,1,1,1,1,1,1,0},
{0,1,0,0,0,1,0,0},
{1,1,0,0,0,0,1,0},
{0,1,0,0,0,0,0,1},
{0,0,0,0,0,0,0,0}
}
</code></pre>
<p>output: 7 (The 4th horizontal row is the longest line in this case.)</p>
<p>My java code:</p>
<pre><code>public class LongestLine {
private int hmax = 0;
private int vmax = 0;
private int rdmax = 0; // right down direction
private int ldmax = 0; // left down direction
public int longestLine(int[][] grid) {
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
if(grid[i][j] == 1) update(grid, i, j);
}
}
return Math.max(Math.max(hmax, vmax), Math.max(rdmax, ldmax));
}
private void update(int[][] grid, int i, int j) {
int h = 1, v = 1, rd = 1, ld = 1;
if(j < grid[i].length - 1 && grid[i][j+1] == 1) {
if(j == 0 || grid[i][j-1] != 1) h = updateH(grid, i, j+1, h);
}
if(i < grid.length - 1 && grid[i+1][j] == 1) {
if(i == 0 || grid[i-1][j] != 1) v = updateV(grid, i+1, j, v);
}
if(j < grid[i].length - 1 && i < grid.length - 1 && grid[i+1][j+1] == 1) {
if(j == 0 || i == 0 || grid[i-1][j-1] != 1) rd = updateRD(grid, i+1, j+1, rd);
}
if(j > 0 && i < grid.length - 1 && grid[i+1][j-1] == 1) {
if(j == grid[i].length - 1 || i == 0 || grid[i-1][j+1] != 1) ld = updateLD(grid, i+1, j-1, ld);
}
hmax = Math.max(h, hmax);
vmax = Math.max(v, vmax);
rdmax = Math.max(rd, rdmax);
ldmax = Math.max(ld, ldmax);
}
private int updateH(int[][] grid, int i, int j, int h) {
h++;
if(j < grid[i].length - 1 && grid[i][j+1] == 1) h = updateH(grid, i, j+1, h);
return h;
}
private int updateV(int[][] grid, int i, int j, int v) {
v++;
if(i < grid.length - 1 && grid[i+1][j] == 1) v = updateV(grid, i+1, j, v);
return v;
}
private int updateRD(int[][] grid, int i, int j, int rd) {
rd++;
if(j < grid[i].length - 1 && i < grid.length - 1 && grid[i+1][j+1] == 1)
rd = updateRD(grid, i+1, j+1, rd);
return rd;
}
private int updateLD(int[][] grid, int i, int j, int ld) {
ld++;
if(j > 0 && i < grid.length - 1 && grid[i+1][j-1] == 1)
ld = updateLD(grid, i+1, j-1, ld);
return ld;
}
}
</code></pre>
<p><strong>My code seems to work, but I'm not sure if this is the most efficient code. Do you think this is OK? Or are there any faster/simpler implementation? (Answer in Java format preferred.)</strong></p>
| [] | [
{
"body": "<p>In worst case (array that has only 1, no 0) you are doing M operations for each cell in MxM for a total of M^3 operations. You can reduce it to M^2 if you remember the results for previous row (for vertical, LD, RD) and current(horizontal). If the cell is 1 increment the counters, otherwise reset ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T16:41:01.803",
"Id": "204192",
"Score": "3",
"Tags": [
"java",
"matrix"
],
"Title": "Find the longest line in 2D (MxM) array (vertical, horizontal, or diagonal)"
} | 204192 |
<p>I wrote a <a href="https://github.com/KevinRamharak/ng-sane-defaults/tree/fc5e7027dad4af013339f8616484686bef144993" rel="nofollow noreferrer">small module in typescript</a> that augments the angularjs <code>registerComponent</code> function to provide a new way of default values for the component controller.</p>
<p>This module was written to solve the problem of not having a nice non-biolerplatey way of providing default values for components. Another problem it attempts to solve is to prevent the default value not applying if a value was provided trough bindings but the value is undefined or null.</p>
<p>The module works by using a static property on the component controller called <code>$defaults</code>. Getter functions are also supported to provide dynamic defaults for each component instance.</p>
<p>I wrote it with dynamic getters in mind. Because it is a function you could do anything in the function body (for example call an API).</p>
<p>I am looking for some feedback on the code and its purpose. The source code is available.</p>
<pre><code>(function() {
type Dict<T = any> = { [key: number]: T, [key: string]: T };
angular.module('ng-sane-defaults', []).config([
'$compileProvider',
function configure($compileProvider: angular.ICompileProvider) {
// get the original `registerComponent` function
const registerComponent = $compileProvider.component;
// override the original function
$compileProvider.component = component;
/**
*
* @param nameOrDict name or Dictionary of component names and their options
* @param options options for the component if the first parameter is the name
*/
function component(this: angular.ICompileProvider, nameOrDict: string|Dict<angular.IComponentOptions>, options?: angular.IComponentOptions) {
// make sure the function signature is correct, if not pass it trough to the original function to handle errors
if (typeof nameOrDict === 'string' && typeof options !== 'object')
return registerComponent.call(this, nameOrDict, options as any);
if (typeof nameOrDict !== 'string' && typeof nameOrDict !== 'object')
return registerComponent.call(this, nameOrDict, options as any);
// create the dictionary call signature as it is easier to work with
const components: Dict<angular.IComponentOptions> = (typeof nameOrDict === 'string') ? { [nameOrDict]: options! } : nameOrDict;
for (const key in components) {
const options = components[key];
// check if it has a controller function
if (typeof options.controller !== 'function')
continue;
// check if it has a `static $defaults` property, use `getOwnPropertyNames` to check for a getter function without invoking it
if (Object.getOwnPropertyNames(options.controller).indexOf('$defaults') === -1)
continue;
// get the original `$onInit` function or undefined if there was none
const onInit: Function|undefined = options.controller.prototype.$onInit;
// patch the `$onInit` function
options.controller.prototype.$onInit = function $onInit() {
const defaults = (options.controller as Dict).$defaults;
if (typeof defaults === 'object') {
for (const prop in defaults) {
if (this[prop] == null) {
this[prop] = defaults[prop];
}
}
}
// call the lifecycle hook if it existed
return (typeof onInit === 'function') ? onInit.call(this) : void 0;
};
}
return registerComponent.call(this, components);
}
}
]);
})();
</code></pre>
<p>You can check <a href="https://plnkr.co/edit/c5SW6kDUsovsczGY1rOL?p=preview" rel="nofollow noreferrer">this</a> plunkr to see it in action</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T18:15:16.077",
"Id": "204196",
"Score": "2",
"Tags": [
"angular.js",
"typescript",
"modules"
],
"Title": "Addition of defaults to components in AngularJS"
} | 204196 |
<blockquote>
<p>Given a Binary Search Tree and a number N, the task is to find the
smallest number in the binary search tree that is greater than or
equal to N. Print the value of the element if it exists otherwise
print -1.</p>
</blockquote>
<p>Please review the code, the unit tests are just for the demo. please comment about performance thanks.</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
/// <summary>
/// https://www.geeksforgeeks.org/smallest-number-in-bst-which-is-greater-than-or-equal-to-n/
/// </summary>
[TestClass]
public class SamllestNumberBstGreatherThanOrEqualToN
{
[TestMethod]
public void SmallestNumberBstGreatherThanOrEqualToNTest()
{
BstNode root = new BstNode(19 );
BstNode left = new BstNode(7);
BstNode right = new BstNode(21);
root.Left = left;
root.Right = right;
BstNode leftLeft = new BstNode(3);
BstNode leftRight = new BstNode(11);
BstNode leftRightLeft = new BstNode(9);
BstNode leftRightRight = new BstNode(14);
root.Left.Left = leftLeft;
root.Left.Right = leftRight;
root.Left.Right.Left = leftRightLeft;
root.Left.Right.Right = leftRightRight;
int result = SmallestNumberGratherThanOrEqual(root, 20);
Assert.AreEqual(21, result);
}
[TestMethod]
public void SmallestNumberBstGreatherThanOrEqualToNTest2()
{
/* 19
/ \
7 21
/ \
3 11
/ \
9 14
*/
BstNode root = new BstNode(19);
root = root.Add(root, 7);
root = root.Add(root, 3);
root = root.Add(root, 11);
root = root.Add(root, 9);
root = root.Add(root, 13);
root = root.Add(root, 21);
int result = SmallestNumberGratherThanOrEqual(root, 18);
Assert.AreEqual(19, result);
}
private int SmallestNumberGratherThanOrEqual(BstNode root, int num)
{
int smallest = -1;
while (root != null)
{
if (root.Value >= num)
{
smallest = root.Value;
root = root.Left;
}
else
{
root = root.Right;
}
}
return smallest;
}
}
}
</code></pre>
<p>here is also the BST class</p>
<pre><code>public class BstNode
{
public int Value;
public BstNode Left;
public BstNode Right;
public BstNode Parent;
public BstNode(int keyt)
{
Value = keyt;
}
public BstNode Add(BstNode node , int key)
{
if (node == null)
{
return new BstNode(key);
}
if (node.Value < key)
{
node.Right = Add(node.Right, key);
}
else
{
node.Left = Add(node.Left, key);
}
return node;
}
}
</code></pre>
| [] | [
{
"body": "<h2><code>SmallestNumberGratherThanOrEqual</code></h2>\n\n<p>This looks mostly fine to me. I can't think how else to implement it, since you can't really separate the 'finding smallest' bit from the 'finding where <code>num</code> would go' bit.</p>\n\n<ul>\n<li><p>The method should probably be publi... | {
"AcceptedAnswerId": "204203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T18:52:34.923",
"Id": "204199",
"Score": "1",
"Tags": [
"c#",
"interview-questions",
"binary-search"
],
"Title": "Smallest number in BST which is greater than or equal to N"
} | 204199 |
<h3>Some context</h3>
<p>I'm implementing a <em>self-closing pairs</em> auto-completion feature in <a href="https://github.com/rubberduck-vba/Rubberduck" rel="noreferrer">Rubberduck</a>. One of the challenges is that the VBIDE API doesn't allow editing a line of code by "injecting" characters: we have to replace the entire line, and a side-effect of this is that it causes the VBE to parse/compile the line (since it's no longer "being edited"), which means a partial line of code like this:</p>
<pre class="lang-vb prettyprint-override"><code>msgbox(
</code></pre>
<p>Turns into this:</p>
<pre class="lang-vb prettyprint-override"><code>MsgBox (
</code></pre>
<p>And there's nothing we can do about it. Obviously this causes a serious problem with determining where the caret is supposed to be - ok maybe not in <em>this particular case</em>, but say you have this (where <code>|</code> denotes caret position):</p>
<pre class="lang-vb prettyprint-override"><code>dosomething |, foo
</code></pre>
<p>If you type a <code>"</code> here, what we want to do is to end up with this:</p>
<pre class="lang-vb prettyprint-override"><code>dosomething "|", foo
</code></pre>
<p>But we need to account for the VBE's "prettifying", and end up with this instead:</p>
<pre class="lang-vb prettyprint-override"><code>DoSomething "|", foo
</code></pre>
<p>So I needed a way to get the VBE to "prettify" the original code, while not losing track of where the caret needs to be - which is fundamental if I don't want Rubberduck's auto-completion to get in the way of typing code in the editor.</p>
<h3>The Solution</h3>
<p>So I wrote an <code>ICodeStringPrettifier</code> interface, and implemented it like this:</p>
<pre><code>public class CodeStringPrettifier : ICodeStringPrettifier
{
private readonly ICodeModule _module;
public CodeStringPrettifier(ICodeModule module)
{
_module = module;
}
public CodeString Prettify(CodeString original)
{
var originalCode = original.Code;
var originalPosition = original.CaretPosition.StartColumn;
var originalNonSpacePosition = 0;
for (var i = 0; i < originalPosition; i++)
{
if (originalCode[i] != ' ')
{
originalNonSpacePosition++;
}
}
_module.DeleteLines(original.SnippetPosition.StartLine);
_module.InsertLines(original.SnippetPosition.StartLine, originalCode);
var prettifiedCode = _module.GetLines(original.SnippetPosition);
var prettifiedNonSpacePosition = 0;
var index = 0;
for (var i = 0; i < prettifiedCode.Length; i++)
{
if (prettifiedCode[i] != ' ')
{
prettifiedNonSpacePosition++;
if (prettifiedNonSpacePosition == originalNonSpacePosition)
{
index = i;
break;
}
}
}
return new CodeString(prettifiedCode, new Selection(0, index + 1));
}
}
</code></pre>
<p>Where <a href="https://github.com/rubberduck-vba/Rubberduck/blob/next/Rubberduck.Core/Common/CodeString.cs" rel="noreferrer"><code>CodeString</code></a> is a <code>struct</code> that is a little more than a formalized <code>(string,Selection)</code> value tuple, that uses the pipe character exactly as shown at the top of this post, to denote the caret position in a code string - which is extremely handy for testing... but then, using this type with actual VBA code that includes an actual pipe character is problematic (<a href="https://github.com/rubberduck-vba/Rubberduck/issues/4373" rel="noreferrer">#4373</a>), but fixing that isn't in scope here.</p>
<p>I've written a few tests for the prettifier, and they all pass:</p>
<pre><code>[TestFixture]
public class PrettifierTests
{
[Test][Category("AutoComplete")]
public void GivenSamePrettifiedCode_YieldsSameCodeString()
{
var original = "MsgBox (|".ToCodeString();
var module = new Mock<ICodeModule>();
module.Setup(m => m.GetLines(original.SnippetPosition)).Returns(original.Code);
var sut = new CodeStringPrettifier(module.Object);
var actual = sut.Prettify(original);
Assert.AreEqual(original, actual);
}
[Test][Category("AutoComplete")]
public void GivenTrailingWhitespace_PrettifiedCaretIsAtLastCharacter()
{
var original = "MsgBox |".ToCodeString();
var prettified = "MsgBox";
var expected = "MsgBox|".ToCodeString();
var module = new Mock<ICodeModule>();
module.Setup(m => m.GetLines(original.SnippetPosition)).Returns(prettified);
var sut = new CodeStringPrettifier(module.Object);
var actual = sut.Prettify(original);
Assert.AreEqual(expected, actual);
}
[Test]
[Category("AutoComplete")]
public void GivenExtraWhitespace_PrettifiedCaretStillAtSameToken()
{
var original = "MsgBox (\"test|\")".ToCodeString();
var prettified = "MsgBox (\"test\")";
var expected = "MsgBox (\"test|\")".ToCodeString();
var module = new Mock<ICodeModule>();
module.Setup(m => m.GetLines(original.SnippetPosition)).Returns(prettified);
var sut = new CodeStringPrettifier(module.Object);
var actual = sut.Prettify(original);
Assert.AreEqual(expected, actual);
}
}
</code></pre>
<p>Since this appears to work exactly as I need it, I'm going to start tweaking the self-closing pairs auto-completion feature to use it - now while <em>it works</em>, for a <em>prettifier</em>, I don't find the implementation particularly <em>pretty</em>. Ideas?</p>
| [] | [
{
"body": "<p>Not knowing anything about RubberDuck, I'm a little frightened by the necessity that the <code>CodeString</code> come from a particular <code>ICodeModule</code>, but that this is not (cannot be?) verified. Obviously if modules are not the only source of <code>CodeString</code>s then this abstracti... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T21:02:20.423",
"Id": "204204",
"Score": "10",
"Tags": [
"c#",
"strings",
"formatting",
"rubberduck",
"autocomplete"
],
"Title": "Prettifier isn't pretty"
} | 204204 |
<p>I am writing a Python class which checks if a given number is divisible by numbers 2-11. I am not using the <code>__init__</code> method which in my opinion is not necessary in this case.</p>
<p>Questions:</p>
<ul>
<li>How can I convert a given number in to <code>abs(x)</code> without using the <code>__init__</code> method in every method at once?</li>
<li>How can I check if a number is divisible by 7 without using a <a href="https://www.geeksforgeeks.org/divisibility-by-7/" rel="nofollow noreferrer">recursive solution</a>?</li>
</ul>
<p></p>
<pre><code>class Divisibility:
"""
Program checks if given number is divisible
by any number from 2 to 11
"""
# Divisibe by 2 if last digit is divisible by 2
def divisible_by_2(self, number):
number = abs(number)
if (number % 10) % 2 == 0:
return True
else:
return False
# Divisible by 3 if sum of its digits is divisible by 3
def divisible_by_3(self, number):
number = abs(number)
n = number
s = 0
while n:
s, n = s + n % 10, n // 10
if s % 3 == 0:
return True
else:
return False
# Divisible by 4 if last two digits is divisible by 4
def divisible_by_4(self, number):
number = abs(number)
if (number % 100) % 4 == 0:
return True
else:
return False
# Divisible by 5 if last digit is either 5 or 0
def divisible_by_5(self, number):
number = abs(number)
if number % 10 == 0 or number % 10 == 5:
return True
else:
return False
# Divisible by 6 if number is divisible by 2 and 3
def divisible_by_6(self, number):
number = abs(number)
if self.divisible_by_2(number) and self.divisible_by_3(number):
return True
else:
return False
def divisible_by_7(self, number):
number = abs(number)
if number % 7 == 0:
return True
else:
return False
# Divisible by 8 if last three digits is divisible by 8
def divisible_by_8(self, number):
number = abs(number)
if (number % 1000) % 8 == 0:
return True
else:
return False
# Divisible by 9 if the sum of its digits is divisible by 9
def divisible_by_9(self, number):
number = abs(number)
s = 0
while number:
s, number = s + number % 10, number // 10
if s % 3 == 0:
return True
else:
return False
# Divisible by 10 if last digit is 0
def divisible_by_10(self, number):
number = abs(number)
if number % 10 == 0:
return True
else:
return False
# Divisible by 11 if the difference between
# the sum of numbers at even possitions and odd
# possitions is divisible by 11
def divisible_by_11(self, number):
number = abs(number)
n = number
nn = number // 10
total = 0
while n:
total += n % 10
n //= 100
while nn:
total -= nn % 10
nn //= 100
if abs(total) % 11 == 0:
return True
else:
return False
if __name__ == '__main__':
D = Divisibility()
print(D.divisible_by_2(-6))
print(D.divisible_by_3(6))
print(D.divisible_by_4(6))
print(D.divisible_by_5(60))
print(D.divisible_by_6(6))
print(D.divisible_by_7(616))
print(D.divisible_by_8(82453))
print(D.divisible_by_9(9512244))
print(D.divisible_by_10(-571288441))
print(D.divisible_by_11(121))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T13:38:17.660",
"Id": "393748",
"Score": "0",
"body": "Related question: [Checking if a number is divisible by 3](/q/52315/9357)"
}
] | [
{
"body": "<p>You do this quite alot</p>\n\n<pre><code>if s % 3 == 0:\n return True\nelse:\n return False\n</code></pre>\n\n<p>Instead you could return directly</p>\n\n<pre><code>return s % 3 == 0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": ... | {
"AcceptedAnswerId": "204210",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T21:30:13.493",
"Id": "204206",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Checking if a number is divisible by 2-11"
} | 204206 |
<p>I'm an active contributing member of <a href="https://en.wiktionary.org/wiki/Wiktionary:Main_Page" rel="nofollow noreferrer">Wiktionary</a> and an active member of an active Wiktionary Discord server. Some time ago, several users proposed a bot which would make linking to Wiktionary in Discord much easier (originally one would have had to go to Wiktionary, search their entry, copy the link, and then navigate back to Discord to paste it); thus I made this bot.</p>
<p>The bot works exactly like link formatting on Wikimedia sites; the only exception is that the heading character <code>#</code> is replaced with <code>?</code> since Discord already utilizes pound signs to reference server channels. A couple of example commands might be:</p>
<blockquote>
<ul>
<li><code>[[cogito?Latin|cōgitō]]</code> produces <code>cōgitō: https://en.wiktionary.org/wiki/cogito#Latin</code> </li>
<li><code>[[cogito?Latin]]</code> produces <code>https://en.wiktionary.org/wiki/cogito#Latin</code></li>
<li><code>[[cogito|cōgitō]]</code> produces <code>cōgitō: https://en.wiktionary.org/wiki/cogito</code> </li>
<li><code>[[cogito]]</code> produces <code>https://en.wiktionary.org/wiki/cogito</code></li>
<li>etc.</li>
</ul>
</blockquote>
<p>The bot can also produce links to other Wikimedia sites, like Wiktionary, Wikibooks, etc. due to the fact that top-level namespaces exist on every Wikimedia site which serve as redirects. Examples:</p>
<blockquote>
<ul>
<li><code>[[wikipedia:Tire?History]]</code> produces <code>https://en.wiktionary.org/wiki/wikipedia:Tire#History</code> </li>
<li><code>[[wikipedia:Tire?History|History of the tyre]]</code> produces <code>History of the tyre: https.en.wiktionary.org/wikipedia:Tire#History</code></li>
<li>etc.</li>
</ul>
</blockquote>
<p>Commands can also be embedded within the middle of messages; one could write something like <code>The word [[subductisupercilicarptor?Latin]] is one of Latin's longest</code> and the bot would be able to output the message <code>https://en.wiktionary.org/wiki/subductisupercilicarptor#Latin</code>.</p>
<p><strong>EntryPoint.cs</strong>*</p>
<pre><code>using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Discord;
using Discord.WebSocket;
namespace WiktionaryBot
{
/// <summary>
/// Entry point of the bot.
/// </summary>
public class EntryPoint
{
const string CLIENT_ID = "REDACTED";
const string CLIENT_SECRET = "REDACTED";
const string BOT_TOKEN = "REDACTED";
/// <summary>
/// Normal entry point of the application, starts an async context.
/// </summary>
/// <param name="args">The command line arguments passed to the bot.</param>
public static void Main(string[] args)
=> new EntryPoint().MainAsync(args).GetAwaiter().GetResult();
/// <summary>
/// The async context of the bot.
/// </summary>
/// <param name="args">The command line arguments passed to the bot.</param>
public async Task MainAsync(string[] args)
{
DiscordSocketClient discordClient = new DiscordSocketClient();
await discordClient.LoginAsync(TokenType.Bot, BOT_TOKEN);
await discordClient.StartAsync();
discordClient.MessageReceived += this.MessageRecieved;
await Task.Delay(-1);
}
/// <summary>
/// This function is triggered when a message is received.
/// </summary>
/// <param name="message">The message received.</param>
public async Task MessageRecieved(SocketMessage message)
{
MatchCollection matchCollection = Regex.Matches(message.Content, @"\[\[[^\[\]]+\]\]");
List<string> matchedStrings = matchCollection.Cast<Match>().Select(match => match.Value).ToList();
string finalLinkString = "";
foreach(string matchedString in matchedStrings)
{
CommandParser commandParser = new CommandParser(matchedString);
commandParser.GenerateTokens();
commandParser.GenerateOutputLink();
finalLinkString += commandParser.OutputText[0].Item2 + "\n";
}
await message.Channel.SendMessageAsync(finalLinkString);
}
}
}
</code></pre>
<p><strong>CommandParser.cs</strong></p>
<pre><code>using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace WiktionaryBot
{
/// <summary>
/// This enum contains all types of command tokens.
/// </summary>
public enum CommandTokenType
{
LinkTitle,
LinkSubheading,
LinkDisplayTitle
}
/// <summary>
/// This enum contains all of the different types of command output.
/// </summary>
public enum CommandOutputType
{
Link,
}
/// <summary>
/// This class is responsible for parsing an input command.
/// </summary>
public class CommandParser
{
public string InputText { get; set; }
public List<Tuple<CommandOutputType, string>> OutputText { get; set; }
private List<Tuple<CommandTokenType, string>> OutputTokens { get; set; }
/// <summary>
/// Constructor for the CommandParser class.
/// </summary>
/// <param name="inputText">The input command.</param>
public CommandParser(string inputText)
{
this.InputText = inputText;
this.OutputText = new List<Tuple<CommandOutputType, string>>() { };
this.OutputTokens = new List<Tuple<CommandTokenType, string>>() { };
}
/// <summary>
/// Helper method for this.GenerateTokens.
/// </summary>
/// <param name="splitString">A reference to the splitString list.</param>
private void GenerateTokens(ref List<string> splitString)
{
splitString.AddRange(Regex.Split(splitString[0], @"(?=[\?\|])"));
splitString.RemoveAt(0);
this.OutputTokens.Add(
new Tuple<CommandTokenType, string>(
CommandTokenType.LinkTitle,
splitString[0]
)
);
for(int i = 1; i < splitString.Count; i++)
{
string currentToken = splitString[i];
switch(currentToken[0])
{
case '?':
this.OutputTokens.Add(
new Tuple<CommandTokenType, string>(
CommandTokenType.LinkSubheading,
splitString[i].Trim('?')
)
);
break;
case '|':
this.OutputTokens.Add(
new Tuple<CommandTokenType, string>(
CommandTokenType.LinkDisplayTitle,
splitString[i].Trim('|')
)
);
break;
default:
break;
}
}
}
/// <summary>
/// Generate a list of tokens to be interpreted.
/// </summary>
public void GenerateTokens()
{
string linkText = this.InputText.Trim('[', ']');
List<string> splitString = new List<string>() { linkText };
this.GenerateTokens(ref splitString);
}
/// <summary>
/// Generate an output link based on the generated output tokens.
/// </summary>
public void GenerateOutputLink()
{
string linkTitle = this.OutputTokens
.Where(token => token.Item1 == CommandTokenType.LinkTitle)
.ToList()[0].Item2.Replace(' ', '_');
string linkSubheading = this.OutputTokens.Any(token => token.Item1 == CommandTokenType.LinkSubheading)
? "#" + this.OutputTokens.Where(token => token.Item1 == CommandTokenType.LinkSubheading).ToList()[0].Item2.Replace(' ', '_')
: "";
string linkDisplayTitle = this.OutputTokens.Any(token => token.Item1 == CommandTokenType.LinkDisplayTitle)
? this.OutputTokens.Where(token => token.Item1 == CommandTokenType.LinkDisplayTitle).ToList()[0].Item2 + ": "
: "";
this.OutputText.Add(
new Tuple<CommandOutputType, string>(
CommandOutputType.Link,
String.Format("{0}{1}{2}{3}", linkDisplayTitle, "https://en.wiktionary.org/wiki/", linkTitle, linkSubheading)
)
);
}
}
}
</code></pre>
<p>The GitHub link for this bot can be found <a href="https://github.com/Ethan-Bierlein/WiktionaryBot" rel="nofollow noreferrer">here</a>; any suggestions for improvements are welcome.</p>
<p><sub>* The <code>CLIENT_ID</code>, <code>CLIENT_SECRET</code>, and <code>BOT_TOKEN</code> values are redacted in EntryPoint.cs; they are private values used by Discord to connect and authenticate the bot.</sub></p>
| [] | [
{
"body": "<p>There are a couple of things that you can change to simplify the code and to greatly improve the readability.</p>\n\n<blockquote>\n<pre><code>public static void Main(string[] args)\n</code></pre>\n</blockquote>\n\n<p>If you are working with the latest C# then it's now legal to make <code>Main</cod... | {
"AcceptedAnswerId": "204219",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-22T23:07:42.137",
"Id": "204209",
"Score": "4",
"Tags": [
"c#",
"parsing",
".net"
],
"Title": "WiktionaryBot -- A Discord bot for generating Wiktionary links quickly"
} | 204209 |
<p>This is a controller from an Express app that lets users view and manage articles. There are at least a couple of issues I'd like to address...</p>
<p>The program displays a list of articles in a sidebar that appears on each page. Right now, the app queries the database for article names, caches them, and includes them in the payload. It does this for each route that loads a view.</p>
<p>Is there a more efficient way to do this?</p>
<p>A good bit of code is repeated in the first two methods (<code>retrieve</code> and <code>settings</code>). Both methods get a list of articles for the sidebar and show an article or the settings for an article.</p>
<p>Is there a way to DRY up this code?</p>
<pre><code>const { Article } = require('../models');
import CacheService from '../services/cache';
const ttl = 60 * 60 * 1;
const cache = new CacheService(ttl);
module.exports = {
// display one article
retrieve (req, res, next) {
// list of articles displayed in the sidebar
const allArticles = module.exports.getUserArticles(req.user.id);
// the article to display
const thisArticle = module.exports.getArticleById(req.params.publicId);
Promise
.all([allArticles, thisArticle])
.then((result) => {
const articles = result[0];
const article = result[1];
if (!article) {
const error = new Error('Article not found');
error.status = 404;
return next(error);
}
return res.render('article', { articles, article, title: article.name });
})
.catch(next);
},
// show settings page for an article
settings (req, res, next) {
// list of articles displayed in the sidebar
const allArticles = module.exports.getUserArticles(req.user.id);
// the article to display
const thisArticle = module.exports.getArticleById(req.params.publicId);
Promise
.all([allArticles, thisArticle])
.then((result) => {
const articles = result[0];
const article = result[1];
if (!article) {
const error = new Error('Article not found');
error.status = 404;
return next(error);
}
const { page } = req.params;
const pageTitle = module.exports.getSettingsPageTitle(page);
const pageTemplate = `settings-${page}`;
return res.render(pageTemplate, { articles, article, title: `${article.name}: ${pageTitle}` });
})
.catch(next);
},
getUserArticles (userId) {
return cache.get(`getUserArticles_${userId}`, () => Article.findAll({ where: { userId }, order: [['name']] }));
},
getArticleById (publicId) {
return cache.get(`getArticleById_${publicId}`, () => Article.findOne({ where: { publicId } }));
},
getSettingsPageTitle (page) {
return {
edit: 'Edit name, URL',
response: 'Edit email response',
notifications: 'Configure notifications'
}[page];
}
};
</code></pre>
| [] | [
{
"body": "<p>Try to envision how you would want your code to look, then build from there. </p>\n\n<p>For example, I would like for the articles in the sidebar to just be there, so I pretend I have a function I can call that just fixes this for me.</p>\n\n<pre><code>res.render('article', { articles, article, ti... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T00:25:22.570",
"Id": "204211",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"express.js"
],
"Title": "Allowing users to view and manage articles"
} | 204211 |
<p>I did research about binary counting, and wanted to make an application in Java that converts a string to binary code:</p>
<pre><code> /**
* This class converts strings by looping through the characters, gets the
* decimal code for each, then divides the number by 2 untill the quotient is 0
*
* @author Mr Pro Pop
*
*/
public class Binary {
/**
* This function takes a string as a parameter and converts it to binary code
*
* @param string The string to be converted to binary code
* @return The binary code of the input string
*/
public String getBinaryCode(String string) {
if (string.length() == 0)
return null;
char[] characters = string.toCharArray();
StringBuilder result = new StringBuilder();
int number = 0;
for (int i = 0; i < characters.length; i++) {
number = getDecimal(characters[i]);
for (int j = 0; j < 8; j++) {
if (number % 2 == 0) {
result.insert(0, 0);
} else {
result.insert(0, 1);
}
number = (int) (number / 2);
}
result.append(" ");
}
return result.toString();
}
/**
* This function gets the decimal number of a character
*
* @param character The character that we want the decimal value of
* @return The decimal of the character from the ascii table
*/
public int getDecimal(char character) {
for (int i = 0; i <= 255; i++) {
if (character == (char) i) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String string = "a";
Binary b = new Binary();
System.out.println("Binary code for" + string + " is " + b.getBinaryCode(string));
}
}
</code></pre>
<p>Output:</p>
<blockquote>
<p>Binary code for a is 01100001</p>
</blockquote>
<p>Here it works well, however, spacing doesn't work. I do acknowledge that I could simply code this in a different easier method by <code>Integer.toBinaryString(character[i])</code> but tried doing it my way to learn and especially with this method.</p>
<p>Any improvements I could do or anything to pay attention for?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T21:39:02.003",
"Id": "393785",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>I would change</p>\n\n<pre><code>public int getDecimal(char character)\n{\n for (int i = 0; i <= 255; i++)\n {\n if (character == (char) i)\n {\n return i;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>To just</p>\n\n<pre><code>public int getDe... | {
"AcceptedAnswerId": "204215",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T00:27:09.093",
"Id": "204212",
"Score": "5",
"Tags": [
"java",
"reinventing-the-wheel",
"number-systems"
],
"Title": "String to binary converter"
} | 204212 |
<p>Please take a look at the following code. This is my attempt at understanding concurrent applications.</p>
<pre><code>class Program
{
static void Main(string[] args)
{
var consumers = new List<Consumer>
{
new Consumer(1000),
new Consumer(900),
new Consumer(800),
new Consumer(700),
new Consumer(600),
};
var resourceManager = new ResourceManager(consumers);
resourceManager.Process();
}
}
public class Resource
{
private int Capacity { get; set; } = 1000;
private Guid? _currentConsumer;
public int GetCapacity(Guid? id)
{
while (id.HasValue && _currentConsumer.HasValue && id != _currentConsumer)
{
Thread.Sleep(5);
}
_currentConsumer = id;
return Capacity;
}
public void SetCapacity(int cap, Guid id)
{
if (_currentConsumer.HasValue && id != _currentConsumer)
return;
Capacity = cap;
_currentConsumer = null;
}
}
public class Consumer
{
private readonly int _sleep;
private Guid _id = Guid.NewGuid();
public Consumer(int sleep)
{
_sleep = sleep;
}
public void ConsumeResource(Resource resource)
{
var capture = resource.GetCapacity(_id);
Thread.Sleep(_sleep); // some calsulations and stuff
if (resource.GetCapacity(_id) != capture)
throw new SystemException("Something went wrong");
resource.SetCapacity(resource.GetCapacity(_id) - 1, _id);
}
}
public class ResourceManager
{
private readonly List<Consumer> _consumers;
public readonly Resource _resource;
public ResourceManager(List<Consumer> consumers)
{
_consumers = consumers;
_resource = new Resource();
}
public void Process()
{
Parallel.For(0, _consumers.Count, i =>
{
var consumer = _consumers[i];
consumer.ConsumeResource(_resource);
});
}
}
</code></pre>
<p>The lines of code from <code>Consumer::ConsumeResource</code></p>
<pre><code>Thread.Sleep(_sleep); // some calsulations and stuff
if (resource.GetCapacity(_id) != capture)
throw new SystemException("Something went wrong");
</code></pre>
<p>are meant to simulate a real application situation, when there are several consumers that might use the same resource, and which calculations can be broken if resource's state changes in process of calculations (probably by another consumer).</p>
<p>I created a solution for that, using good old <code>Thread.Sleep</code>, therefore locking resource from being used while it is already being used by another consumer, but I feel like there are more correct ways to achieve the same.</p>
<p>Looking forward for your review notes!</p>
<hr>
<hr>
<hr>
<p><strong>EDITED:</strong></p>
<p>After some research about <code>lock</code>s and stuff, I wrote that little helper class:</p>
<pre><code>public class ConcurrentAccessProvider<TObject>
{
private readonly Func<TObject> _getter;
private readonly Action<TObject> _setter;
private readonly object _lock = new object();
public ConcurrentAccessProvider(Func<TObject> getter, Action<TObject> setter)
{
_getter = getter;
_setter = setter;
}
public TObject Get()
{
lock (_lock)
{
return _getter();
}
}
public void Set(TObject value)
{
lock (_lock)
{
_setter(value);
}
}
public void Access(Action accessAction)
{
lock (_lock)
{
accessAction();
}
}
}
</code></pre>
<p>With that, I rewrote <code>Resource</code> and <code>Consumer</code> in order to make it thread-safe:</p>
<pre><code>public class Resource
{
public ConcurrentAccessProvider<int> CapacityAccessProvider { get; }
private int _capacity;
public Resource()
{
CapacityAccessProvider = new ConcurrentAccessProvider<int>(() => _capacity, val => _capacity = val);
}
public int Capacity
{
get => CapacityAccessProvider.Get();
set => CapacityAccessProvider.Set(value);
}
}
public class Consumer
{
private readonly int _sleep;
public Consumer(int sleep)
{
_sleep = sleep;
}
public void ConsumeResource(Resource resource)
{
resource.CapacityAccessProvider.Access(() =>
{
var capture = resource.Capacity;
Thread.Sleep(_sleep); // some calsulations and stuff
if (resource.Capacity != capture)
throw new SystemException("Something went wrong");
resource.Capacity -= 1;
Console.WriteLine(resource.Capacity);
});
}
}
</code></pre>
<p>In the provided example those manipulations effectively kill all possible profits from concurrency, but it is because there is only one <code>Resource</code> instance. In real world application when there are thousands of resources and only several conflicting cases, that will work just fine.</p>
<p>Nevertheless, I would still love to hear about how I could improve the concurrency related code! </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T09:06:42.137",
"Id": "393727",
"Score": "3",
"body": "Can you tell us please how this application works and why it needs the `Capacity` and what it is doing with that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDat... | [
{
"body": "<p>Let us first examine the content of <code>ConsumeResource</code> to understand why some form of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement\" rel=\"nofollow noreferrer\"><code>locking</code></a> (now provided by <code>resource.CapacityAccessP... | {
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T06:58:18.683",
"Id": "204220",
"Score": "1",
"Tags": [
"c#",
".net",
"concurrency",
"locking",
"task-parallel-library"
],
"Title": "Concurrent usage of resources"
} | 204220 |
<p>First time asking a question here.</p>
<p>I made a simple application as a task for a position of a junior programmer, but it did not work out the way I hoped. Nevertheless, I would definitely be interested in code improvement suggestions (sorry for not being more specific, I did not get any feedback by the task creators, so I try to get some here).</p>
<p>Desired functionality description is as follows (see <a href="https://gist.github.com/MichalCab/c1dce3149d5131d89c5bbddbc602777c" rel="nofollow noreferrer">https://gist.github.com/MichalCab/c1dce3149d5131d89c5bbddbc602777c</a>):</p>
<blockquote>
<h1>Create currency converter</h1>
<h2>What to do?</h2>
<ul>
<li>CLI application</li>
<li>web API application</li>
</ul>
<h2>What do we expect?</h2>
<ul>
<li>show us your best</li>
<li>take your time, you have 2 weeks for implementation</li>
<li>real-life production ready project</li>
</ul>
<h2>Limitations</h2>
<ul>
<li>Python</li>
<li>all modules are allowed</li>
<li>no other limitations</li>
</ul>
<h2>Parameters</h2>
<ul>
<li><code>amount</code> - amount which we want to convert - float</li>
<li><code>input_currency</code> - input currency - 3 letters name or currency symbol</li>
<li><code>output_currency</code> - requested/output currency - 3 letters name or currency symbol</li>
</ul>
<h2>Functionality</h2>
<ul>
<li>if output_currency param is missing, convert to all known currencies</li>
</ul>
<h2>Output</h2>
<ul>
<li><p>json with following structure.</p>
<pre><code>{
"input": {
"amount": <float>,
"currency": <3 letter currency code>
}
"output": {
<3 letter currency code>: <float>
}
}
</code></pre></li>
</ul>
<h2>Examples</h2>
<h3>CLI</h3>
<pre><code>./currency_converter.py --amount 100.0 --input_currency EUR --output_currency CZK
{
"input": {
"amount": 100.0,
"currency": "EUR"
},
"output": {
"CZK": 2707.36,
}
}
./currency_converter.py --amount 0.9 --input_currency ¥ --output_currency AUD
{
"input": {
"amount": 0.9,
"currency": "CNY"
},
"output": {
"AUD": 0.20,
}
}
./currency_converter.py --amount 10.92 --input_currency £
{
"input": {
"amount": 10.92,
"currency": "GBP"
},
"output": {
"EUR": 14.95,
"USD": 17.05,
"CZK": 404.82,
.
.
.
}
}
</code></pre>
<h3>API</h3>
<pre><code>GET /currency_converter?amount=0.9&input_currency=¥&output_currency=AUD HTTP/1.1
{
"input": {
"amount": 0.9,
"currency": "CNY"
},
"output": {
"AUD": 0.20,
}
}
GET /currency_converter?amount=10.92&input_currency=£ HTTP/1.1
{
"input": {
"amount": 10.92,
"currency": "GBP"
},
"output": {
"EUR": 14.95,
"USD": 17.05,
"CZK": 404.82,
.
.
.
}
}
</code></pre>
</blockquote>
<p>And the project itself can be found here:
<a href="https://github.com/ciso112/kiwi-currencies" rel="nofollow noreferrer">https://github.com/ciso112/kiwi-currencies</a></p>
<p>I enclose a service.py class which is imported by CLI or web API interface (pls refer to the project link above).</p>
<p><strong>service.py:</strong></p>
<pre><code>import json
import logging
import requests
import requests_cache
# global dictionary filled up at a start of an application
currencies_symbols = {}
requests_cache.install_cache('currency_cache', backend='sqlite', expire_after=21600) #expires after 6 hours
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
#creates an output in JSON format
def create_json(input_currency, output_currency, amount):
logging.info(" FUNC: create_json parameters: inp:%s out:%s am=%s", input_currency, output_currency, amount)
if input_currency == None or output_currency == None:
return "Currency not recognized"
# if input_currency contains ",", it means a currency sign has different currency representations
# f.e.: symbol £ can be used for GIP,SYP,SHP,LBP,EGP,GBP,FKP
if "," in input_currency:
return "Input currency not clearly defined. Possible currencies with such symbol: " + input_currency
dict = {}
dict["input"] = {"amount": float(amount), "currency": input_currency}
# in case no output currencies, prepare to convert to all known currencies
if output_currency == "None":
output_currency = ",".join(list(currencies_symbols.values()))
output_currencies = output_currency.split(",")
for curr in output_currencies:
if not curr == input_currency:
if "output" not in dict:
dict["output"] = {}
dict["output"].update({curr: convert(input_currency, curr, amount)})
return json.dumps(dict, indent=4, separators=(',', ': '))
#input/output can be in a currency symbol format, but we will need
#a three-letter currency name
def sign_to_abbreviation(curr):
logging.info(" FUNC: sign_to_abbreviation parameters: curr:%s", curr)
if len(curr) == 3:
return curr
if curr != "None":
for key, value in currencies_symbols.items():
if curr == key:
curr = value
return curr
return None
return curr
#function run at the start of the program to get the known currencies
#and their symbols
def create_currencies_dict():
if not currencies_symbols:
logging.info(" FUNC: create_currencies_dict")
api_url = "https://free.currencyconverterapi.com/api/v6/currencies"
response = requests.get(api_url)
if response.status_code == 200:
currencies = json.loads(response.content.decode('utf-8'))
for key, value in currencies['results'].items():
if 'currencySymbol' in value.keys():
# because some currencies have the same symbol --> we append values to the same key
if value['currencySymbol'] in currencies_symbols.keys():
new_currency = currencies_symbols.get(value['currencySymbol'])
currencies_symbols[value['currencySymbol']] = value['id'] + "," + new_currency
else:
currencies_symbols[value['currencySymbol']] = value['id']
else:
pass
return currencies_symbols
else:
return None
def convert(input_currency, output_currency, amount):
logging.info(" FUNC: convert parameters: inp:%s out:%s am=%s", input_currency, output_currency, amount)
if len(input_currency) and len(output_currency) == 3:
# returns dictionary with exactly 1 key-value pair
rate = contact_api(input_currency, output_currency)
logging.info(" FUNC: convert rate: %s", rate)
try:
return round(float(amount) * float(rate.get(input_currency+"_"+output_currency)), 2)
except TypeError as e:
print("WARN Check your currencies. Exception: ", e.args)
else:
return "Currency not recognized"
# external converter service
def contact_api(inp, out):
logging.info(" FUNC: contact_api parameters: inp:%s out:%s", inp, out)
api_url_base = 'http://free.currencyconverterapi.com/api/v5/convert'
conversion = inp + "_" + out
payload = {"q": conversion, "compact": "ultra"}
response = requests.get(api_url_base, params=payload)
logging.info(" FUNC: contact_api Loading from CACHE: %s", response.from_cache)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))
else:
return None
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T15:18:14.490",
"Id": "393762",
"Score": "1",
"body": "Welcome to CodeReview! I've included the problem statement for you, but please keep in mind next time that posts should be self-sufficient; while it's okay to link to external re... | [
{
"body": "<p>Sorry to hear that; at a first glance the code looks okay, naming and splitting into functionality looks good, as well as the use of appropriate libraries, but there's a\nnumber of things that could be improved too.</p>\n\n<p>For starters, on the GitHub <code>README.md</code> you're listing a coup... | {
"AcceptedAnswerId": "204236",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T08:44:58.443",
"Id": "204222",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Currency converter - CLI and API"
} | 204222 |
<p>I am looking for a more efficient way than bruteforcing my way through in the following problem in python 3.</p>
<p><strong>Problem statement:</strong></p>
<p><strong>Input:</strong></p>
<ul>
<li><p>An array of n integers, scores, where each score is denoted by scores_j</p></li>
<li><p>An array of q integers, lowerLimits, where each lowerLimits_i denotes
the lowerLimit for score range i.</p></li>
<li><p>An array of q integers, upperLimits, where each upperLimits_i denotes
the upperLimit for score range i.</p></li>
</ul>
<p><strong>Output:</strong> A function that returns an array of Q integers where the value at each index i denotes the number of integers that are in the inclusive range [lowerLimits_i, upperLimits_i].</p>
<p><strong>Constraints</strong>:</p>
<ul>
<li>1 ≤ n ≤ 1e5</li>
<li>1 ≤ scores_j ≤ 1e9 </li>
<li>1 ≤ q ≤ 1e5 </li>
<li>1 ≤ lowerLimits_i ≤ upperLimits_i ≤ 1e9</li>
</ul>
<p>Example:
Given <code>scores= [5, 8, 7]</code>, <code>lowerLimits = [3, 7]</code>, and <code>upperLimits = [9, 7]</code>
I want to check how many of the integers are contained in each interval (inclusive). In this examples: intervals are <code>[3,9]</code> and <code>[7,7]</code>, and the result would be <code>[3, 1]</code>.</p>
<p>My code looks like this:</p>
<pre><code>def check(scores, lowerLimits, upperLimits):
res = []
for l, u in zip(lowerLimits, upperLimits):
res.append(sum([l <= y <= u for y in scores]))
return res
if __name__ == "__main__":
scores= [5, 8, 7]
lowerLimits = [3, 7]
upperLimits = [9, 7]
print(check(scores, lowerLimits, upperLimits))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T10:42:56.340",
"Id": "393730",
"Score": "0",
"body": "This has all hardcoded values. What's your actual problem statement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T10:46:10.427",
"Id": "393... | [
{
"body": "<p>If you sort your values, you can then make an iterator on the sorted list, forward it to the lower limit, count until the first value is reached that is larger than the upper limit and discard all further values.</p>\n\n<p>The sorting will add <span class=\"math-container\">\\$\\mathcal{O}(n\\log ... | {
"AcceptedAnswerId": "204229",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T10:29:33.640",
"Id": "204224",
"Score": "4",
"Tags": [
"python",
"performance",
"interval"
],
"Title": "Counting integers that are within intervals"
} | 204224 |
<p>This is my first hands-on experience with Rust. The program actually works and I really like how it functions. I'm just very interested in what code improvements I could do.</p>
<p>I wrote an application in Rust to help me manage my php environments.
The binary can be run like:</p>
<pre><code>timpack-cli composer install # run composer install
timpack-cli php72 composer install # run composer install with 'php72'
</code></pre>
<p>In the future I want to add in detetection to check what php version should be used. </p>
<pre><code>use std::collections::HashMap;
use std::env;
use std::process::{exit, Command, Output, Stdio};
use std::str;
fn main() {
let input_arguments: Vec<String> = env::args().collect();
let interpreters = ["php", "php70", "php71", "php72"];
let mut interpreter = String::new();
let mut binary = String::new();
// Create a hashmap for the command aliases.
let mut aliases = HashMap::new();
aliases.insert(string("m1"), string("n98-magerun"));
aliases.insert(string("m2"), string("n98-magerun2"));
aliases.insert(string("cc"), string("composer"));
// Start from index one, since first element is the executed binary, which we don't need right now.
for i in 1..input_arguments.len() {
let arg: &str = &input_arguments[i];
if i == 1 {
if interpreters.contains(&arg) {
interpreter = arg.to_string();
} else {
binary = arg.to_string();
}
}
if i == 2 && !interpreter.is_empty() {
binary = arg.to_string();
break;
}
}
// Fail fast, no binary to run.
if binary.is_empty() {
println!("No binary given.");
exit(1);
}
// Resolve alias usage if necessary.
if aliases.contains_key(&binary) {
binary = aliases.get(&binary).unwrap().to_string();
}
let mut executable = binary;
let mut command_arguments_index = 2;
let mut command_arguments = Vec::new();
// Prepare command execution if binary needs to be run with interpreter.
if !interpreter.is_empty() {
let output = Command::new("which")
.arg(executable)
.output()
.expect("Execution of 'which' failed.");
command_arguments.push(output_to_string(output));
executable = interpreter;
command_arguments_index += 1;
}
// Push all remaining stdin args to the new command arguments
for i in command_arguments_index..input_arguments.len() {
&command_arguments.push(input_arguments[i].to_owned());
}
// Run command and wait for status.
let status = Command::new(executable)
.args(command_arguments)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
.expect("Failed to execute command");
// Exit program with status code of command execution.
exit(status.code().unwrap());
}
/**
* Create String from str.
*/
fn string(value: &str) -> String {
return value.to_owned();
}
/**
* Get string from Output type.
*
* @TODO: What about stderr?
*/
fn output_to_string(output: Output) -> String {
return String::from_utf8(output.stdout).unwrap().trim().to_string();
}
</code></pre>
<p>Also, it's <a href="https://github.com/tdgroot/timpack-cli/tree/077af180bde618c82ea9f5d96ef9f6ad24ddd880" rel="nofollow noreferrer">available on Github</a>, if that's easier.</p>
| [] | [
{
"body": "<p>A couple of things pop out at me. </p>\n\n<ol>\n<li><p>Prefer `Iterators‘ over “raw” indexing for loops. </p>\n\n<p>Instead of this</p>\n\n<blockquote>\n<pre><code>for i in 1..input_arguments.len()\n</code></pre>\n</blockquote>\n\n<p>You can just loop over the arguments. </p>\n\n<pre><code>for arg... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T14:17:55.977",
"Id": "204230",
"Score": "5",
"Tags": [
"rust",
"child-process"
],
"Title": "CLI helper in Rust"
} | 204230 |
<p>The challenge was to create a function which performs an in order traversal without using recursion. What I came up with was to use a stack and some clever popping and pushing. I was wondering if there was any way to improve the following solution. Specifically a better way to implement my <code>if(s.empty()) break;</code> line.</p>
<pre><code>vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> ans;
if(root == nullptr) return ans;
s.push(root);
while(!s.empty()){
TreeNode* x = s.top();
s.pop();
if(x != nullptr && (x -> right != nullptr || x -> left != nullptr)){
s.push(x -> right);
s.push(x);
s.push(x -> left);
}else{ //leaf node
if(x != nullptr)
ans.push_back(x -> val);
if(s.empty()) break;
if(s.top() != nullptr)
ans.push_back(s.top() -> val);
s.pop();
}
}
return ans;
}
</code></pre>
| [] | [
{
"body": "<p>Your algorithm does seem to work, but it is very complex. You are pushing <code>nullptr</code> onto the stack when a node has only one child, so you have to check for <code>x != nullptr</code> (which you do), and if the top of the stack is <code>nullptr</code> (which again, you do).</p>\n\n<p>A... | {
"AcceptedAnswerId": "204256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T16:19:41.843",
"Id": "204238",
"Score": "4",
"Tags": [
"c++",
"tree",
"iteration"
],
"Title": "C++ inorder traversal of binary tree"
} | 204238 |
<p>Some time ago I started writing a blockchain implementation for learning purposes. I used <a href="https://medium.com/@lhartikk/a-blockchain-in-200-lines-of-code-963cc1cc0e54" rel="nofollow noreferrer">this article</a> as reference. Originally I wrote the code in C# but recently I have rewritten everything to F#. Please review my F# code, although feel free to comment on C# as well if you feel like it.</p>
<p>Hopefully I will continue with my work and post more questions in the future. I plan to create further functionalities directly in F#.</p>
<p>Anyway, here is my C# code (so it's clear what exactly I wanted to achieve) and the F# equivalent. I have also added some questions at the end of the post.</p>
<h1>Code</h1>
<blockquote>
<p><strong>Helpers.cs</strong></p>
<pre><code>namespace Blockchain
{
public static class IntExtesions
{
public static string ToHex(this int i)
{
return i.ToString("x");
}
}
}
</code></pre>
</blockquote>
<p><strong>Helpers.fs</strong></p>
<pre><code>namespace Blockchain.Core
module Int32 =
let toHex(i: int) = i.ToString("x")
</code></pre>
<blockquote>
<p><strong>Block.cs</strong></p>
<pre><code>using System;
namespace Blockchain.Core
{
public class Block : IEquatable<Block>
{
public Block(int index, string previousHash, DateTime timestamp, string data, string hash, int difficulty, string nonce)
{
Index = index;
PreviousHash = previousHash;
Timestamp = timestamp;
Data = data;
Hash = hash;
Difficulty = difficulty;
Nonce = nonce;
}
public int Index { get; }
public string PreviousHash { get; }
public DateTime Timestamp { get; }
public string Data { get; }
public string Hash { get; }
public int Difficulty { get; }
public string Nonce { get; }
public bool Equals(Block other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Index == other.Index &&
string.Equals(PreviousHash, other.PreviousHash) &&
Timestamp.Equals(other.Timestamp) &&
string.Equals(Data, other.Data) &&
string.Equals(Hash, other.Hash);
}
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == this.GetType() && Equals((Block) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Index;
hashCode = (hashCode * 397) ^ (PreviousHash != null ? PreviousHash.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Timestamp.GetHashCode();
hashCode = (hashCode * 397) ^ (Data != null ? Data.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Hash != null ? Hash.GetHashCode() : 0);
return hashCode;
}
}
}
}
</code></pre>
</blockquote>
<p><strong>Block.fs</strong></p>
<pre><code>namespace Blockchain.Core
open System
type Block(index: int, previousHash: string, timestamp: DateTime, data: string, hash: string, difficulty: int, nonce: string) =
member val Index = index
member val PreviousHash = previousHash
member val Timestamp = timestamp
member val Data = data
member val Hash = hash
member val Difficulty = difficulty
member val Nonce = nonce
override x.Equals(obj) =
match obj with
| :? Block as b -> (index, previousHash, timestamp, data, hash) = (b.Index, b.PreviousHash, b.Timestamp, b.Data, b.Hash)
| _ -> false
override x.GetHashCode() =
let mutable hashCode = index
hashCode <- (hashCode * 397) ^^^ (if previousHash <> null then previousHash.GetHashCode() else 0)
hashCode <- (hashCode * 397) ^^^ timestamp.GetHashCode();
hashCode <- (hashCode * 397) ^^^ (if data <> null then data.GetHashCode() else 0)
hashCode <- (hashCode * 397) ^^^ (if hash <> null then hash.GetHashCode() else 0)
hashCode
</code></pre>
<blockquote>
<p><strong>Blockchain.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Blockchain.Core
{
public class Blockchain
{
public List<Block> Chain { get; private set; } = new List<Block>();
public int Difficulty { get; } = 1;
public Block GenesisBlock => new Block(0, "0", new
DateTime(2000, 1, 1), "Genesis block",
"816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7",
1, 0.ToHex());
public void ReplaceChain(List<Block> newChain)
{
if (newChain.Count > Chain.Count && ChainIsValid(newChain))
{
Chain = newChain;
}
}
public Block GenerateNextBlock(string blockData)
{
var previousBlock = GetLatestBlock();
var nextIndex = previousBlock.Index + 1;
var nextTimestamp = DateTime.Now;
var nonce = 0;
bool hashIsValid = false;
string hexNonce = null;
string nextHash = null;
while (!hashIsValid)
{
hexNonce = nonce.ToHex();
nextHash = CalculateBlockHash(nextIndex, previousBlock.Hash, nextTimestamp, blockData, hexNonce);
if (HashIsValid(nextHash, Difficulty))
{
hashIsValid = true;
}
nonce++;
}
return new Block(nextIndex, previousBlock.Hash, nextTimestamp, blockData, nextHash, Difficulty, hexNonce);
}
public string CalculateBlockHash(int index, string previousHash, DateTime timestamp, string data, string nonce)
{
var sb = new StringBuilder();
using (var hash = SHA256.Create())
{
var value = index +
previousHash +
timestamp.ToString(CultureInfo.InvariantCulture.DateTimeFormat.FullDateTimePattern) +
data +
nonce;
var result = hash.ComputeHash(Encoding.UTF8.GetBytes(value));
foreach (var b in result)
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
public string CalculateBlockHash(Block block)
{
return CalculateBlockHash(block.Index, block.PreviousHash, block.Timestamp, block.Data, block.Nonce);
}
private bool ChainIsValid(IReadOnlyList<Block> chain)
{
if (!chain[0].Equals(GenesisBlock))
{
return false;
}
for (var i = 1; i < chain.Count; i++)
{
if (!BlockIsValid(chain[i], chain[i - 1]))
{
return false;
}
}
return true;
}
private bool BlockIsValid(Block newBlock, Block previousBlock)
{
if (previousBlock.Index + 1 != newBlock.Index)
{
return false;
}
if (previousBlock.Hash != newBlock.PreviousHash)
{
return false;
}
return CalculateBlockHash(newBlock) == newBlock.Hash;
}
private static bool HashIsValid(string hash, int difficulty)
{
var prefix = string.Concat(Enumerable.Repeat('0', difficulty));
return hash.StartsWith(prefix);
}
private Block GetLatestBlock()
{
return Chain.Last();
}
}
}
</code></pre>
</blockquote>
<p><strong>Blockchain.fs</strong></p>
<pre><code>namespace Blockchain.Core
open System
open System.Security.Cryptography
open System.Globalization
open System.Text
type Blockchain() =
let mutable chain = [||] : Block array
member x.Chain
with get() = chain
and private set(value) = chain <- value
member val Difficulty = 1
member x.GenesisBlock =
new Block(0, "0", new DateTime(2000, 1, 1), "Genesis block",
"816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7", 1, Int32.toHex(0))
member x.ReplaceChain(newChain: Block array) =
if newChain.Length > x.Chain.Length && x.ChainIsValid newChain then x.Chain <- newChain
member x.GenerateNextBlock(blockData) =
let previousBlock = x.GetLatestBlock()
let nextIndex = previousBlock.Index + 1
let nextTimestamp = DateTime.Now
let rec generateBlock nonce =
let hexNonce = Int32.toHex(nonce)
let nextHash = x.CalculateBlockHash(nextIndex, previousBlock.Hash, nextTimestamp, blockData, hexNonce)
match x.HashIsValid(nextHash, x.Difficulty) with
| true -> new Block(nextIndex, previousBlock.Hash, nextTimestamp, blockData, nextHash, x.Difficulty, hexNonce)
| false -> generateBlock(nonce + 1)
generateBlock 0
member x.CalculateBlockHash((index: int), previousHash, (timestamp: DateTime), data, nonce) =
use hash = SHA256.Create()
[index.ToString(); previousHash; timestamp.ToString(CultureInfo.InvariantCulture.DateTimeFormat.FullDateTimePattern); data; nonce]
|> String.Concat
|> Encoding.UTF8.GetBytes
|> hash.ComputeHash
|> Encoding.UTF8.GetString
|> (+) "x2"
member x.CalculateBlockHash(block: Block) =
x.CalculateBlockHash(block.Index, block.PreviousHash, block.Timestamp, block.Data, block.Nonce)
member private x.ChainIsValid(chain: Block array) =
match chain.[0].Equals x.GenesisBlock with
| true -> chain |> Seq.pairwise |> Seq.forall (fun (a, b) -> x.BlockIsValid(a, b))
| false -> false
member private x.BlockIsValid(newBlock: Block, previousBlock: Block) =
if previousBlock.Index + 1 <> newBlock.Index then
false
else if previousBlock.Hash <> newBlock.PreviousHash then
false
else
x.CalculateBlockHash newBlock = newBlock.Hash
member private x.HashIsValid((hash: string), difficulty) =
let prefix = (Seq.replicate difficulty '0') |> String.Concat
hash.StartsWith(prefix)
member private x.GetLatestBlock() = Array.last x.Chain
</code></pre>
<h1>Questions</h1>
<p><strong>Block.fs</strong></p>
<ul>
<li>There is a <code>hash</code> function in F# but I couldn't find a definite answer if it can/should be used instead of <code>GetHashCode</code>. Are there some useful good practices?</li>
<li>The <code>Equals</code> override in C# has been generated by ReSharper (as was <code>GetHashCode</code>). Is the F#'s <code>Equals</code> code good enough?</li>
</ul>
<p><strong>Blockchain.fs</strong></p>
<ul>
<li>Does F# have a more suitable data structure for <code>chain</code>?</li>
<li>When invoking functions with a single <code>unit</code> parameter, is it good practice to write parenthesis or to omit them?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T22:22:27.507",
"Id": "393788",
"Score": "2",
"body": "It might be easier to review this if you just posted the f# code. Or maybe consider using quote blocks for the code that isn’t up for review."
},
{
"ContentLicense": "CC ... | [
{
"body": "<p>Below find my comments and suggestions inline in the C# code (I'm not an expert on BlockChains so this is just use of my version of common sense and some programming experience):</p>\n\n<pre><code> public static class IntExtesions\n {\n public static string ToHex(this int i)\n {\n ret... | {
"AcceptedAnswerId": "204303",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T21:27:28.187",
"Id": "204247",
"Score": "6",
"Tags": [
"c#",
"f#",
"blockchain"
],
"Title": "Blockchain implementation in F#: Block and Blockchain"
} | 204247 |
<pre><code>$pageUN = $conn->query("SELECT slug_link FROM bn_publicacao WHERE entry_type = 'pagina' and id = 2")->fetchAll();
$maxlinks = 4;
$pagina = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
$maximo = 12;
$inicio = (($maximo * $pagina) - $maximo);
$stmtUN = "SELECT * FROM bn_publicacao WHERE entry_type = 'post' ORDER BY id DESC LIMIT $inicio, $maximo";
$pUN = $conn->query($stmtUN)->fetchAll();
<?php foreach ($pUN as $UN): ?>
<h3><a href="index.php?post=<?php echo htmlentities($UN['slug_link'], \ENT_QUOTES, 'UTF-8', false); ?>"><?php echo htmlentities($UN['title'], \ENT_QUOTES, 'UTF-8', false); ?></a></h3>
<?php endforeach; ?>
$stmtPG = $conn->prepare("SELECT * FROM bn_publicacao WHERE entry_type = 'post'");
$stmtPG->execute();
$total = $stmtPG->rowCount();
$total_paginas = ceil($total/$maximo);
if($total > $maximo){
echo '<nav aria-label="Page navigation example">';
echo '<ul class="pagination justify-content-center">';
echo '<li class="page-item">';
foreach($pageUN as $PUN){
echo '<a class="page-link text-secondary" href="?p=';
echo htmlentities($PUN['slug_link'], \ENT_QUOTES, "UTF-8", false);
echo '&pagina=1">Primeira</a>';
}
echo '</li>';
for ($i = $pagina - $maxlinks; $i <= $pagina -1; $i++) {
if ($i >= 1) {
echo '<li class="page-item">';
foreach($pageUN as $PUN) {
echo '<a class="page-link text-secondary" href="?p=';
echo htmlentities($PUN["slug_link"], \ENT_QUOTES, "UTF-8", false);
echo '&pagina='.$i.'">'.$i.'</a>';
}
echo '</li>';
}
}
echo '<a class="page-link text-danger">'.$pagina.'</a>';
for ($i= $pagina +1; $i <= $pagina + $maxlinks; $i++) {
if ($i <= $total_paginas) {
echo '<li class="page-item">';
foreach($pageUN as $PUN) {
echo '<a class="page-link text-secondary" href="?p=';
echo htmlentities($PUN["slug_link"], \ENT_QUOTES, "UTF-8", false);
echo '&pagina='.$i.'">'.$i.'</a>';
}
echo '</li>';
}
}
echo '<li class="page-item">';
foreach($pageUN as $PUN) {
echo '<a class="page-link" href="?p=';
echo htmlentities($PUN["slug_link"], \ENT_QUOTES, "UTF-8", false);
echo '&pagina='.$total_paginas.'">Última</a>';
}
echo '</li>';
echo '</nav>';
}
$conn = null;
</code></pre>
<p>I want to know if my pagination is safe and if it's not, where's the problems and what can i do to make it safe.</p>
<p>What you guys think?</p>
<p>Edit:</p>
<pre><code> $stmtPG = $conn->query("SELECT count(*) FROM bn_publicacao WHERE entry_type = 'post'");
$stmtPG->execute();
$total = $stmtPG->fetchColumn();
$total_paginas = ceil($total/$maximo);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T07:43:34.293",
"Id": "393812",
"Score": "0",
"body": "The way you are getting the number of rows it terrible performance-wise and could be potentially dangerous as it could bring your site down.[Instead of selecting all rows only to... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-23T23:01:20.427",
"Id": "204250",
"Score": "1",
"Tags": [
"php",
"html",
"sql",
"pagination"
],
"Title": "Pagination links for a publications list"
} | 204250 |
<p>This is a class for creating and traversing a BST while also getting its depth and width. I feel like this can be factored down into something more elegant and shorter I also feel like the overall design can be improved.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class BinaryNode {
constructor(val) {
this.val = val
this.left = null
this.right = null
}
}
class BinaryTree {
constructor(traversal) {
this.traversal = traversal
}
* inorder(node) {
if (node === undefined) node = this.root;
if (!node) {
return;
}
if (node) {
yield* this.inorder(node.left)
yield node.val;
yield* this.inorder(node.right)
}
}
* preorder(node) {
if (node === undefined) node = this.root;
if (!node) {
return;
}
if (node) {
yield node.val;
yield* this.preorder(node.left)
yield* this.preorder(node.right)
}
}
* postorder(node) {
if (node === undefined) node = this.root;
if (!node) {
return;
}
if (node) {
yield* this.preorder(node.left)
yield* this.preorder(node.right)
yield node.val
}
}
[Symbol.iterator]() {
return this[this.traversal]()
}
length() {
const len = node => {
if (!node) return 0;
return 1 + len(node.left) + len(node.right);
}
return len(this.root)
}
height() {
const hi = node => {
if (!node) return 0;
return 1 + Math.max(hi(node.left), hi(node.right))
}
return hi(this.root)
}
diameter() {
let max = 0;
dfs(this.root)
return max
function dfs(node) {
if (!node) return -1;
let left = dfs(node.left) + 1
let right = dfs(node.right) + 1
max = Math.max(max, left + right)
return Math.max(left, right);
}
}
}
class BST extends BinaryTree {
constructor(traverse) {
super(traverse)
this.string = '';
}
deseralize() {
let data = this.string.split(" ")
return this.deseralizer(data)
}
deseralizer(data) {
let val = data.shift()
if (!data.length || val === '#') {
return null;
} else {
let node = new BinaryNode(val)
node.left = this.deseralizer(data)
node.right = this.deseralizer(data)
return node;
}
}
seralize(node) {
this.root = node;
this.string = ''
this.seralizer(node)
return this.string
}
seralizer(node) {
if (!node) {
this.string += '# '
} else {
this.string += node.val + ' '
this.seralizer(node.left)
this.seralizer(node.right)
}
}
}
var tree = new BST('preorder');
let root = {
"val": 1,
"right": {
"val": 3,
"right": {
"val": 5,
"right": null,
"left": null
},
"left": {
"val": 4,
"right": null,
"left": null
}
},
"left": {
"val": 2,
"right": null,
"left": null
}
}
console.log('seralize: ', tree.seralize(root))
console.log('deseralize: ', tree.deseralize())
for (let i of tree) {
console.log('preorder', i)
}
console.log('preorder', [...tree])</code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T02:47:59.660",
"Id": "204257",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"design-patterns"
],
"Title": "Method for creating and traversing a BST while also getting its depth and width"
} | 204257 |
<p>I request a review of the following web page, especially on the use of semantic elements:</p>
<p><a href="https://jsfiddle.net/SSteven/qt9d2sfw/" rel="nofollow noreferrer">https://jsfiddle.net/SSteven/qt9d2sfw/</a></p>
<p>The HTML5 code is:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Semantic page</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<style>
*
{
box-sizing: border-box;
}
body
{
margin: 0;
}
.clearfix::after
{
content: "";
clear: both;
display: table;
}
.img-container
{
float: left;
width: 50%; /* 2 boxes */
padding: 10px; /* space between the images */
}
nav
{
margin: 0;
padding: 0;
overflow: hidden;
background-color: navy;
}
nav a
{
float: left;
display: inline-block;
color: white;
text-align: center;
padding: 16px;
text-decoration: none;
}
nav a:hover
{
background-color: hsl(240, 100%, 35%);
}
nav a.active
{
color: navy;
background-color: white;
}
.column
{
float: left;
padding: 15px;
}
#sidenav
{
width: 20%;
}
#sidenav ul
{
list-style-type: none;
margin: 0;
padding: 0;
}
#sidenav li a
{
margin-bottom: 4px;
display: block;
padding: 8px;
background-color: hsl(209, 70%, 90%);
text-decoration: none;
color: #444;
}
#sidenav li a:hover
{
background-color: hsl(240, 100%, 80%);
color: white;
}
#sidenav li a.active
{
background-color: #008CBA;
color: white;
}
main
{
width: 80%;
}
table, th, td
{
border: 1px solid grey;
border-collapse: collapse;
}
th, td
{
padding: 10px;
}
footer
{
background-color: #eee;
color: #aaa;
padding: 10px 0 5px 0;
text-align: center;
}
/* Use a media query to add a break point at 800px: */
@media screen and (max-width: 800px)
{
nav li, #sidenav, main
{
/* The width is 100%, when the viewport is 800px or smaller */
width: 100%;
}
}
</style>
</head>
<body>
<header class="clearfix">
<div class="img-container">
<img src="http://www.company.com/Images/Logo.jpg"
alt="[Company logo]"
style="width: 100%;">
</div>
<div class="img-container">
<img src="http://www.company.com/Images/Office.jpg"
alt="[Company Office]"
style="width: 100%;">
</div>
</header>
<nav>
<a href="#AboutUs" class="active">ABOUT US</a>
<a href="#Expertise">EXPERTISE</a>
<a href="#Careers">CAREERS</a>
<a href="#ContactUs">CONTACT US</a>
</nav>
<div class="clearfix">
<aside class="column"
id="sidenav">
<ul>
<li><a href="#WhatWeDo">What we do</a></li>
<li><a href="#WhyUs">Why Us?</a></li>
<li><a href="#Technologies">Technologies</a></li>
</ul>
</aside>
<main class="column">
<article>
<h1>ABOUT THE COMPANY</h1>
<section id="WhatWeDo">
<h2>What we do</h2>
<p>
blah blah blah ...
</p>
<br><hr>
</section>
<section id="WhyUs">
<h2>Why Us?</h2>
<p>More blah ...</p>
<br><hr>
</section>
<section id="Technologies">
<h2>Technologies</h2>
<p>Still more blah ...</p>
</section>
</article>
</main>
</div>
<footer>
<a href = "Terms.html">Terms</a> |
<a href = "Privacy.html">Privacy Policy</a> |
<a href = "TrademarksCopyrights.html">Trademarks &amp; Copyrights</a> |
<a href = "Sitemap.html">Sitemap</a>
<br />
All rights reserved.
</footer>
</body>
</code></pre>
<p></p>
<p>Specifically:</p>
<p>1) At the top, 2 images are supposed to be displayed. (Currently, their alt text is displayed.) I have treated this as the <<strong>header</strong>>. I have used "float: left" to display both images horizontally.</p>
<p>2) The top menu has been displayed in an <<strong>nav</strong>> element, which has been styled along with its sub-elements.</p>
<p>3) The "side menu" has been included in an <<strong>aside</strong>> element.<br>
4) The <<strong>main</strong>> element contains an <<strong>article</strong>> element, which has the main content.</p>
<p>Both the "side menu" and the <<strong>main</strong>> element are floated horizontally.</p>
<p>5) Finally, there is a <<strong>footer</strong>> element.</p>
<p><br>Basically, I'd like to ask:<br>
1) Is the use of the semantic elements appropriate?<br>
2) Is their styling done correctly or is there a better way?<br>
3) I have indented the HTML code. Does this conform to a best practice for markup languages?<br>
4) Review of the CSS code is also requested. I have indented it.</p>
| [] | [
{
"body": "<h1>Character encoding</h1>\n\n<p>As a good practice, the character encoding should be included in the <code>head</code> section of the document before the <code>title</code> element:</p>\n\n<pre><code><meta charset=\"utf-8\">\n<title>SigmaCubes - Home</title>\n</code></pre>\n\n<bl... | {
"AcceptedAnswerId": "204267",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T05:59:57.507",
"Id": "204261",
"Score": "1",
"Tags": [
"css",
"html5"
],
"Title": "Web page's semantic elements"
} | 204261 |
<p>I am a javascript noob. I did this program for the sake of learning javascript in a better way. the code is to display matrix live wallpaper in the browser.
Here is the code</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Hacker Live Wallpaper</title>
</head>
<body>
<div id="wallpaper"></div>
<script type="text/javascript" async="true">
var pageEndCounter = 0;
document.getElementsByTagName('body')[0].style.background = "black";
wallpaper = document.getElementById('wallpaper');
wallpaper.style.color = "green";
setInterval(function() {
pageEndCounter++;
if (pageEndCounter >= 35) {
wallpaper.innerHTML = " ";
pageEndCounter = 0;
}
wallpaper.innerHTML += "</br>";
for (var i = 0; i < 5; i++) {
for (var j = returnRandomInt(2); j > 0; j--) {
wallpaper.innerHTML += "&nbsp";
}
wallpaper.innerHTML += returnRandomInt();
for (var j = returnRandomInt(2); j > 0; j--) {
wallpaper.innerHTML += "&nbsp";
}
}
}, 100);
function returnRandomInt(c) {
if (c == undefined) {
return Math.floor(Math.random() * 100);
} else
return Math.floor(Math.random() * 100 / c);
}
</script>
</body>
</html>
</code></pre>
<p>It stucks to much on chrome and firefox.</p>
<p>Any suggestions to make the code run faster and smoother would be kindly appreciated.</p>
<p>Thanks. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T11:19:32.613",
"Id": "393838",
"Score": "0",
"body": "A) This question is off topic for this site, as it contains code that does not work. B) You have an unterminated `setInterval`, so it never ends."
},
{
"ContentLicense": ... | [
{
"body": "<p>I think you want to print random 5 numbers per line spaced at random distance, Instead of using so many & nbsp; in your code you can use spans/divs with random margins/padding etc. since there will be less number of DOM elements to be parsed it should work much faster.</p>\n\n<pre><code>setInt... | {
"AcceptedAnswerId": "204271",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T11:13:09.347",
"Id": "204269",
"Score": "-1",
"Tags": [
"javascript",
"performance"
],
"Title": "Javascript code to make Matrix wallpaper"
} | 204269 |
<p>I wanted to in the most generic way possible write a method in C# to achieve the following.</p>
<ul>
<li>Take in a string, a set of objects, and a function to access the field of a given object</li>
<li>Look at all of the strings from the fields of these objects to match against provided string</li>
<li>If provided string is not unique in a case insensitive manner, append <code>_x</code> to the end, where <code>x</code> is an incrementing integer until a unique string is found</li>
</ul>
<p>With that in mind, I created this.</p>
<pre><code>private string GetUniqueStringForModel<T>(string originalString, IEnumerable<T> enumerableObjects, Func<T, string> stringFieldFunction) where T : class
{
var uniqueString = originalString;
var duplicateCount = 1;
while (enumerableObjects.Select(stringFieldFunction).ToList().Any(currentString => string.Equals(currentString, uniqueString, StringComparison.InvariantCultureIgnoreCase)))
{
uniqueString = originalString + "_" + duplicateCount++;
}
return uniqueString;
}
</code></pre>
<p>I would rather have not put the <code>ToList()</code> in but when working with Entity Framework it was complaining about doing the string comparison in LINQ (presumably because it couldn't compile it SQL).</p>
<p>Any thoughts or ideas for improvement?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T12:24:25.073",
"Id": "393849",
"Score": "1",
"body": "I guess that `StringComparison.InvariantCultureIgnoreCase` comparison really bothers EF. Can't you handle this on your DB column? A case insensitive collation `SQL_Latin1_General... | [
{
"body": "<p>It will be more efficient to call <code>.ToList()</code> just once:</p>\n\n<pre><code>// ...\nvar list = enumerableObjects.Select(stringFieldFunction).ToList();\nwhile (list.Any(currentString => string.Equals(currentString, uniqueString, StringComparison.InvariantCultureIgnoreCase)))\n{\n un... | {
"AcceptedAnswerId": "204276",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T11:22:04.947",
"Id": "204270",
"Score": "5",
"Tags": [
"c#",
"strings",
"linq",
"generics",
"iterator"
],
"Title": "Take a desired string, iterate through objects to see if it exists in a given field and append a number until a unique string is found"
} | 204270 |
<p>code review friends/teachers! This is a trivial(no dfs/permutations/backtrace required) <a href="https://en.wikipedia.org/wiki/Eight_queens_puzzle" rel="nofollow noreferrer">n queen</a> problem from codeforces: <a href="http://codeforces.com/problemset/gymProblem/100947/B" rel="nofollow noreferrer">B. 8 Queens, Again!!
</a></p>
<h3>input</h3>
<blockquote>
<p>2</p>
<p>A1 B5 C8 D6 E3 F7 G2 H4</p>
<p>C3 E4 C4 E1 C4 F4 A8 G6</p>
</blockquote>
<h3>output</h3>
<blockquote>
<p>Valid</p>
<p>Invalid</p>
</blockquote>
<p>Here is my solution:</p>
<h3>queen.h</h3>
<pre><code>#ifndef QUEEN
#define QUEEN
#include <array>
constexpr int N = 8;
void paint(std::array<std::array<int, N>, N>& m, int x, int y);
bool check(const std::array<std::array<int, N>, N>& m, int x, int y);
#endif
</code></pre>
<h3>queen.cpp</h3>
<pre><code>#include "queen.h"
#include <cstdlib>
#include <iostream>
#include <string>
void paint(std::array<std::array<int, N>, N>& m, int x, int y)
{
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(i == x || j == y || abs(i - x) == abs(j - y))
{
m[i][j] = 1;
}
}
}
}
bool check(const std::array<std::array<int, N>, N>& m, int x, int y)
{
if(m[x][y] == 1)
{
return false;
}
return true;
}
</code></pre>
<h3>testqueen.h</h3>
<pre><code>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this
// in one cpp file
#include "catch.hpp"
#include "queen.h"
#include <iostream>
#include <sstream>
TEST_CASE("eight queens test")
{
std::ostringstream out;
std::streambuf* coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf()); // redirect cout to out
int n;
std::cin >> n;
for(int i = 0; i < n; i++)
{
std::array<std::array<int, 8>, 8> arr{};
std::string s;
for(int j = 0; j < N; j++)
{
std::cin >> s;
auto x = s[0] - 'A', y = s[1] - '1';
if(check(arr, x, y) == true)
{
paint(arr, x, y);
}
else
{
std::cout << "Invalid" << '\n';
for(int k = j + 1; k < N; k++)
{
std::cin >> s;
}
break;
}
if(j == N - 1)
{
std::cout << "Valid" << '\n';
}
}
}
std::cout.rdbuf(coutbuf);
REQUIRE(out.str() == "Valid\nInvalid\n");
}
</code></pre>
<h3>Test:</h3>
<pre><code>~/.../codeforces/100947-B(eight-queen) >>> ./build/test/tests ±[●●][master]
2
A1 B5 C8 D6 E3 F7 G2 H4
C3 E4 C4 E1 C4 F4 A8 G6
===========================================================
All tests passed (1 assertion in 1 test case)
</code></pre>
<p>Please help me to point out any bad habits, better algorithms or better c++ paradigms</p>
<p>Thanks in advance!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T05:30:58.173",
"Id": "393956",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<ul>\n<li><p><strong><code>check</code></strong> features a well-known anti-idiom:</p>\n\n<pre><code>if (condition) {\n return false;\n}\nreturn true;\n</code></pre>\n\n<p>is a long way to say</p>\n\n<pre><code>return !condition;\n</code></pre></li>\n<li><p>Testing for <code>j == N - 1</code> in a... | {
"AcceptedAnswerId": "204291",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T11:56:34.183",
"Id": "204272",
"Score": "2",
"Tags": [
"c++",
"n-queens"
],
"Title": "Codeforces: Queens, Again"
} | 204272 |
<p>I am currently learning to code in ruby. I have created a small program that iterates through a directory of video files and opens one at random. The program is fully functioning (with the odd issue). The aim of my question is to hopefully gain some insight into how I can better structure the code, or simplify the process - I think this will really aid me in my learning!</p>
<p>The random selection method I have created, creates 2 random numbers and converts them to a string:</p>
<pre><code>def random_num_generator
first_num = rand(2..9) #NOTE: generates a random number that is firt name and last name. s
second_num = rand(1..25)
second_num < 10 ? "0#{first_num}0#{second_num}" : "0#{first_num}#{second_num}"
#this returns value that, for example is 0101, relative to whether or not there is a requirement for the additional "0"
#value is equal to a string
end
</code></pre>
<p>The second part of the program iterates through the directory where the video files are stored. As all the file names are written as "0101.mkv" for example, the iteration will then stop and open a file if it is equal to the number generated in the "random_num_generator" method. </p>
<pre><code> def episode_picker
Dir.foreach("/GitHub/videos") do |x|
next if x == "." or x == ".."
if x == "#{random_num_generator}.mkv"
system %{open "/GitHub/videos/#{x}"}
elsif x == "#{random_num_generator}.mp4"
puts "You are watching Season: #{x[0..1]} Episode: #{x[2..3]}!"
system %{open "/GitHub/videos/#{x}"}
elsif x == "#{random_num_generator}.avi"
puts "You are watching Season: #{x[0..1]} Episode: #{x[2..3]}!"
system %{open "/GitHub/videos/#{x}"}
end
end
end
</code></pre>
<p>Any advice is greatly appreciated and a big thanks in advance!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T12:38:08.877",
"Id": "393858",
"Score": "0",
"body": "Please state what your question does in the title, not what you are looking for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T12:54:33.413",
... | [
{
"body": "<p>I'll try to help you on how you could improve your code here.\nKeep in mind that I have no idea what is your current level in programming in general. You state that you started learning ruby, but you don't tell us about other languages.</p>\n\n<h1>Random number generator</h1>\n\n<p>This method is ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T12:06:29.403",
"Id": "204273",
"Score": "3",
"Tags": [
"ruby",
"file-system",
"iteration"
],
"Title": "Short Ruby program that opens a random video file from a directory"
} | 204273 |
<p>I wrote this program to help me understand how BFS and Queues work. (Also DFS if I replace the queue with a stack).</p>
<p>It works, but I'm curious how well I implemented the algorithm.</p>
<p>Are there any obvious improvements?</p>
<p>For example, I notice that there are duplicate values in the Queue. I understand that I should avoid visiting already visited positions. However the queue contains only "prospective" positions which are yet to be visited. Should I modify the algorithm to not enqueue positions which it already contains?</p>
<p>My agenda is to understand Data Structures and Algorithms and write reasonable quality code to implement the basic concepts.</p>
<pre><code>from os import system
from random import randint
class Queue:
def __init__(self):
self.list = []
def enqueue(self, item):
self.list.append(item)
def dequeue(self):
temp = self.list[0]
del self.list[0]
return temp
def isEmpty(self):
return not self.list
def empty(self):
self.list = []
def create_maze(n):
maze = []
for row in range(n):
row = []
for col in range(n):
if randint(0,3) == 0:
row.append(1)
else:
row.append(0)
maze.append(row)
maze[0][0] = 0
maze[n-1][n-1] = 2
return maze
def print_maze(maze):
for row in maze:
print((row))
def is_valid_pos(tup):
(col, row) = tup
if col < 0 or row < 0 or col >= MAZE_SIZE or row >= MAZE_SIZE :
return False
return maze[row][col] == 0 or maze[row][col] == 2
def solve(maze, start):
q = Queue()
(col,row) = start
print('Enqueueing ({},{})'.format(col,row))
q.enqueue((col,row))
while not q.isEmpty():
print('Queue contents: {}'.format(q.list))
input('Press Enter to continue: ')
print('Dequeueing')
(col, row) = q.dequeue()
print('Current position: ({}, {})'.format(col,row))
if maze[row][col] == 2:
print('Goal reached at ({}, {})'.format(col,row))
return
if maze[row][col] == 0:
print('Marking ({}, {})'.format(col,row))
maze[row][col] = 3
print_maze(maze)
print('Enqueueing coordinates of valid positions in 4 directions.')
if is_valid_pos((col+1, row)): q.enqueue((col+1, row))
if is_valid_pos((col, row+1)): q.enqueue((col, row+1))
if is_valid_pos((col-1, row)): q.enqueue((col-1, row))
if is_valid_pos((col, row-1)): q.enqueue((col, row-1))
print("Goal can't be reached.")
while True:
system('cls')
maze = create_maze(4)
MAZE_SIZE = len(maze)
solve(maze, (0,0))
input('Press Enter to restart: ')
</code></pre>
| [] | [
{
"body": "<p>Feedback in mostly top-down order</p>\n\n<hr>\n\n<p><code>\"\"\"Doc strings\"\"\"</code>. You should get in the habit of adding these at the top of your file, the top of every class, and the top of every (public) function.</p>\n\n<hr>\n\n<p><code>class Queue</code>. I'm certain you know that Pyt... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T12:53:40.800",
"Id": "204275",
"Score": "3",
"Tags": [
"python",
"algorithm",
"queue"
],
"Title": "Non-recursive BFS Maze Solving with Python"
} | 204275 |
<pre><code>double time_in_seconds() {
std::chrono::time_point<std::chrono::system_clock,std::chrono::microseconds> tp = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now());
auto tmp = std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch());
std::time_t time_micro = tmp.count();
return time_micro / 1000000.0;
}
</code></pre>
<p>Here C++11 <code>chrono</code> is used to be able run on multi platform. Use <code>high_resolution_clock</code> to hope to get precision of micro second. <code>std::time_t</code> should be enough to hold this number.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T15:28:51.563",
"Id": "393878",
"Score": "1",
"body": "Welcome to Code Review! You might get better reviews if you show a little more of the context, such as a sample `main` that shows how you intend to use this function."
},
{
... | [
{
"body": "<p>Leveraging the standard library is the best way to obtain cross-platform code, so you're on the right track. The problem is that your doesn't compile with one of the compilers I've tested it with (clang 8). Using auto would make your code simpler and avoid problematic conversions:</p>\n\n<pre><cod... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T13:16:49.560",
"Id": "204277",
"Score": "2",
"Tags": [
"c++",
"c++11",
"datetime"
],
"Title": "A cross platform function to get current time in seconds with precision of micro second"
} | 204277 |
<p>I'm struggling with organizing my code regarding 'best practise'. In particular how I link a class with its collection class.</p>
<p>I've 2 classes:</p>
<pre><code>class car
{
private $color;
private $model;
private $speed;
public function getColor() {}
public function setColor() {}
public function getModel() {}
public function setModel() {}
public function getSpeed() {}
public function setSpeed() {}
}
class carLoader
{
public function loadAllCars()
{
// load all cars from the database
...
// iterate through the result and create an object for each car
$allCars = array();
foreach ($result as $carName => $carData) {
$allCars[$carName] = $this->createCar($carData);
}
return $allCars;
}
private function createCar(array $carData)
{
$car = new Car();
$car->setColor($carData['color']);
$car->setModel($carData['model']);
$car->setSpeed($carData['speed']);
return $car;
}
}
</code></pre>
<p>Now I have an array with all car objects. So far so good. However, I am not sure whats the best approach to save manipulated properties in the database. Or in other words, how to connect the property class 'car' to the database because (as far as I've learned) it should NOT contain any database queries but only the properties.</p>
<p>One solution I came up with is to add a collection function which holds an object of a new 'collection' class. So my solution would look like:</p>
<pre><code>class car
{
private $color;
private $model;
private $speed;
private $collection;
public function getColor() { return $this->color; }
public function setColor() { return $this->getCollection()->saveColor($value); }
public function getModel() { return $this->model; }
public function setModel() { return $this->getCollection()->saveModel($value); }
public function getSpeed() { return $this->speed; }
public function setSpeed() { return $this->getCollection()->saveSpeed($value); }
public function getCollection()
{
return $this->collection;
}
public function setCollection($collection)
{
$this->collection = $collection
}
class carLoader
{
public function __construct(DbManager $pdo)
{
$this->pdo = $pdo;
}
public function loadAllCars()
{
// load all cars from the database
...
// iterate through the result and create an object for each car
$allCars = array();
foreach ($result as $carName => $carData) {
$allCars[$carName] = $this->createCar($carData);
}
return $allCars;
}
private function createCar(array $carData)
{
$car = new Car();
$car->setColor($carData['color']);
$car->setModel($carData['model']);
$car->setSpeed($carData['speed']);
$car->setCollection($this-getCollection());
return $car;
}
private function getCollection()
{
if ($this->carCollection === null) {
$this->carCollection = new CarCollection($this->pdo);
}
return $this->carCollection;
}
}
class carCollection()
{
public function __construct(DbManager $pdo)
{
$this->pdo = $pdo;
}
public function getCollection()
{
// logic to save the data in the database
}
}
</code></pre>
<p>Is this a 'good' way to do it if I do need to work with the array of car objects? How else should I save new values (color, speed, model) in the database?</p>
<p>Thank you very much</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T15:36:41.790",
"Id": "393883",
"Score": "1",
"body": "I have no idea about 'best practises', but what I would do is create another class containing the methods to get and set properties in the database: `public function getProperty(... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T13:21:08.120",
"Id": "204278",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"collections"
],
"Title": "How to connect a propery class/object with a collection (its database class)?"
} | 204278 |
<p>I've built a fairly simple tip calculator. What I have so far is a bunch of functions to calculate each tip amount and calling each with <code>eventListener</code>.</p>
<p>It works however trying to see if there's a better approach that would modularize the code. I'm thinking possibilities include passing functions as arguments or functions calling other functions but can't figure it out yet.</p>
<p>Here's the code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var tenPerBtn = document.querySelector('.tenPercent');
var fifteenPerBtn = document.querySelector('.fifteenPercent');
var twentyPerBtn = document.querySelector('.twentyPercent');
var customPerBtn = document.querySelector('.customTipBtn');
var bill = document.getElementById('billInput');
var tipSuggestion = document.getElementById('tipAmount');
function calcTen() {
var billInput = bill.value;
var tipAmount = billInput * .1;
tipSuggestion.innerHTML = 'A ten percent tip would equal $' + tipAmount;
}
function calcFifteen() {
var billInput = bill.value;
var tipAmount = billInput * .15;
tipSuggestion.innerHTML = 'A fifteen percent tip would equal $' + tipAmount;
}
function calcTwenty() {
var billInput = bill.value;
var tipAmount = billInput * .2;
tipSuggestion.innerHTML = 'A twenty percent tip would equal $' + tipAmount;
}
function calcCustom() {
var billInput = bill.value;
var customTipAmount = document.querySelector('#customTip').value;
var tipAmount = billInput * customTipAmount;
tipSuggestion.innerHTML = 'A ' + customTipAmount + ' percent tip would equal $' + tipAmount;
}
tenPerBtn.addEventListener('click', calcTen)
fifteenPerBtn.addEventListener('click', calcFifteen)
twentyPerBtn.addEventListener('click', calcTwenty)
customPerBtn.addEventListener('click', calcCustom)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Bill Amount: </label><input type="text" id="billInput">
<br><br>
<button class="tenPercent">Tip 10%</button>
<br>
<button class="fifteenPercent">Tip 15%</button>
<br>
<button class="twentyPercent">Tip 20%</button>
<br><br>
<label>Custom Tip Percentage: </label><input type="text" id="customTip"> <button class="customTipBtn">Tip Custom Amount</button>
<br><br>
<p id="tipAmount"></p></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<ul>\n<li>Eliminate code duplication by using function parameters (numbers in function name is usually a bad smell )</li>\n<li>Separate calculating/processing data and DOM manipulations</li>\n</ul>\n\n<h2>My suggested solution:</h2>\n\n<pre><code>function calcTip(bill, percent) {\n return bill * p... | {
"AcceptedAnswerId": "204329",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T15:52:07.873",
"Id": "204290",
"Score": "6",
"Tags": [
"javascript",
"calculator"
],
"Title": "Simple JavaScript tip calculator"
} | 204290 |
<p>I am working on a blog with PHP, specially in order to practice OOP.</p>
<p>Since the blogging system will handle users, i thought that a Validation class would be a good idea in order to not repeat code for both login and signup validation.</p>
<p>So far it works, but as you may notice, i'm using static methods from other class here, the UsersTable class, and i feel this is a "code smell".</p>
<p>validation.php:
<pre><code>class Validation
{
private static $emailValidationRegex = '/^[^\s@]+@[^\s@]+\.[^\s@]+/';
public static function fieldIsEmpty($field)
{
return empty($field);
}
public static function validateEmail($email)
{
return preg_match(self::$emailValidationRegex, $email);
}
public static function usernameExists($username)
{
if (UsersTable::getUserByUsername($username))
{
return true;
}
return false;
}
public static function emailExists($email)
{
if (UsersTable::getUserByEmail($email))
{
return true;
}
return false;
}
public static function redirectUser($validUser)
{
if ($validUser)
{
header('Location: ../index.php');
}
else
{
header('Location: ../login-page.php');
}
}
public static function loginValidation($usernameOrEmail, $password)
{
$validUser = false;
if (!self::fieldIsEmpty($usernameOrEmail) && !self::fieldIsEmpty($password))
{
$user = null;
if (self::validateEmail($usernameOrEmail))
{
if (self::emailExists($usernameOrEmail))
{
$user = UsersTable::getUserByEmail($usernameOrEmail);
}
}
else
{
if (self::usernameExists($usernameOrEmail))
{
$user = UsersTable::getUserByUsername($usernameOrEmail);
}
}
if ($user !== null)
{
if (password_verify($password, $user['password']))
{
$validUser = true;
}
}
}
self::redirectUser($validUser);
}
public static function signupValidation($email, $username, $password,
$passwordConfirmation, $name)
{
echo 'Working so far!';
}
}
</code></pre>
<p>users-table.php:
<pre><code>class UsersTable
{
public static function getAllUsers()
{
$statement = "SELECT * FROM `users`";
$query = Database::query($statement);
if ($query)
{
return $query->fetchAll(PDO::FETCH_ASSOC);
}
}
public static function getUserByID($id)
{
$statement = "SELECT * FROM `users` WHERE `id` = '$id' "
. "LIMIT 1";
$query = Database::query($statement);
if ($query)
{
return $query->fetch(PDO::FETCH_ASSOC);
}
}
public static function getUserByEmail($email)
{
$statement = "SELECT * FROM `users` WHERE `email` = '$email' "
. "LIMIT 1";
$query = Database::query($statement);
if ($query)
{
return $query->fetch(PDO::FETCH_ASSOC);
}
}
public static function getUserByUsername($username)
{
$statement = "SELECT * FROM `users` WHERE `username` = '$username' "
. "LIMIT 1";
$query = Database::query($statement);
if ($query)
{
return $query->fetch(PDO::FETCH_ASSOC);
}
}
public static function addUser($name, $email, $username, $password)
{
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$statement = "INSERT INTO `users` (`name`, `email`, `username`, "
. " `password`) VALUES ('$name', '$email', '$username', "
. "'$hashedPassword')";
$query = Database::query($statement);
}
}
</code></pre>
<p>login.php:
<pre><code>require_once('../config.php');
require_once('database.php');
require_once('users-table.php');
require_once('validation.php');
Database::connect();
Validation::loginValidation($_POST['username-email'], $_POST['password']);
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>i'm using static methods from other class here, the UsersTable class, and i feel this is a \"code smell\".</p>\n</blockquote>\n\n<p>Some people hate static methods, others prize them for the micro-optimization... if your method is idempotent (or, in the case of a query, not depende... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T19:21:58.473",
"Id": "204299",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"validation",
"authentication"
],
"Title": "PHP login/signup validation class"
} | 204299 |
<p>I'm trying to write game server core that I can easy extend to use for various games. From simple online Blackjack session, to MMORPG. Long story short, I came up with this solution:</p>
<p>Firstly, we have common classes for both Server and Client. Those are simple data structures, probably will need to wrap them with <code>Builders</code>, but for this presentation I guess I can skip this. </p>
<pre><code>public abstract class DataPacket implements Serializable {
}
final public class LoginRequest extends DataPacket implements Serializable {
private final String accountNumber;
private final String password;
public LoginRequest(String accountNumber, String password) {
this.accountNumber = accountNumber;
this.password = password;
}
public String getAccountNumber() {
return accountNumber;
}
public String getPassword() {
return password;
}
}
final public class LoginResponse extends DataPacket implements Serializable {
private final String message;
public LoginResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
</code></pre>
<p>Now lets go to the core, <code>ServerController</code>, which is kind of Server API, that has all the public methods. Config is just a <code>Property</code> loader class, in the future, probably will change to *.ini file instead of *.property, so I'm using DI here. </p>
<pre><code>public class ServerController {
private Config config;
private Dispatcher dispatcher;
@Autowired
public ServerController(Config config) {
this.config = config;
dispatcher = new Dispatcher(config.getPort(), config.getMaxHosts());
}
public void start() {
dispatcher.start();
}
public void stop() {
dispatcher.stopAccepting();
}
}
</code></pre>
<p>Then there is <code>Dispatcher</code> that listen for incoming connections and creates new <code>ServerWorker</code> for each one.</p>
<pre><code>class Dispatcher extends Thread {
private ServerSocket serverSocket;
private List<ServerWorker> serverWorkers;
private Status status;
private final int maxHosts;
Dispatcher(int port, int maxHosts) {
serverWorkers = new ArrayList<>();
status = Status.DOWN;
this.maxHosts = maxHosts;
try {
this.serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
status = Status.UP_ACCEPTING;
while(status == Status.UP_ACCEPTING) {
acceptIncomingConnections();
}
}
void stopAccepting() {
status = Status.UP_NOT_ACCEPTING;
this.interrupt();
}
void disconnectClient(ServerWorker worker) {
serverWorkers.remove(worker);
worker.interrupt();
}
private void acceptIncomingConnections() {
try {
Socket socket = serverSocket.accept();
ServerWorker worker = new ServerWorker(socket, this);
worker.start();
serverWorkers.add(worker);
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>Which leads us to <code>ServerWorker</code> which is listening for requests and redirecting them to further process.</p>
<pre><code>class ServerWorker extends Thread {
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
private Dispatcher dispatcher;
ServerWorker(Socket socket, Dispatcher dispatcher){
this.dispatcher = dispatcher;
try {
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
listen();
} catch (IOException | NullPointerException e) {
e.printStackTrace();
dispatcher.disconnectClient(this); //Once Client disconnects, this Exception is thrown
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void listen() throws IOException, ClassNotFoundException {
DataPacket dataPacket;
while((dataPacket = (DataPacket)inputStream.readObject()) != null ) {
process(dataPacket);
}
}
private void process(DataPacket dataPacket) throws IOException {
Optional<Event> event = EventFactory.getEvent(dataPacket);
event.ifPresent(e -> {
e.process();
send(e.getProcessedData());
});
}
private void send(DataPacket dataPacket) throws IOException {
outputStream.flush();
outputStream.writeObject(dataPacket);
}
}
</code></pre>
<p>And that leaves us with final part, <code>Events</code>. Not sure if I can avoid using <code>instanceof</code> here, since it translates incoming data into event, which are 2 different objects. </p>
<pre><code>public interface Event {
void process();
DataPacket getProcessedData();
}
public class EventFactory {
public static Optional<Event> getEvent(DataPacket dataPacket){
if(dataPacket instanceof LoginRequest) {
return Optional.of(new LoginEvent((LoginRequest) dataPacket));
}
return Optional.empty();
}
}
public class LoginEvent implements Event {
private LoginRequest request;
private LoginResponse response;
LoginEvent(LoginRequest loginRequest) {
request = loginRequest;
}
@Override
public void process() {
if(isValid(request.getAccountNumber(), request.getPassword())) {
response = new LoginResponse("You successfully logged in!");
} else {
response = new LoginResponse("Something went wrong...");
}
}
@Override
public DataPacket getProcessedData() {
return response;
}
private boolean isValid(String accountNumber, String password) {
return true;
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I'm trying to write game server core that I can easy extend to use for various games. From simple online Blackjack session, to MMORPG.</p>\n</blockquote>\n\n<p>I'm fairly certain, that won't work as easy as you think. It's a huge difference in requirements between exchanging data o... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T19:35:57.797",
"Id": "204300",
"Score": "0",
"Tags": [
"java",
"socket",
"server"
],
"Title": "Game Server application"
} | 204300 |
<p>I needed to make a base64 file encoder where you can control the read buffer size. This is what I came up with and it's quite fast. It might be able to be simpler but still maintain its performance characteristics. Any suggestions?</p>
<pre><code>def chunked_base64_encode(input, input_size, output, read_size=1024):
"""
Read a file in configurable sized chunks and write to it base64
encoded to an output file.
This is an optimization over ``base64.encode`` which only reads 57
bytes at a time from the input file. Normally this is OK if the
file in question is opened with ``open`` because Python will
actually read the data into a larger buffer and only feed out
57 bytes at a time. But if the input file is something like a
file stream that's read over the network, only 57 bytes will be
read at a time. This is very slow if the file stream is not
buffered some other way.
This is the case for MongoDB GridFS. The GridOut file returned by
GridFS is not a normal file on disk. Instead it's a file read in
256 KB chunks from MongoDB. If you read from it 57 bytes at a time,
GridFS will read 256 KB then make lots of copies of that chunk
to return only 57 bytes at a time. By reading in chunks equal
to the GridFS chunk size, performance is 300 times better.
Performance comparison:
File size 10 MB
Save to MongoDB took 0.271495819092 seconds
Fast Base 64 encode (chunk size 261120) took 0.250380992889 seconds
Base 64 encode (chunk size 57) took 62.9280769825 seconds
File size 100 MB
Save to MongoDB took 0.994009971619 seconds
Fast Base 64 encode (chunk size 261120) took 2.78231501579 seconds
Base 64 encode (chunk size 57) took 645.734956026 seconds
For regular files on disk, there is no noticeable performance gain
for this function over ``base64.encode`` because of Python's built
in buffering for disk files.
Args:
input (file): File like object (implements ``read()``).
input_size (int): Size of file in bytes
output (file): File like object (implements ``write()``).
read_size (int): How many bytes to read from ``input`` at
a time
"""
# 57 bytes of input will be 76 bytes of base64
chunk_size = base64.MAXBINSIZE
base64_line_size = base64.MAXLINESIZE
# Read size needs to be in increments of chunk size for base64
# output to be RFC 3548 compliant.
read_size = read_size - (read_size % chunk_size)
num_reads = int(ceil(input_size / float(read_size)))
# RFC 3548 says lines should be 76 chars
base64_lines_per_read = read_size / chunk_size
input.seek(0)
for r in xrange(num_reads):
is_last_read = r == num_reads - 1
s = input.read(read_size)
if not s:
# If this were to happen, then ``input_size`` is wrong or
# the file is corrupt.
raise ValueError(
u'Expected to need to read %d times but got no data back on read %d' % (
num_reads, r + 1))
data = b2a_base64(s)
if is_last_read:
# The last chunk will be smaller than the others so the
# line count needs to be calculated. b2a_base64 adds a line
# break so we don't count that char
base64_lines_per_read = int(ceil((len(data) - 1) / float(base64_line_size)))
# Split the data chunks into base64_lines_per_read number of
# lines, each 76 chars long.
for l in xrange(base64_lines_per_read):
is_last_line = l == base64_lines_per_read - 1
pos = l * base64_line_size
line = data[pos:pos + base64_line_size]
output.write(line)
if not (is_last_line and is_last_read):
# The very last line will already have a \n because of
# b2a_base64. The other lines will not so we add it
output.write('\n')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-28T04:35:21.463",
"Id": "394396",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>The first thing I notice is that you are using Python2. This is almost certainly wrong. Python3 is faster for most applications, and Python2 is going EOL in 15 months.</p>\n\n<p>Other than that, my main comments would be that this would probably benefit from <code>async</code> as this is an IO hea... | {
"AcceptedAnswerId": "204545",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T19:47:33.783",
"Id": "204302",
"Score": "5",
"Tags": [
"python",
"python-2.x",
"base64"
],
"Title": "Python optimized base64 writer for streamed files"
} | 204302 |
<p>I'm simulating my real-world application by using a really simple demo app here, but it has the same concept. <strong>The question is <code>MVVM Light Toolkit</code> specific, as the purpose of my project is to learn the workings of the toolkit.</strong></p>
<p>Let's say I have a <code>Main</code> form, inside which I have a <code>UserControl</code>. The <code>Main</code> has a stand-alone <code>TextBox</code>, and the user control itself contains a single <code>TextBox</code>. It would look something like this:</p>
<p><a href="https://i.stack.imgur.com/6YckR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6YckR.png" alt="enter image description here"></a></p>
<p>The goal is this: if the user types on the <code>Main</code> form <code>TextBox</code>, I want to see the text displayed on the <code>UserControl</code>'s <code>TextBox</code>, and wise-versa, in real time. I'm using the <code>TextChanged</code> event.</p>
<h2>UserControl XAML</h2>
<p>When all the unnecessary clutter is removed my <code>UserControl</code> XAML looks like this:</p>
<pre><code><UserControl ...
d:DesignHeight="80" d:DesignWidth="280">
<Grid Background="LightSteelBlue">
<TextBox Name="TxtDisplay" Background="PaleGreen" Grid.Row="1"
Width="250" Height="32"
TextChanged="TxtDisplay_TextChanged"
Text="{Binding Display, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}">
</TextBox>
</Grid>
</UserControl>
</code></pre>
<h2>UserControl Code Behind</h2>
<p>I have a <code>RoutedEvent</code> so I can bubble up the <code>TextChanged</code> event, and a <code>DependancyProperty</code> to send the content of the <code>TextBox</code> to the <code>Main</code>.</p>
<pre><code>public partial class TextDisplay : UserControl
{
public TextDisplay()
{
InitializeComponent();
}
public event RoutedEventHandler RoutedTextChanged;
public static readonly DependencyProperty DisplayProperty = DependencyProperty.Register("Display", typeof(string), typeof(TextDisplay));
public string Display
{
get { return (string)GetValue(DisplayProperty); }
set
{
SetValue(DisplayProperty, value);
}
}
private void TxtDisplay_TextChanged(object sender, TextChangedEventArgs e)
{
Display = TxtDisplay.Text;
RoutedTextChanged?.Invoke(this, new RoutedEventArgs());
}
}
</code></pre>
<h2>Main Window XAML</h2>
<p><code>DataContext</code> is bound to the <code>MainViewModel</code>.</p>
<pre><code><Window ...
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid x:Name="LayoutRoot">
<TextBox Grid.Row="0" Name="TxtInput" Width="200" Height="32"
Text="{Binding MainDisplay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding MainDisplayTextChangedCommand}"
CommandParameter="{Binding ElementName=TxtInput, Path=Text}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<uc:TextDisplay Grid.Row="1" Width="300" Height="80"
Display="{Binding UCDisplayText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="RoutedTextChanged">
<i:InvokeCommandAction Command="{Binding UCDisplayTextChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</uc:TextDisplay>
</Grid>
</Window>
</code></pre>
<h2>MainViewModel</h2>
<pre><code>public class MainViewModel : ViewModelBase
{
public const string MainDisplayPropertyName = "MainDisplay";
private string _mainDisplay = string.Empty;
public string MainDisplay
{
get { return _mainDisplay; }
set
{
if (_mainDisplay == value) { return; }
_mainDisplay = value;
RaisePropertyChanged(() => MainDisplay);
}
}
public const string UCDisplayTextPropertyName = "UCDisplayText";
private string _ucDisplayText = string.Empty;
public string UCDisplayText
{
get { return _ucDisplayText; }
set
{
if (_ucDisplayText == value) { return; }
_ucDisplayText = value;
RaisePropertyChanged(() => UCDisplayText);
}
}
public MainDisplayTextChanged MainDisplayTextChangedCommand { get; private set; }
public UCDisplayTextChanged UCDisplayTextChangedCommand { get; private set; }
public MainViewModel(IDataService dataService)
{
MainDisplayTextChangedCommand = new MainDisplayTextChanged(this);
UCDisplayTextChangedCommand = new UCDisplayTextChanged(this);
}
public void MainTextChanged()
{
UCDisplayText = MainDisplay;
}
public void UCTextChanged()
{
MainDisplay = UCDisplayText;
}
}
</code></pre>
<h2>TextChanged Commands</h2>
<p>The two <code>TextChanged</code> command classes derive from <code>ICommand</code> and is designed according to the pattern shown in the <a href="http://pluralsight.com/training/Courses/TableOfContents/mvvm-light-toolkit-fundamentals" rel="nofollow noreferrer"><code>Official MVVM Toolkit Tutorial</code> on PluralSight</a>.</p>
<pre><code>public class MainDisplayTextChanged : ICommand
{
protected readonly MainViewModel _owner;
public MainDisplayTextChanged(MainViewModel owner)
{
_owner = owner;
_owner.PropertyChanged += (s, e) =>
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
};
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_owner.MainTextChanged();
}
}
public class UCDisplayTextChanged : ICommand
{
protected readonly MainViewModel _owner;
public UCDisplayTextChanged(MainViewModel owner)
{
_owner = owner;
_owner.PropertyChanged += (s, e) =>
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
};
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_owner.UCTextChanged();
}
}
</code></pre>
<h2>QUESTIONS</h2>
<p>Now this works, but I have this feeling that this might not quite be the right way to go about this. Particularly:</p>
<ol>
<li>In <code>TextDisplay.xaml.cs</code> code's <code>TextChanged</code> event, if I don't do <code>Display = TxtDisplay.Text;</code> then the <code>DataBinding</code> alone doesn't update the <code>DependancyProperty</code> value. What am I doing wrong?</li>
<li>Can I avoid using <code>DependancyProperty</code> altogether? I know I can bind to a property of the <code>DataContext</code> and have changes reflected instantly, but I'm looking for a decoupled solution where the `UserControl can stand on it's own.</li>
<li>Is there a better design for the two <code>ICommand</code> derivative classes?</li>
<li>Any other comments/suggestions are also welcome.</li>
</ol>
<h2>EDIT</h2>
<p>Download the entire project <a href="https://github.com/sachintha81/PublicDownloads/blob/master/MvvmLightDepProp.zip" rel="nofollow noreferrer">here</a>.</p>
<p>Thank you!</p>
| [] | [
{
"body": "<h3>Simplifications</h3>\n\n<p>What you want to do can be achieved with data-binding alone, you don't need all those commands.</p>\n\n<ol>\n<li><p>Since both text-boxes should display the same content, we only need one string property in <code>MainViewModel</code>:</p>\n\n<pre><code>private string _m... | {
"AcceptedAnswerId": "204392",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-24T23:59:04.527",
"Id": "204310",
"Score": "1",
"Tags": [
"c#",
"wpf",
"mvvm",
"databinding"
],
"Title": "MVVMLight Toolkit Data Binding Technique"
} | 204310 |
<p>I've been coding a Gameboy emulator in C for some time(seems like a common project for people). It's reasonably functional and has some MBC1 support, but has some minor graphical glitches still. I've coded on and off for a long time, but consider myself still very much an amateur and have no professional experience.</p>
<p>The code is very much a work in progress. I realize the error-handling is lax.
I'm just looking for some general critiques. I would like to try and start a career in software development, but don't have the benefit of a degree. Would something like this be reasonable for a portfolio and to put on a resume? If not, are there parts of the code that stick out and say "unprofessional"?</p>
<p>This is the emulation code of the project. The rest of the code, including I/O and screen drawing support, is <a href="https://github.com/bcrew1375/Miracle-GB/tree/2da4ed168b420511a62f2fc66216bbdeb57f3ec7" rel="noreferrer">on GitHub</a>.</p>
<pre><code>#include <stdio.h>
#include <conio.h>
#include <sdl.h>
#include <windows.h>
#include "define.h"
struct Emulation
{
struct MemoryMap
{
unsigned char romBank0[0x4000]; // Primary rom bank from 0x0000-0x3FFF.
unsigned char romBank1[0x4000]; // Secondary rom bank from 0x4000-0x7FFF (Switchable on MBC carts).
unsigned char videoRam[0x2000]; // The Gameboy's 8 KB video RAM from 0x8000-0x9FFF.
unsigned char ramBank[0x2000]; // An 8 KB switchable RAM bank that is supported by some cartridges from 0xA000-0xBFFF.
unsigned char internRam[0x2000]; // The Gameboy's 8 KB internal RAM from 0xC000-0xDFFF, this is also echoed from 0xE000-FDFF.
unsigned char sprite[0xA0]; // Sprite Attribute Memory (OAM) from 0xFE00-0xFE9F.
// The address space from FEA0-FEFF is unusable.
unsigned char ioRegs[0x4C]; // I/O registers from 0xFF00-0xFF4B. FF03, FF08-FF0E, FF15, FF1F, and FF27-FF2F are unused.
// The address space from FF4C-FF7F is unusable.
unsigned char highRam[0x7F]; // The Gameboy's high RAM from 0xFF80-FFFE.
unsigned char intrpFlags; // The interrupt enable(IE) flags at 0xFFFF.
} memory;
struct Cartridge
{
int systemType;
int mbcType;
unsigned char romBankRegister; // This will store the currently selected MBC ROM bank.
unsigned char dataBuffer[16777216]; // Set a maximum cartridge size at 16 megabytes.
} cart;
struct CPU
{
union Registers
{
struct { unsigned short int AF, BC, DE, HL, SP, PC; };
struct { unsigned char F, A, C, B, E, D, L, H, SPL, SPH, PCL, PCH; };
} regs;
} cpu;
struct State
{
boolean eiDelay; // EI instruction enables interrupts one instruction after its execution.
boolean intrpEnable; // Master interrupt enable switch.
boolean halted;
boolean haltInstructionRepeat;
boolean running;
boolean stopped;
} state;
struct Cycles
{
unsigned short int internalCounterCycles; // Cycle counter for DIV and TIMA register.
unsigned short int previousInternalCounterCycles; // Cycle counter for DIV and TIMA register.
unsigned short int timaIncCounterCycles; // A cycle counter for incrementing the TIMA register.
unsigned int frameCycles;
unsigned int statCycles; // Cycle counter for STAT register.
unsigned char opCycles[0x100]; // Store the number of clock cycles for every instruction
unsigned char opCBCycles[0x100]; // Store cycles for CB bit instructions
} cycles;
struct IO
{
struct Display
{
unsigned char bgBuffer[256][256];
};
} io;
} emu;
// Standard Gameboy opcode clock cycles.
unsigned char GB_CycleTable[0x100] = { //0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F
/*0x00*/ 4, 12, 8, 8, 4, 4, 8, 4, 20, 8, 8, 8, 4, 4, 8, 4,
/*0x10*/ 0, 12, 8, 8, 4, 4, 8, 4, 12, 8, 8, 8, 4, 4, 8, 4,
/*0x20*/ 8, 12, 8, 8, 4, 4, 8, 4, 8, 8, 8, 8, 4, 4, 8, 4,
/*0x30*/ 8, 12, 8, 8, 12, 12, 12, 4, 8, 8, 8, 8, 4, 4, 8, 4,
/*0x40*/ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4,
/*0x50*/ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4,
/*0x60*/ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4,
/*0x70*/ 8, 8, 8, 8, 8, 8, 0, 8, 4, 4, 4, 4, 4, 4, 8, 4,
/*0x80*/ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4,
/*0x90*/ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4,
/*0xA0*/ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4,
/*0xB0*/ 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4,
/*0xC0*/ 8, 12, 12, 16, 12, 16, 8, 16, 8, 16, 12, 0, 12, 24, 8, 16,
/*0xD0*/ 8, 12, 12, 0, 12, 16, 8, 16, 8, 16, 12, 0, 12, 0, 8, 16,
/*0xE0*/ 12, 12, 8, 0, 0, 16, 8, 16, 16, 4, 16, 0, 0, 0, 8, 16,
/*0xF0*/ 12, 12, 8, 4, 0, 16, 8, 16, 12, 8, 16, 4, 0, 0, 8, 16
};
// Gameboy bit operation clock cycles
unsigned char GB_CBCycleTable[0x100] = {//0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F
/*0x00*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0x10*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0x20*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0x30*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0x40*/ 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8,
/*0x50*/ 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8,
/*0x60*/ 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8,
/*0x70*/ 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8,
/*0x80*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0x90*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0xA0*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0xB0*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0xC0*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0xD0*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0xE0*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8,
/*0xF0*/ 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8
};
//Blank 8-bit table for possible future use
//unsigned char GB_BitCycleTable[0x100] = {//0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F
// /*0x00*/ , , , , , , , , , , , , , , , ,
// /*0x10*/ , , , , , , , , , , , , , , , ,
// /*0x20*/ , , , , , , , , , , , , , , , ,
// /*0x30*/ , , , , , , , , , , , , , , , ,
// /*0x40*/ , , , , , , , , , , , , , , , ,
// /*0x50*/ , , , , , , , , , , , , , , , ,
// /*0x60*/ , , , , , , , , , , , , , , , ,
// /*0x70*/ , , , , , , , , , , , , , , , ,
// /*0x80*/ , , , , , , , , , , , , , , , ,
// /*0x90*/ , , , , , , , , , , , , , , , ,
// /*0xA0*/ , , , , , , , , , , , , , , , ,
// /*0xB0*/ , , , , , , , , , , , , , , , ,
// /*0xC0*/ , , , , , , , , , , , , , , , ,
// /*0xD0*/ , , , , , , , , , , , , , , , ,
// /*0xE0*/ , , , , , , , , , , , , , , , ,
// /*0xF0*/ , , , , , , , , , , , , , , ,
unsigned char opcodeDescription[256][32];
// An array that holds the pixel data that will actually be drawn to the screen.
unsigned char screenData[0x5A00];
//----------------------------------------//
// Gameboy status arrays. //
//----------------------------------------//
unsigned char joyState[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
//----------------------------------------//
// Miscellaneous variables //
//----------------------------------------//
unsigned long long int FPS = 0;
SDL_TimerID FPSTimerID;
// This will check if the read address is readable and return the data from the proper location.
unsigned char ReadMemory(unsigned short int address)
{
if ((address >= 0x0000) && (address <= 0x3FFF))
return emu.memory.romBank0[address];
else if ((address >= 0x4000) && (address <= 0x7FFF))
return emu.memory.romBank1[address - 0x4000];
else if ((address >= 0x8000) && (address <= 0x9FFF))
return emu.memory.videoRam[address - 0x8000];
else if ((address >= 0xA000) && (address <= 0xBFFF))
return emu.memory.ramBank[address - 0xA000];
else if ((address >= 0xC000) && (address <= 0xDFFF))
return emu.memory.internRam[address - 0xC000];
else if ((address >= 0xE000) && (address <= 0xFDFF)) // Echo Ram. Returns the same value as the C000-DDFF space.
return emu.memory.internRam[address - 0xE000];
else if ((address >= 0xFE00) && (address <= 0xFE9F)) // Read from the sprite OAM RAM.
return emu.memory.sprite[address - 0xFE00];
//else if ((address >= 0xFEA0) && (address <= 0xFEFF)) // Restricted memory space.
// return 0xFF;
else if ((address >= 0xFF00) && (address <= 0xFF4B)) // Read from an I/O register.
{
return emu.memory.ioRegs[address - 0xFF00];
}
//else if ((address >= 0xFF4C) && (address <= 0xFF7F)) // Restricted memory space.
// return 0xFF;
else if ((address >= 0xFF80) && (address <= 0xFFFE))
return emu.memory.highRam[address - 0xFF80];
else if (address == 0xFFFF)
return emu.memory.intrpFlags;
else
return 0xFF;
}
// This will check whether a write to memory is valid and if any special location is written
void WriteMemory(unsigned short int address, unsigned char data)
{
// Make sure the instruction isn't trying to write to the ROM bank areas.
if ((address >= 0x0000) && (address <= 0x7FFF))
{
// See if this is a special memory write.
if ((address >= 0x2000) && (address <= 0x3FFF))
if ((emu.cart.mbcType >= 1) && (emu.cart.mbcType <= 3))
{
// 0 or ROM banks that are a multiple of 0x20 refer to the next ROM bank (0x20 = 0x21, 0x40 = 0x41).
// The low 5 bits of the 7-bit ROM bank are selected here.
// if ((data % 20) == 0)
// data |= 1;
// This will combine the lower 5 bits of the written data with the ROM bank register.
emu.cart.romBankRegister = (emu.cart.romBankRegister & 0xE0) | (data & 0x1F);
emu.cart.romBankRegister = data;
memcpy(&emu.memory.romBank1[0], &emu.cart.dataBuffer[emu.cart.romBankRegister * 0x4000], 0x4000);
}
else if ((address >= 0x4000) && (address <= 0x5FFF))
if ((emu.cart.mbcType >= 1) && (emu.cart.mbcType <= 3))
{
// 0 or ROM banks that are a multiple of 0x20 refer to the next ROM bank (0x20 = 0x21, 0x40 = 0x41).
// The high 2 bits of the 7-bit ROM bank are selected here.
emu.cart.romBankRegister = (emu.cart.romBankRegister & 0x1F) | (data & 0x60);
memcpy(&emu.memory.romBank1[0], &emu.cart.dataBuffer[emu.cart.romBankRegister * 0x4000], 0x4000);
}
}
else if ((address >= 0x8000) && (address <= 0x9FFF))
emu.memory.videoRam[address - 0x8000] = data;
else if ((address >= 0xA000) && (address <= 0xBFFF))
emu.memory.ramBank[address - 0xA000] = data;
else if ((address >= 0xC000) && (address <= 0xDFFF))
emu.memory.internRam[address - 0xC000] = data;
else if ((address >= 0xE000) && (address <= 0xFDFF)) // Echo Ram. Writes the value to the C000-DDFF space.
emu.memory.internRam[address - 0xE000] = data;
else if ((address >= 0xFE00) && (address <= 0xFE9F)) // Write to the sprite OAM RAM.
emu.memory.sprite[address - 0xFE00] = data;
else if ((address >= 0xFEA0) && (address <= 0xFEFF)) // Restricted memory space.
return;
else if ((address >= 0xFF00) && (address <= 0xFF4B)) // Write to an I/O register.
{
if (address == 0xFF00)
IOregister_P1 = 0xCF + (data & 0x30); // Only bits 4 and 5 of the P1 register are writable.
else if (address == 0xFF01)
IOregister_SB = data;
else if (address == 0xFF02)
{
// If a serial transfer was attempted, set the received data to 0xFF since no second Gameboy is present.
// The interrupt is only triggered if the system has set itself as the master Gameboy.
if ((data & BIT_7) && (data & BIT_0))
IOregister_IF |= BIT_3;
IOregister_SB = 0xFF;
}
// Reset the internal counter if DIV is written to.
else if (address == 0xFF04)
{
emu.cycles.internalCounterCycles = 0;
emu.cycles.previousInternalCounterCycles = 0;
emu.cycles.timaIncCounterCycles = 0;
}
else if (address == 0xFF05)
IOregister_TIMA = data;
else if (address == 0xFF06)
IOregister_TMA = data;
else if (address == 0xFF07)
{
IOregister_TAC = 0xF8 + (data & 0x07); // Only the low 3 bits of TAC can be written.
emu.cycles.timaIncCounterCycles = 0;
//emu.cycles.previousInternalCounterCycles = 0;
}
else if (address == 0xFF0F)
IOregister_IF = 0xE0 + (data & 0x1F); // Only the low 5 bits of IF can be written.
else if (address == 0xFF10)
IOregister_NR10 = 0x80 + (data & 0x7F); // The 7th bit always returns 1.
else if (address == 0xFF40)
{
IOregister_LCDC = data;
if (!(IOregister_LCDC & BIT_7))
{
// If the LCD is turned off, STAT mode, LY, and triggered display interrupts are all reset, but the LY/LYC compare bit and enabled STAT interrupt are retained.
IOregister_STAT &= (BIT_0_OFF & BIT_1_OFF);
IOregister_LY = 0;
WYTemp = IOregister_WY;
// IOregister_IF &= (BIT_0_OFF & BIT_1_OFF);
emu.cycles.statCycles = 0;
}
}
else if (address == 0xFF41)
IOregister_STAT = (BIT_7 | (data & 0x78)) | IOregister_STAT & (BIT_1 | BIT_0); // Make sure the mode flag is not affected and the 7th bit always returns 1.
else if (address == 0xFF46)
{
IOregister_DMA = data;
for (int i = 0; i < 0xA0; i++)
emu.memory.sprite[i] = ReadMemory((IOregister_DMA << 8) + i); // If data is written to the OAM register, begin an OAM transfer.
}
else
emu.memory.ioRegs[address - 0xFF00] = data;
}
//else if ((address >= 0xFF4C) && (address <= 0xFF7F)) // Restricted memory space.
// return;
else if ((address >= 0xFF80) && (address <= 0xFFFE))
emu.memory.highRam[address - 0xFF80] = data;
else if (address == 0xFFFF)
IOregister_IE = 0xE0 + (data & 0x1F); // Only the low 5-bits of IE can be written.
}
//----------------------------------------//
// This instruction will add a given value//
// plus the carry flag to register A. //
//----------------------------------------//
void z80_ADC_A_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
// If there is a carry from bit 3, set flag H, otherwise
// reset it.
if (((emu.cpu.regs.A & 0xF) + (value & 0xF) + FLAG_C) > 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// If there will be a carry from bit 7, set flag C, otherwise
// reset it.
if ((emu.cpu.regs.A + value + FLAG_C) > 0xFF)
{
emu.cpu.regs.A += value + FLAG_C;
emu.cpu.regs.F |= FLAG_C_ON;
}
else
{
emu.cpu.regs.A += value + FLAG_C;
emu.cpu.regs.F &= FLAG_C_OFF;
}
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag N is reset.
emu.cpu.regs.F &= FLAG_N_OFF;
// Increment Program Counter to skip read value.
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will add an 8-bit //
// register plus the carry flag to //
// register A. //
//----------------------------------------//
void z80_ADC_A_reg8(unsigned char *reg)
{
// If there will be a carry from bit 3, set flag H, otherwise
// reset it.
if (((emu.cpu.regs.A & 0xF) + (*reg & 0xF) + FLAG_C) > 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// If there will be a carry from bit 7, set flag C, otherwise
// reset it.
if ((emu.cpu.regs.A + *reg + FLAG_C) > 0xFF)
{
emu.cpu.regs.A += *reg + FLAG_C;
emu.cpu.regs.F |= FLAG_C_ON;
}
else
{
emu.cpu.regs.A += *reg + FLAG_C;
emu.cpu.regs.F &= FLAG_C_OFF;
}
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag N is reset.
emu.cpu.regs.F &= FLAG_N_OFF;
}
//----------------------------------------//
// This instruction will add a given value//
// to register A. //
//----------------------------------------//
void z80_ADD_A_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
// If there will be a carry from bit 3, set flag H, otherwise
// reset it.
if (((emu.cpu.regs.A & 0xF) + (value & 0xF)) > 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// If there will be a carry from bit 7, set flag C, otherwise
// reset it.
if ((emu.cpu.regs.A + value) > 0xFF)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
// Add *reg to register A.
emu.cpu.regs.A += value;
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag N is reset.
emu.cpu.regs.F &= FLAG_N_OFF;
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will add an 8-bit //
// register's value to register A. //
//----------------------------------------//
void z80_ADD_A_reg8(unsigned char *reg)
{
// If there will be a carry from bit 3, set flag H, otherwise
// reset it.
if (((emu.cpu.regs.A & 0xF) + (*reg & 0xF)) > 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// If there will be a carry from bit 7, set flag C, otherwise
// reset it.
if ((emu.cpu.regs.A + *reg) > 0xFF)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
// Add *reg to register A.
emu.cpu.regs.A += *reg;
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag N is reset.
emu.cpu.regs.F &= FLAG_N_OFF;
}
//----------------------------------------//
// This instruction will add the value of //
// a 16-bit register to register HL. //
//----------------------------------------//
void z80_ADD_HL_reg16(unsigned short int *reg)
{
// If there will be a carry from bit 11, set flag H.
if (((emu.cpu.regs.HL & 0xFFF) + (*reg & 0xFFF)) > 0xFFF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// If there will be a carry from bit 15, set flag C.
if ((emu.cpu.regs.HL + *reg) > 0xFFFF)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
// Add *reg to HL.
emu.cpu.regs.HL += *reg;
// Flag N is reset.
emu.cpu.regs.F &= FLAG_N_OFF;
}
//----------------------------------------//
// This instruction will add a given, //
// signed 8-bit value to the //
// Stack pointer. //
//----------------------------------------//
void z80_ADD_SP_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
// The flags are determined with an unsigned value.
// Turn on flag H if there is a carry from bit 3.
if (((emu.cpu.regs.SP & 0xF) + (value & 0xF)) > 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// Turn on flag C if the result is above 0xFFFF, or below 0x0000.
if (((emu.cpu.regs.SP & 0xFF) + value) > 0xFF)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
emu.cpu.regs.SP += (signed char)value;
// Flag Z and N are reset.
emu.cpu.regs.F &= (FLAG_Z_OFF & FLAG_N_OFF);
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will logical AND a //
// given value with register A. //
//----------------------------------------//
void z80_AND_immediate()
{
// Logically AND register A with an immediate value.
emu.cpu.regs.A &= ReadMemory(emu.cpu.regs.PC);
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag_H is set.
emu.cpu.regs.F |= FLAG_H_ON;
// Flags N and C are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_C_OFF);
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will logical AND a //
// given value with an 8-bit register. //
//----------------------------------------//
void z80_AND_reg8(unsigned char *reg)
{
// Logically AND register A with *reg.
emu.cpu.regs.A &= *reg;
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag_H is set.
emu.cpu.regs.F |= FLAG_H_ON;
// Flags N and C are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_C_OFF);
}
//----------------------------------------//
// This instruction will test a bit of an //
// 8-bit register. //
//----------------------------------------//
void z80_BIT_bit_reg8(unsigned char bit, unsigned char *reg)
{
// If result is 0, set flag Z, otherwise reset it.
if ((*reg & bit) == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag N is reset.
emu.cpu.regs.F &= FLAG_N_OFF;
// Flag H is set.
emu.cpu.regs.F |= FLAG_H_ON;
}
//----------------------------------------//
// This instruction will push the current //
// value of the Program Counter onto the //
// stack and jump to a new address, but //
// only if the given condition is met. //
//----------------------------------------//
int z80_CALL_condition_immediate(unsigned char condition)
{
unsigned short int callAddress;
unsigned int conditionTrue;
callAddress = (ReadMemory(emu.cpu.regs.PC) + (ReadMemory(emu.cpu.regs.PC + 1) << 8));
conditionTrue = 0;
switch (condition)
{
case 0x01:
{
if (FLAG_Z == 0)
conditionTrue = 1;
}
break;
case 0x02:
{
if (FLAG_Z == 1)
conditionTrue = 1;
}
break;
case 0x03:
{
if (FLAG_C == 0)
conditionTrue = 1;
}
break;
case 0x04:
{
if (FLAG_C == 1)
conditionTrue = 1;
}
break;
}
emu.cpu.regs.PC += 2;
if (conditionTrue == 1)
{
// Push address of next instruction onto the stack.
emu.cpu.regs.SP--;
WriteMemory(emu.cpu.regs.SP, emu.cpu.regs.PCH);
emu.cpu.regs.SP--;
WriteMemory(emu.cpu.regs.SP, emu.cpu.regs.PCL);
emu.cpu.regs.PC = callAddress;
return 12; // return additional cycles if jump was executed.
}
else
return 0;
}
//----------------------------------------//
// This instruction will push the current //
// value of the Program Counter onto the //
// stack and jump to a new address. //
//----------------------------------------//
void z80_CALL_immediate()
{
unsigned short int callAddress;
callAddress = ReadMemory(emu.cpu.regs.PC) + (ReadMemory(emu.cpu.regs.PC + 1) << 8);
emu.cpu.regs.PC += 2;
// Push address of next instruction onto the stack.
emu.cpu.regs.SP--;
WriteMemory(emu.cpu.regs.SP, emu.cpu.regs.PCH);
emu.cpu.regs.SP--;
WriteMemory(emu.cpu.regs.SP, emu.cpu.regs.PCL);
// Load new address into Program Counter.
emu.cpu.regs.PC = callAddress;
}
//----------------------------------------//
// This instruction will complement(flip) //
// the carry flag. //
//----------------------------------------//
void z80_CCF()
{
// Complement flag C.
emu.cpu.regs.F ^= FLAG_C_ON;
// Flags N and H are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_H_OFF);
}
//----------------------------------------//
// This instruction will set flags as if //
// a given value with subtracted from //
// register A. //
//----------------------------------------//
void z80_CP_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
if (emu.cpu.regs.A == value)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
if ((emu.cpu.regs.A & 0xF) < (value & 0xF))
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
if (emu.cpu.regs.A < value)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
emu.cpu.regs.F |= FLAG_N_ON;
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will set flags as if //
// a register was subtracted from //
// register A. //
//----------------------------------------//
void z80_CP_reg8(unsigned char *reg)
{
if (emu.cpu.regs.A == *reg)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
if ((emu.cpu.regs.A & 0xF) < (*reg & 0xF))
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
if (emu.cpu.regs.A < *reg)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
emu.cpu.regs.F |= FLAG_N_ON;
}
//----------------------------------------//
// This instruction will flip all of //
// register A's bits. //
//----------------------------------------//
void z80_CPL()
{
// Exclusive OR register A with 0xFF, this will flip the bits.
emu.cpu.regs.A ^= 0xFF;
// Flags N and H are set.
emu.cpu.regs.F |= (FLAG_N_ON | FLAG_H_ON);
}
//----------------------------------------//
// This instruction will convert register //
// A to its packed-BCD representation. //
//----------------------------------------//
void z80_DAA()
{
unsigned short int result;
result = emu.cpu.regs.A;
// Check if flag N is on indicating the last operation was a subtraction.
if (FLAG_N == 1)
{
if (FLAG_H == 1)
result = (result - 0x06) & 0xFF;
if (FLAG_C == 1)
result -= 0x60;
}
// Otherwise, convert for an addition.
else
{
if (((result & 0xF) > 0x09) || (FLAG_H == 1))
result += 0x06;
if ((result > 0x9F) || (FLAG_C == 1))
result += 0x60;
}
// Set the carry flag if the BCD value of the result is greater than 99.
if ((result & 0x100) == 0x100)
emu.cpu.regs.F |= FLAG_C_ON;
// else
// emu.cpu.regs.F &= FLAG_C_OFF;
emu.cpu.regs.A = (unsigned char)(result & 0xFF);
// If the result was 0, turn the Z flag on.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flag H is turned off.
emu.cpu.regs.F &= FLAG_H_OFF;
}
//----------------------------------------//
// This instruction will decrease the //
// value at memory location (HL) by 1. //
//----------------------------------------//
void z80_DEC_location_HL()
{
WriteMemory(emu.cpu.regs.HL, ReadMemory(emu.cpu.regs.HL) - 1);
// Turn on flag N since operation is a subtraction.
emu.cpu.regs.F |= FLAG_N_ON;
if (ReadMemory(emu.cpu.regs.HL) == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
if ((ReadMemory(emu.cpu.regs.HL) & 0xF) == 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
}
//----------------------------------------//
// This instruction decreases a given //
// 16-bit register's value by 1. //
//----------------------------------------//
void z80_DEC_reg16(unsigned short int *reg)
{
*reg -= 1;
}
//----------------------------------------//
// This instruction decreases a given //
// 8-bit register's value by 1. //
//----------------------------------------//
void z80_DEC_reg8(unsigned char *reg)
{
// If the lo nibble of the register is 0, then there will be a borrow from bit 4.
if ((*reg & 0xF) == 0)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// Decrement *reg
*reg -= 1;
// If result is 0, set flag Z, otherwise reset it.
if (*reg == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Turn on flag N.
emu.cpu.regs.F |= FLAG_N_ON;
}
//----------------------------------------//
// This instruction turns off the //
// Interrupt Master Enable flag. //
//----------------------------------------//
void z80_DI()
{
IntrpMasterEnable = 0;
}
//----------------------------------------//
// This instruction turns on the //
// Interrupt Master Enable flag. //
//----------------------------------------//
void z80_EI()
{
IntrpMasterEnable = 1;
}
//----------------------------------------//
// This instruction will halt the GB CPU //
// until an interrupt occurs. //
//----------------------------------------//
void z80_HALT()
{
// Make sure interrupts are enabled before allowing the CPU to halt.
if (IntrpMasterEnable == 1)
emu.state.halted = 1;
else
{
if ((IOregister_IE & IOregister_IF & 0x1F) != 0)
emu.state.haltInstructionRepeat = 1;
else
emu.state.halted = 1;
}
}
//----------------------------------------//
// This instruction will increase the //
// value at memory location (HL) by 1. //
//----------------------------------------//
void z80_INC_location_HL()
{
// See if there will be a carry from bit 3, if there was, set flag H.
if ((ReadMemory(emu.cpu.regs.HL) & 0xF) == 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// Add 1 to the value at the address in register HL.
WriteMemory(emu.cpu.regs.HL, ReadMemory(emu.cpu.regs.HL) + 1);
// If result is 0, set flag Z, otherwise reset it.
if (ReadMemory(emu.cpu.regs.HL) == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Turn off flag N.
emu.cpu.regs.F &= FLAG_N_OFF;
}
//----------------------------------------//
// This instruction increases a given //
// 16-bit register's value by 1. //
//----------------------------------------//
void z80_INC_reg16(unsigned short int *reg)
{
*reg += 1;
}
//----------------------------------------//
// This instruction increases a given //
// 8-bit register's value by 1. //
//----------------------------------------//
void z80_INC_reg8(unsigned char *reg)
{
// Turn the H flag on if incrementing the register carries from bit 3.
if ((*reg & 0xF) == 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// Add 1 to *reg.
*reg += 1;
// If result is 0, set flag Z, otherwise reset it.
if (*reg == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Turn off flag N. Flag C is not affected.
emu.cpu.regs.F &= FLAG_N_OFF;
}
void z80_JP_location_HL()
{
emu.cpu.regs.PC = emu.cpu.regs.HL;
//emu.cpu.regs.PCL = ReadMemory(emu.cpu.regs.HL);
//emu.cpu.regs.PCH = ReadMemory(emu.cpu.regs.HL + 1);
}
//----------------------------------------//
// This instruction will relocate the //
// Program Counter(PC) to a given //
// immediate address. //
//----------------------------------------//
void z80_JP_immediate()
{
unsigned short int readAddress;
readAddress = emu.cpu.regs.PC;
emu.cpu.regs.PCL = ReadMemory(readAddress);
readAddress++;
emu.cpu.regs.PCH = ReadMemory(readAddress);
}
//----------------------------------------//
// This instruction will relocate the //
// Program Counter(PC) to a given address,//
// but only if the given condition is met.//
//----------------------------------------//
int z80_JP_condition_immediate(unsigned char condition)
{
unsigned short int jumpAddress;
boolean conditionTrue;
jumpAddress = (ReadMemory(emu.cpu.regs.PC) + ((ReadMemory(emu.cpu.regs.PC + 1) << 8)));
conditionTrue = 0;
switch (condition)
{
// If the Z flag is off, jump to the address.
case 0x01:
{
if (FLAG_Z == 0)
conditionTrue = 1;
}
break;
// If the Z flag is on, jump to the address.
case 0x02:
{
if (FLAG_Z == 1)
conditionTrue = 1;
}
break;
// If the C flag is off, jump to the address.
case 0x03:
{
if (FLAG_C == 0)
conditionTrue = 1;
}
break;
// If the C flag is on, jump to the address.
case 0x04:
{
if (FLAG_C == 1)
conditionTrue = 1;
}
break;
}
if (conditionTrue == 1)
{
emu.cpu.regs.PC = jumpAddress;
return 4; // Add four additional cycles if jump succeeds.
}
else
{
emu.cpu.regs.PC += 2;
return 0;
}
}
//----------------------------------------//
// This instruction will add a signed //
// 8-bit offset to the Program Counter //
// only if the given condition is met. //
//----------------------------------------//
int z80_JR_condition_offset(unsigned char condition)
{
boolean conditionTrue;
conditionTrue = 0;
// condition decides the jump condition to look for.
switch(condition)
{
case 0x01: //JR NZ, offset
{
if (FLAG_Z == 0)
conditionTrue = 1;
}
break;
case 0x02: //JR Z, offset
{
if (FLAG_Z == 1)
conditionTrue = 1;
}
break;
case 0x03: //JR NC, offset
{
if (FLAG_C == 0)
conditionTrue = 1;
}
break;
case 0x04: //JR C, offset
{
if (FLAG_C == 1)
conditionTrue = 1;
}
break;
}
if (conditionTrue)
{
// Relative jump within 128 bytes.
emu.cpu.regs.PC += (signed char)ReadMemory(emu.cpu.regs.PC);
emu.cpu.regs.PC++;
return 4;
}
else
emu.cpu.regs.PC++;
return 0;
}
//----------------------------------------//
// This instruction will add a signed //
// 8-bit offset to the Program Counter. //
//----------------------------------------//
void z80_JR_offset()
{
// Relative jump within 128 bytes.
emu.cpu.regs.PC += (signed char)ReadMemory(emu.cpu.regs.PC);
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will load the value at//
// a given memory location into A. //
//----------------------------------------//
void z80_LD_A_location_immediate()
{
unsigned short int readAddress;
readAddress = ReadMemory(emu.cpu.regs.PC) + (ReadMemory(emu.cpu.regs.PC + 1) << 8);
emu.cpu.regs.A = ReadMemory(readAddress);
emu.cpu.regs.PC += 2;
}
//----------------------------------------//
// This instruction loads the value at //
// memory location 0xFF00 plus register C //
// into register A. //
//----------------------------------------//
void z80_LD_A_0xFF00_C()
{
// Load the value at 0xFF00 + register C into register A.
emu.cpu.regs.A = ReadMemory(0xFF00 + emu.cpu.regs.C);
}
//----------------------------------------//
// This instruction will load the value //
// at memory location 0xFF00 plus an 8-bit//
// value into register A. //
//----------------------------------------//
void z80_LD_A_0xFF00_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
// Load the value at 0xFF00 + value into register A.
emu.cpu.regs.A = ReadMemory(0xFF00 + value);
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will load the value in//
// memory at (reg16) into register A. //
//----------------------------------------//
void z80_LD_A_location_reg16(unsigned short int *reg)
{
// Load A with the value at the address in *reg.
emu.cpu.regs.A = ReadMemory(*reg);
}
//----------------------------------------//
// Load the Stack Pointer plus a given, //
// signed 8-bit value into memory //
// location (HL). //
//----------------------------------------//
void z80_LD_HL_SP_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
// The flags are determined with an unsigned value.
// Flag H is set if there is a carry from bit 3.
if (((emu.cpu.regs.SP & 0xF) + (value & 0xF)) > 0xF)
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// Flag C is set if there is a carry from bit 7.
if ((emu.cpu.regs.SP & 0xFF) + value > 0xFF)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
emu.cpu.regs.HL = emu.cpu.regs.SP + (signed char)value;
// Reset flags Z and N.
emu.cpu.regs.F &= (FLAG_Z_OFF & FLAG_N_OFF);
// Increment Program Counter.
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will load a given //
// value into memory location (HL). //
//----------------------------------------//
void z80_LD_location_HL_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
// Load the address in HL with the immediate value
WriteMemory(emu.cpu.regs.HL, value);
// Increment the Program Counter to skip over the 8-bit value.
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will load the value of//
// an 8-bit register into memory location //
// (HL). //
//----------------------------------------//
void z80_LD_location_HL_reg8(unsigned char *reg)
{
// Load *reg into the address in register HL
WriteMemory(emu.cpu.regs.HL, *reg);
}
//----------------------------------------//
// This instruction will load the value of//
// register A into memory at a given //
// location. //
//----------------------------------------//
void z80_LD_location_immediate_A()
{
unsigned short int writeAddress;
writeAddress = ReadMemory(emu.cpu.regs.PC) + (ReadMemory(emu.cpu.regs.PC + 1) << 8);
// Load register A into the location.
WriteMemory(writeAddress, emu.cpu.regs.A);
// Skip over the 16-bit address.
emu.cpu.regs.PC += 2;
}
//----------------------------------------//
// This will load the Stack Pointer into a//
// given memory location. //
//----------------------------------------//
void z80_LD_location_SP()
{
unsigned short int writeAddress;
writeAddress = ReadMemory(emu.cpu.regs.PC) + (ReadMemory(emu.cpu.regs.PC + 1) << 8);
WriteMemory(writeAddress, emu.cpu.regs.SPL);
writeAddress++;
WriteMemory(writeAddress, emu.cpu.regs.SPH);
// Skip over the 16-bit address.
emu.cpu.regs.PC += 2;
}
//----------------------------------------//
// This instruction will load a 16-bit //
// register with a given value. //
//----------------------------------------//
void z80_LD_reg16_value(unsigned char *hiReg, unsigned char *loReg)
{
// Load the 16-bit value into the registers.
*loReg = ReadMemory(emu.cpu.regs.PC);
emu.cpu.regs.PC++;
*hiReg = ReadMemory(emu.cpu.regs.PC);
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will load the address //
// at a 16-bit pointer register with the //
// value in register A. //
//----------------------------------------//
void z80_LD_location_reg16_A(unsigned short int *reg)
{
WriteMemory(*reg, emu.cpu.regs.A);
}
//----------------------------------------//
// This instruction will load an 8-bit //
// register with a given value. //
//----------------------------------------//
void z80_LD_reg8_value(unsigned char *reg)
{
// Load *reg with the 8-bit value immediately after it.
*reg = ReadMemory(emu.cpu.regs.PC);
// Increment the program counter to skip the value.
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will load an 8-bit //
// register with the value at memory //
// location (HL). //
//----------------------------------------//
void z80_LD_reg8_location_HL(unsigned char *reg)
{
// Load the value at the address in HL into *reg.
*reg = ReadMemory(emu.cpu.regs.HL);
}
//----------------------------------------//
// This instruction will load an 8-bit //
// register with the value of another //
// 8-bit register. //
//----------------------------------------//
void z80_LD_reg8_reg8(unsigned char *reg1, unsigned char *reg2)
{
// Load the value in *reg2 into *reg1.
*reg1 = *reg2;
}
//----------------------------------------//
// This instruction will load the Stack //
// Pointer with the value of register HL. //
//----------------------------------------//
void z80_LD_SP_HL()
{
// Load register HL into Stack Pointer.
emu.cpu.regs.SP = emu.cpu.regs.HL;
}
//----------------------------------------//
// This instruction loads register A into //
// memory location 0xFF00 plus register C.//
//----------------------------------------//
void z80_LD_0xFF00_C_A()
{
WriteMemory(0xFF00 + emu.cpu.regs.C, emu.cpu.regs.A);
}
//----------------------------------------//
// This instruction will load the value //
// of register A into memory at the //
// location of 0xFF00 plus an 8-bit value.//
//----------------------------------------//
void z80_LD_0xFF00_immediate_A()
{
// Write the value of register A into memory.
WriteMemory(0xFF00 + ReadMemory(emu.cpu.regs.PC), emu.cpu.regs.A);
// Increment Program Counter
emu.cpu.regs.PC++;
}
// Load A with data at location HL and decrement HL.
void z80_LDD_A_HL()
{
emu.cpu.regs.A = ReadMemory(emu.cpu.regs.HL);
emu.cpu.regs.HL--;
}
// Load location HL with data from register A and decrement HL.
void z80_LDD_HL_A()
{
WriteMemory(emu.cpu.regs.HL, emu.cpu.regs.A);
emu.cpu.regs.HL--;
}
// Load A with data at location HL and increment HL.
void z80_LDI_A_HL()
{
emu.cpu.regs.A = ReadMemory(emu.cpu.regs.HL);
emu.cpu.regs.HL++;
}
// Load location HL with data from register A and increment HL.
void z80_LDI_HL_A()
{
WriteMemory(emu.cpu.regs.HL, emu.cpu.regs.A);
emu.cpu.regs.HL++;
}
//----------------------------------------//
// This instruction will set(turn on) a //
// given bit of an 8-bit register. //
//----------------------------------------//
void z80_SET_bit_reg8(unsigned char bit, unsigned char *reg)
{
*reg |= bit;
}
//----------------------------------------//
// This instruction shifts bit 7 of an //
// 8-bit register left into the carry flag//
// A 0 is shifted into bit 0. //
//----------------------------------------//
void z80_SLA_reg8(unsigned char *reg)
{
// Put *reg's old bit 7 data in Carry flag.
if (*reg & BIT_7)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
// Shift *reg left once. 0 is shifted in from right.
*reg <<= 1;
// If result is 0, set flag Z, otherwise reset it.
if (*reg == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flags N and H are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_H_OFF);
}
//----------------------------------------//
// This instruction shifts bit 0 of an //
// 8-bit register right into the carry //
// flag. Bit 7 doesn't change. //
//----------------------------------------//
void z80_SRA_reg8(unsigned char *reg)
{
// Put *reg's old bit 0 data in Carry flag.
if (*reg & BIT_0)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
// Shift *reg right once. 0 is shifted in from left. If bit 7
// is set, make sure it stays set.
if (*reg & BIT_7)
*reg = (*reg >> 1) + BIT_7;
else
*reg >>= 1;
// If result is 0, set flag Z, otherwise reset it.
if (*reg == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flags N and H are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_H_OFF);
}
//----------------------------------------//
// This instruction shifts bit 0 of an //
// 8-bit register right into the carry //
// flag. A 0 is shifted into bit 7. //
//----------------------------------------//
void z80_SRL_reg8(unsigned char *reg)
{
// Put *reg's old bit 0 data in Carry flag.
if (*reg & BIT_0)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
// Shift *reg right once. 0 is shifted in from right.
*reg >>= 1;
// If result is 0, set flag Z, otherwise reset it.
if (*reg == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Flags N and H are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_H_OFF);
}
//----------------------------------------//
// This halts the GB CPU until a button is//
// pressed. //
//----------------------------------------//
void z80_STOP()
{
// Don't allow STOP if interrupts are disabled.
//if (emu.state.intrpEnable == 1)
emu.state.stopped = 1;
// Skip over the extra 0x00
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will subtract a given //
// value from register A. //
//----------------------------------------//
void z80_SUB_immediate()
{
unsigned char value;
value = ReadMemory(emu.cpu.regs.PC);
// Check for a borrow from bit 4.
if ((emu.cpu.regs.A & 0xF) < (value & 0xF))
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// Set flag C if result will be below 0.
if ((emu.cpu.regs.A - value) < 0)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
emu.cpu.regs.A -= value;
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Set N since the operation was a subtraction.
emu.cpu.regs.F |= FLAG_N_ON;
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This instruction will subtract an 8-bit//
// register's value from register A. //
//----------------------------------------//
void z80_SUB_reg8(unsigned char *reg)
{
// Check for a borrow from bit 4.
if ((emu.cpu.regs.A & 0xF) < (*reg & 0xF))
emu.cpu.regs.F |= FLAG_H_ON;
else
emu.cpu.regs.F &= FLAG_H_OFF;
// Set flag C if result will be below 0.
if ((emu.cpu.regs.A - *reg) < 0)
emu.cpu.regs.F |= FLAG_C_ON;
else
emu.cpu.regs.F &= FLAG_C_OFF;
emu.cpu.regs.A -= *reg;
// If result is 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Set N since the operation was a subtraction.
emu.cpu.regs.F |= FLAG_N_ON;
}
//----------------------------------------//
// This instruction swaps the higher and //
// lower 4-bits of an 8-bit register. //
//----------------------------------------//
void z80_SWAP_reg8(unsigned char *reg)
{
// Swap the upper and lower nibbles of *reg.
*reg = (((*reg & 0xF0) >> 4) | ((*reg & 0x0F) << 4));
// If the result was 0, set flag Z, otherwise reset it.
if(*reg == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Other flags are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_H_OFF & FLAG_C_OFF);
}
//----------------------------------------//
// This will exclusive OR a given value //
// and register A. //
//----------------------------------------//
void z80_XOR_immediate()
{
// Logically Exclusive OR register A and an immediate value.
emu.cpu.regs.A ^= ReadMemory(emu.cpu.regs.PC);
// If the result was 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Other flags are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_H_OFF & FLAG_C_OFF);
// Increment Program Counter.
emu.cpu.regs.PC++;
}
//----------------------------------------//
// This will exclusive OR an 8-bit //
// register and register A. //
//----------------------------------------//
void z80_XOR_reg8(unsigned char *reg)
{
// Logically Exclusive OR register A and *reg.
emu.cpu.regs.A ^= *reg;
// If the result was 0, set flag Z, otherwise reset it.
if (emu.cpu.regs.A == 0)
emu.cpu.regs.F |= FLAG_Z_ON;
else
emu.cpu.regs.F &= FLAG_Z_OFF;
// Other flags are reset.
emu.cpu.regs.F &= (FLAG_N_OFF & FLAG_H_OFF & FLAG_C_OFF);
}
//----------------------------------------//
// This function will initialize the GB //
// to it's startup state.
//----------------------------------------//
int EmulationInitialize(unsigned char *fileBuffer, unsigned int fileSize)
{
//emu.cart.dataBuffer = (unsigned char *)malloc(fileSize);
//if (!emu.cart.dataBuffer)
// return -1;
memcpy(&emu.cart.dataBuffer[0], &fileBuffer[0], fileSize); // Copy ROM file data to cartridge buffer
if (emu.cart.dataBuffer[0x0143] == 0x80)
emu.cart.systemType = SYSTEM_CGB;
if (emu.cart.dataBuffer[0x0146] == 0x03)
emu.cart.systemType = SYSTEM_SGB;
if (emu.cart.dataBuffer[0x0146] == 0x00)
emu.cart.systemType = SYSTEM_GB;
if ((emu.cart.systemType != SYSTEM_GB) && (emu.cart.systemType != SYSTEM_SGB)) // Only original Gameboy supported for now.
return -1;
emu.cart.mbcType = emu.cart.dataBuffer[0x147];
//----------------------------------------//
// Set the CPU and IO register startup //
// values. //
//----------------------------------------//
// if (emu.cart.systemType == SYSTEM_GB)
// {
IOregister_NR52 = 0xF1;
emu.cpu.regs.AF = 0x01B0;
// }
// else
// emu.cpu.regs.AF = 0x00B0;
emu.cpu.regs.BC = 0x0013;
emu.cpu.regs.DE = 0x00D8;
emu.cpu.regs.HL = 0x014D;
emu.cpu.regs.SP = 0xFFFE;
emu.cpu.regs.PC = 0x0100;
IOregister_P1 = 0xCF;
IOregister_SB = 0x00;
IOregister_SC = 0x7E;
IOregister_DIV = 0xAB;
IOregister_TIMA = 0x00;
IOregister_TMA = 0x00;
IOregister_TAC = 0x00;
IOregister_IF = 0xE1;
IOregister_NR10 = 0x80;
IOregister_NR11 = 0xBF;
IOregister_NR12 = 0xF3;
IOregister_NR14 = 0xBF;
IOregister_NR21 = 0xF3;
IOregister_NR12 = 0xF3;
IOregister_NR22 = 0x00;
IOregister_NR24 = 0xBF;
IOregister_NR30 = 0x7F;
IOregister_NR31 = 0xFF;
IOregister_NR32 = 0x9F;
IOregister_NR33 = 0xBF;
IOregister_NR41 = 0xFF;
IOregister_NR42 = 0x00;
IOregister_NR43 = 0x00;
IOregister_NR44 = 0xBF;
IOregister_NR50 = 0x77;
IOregister_NR51 = 0xF3;
IOregister_LCDC = 0x91;
IOregister_STAT = 0x81;
IOregister_SCY = 0x00;
IOregister_SCX = 0x00;
IOregister_LY = 0x90;
IOregister_LYC = 0x00;
IOregister_DMA = 0x00;
IOregister_BGP = 0xFC;
IOregister_OBP0 = 0xFF;
IOregister_OBP1 = 0xFF;
IOregister_WY = 0x00;
IOregister_WX = 0x07;
IOregister_IE = 0x00;
IntrpMasterEnable = 1;
// Assume standard Gameboy opcode cycles for now
memcpy(&emu.cycles.opCycles[0], &GB_CycleTable[0], 0x100);
memcpy(&emu.cycles.opCBCycles[0], &GB_CBCycleTable[0], 0x100);
//----------------------------------------//
// Load the base ROM (32K). //
//----------------------------------------//
memcpy(&emu.memory.romBank0[0x0000], &emu.cart.dataBuffer[0x0000], 0x4000);
memcpy(&emu.memory.romBank1[0x0000], &emu.cart.dataBuffer[0x4000], 0x4000);
// Clear the video RAM.
memset(&emu.memory.videoRam, 0, 0x2000);
emu.cycles.statCycles = 0;
emu.cycles.internalCounterCycles = 0xABCC;
emu.state.halted = 0;
emu.state.haltInstructionRepeat = 0;
emu.state.stopped = 0;
return 1;
}
//----------------------------------------//
// This function takes care of the main GB//
// CPU processes. //
//----------------------------------------//
void RunEmulation()
{
unsigned int systemRunning = 1;
unsigned int conditionalCycles = 0;
unsigned int cyclesRan = 0;
while (systemRunning)
{
cyclesRan += HandleInterrupts();
if (emu.state.eiDelay == 1)
{
emu.state.eiDelay = 0;
IntrpMasterEnable = 1;
}
// Get the value from memory at the HL pointer in case an operation needs it.
hlMemVal = ReadMemory(emu.cpu.regs.HL);
// Don't actually execute an opcode if the system is halted or stopped.
if ((emu.state.halted == 0) && (emu.state.stopped == 0))
{
opcode = ReadMemory(emu.cpu.regs.PC);
if (emu.state.haltInstructionRepeat == 1) // If the halt bug occured, don't increment PC for one instruction.
emu.state.haltInstructionRepeat = 0;
else
emu.cpu.regs.PC++;
// Use the opcode to call the appropriate function.
switch (opcode)
{
// *switch statement covering all opcodes from 0x00 to 0xFF
// Cover the special 0xCB opcodes.
case 0xCB:
{
cbOpcode = ReadMemory(emu.cpu.regs.PC);
emu.cpu.regs.PC++;
switch (cbOpcode)
{
// *switch statement covering special CB opcodes.
}
break;
}
}
break;
}
break;
}
}
// If the opcode was 0xCB, add cycles from the bit operation cycle table.
if (opcode == 0xCB)
cyclesRan += emu.cycles.opCBCycles[cbOpcode];
else
cyclesRan += emu.cycles.opCycles[opcode] + conditionalCycles;
// If the last instruction ran was a HALT or a STOP, run cycles until the system resumes.
if ((opcode == 0x76) || (opcode == 0x10))
cyclesRan += 4;
if (IOregister_LCDC & BIT_7)
emu.cycles.statCycles += cyclesRan;
emu.cycles.internalCounterCycles += cyclesRan;
UpdateIORegisters();
conditionalCycles = 0; // Reset the conditional cycles added if an instruction's condition was true.
cyclesRan = 0; // Reset the total cycles ran.
HandleSDLEvents();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T18:42:02.577",
"Id": "394065",
"Score": "0",
"body": "\" are there parts of the code that stick out and say \"unprofessional\"?\" 1) Try compiling this code using only what is posted and <> headers. `#include \"define.h\"` belongs ... | [
{
"body": "<blockquote>\n <p>I'm just looking for some general critiques.</p>\n</blockquote>\n\n<p><strong>Fixed width types</strong></p>\n\n<p>Rather than <code>int, unsigned char, unsigned short</code>, I'd go right into using <code>int32_t, uint8_t, uint16_t</code>. It conveys code's intent and is more por... | {
"AcceptedAnswerId": "204363",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T00:26:31.843",
"Id": "204311",
"Score": "10",
"Tags": [
"c",
"windows",
"sdl",
"virtual-machine"
],
"Title": "Gameboy emulator in C"
} | 204311 |
<p>Following up on <a href="https://codereview.stackexchange.com/q/203796/41243">my implementation of Cryptopals Challenge 1</a>, this is my solution to <a href="http://cryptopals.com/sets/1/challenges/3" rel="nofollow noreferrer">Challenge 3</a>.</p>
<blockquote>
<p>Single-byte XOR cipher The hex encoded string:</p>
<pre><code>1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736
</code></pre>
<p>... has been XOR'd against a single character. Find the key, decrypt
the message.</p>
<p>You can do this by hand. But don't: write code to do it for you.</p>
<p>How? Devise some method for "scoring" a piece of English plaintext.
Character frequency is a good metric. Evaluate each output and choose
the one with the best score.</p>
</blockquote>
<p>The idea here is that I try to decrypt with every possible single byte repeating key (each extended ascii/utf8 character), then compare the resulting character frequency to the expected frequency with a <a href="https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test" rel="nofollow noreferrer">Chi-Squared test</a>.</p>
<p><span class="math-container">$$
\chi^2 = \sum_{i=1}^n \frac{(obs - exp)^2}{exp}
$$</span></p>
<p>If <span class="math-container">\$\chi^2\$</span> < the critical value, then the decrypted cipher is determined to be English text, therefore we've cracked the cipher and found the key.</p>
<p>I'm some <a href="http://www.fitaly.com/board/domper3/posts/136.html" rel="nofollow noreferrer">data</a> and a build script to do some code generation before compiling the rest of the project.</p>
<h3>data/english.csv</h3>
<pre><code>32,17.1660
101,8.5771
116,6.3700
111,5.7701
97,5.1880
...
</code></pre>
<h3>build.rs</h3>
<pre><code>use std::env;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Write;
use std::path::Path;
fn main() {
let declaration = String::from("fn english_frequencies() -> HashMap<u8, f32> {[");
// csv must be 2 columns, no header
// ascii number, frequency as percentage
// 32,17.16660
let file = File::open("data/english.csv").unwrap();
let reader = BufReader::new(&file);
let formatted_lines = reader
.lines()
.map(|line| format!("({}),\n", line.unwrap()))
.collect();
let close = String::from("].iter().cloned().collect()}");
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("english_frequencies.rs");
let mut f = File::create(&dest_path).unwrap();
f.write_all(
&[declaration, formatted_lines, close]
.join("\n")
.into_bytes(),
).unwrap();
}
</code></pre>
<p>This generated table of expected frequencies is then included in a module that implements the frequency analysis.</p>
<h3>src/frequency.rs</h3>
<pre><code>use std::collections::HashMap;
include!(concat!(env!("OUT_DIR"), "/english_frequencies.rs"));
pub fn english(message: &str) -> bool {
let expected_counts: HashMap<char, f32> = english_frequencies()
.iter()
.map(|(k, freq)| (k.clone() as char, (freq / 100.0) * (message.len() as f32)))
.collect();
let actual_counts = message
.chars()
.fold(HashMap::new(), |mut acc: HashMap<char, isize>, c| {
let count = match acc.get(&c) {
Some(x) => x.clone() + 1,
None => 1,
};
acc.insert(c, count);
acc
});
let chi_statistic = chi_statistic(actual_counts, expected_counts);
if cfg!(debug_assertions) {
println!("X-statistic: {}", chi_statistic);
}
// Degrees of freedom = 256 - 1 = 255 (character space)
// Usign this table:
// https://en.wikibooks.org/wiki/Engineering_Tables/Chi-Squared_Distibution
// We can use the approximate value for 250 degrees of fredom.
// Given a significance factor (alpha) of 0.05, our critical value is 287.882.
// If our chi_statistic is < the critical_value, then we have a match.
// See this page for an explanation:
// https://en.wikipedia.org/wiki/Chi-squared_distribution#Table_of_%CF%872_values_vs_p-values
chi_statistic < 287.882
}
/// Calculates Pearson's Cumulative Chi Statistic
/// https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test#Calculating_the_test-statistic
///
/// This is a slight variation.
/// Technichally, if the expected value is zero and the actual is non-zero, then the statistic is infinite.
/// For the sake of ergonommics, this implementation assumes missing expected values to be small, but non-zero.
/// This allows us to only specify values in the expected frequencies that are statistically
/// significant while allowing for all valid utf-8 characters in the message.
fn chi_statistic(observed: HashMap<char, isize>, expected: HashMap<char, f32>) -> f32 {
observed
.into_iter()
.map(|(key, obs)| {
let exp = match expected.get(&key) {
Some(x) => x.clone() as f32,
None => 0.0000001, //non-zero, but tiny possibility
};
(obs as f32 - exp).powi(2) / exp
}).sum()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bacon_message_is_english() {
let message = "Cooking MC's like a pound of bacon";
assert!(english(message));
}
#[test]
fn message_with_unprintable_chars_is_not_english() {
assert!(!english(
"\u{7f}SSWUR[\u{1c}q\u{7f}\u{1b}O\u{1c}PUWY\u{1c}]\u{1c}LSIRX\u{1c}SZ\u{1c}^]_SR"
));
}
#[test]
fn printable_nonsense_is_not_english() {
assert!(!english("Yuuqst}:WY=i:vsq\u{7f}:{:juot~:u|:x{yut"));
}
#[test]
fn readable_but_incorrect_is_not_english() {
assert!(!english(
"cOOKING\u{0}mc\u{7}S\u{0}LIKE\u{0}A\u{0}POUND\u{0}OF\u{0}BACON"
));
}
}
</code></pre>
<p>Finally, we call it from the main program and crack the cipher.</p>
<h3>src/main.rs</h3>
<pre><code>extern crate cryptopals;
use cryptopals::byte_array::xor;
use cryptopals::frequency;
use cryptopals::hex;
use std::iter;
fn main() {
let secret =
hex::to_bytes("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
println!("{:?}", crack_xor(&secret));
}
fn crack_xor(cipher: &[u8]) -> Vec<String> {
let alphabet = 0..255u8; /* ascii/utf-8 range */
alphabet
.into_iter()
.filter_map(|c| {
let key = iter::repeat(c).take(cipher.len()).collect::<Vec<u8>>();
let decrypted = xor(&cipher, &key);
match String::from_utf8(decrypted) {
Ok(s) => Some(s),
Err(_) => None,
}
}).filter(|s| frequency::english(s))
.collect::<Vec<String>>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn analysis_matches_bacon_message() {
let secret =
hex::to_bytes("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
let actual = crack_xor(&secret);
assert_eq!(vec!["Cooking MC's like a pound of bacon"], actual);
}
}
</code></pre>
| [] | [
{
"body": "<p>Why use a build.rs here? Why not read english.csv in at runtime? For the purposes of an exercise like that I'm surprised you went to the trouble of converting the csv file into rust code like that.</p>\n\n<p>If you wanted to move as much work as possible to compile time you only went part way. You... | {
"AcceptedAnswerId": "204897",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T00:48:55.320",
"Id": "204313",
"Score": "7",
"Tags": [
"programming-challenge",
"cryptography",
"statistics",
"rust"
],
"Title": "Frequency Analysis & Chi-Squared Test"
} | 204313 |
<p>I have to count the number of contiguous sub-arrays whose sum is a perfect square.</p>
<p>For instance, if we have an array:</p>
<pre><code>number = [1,4,2,3,5]
</code></pre>
<p>Now the contiguous sub-arrays whose elements sum is a perfect square are:</p>
<pre><code>[1] [4] [4,2,3]
</code></pre>
<p>Total count = 3</p>
<p>To solve this problem I took an array which stores the prefix sum and then I run two loops to get the answer:</p>
<pre><code>int array[] = new int[n + 1];
int prefixSum[] = new int[n + 1];
int count = 0;
for (int index = 1; index <= n; index++) {
array[index] = in.nextInt();
prefixSum[index] = (prefixSum[index-1]+array[index]);
count +=isPerfectSquare(prefixSum[index])?1:0;
}
for (int prev = 1; prev <= n; prev++) {
for (int index = prev+1; index <= n; index++) {
count += isPerfectSquare(prefixSum[index]-prefixSum[prev]) ? 1 : 0;
}
}
System.out.println("count = " + count);
</code></pre>
<p>How can I improve this in terms of complexity?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T09:28:36.030",
"Id": "394112",
"Score": "1",
"body": "I don't think it is possible to improve time complexity unless there are some additional constraints. For example if sum of all elements would be known to be much smaller than N*... | [
{
"body": "<p>You don't really use <code>array[]</code>. You store a value in <code>array[index]</code>, and then immediately read the value back out, and then never use that value again. This results in unnecessary memory cycles.</p>\n\n<pre><code> array[index] = in.nextInt();\n prefixSum[index] = (pre... | {
"AcceptedAnswerId": "204370",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T01:58:27.863",
"Id": "204315",
"Score": "3",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Count contiguous sub-array whose sum is a perfect square"
} | 204315 |
<p>Fairly new to Python, and I have been doing a few Edabit challenges, to better help with my problem-solving. I have just completed a some what semi-difficult challenge, and I was hoping for some feed back. </p>
<p>The challenge itself:</p>
<blockquote>
<p>Create a function that takes an imgur link (as a string) and extracts
the unique id and type. Return an object containing the unique id, and
a string indicating what type of link it is.</p>
<p>The link could be pointing to:</p>
<ul>
<li>An album (e.g. <a href="https://imgur.com/a/cjh4E" rel="noreferrer">http://imgur.com/a/cjh4E</a>)</li>
<li>A gallery (e.g. <a href="https://imgur.com/gallery/59npG" rel="noreferrer">http://imgur.com/gallery/59npG</a>)</li>
<li>An image (e.g. <a href="https://imgur.com/OzZUNMM" rel="noreferrer">http://imgur.com/OzZUNMM</a>)</li>
<li>An image (direct link) (e.g. <a href="https://i.imgur.com/altd8Ld.png" rel="noreferrer">http://i.imgur.com/altd8Ld.png</a>)</li>
</ul>
<h3>Examples</h3>
<ul>
<li>"<a href="https://imgur.com/a/cjh4E" rel="noreferrer">http://imgur.com/a/cjh4E</a>" ➞ { id: "cjh4E", type: "album" }</li>
<li>"<a href="https://imgur.com/gallery/59npG" rel="noreferrer">http://imgur.com/gallery/59npG</a>" ➞ { id: "59npG", type: "gallery" }</li>
<li>"<a href="https://i.imgur.com/altd8Ld.png" rel="noreferrer">http://i.imgur.com/altd8Ld.png</a>" ➞ { id: "altd8Ld", type: "image" }</li>
</ul>
</blockquote>
<p>I came up with the following. </p>
<pre><code>import re
def imgurUrlParser(url):
url_regex = "^[http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.]*[imgur|i.imgur]*\.com"
url = re.match(url_regex, url).string
gallery_regex = re.match(url_regex + "(\/gallery\/)(\w+)", url)
album_regex = re.match(url_regex + "(\/a\/)(\w+)", url)
image_regex = re.match(url_regex + "\/(\w+)", url)
direct_link_regex = re.match(url_regex + "(\w+)(\.\w+)", url)
if gallery_regex:
return { "id" : gallery_regex.group(2), "type" : "gallery" }
elif album_regex:
return { "id" : album_regex.group(2), "type" : "album" }
elif image_regex:
return { "id" : image_regex.group(1), "type" : "image" }
elif direct_link_regex:
return { "id" : direct_link_regex.group(1), "type" : "image"}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T02:42:57.140",
"Id": "393947",
"Score": "0",
"body": "This code doesn't run. `direct_link_regex` is a string and strings don't have a `group()` method. Also, the parentheses for that regex are not balanced properly. Perhaps you copi... | [
{
"body": "<p>For a first pass, not bad! Your code is pretty easy to follow.</p>\n\n<p>Problems:</p>\n\n<ol>\n<li><p>Don't use <code>[]</code> to match different strings. <code>[]</code> matches any set of characters, so <code>[imgur|i.imgur]*</code> will match ``, <code>g</code>, <code>mgi</code>, etc. You pro... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T02:02:20.820",
"Id": "204316",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"regex",
"url"
],
"Title": "Imgur URL parser"
} | 204316 |
<blockquote>
<p><strong>Question:</strong> Write a program to swap pairs of characters of a String. In
case of odd number of characters last character should remain
unchanged. </p>
<p>Examples: </p>
<p>Input: HI</p>
<p>Output: IH</p>
<p>Input: hello there</p>
<p>Output: ehll ohtree</p>
</blockquote>
<p>My Code: </p>
<pre><code>import java.util.*;
class SwappedPairs
{
static String swapPairs(String str)
{
int len = str.length();
int n; //array's length
if(len%2 == 0)
{
n = len;
}
else
{
n=len-1;
}
char []arr = new char[n];
for(int i = 0; i< n; i++)
{
arr[i] = str.charAt(i);
}
StringBuffer str1 = new StringBuffer(n);
for(int i = 0; i<=n-2; i= i+2)
{
char temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
str1 = str1.append(arr[i]).append(arr[i+1]);
}
if(len%2 != 0)
{
str1 .append(str.charAt(len-1));
}
str = str1.toString();
return str;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = sc.nextLine();
System.out.println(swapPairs(str));
}
}
</code></pre>
<p>Any suggestion on how to improve it? (It gives the desired output)</p>
| [] | [
{
"body": "<p>Using a <code>StringBuffer</code> for building the new string is good,\nbut the variable name <code>str1</code> is non-descriptive.</p>\n\n<p>The computation of the required array length can be shortened \nwith the conditional operator:</p>\n\n<pre><code>int n = len % 2 == 0 ? len : len - 1;\n</co... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T06:34:34.483",
"Id": "204324",
"Score": "3",
"Tags": [
"java",
"strings",
"array"
],
"Title": "Swapping pairs of characters in a String"
} | 204324 |
<p>I need to apply a <a href="https://en.wikipedia.org/wiki/Gaussian_filter" rel="nofollow noreferrer">Gaussian filter</a> to a 2D numpy array where the distance between adjacent array elements depends on the row of the array. (Specifically, the data are evenly spaced in latitude and longitude but are not evenly spaced in terms of distance on the surface of the sphere.)</p>
<p>This means that I need a different filtering array for each row of data. My approach has been to pre-compute the filtering array for each row of pixels, then pass these arrays to SciPy's <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.generic_filter.html#scipy.ndimage.generic_filter" rel="nofollow noreferrer"><code>scipy.ndimage.generic_filter</code></a>, along with a function that selects the appropriate filtering array.</p>
<pre><code>import gc
import numpy as np
from scipy.ndimage import generic_filter
def convert_between_latitude_and_polar_angle(coord_array, angle='radians'):
rads = ['rad', 'rads', 'radian', 'radians']
degs = ['deg', 'degs', 'degree', 'degrees']
if angle in rads:
coord_array = np.pi/2 - coord_array
elif angle in degs:
coord_array = 90 - coord_array
else:
print('angle must be radians or degrees!')
quit()
return coord_array
def calculate_haversine_distances_between_theta_phi_points(theta_2, phi_2, theta_1, phi_1, sphere_radius, angle='radians'):
'''
Calculate the haversine-based distance between two points on the surface of a sphere. Should be more accurate than the arc cosine strategy. See, for example: http://en.wikipedia.org/wiki/Haversine_formula
'''
rads = ['rad', 'rads', 'radian', 'radians']
degs = ['deg', 'degs', 'degree', 'degrees']
if angle in rads:
degrees = False
elif angle in degs:
degrees = True
theta_2 = np.radians(theta_2)
phi_2 = np.radians(phi_2)
theta_1 = np.radians(theta_1)
phi_1 = np.radians(phi_1)
else:
print('angle must be radians or degrees!')
quit()
spherical_distance = 2.0 * sphere_radius * np.arcsin(np.sqrt( ((1 - np.cos(theta_2-theta_1))/2.) + np.sin(theta_1) * np.sin(theta_2) * ( (1 - np.cos(phi_2-phi_1))/2.) ))
return spherical_distance
class Surface(object):
'''
the surface class defines a surface on a segment of a spherical shell. it
contains a numpy meshgrid of coordinates in theta and phi, and a
corresponding array of the surface values at each coordinate pair.
should passed as [rs, thetas, phis] (or equivalent ndarray)
'''
def __init__(self, data, coords='spherical', r=6371000, angle='radians'):
rads = ['rad', 'rads', 'radian', 'radians']
degs = ['deg', 'degs', 'degree', 'degrees']
if angle in rads:
pass
elif angle in degs:
data[1] = np.radians(data[1])
data[2] = np.radians(data[2])
else:
print("angle must be 'radians' or 'degrees'!")
quit()
self.surface = np.array(data[0], dtype="float16")
self.thetas = np.array(data[1], dtype="float16")
self.phis = np.array(data[2], dtype="float16")
self.r = r
self.dtheta = self.thetas[1, 0] - self.thetas[0, 0]
self.dphi = self.phis[0, 1] - self.phis[0, 0]
def smooth(self, sigma=50000, n_sigma=4):
# here we construct the 'private' filtering function
## here 'middle_theta' is (2*m)+1 due to the way the flattening works
def spherical_gaussian_filter(image_slice, filter_arrays, middle_theta):
n_middle_theta = int(image_slice[middle_theta])
return (image_slice * filter_arrays[n_middle_theta]).sum()
# we can get the required height of the Gaussian array immediately,
# since degrees of latitude are evenly spaced (on a perfect sphere)
## first get the required change in theta to cover n*sigma on the sphere
Delta_theta = n_sigma*sigma/self.r
## next, get the required size of the array's outer dimension (its
## vertical size) AWAY from the centre pixel (i.e. the total size of the
## outer dimension is 2m+1)
## applying ceil guarantees we are at least as good as n*sigma
m = np.ceil(Delta_theta/np.abs(self.dtheta)).astype('int')
# now get the maximum required width of the Gaussian array
## the maximum width will be at the most extremal value of theta
## convert to latitude so finding the angle farthest from the equator is
## easy
latitudes = convert_between_latitude_and_polar_angle(self.thetas)
max_theta = convert_between_latitude_and_polar_angle(np.max(np.abs(latitudes[..., 0])))
del latitudes
gc.collect()
## now get the required change in phi
Delta_phi = n_sigma*sigma/(self.r*np.sin(max_theta))
print(np.degrees(Delta_theta))
print(np.degrees(Delta_phi))
## and then the size of the inner dimension of the array (away from the
## centre pixel)
n = np.ceil(Delta_phi/self.dphi).astype('int')
# next create all the arrays of coordinates around the central element
# note that we only need an array for each row of pixels, since they
# are independant of longitude
## first make arrays corresponding to the coordinates of the 'central'
## pixel for each row
## the None suffix in the array slicing functions like numpy.expand_dim
central_thetas = np.broadcast_to(self.thetas[..., 0, None, None], (len(self.thetas), 2*m+1, 2*n+1))
central_phis = np.zeros_like(central_thetas, dtype="float16")
## create the arrays of distances (relative coordinates) in theta and
## phi from the central pixel
relative_theta = np.arange(-m, m + 1, dtype="float16")*np.abs(self.dtheta)
relative_phi = np.arange(-n, n + 1, dtype="float16")*self.dphi
relative_phis, relative_thetas = np.meshgrid(relative_phi, relative_theta)
del relative_phi, relative_theta
gc.collect()
## now we can get the actual coordinates of each element of the
## filtering array
absolute_thetas = (central_thetas + relative_thetas).astype("float16")
del relative_thetas
gc.collect()
absolute_phis = (central_phis + relative_phis).astype("float16")
del relative_phis
gc.collect()
# next we need the distance on the surface of the sphere from the
# central pixel to each element
## use the Haversine formula, slightly adapted from the formulation used
## in 2017 for my honours project
print("About to do distances between points")
print(absolute_thetas.shape)
distances_from_central_pixel = calculate_haversine_distances_between_theta_phi_points(absolute_thetas, absolute_phis, central_thetas, central_phis, self.r)
del absolute_thetas, absolute_phis, central_thetas, central_phis
gc.collect()
# now we need to calculate the gaussian weights of each distance array
gaussian_weights = ( 1 / (sigma*np.sqrt(2*np.pi)) ) * np.exp( -0.5 * (distances_from_central_pixel / sigma)**2 )
# and normalise
sums = gaussian_weights.sum(axis=(1,2))[..., None, None]
gaussian_weights /= sums
del sums
gc.collect()
# print(gaussian_weights, end='\n\n')
# we need to add in the zeros that will take care of the theta_ns in the
# surface that is passed to generic_filter
gaussian_weights = gaussian_weights.flatten()
gaussian_weights = np.insert(gaussian_weights, np.arange(1, len(gaussian_weights) + 1), np.zeros(len(gaussian_weights)))
gaussian_weights = gaussian_weights.reshape(len(self.thetas), 2*(2*m+1)*(2*n+1))
# lastly, need to create an array with the n of each theta at each point
# on the surface
surface = np.copy(self.surface).flatten()
theta_ms = np.arange(len(self.surface)).reshape(len(self.surface), 1)
theta_ms = np.repeat(theta_ms, len(self.surface[0])).flatten()
surface_with_theta_ms = np.insert(surface, np.arange(1, len(surface) + 1), theta_ms)
surface_with_theta_ms = surface_with_theta_ms.reshape(len(self.surface), len(self.surface[0]), 2)
del surface, theta_ms
gc.collect()
# print(surface_with_theta_ms, end='\n\n')
# pass generic_filter an array which is pretending to be 2d but each element actually contains the height, theta
self.filtered_surface = generic_filter(surface_with_theta_ms.astype("float16"), spherical_gaussian_filter, size=(2*m+1, 2*n+1, 2), extra_arguments=(gaussian_weights, (2*m)+1))[:,:,0]
del surface_with_theta_ms
gc.collect()
if __name__ == '__main__':
m, n = 300, 400
x, y = np.meshgrid(np.linspace(-15, 15, num=n), np.linspace(120, 150, num=m))
surface = np.ones((m,n))
surface[:,int(n/2):] = surface[:,int(n/2):] * 0
test_data = np.array([surface, y, x])
print(test_data[0], end='\n\n')
test_surface = Surface(test_data, angle='deg')
test_surface.smooth(sigma=50000, n_sigma=4)
print(test_surface.filtered_surface)
</code></pre>
<p>It works fine for small arrays of data, but when I scale it up to run on my data (~ 3000 x 2000 pixels), my pre-computed filtering arrays are large, and there's around 2000 of them, resulting in using up all 22 GB of free RAM.</p>
<p>As you can see I've made some efforts to reduce memory usage already by using less accurate data types in my ndarrays by using <code>gc.collect()</code>, but the program still uses all 22 GB of RAM when it tries to calculate the distances on the surface of the sphere for each filtering array.</p>
<p>This is my first time posting a question to Code Review, so I appreciate that it might be inappropriate as written, but I really am at a loss for how to reduce memory usage further.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T10:02:53.453",
"Id": "394113",
"Score": "1",
"body": "@Graipher Thanks for the feedback! I've included the two functions as well as the test data I was running it on"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T11:25:59.207",
"Id": "204341",
"Score": "1",
"Tags": [
"python",
"performance",
"numpy",
"memory-optimization",
"scipy"
],
"Title": "Applying a filter to a large array with elements that are not regularly spaced"
} | 204341 |
<p>This is an implementation of a general Purpose Parser/Matcher that can operate on any input stream of objects and will return all possible combinations.</p>
<p>In this case I do not value performance that much, but if you find something major, tell me.</p>
<p>This does by design no optimizations before parsing to be easily editable.</p>
<pre><code>from __future__ import annotations
from typing import Iterator, TypeVar, Iterable, Generic, List
T = TypeVar('T')
class Rewindable(Iterator[T]):
"""
A Rewindable Wrapper around an iterator the allows for 'rewinding'
the iterator by reloading an old state
"""
def __init__(self, iterator: Iterable[T]):
self._iterator = iter(iterator)
self._index = 0
self._cache = []
def __next__(self) -> T:
self._index += 1
while self._index > len(self._cache):
self._cache.append(next(self._iterator))
return self._cache[self._index - 1]
def get_state(self) -> object:
"""Returns an object indicating the current position
that can be reloaded via `load_state`"""
return self._index
def load_state(self, state: object):
"""Reloads a state returned by `get_state`"""
assert isinstance(state, int)
self._index = state
IN = TypeVar('IN')
OUT = TypeVar('OUT')
class Parser(Generic[IN, OUT]):
"""
Base class for Parser which match pattern in an rewindable
input stream and return all possible matches
"""
def parse(self, in_stream: Rewindable[IN]) -> Iterator[Iterator[OUT]]:
"""
Matches the pattern in the Rewindable stream `in_stream`
Returns an Iterator over all possible matches (also iterator)
The implementation must insure that `in_stream` is reset
after StopIteration is thrown
"""
raise NotImplementedError
class DirectParser(Parser):
"""
A Parser that matches the value `expected` and yields `result` in response
"""
def __init__(self, expected: IN, result: OUT):
self.expected = expected
self.result = result
def __repr__(self):
return f"<{self.expected!r}>"
def parse(self, in_stream: Rewindable[IN]) -> Iterator[Iterator[OUT]]:
state = in_stream.get_state()
try:
n = next(in_stream)
except StopIteration:
return
if n == self.expected:
yield iter((self.result,))
in_stream.load_state(state)
class ORParser(Parser[IN, OUT]):
"""
A Parser that matches any Parser of `sub_parser` and returns all possible results of each one
"""
def __init__(self, sub_parser: List[Parser[IN, OUT]]):
self._sub_parser = list(sub_parser)
def __repr__(self):
return '(' + '|'.join(repr(sp) for sp in self._sub_parser) + ')'
def parse(self, in_stream: Rewindable[IN]) -> Iterator[Iterator[OUT]]:
for sp in self._sub_parser:
yield from sp.parse(in_stream)
class ANDParser(Parser[IN, OUT]):
"""
A Parser that matches the Parsers of `sub_parser` and returns all possible combinations
"""
def __init__(self, sub_parser: List[Parser[IN, OUT]]):
self._sub_parser = list(sub_parser)
def __repr__(self):
return '(' + ' '.join(repr(sp) for sp in self._sub_parser) + ')'
def parse(self, in_stream: Rewindable[IN]) -> Iterator[Iterator[OUT]]:
iterator_stack = [self._sub_parser[0].parse(in_stream)]
try:
result = [tuple(next(iterator_stack[0]))]
except StopIteration:
return
skip = False
while len(iterator_stack) > 0:
if not skip:
if len(iterator_stack) == len(self._sub_parser):
assert len(result) == len(self._sub_parser)
yield (v for t in result for v in t)
else:
iterator_stack.append(self._sub_parser[len(iterator_stack)].parse(in_stream))
result.append(())
try:
result[-1] = tuple(next(iterator_stack[-1]))
skip = False
except StopIteration:
skip = True
result.pop()
iterator_stack.pop()
class RepeatingNGParser(Parser[IN, OUT]):
"""
A Parser that matches `min_count` to `max_count` repetitions of Parser `parser`
and returns all possible combinations (Non Greedy, matches as few repetitions as possible first
`max_count` can be `None` to indicate that the repetition can be infinite
"""
def __init__(self, parser: Parser[IN, OUT], min_count: int, max_count: int = None):
self.parser = parser
self.min_count = min_count
self.max_count = max_count
def parse(self, in_stream: Rewindable[IN]) -> Iterator[Iterator[OUT]]:
count = self.min_count
if count == 0: # Special case Optional matching
yield iter(())
count = 1
while self.max_count is None or self.max_count > count:
iterator_stack = [self.parser.parse(in_stream)]
try:
result = [tuple(next(iterator_stack[0]))]
except StopIteration:
return
skip = False
any_result = False
while len(iterator_stack) > 0:
if not skip:
if len(iterator_stack) >= count:
assert len(result) == len(iterator_stack)
any_result = True
yield (v for t in result for v in t)
else:
iterator_stack.append(self.parser.parse(in_stream))
result.append(())
try:
result[-1] = tuple(next(iterator_stack[-1]))
skip = False
except StopIteration:
skip = True
result.pop()
iterator_stack.pop()
count += 1
if not any_result:
return
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T12:08:14.390",
"Id": "204342",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"parsing"
],
"Title": "Simple General Purpose Parser Implementation"
} | 204342 |
<p>I created <a href="https://codesandbox.io/s/6vx977rr8r" rel="nofollow noreferrer">this simple react application</a> for a coding challenge, which is described in the linked README file. Basically, I created the components and helper logic to display dynamic JSON data in a sortable table.</p>
<p>I did not clear the coding challenge and I am looking for some feedback on how this could be done better. Note that the solution does work but the code quality may not be that good.</p>
<p>In my opinion, the issue could be how I implemented this <code>getSortedData</code> function:</p>
<pre><code>import moment from "moment";
export const getSortedData = (tableData, sortBy, sortOrderAsc) => {
tableData.rows.sort((a, b) => {
const valueA = a[sortBy];
const valueB = b[sortBy];
switch (sortBy) {
case "title": {
return valueA.toLowerCase() > valueB.toLowerCase() ? 1 : -1;
}
case "releaseDate": {
const momentA = moment(valueA, "DD-MM-YYYY");
const momentB = moment(valueB, "DD-MM-YYYY");
if (!momentA.isValid()) {
return 1;
}
if (!momentB.isValid()) {
return -1;
}
return momentA.isAfter(momentB) ? 1 : -1;
}
case "productionBudget":
case "worldwideBoxOffice":
case "number": {
if (Number.isNaN(parseFloat(valueA))) return -1;
if (Number.isNaN(parseFloat(valueB))) return 1;
return valueA > valueB ? 1 : -1;
}
default: {
return valueA > valueB ? 1 : -1;
}
}
});
if (!sortOrderAsc) {
tableData.rows.reverse();
}
return tableData;
};
</code></pre>
<p>Where <code>sortBy</code> could be the <code>id</code> of one of the columns in following tableData. <code>sortOrderAsc</code> is a boolean which tells whether the data ia sorted in ascending order. <code>tableData</code> is as following:</p>
<pre><code> {
"columns": [
{ "id": "number", "title": "Number" },
{ "id": "title", "title": "Movie" },
{ "id": "releaseDate", "title": "Release Date" },
{ "id": "productionBudget", "title": "Production Budget in $" },
{ "id": "worldwideBoxOffice", "title": "Worldwide Box Office in $" }
],
"rows": [
{
"number": 1,
"releaseDate": "02-05-2008",
"title": "Iron Man",
"productionBudget": 186000000,
"worldwideBoxOffice": 585171547
},
{
"number": 2,
"releaseDate": "13-06-2008",
"title": "The Incredible Hulk",
"productionBudget": 137500000,
"worldwideBoxOffice": 265573859
},
{
"number": 3,
"releaseDate": "07-05-2010",
"title": "Iron Man 2",
"productionBudget": 170000000,
"worldwideBoxOffice": 621156389
},
{
"number": 4,
"releaseDate": "06-05-2011",
"title": "Thor",
"productionBudget": 150000000,
"worldwideBoxOffice": 449326618
},
{
"number": 5,
"releaseDate": "22-07-2011",
"title": "Captain America: The First Avenger",
"productionBudget": 140000000,
"worldwideBoxOffice": 370569776
},
{
"number": 6,
"releaseDate": "04-05-2012",
"title": "The Avengers",
"productionBudget": 225000000,
"worldwideBoxOffice": 1519479547
},
{
"number": 7,
"releaseDate": "03-05-2013",
"title": "Iron Man 3",
"productionBudget": 200000000,
"worldwideBoxOffice": 1215392272
},
{
"number": 8,
"releaseDate": "08-11-2013",
"title": "Thor: The Dark World",
"productionBudget": 150000000,
"worldwideBoxOffice": 644602516
},
{
"number": 9,
"releaseDate": "04-04-2014",
"title": "Captain America: The Winter Soldier",
"productionBudget": 170000000,
"worldwideBoxOffice": 714401889
},
{
"number": 10,
"releaseDate": "01-08-2014",
"title": "Guardians of the Galaxy",
"productionBudget": 170000000,
"worldwideBoxOffice": 771051335
},
{
"number": 11,
"releaseDate": "01-05-2015",
"title": "Avengers: Age of Ultron",
"productionBudget": 330600000,
"worldwideBoxOffice": 1408218722
},
{
"number": 12,
"releaseDate": "17-07-2015",
"title": "Ant-Man",
"productionBudget": 130000000,
"worldwideBoxOffice": 518860086
},
{
"number": 13,
"releaseDate": "06-05-2016",
"title": "Captain America: Civil War",
"productionBudget": 250000000,
"worldwideBoxOffice": 1153304495
},
{
"number": 14,
"releaseDate": "04-11-2016",
"title": "Doctor Strange",
"productionBudget": 165000000,
"worldwideBoxOffice": 677323653
},
{
"number": 15,
"releaseDate": "05-05-2017",
"title": "Guardians of the Galaxy Vol 2",
"productionBudget": 200000000,
"worldwideBoxOffice": 862888462
},
{
"number": 16,
"releaseDate": "07-07-2017",
"title": "Spider-Man: Homecoming",
"productionBudget": 175000000,
"worldwideBoxOffice": 880070886
},
{
"number": 17,
"releaseDate": "03-11-2017",
"title": "Thor: Ragnarok",
"productionBudget": 180000000,
"worldwideBoxOffice": 850650283
},
{
"number": 18,
"releaseDate": "16-02-2018",
"title": "Black Panther",
"productionBudget": 200000000,
"worldwideBoxOffice": 1346960289
},
{
"number": 19,
"releaseDate": "27-04-2018",
"title": "Avengers: Infinity War",
"productionBudget": 300000000,
"worldwideBoxOffice": 2017483467
},
{
"number": 20,
"releaseDate": "06-06-2018",
"title": "Ant-Man and the Wasp",
"productionBudget": 130000000,
"worldwideBoxOffice": 361759753
},
{
"number": 21,
"releaseDate": "Unknown",
"title": "The Eternals",
"productionBudget": 0,
"worldwideBoxOffice": 0
},
{
"number": 22,
"releaseDate": "Unknown",
"title": "Black Widow",
"productionBudget": 0,
"worldwideBoxOffice": 0
},
{
"number": 23,
"releaseDate": "08-05-2019",
"title": "Captain Marvel",
"productionBudget": 0,
"worldwideBoxOffice": 0
},
{
"number": 24,
"releaseDate": "03-05-2019",
"title": "UnreleaseDated Avengers Movie"
},
{
"number": 25,
"releaseDate": "05-07-2019",
"title": "Spider-Man: Far From Home"
},
{
"number": 26,
"releaseDate": "2020",
"title": "Guardians of the Galaxy Vol 3",
"productionBudget": 0,
"worldwideBoxOffice": 0
}
]
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T15:02:09.987",
"Id": "394032",
"Score": "0",
"body": "I don't think it is possible for me to paste the code here, as I want to review the whole solution, how I broke the components, if I should be making more smaller components and ... | [
{
"body": "<p>I don't know why you didn't clear the coding challenge. It looks mostly alright. </p>\n\n<p>There's a couple of things I think could be improved:</p>\n\n<ul>\n<li>getSortedData mutates the tableData. Only setState should be able to mutate state.</li>\n<li>getSortedData has hard-coded the column na... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T13:44:25.157",
"Id": "204348",
"Score": "4",
"Tags": [
"javascript",
"sorting",
"json",
"react.js"
],
"Title": "Sorting function from a React app to display JSON data in a sortable table"
} | 204348 |
<pre><code>$a=$_GET["a"];
$b=$_GET["b"];
$a=str_replace("%", "\%", $a);
$b=str_replace("%", "\%", $b);
$sql="SELECT * FROM table ";
$sql.="WHERE ColA LIKE :txtA AND ColB LIKE :txtB";
$query = $db->prepare($sql);
$query->bindValue(':txtA', '%'.$a.'%', PDO::PARAM_STR);
$query->bindValue(':txtB', '%'.$b.'%', PDO::PARAM_STR);
$query->execute();
</code></pre>
<p>I want to give user ability to search anything. Should I filter more characters? Will it be 100% safe and work as it should do for searching pieces of text in database?</p>
<p>Edit:
ColA and ColB are strings, just text (phrase and tags in search engine)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T15:13:02.347",
"Id": "394035",
"Score": "0",
"body": "Please [edit] to add some description. What do `ColA` and `ColB` represent? What's the schema? What flavour of SQL? This mostly looks like stub/sample code rather than real c... | [
{
"body": "<blockquote>\n <p>I want to give user ability to search anything.</p>\n</blockquote>\n\n<p>It looks like you've achieved that, however, I'd use <code>$_POST</code> to reduce the likelihood that your application will be taken offline by users opening multiple tabs or search engine spiders hitting URL... | {
"AcceptedAnswerId": "204356",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T14:26:39.740",
"Id": "204352",
"Score": "2",
"Tags": [
"php",
"sql",
"pdo",
"sql-injection"
],
"Title": "Is this a 100% safe from SQL Injection and will work correctly for any input?"
} | 204352 |
<p>A palindromic number reads the same both ways.</p>
<p>The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.</p>
<p>Find the largest palindrome made from the product of two 3-digit numbers.</p>
<pre><code><?php
function isPalindrome($input) {
return (string) $input === strrev($input);
}
$max = 999;
$min = 100;
$found = 0;
for ($i = $max; $i >= $min; $i--) {
for ($j = $max; $j >= $min; $j--) {
$result = $i * $j;
if (isPalindrome($result)) {
if ($result > $found) {
$found = $result;
$a = $i;
$b = $j;
}
}
}
}
print sprintf("Found %d times %d = %d", $a, $b, $found);
</code></pre>
| [] | [
{
"body": "<p>Your outer loop starts at 999 and the inner loop multiplies that by all the numbers from 999 down to 100.</p>\n\n<p>Then your outer loop decrements <code>$i</code> to 998, and the inner loop multiplies that by all the numbers from 999 down to 100. The first test <code>998*999</code> has already b... | {
"AcceptedAnswerId": "204375",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T14:41:32.857",
"Id": "204353",
"Score": "4",
"Tags": [
"php",
"programming-challenge",
"palindrome"
],
"Title": "Solve Project Euler #4 in PHP"
} | 204353 |
<p><strong>Summary:</strong> The basic calculator which allows the end-user to calculate the value by evaluating the math expression string. It supports all the main arithmetic operators, also extended by modulo and exponent operations. Evaluation does follow the classic arithmetic rules and precedence and does take parentheses into consideration.</p>
<p><strong>Note:</strong> While it detects a bunch of errors on the end-user side (such as division by zero or incorrect parentheses), most of them are left unnoticed. The user input of "----1" is still considered valid. The iterator, which presumably parses the integer/float, do not detect forbidden characters, so "5.0g" is also valid. To add, I could have used the <code>istringstream</code> for parsing values, but chose to do it manually as an exercise and wish to leave it as is.</p>
<p>Would like to hear the tips.</p>
<pre><code>#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <string_view>
#include <algorithm>
#include <stack>
#include <memory>
#include <cmath>
#include <cctype>
#include <regex>
class Calculator {
private:
Calculator() = default;
Calculator(std::string const& str) : _expr(str) {
_expr.erase(std::remove_if(std::begin(_expr), std::end(_expr), [&](auto ch) -> bool { return std::isspace(ch); }), std::end(_expr));
try {
std::stack<std::string::value_type> p_stack;
for (const auto& ch : _expr) {
switch (ch) {
case '(': p_stack.push('('); break;
case ')': if (p_stack.empty() || p_stack.top() != '(')
throw std::runtime_error("error: unbalanced or unexpected parentheses\n");
else
p_stack.pop(); break;
default: break;
}
}
if (!p_stack.empty())
throw std::runtime_error("error: unbalanced or unexpected parentheses\n");
fretval = evaluate();
std::cout << fretval << "\n";
}
catch (std::exception const& e) { std::cerr << e.what() << "\n"; }
}
enum class enum_op_t : char
{ OP_ADD = '+', OP_SUB = '-', OP_EXP = '^', OP_MUL = '*', OP_DIV = '/', OP_MOD = '%', NULLTYPE = '0' };
class operator_t {
public:
enum_op_t _type;
unsigned short _priority = 0;
char _assoc;
operator_t(enum_op_t const& s, unsigned short i = 0, char a = 'L')
: _type(s), _priority(i), _assoc(a) {}
private:
operator_t() = delete;
};
Calculator(Calculator const&) = delete;
Calculator(Calculator&&) = delete;
auto operator=(Calculator const&) = delete;
std::string _expr;
std::string::iterator _cur = std::begin(_expr);
std::stack<std::pair<operator_t, double>> mid;
double fretval;
auto getOperator() {
switch (*_cur) {
case '+': _cur++; return operator_t(enum_op_t::OP_ADD, 1, 'L');
case '-': _cur++; return operator_t(enum_op_t::OP_SUB, 1, 'L');
case '*': _cur++; return operator_t(enum_op_t::OP_MUL, 2, 'L');
case '/': _cur++; return operator_t(enum_op_t::OP_DIV, 2, 'L');
case '^': _cur++; return operator_t(enum_op_t::OP_EXP, 3, 'R');
case '%': _cur++; return operator_t(enum_op_t::OP_MOD, 2, 'L');
default: return operator_t(enum_op_t::NULLTYPE); break;
}
}
auto getNumerical() {
std::string::iterator _tmp = _cur;
for (; std::isdigit(*(_tmp)) || *_tmp == '.'; ++_tmp) {}
std::string tstr = std::string(_cur, _tmp);
if (!std::regex_match(tstr, std::regex {"[+-]?([0-9]*[.])?[0-9]+"})) {
throw std::runtime_error("error: could not parse token, expect <int> or <float>.\n");
}
auto retval = std::stod(tstr);
_cur = _tmp;
return retval;
};
auto performOp(operator_t var, double lhs, double rhs) {
switch (var._type) {
case enum_op_t::OP_ADD: return lhs + rhs;
case enum_op_t::OP_DIV: if (!rhs) {
throw std::runtime_error("error: division by zero.\n");
}
else
return lhs / rhs;
case enum_op_t::OP_MUL: return lhs * rhs;
case enum_op_t::OP_SUB: return lhs - rhs;
case enum_op_t::OP_MOD: if (!rhs) {
throw std::runtime_error("error: mod 0 is forbidden.\n");
}
else
return std::fmod(lhs, rhs);
case enum_op_t::OP_EXP: return std::pow(lhs, rhs);
default: return 0.0;
}
}
double getValue() {
double retval = 0;
switch (*_cur) {
case '0': case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
retval = getNumerical(); break;
case '(':
_cur++; retval = evaluate();
if (*_cur != ')') {
if (_cur <= std::end(_expr))
throw std::runtime_error("error");
throw std::runtime_error("error: value expected, got token.\n");
}
_cur++; break;
case '+': _cur++; retval = getValue(); break;
case '-': _cur++; retval = getValue() * (-1); break;
default: throw std::runtime_error("error: unexpected expression, could not parse.\n");
}
return retval;
}
double evaluate() {
mid.push({ operator_t {enum_op_t::NULLTYPE}, 0 });
double retval = getValue();
while (!mid.empty()) {
operator_t var { getOperator() };
while (var._priority < mid.top().first._priority || (var._priority == mid.top().first._priority && var._assoc == 'L'))
{
if (mid.top().first._type == enum_op_t::NULLTYPE) {
mid.pop(); return retval;
}
retval = performOp(mid.top().first, mid.top().second, retval);
mid.pop();
}
mid.push({ var, retval }); retval = getValue();
}
return 0;
}
public:
static auto& getInstance(std::string const& expr) {
Calculator c(expr);
return c;
}
};
int main() {
for (;;) {
std::cout << "<calc> ";
std::string input;
std::getline(std::cin, input);
Calculator::getInstance(input);
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T16:03:51.350",
"Id": "394046",
"Score": "0",
"body": "@firda I don't want the review to be tied to the specific version of standard. If rules require that, I can also add C++14 to the tags list."
},
{
"ContentLicense": "CC B... | [
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Put each statement on a separate line</h2>\n\n<p>Instead of crowding things together like this:</p>\n\n<pre><code>case '(': p_stack.push('('); break;\n</code></pre>\n\n<p>it seems to me to be more readable if each statemen... | {
"AcceptedAnswerId": "204418",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T15:30:57.940",
"Id": "204357",
"Score": "7",
"Tags": [
"c++",
"c++14",
"math-expression-eval"
],
"Title": "Basic arithmetic calculator with float, parentheses and operator priority support"
} | 204357 |
<p><strong><em>Is this a good approach or I've just found a nasty workaround?</em></strong></p>
<p>I'm using <code>MediatorLiveData</code> class because seems useful to update the source of a <code>LiveData</code> object.</p>
<p>I mean, the majority of tutorials that I've found on internet just use <code>Livedata</code> or <code>MutableLivedata</code> without a dynamic source, in example:</p>
<pre><code>fun search(/*no input params*/): Call<List<Person>>
</code></pre>
<p>But in my case, I have the following web service that performs a search by name:</p>
<pre><code>interface APIServidor {
@GET("search")
fun search(@Query("name") name: String): Call<List<Person>>
}
public class PeopleRepository {
public LiveData<List<Person>> search(String name){
final MutableLiveData<List<Person>> apiResponse = new MutableLiveData<>();
Call<List<Person>> call = RetrofitService.Companion.getInstance().getApiServer().search(name);
call.enqueue(new Callback<List<Person>>() {
@Override
public void onResponse(@NonNull Call<List<Person>> call, @NonNull Response<List<Person>> response) {
if (response.isSuccessful()) {
apiResponse.postValue(response.body());
}
}
@Override
public void onFailure(@NonNull Call<List<Person>> call, @NonNull Throwable t) {
apiResponse.postValue(null);
}
});
return apiResponse;
}
}
</code></pre>
<p>Then in the viewmodel class I'm adding source per new request.</p>
<pre><code>public class SearchViewModel extends ViewModel {
private MediatorLiveData<List<Person>> mApiResponse;
private PeopleRepository mApiRepo;
public SearchViewModel() {
mApiResponse = new MediatorLiveData<>();
mApiRepo = new PeopleRepository();
}
public LiveData<List<Person>> getPlayers() {
return mApiResponse;
}
public void performSearch(String name){
mApiResponse.addSource(mApiRepo.search(name), new Observer<List<Person>>() {
@Override
public void onChanged(List<Person> apiResponse) {
mApiResponse.setValue(apiResponse);
}
});
}
}
</code></pre>
<p>Activity</p>
<pre><code>bt_search.setOnClickListener {
val player_name = et_player.text.toString()
viewModel.performSearch(player_name)
}
</code></pre>
<h1>Project scope</h1>
<p>I'm in a personal project</p>
<h1>Goals</h1>
<p>Use MVVM + Live data + Repository pattern</p>
<h1>Problem</h1>
<p>I've only found tutorials with a simple approach: observe a <code>LiveData</code> object that access to a <code>repository</code> object and fetch data only once. </p>
<p>In example: Fetch all people (<code>select * from people</code>) from web service.</p>
<p>My case: Fetch people that mach a name (<code>select * from people where name=?</code>) from web service.</p>
<p><a href="https://medium.com/@elye.project/kotlin-and-retrofit-2-tutorial-with-working-codes-333a4422a890" rel="nofollow noreferrer">https://medium.com/@elye.project/kotlin-and-retrofit-2-tutorial-with-working-codes-333a4422a890</a>
<a href="https://medium.com/@sriramr083/error-handling-in-retrofit2-in-mvvm-repository-pattern-a9c13c8f3995" rel="nofollow noreferrer">https://medium.com/@sriramr083/error-handling-in-retrofit2-in-mvvm-repository-pattern-a9c13c8f3995</a></p>
<h1>Doubts</h1>
<p>Is a good idea use <code>MediatorLiveData</code> class to <code>merge</code> all requests took from user input?</p>
<p>Should I use <code>MutableLiveData</code> and change the <code>repository</code> class and use a custom clousure?</p>
<p>Is there a better approach? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T06:35:50.227",
"Id": "394093",
"Score": "1",
"body": "Does it work for whatever you want it to do? Please add a description of what problem your code solves in less general terms. You're doing something with people and companions, b... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T20:29:48.730",
"Id": "204369",
"Score": "1",
"Tags": [
"android",
"mvvm",
"kotlin"
],
"Title": "LiveData, MVVM and Repository Pattern"
} | 204369 |
<p>I would like to compare the min/max values of a time-series with a test time-series. Additionally, I would like to compare the time of the "peaks". However, I'm having trouble extracting these features from a Pandas DataFrame.</p>
<p>Given the following data:</p>
<pre><code>def fake_phase_data():
in_li = []
sample_points = 24 * 4
for day, bias in zip((11, 12, 13), (.5, .7, 1.)):
day_time = datetime(2016, 6, day, 0, 0, 0)
for x in range(int(sample_points)):
in_li.append((day_time + timedelta(minutes=15*x),
bias * np.sin(2 * np.pi * x / sample_points + (1.2*bias)),
bias))
fake_df = pd.DataFrame(in_li, columns=("time", "phase_sig", "bias")).set_index("time")
return fake_df
fp = fake_phase_data()
# Convert to pivot-table with 24 hour columns
dfs = {
col: pd.pivot_table(
fp,
index=fp.index.date,
columns=fp.index.hour,
values=col,
aggfunc='mean',
)
for col in fp.columns
}
ddf = pd.concat(dfs, axis=1)
</code></pre>
<p>Which looks like:</p>
<pre><code>for i in range(len(ddf)):
ddf["phase_sig"].iloc[i].plot()
</code></pre>
<p><a href="https://i.stack.imgur.com/FYxx9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FYxx9.png" alt="data_viz"></a></p>
<p>I process the data:</p>
<pre><code>def col_peaks(df, cols, peak_func):
return [list(getattr(df[col], peak_func)(axis=1).values) for col in cols]
def peak_vals(df, cols, t_peak):
peak_v = []
for c_i, col in enumerate(cols):
vals = df[col].values
peak_idx = t_peak[c_i]
peak_v.append(list(vals[np.arange(len(peak_idx)), peak_idx]))
return peak_v
# I may want to process multiple columns later
# but let's focus on the single-column case
x_cols = ["phase_sig"]
# Technically, I also want the minimum
# but let's focus on the maximum case first
orig_t_max = col_peaks(ddf, x_cols, "idxmax")
print("Orig t_max", orig_t_max)
orig_v_max = peak_vals(ddf, x_cols, orig_t_max)
print("Orig v_max", orig_v_max)
# actual test data will be a single row in a dataframe
# but this test is fine for now
test_df = ddf.iloc[[0]]
test_t_max = col_peaks(test_df, x_cols, "idxmax")
print("Test t_max", test_t_max)
test_v_max = peak_vals(test_df, x_cols, test_t_max)
print("Test v_max", test_v_max)
</code></pre>
<p>And get the result:</p>
<pre><code>Orig t_max [[4, 3, 1]]
Orig v_max [[0.4985414229286749, 0.6989567830263389, 0.9940657122457474]]
Test t_max [[4]]
Test v_max [[0.4985414229286749]]
</code></pre>
<p>How do I get both of these values without the weird loops I'm doing? I know I could make them more compact by using a list-comprehension, but I'd rather get rid of them altogether. Is there a way to deal with both DataFrame and Series without the awkward if-statement I use in <code>col_peaks</code> and <code>peak_vals</code>?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-28T22:09:44.330",
"Id": "394524",
"Score": "0",
"body": "You could avoid using `Series` by e.g. `.iloc[[0]]` instead of `.iloc[0]`, then just remove the two `else` branches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creation... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T21:13:16.193",
"Id": "204371",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Finding peaks in a DataFrame"
} | 204371 |
<p>I recently got a homework assignment from my C++ teacher. The verbatim assignment was this:</p>
<blockquote>
<p>Write a program that simulates a vending machine. A customer selects and item for purchase and inserts a bill into the vending machine. The vending machine dispenses the purchased item and gives change. Assume that all item prices are multiples of 25 cents, and the machine gives all change in dollar coins and quarters. Your task is to compute how many coins of each type to return.</p>
</blockquote>
<p>I'm new to C++ specifically, but I have a bit of experience with some other, higher-level languages, as well as some general experience with software development.</p>
<p>I took about an hour to write this code, using Google to look up certain problems I needed to overcome:</p>
<pre><code>// Vending Machine Thingy (totally creative name)
// Author: [censored]
//
// This program includes all the edge cases, including handlers
// for faulty input.
//
// Enjoy. Try to break it, if you can :)
//
// Valid breakages include infinite loops or exceptions. Early
// exits are not breakages.
#include <iostream> // std::cin, std::cout
#include <math.h> // fmod
#include <array> // std::array
#include <algorithm> // std::max_element
#include <iterator> // std::begin, std::end
#include <limits> // std::numeric_limits
#include <ios> // std::streamsize
// Clears std::cin to prevent an infinite loop.
//
// This needs to happen once per input, but NOT
// more than once
void clearcin() {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
int main() {
// The price of the item we're buying
float price;
// The bills we have available
std::array<int, 4> bills = {1, 5, 20, 100};
// The biggest bill we have available
int max_bill = *std::max_element(std::begin(bills), std::end(bills));
// The bill we're inserting into the machine
// Must exist in `bills`
int bill;
while (true) {
// Prompt the user for the price
std::cout << "What is the price of the item you'll be buying?" << std::endl << ">";
std::cin >> price;
// If a non-number was entered
if (std::cin.fail()) {
std::cout << "The price must be a number." << std::endl;
clearcin();
continue;
}
if (fmod(price, 0.25f) != 0.0f) {
std::cout << "The price must be a multiple of 0.25 (one quarter)." << std::endl;
clearcin();
continue;
}
if (price > max_bill) {
std::cout << "The price must be under $" << max_bill << "." << std::endl;
clearcin();
continue;
}
if (price < 0) {
std::cout << "Sure, let's insert a $20 bill and get $" << 20 - price << " back." << std::endl;
clearcin();
continue;
}
if (price == 0) {
std::cout << "<3" << std::endl;
clearcin();
return 0;
}
clearcin();
break;
}
while (true) {
std::cout << "How much money will you insert into the machine?" << std::endl;
// To get the length of the array, I'm dividing the size
// of the whole array by the size of one item.
//
// This is guaranteed to return the length of the array,
// since all items are guaranteed to be the same length
// when using `int` as the type.
//
// They're all pointers anyway, and pointers are always
// the same length, so it doesn't matter what the value
// is, to be honest...
int lengthOfBills = sizeof(bills) / sizeof(bills[0]);
// There are multiple things going on here:
//
// Initializer: I assign 0 to `int i`, as we're on the first
// element on the first iteration.
//
// Condition: I basically make sure `i` is below the length
// of the array (not equal), since we count from 0.
//
// Multiplication is easier when counting from 0 :)
//
// After each iteration, I increment `i` by one. Nothing too
// interesting.
for (unsigned int i = 0; i < lengthOfBills; i = i + 1) {
int billValue = bills[i];
std::cout << i + 1 << ") " << billValue << std::endl;
}
std::cout << ">";
std::cin >> bill;
if (std::cin.fail()) {
std::cout << "Your selection must be an integer. Use the indexes on the left." << std::endl;
clearcin();
continue;
}
// The input is 1-based, we want it to be 0-based
bill -= 1;
if (bill < 0 || bill > lengthOfBills) {
std::cout << "Your selection must be a valid index. Use the indexes on the left." << std::endl;
clearcin();
continue;
}
// They're both ints, so why not?
//
// Saves one variable :)
bill = bills[bill];
if (bill < price) {
std::cout << "Try using a bigger bill! This one can't pay for the item." << std::endl;
clearcin();
continue;
}
clearcin();
break;
}
// Naturally, the remainder would be
// `(your balance) - (the price)`
float left = bill - price;
// We can just chop off the extra quarters here using `floor`
int dollars = floor(left);
// Take the remainder of `left / 4`, multiply it by 4, and
// convert to an int using `floor`
int quarters = floor(fmod(left, 1) * 4);
std::cout
<< "You have $" << left << " left." << std::endl
<< "The machine dispenses $" << dollars << " and " << quarters << " quarter" << (quarters == 1 ? "" : "s") << "." << std::endl;
if (dollars > 20) {
std::cout << "Wow, that's a lot of change. I hope there's a Coinstar nearby." << std::endl;
}
// `return 0` is implicit
}
</code></pre>
<p>I even included a challenge at the top for my teacher to break it. Excuse all the comments, please. He told me last time that I didn't include enough comments, so I decided to play it safe here.</p>
<p>I'm interested in learning how this code can be improved. Namely, I'm a bit skeptical about all the calls to <code>clearcin()</code>, because they're scattered all over the program. Any feedback is appreciated, I'd love to know what you think of it!</p>
<p>P.S. <code>0</code> is an easter egg. All behavior there is intentional. :P</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T23:39:55.827",
"Id": "394076",
"Score": "0",
"body": "Your code doesn't really solve the challenge. It is specifically stated the customer selects an item, then inserts the payment."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<h1>Be careful using floating-point arithmetic for money</h1>\n\n<p>The challenge has been favourable to you, because all your prices are a multiple of 0.25, which can be represented exactly in binary. If the environment changes, so that prices are in units of 0.05, for instance, code such as the <c... | {
"AcceptedAnswerId": "204389",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-25T23:10:27.730",
"Id": "204373",
"Score": "1",
"Tags": [
"c++",
"homework",
"simulation"
],
"Title": "Yet another vending machine"
} | 204373 |
<p>I trying to see if I implemented these operations correctly and if they could be optimized in any way. The implementations are just the typical implementations found online but I adjusted them to work with pointers. I did not find pseudocode for transplant, it was only described and I am unsure if it does what it is supposed to do. The tree works correctly for my small test cases, but I have not tried it with bigger data sets and operations. I purposely made the tree non-owning but if it were owning, left and right children could be <code>unique_ptr</code>'s and parent be a <code>Node*</code>. I may implement that later.</p>
<pre><code>class Node {
public:
Node(int key) : key(key) {}
Node* parent = nullptr;
Node* left = nullptr;
Node* right = nullptr;
int key;
};
class BinarySearchTree {
public:
BinarySearchTree() = default;
/// create tree from existing nodes
BinarySearchTree(Node* nodes[], unsigned n);
/// insert key into tree
void insert(Node* node);
/// remove node with key
void remove(Node* node);
/// find smallest node in subtree
Node* minimum(Node* node) const;
/// find largest node in subtree
Node* maximum(Node* node) const;
/// find successor of node
Node* successor(Node* node) const;
/// find predecessor of node
Node* predecessor(Node* node) const;
/// replace subtree at a with subtree at b
void transplant(Node* a, Node* b);
/// find node with key
Node* find(int key) const;
/// find kth smallest element
Node* kth(unsigned k) const;
/// write data to stream
friend std::ostream& operator<<(std::ostream& out, const BinarySearchTree& tree);
private:
/// helper method to initialize tree
void build_bst(BinarySearchTree& tree, Node* nodes[], unsigned n);
/// helper method for find
Node* find(int key, Node* subtree) const;
/// pointer to the root
Node* root = nullptr;
};
void BinarySearchTree::build_bst(BinarySearchTree& tree, Node* nodes[], unsigned n) {
if (n == 0) return;
tree.insert(nodes[n/2]);
build_bst(tree, nodes, n/2);
build_bst(tree, nodes + n/2 + 1, n - 1 - n/2);
}
BinarySearchTree::BinarySearchTree(Node* nodes[], unsigned n) {
build_bst(*this, nodes, n);
}
void BinarySearchTree::insert(Node* node) {
Node* parent = nullptr;
Node* child = root;
while (child) {
parent = child;
if (node->key < child->key)
child = child->left;
else
child = child->right;
}
node->parent = parent;
if (!parent) {
root = node;
} else if (node->key < parent->key) {
parent->left = node;
} else {
parent->right = node;
}
}
void BinarySearchTree::remove(Node* node) {
if (!node->left && !node->right) {
// special case where only node is root
if (node->parent) {
// remove leaf node
if (node->parent->key < node->key) {
node->parent->right = nullptr;
} else {
node->parent->left = nullptr;
}
} else {
root = nullptr;
}
node->parent = nullptr;
} else if (!node->left && node->right) {
// no left child
transplant(node, node->right);
} else if (node->left && !node->right) {
// no right child
transplant(node, node->left);
} else {
// check if min = successor(node)
Node* min = successor(node);
if (min->parent != node) {
transplant(min, min->right);
min->right = node->right;
min->right->parent = min;
}
transplant(node, min);
min->left = node->left;
min->left->parent = min;
}
}
Node* BinarySearchTree::minimum(Node* node) const {
Node* parent = nullptr;
Node* child = node;
while (child) {
parent = child;
child = child->left;
}
return parent;
}
Node* BinarySearchTree::maximum(Node* node) const {
Node* parent = nullptr;
Node* child = node;
while (child) {
parent = child;
child = child->right;
}
return parent;
}
Node* BinarySearchTree::successor(Node* node) const {
if (node->right) {
// find minimum of right subtree
return minimum(node->right);
} else {
// find parent of furthest node through right branches
Node* iter = node;
while (iter->parent) {
if (iter->parent->key < iter->key) {
iter = iter->parent;
} else {
break;
}
}
// will return nullptr if no successor
return iter->parent;
}
}
Node* BinarySearchTree::predecessor(Node* node) const {
if (node->left) {
return maximum(node->left);
} else {
// find parent of furthest node through left branches
Node* iter = node;
while (iter->parent) {
if (iter->key < iter->parent->key) {
iter = iter->parent;
} else {
break;
}
}
// will return nullptr if no predecessor exists
return iter->parent;
}
}
void BinarySearchTree::transplant(Node* a, Node* b) {
if (b->parent->key < b->key) {
b->parent->right = nullptr;
} else {
b->parent->left = nullptr;
}
b->parent = a->parent;
// special case when a is root
if (a->parent) {
if (a->parent->key < a->key) {
a->parent->right = b;
} else {
a->parent->left = b;
}
} else {
root = b;
}
}
Node* BinarySearchTree::find(int key) const {
return find(key, root);
}
Node* BinarySearchTree::find(int key, Node* subtree) const {
if (!subtree) return nullptr;
if (subtree->key < key)
return find(key, subtree->right);
else if (subtree->key > key)
return find(key, subtree->left);
else
return subtree;
}
Node* BinarySearchTree::kth(unsigned k) const {
Node* kth = minimum(root);
for (unsigned i = 0; i < k-1; ++i) {
if (kth)
kth = successor(kth);
else
return kth;
}
// returns nullptr if kth element does not exist
return kth;
}
/// in-order traversal/print
std::ostream& operator<<(std::ostream& out, const Node& node) {
if (node.left)
out << *node.left;
out << node.key << ' ';
if (node.right)
out << *node.right;
return out;
}
/// print the entire tree
std::ostream& operator<<(std::ostream& out, const BinarySearchTree& tree) {
if (!tree.root) return out;
return out << *tree.root;
}
</code></pre>
| [] | [
{
"body": "<h1>Good stuff</h1>\n\n<ul>\n<li>Consistent indentation</li>\n<li><code>/// documenting comments</code> (I applaud to <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">that</a>)</li>\n<li>What it does first, how it does it last <br><em>(although I personally prefer inline bodies, this is... | {
"AcceptedAnswerId": "204541",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T02:25:32.230",
"Id": "204378",
"Score": "2",
"Tags": [
"c++",
"tree",
"binary-search"
],
"Title": "Binary search tree with common operations"
} | 204378 |
<p>I'm a newbie in Python.</p>
<p>I need to read a GZ file contains thousands of users.
But I think my code is not optimized in this case. Could anyone can help me? What should I do to improve performance? Or is it standard?</p>
<pre><code>if os.path.isfile("file.gz"):
with gzip.GzipFile("file.gz", 'r') as fin:
for line in fin:
if get_new_user is True:
if datetime.strptime(json.loads(line).get('UpdatedAt'), '%Y-%m-%dT%H:%M:%S.%fZ').date() == (datetime.today()-timedelta(1)).date():
users.append(json.loads(line))
else:
users.append(json.loads(line))
os.remove("file.gz")
return users
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T04:41:39.177",
"Id": "394088",
"Score": "0",
"body": "Could you include an excerpt of the un-gzipped data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T05:36:42.173",
"Id": "394089",
"Score... | [
{
"body": "<p>It looks like your code is somewhat non-optimal.</p>\n\n<ol>\n<li>In the case <code>get_new_user is True</code>, you call <code>json.loads(line)</code> once for the \"UpdatedAt\" test, and if that passes, you call it <em>again</em>, returning effectively the same value, to append the users list.</... | {
"AcceptedAnswerId": "204383",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T04:25:05.077",
"Id": "204381",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"json",
"compression"
],
"Title": "Reading a gzipped file with JSON data for thousands of users"
} | 204381 |
<p>I have been learning Probability from <a href="https://www.youtube.com/playlist?list=PL2SOU6wwxB0uwwH80KTQ6ht66KWxbzTIo" rel="nofollow noreferrer">Statistics 110</a> and trying to simulate problems that have an unintuitive answer</p>
<pre><code>from numpy import cumsum
from statistics import mean
from numpy.random import exponential
from random import randint, sample, uniform
from bisect import bisect_left
def mean_of_experiments(experiment_func, N=100000):
'''Decorator to repeat any Bernoulli trial N times and return probability of success'''
def wrapper(*args, **kwargs):
return round(mean(experiment_func(*args, **kwargs) for _ in range(N)), 3)
return wrapper
@mean_of_experiments
def common_birthday(k):
'''Simulates an experiment to generate k independent uniformly random birthdays and check if there are any repeat birthdays'''
rands = [randint(1, 365) for _ in range(k)]
return len(rands) != len(set(rands))
@mean_of_experiments
def matching(k=52):
'''Simulates an experiment to permute 'k' cards and check if any jth card's value is j'''
idx_labels = enumerate(sample(range(k), k))
return any(idx == label for idx, label in idx_labels)
@mean_of_experiments
def dice(n, c):
'''Simulates an experiment to roll 'n' dice and and check if count of 6's is at least c'''
return [randint(1, 6) for _ in range(n)].count(6) >= c
def boardings(scale=5.0, N=1_00_000):
'''Simulates an experiment where arrival of buses at stop follows a Poisson process and finds avg. inter-arrival time at a random instant'''
arrivals = cumsum([exponential(scale=scale) for _ in range(N)])
@mean_of_experiments
def wait():
boarding_idx = bisect_left(arrivals, uniform(0, arrivals[-1]))
missed_bus = 0 if boarding_idx == 0 else arrivals[boarding_idx - 1]
return arrivals[boarding_idx] - missed_bus
return wait()
</code></pre>
<p>Probability Problems:</p>
<ol>
<li><code>common_birthday</code>: Given <em>k</em> people, what's the probability that any 2 people share a birthday? For 23 people, it's >50% and for 50 people, >97%.</li>
<li><code>matching</code>: Given 52 cards with a unique label in 0...n-1, they are shuffled. What's the probability that <em>any</em> <em>j</em>^th card's label is <em>j</em>? Answer's very close to 1-1/e</li>
<li><code>dice</code>: Problem posed by a gambler to Newton; <code>dice(6, 1)</code> > <code>dice(12, 2)</code> > <code>dice(18, 3)</code></li>
<li><code>boardings</code>: Given that a bus company's buses follow a Poisson process, if a person visits a stop at some random time, what was that inter-arrival time? From <a href="https://www.youtube.com/watch?v=XsYXACeIklU&index=16&list=PLUl4u3cNGP61MdtwGTqZA0MreSaDybji8&t=0s" rel="nofollow noreferrer">Tsitsiklis' lectures</a>; answer is 2*<code>scale</code> for any value of <code>scale</code>.</li>
</ol>
<p>What I wish I could do in my code is dynamically set the value of <code>N</code> in the decorator <code>mean_of_experiments</code>. Is that possible?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T07:25:40.043",
"Id": "394097",
"Score": "3",
"body": "Welcome to Code Review! Thank you for writing a question that's both clear and complete. Could you please add what version of Python you wrote this for?"
},
{
"ContentLic... | [
{
"body": "<h1><code>functools.wraps</code></h1>\n<p>Unrelated to your main question, I advice you to use <a href=\"https://docs.python.org/3.6/library/functools.html#functools.wraps\" rel=\"noreferrer\"><code>functools.wraps</code></a>. This way, your methods metadata get transferred to the wrapped method.\nFo... | {
"AcceptedAnswerId": "204388",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T06:59:14.160",
"Id": "204384",
"Score": "16",
"Tags": [
"python",
"python-3.x",
"statistics",
"simulation"
],
"Title": "Newton-Pepys, common birthdays and other probability simulations in Python 3"
} | 204384 |
<p>I'm creating an XML from a defined schema I need to follow.</p>
<p>This is my code:</p>
<pre><code>using (XmlWriter writer = XmlWriter.Create(desktopPath + "\fatt.xml", settings))
{
writer.WriteStartDocument();
#region FatturaElettronicaHeader 1
writer.WriteStartElement("FatturaElettronicaHeader");
#region DatiTrasmissione 1.1
writer.WriteStartElement("DatiTrasmissione");
var statoAnag = statiRep.GetId(anagraficoCliente.stato);
writer.WriteStartElement("IdTrasmittente");
writer.WriteElementString("IdPaese",statoAnag.codice_iso);
writer.WriteElementString("IdCodice",anagraficoCliente.codice_fiscale);
writer.WriteEndElement();
writer.WriteElementString("ProgressivoInvio", "0");
writer.WriteElementString("FormatoTrasmissione",FORMATO_TRASMISSIONE);
writer.WriteElementString("CodiceDestinatario",codiceSdi);
writer.WriteElementString("PECDestinatario","prova@pec.it");
writer.WriteEndElement();
#endregion DatiTrasmissione 1.1
#region 2
....
#endregion 2
writer.WriteEndDocument();
}
</code></pre>
<p>Basically I just have to read data from my db and then put in a xml file.</p>
<p>It works fine but I think is not really readable even if I used a lot of region to tidy up code.</p>
<p>What can I do to improve my code ? If there's any</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T10:40:13.570",
"Id": "394115",
"Score": "4",
"body": "I think you shouldn't have removed any code but you definitely should have included the schema of the xml and the models you are converting to it."
},
{
"ContentLicense":... | [
{
"body": "<p>When I had to create an XML file for one of my projects, I basically created a class for each element and passed along a class that contained all the data I needed to use in the XML.</p>\n\n<p>It started with this class:</p>\n\n<pre><code>internal sealed class XmlCreator\n{\n public static XEle... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T07:35:55.043",
"Id": "204386",
"Score": "0",
"Tags": [
"c#",
"xml"
],
"Title": "Writing XML in C# from defined schema"
} | 204386 |
<p>Just a general code review. I'm looking for my first developer job so anything constructive is awesome. Please, and thank you very much.</p>
<p>I've written this implementation as an exercise and to add to my code base. I've tried to keep most nuts and bolts hidden away in the Node class.</p>
<pre><code>"""AVLTree/Balanced Binary Search Tree Data structure.
Thanks for checking out my implementation of a BBST. Feel free to use it and/or change it to better suit your needs.
Any feedback is greatly appreciated.
Tree designed for data types supporting <, =, >.
The following methods are implemented:
Create a new tree:
tree = AVLTree()
View tree structure (may need some adjustment for screen size):
print(tree)
Determine height of tree:
tree.height(print_result=True)
Returns int
print_result is optional, defaults to False
Insert data into tree:
tree.insert(data)
If data already exists in tree, user is alerted
Search for data in tree:
tree.search(data, print_results=True)
returns Boolean
print_results is optional, defaults to False
Delete data from tree:
tree.delete(data)
If data does not exist in tree, user is alerted
Clear all data from tree:
tree.clear_tree()
"""
class Node(object):
"""Node object for AVLTree.
Node class is wrapped by AVLTree class. All user methods are exposed there.
Methods for printing, searching, inserting, deleting and determining height of AVLTree provided.
"""
def __init__(self, data):
"""Instantiates Node object for AVLTree.
Data assumed to be compatible with <, =, > operators.
Parent, left and right are pointers to parent and child nodes.
Tallness initialized at 1, adjusted with insert and delete to represent height of node. Null nodes have
height of 0.
:param data: Values compatible with <, =, > operators.
"""
self.data = data
self.parent = None
self.left = None
self.right = None
self.tallness = 1
def print_tree(self, cur_node, order=None):
"""Prints tree in specified order to stdout.
:param cur_node: Root node from Tree.get_root.
:param order: Keyword arg for order of tree traversal.
"""
if order == 'pre-order':
print(*self._pre_order(cur_node, []))
elif order == 'in-order':
print(*self._in_order(cur_node, []))
elif order == 'post-order':
print(*self._post_order(cur_node, []))
def _pre_order(self, cur_node, output):
"""Prints tree: Root -> Left node -> Right node.
:param cur_node: Root of tree.
:param output: Empty list.
:return: List of node values.
"""
if cur_node:
output += [cur_node.data]
self._pre_order(cur_node.left, output)
self._pre_order(cur_node.right, output)
return output
def _in_order(self, cur_node, output):
"""Prints tree: Left node -> Root -> Right node.
:param cur_node: Node.Root of tree.
:param output: Empty list.
:return: List of node values.
"""
if cur_node:
self._in_order(cur_node.left, output)
output += [cur_node.data]
self._in_order(cur_node.right, output)
return output
def _post_order(self, cur_node, output):
"""Prints tree: Left node -> Right node -> Root.
:param cur_node: Root of tree.
:param output: Empty list.
:return: List of node values.
"""
if cur_node:
self._post_order(cur_node.left, output)
self._post_order(cur_node.right, output)
output += [cur_node.data]
return output
def height(self, cur_node, cur_height):
"""Calculates and returns total height of tree.
:param cur_node: Root of tree.
:param cur_height: 0.
:return: Height of tree.
"""
if not cur_node:
return cur_height
left_height = self.height(cur_node.left, cur_height + 1)
right_height = self.height(cur_node.right, cur_height + 1)
return max(left_height, right_height)
def search(self, cur_node, data):
"""Searches tree for data, returns bool.
:param cur_node: Root of tree.
:param data: Data to be found in tree.
:return: bool. True if data in tree, else, False.
"""
if data == cur_node.data:
return True
elif data < cur_node.data and cur_node.left:
return self.search(cur_node.left, data)
elif data > cur_node.data and cur_node.right:
return self.search(cur_node.right, data)
return False
def insert(self, cur_node, data):
"""Inserts data into tree. Alerts user if data already exists in tree.
Calls _inspect_insertion to determine if insertion caused tree imbalance.
:param cur_node: Root of tree.
:param data: Data to be inserted.
"""
if data < cur_node.data:
if not cur_node.left:
cur_node.left = Node(data)
cur_node.left.parent = cur_node
self._inspect_insertion(cur_node.left, [])
else:
self.insert(cur_node.left, data)
elif data > cur_node.data:
if not cur_node.right:
cur_node.right = Node(data)
cur_node.right.parent = cur_node
self._inspect_insertion(cur_node.right, [])
else:
self.insert(cur_node.right, data)
elif data == cur_node.data and cur_node.parent is not None:
print(f'{data} already in tree. Cannot insert.')
def _inspect_insertion(self, cur_node, nodes):
""" Determines if insertion creates need to balance sub-tree.
Rebalance needed if difference in height of child nodes is > 1.
Creates list of nodes to be rotated if above condition is true.
Calls _rebalance_node with nodes to be balanced.
:param cur_node: The newly inserted node.
:param nodes: Empty list.
:return:
"""
if not cur_node.parent:
return
nodes = [cur_node] + nodes
left = self._get_height(cur_node.parent.left)
right = self._get_height(cur_node.parent.right)
if abs(left - right) > 1 and len(nodes) > 2:
nodes = [cur_node.parent] + nodes
self._rebalance_node(*nodes[:3])
return
new = 1 + cur_node.tallness
if new > cur_node.parent.tallness:
cur_node.parent.tallness = new
self._inspect_insertion(cur_node.parent, nodes)
def _get_height(self, cur_node):
""" Gets height of cur_node. Returns 0 if node is None else returns node.tallness.
:param cur_node: Node
:return: Node.tallness
"""
if not cur_node:
return 0
return cur_node.tallness
def _rebalance_node(self, z, y, x):
"""Determines orientation of imbalanced nodes and calls indicated balancing methods.
Calls _rotate_right or _rotate_left as determined by orientation of unbalanced nodes.
:param z: Highest node. Rebalance occurs 'around' this node.
:param y: Child of z
:param x: Child of y
"""
if y == z.left and x == y.left:
""" z
/
y
/
x """
self._right_rotate(z)
elif y == z.left and x == y.right:
""" z
/
y
\
x """
self._left_rotate(y)
self._right_rotate(z)
elif y == z.right and x == y.right:
""" z
\
y
\
x """
self._left_rotate(z)
elif y == z.right and x == y.left:
""" z
\
y
/
x """
self._right_rotate(y)
self._left_rotate(z)
else:
raise Exception('Tree corrupted')
def _right_rotate(self, z):
"""Rotates around z to rebalance sub-tree.
:param z: Root of sub-tree to be balanced.
"""
temp = z.parent
y = z.left
x = y.right
y.right = z
z.parent = y
z.left = x
if x:
x.parent = z
y.parent = temp
if y.parent:
if y.parent.left == z:
y.parent.left = y
else:
y.parent.right = y
z.tallness = 1 + max(self._get_height(z.left), self._get_height(z.right))
y.tallness = 1 + max(self._get_height(y.left), self._get_height(y.right))
def _left_rotate(self, z):
"""Rotates around z to rebalance sub-tree.
:param z: Root of sub-tree to be balanced.
"""
temp = z.parent
y = z.right
x = y.left
y.left = z
z.parent = y
z.right = x
if x:
x.parent = z
y.parent = temp
if y.parent:
if y.parent.left == z:
y.parent.left = y
else:
y.parent.right = y
z.tallness = 1 + max(self._get_height(z.left), self._get_height(z.right))
y.tallness = 1 + max(self._get_height(y.left), self._get_height(y.right))
def delete(self, node):
""" Deletes node found in _find_node.
Removes nodes and handles deleted node's orphaned children, if any.
Deleted nodes with two children are handled by finding the smallest relative of the deleted node's right child,
replacing the to-be-deleted node's data with that of its smaller relative, then marking the smaller relative
to be deleted instead. This preserves the BST imperative.
Calls _inspect_deletion to ensure proper balancing of sub-tree after deletion.
:param node: Node to be deleted.
:return:
"""
def smallest_node(curr_node):
""" Finds smallest relative of curr_node.
:param curr_node: A node.
:return: Relative of curr_node with smallest value.
"""
while curr_node.left:
curr_node = curr_node.left
return curr_node
def children(curr_node):
""" Finds number of curr_node's children.
:param curr_node: A node
:return: Number of curr_node's children.
"""
num = 0
if curr_node.left:
num += 1
if curr_node.right:
num += 1
return num
node_parent = node.parent
node_children = children(node)
# Leaf nodes may simply be deleted.
if node_children == 0:
if node_parent:
if node_parent.left == node:
node_parent.left = None
else:
node_parent.right = None
else:
return None
# Parent of deleted node made parent of deleted node's child.
if node_children == 1:
if node.left:
child = node.left
else:
child = node.right
if node_parent:
if node_parent.left == node:
node_parent.left = child
else:
node_parent.right = child
else:
child.parent = node_parent
return child # returned to promote child to root node
child.parent = node_parent
# If the node to be deleted has 2 children, the data of its smallest relative is promoted to the to-be-deleted
# node. The smallest relative is then deleted instead.
if node_children == 2:
progeny = smallest_node(node.right)
node.data = progeny.data
self.delete(progeny)
return
# Adjust height and inspect the tree for balance.
if node_parent:
node_parent.tallness = 1 + max(self._get_height(node_parent.left), self._get_height(node_parent.right))
self._inspect_deletion(node_parent)
def _inspect_deletion(self, cur_node):
"""Ensures tree is balanced after deletion.
Calls _rebalance_node if imbalance is detected.
Calls _inspect_insertion to ensure balance up the tree.
:param cur_node: Node. Parent of deleted node.
:return:
"""
if not cur_node:
return
left = self._get_height(cur_node.left)
right = self._get_height(cur_node.right)
if abs(left - right) > 1:
y = self.taller_child(cur_node)
x = self.taller_child(y)
self._rebalance_node(cur_node, y, x)
if cur_node.parent:
self._inspect_insertion(cur_node, [])
def taller_child(self, cur_node):
"""Finds taller of node's children.
:param cur_node: Node. Node to be inspected.
:return: Node. Child of curr_node with greater height.
"""
left = self._get_height(cur_node.left)
right = self._get_height(cur_node.right)
if left >= right:
return cur_node.left
return cur_node.right
class AVLTree(object):
"""Wraps Node class. Methods call corresponding methods of Node class.
User accessible methods for insert, delete, search, height, print_tree, and clear_tree.
"""
def __init__(self):
"""Tree is represented by its root node, initially None."""
self.root = None
def __repr__(self):
"""Prints text based structure of tree.
:return: str. Tree structure.
"""
if not self.root:
return 'Tree is empty. Please insert data.'
the_tree = '\n'
nodes = [self._get_root()]
cur_tallness = self.root.tallness
space = ' ' * (40 - int(len(str(self.root.data))) // 2)
buffer = ' ' * (60 - int(len(str(self.root.data))) // 2)
while True:
if all(n is None for n in nodes):
break
cur_tallness -= 1
this_row = ' '
next_row = ' '
next_nodes = []
for cur_node in nodes:
if not cur_node:
this_row += ' ' + space
next_nodes.extend([None, None])
if cur_node and cur_node.data is not Node:
this_row += f'{buffer}{str(cur_node.data)}{buffer}'
if cur_node and cur_node.left:
next_nodes.append(cur_node.left)
next_row += space + '/' + space
else:
next_nodes.append(None)
next_row += ' ' + space
if cur_node and cur_node.right:
next_nodes.append(cur_node.right)
next_row += '\\' + space
else:
next_nodes.append(None)
next_row += ' ' + space
the_tree += (cur_tallness * ' ' + this_row + '\n' + cur_tallness * ' ' + next_row + '\n')
space = ' ' * int(len(space) // 2)
buffer = ' ' * int(len(buffer) // 2)
nodes = next_nodes
return the_tree
def _get_root(self, data=None):
"""Returns root node.
Creates root node if called from Tree.insert and tree is empty.
:param data: If provided and tree is empty, tree root is established with data.
:return: Root node of tree.
"""
if not self.root:
if data is not None:
self.root = Node(data)
else:
print('Tree is empty.')
return
else:
while self.root.parent:
self.root = self.root.parent
return self.root
def print_tree(self, order=None):
"""User interface for printing tree.
Calls _print_tree with root from _get_root.
Prints order as entered by user for correcting typos and such.
Ensures print order requested is valid.
:param order: 'in-order', 'pre-order', or 'post-order'
:return: _print_tree
"""
print(order)
if not order or not any([order == 'pre-order', order == 'post-order', order == 'in-order']):
print('Please specify a valid print order.')
print('(eg. order=\'in-order\', \'pre-order\', or \'post-order\')')
return
return self._print_tree(self._get_root(), order)
def _print_tree(self, root, order=None):
"""Calls print_tree method of Node class.
:param root: Root node
:param order: 'in-order', 'pre-order', or 'post-order'
:return: Node.print_tree
"""
return root.print_tree(root, order)
def height(self, print_result=False):
"""User interface for finding height of tree.
Calls _height with root from _get_root.
Option to print height to stdout.
:param print_result: Prints height to stdout if True.
:return: _height
"""
height = self._height(self._get_root())
if print_result:
print(height)
return height
def _height(self, root):
"""Calls height method of Node class.
:param root: Root node.
:return: Node.height
"""
return root.height(root, 0)
def search(self, data, print_result=False):
"""User interface for search method.
Calls _search with root from _get_root.
Option to print results to stdout.
:param print_result: Set to True to print search results.
:param data: Data to be found in tree.
:return: _search
"""
result = self._search(self._get_root(), data)
if print_result:
if result:
print(f'{data} found.')
else:
print(f'{data} not found.')
return result
def _search(self, root, data):
"""Calls search method of Node class.
:param root: Root node.
:param data: Data to search for in tree.
:return: Node.search
"""
return root.search(root, data)
def insert(self, data):
"""User interface for inserting data into tree.
Calls _insert with root provided by _get_root.
Data field provided to _get_root ensures tree root is created on first insertion.
:param data: Data to be inserted into tree.
:return: _insert
"""
return self._insert(self._get_root(data=data), data)
def _insert(self, root, data):
"""Calls insert method of Node class.
:param root: Root node.
:param data: Data to be inserted into tree.
:return: Node.insert
"""
return root.insert(root, data)
def _find_node(self, cur_node, data):
"""Finds and returns node with given data, else, returns None.
:param cur_node: Root node from _get_root.
:param data: Data contained within node to be found.
:return: Node containing data if such a node exists. Else, None.
"""
if cur_node and data == cur_node.data:
return cur_node
elif cur_node and data < cur_node.data:
return self._find_node(cur_node.left, data)
elif cur_node and data > cur_node.data:
return self._find_node(cur_node.right, data)
return None
def delete(self, data):
"""Passes root and data to be deleted to _delete.
Calls _delete with root from _get_root.
:param data: Data to delete from tree.
:return: _delete if data in tree, else, None.
"""
node = self._find_node(self._get_root(), data)
if not node:
print(f'{data} not in tree, Cannot delete.')
return
return self._delete(node)
def _delete(self, node):
"""Calls delete method of Node class.
If root is to be deleted and has no children, root is set to None.
If Node.delete returns a node it is the new root node.
:param node: Node to be deleted
"""
if node == self.root and (not node.left and not node.right):
self.root = None
return self.root
result = node.delete(node)
if result:
self.root = result
return self.root
def clear_tree(self):
"""Clears tree of all data.
:return: Tree root
"""
self.root = None
return self.root
</code></pre>
<p>Thank you for taking a look!</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T09:24:54.157",
"Id": "204390",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"tree",
"binary-search"
],
"Title": "AVL Tree with delete method in Python 3"
} | 204390 |
<p>vir.php</p>
<pre><code><?php
require_once '../db.php';
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = trim($_POST['username']);
try{
$Query = "SELECT * FROM users WHERE username = :username";
$statement = $conn->prepare($Query);
$statement->bindValue(':username', $username);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
$RowCount = $statement->rowCount();
} catch (PDOerrorInfo $e){
die('QuerySCD Error '.$e->getMessage());
}
if( $RowCount == 0 ){
// User doesn't exist
$_SESSION['message'] = "error!";
header("location: error-login.php");
} else{ // User exists
if( password_verify($_POST['password'], $user['password'])){
$_SESSION['username'] = $user['username'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "error!";
header("location: error-login.php");
}
}
}
$conn = NULL;
?>
<!DOCTYPE html>
<html lang="pt_BR">
<head>
<title>Login</title>
<meta charset="UTF-8">
</head>
<body>
<form action="vir.php" method="post" autocomplete="off">
<input type="username" required autocomplete="off" name="username">
<span data-placeholder="User"></span>
<input type="password" required autocomplete="off" name="password">
<span data-placeholder="Password"></span>
<button name="login">
Logar
</button>
</form>
</body>
</html>
</code></pre>
<p>ir.php</p>
<pre><code><?php
/* Log out process, unsets and destroys session variables */
session_start();
session_unset();
session_destroy();
?>
<!DOCTYPE html>
<html lang="pt_BR">
<head>
<title>Login</title>
<meta charset="UTF-8">
</head>
<body>
<p><?= 'You have been logged out!'; ?></p>
</body>
</html>
</code></pre>
<p>error-login.php</p>
<pre><code><?php
/* Displays all error messages */
session_start();
?>
<!DOCTYPE html>
<html lang="pt_BR">
<head>
<title>Login</title>
<meta charset="UTF-8">
</head>
<body>
<h4>
<?php
if( isset($_SESSION['message']) AND !empty($_SESSION['message']) ):
echo $_SESSION['message'];
else:
header( "location: vir.php" );
endif;
?>
</h4>
</body>
</html>
</code></pre>
<p>Only me will use this login sytem and only me will have the link to this login system, i will use this to insert records on my database.</p>
<p>I don't know if someone could find the link to this login, to i used PDO <code>prepared statement</code>, so prevent against SQL Injection.</p>
<p>How safe is my code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T11:13:06.490",
"Id": "394124",
"Score": "0",
"body": "What happens if the pdo statement fails (e.g. because the server went away)? As i see it, this would result in an `undefined variable` error for `$RowCount`."
},
{
"Conte... | [
{
"body": "<blockquote>\n <p>How safe is my code?</p>\n</blockquote>\n\n<p>I would suggest if you protect the login form from</p>\n\n<ul>\n<li>CSRF (<a href=\"https://en.wikipedia.org/wiki/Cross-site_request_forgery\" rel=\"nofollow noreferrer\">Cross site request forgery</a>) Attacks by generating a unique co... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T10:02:14.987",
"Id": "204394",
"Score": "3",
"Tags": [
"php",
"pdo",
"session"
],
"Title": "Login System using PHP and PDO Prepared Statement"
} | 204394 |
<p>I've recently written a simple progress bar class in C++ to mimic usage of similar libraries I've used in Python. The idea is to take some iterable container (e.g. <code>std::vector</code>), and iterate over the container while printing the progress to stdout. This can be useful when doing some computationally expensive operations on the container in the loop body, such as in physics simulations.</p>
<p>The code as it stands is</p>
<pre><code>#include <iostream>
#include <iterator>
#ifndef __PBAR_H
#define __PBAR_H
namespace pbar {
template<class It>
class ProgressBar {
public:
ProgressBar(It&& it, It&& it_end, int width, const char symbol='=')
: pos_(0),
width_(width),
symbol_(symbol),
iter_(it),
iter_begin_(it),
iter_end_(it_end)
{}
using value_type = typename It::value_type;
using reference = typename It::reference;
class iterator
: public std::iterator<typename It::iterator_category,
value_type,
typename It::difference_type,
typename It::pointer,
reference>
{
private:
value_type val_ = *iter_;
ProgressBar<It> *parent_;
public:
iterator(ProgressBar<It> *parent, value_type start)
: val_(start), parent_(parent) {}
iterator& operator++();
iterator operator++(int);
bool operator==(iterator other);
bool operator!=(iterator other);
reference operator*();
};
iterator begin();
iterator end();
template<class I>
friend std::ostream& operator<<(std::ostream &steam, const ProgressBar<I> &pbar);
private:
int pos_;
int width_;
char symbol_;
char left_delim_{'['};
char right_delim_{']'};
char pointer_{'>'};
It iter_;
It iter_begin_;
It iter_end_;
}; // class ProgressBar
template<class It>
using piter = typename ProgressBar<It>::iterator;
template<class It>
inline bool ProgressBar<It>::iterator::operator==(piter<It> other) {
return val_ == other.val_;
}
template<class It>
inline bool ProgressBar<It>::iterator::operator!=(piter<It> other) {
return !(*this == other);
}
template<class It>
inline typename It::reference ProgressBar<It>::iterator::operator*() {
return val_;
}
template<class It>
inline piter<It>& ProgressBar<It>::iterator::operator++() {
++(parent_->iter_);
val_ = *(parent_->iter_);
auto fraction = static_cast<double>(std::distance(parent_->iter_begin_,
parent_->iter_))/std::distance(parent_->iter_begin_, parent_->iter_end_);
parent_->pos_ = parent_->width_*fraction;
std::cout << *parent_;
return *this;
}
template<class It>
inline piter<It> ProgressBar<It>::iterator::operator++(int) {
auto retval = *this;
++(*this);
return retval;
}
template<class It>
inline piter<It> ProgressBar<It>::begin() {
return ProgressBar<It>::iterator(this, *iter_begin_);
}
template<class It>
inline piter<It> ProgressBar<It>::end() {
return ProgressBar<It>::iterator(this, *iter_end_);
}
template<class It>
inline std::ostream& operator<<(std::ostream &stream, const ProgressBar<It> &pbar) {
stream << pbar.left_delim_;
for (int i=0; i<pbar.width_; i++) {
if (i < pbar.pos_)
stream << pbar.symbol_;
else if (i == pbar.pos_)
stream << pbar.pointer_;
else
stream << " ";
}
stream << pbar.right_delim_ << int(double(pbar.pos_)/pbar.width_*100) << "%\r";
stream.flush();
return stream;
}
}; // namespace pbar
#endif // __PBAR_H
</code></pre>
<p>Using the class:</p>
<pre><code>#include <iostream>
#include <vector>
#include "pbar.h"
using namespace pbar;
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
ProgressBar<std::vector<int>::iterator> pbar(v.begin(), v.end(), 50);
for (auto i = pbar.begin(); i != pbar.end(); i++) {
;
}
// The constructor allows changing the bar symbol (default '=')
ProgressBar<std::vector<int>::iterator> pbar2(v.begin(), v.end(), 50, '#');
std::cout << "\nRange based loops also work" << std::endl;
for (auto& i: pbar2) {
;
}
}
</code></pre>
<p>While I've been programming in C++ for a while now, I haven't had the opportunity to get a lot of feedback on my code yet, and it's making me anxious that I'm learning bad patterns. So, I'd like to know:</p>
<ol>
<li>Are there any obvious pitfalls in my code? </li>
<li>Bad design decisions?</li>
<li>General improvements or additions to the code? </li>
<li>Should I separate the library into a header and implementation file, or keep it header-only?</li>
<li>Is there a better way to implement iterators for custom types? I've taken this implementation from <a href="https://en.cppreference.com/w/cpp/iterator/iterator#Example" rel="nofollow noreferrer">here</a>, but I'm wondering if there's a different way than using nested classes.</li>
</ol>
<p>I appreciate any and all advice!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T13:13:51.957",
"Id": "394144",
"Score": "0",
"body": "The sentence continues on the next line with a link to https://en.cppreference.com/w/cpp/iterator/iterator#Example :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creatio... | [
{
"body": "<p>The constructor takes two forwarding references, but doesn't actually forward them:</p>\n\n<pre><code> ProgressBar(It&& it, It&& it_end, int width, const char symbol='=')\n iter_(it),\n iter_begin_(it),\n iter_end_(it_end)\n</code></pre>\n\n<p>It's better to a... | {
"AcceptedAnswerId": "204408",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T10:16:20.583",
"Id": "204396",
"Score": "6",
"Tags": [
"c++",
"c++11",
"iterator"
],
"Title": "Progress bar wrapper class in C++"
} | 204396 |
<p>Is there any way to improve this code? Using ES6 style i am using latest stable version of node.js.</p>
<pre><code>const UserSchema = new mongoose.Schema({
date: string;
dateObj: {
year: number,
month: number,
day: number
};
project: string;
task: string;
hours: number;
});
let data = new Data();
data.date = new Date(body.date);
data.dateObj = {
year: body.dateObj.year,
month: body.dateObj.month,
day: body.dateObj.day
}
data.project = body.project;
data.task = body.task;
data.hours = body.hours;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T14:28:30.913",
"Id": "394157",
"Score": "1",
"body": "We first need to know what your code is accomplishing. Please [edit] your question and describe the assignment ;-)"
}
] | [
{
"body": "<p>For flat objects (i.e. whose values are only primitive types), there's <code>Object.assign()</code>, which shallow-copies all <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties\" rel=\"nofollow noreferrer\" title=\"enumerable\">enumerable</a... | {
"AcceptedAnswerId": "204413",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T12:04:56.597",
"Id": "204400",
"Score": "0",
"Tags": [
"javascript",
"node.js",
"ecmascript-6"
],
"Title": "Best Approach for Assignment Code in Node.js (ES6 style)"
} | 204400 |
<p>Basically What I have is basket ball App. In which I have Added some levels and difficulties. logic is simply use tupple in enum and I have some methods to update / get current level with new values </p>
<p>I have created following code </p>
<pre><code>enum Difficulty:String {
case easy
case medium
case hard
func getRatioForTargetAgaintsAvailable() -> Float {
switch self {
case .easy:
return 0.3
case .medium:
return 0.5
case .hard :
return 0.8
}
}
func getDistanceForTarget () -> Float {
switch self {
case .easy:
return 5
case .medium:
return 6
case .hard :
return 7
}
}
}
</code></pre>
<p>And main enum</p>
<pre><code>enum Level:CustomStringConvertible {
var description: String {
return "Welcome to New \(self.getDifficulty().rawValue) Level , Your Target is \(getTargetValue()), You have \(getAvailableBalls()) Balls left"
}
case level1(avaiableBalls:Int,difficulty:Difficulty,totalScore:Int)
case level2(avaiableBalls:Int,difficulty:Difficulty,totalScore:Int)
case level3(avaiableBalls:Int,difficulty:Difficulty,totalScore:Int)
//--------------------------------------------------------------------------------
//MARK:- Set Methdos
//--------------------------------------------------------------------------------
mutating func updateTotalScore (newValue:Int) {
switch self {
case .level1( let availableBall, let difficulty, _):
self = Level.level1(avaiableBalls: availableBall, difficulty: difficulty, totalScore: newValue)
case .level2( let availableBall, let difficulty, _):
self = Level.level2(avaiableBalls: availableBall, difficulty: difficulty, totalScore: newValue)
case .level3( let availableBall, let difficulty, _):
self = Level.level3(avaiableBalls: availableBall, difficulty: difficulty, totalScore: newValue)
}
}
mutating func updateAvailableBalls (newValue:Int) {
switch self {
case .level1( _, let difficulty, let totalScore):
self = Level.level1(avaiableBalls: newValue, difficulty: difficulty, totalScore: totalScore)
case .level2( _ , let difficulty, let totalScore):
self = Level.level2(avaiableBalls: newValue, difficulty: difficulty, totalScore: totalScore)
case .level3( _ , let difficulty, let totalScore):
self = Level.level3(avaiableBalls: newValue, difficulty: difficulty, totalScore: totalScore)
}
}
mutating func gotoNextLevel() -> Bool {
switch self {
case .level1:
self = Level.level2(avaiableBalls: 20, difficulty: .medium, totalScore: 0)
return true
case .level2:
self = Level.level2(avaiableBalls: 20, difficulty: .hard, totalScore: 0)
return true
case .level3 :
self = Level.level3(avaiableBalls: 20, difficulty: .hard, totalScore: 0)
return false
}
}
mutating func restartLevel () {
switch self {
case .level1:
self = Level.level1(avaiableBalls: 20, difficulty: .easy, totalScore: 0)
case .level2:
self = Level.level2(avaiableBalls: 20, difficulty: .medium, totalScore: 0)
case .level3 :
self = Level.level3(avaiableBalls: 20, difficulty: .hard, totalScore: 0)
}
}
//--------------------------------------------------------------------------------
//MARK:- Get Methdos
//--------------------------------------------------------------------------------
func getTotalScore () -> Int {
switch self {
case .level1(_,_, let totalScore) :
return totalScore
case .level2(_,_, let totalScore) :
return totalScore
case .level3(_,_ ,let totalScore):
return totalScore
}
}
func getAvailableBalls () -> Int {
switch self {
case .level1(let availableBall,_,_) :
return availableBall
case .level2(let availableBall,_,_) :
return availableBall
case .level3(let availableBall,_,_) :
return availableBall
}
}
func getTargetValue () -> Int {
switch self{
case .level1( let _, let difficulty, _):
return Int(difficulty.getRatioForTargetAgaintsAvailable() * Float(20))
case .level2( let _, let difficulty, _):
return Int(difficulty.getRatioForTargetAgaintsAvailable() * Float(20))
case .level3( let _, let difficulty, _):
return Int(difficulty.getRatioForTargetAgaintsAvailable() * Float(20))
}
}
func getMinDistanceFromHook () -> Float {
switch self{
case .level1( _, let difficulty, _):
return difficulty.getDistanceForTarget()
case .level2( _, let difficulty, _):
return difficulty.getDistanceForTarget()
case .level3( _, let difficulty, _):
return difficulty.getDistanceForTarget()
}
}
func getDifficulty () -> Difficulty {
switch self{
case .level1( _, let difficulty, _):
return difficulty
case .level2( _, let difficulty, _):
return difficulty
case .level3( _, let difficulty, _):
return difficulty
}
}
func isLevelPassed () -> Bool {
return getTotalScore() == getTargetValue()
}
}
</code></pre>
<p>Now In my <code>ViewController</code> I create Object </p>
<pre><code>var currentLevel = Level.level1(avaiableBalls: 20, difficulty: .easy, totalScore: 0)
</code></pre>
<p>So my Question is is it good way to implement this functionality any suggested improvement in it?</p>
<p>Thanks for reading this </p>
| [] | [
{
"body": "<h3>Remarks and simplifications for your current code</h3>\n\n<p>Swift does not use the “get” prefix for getter methods, so</p>\n\n<pre><code>func getDistanceForTarget() -> Float\n</code></pre>\n\n<p>is better named</p>\n\n<pre><code>func targetDistance() -> Float\n</code></pre>\n\n<p>Functions... | {
"AcceptedAnswerId": "204479",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T12:47:09.083",
"Id": "204404",
"Score": "2",
"Tags": [
"swift",
"ios",
"enum"
],
"Title": "Manage Game Level with enum"
} | 204404 |
<p>I'm learning C and I am currently implementing a memory pool.</p>
<p>I'm writing it in steps, first I implemented a fixed-sized memory pool then I will try to implement a memory pool with a known size of elements but an unknown number of elements and ultimately try to write a generic one that is just a block of memory that can allocate any size.</p>
<p>The pool is actually a block of memory that is initialized with values that are pointers to the next memory like so:</p>
<pre><code> ______________
|0x8 |0x10|NULL|
|____|____|____|
^ ^ ^
0x0 0x8 0x10
</code></pre>
<p>I want to know if I'm heading in the right direction.
There is the code</p>
<p>allocator.h:</p>
<pre><code>#include <stdlib.h>
typedef struct FixedPoolAllocator FixedPoolAllocator;
FixedPoolAllocator* FixedPoolAllocator_new(size_t nmemb, size_t size);
void* FixedPoolAllocator_alloc(FixedPoolAllocator *allocator);
void FixedPoolAllocator_free(FixedPoolAllocator *allocator, void *ptr);
void FixedPoolAllocator_destroy(FixedPoolAllocator *allocator);
</code></pre>
<p>allocator.c:</p>
<pre><code>#include "allocator.h"
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
typedef struct FixedPoolAllocator {
// The currently free space in which a value can be stored
size_t *currentFree;
size_t numOfMembers;
size_t memberSize;
// The actual memory block, It is of type char* so that pointer arithmetic will be easier
char *mem;
} FixedPoolAllocator;
FixedPoolAllocator* FixedPoolAllocator_new(size_t nmemb, size_t size)
{
if (0 == size || 0 == nmemb) return NULL;
FixedPoolAllocator *ret = malloc(sizeof *ret);
if (NULL == ret) return NULL;
// Make sure that the size of each member is atleast size_t so that the members can store a memory address
size_t member_size = MAX(sizeof(size_t), size);
ret->mem = malloc(nmemb * member_size);
if (NULL == ret->mem) return NULL;
// The initial free member
ret->currentFree = (size_t*)ret->mem;
ret->numOfMembers = nmemb;
ret->memberSize = size;
size_t *temp = ret->currentFree;
// Assign each member with the address of the next member
size_t i;
for (i = 0; i < nmemb - 1; i++) {
*temp = (size_t) (ret->mem + (i+1) * member_size);
temp = (size_t*) ((char*)temp + member_size);
}
// The last member points to NULL
*temp = (size_t)NULL;
return ret;
}
void* FixedPoolAllocator_alloc(FixedPoolAllocator *allocator)
{
if (NULL == allocator || NULL == allocator->currentFree) return NULL;
// Return the currently free member and update currentFree to the next member in the list
void *ret = allocator->currentFree;
allocator->currentFree = (size_t*)*allocator->currentFree;
return ret;
}
void FixedPoolAllocator_free(FixedPoolAllocator *allocator, void *ptr)
{
size_t ptr_as_value = (size_t)ptr;
// Assign the pointed value with the current free member
*(size_t*)ptr = (size_t)allocator->currentFree;
// Update the currenty free member to be the one that was just freed
allocator->currentFree = ptr;
}
void FixedPoolAllocator_destroy(FixedPoolAllocator *allocator)
{
free(allocator->mem);
free(allocator);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T14:32:49.427",
"Id": "394159",
"Score": "3",
"body": "Thanks for fixing the post, and I hope you get some good answers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-27T09:54:31.903",
"Id": "394245... | [
{
"body": "<p>If you want enough size to fit a <code>void*</code> then actually use <code>sizeof(void*)</code>. If you really want to use an integer type instead of a pointer type then use <code>intptr_t</code> instead of <code>size_t</code>.</p>\n\n<pre><code>size_t member_size = MAX(sizeof(void*), size);\n</c... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T13:04:04.890",
"Id": "204406",
"Score": "7",
"Tags": [
"c",
"memory-management"
],
"Title": "Fixed-sized memory pool in C"
} | 204406 |
<p>I am modeling a capacitor which has its capacitance varying according to the DC Bias. The DC Bias is computed by taking the mean of the voltage across the capacitance.</p>
<pre><code>class CAP:
"""
Represents the Capacitor.
"""
def __init__(self, nominal_capacitance):
# Theoretical capacitance without DC Bias (i.e. voltage mean at 0)
self.nominal_capacitance = nominal_capacitance # uF
# Actual capacitance, initialized at the nominal value
self.capacitance = nominal_capacitance # uF
# Voltage control loop settings
self.set_voltage_value = None # Value set in mV
self.set_lower_voltage_window_bound = None # Window upper bound in mV
self.set_upper_voltage_window_bound = None # Window lower bound in mV
self.voltage = 0 # Voltage across the capacitor
self.being_charge = False # Is it being charged/discharged by the control loop?
# Measurements
self.charge_counter = 0
self.discharge_counter = 0
self.voltage_charged = 0
self.voltage_discharged = 0
# List of the voltage across the capacitance
self.timeline = [] # mV
def update_capacitance(self):
"""
Value according to the DC Bias characterstic approximation.
"""
global timelines_resolution # time step between 2 voltages measurements in the list self.timeline
DC_bias = np.mean(self.timeline) / 1000
change_perc = (-0.0008*(DC_bias**4)+0.0474*(DC_bias**3)-0.7953*(DC_bias**2)-0.5447*DC_bias-0.4847)/100
self.capacitance = self.nominal_capacitance * (1+change_perc)
</code></pre>
<p>The voltage across the capacitance is controlled via a control loop which will recharge or discharge the capacitor. The goal is to keep its voltage within boundaries (window).</p>
<p>The attribute <code>self.timeline</code> will have one measure point (voltage) added every <code>timelines_resolution</code>. I can get between 200 000 points to a few millions. </p>
<p>The conversion to a numpy array and the mean computation become quite long. On the otherhand, it is handy to work with a list and its <code>append</code> method since I do not know beforehand the number of point that will be measured.</p>
<p>Do you see any other way to compute this DC Bias or to make this faster?
At the moment, I call the function <code>update_capacitance</code> every 25000 points. I would like to increase this resolution.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-27T02:12:14.977",
"Id": "394202",
"Score": "0",
"body": "I find it unclear how this code is intended to be used. Please include the \"control loop\" of which you speak."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate"... | [
{
"body": "<p>Computing the mean of 25000 values is summing up the values and dividing by 25000.\nComputing the mean of 50000 values (the original 25000 plus 25000 new values) is summing up the values and dividing by 50000. This means (no pun intended) you are adding up the first 25000 values over and over aga... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T13:37:50.373",
"Id": "204409",
"Score": "0",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy",
"physics"
],
"Title": "Modeling a capacitor with DC Bias"
} | 204409 |
<p>I have a dataframe like:</p>
<pre><code> time_stamp id next_timestamp
0 2010-04-16 11:57:52 string_1 NaT
1 2010-04-16 12:06:16 string_1 NaT
2 2010-04-16 12:40:53 string_2 NaT
</code></pre>
<p>I want to fill <code>next_timestamp</code> column, with the next time_stamp that id has (if it exists).</p>
<p>Result would be something like:</p>
<pre><code> time_stamp id next_timestamp
0 2010-04-16 11:57:52 string_1 2010-04-16 12:06:16
1 2010-04-16 12:06:16 string_1 NaT
2 2010-04-16 12:40:53 string_2 NaT
</code></pre>
<p>My code at the moment:</p>
<pre><code>for row in df.index:
row_time_stamp = df.time_stamp[row]
id_array = df.id[row]
df_temp = df.loc[(df['time_stamp'] >= row_time_stamp) & \
(df['time_stamp'] <= row_time_stamp + datetime.timedelta(days=7))]
try:
next_id_msg = df_temp.loc[(df_temp['id'] == str(id_array))].time_stamp.min()
df['next_timestamp'][row] = next_id_msg
except IndexError:
df['next_timestamp'][row] = pd.NaT
</code></pre>
<p>The problem is that my my df is 50+ million rows long, and setting up a temp table for every row is not a good pattern.</p>
<p>Please help me out with a better pattern.</p>
| [] | [
{
"body": "<p>you can use <code>groupby.transform</code></p>\n\n<pre><code>df[\"next_timestamp\"] = df.groupby(\"id\")[\"time_stamp\"].transform(\n lambda x: x.shift(-1)\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-27T07:27:56.013"... | {
"AcceptedAnswerId": "204417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T14:38:07.893",
"Id": "204414",
"Score": "4",
"Tags": [
"python",
"datetime",
"pandas"
],
"Title": "Subtable timestamps in python pandas"
} | 204414 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.