body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I am trying to develop an ECS registry. How would you improve this ? First disadvantage comes to my mind is using lambdas might be expensive, however I was not able to replicate functionality using F&& template arguments.</p>
<pre><code> engine->addEntity(1,
Position{1, 1},
Mesh{"thing.gltf"},
PhysicsBody{10.0f}
);
engine->addEntity(2,
Position{ 2, 2 },
Mesh{ "other.gltf" },
PhysicsBody{ 30.0f }
);
engine->entity<Position>(1, [&](auto pos) {
std::cout << "entity";
});
engine->each<Position, Mesh>([] (int id, Position& pos, Mesh& mesh) {
std::cout << "entity" << id;
});
</code></pre>
<pre><code> template<typename First>
void entity(int id, std::function<void(First&)> callback)
{
auto comp = storage<First>()->get(id);
if (!comp) return;
callback(*comp);
}
template<typename First, typename...Rest>
void entity(int id, std::function<void(Rest&...)> callback)
{
auto comp = storage<First>()->get(id);
if (!comp) return;
entity<Rest...>(id, [](Rest&...args) {
callback(*comp, args...)
});
}
template<typename T, typename...Rest, typename F>
void each(F&& callback)
{
storage<T>()->forEach([&](int id, T& value) {
entity<Rest...>(id, [&](Rest&...args) {
callback(id, value, args...);
});
});
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>using lambdas might be expensive</p>\n</blockquote>\n\n<p>Why do you think that?</p>\n\n<p>Lambdas are simply syntactic hand waving for class functors (that have been around for over 3 decades). Functors are considered (in general) to be much more efficient than standard functions (especially when used by templates) as the compiler can do a lot of optimizations on them.</p>\n\n<pre><code>auto x = [&capture](X const& parm){ /* BODY */ }\n</code></pre>\n\n<p>You can consider as syntactic sugar for:</p>\n\n<pre><code>class CompilerNamedType\n{\n TypeOfCapure& capture;\n public:\n CompilerNamedType(TypeOfCapure& capture)\n : capture(capture)\n {}\n\n CompilerCalculatedReturnType operator()(X const& param) const\n {\n /* BODY */\n }\n};\n\nCompilerNamedType x(capture);\n</code></pre>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:25:15.750",
"Id": "241207",
"ParentId": "241188",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T12:25:31.470",
"Id": "241188",
"Score": "2",
"Tags": [
"c++",
"generics",
"entity-component-system"
],
"Title": "Variadic template with function argument"
}
|
241188
|
<p>Hi I need advice and review, here I have class AutomaticWorker which should constantly running and check if there is any file to process and after processing write data in database. OnDoWork method is inside while loop and started every 5 min to check if there is some job to do.</p>
<pre><code>public override void OnDoWork()
{
Exception ex = null;
try
{
_automaticWorker = new AutomaticWorker ();
Service.Log(this, "Starting...", EventLogEntryType.Information);
foreach(AutomaticProcesses process in _automaticWorker.GetAutomaticProcesses())
{
process.StartTransferProcessing();
}
Service.Log(this, "Finished...", EventLogEntryType.Information);
}
catch (Exception ex)
{
Service.Log(this, "Error: " + ex.Message + Constants.vbNewLine + ex.StackTrace, EventLogEntryType.Information);
}
}
public class AutomaticWorker
{
private readonly List<AutomaticProcess> _automaticProcesses;
public List<AutomatskaObradaOperacije> AutomaticProcesses
{
get
{
return _automaticProcesses;
}
}
public AutomaticWorker()
{
_automaticProcesses = AutomaticWorker.GetAutomaticProcesses();
}
private static List<AutomaticProcesses> GetAutomaticProcesses()
{
try
{
List<AutomaticProcesses> processes = new List<AutomaticProcesses>();
using (SqlConnection defaultConnection = CNN.DefaultConnection)
{
string sqlQuery = string.Empty;
sqlQuery = <string>...</string>.Value
using (IDataReader reader = ExecuteReader(sqlQuery, defaultConnection))
{
while (reader.Read())
{
AutomaticProcess process = new AutomaticProcess()
{
Code = reader("CODE").ToString.Trim,
Market = (MarketType)System.Convert.ToInt32(reader("MARKET")),
eMailInfo = dbNullOrNothingEmpty(reader("EMAIL_INFO"), "").ToString.Trim,
eMailError = dbNullOrNothingEmpty(reader("EMAIL_ERROR"), "").ToString.Trim,
Transfer = (TransferType)System.Convert.ToInt32(reader("TRANSFER_TYPE")),
Parameter = dbNullOrNothingEmpty(reader("PARAMETER"), "").ToString.Trim,
Path = dbNullOrNothingEmpty(reader("PATH"), "").ToString.Trim,
Extension = dbNullOrNothingEmpty(reader("EXTENSION"), "").ToString.Trim
};
processes.Add(process);
}
}
}
return processes;
}
catch (Exception ex)
{
if (Debugger.IsAttached)
Debugger.Break();
throw new Exception("...");
}
}
}
</code></pre>
<p>Here is AutomaticProcess class which contains method StartTransferProcessing which process transfer based on transfer type, before process it scan specific file from directory and process each file in static method TransferProcesor.Processing(Transfer transfer).</p>
<pre><code>public enum TransferType
{
MC,
DC,
DG
}
public class AutomaticProcess
{
public string Code { get; set; }
public MarketType Market { get; set; }
public string eMailInfo { get; set; }
public string eMailError { get; set; }
public TransferType Transfer { get; set; }
public string Parameter { get; set; }
public string Path { get; set; }
public string Extension { get; set; }
private DirectoryData _directoryFiles;
public AutomaticProcess()
{
}
private DirectoryData GetDirectoryData(string directory, string extension)
{
return dataDirectory; //this method scans directory and return all files with specific extension
}
public void StartTransferProcessing()
{
TransferResult result;
try
{
switch (Transfer)
{
case TransferType.DC:
{
TransferInfo transferInfo;
transferInfo = GetAllTransferInfo()
.Where(f => f.TransferCode.ToUpper().Trim() == Parameter.ToUpper().Trim())
.FirstOrDefault();
_directoryFiles = GetFilesFromDirectory(transfer.Directory, Extension);
if (!_directoryFiles == null && !_directoryFiles.Files.Count == 0)
{
foreach (DataFile file in _directoryFiles.Files)
{
DCTransfer transfer = new DCTransfer()
{
Market = this.Market,
TransferData = transferInfo,
FileData = file,
TransferType = this.TransferType
};
result = TransferProcesor.Processing(transfer);
TransferProcesor.SaveResult(result); //save result in database, method with insert data in database
}
}
break;
}
case TransferType.MC:
{
TransferInfo transferInfo;
transferInfo = GetAllTransferInfo()
.Where(f => f.TransferCode.ToUpper().Trim() == Parameter.ToUpper().Trim())
.FirstOrDefault();
_directoryFiles = GetFilesFromDirectory(transfer.Directory, Extension);
if (!_directoryFiles == null && !_directoryFiles.Files.Count == 0)
{
foreach (DataFile file in _directoryFiles.Files)
{
MCTransfer transfer = new MCTransfer()
{
Market = this.Market,
TransferData = transferInfo,
FileData = file,
TransferType = this.TransferType
};
result = TransferProcesor.Processing(transfer);
TransferProcesor.SaveResult(result); //save result in database, method with insert data in database
}
}
break;
}
case TransferType.DG:
{
_directoryFiles = GetFilesFromDirectory(transfer.Directory, Extension);
if (!_directoryFiles == null && !_directoryFiles.Files.Count == 0)
{
foreach (DataFile file in _directoryFiles.Files)
{
DGTransfer transfer = new DGTransfer()
{
FileData = file,
TransferType = this.TransferType
};
result = TransferProcesor.Processing(transfer);
TransferProcesor.SaveResult(result); //save result in database, method with insert data in database
}
}
break;
}
}
}
catch (Exception ex)
{
if (Debugger.IsAttached)
Debugger.Break();
throw new Exception("...!", ex);
}
}
}
</code></pre>
<p>Processing method creates specific object for processing each transfer depending on type.</p>
<pre><code>public class TransferResult
{
public MarketType Market { get; set; }
public TransferType Type { get; set; }
public TransferStatus Status { get; set; }
public bool Success { get; set; }
public string FileName { get; set; }
public string Info { get; set; }
public List<Errors> TransferErrors { get; set; }
}
public abstract class Transfer
{
public FileData fileData { get; set; }
public TransferType transferType { get; set; }
}
public class DCTransfer : Transfer
{
public TransferInfo TransferInfo { get; set; }
}
public class MCTransfer : Transfer
{
public TransferInfo TransferInfo { get; set; }
}
public class DGTransfer : Transfer
{
}
public class TransferProcesor
{
public static TransferResult Processing(Transfer transfer)
{
TransferResult result;
switch (transfer.TransferType)
{
case TransferType.DC:
{
DCTransferProcessing dcProcessing = new DCTransferProcessing(transfer);
result = dcProcessing.ProcessData();
break;
}
case TransferType.DG:
{
DGTransferProcessing dgProcessing = new DGTransferProcessing(transfer);
result = dgProcessing.ProcessData();
break;
}
case TransferType.MC:
{
MCTransferProcessing mcProcessing = new MCTransferProcessing(transfer);
result = mcProcessing.ProcessData();
break;
}
default:
{
throw new NotImplementedException("...");
break;
}
}
return result;
}
}
</code></pre>
<p>For me this code looks a little bit ugly, is it better approach to use some design pattern?
If you need further explanation for this classes or methods feel free to ask.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:25:28.413",
"Id": "473315",
"Score": "0",
"body": "Does this code compile? 1) is `RezultatTransfera` actually `TransferResult`? 2) `Transfer` inheritors (e.g. `MDCTransfer`) are not used. 3) I don't see a `TransferType` implementation. 4) `TransferType` seems to be both a property and a class within the same scope - `AutomaticProcess` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:33:36.863",
"Id": "473316",
"Score": "0",
"body": "Hi @radarbob, I translated from my mother language on some places I missed to translate on English, I edited my post and added enum definition for TransferType."
}
] |
[
{
"body": "<p>This code needs better abstraction and <strong>S</strong>ingle <strong>R</strong>esponsibility <strong>P</strong>rinciple re-structuring which will naturally facilitate pattern use. Right off the bat I see \"factory pattern\" as one result.</p>\n\n<hr>\n\n<p><strong>Factory Pattern</strong></p>\n\n<p>When <code>abstract Transfer</code> defines ALL members needed to do stuff then we can use factory pattern to build all the derived types. Same for those three <code>xxTransferProcessing</code> types.</p>\n\n<pre><code>// EVERYTHING needed to instantiate a Transfer must be in here.\npublic static class TransferFactory {\n\n // maybe no switch, but overloaded `Create` for different parameters. Or maybe use `params`.\n\n public static Transfer Create( TransferType thisGuy ) {\n Transfer aTransfer;\n\n switch ( thisGuy ) {\n\n case TransferType.DC: {\n aTransfer = new DCTransfer( thisGuy );\n break;\n }\n\n case TransferType.DG: {\n aTransfer = new DGTransfer( thisGuy );\n break;\n }\n\n case TransferType.MC: {\n aTransfer = new MCTransfer( thisGuy );\n break;\n }\n\n case TransferType.Undefined: { ... } // see below\n\n default: { ... }\n }\n\n return aTransfer;\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>TransferType enum</strong></p>\n\n<pre><code>public enum TransferType { undefined, MC, DC, DG }\n</code></pre>\n\n<p><code>enum</code> default value is zero, so might as well give it a name. Assigning it explicitly is saying \"yeah, this guy is 'undefined' on purpose\". The next time you have a 60 value <code>enum</code> used across dozens of classes you'll say \"thanks for the tip, Bob.\" Yeah, you will. ;-)</p>\n\n<p>In a way it makes a \"nothing / null-like\" value type safe with respect to <code>TransferType</code> variables.</p>\n\n<hr>\n\n<p>Now the massive <code>TransferProcess.StartTransferProcessing()</code> total code is cut by at least 2/3.</p>\n\n<pre><code>transferInfo = GetAllTransferInfo()\n .Where(f => f.TransferCode.ToUpper().Trim() == Parameter.ToUpper().Trim())\n .FirstOrDefault();\n\n _directoryFiles = GetFilesFromDirectory(transfer.Directory, Extension);\n\n if (!_directoryFiles == null && !_directoryFiles.Files.Count == 0)\n {\n foreach (DataFile file in _directoryFiles.Files)\n {\n // ******* LOOK! NO SWITCH *******\n Transfer = TranferFactory.Create( Transfer, this.Market,\n transferInfo, file )\n };\n\n result = TransferProcesor.Processing( transfer );\n\n TransferProcesor.SaveResult(result); \n\n// yeah, this should be in try/catch.\n{\n if ( Debugger.IsAttached )\n Debugger.Break();\n throw new Exception(\"...!\", ex);\n}\n</code></pre>\n\n<hr>\n\n<p><strong>abstract class Transfer</strong></p>\n\n<p>Move <code>public TransferInfo TransferInfo</code> into the abstract class. Make its implementation required and have some kind of \"nothing\" or \"null-ish\" implementation for classes like <code>DCTransfer</code>. </p>\n\n<pre><code>public abstract class Transfer\n{\n public FileData fileData { get; set; }\n public TransferType transferType { get; set; }\n public abstract TransferInfo TransferInfo ();\n}\n\npublic class DCTransfer : Transfer { }\n\npublic class MCTransfer : Transfer { }\n\npublic class DGTransfer : Transfer \n{ public TransferInfo get{ return null; } }\n</code></pre>\n\n<p>When all base-type object are consistent then client code gets much simpler. If client code must, for itself, differentiate derived types that's <em>possibly</em> a design defect (aka \"code smell\").</p>\n\n<p>Resulting OO goodness:</p>\n\n<p><strong>public static TransferResult Processing(Transfer transfer)</strong></p>\n\n<p>becomes dead simple when we treat all derived objects the same way. </p>\n\n<pre><code>{\n Transfer Transfer = TransferFactory.Create(transfer.TransferType);\n TransferResult result = Transfer.ProcessData();\n return result;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>abstract class TransferProcessing</strong></p>\n\n<p>Make a base for <code>xxxTransferProcessing</code> objects. </p>\n\n<p>Resulting OO goodness:</p>\n\n<pre><code>public abstract class TransferProcesor {\n{\n public static TransferResult Processing(Transfer transfer)\n {\n TransferResult result;\n TransferProcessing xxProcessing = ProcessFactory.Create( transfer )\n result = xxProcessing.ProcessData();\n return result;\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Collection classes</strong></p>\n\n<p>I sigh whenever I see this kind of thing:</p>\n\n<pre><code>private readonly List<AutomaticProcess> processes;\n</code></pre>\n\n<p>Do this instead:</p>\n\n<pre><code>public class AutoProcesses { \n protected List<AutomaticProcess> processes { get; set; }\n\n public AutoProcesses() { processes = new List<AutomaticProcesses>() }\n\n public void Add(AutomaticProcess thisGuy) {\n if ( thisGuy == null ) return;\n\n processes.Add(thisGy);\n }\n\n pubic AutoProcesses AllDC() {\n AutoProcesses DcProcesses = new AutoProcesses();\n\n forEach (var process in processes) {\n DcProcesses.Add(this.processes.Find(process.Type == TransferType.DC);\n }\n\n return DcProcesses; \n }\n}\n</code></pre>\n\n<p>The OO goodness:</p>\n\n<ul>\n<li>Look and feel of a business domain object</li>\n<li>All <code>List</code> public members are hidden. Does only what you intend. This is why there's no inheritance.</li>\n<li>Proper SRP. The collection knows how to find its own members, thank you very much.</li>\n<li>Client code is vastly simplified because needed collection functionality is encapsulated in the right kind of class.</li>\n<li>Client code becomes far more readable, understandable, and amazingly simplified.</li>\n<li>Principle of least knowledge. Client does not do-it-yourself with internal access to the collection ( nor the contained objects ).</li>\n</ul>\n\n<hr>\n\n<h2>Which Design Pattern?</h2>\n\n<p>Heck, I don't know. Often a certain pattern may inspire some design aspect but without precisely implementing the pattern. IN ALL CASES, good OO design of your basic classes is essential. I hope I have shown this in getting to the factory pattern.</p>\n\n<p><strong>Factory</strong> is a <em>construction</em> pattern. Its purpose is to encapsulate details and complexities of building objects, giving clients a simple interface (method calls) to use it. However complex the construction process may be, the client is blissfully ignorant - all it knows is <code>myFactory.Create( thisGuy )</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T19:41:53.590",
"Id": "473411",
"Score": "0",
"body": "Thank you @radarbob for your advice and review"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T03:55:39.177",
"Id": "241221",
"ParentId": "241189",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241221",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T12:59:25.323",
"Id": "241189",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Which design pattern is best suited for automatic processing transfer data"
}
|
241189
|
<p>I'd like feedback please as to improvements which could be made to make this more 'pythonic' in its approach/structure. Any constructive feedback welcome. The below is a game which takes a single random word from a list of 3000 and has the player guess letters (whilst being limited to a certain number of attempts).</p>
<pre><code>#!/usr/bin/env python3
import random
import linecache
import sys
sourcefile = 'wordlist' # list of words
def playagain():
response = input('Do you want to play again? ')
response = response.lower()
if response == 'yes' or response == 'y':
main()
else:
print('OK...')
sys.exit(0)
def find_word():
random_line = random.randint(1, 3000) # random line number
chosen_word = linecache.getline(sourcefile, random_line)
str_chosen_word = chosen_word.strip('\n')
return str_chosen_word.lower()
def getIndexPositions(list_chosen_word, char):
indexPosList = []
indexPos = 0
while True:
try:
# Search for item in list from indexPos to the end of list
indexPos = list_chosen_word.index(char, indexPos)
# Add the index position in list
indexPosList.append(indexPos)
indexPos += 1
except ValueError as e:
break
return indexPosList
def main():
guessed = [] # create list to track guessed letters
list_masked_word = [] # create list to show progress of guessing
str_chosen_word = find_word() # get random word
list_chosen_word = list(str_chosen_word) # create list from word
length_list_chosen_word = len(list_chosen_word) # length of word
attempts = length_list_chosen_word + 3 # number of attempts
list_masked_word = ['\u25A0'] * length_list_chosen_word # masking
game(attempts, guessed, list_chosen_word, list_masked_word)
def game(attempts, guessed, list_chosen_word, list_masked_word):
print()
print('Welcome to the word game')
while (attempts != 0):
print()
print('You have', attempts, 'attempts to guess the word correctly')
print('So far you have found: ', ''.join(list_masked_word))
attempts -= 1 # reduce the number of attempts available
guess = str(input('Enter a letter: ')).lower()
if len(guess) == 1:
if guess in guessed:
print('Ooops - You have already tried that letter')
else:
guessed.append(guess) # keeps track of letters guessed
indexPosList = getIndexPositions(list_chosen_word, guess)
for index in indexPosList:
list_masked_word[index] = guess
if list_chosen_word == list_masked_word:
print('The word was: ',''.join(list_chosen_word))
print('Well Done - you guessed the word')
playagain()
else:
print()
print('Enter only one letter!')
print()
print('You are out of guesses')
playagain()
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:12:18.510",
"Id": "473270",
"Score": "1",
"body": "What is this program? What is it supposed to do and why does it exist? Please add context; thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:58:36.880",
"Id": "473321",
"Score": "0",
"body": "It's a word game. It takes a random word. Masks it. The player has a certain number of attempts to guess the correct word."
}
] |
[
{
"body": "<h2>Global constants</h2>\n\n<pre><code>sourcefile = 'wordlist' # list of words\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>SOURCE_FILE = 'wordlist' # list of words\n</code></pre>\n\n<h2>Looping instead of recursion</h2>\n\n<pre><code>if response == 'yes' or response == 'y':\n main()\n</code></pre>\n\n<p>For a small number of replays this will have no noticeable ill effect, but if an obsessive user replays enough, they will eventually blow the stack. Replace this with a loop at the upper level in <code>main</code>.</p>\n\n<h2>Function names</h2>\n\n<pre><code>def getIndexPositions\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>def get_index_positions\n</code></pre>\n\n<p>and similar snake_case for your local variables.</p>\n\n<h2>State passing</h2>\n\n<p>Why are <code>guessed</code> and <code>list_masked_word</code> passed into <code>game</code>? They seem like they should just be initialized within <code>game</code> without being parameters.</p>\n\n<h2>String interpolation</h2>\n\n<pre><code>'You have', attempts, 'attempts to guess the word correctly'\n</code></pre>\n\n<p>is more easily expressed as</p>\n\n<pre><code>f'You have {attempts} attempts to guess the word correctly'\n</code></pre>\n\n<h2>Loop syntax</h2>\n\n<p>This:</p>\n\n<pre><code>while (attempts != 0):\n</code></pre>\n\n<p>does not need parens. Also, rather than manually decrementing it, you can do</p>\n\n<pre><code>for attempt in range(attempts, 0, -1):\n</code></pre>\n\n<h2>Typo</h2>\n\n<p><code>Ooops</code> -> <code>Oops</code></p>\n\n<h2>Early-continue</h2>\n\n<p>I find that this:</p>\n\n<pre><code> if len(guess) == 1:\n # lots of code...\n else:\n print()\n print('Enter only one letter!')\n</code></pre>\n\n<p>is more easily legible as</p>\n\n<pre><code> if len(guess) != 1:\n print()\n print('Enter only one letter!')\n continue\n\n # lots of code...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T14:51:10.730",
"Id": "474671",
"Score": "0",
"body": "Thats great - thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T16:56:04.103",
"Id": "241307",
"ParentId": "241191",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241307",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T14:42:43.993",
"Id": "241191",
"Score": "4",
"Tags": [
"python",
"game"
],
"Title": "Wordgame in Python"
}
|
241191
|
<p>I have written C++ code using trie and min-heap to find the k most frequent words. I want to review my code.</p>
<pre><code> #include<bits/stdc++.h>
using namespace std ;
//structure of the node of trie
struct TrieNode
{
bool IsEnd ; // If this node is end node
int HeapIndex ; // To store the index of this word in heap.
TrieNode * children [ 26 ] ; // To store its children.
int frequency ; // To store the frequency of word ending at this
TrieNode () // Constructure .
{
HeapIndex = -1 ;
IsEnd = false ;
frequency = 0 ;
for ( int i = 0 ; i < 26 ; i ++ )
children [ i ]= NULL ;
}
};
struct HeapNode
{
string word ; // To store the word.
int frequency ; // to store the frequency of word.
TrieNode* TN ; // To store the last Triendnode of this word.
HeapNode ()
{
frequency = 0 ;
TN = NULL ;
word = "" ;
}
};
class Trie {
TrieNode * root ;
public:
Trie()
{
root = new TrieNode() ;
}
TrieNode* insert( string word)
{
TrieNode * temp = root ;
for ( int i = 0 ; i < word.length() ; i ++ )
{
if ( temp -> children [ word [ i ] - 'a' ] == NULL )
{
TrieNode * node = new TrieNode() ;
temp -> children [ word [ i ] - 'a' ] = node ;
}
temp = temp -> children [ word [ i ] - 'a' ] ;
}
temp -> frequency = 1 ;
temp -> IsEnd = 1 ;
return temp ;
}
TrieNode* search(string word)
{
TrieNode * temp = root ;
for ( int i = 0 ; i < word.length() ; i ++ )
{
if ( temp -> children [ word [ i ] - 'a' ]== NULL )
return NULL ;
temp = temp -> children [ word [ i ] - 'a' ] ;
}
if ( temp -> IsEnd )
return temp ;
else
return NULL ;
}
};
class MinHeap
{
int capacity , count ;
HeapNode * arr ;
public :
MinHeap ( int capacity )
{
this -> capacity = capacity ;
count = 0 ;
arr = new HeapNode [ capacity ] ;
}
void Display ()
{
for ( int i = 0 ; i < capacity ; i ++ )
cout << arr [ i ] .word << ":" << arr [ i ] .frequency << endl ; ;
}
void MinHeapify ( int idx )
{
int left = 2 * idx + 1 ;
int right = 2 * idx + 2 ;
int minidx = idx ;
if ( left < count and arr[ left ] .frequency < arr [ minidx ] .frequency )
minidx = left ;
if ( right < count and arr[ right ] .frequency < arr [ minidx ] .frequency )
minidx = right ;
if ( minidx != idx )
{
arr [ idx ] .TN -> HeapIndex = minidx ;
arr [ minidx ] .TN -> HeapIndex = idx ;
swap ( arr [ idx ] , arr [ minidx ] ) ;
MinHeapify ( minidx ) ;
}
}
void Build ( int idx )
{
int n = count - 1 ;
for ( int i = ( n - 1 ) / 2 ; i >= 0 ; i -- )
MinHeapify ( i ) ;
}
void insert ( TrieNode * TN , string word )
{
if ( TN -> HeapIndex != -1 ) //When word is already present in the heap.
{
//cout << 1 << endl ;
arr [ TN -> HeapIndex ] .frequency ++ ;
MinHeapify ( TN -> HeapIndex ) ;
}
else if ( count < capacity ) // When heap size is less than k
{
//cout << 2 << endl ;
arr [ count ]. word = word ;
arr [ count ]. frequency = 1 ;
arr [ count ] . TN = TN ;
TN -> HeapIndex = count ;
count ++ ;
Build ( count ) ;
}
else if ( TN -> frequency > arr [ 0 ] . frequency )
{
//cout << 3 << endl ;
arr [ 0 ] .TN -> HeapIndex = -1 ;
arr [ 0 ] . word = word ;
arr [ 0 ] . frequency = TN -> frequency ;
arr [ 0 ] . TN = TN ;
TN -> HeapIndex = 0 ;
MinHeapify ( 0 ) ;
}
}
};
void TopKFrequentWords ( string FileName , int k )
{
MinHeap MH ( k ) ;
Trie T ;
fstream file;
file.open ( FileName.c_str() ) ;
string word ;
while ( file >> word )
{
TrieNode * TN = T.search ( word ) ;
if ( !TN )
{
//cout << word << "**" << endl ;
TN = T.insert ( word ) ;
}
else
{
//cout << word << "&&&&" << endl ;
TN -> frequency ++ ;
}
MH.insert ( TN , word ) ;
}
MH.Display() ;
}
int main()
{
int k ;
cin >> k ;
string FileName ;
cin >> FileName ;
TopKFrequentWords ( FileName , k ) ;
}
</code></pre>
<p>I want to know how will I accommodate frequency for words like beautiful and ful having same suffix. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:38:30.307",
"Id": "473307",
"Score": "2",
"body": "Are you experimenting with building structures (like the Tri tree) or are you looking for the best way to count words (as you can do it using standard containers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T05:28:25.997",
"Id": "473347",
"Score": "0",
"body": "Please fix the indentation of your code presentation. In the post editor, I find it least troublesome to create two lines of markdown just containing `~~~` and pasting the code between them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T05:31:36.197",
"Id": "473348",
"Score": "0",
"body": "`how will I accommodate frequency for words like beautiful and ful having same suffix` as specified, for all the specification not presented."
}
] |
[
{
"body": "<p>Never ever do that:</p>\n\n<pre><code>#include<bits/stdc++.h> \n using namespace std ;\n</code></pre>\n\n<p>Otherwise you'll get into trouble soon. Xou can check <a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h\">Why should I not #include ?</a> and <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a> for more details.</p>\n\n<p>Just include every header you need separately and prefix the <code>std::</code> namespace when needed (alternatively use a <code>using</code> definition).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:06:38.893",
"Id": "473285",
"Score": "1",
"body": "It might be good to explain why `using namespace std;` is bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:13:55.143",
"Id": "473290",
"Score": "0",
"body": "@pacmaninbw Added at least the most relevant links."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T16:06:20.800",
"Id": "241196",
"ParentId": "241192",
"Score": "0"
}
},
{
"body": "<h2>Overall</h2>\n<p>I find your code very untidy (and thus hard to read). Please make sure to use nice indentation and generally make the code easy to read.</p>\n<p>You don't do any memory management. In the class <code>Trie</code> it creates a lot of <code>TriNode</code> objects via <code>new</code>. You are supposed to track these and eventually call <code>delete</code> on all these objects.</p>\n<h2>Code Review</h2>\n<p>This is not a standard header file:</p>\n<pre><code>#include<bits/stdc++.h> \n</code></pre>\n<p>Please never use it.<br />\nYou are supposed to include only the headers you need.</p>\n<hr />\n<p>This is not a good idea:</p>\n<pre><code> using namespace std ;\n</code></pre>\n<p>Please read the article: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n<p>The main issue is that it can completely change the meaning of code without causing any kind of compiler warning.</p>\n<p>The reason the "standard" library is named "std" is so that it is not a big issue to prefix things in the standard library with <code>std::</code>. This is the preferred technique.</p>\n<hr />\n<p>In C++ we have deprecated the use of <code>NULL</code> and replaced it with <code>nullptr</code>. The difference is that <code>NULL</code> is a macro that evaluates to the integer zero while <code>nullptr</code> has a specific type of <code>std::nullptr_t</code>. The advantage of this is that <code>nullptr</code> can only be assigned to pointer types while <code>NULL</code> can be assigned to pointers and any integer type (which has caused issues).</p>\n<pre><code>TN = NULL;\n// prefer\nTN = nullptr;\n</code></pre>\n<hr />\n<p>Note the default constructor for <code>std::string</code> assigns it the empty string. So there is no need to set it to the empty string in a constructor.</p>\n<pre><code> word = "";\n // Useful to reset to the empty string if the word object had\n // been used. But in a constructor you know it has just been constructed\n // and thus does not need to be set again. So just leave it.\n</code></pre>\n<hr />\n<p>When writing constructors prefer to use the initializer list rather than initializing them in the code block:</p>\n<pre><code> HeapNode ()\n {\n frequency = 0 ;\n TN = NULL ; \n word = "" ; \n }\n\n // I would write this as: \n HeapNode()\n : frequency(0)\n , TN(nullptr) \n {}\n</code></pre>\n<p>The reason for this is that member variables are already initialized by their constructor before the code block is entered. The initializer list allows you to pass parameters to the constructors.</p>\n<p>So if you initialize variables in the code block you are doing twice the work. Because you are calling the default constructor then you are calling the assignment constructor.</p>\n<p>You may think it's OK not to do this for <code>int</code> and pointer types because they don't have constructors or assignment operators. But this does not consider the normal usage of C++. In is quite normal to change C++ by simply changing the type of a member and not changing anything else. If you have not followed the above pattern then you end up paying the price after the change.</p>\n<hr />\n<p>Taking a risk here that there are only lower case alphabetic characters.</p>\n<pre><code> if ( temp -> children [ word [ i ] - 'a' ] == NULL )\n</code></pre>\n<p>You should check to make sure there are no upper case letters (or convert to lower case) and no none alphabetic characters.</p>\n<hr />\n<p>You can open a file in a single line.</p>\n<pre><code> fstream file; \n file.open ( FileName.c_str() ) ; \n\n\n // I would use this:\n std::ifstream file(FileName);\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:12:49.867",
"Id": "241204",
"ParentId": "241192",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:17:01.700",
"Id": "241192",
"Score": "-1",
"Tags": [
"c++",
"file",
"heap",
"trie"
],
"Title": "Finding the k most frequent words in file in c++"
}
|
241192
|
<p>I want to make a command-line text editor in python. Is this good code?</p>
<pre class="lang-py prettyprint-override"><code>from termcolor import *
import os
while True:
files = os.listdir()
bufname = input("File name: ")
title = cprint("Ganesha Editor v1.0", "green")
controls = cprint("Type $exit to exit text editor. It autosaves.", "blue")
def write():
print("Compose Something Below:\n\n")
text = input()
if text == "$exit":
exit()
else:
if bufname in files:
os.remove(bufname)
create = open(bufname, "w")
create.close()
autosave = open(bufname, "a")
autosave.write(text)
autosave.write("\n")
autosave.close()
else:
autosave = open(bufname, "a")
autosave.write(text)
autosave.write("\n")
autosave.close()
while True:
write()
</code></pre>
<p>I prettified the code with 8 spaces for the indents.</p>
<p>Does anyone like this code? It's very minimal, and no one will like it, but, I'm trying to make a secondary text-editor.</p>
|
[] |
[
{
"body": "<p>The code's pretty straightforward, but it could still be simplified a bit:</p>\n\n<ol>\n<li><p>There's no reason to have multiple levels of <code>while</code> loop; you already run your <code>write()</code> function in an inner loop until it's time to exit, so the outer loop only ever gets executed once.</p></li>\n<li><p>The code to append to the file is duplicated.</p></li>\n<li><p>The file deletion behavior is very strange and seems like a bug -- if the file exists, you delete it, but you do that after every line, making it impossible to write a multi-line file (but only in the case where the file existed when you started the editor). Seems like you probably meant to only delete it once but forgot to update your <code>files</code> list?</p></li>\n<li><p>The <code>write()</code> function doesn't necessarily always write something; sometimes it exits (which is generally considered bad form since it makes reuse and testing difficult). It also has the extra responsibility of deleting the existing file, which is why that deletion is maybe happening more often than you meant it to. Separating the setup from the core editing loop would make this much easier to reason about.</p></li>\n<li><p><code>cprint</code> doesn't return a value, so assigning it to <code>title</code> and <code>controls</code> (which you don't use anyway) is confusing.</p></li>\n<li><p>When an <code>if</code> block breaks the control flow (e.g. by <code>exit()</code> or <code>return</code> or <code>break</code>) it's not necessary to have everything else under an <code>else</code>. In some cases the code may be more clear with a redundant <code>else</code> (e.g. when the two branches are similar in length and/or when you want to make it more obvious that they're mutually exclusive), but when the bulk of your code is indented unnecessarily it tends to make it harder to follow rather than easier.</p></li>\n<li><p>It's generally better to use file handles as context managers (<code>with open ...</code>). It makes it impossible to forget to close the file, and it makes it very obvious what you're doing while the file is open.</p></li>\n<li><p>This is more of a note on the UX than the code, but I suggest (A) telling the user when you're deleting their file (and only doing it on startup rather than after every autosave) and (B) not having so many blank/repeated lines in the interface (it makes it harder to see what you've already entered).</p></li>\n</ol>\n\n<p>Below is the result of applying the above notes -- now there are two functions (<code>init</code> and <code>run</code>), with one in charge of everything that happens up front, and the other in charge of everything that happens on each subsequent input.</p>\n\n<pre><code>import os\nfrom termcolor import cprint\n\n\ndef init() -> str:\n \"\"\"\n Start the editor by prompting for a filename and printing\n usage information. If the file already exists, remove it.\n Returns the filename.\n \"\"\"\n filename = input(\"File name: \")\n if filename in os.listdir():\n print(\"Deleting existing file to give you a blank slate.\")\n os.remove(filename)\n cprint(\"Ganesha Editor v1.0\", \"green\")\n cprint(\"Type $exit to exit text editor. It autosaves.\", \"blue\")\n print(\"Compose Something Below:\")\n return filename\n\n\ndef run(filename: str) -> bool:\n \"\"\"\n Prompts for input and writes it to the file. \n Returns True as long as it's still running, \n returns False when it's time to exit.\n \"\"\"\n text = input()\n if text == \"$exit\":\n return False\n with open(filename, \"a\") as autosave:\n autosave.write(text)\n autosave.write(\"\\n\")\n return True\n\n\nif __name__ == \"__main__\":\n filename = init()\n while run(filename):\n pass\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T22:10:08.757",
"Id": "241215",
"ParentId": "241194",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241215",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:34:11.723",
"Id": "241194",
"Score": "2",
"Tags": [
"python",
"text-editor"
],
"Title": "Python Command Line text editor"
}
|
241194
|
<p>I have a class with numerous methods, and so I would like to split these up into groups. This would make it easier for the user to find the method they are after. Here is a minimal example of this functionality.</p>
<pre><code>class Greeter():
def __init__(self, name):
self.name = name
self.spanish = Spanish(self)
def generic(self):
return f"Hello, {self.name}"
class Spanish():
def __init__(self, greeter):
self.grtr = greeter
def hola(self):
return f"Hola, {self.grtr.name}"
def buen_dia(self):
return f"Buenos días, {self.grtr.name}"
greeter = Greeter("Ann Example")
greeter.generic()
#> "Hello, Ann Example"
greeter.spanish.hola()
#> "Hola, Ann Example"
</code></pre>
<p>This feels like a hacky approach. Are there places people could see this failing? Is there a better solution in general?</p>
<p><strong>EDIT</strong></p>
<p>As suggested, here is a reduced example of my actual need for this functionality:</p>
<pre><code>class Matrix():
def __init__(self, m, n, data):
# checks on m, n, data
self.m = m
self.n = n
self.data = data
self.decomposition = Decomposition(self)
# many generic methods some returning more matrices
def __add__(self, other):
# add matrices
return Matrix(m, n, data)
# some methods will affect m, n, data
def transpose(self):
# set up new attributes
self.m = m
self.n = n
self.data = data
class Decomposition():
def __init__(self, mtrx):
self.mtrx = mtrx
# NB: eventually these might change m, n, data
def QR(self):
# do stuff for QR decomposition using self.mtrx
return Q, R
def LU(self):
# do stuff for LU decomposition using self.mtrx
return L, U
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:04:48.293",
"Id": "473300",
"Score": "1",
"body": "Why don't you make the Generic class abstract and then have Spanish or whatever language inherit from it? That way you can have generic methods for each message you want to display, and override them in the child classes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:34:01.380",
"Id": "473304",
"Score": "0",
"body": "I appreciate that with this abstract example that makes sense but for my actual use case (which is probably just confusing to share) it doesn't quite work as there would be multiple groups of methods which all need to be accessed. It's just a way of grouping methods. If I want to greet someone in Spanish I don't have to search through all the methods for other languages but rather specify that I'm after a Spanish greeting first then choose the method. It would be clunky to have to instantiate a new class member to do this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T04:44:02.160",
"Id": "473344",
"Score": "2",
"body": "In your `reduced example`, I do not see `a class with numerous methods`. (I do see a funny `transpose()`.) Please present [enough actual code from your project to support meaningful reviews](https://codereview.stackexchange.com/help/on-topic). If need be, *someone* is bound to try and sort out *why* the presented is confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T09:36:50.847",
"Id": "473473",
"Score": "0",
"body": "@greybeard This feels like obsessive nit-picking and it's a very unfriendly welcome to this community. I'm sure you can imagine what multiple methods look like. I've explained all the types of methods I have and what they might return which is what is important. For all it matters, the others could be `transpose1()`, `transpose2()`, ... `transpose1000()` and any answer would be exactly the same."
}
] |
[
{
"body": "<p>This is a review of the initial code that was posted. Unfortunately, I don't have time to revise it now for the new code.</p>\n\n<hr>\n\n<p>Wanting to lessen the number of methods in a class is on its own a poor reason to split up a class into multiple. Classes can have many methods, and we can use IDE functionality and good documentation to make sense of a class.</p>\n\n<p>Having many methods <em>can</em> suggest though that the class is doing too much, and <em>that</em> would be a more logical justification to split the class up. A better thing to think about is not the size of the class, but what the job of the class is, and if it's doing too many things.</p>\n\n<p>That said, if you feel like it's justified to split it, I wouldn't do it as you have here. You've given the entire state of the <code>Greeter</code> object to <code>Spanish</code>. If <code>Spanish</code> begins using a lot of the state in <code>Greeter</code>, you now have two tightly coupled classes that will begin to break as you make changes to either.</p>\n\n<p>Just give <code>Spanish</code> the information that it explicitly needs:</p>\n\n<pre><code>class Spanish:\n def __init__(self, name):\n self.name = name\n\n def hola(self):\n return f\"Hola, {self.name}\"\n\n def buen_dia(self):\n return f\"Buenos días, {self.name}\"\n</code></pre>\n\n<p>And</p>\n\n<pre><code>class Greeter:\n def __init__(self, name):\n self.name = name\n self.spanish = Spanish(name) # And just pass the name\n . . .\n</code></pre>\n\n<p>This setup really doesn't make sense though. To get a greeting in Spanish, you need to access an object that greets in English? Even combined it doesn't make much sense. Having an object that greets in multiple languages seems odd. It would make more sense to have completely discrete classes that don't know about each other.</p>\n\n<p>With a toy example like this though, it's really hard to make a concrete suggestion because the actual intent isn't clear. The textbox that I'm writing the answer in is also bugging out, so I'm going to submit this before I lose everything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:31:07.707",
"Id": "473302",
"Score": "0",
"body": "But in this case how do I keep Greeter and Spanish in sync? Say, I add an `update_name()` method? I seems excessive and confusing to have my code track down all method groups and update the name there.\n\nAlso, I appreciate the difficulty of working with these abstract examples. I feel confident that this is a reasonable thing to do for my project though. It's inspired by Pandas' Series.str.replace() and the likes though the source code for that is too complex for me to disect and base my solution on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:33:10.460",
"Id": "473303",
"Score": "0",
"body": "@TimHargreaves If you needed the objects to be in sync, then that changes things a bit. You didn't post very detailed requirements, and intent wasn't super clear from the example code though, so it isn't entirely clear what the end goal is. I'll note, that's one reason why toy code like this is discouraged here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:35:20.857",
"Id": "473305",
"Score": "0",
"body": "Apologies. I've had people discourage the use of complex examples rather than simple, abstract ones too. I will edit my question to add my full use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:37:59.327",
"Id": "473306",
"Score": "0",
"body": "@TimHargreaves Ideally, the code should be a complete, runnable example (or close to it) if the whole thing is too complex to post in its entirety. It needs to be real enough that the intent is clear, but also a reasonable enough example that reviewers will be able to make sense of it. Some people post massive projects here, and it's hard to expect people to understand the code enough in its entirety to be able to make suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:46:22.643",
"Id": "473308",
"Score": "0",
"body": "Apologies. I've fixed my question to make my use case clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T03:29:44.967",
"Id": "473447",
"Score": "0",
"body": "_I don't have time to revise it now for the new code._ - The OP editing their code so much that it invalidates your answer is against site policy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T03:34:12.217",
"Id": "473448",
"Score": "0",
"body": "@Reinderien The code I'm addressing remains. My answer isn't necessarily invalidated by the addition of new code. I'll admit though, this wasn't an ideal question."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T16:57:35.880",
"Id": "241199",
"ParentId": "241198",
"Score": "2"
}
},
{
"body": "<p>Circular references are bad; if you split the classes into multiple files (which you'll probably want to do if the goal is to make navigation easier) then circular references usually mean circular imports, which cause other problems.</p>\n\n<p>If you need to split a class up, splitting it into superclasses/mixins is better IMO. For example:</p>\n\n<pre><code>class MatrixBase:\n \"\"\"Matrix base class.\n Defines instance variables and initialization.\"\"\"\n def __init__(self, m, n, data):\n # checks on m, n, data\n self.m = m\n self.n = n\n self.data = data\n\n\nclass MatrixGenericOps(MatrixBase):\n \"\"\"Generic matrix operations.\"\"\"\n\n # many generic methods some returning more matrices\n def __add__(self, other):\n # add matrices\n return type(self)(self.m, self.n, self.data)\n\n # some methods will affect m, n, data\n def transpose(self):\n # set up new attributes\n self.m = m\n self.n = n\n self.data = data\n\n\nclass MatrixDecomposition(MatrixBase):\n \"\"\"Decomposition operations.\"\"\"\n\n # NB: eventually these might change m, n, data\n def QR(self):\n # do stuff for QR decomposition using self.mtrx\n # return Q, R\n pass\n\n def LU(self):\n # do stuff for LU decomposition using self.mtrx\n # return L, U\n pass\n\n\nclass Matrix(MatrixGenericOps, MatrixDecomposition):\n \"\"\"A fully-functional Matrix.\"\"\"\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T09:39:30.100",
"Id": "473474",
"Score": "0",
"body": "This seems like a good structure. Thank you. Is there a way I can make this compatible with the naming convention `Matrix.decomposition.QR()`? The idea is that a user is unlikely to remember the name of every decomposition but would be reminded when they saw all options from a shorter list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T13:46:29.167",
"Id": "473492",
"Score": "0",
"body": "I would do this just by naming them `decompose_qr` and `decompose_lu` or whatever so that the naming pattern is easy to remember and makes decomposition functions easy to discover. Having the functionality live on a separate object is weird if it's still something you're doing to the matrix itself IMO, but I'm a big fan of naming things such that they're easily searchable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T16:10:12.003",
"Id": "241252",
"ParentId": "241198",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T16:34:17.027",
"Id": "241198",
"Score": "1",
"Tags": [
"python",
"object-oriented"
],
"Title": "Grouping methods of a Python class"
}
|
241198
|
<blockquote>
<p>Given an array a, find the greatest number in a that is a product of two elements in a. If there are no two elements in a that can be multiplied to produce another element contained in a, return -1.</p>
</blockquote>
<p>I am trying to get this to run as fast as possible. I assume there is some math algorithm or formula to do this that I am unaware of. This is the way I know how to find this answer. However, I assume this would take a long time if the length of the array was huge. Is there a faster way to do this? I have provided the test.</p>
<pre><code>using System;
using System.Linq;
namespace Exercise
{
public static class Program
{
public static int maxPairProduct(int[] a)
{
int x = -1;
for (int i = 0; i < a.Length; ++i)
{
for (int j = i + 1; j < a.Length; ++j)
{
int temp = a[i] * a[j];
if (a.Contains(temp) && temp > x)
{
x = temp;
}
}
}
return x;
}
}
}
</code></pre>
<pre><code>using NUnit.Framework;
namespace Exercise
{
public class SuccessTests
{
[Test]
public static void TestOne() => Assert.That(Program.maxPairProduct(new int[] { 10, 3, 5, 30, 35 }), Is.EqualTo(30));
public static void TestTwo() => Assert.That(Program.maxPairProduct(new int[] { 2, 5, 7, 8 }), Is.EqualTo(-1));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If you sort you array, and after that your <code>temp</code> is greater than max value from that array (last item), then you can break your loops earlier and save some computation. Here is an example:</p>\n\n<pre><code>using System;\nusing System.Linq;\n\nnamespace Exercise\n{\n public static class TestClass\n {\n public static int NewMaxPairProduct(int[] a)\n {\n Array.Sort(a);\n\n int x = -1;\n int maxItemInArray = a[a.Length - 1];\n\n for (int i = 0; i < a.Length; ++i)\n {\n for (int j = i + 1; j < a.Length; ++j)\n {\n int temp = a[i] * a[j];\n\n if (a.Contains(temp) && temp > x)\n x = temp;\n\n if (temp >= maxItemInArray)\n {\n if (j == i + 1) // break both loops - first iteration is greater then max item\n return x;\n\n break; // break only inner loop - we have to verify other options\n }\n }\n }\n\n return x;\n }\n\n public static int OldMaxPairProduct(int[] a)\n {\n int x = -1;\n\n for (int i = 0; i < a.Length; ++i)\n {\n for (int j = i + 1; j < a.Length; ++j)\n {\n int temp = a[i] * a[j];\n\n if (a.Contains(temp) && temp > x)\n {\n x = temp;\n }\n }\n }\n return x;\n }\n }\n}\n</code></pre>\n\n<p>Benchmark .net Performance test:</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Running;\n\nnamespace Exercise\n{\n public class Benchmark\n {\n [Params(10, 100, 1000)]\n public int N { get; set; }\n\n private int[] data;\n\n [GlobalSetup]\n public void GlobalSetup()\n {\n Random random = new Random();\n data = Enumerable.Repeat(0, N).Select(i => random.Next(1000)).ToArray();\n }\n\n [Benchmark]\n public int NewTest() => TestClass.NewMaxPairProduct(data);\n\n [Benchmark]\n public int OldTest() => TestClass.OldMaxPairProduct(data);\n }\n\n public static class Program\n {\n static void Main(string[] args)\n {\n BenchmarkRunner.Run<Benchmark>();\n }\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>| Method | N | Mean | Error | StdDev |\n|-------- |----- |-----------------:|--------------:|--------------:|\n| NewTest | 10 | 126.3 ns | 2.53 ns | 2.91 ns |\n| OldTest | 10 | 483.8 ns | 6.92 ns | 6.13 ns |\n| NewTest | 100 | 1,519.0 ns | 8.21 ns | 7.68 ns |\n| OldTest | 100 | 125,406.8 ns | 1,420.11 ns | 1,258.89 ns |\n| NewTest | 1000 | 293,878.8 ns | 250.04 ns | 195.22 ns |\n| OldTest | 1000 | 137,166,762.5 ns | 713,905.95 ns | 632,859.03 ns |\n</code></pre>\n\n<p>So with the bigger array you have bigger performance gain. Of course this was tested on random arrays so the results may vary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:36:32.673",
"Id": "473312",
"Score": "0",
"body": "Total time: 0.7897 Seconds vs Total time: 0.7846 Seconds on my code from Nunit. I'm looking for something that can if possible half this time. Thank you though for your suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:38:19.760",
"Id": "473314",
"Score": "0",
"body": "Basically the only way I see improvement done is to cut down the complexity itself as in removing the nested loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:42:19.467",
"Id": "473318",
"Score": "0",
"body": "99% of this 0.7897 seconds are spent in unit test adapter, not in the actual method, but I accepted the challenge. I updated my answer with benchmark .net performance tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T04:41:27.950",
"Id": "473343",
"Score": "0",
"body": "Although faster, still not fast enough to beat these constraints. [execution time limit] 3 seconds (cs)\n\n[input] array.integer a\n\nGuaranteed constraints:\n1 ≤ a.length ≤ 105,\n1 ≤ a[i] ≤ 104.\n\nIt will fail the same last 3 test out of 107 test in that time window like my original code. I don't have the test because they mark them hidden or else I would of included them. What I can tell you is that it is failing for same reason as mine, an that is due to complexity as in notation."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:11:52.303",
"Id": "241203",
"ParentId": "241200",
"Score": "3"
}
},
{
"body": "<h1>Sort it</h1>\n<p>As @Peska suggested, sort the array first. But sort it descendand, or simply iterate in reverse order.</p>\n<h1>Overflow</h1>\n<p>The multiplication of integers can overflow. It would be wiser to approach the iterations from product, divide by one element and check if the division equals second element, but only if product modulo first element is zero.</p>\n<h1><code>Contains()</code> checks too much</h1>\n<p>First of all.</p>\n<pre><code>a.Contains(temp) && temp > x\n</code></pre>\n<p>should be written as</p>\n<pre><code>temp > x && a.Contains(temp)\n</code></pre>\n<p>The Contains call is O(n), we want to avoid this as much as possible, as it is turning the entire algorithm to <code>O(n^3)</code>. In sorted input, we can make some restrictions and which elements we search through. We can actually deploy a binary search, introducing another loop instead of call to <code>Contains</code>, but this loop will be <code>O(log(n))</code>. In the code I have a naive variant that is commented out and is still O(n), but still checks much less then full <code>Contains</code> scan.</p>\n<pre><code>// we will use this to skip duplicate elements in forward iterations\nprivate static int NextDistinctElementIndex(int[] input, int i)\n{\n int value = input[i];\n do\n {\n ++i;\n } while (i < input.Length && input[i] == value);\n return i;\n}\n\npublic static int SlepicMaxPairProduct(int[] input)\n{\n if (input.Length < 2)\n {\n // there's never product of two, if there are no two\n return -1;\n }\n\n Array.Sort(input);\n\n if (input[0] < 0)\n {\n throw new ArgumentException("Input cannot contain negative numbers.");\n }\n\n int result = -1;\n int imin = 0;\n\n if (input[0] == 0)\n {\n // if first element after sort is zero, the result will be at least zero\n result = 0;\n // and we will never have to search for zeroes\n imin = NextDistinctElementIndex(input, 0);\n }\n\n if (imin < input.Length - 1 && input[imin] == 1)\n {\n // if there is "1" in the input, the greatest element of input is the result\n // except if there is just one "1" and zero(es)\n return input[input.Length - 1];\n }\n\n // start examining the sorted input from greatest element\n // and assume the values to potentialy be the product we are looking for\n for (int pi = input.Length - 1; pi > imin; --pi)\n {\n int product = input[pi];\n\n // exclusive index of the greatest element that is reasonable to search for a "b" value\n int bmax = pi;\n\n // assume values before bmax are some "a", then look for "b"\n for (int ai = imin; ai < bmax; ++ai)\n {\n int a = input[ai];\n\n // if product is not divisible by a, we won't find any b\n if (product % a != 0)\n {\n continue;\n }\n\n int expectedB = product / a;\n\n /*\n // search for a "b" value in the reasonable range (bmin, ai)\n for (int bi = bmin; bi < ai; ++bi)\n {\n int b = input[bi];\n\n if (b == expectedB)\n {\n return product;\n }\n\n if (b > expectedB)\n {\n bmin = bi;\n break;\n }\n }*/\n\n // let's turn the naive "for bi" loop into log(n)\n\n // searchfor a "b" value using bisection in the reasonable range (bmin, bmax)\n // and export new values of bmax to the outer loop\n // because if we will search for a greater "a" then the current one\n // we are inevitably only going to find a smaller "b"\n int bmin = ai;\n while (bmax > bmin)\n {\n // int bi = (bmin + bmax) / 2;\n // variant with no overflow of index (for very large arrays):\n int bi = (bmin / 2 + bmax / 2) + ((bmin % 2) & (bmax % 2));\n\n int b = input[bi];\n\n if (b == expectedB)\n {\n return product;\n }\n\n if (b < expectedB)\n {\n bmin = bi + 1;\n }\n else\n {\n bmax = bi;\n }\n }\n }\n }\n\n return result;\n}\n</code></pre>\n<p>In conclusion, we have limited the searched space to a great degree and turned the algorithm from <code>O(n^3)</code> to <code>O((n^2) * log(n))</code>.</p>\n<pre><code>| Method | N | Mean | Error | StdDev |\n|------------- |----- |-------------------:|-----------------:|-----------------:|\n| PeskaTest | 10 | 215.3 ns | 3.61 ns | 3.38 ns |\n| MilliornTest | 10 | 4,868.0 ns | 88.16 ns | 134.64 ns |\n| SlepicTest | 10 | 264.6 ns | 3.57 ns | 3.34 ns |\n| PeskaTest | 100 | 56,954.4 ns | 1,131.18 ns | 1,548.37 ns |\n| MilliornTest | 100 | 4,352,830.7 ns | 76,663.28 ns | 94,149.39 ns |\n| SlepicTest | 100 | 16,452.8 ns | 86.02 ns | 76.25 ns |\n| PeskaTest | 1000 | 27,821,365.8 ns | 349,019.38 ns | 309,396.59 ns |\n| MilliornTest | 1000 | 4,193,838,300.0 ns | 43,784,319.26 ns | 40,955,879.40 ns |\n| SlepicTest | 1000 | 50,757.2 ns | 244.00 ns | 203.76 ns |\n</code></pre>\n<p>PS: Based on return value -1 meaning "not found" I assume the input cannot contain negative numbers, otherwise it cannot work like this (where I assume that if zero is present it is on index 0, ...)</p>\n<p>PS2: It is not very nice that the implementation sorts the array for the caller. It may be wise to provide the method expecting the input already sorted and provide a wrapper that creates a sorted copy and passes it to this method that expects sorted input. It will be more expensive because of copying and allocating new array, but for big inputs, this should be neglegable (because it is O(n) which is neglegable compared to O(n^2*log(n)) while making it error safe, immutable for the caller, thus more transparent for him, and offering the method that expects sorted input makes it more flexible/efficient for callers that already sorted their input.</p>\n<p>EDIT:\nNew bench results including @potato's solution (2nd snippet). Mine still seems faster although according to potato's big-O, his should be faster. Not sure what's going on yet...</p>\n<pre><code>| Method | N | Mean | Error | StdDev |\n|------------- |----- |-------------------:|-----------------:|-----------------:|\n| PeskaTest | 10 | 209.6 ns | 1.25 ns | 1.11 ns |\n| MilliornTest | 10 | 5,168.6 ns | 58.73 ns | 54.93 ns |\n| SlepicTest | 10 | 256.8 ns | 1.12 ns | 0.99 ns |\n| PotatoTest | 10 | 539.0 ns | 1.25 ns | 1.04 ns |\n| PeskaTest | 100 | 3,567.1 ns | 45.20 ns | 37.75 ns |\n| MilliornTest | 100 | 4,806,710.5 ns | 13,092.42 ns | 10,932.77 ns |\n| SlepicTest | 100 | 5,039.0 ns | 58.10 ns | 48.52 ns |\n| PotatoTest | 100 | 6,141.9 ns | 111.06 ns | 86.71 ns |\n| PeskaTest | 1000 | 26,678,273.6 ns | 502,308.33 ns | 419,450.21 ns |\n| MilliornTest | 1000 | 4,798,816,196.0 ns | 29,527,973.10 ns | 39,418,995.96 ns |\n| SlepicTest | 1000 | 44,601.9 ns | 407.09 ns | 360.87 ns |\n| PotatoTest | 1000 | 84,168.8 ns | 207.99 ns | 173.69 ns |\n\n| Method | N | Mean | Error | StdDev |\n|----------- |------ |------------:|----------:|----------:|\n| SlepicTest | 1000 | 49.88 us | 0.123 us | 0.103 us |\n| PotatoTest | 1000 | 86.66 us | 1.121 us | 0.994 us |\n| SlepicTest | 2000 | 119.67 us | 0.628 us | 0.557 us |\n| PotatoTest | 2000 | 193.52 us | 0.530 us | 0.470 us |\n| SlepicTest | 4000 | 279.29 us | 4.180 us | 3.705 us |\n| PotatoTest | 4000 | 409.23 us | 1.443 us | 1.127 us |\n| SlepicTest | 8000 | 563.60 us | 1.117 us | 0.990 us |\n| PotatoTest | 8000 | 859.76 us | 4.800 us | 4.490 us |\n| SlepicTest | 16000 | 1,201.41 us | 12.686 us | 11.867 us |\n| PotatoTest | 16000 | 1,659.58 us | 8.473 us | 7.511 us |\n\n| Method | N | Mean | Error | StdDev |\n|----------- |------- |----------:|----------:|----------:|\n| SlepicTest | 100000 | 8.657 ms | 0.0556 ms | 0.0464 ms |\n| PotatoTest | 100000 | 10.628 ms | 0.0301 ms | 0.0266 ms |\n\n| Method | N | Mean | Error | StdDev |\n|----------- |-------- |---------:|--------:|--------:|\n| SlepicTest | 1000000 | 101.7 ms | 0.41 ms | 0.36 ms |\n| PotatoTest | 1000000 | 119.1 ms | 0.30 ms | 0.25 ms |\n\n| Method | N | Mean | Error | StdDev |\n|----------- |--------- |--------:|---------:|---------:|\n| SlepicTest | 10000000 | 1.266 s | 0.0048 s | 0.0043 s |\n| PotatoTest | 10000000 | 1.446 s | 0.0194 s | 0.0172 s |\n</code></pre>\n<p>Those were with random numbers r: 0 <= r < 1000.\nNow 0 <= r < N:</p>\n<pre><code>| Method | N | Mean | Error | StdDev |\n|----------- |--------- |---------------:|------------:|------------:|\n| SlepicTest | 10000 | 726.4 us | 2.90 us | 2.57 us |\n| PotatoTest | 10000 | 1,055.5 us | 4.55 us | 3.80 us |\n| SlepicTest | 100000 | 9,056.1 us | 33.79 us | 31.61 us |\n| PotatoTest | 100000 | 11,992.9 us | 58.15 us | 48.55 us |\n| SlepicTest | 1000000 | 107,084.9 us | 473.48 us | 419.73 us |\n| PotatoTest | 1000000 | 139,090.3 us | 376.83 us | 352.48 us |\n| SlepicTest | 10000000 | 1,306,931.0 us | 2,585.99 us | 2,018.97 us |\n| PotatoTest | 10000000 | 1,648,109.2 us | 7,627.77 us | 7,135.02 us |\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T14:02:30.263",
"Id": "473379",
"Score": "0",
"body": "@RickDavin -3*5=-15 is not even, nor positive. My assumption is based on the fact that -1 is product of 1 and -1 and so returning -1 would then be ambiguous (did we not found a result, or did we found a result -1?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T16:47:58.193",
"Id": "473393",
"Score": "0",
"body": "-1 is what we return if there are no two elements in a that can be multiplied to produce another element. That is why I made a default value of -1 and update it if we find two elements to the produce of those two elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T16:51:04.270",
"Id": "473394",
"Score": "0",
"body": "This also fails this test `public static void TestOne() => Assert.That(Program.maxPairProduct(new int[] { 10, 3, 5, 30, 35 }), Is.EqualTo(30));` Error Message:\n Expected: 30\n But was: -1\n\n Stack Trace:\n at Exercise.SuccessTests.TestOne() in C:\\Users\\scott\\Desktop\\maxPairProduct\\SuccessTests.cs:line 8\n\n\nTest Run Failed.\nTotal tests: 1\n Failed: 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T16:58:22.423",
"Id": "473395",
"Score": "0",
"body": "@Milliorn sry, there was an edge case bug.. fixed now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T11:53:19.787",
"Id": "489238",
"Score": "0",
"body": "FYI this post was auto-flagged for its edit history; consider making fewer, more substantial edits in the future (every edit bumps a post back onto the front page, which *can* be abused). Cheers! (and great post, +1!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T16:50:00.560",
"Id": "489279",
"Score": "0",
"body": "I found a bug in both of our functions. I explained and corrected mine in my answer. Your bug is in the binary search not making sure that the matching `expectedB` doesn't have the same index as `expectedA`. After my bug fix, our functions agree on all the results except those where yours finds a square number whose root appears only once in the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T18:49:19.073",
"Id": "489288",
"Score": "0",
"body": "In [another comment](https://codereview.stackexchange.com/questions/241200/find-greatest-number-in-array-that-is-a-product-of-some-two-elements-in-the-same/241359#comment473343_241203), the OP stated the guaranteed constraints as \"1 ≤ a.length ≤ 105, 1 ≤ a[i] ≤ 104\" (certainly lazy copying and they really are 10^5 and 10^4). Might want to use that in a benchmark as well (if you're still adding some)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T07:05:36.270",
"Id": "241226",
"ParentId": "241200",
"Score": "6"
}
},
{
"body": "<p>You're doing micro-optimization, which means, you don't have any major optimization on your hands more than you've done already. All other optimizations would only impact <code>big-data</code>, but for average data, it won't be noticeable. Or that's what I think. </p>\n\n<p>But, I agree, sorting the array would be much beneficial to your code as dealing with unsorted array would return unexpected results along with producing a disaster code experience. So, sort the array first, ascending or descending, all depends on your data-process. </p>\n\n<p>Then, instead of looping and multiplying, you can try to decrease the amount of looping rounds by taking the max product then based on that value, do your looping while keeping in mind : </p>\n\n<ul>\n<li>the value should be less than the max </li>\n<li>the value should not be negative. </li>\n<li>avoid converting between collections types (like <code>IEnumerable</code> to <code>Array</code>).</li>\n<li>break the loop if the multiplier and multiplicand has been found.</li>\n</ul>\n\n<p>This would cut your looping timing.</p>\n\n<p>I'll demonstrate my idea. </p>\n\n<p>your current code have 2 for loops, and also used <code>Contains</code> which has an also a loop. </p>\n\n<p>Here is the <code>Contains</code> has something like this code : </p>\n\n<pre><code>public static bool Contains(int[] array, int number) {\n\n if(array == null) return false;\n\n for(var x = 0; x < array.Length; x++)\n {\n if (array[x].Equals(number)) { return true; } \n }\n\n return false;\n}\n</code></pre>\n\n<p>This would but your total iterations around 65 iterations (with the provided sample). and that's with the <code>Contains</code> iterations. This is only on 5 elements, which means each element would iterate about 13 times. This is too much iterations. </p>\n\n<p>to reduce that, we can take the highest values first, then iterate over the array based on these values. In your case, you can take the highest 3 values, and loop over them. </p>\n\n<p>So, re-thinking over, the logic would be something like : </p>\n\n<ol>\n<li>take the highest 3 values and store them in descending order. </li>\n<li>for each max value, iterate over the array to check wither there is a multiplier and multiplicand for it or not. </li>\n<li>if there is, return this max. (which would end this process). </li>\n</ol>\n\n<p>with that in mind, we can start with something like this : </p>\n\n<pre><code>public static int maxPairProduct(int[] a)\n{\n foreach (var number in a.OrderByDescending(x => x).Skip(0).Take(3))\n {\n for (var j = 0; j < a.Length; j++)\n {\n // skip if the numbers are equal or bigger than the max number\n if (j+1 >= a.Length || a[j] >= number || a[j + 1] >= number) { continue; }\n\n if (a[j] * a[j + 1] == number) { return number; }\n }\n\n }\n\n return -1;\n}\n</code></pre>\n\n<p>With this, we reduced the iterations to the minimum.</p>\n\n<p><strong>UPDATE :</strong> </p>\n\n<p>if you want to extend the <code>Take</code> so it will take 3 max integers and do the tests until it finds the product multiplier and multiplicand you can do this : </p>\n\n<pre><code>public static int GetMaxPair(int[] a)\n{\n var skip = 0; \n var take = 3; \n var descOrder = a.OrderByDescending(x => x); \n\n do \n {\n foreach(var number in descOrder.Skip(skip).Take(take))\n {\n for (var j = 0; j < a.Length; j++)\n {\n // skip if the numbers are equal or bigger than the max number\n if (j+1 >= a.Length || a[j] >= number || a[j + 1] >= number) { continue; }\n\n if (a[j] * a[j + 1] == number) { return number; }\n } \n }\n\n skip += take;\n\n if(skip > a.Length) { return -1; }\n }\n while(true);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T19:09:31.550",
"Id": "473407",
"Score": "0",
"body": "` foreach (var number in a.a.OrderByDescending(x => x).Skip(0).Take(3))` Typo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T19:21:35.613",
"Id": "473410",
"Score": "0",
"body": "@Milliorn yes, it was a typo, fixed it ;)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T03:22:07.960",
"Id": "473446",
"Score": "0",
"body": "What makes you think that scanning only 3 highest numbers is enough? What If 3 highest numbers are primes? This is a rabbish answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T10:54:37.287",
"Id": "473478",
"Score": "0",
"body": "@slepic if all are primes, simply returns `-1` :)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T11:52:50.780",
"Id": "473488",
"Score": "0",
"body": "@iSR5 {2,3,6,17,19,23}"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T11:56:33.107",
"Id": "473489",
"Score": "0",
"body": "Btw, if `j < a.Length`, how often will `j + 1 > a.Length` yield true? ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T16:16:29.810",
"Id": "473514",
"Score": "0",
"body": "@slepic good catch on `j + 1 > a.Length` I have fixed it. although, i was just putting an example to give a better view on my idea, so the take(3) can be reused. For better or worse, I have post an update with the extended code."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:29:42.087",
"Id": "241262",
"ParentId": "241200",
"Score": "1"
}
},
{
"body": "<p>There is not much to add to the other answers. Your code is well written and easy to understand, but as a brute force algorithm it has its limitation in real world use - for larger data sets at least.</p>\n\n<hr>\n\n<p>The name should be <code>MaxPairProduct</code> (PascalCase) instead of <code>maxPairProduct</code>.</p>\n\n<hr>\n\n<p>There is maybe an issue (that applies to the other answers as well):</p>\n\n<p>For the dataset:</p>\n\n<pre><code>int[] data = { 1, 2, 3 }\n</code></pre>\n\n<p>it returns <code>3</code>, but it should return <code>-1</code>, if the multiplier, multiplicand and product must be distinct entries in the data set? The dataset <code>{ 1, 2, 3, 3 }</code> should return <code>3</code>.</p>\n\n<p>Similar</p>\n\n<pre><code>int[] data = { 1, 2, 2, 3, 4, 5 };\n</code></pre>\n\n<p>should return <code>4</code> but returns <code>5</code>.</p>\n\n<p>The above is somehow inconsistent with:</p>\n\n<pre><code>int[] data = { 2, 3, 4 };\n</code></pre>\n\n<p>that correctly results in <code>-1</code>.</p>\n\n<hr>\n\n<p>Below is an implementation that handles the above problem, and also prevent a possible overflow when multiplying:</p>\n\n<pre><code>static int MaxPairProduct(int[] a)\n{\n Array.Sort(a);\n\n int product = -1;\n int multiplier = -1;\n int multiplicand;\n\n for (int i = a.Length - 1; i > 1; --i)\n {\n if (a[i] == product) continue;\n product = a[i];\n\n for (int j = 0; j < i; ++j)\n {\n if (a[j] == multiplier) continue;\n multiplier = a[j];\n\n if (multiplier == 0) continue;\n multiplicand = product / multiplier;\n if (product % multiplier == 0 && Array.IndexOf(a, multiplicand, j + 1, i - j - 1) > j)\n {\n return product;\n }\n if (multiplicand < multiplier)\n break;\n }\n }\n\n return -1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T16:22:10.680",
"Id": "241303",
"ParentId": "241200",
"Score": "2"
}
},
{
"body": "<h1><code>O(n√n)</code> solution (and a faster one below)</h1>\n<hr>\n<p>First, a quick note about your implementation: it doesn't ensure that the returned product is the maximal product, it just returns the last product it finds. Your tests are too simple to detect this bug.</p>\n<hr>\n<p>Step 1: reduce the time complexity from <code>O(n^3)</code> to <code>O(n^2)</code> (at the cost of increasing memory complexity to <code>O(n)</code>) by creating a hash table with all the numbers from the array, so your <code>contains</code> checks can be <code>O(1)</code> instead of <code>O(n)</code>.</p>\n<p>Sort the array and start checking from the biggest number so you can stop as soon as you find a product.</p>\n<pre><code>public static int MaxPairProduct(int[] input)\n{\n Array.Sort(input);\n if(input[input.Length - 1] == 0)\n {\n return input.Length > 1 ? 0 : -1;\n }\n int minIndex = -1;\n while (input[++minIndex] == 0);\n HashSet<int> hashSet = new HashSet<int>(input);\n\n for (int i = input.Length - 1; i > 0; i--)\n {\n int product = input[i];\n for (int j = i - 1; j >= minIndex; j--)\n {\n if (product % input[j] == 0 && hashSet.Contains(product / input[j]))\n {\n return product;\n }\n }\n }\n\n return input[0] == 0 && input.Length > 1 ? 0 : -1;\n}\n</code></pre>\n<p>Step 2: decrease the time complexity to <code>O(n√n)</code> on average (there are <code>O(n^2)</code> edge cases) by making the inner loop start from index 0 and continue only until it reaches the square root of <code>product</code>, because by then you will have checked all the multiplications that could possibly produce <code>product</code>. Any number bigger than the root needs to be multiplied by a number smaller than the root, and they were all seen already.</p>\n<pre><code>public static int MaxPairProduct(int[] input)\n{\n Array.Sort(input);\n if(input[input.Length - 1] == 0)\n {\n return input.Length > 1 ? 0 : -1;\n }\n int minIndex = -1;\n while (input[++minIndex] == 0);\n HashSet<int> hashSet = new HashSet<int>(input);\n\n for (int i = input.Length - 1; i > 0; i--)\n {\n int product = input[i];\n int root = (int)Math.Sqrt(product);\n int j = minIndex;\n for (; j < input.Length && input[j] < root; j++)\n {\n if (product % input[j] == 0 && hashSet.Contains(product / input[j]))\n {\n return product;\n }\n }\n if(input[j] == root && input[j+1] == root && product % root == 0)\n {\n return product;\n }\n }\n\n return input[0] == 0 && input.Length > 1 ? 0 : -1;\n}\n</code></pre>\n<p>If you want <code>O(1)</code> memory complexity you can use binary search instead of <code>HashSet</code>, giving you time complexity of <code>O(n√n log n)</code>.</p>\n<h2>Update: bug fix</h2>\n<p>The code above doesn't account for rounding errors, for example <code>(int)Math.Sqrt(6) == 2</code> and <code>6 % 2 == 0</code> but <code>2 * 2 != 6</code>.</p>\n<pre><code>public static int MaxPairProduct(int[] input)\n{\n Array.Sort(input);\n\n if (input[input.Length - 1] == 0)\n {\n return input.Length > 1 ? 0 : -1;\n }\n\n int minIndex = -1;\n while (input[++minIndex] == 0);\n HashSet<int> hashSet = new HashSet<int>(input);\n\n for (int i = input.Length - 1; i > minIndex; i--)\n {\n int product = input[i];\n if(product == 1)\n {\n return input[i-1];\n }\n int root = (int)Math.Sqrt(product);\n // remember if root was rounded, to avoid errors: (int)√6 == 2 but 2*2 != 6\n bool rootIsPrecise = root * root == product;\n int j = minIndex;\n for (; input[j] <= root; j++)\n {\n if (product % input[j] == 0)\n {\n if(input[j] == root && rootIsPrecise)\n {\n if(j + 1 < input.Length && input[j+1] == root)\n {\n return product;\n }\n }\n else if(hashSet.Contains(product / input[j]))\n {\n return product;\n }\n }\n }\n }\n\n return input[0] == 0 && input.Length > 1 ? 0 : -1;\n}\n</code></pre>\n<h2><code>O(n√n log n)</code> solution - but faster than the above</h2>\n<p>Apparently using <code>HashSet</code> is incredibly slow (despite the supposed <code>O(1)</code> search), so I replaced it with a binary search.</p>\n<pre><code>public static int MaxPairProduct(int[] input)\n{\n Array.Sort(input);\n if (input[input.Length - 1] == 0)\n {\n return input.Length > 1 ? 0 : -1;\n }\n\n int minIndex = -1;\n while (input[++minIndex] == 0);\n for (int i = input.Length - 1; i > minIndex; i--)\n {\n int product = input[i];\n if(product == 1)\n {\n return input[i-1];\n }\n int root = (int)Math.Sqrt(product);\n bool rootIsPrecise = root * root == product;\n int j = minIndex;\n for (; input[j] <= root; j++)\n {\n if (product % input[j] == 0)\n {\n if(input[j] == root && rootIsPrecise)\n {\n if(j + 1 < input.Length && input[j+1] == root)\n {\n return product;\n }\n }\n else if(BinarySearch(input, product / input[j]))\n {\n return product;\n }\n }\n }\n }\n\n return input[0] == 0 && input.Length > 1 ? 0 : -1;\n}\n\npublic static bool BinarySearch(int[] arr, int key)\n{\n int min = 0, max = arr.Length - 1, mid;\n while(min < max)\n {\n mid = max + (min - max) / 2;\n if(arr[mid] > key)\n {\n max = mid - 1;\n }\n else\n {\n min = mid;\n }\n }\n return arr[max] == key;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T16:32:15.730",
"Id": "473665",
"Score": "1",
"body": "You might also want to point out that Its a tradeoff for increased memory complexity from O(1) to O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T16:50:53.267",
"Id": "473668",
"Score": "1",
"body": "@slepic you're right, I added your note to the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T22:53:16.987",
"Id": "473706",
"Score": "1",
"body": "@slepic hey, I guess you wouldn't want to miss it so I'm tagging you, I figured out an even better solution :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T03:25:15.063",
"Id": "473719",
"Score": "0",
"body": "Hehe nice, I actualy had a thought that square root might help later on, but didnt have time to think about it any deeper. Well Done. And you're right, im glad you mention me :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T04:14:09.060",
"Id": "473720",
"Score": "0",
"body": "OH too early in the morning. Unfortunately, I have realized that it is not O(n * sqrt(n)), it is still O(n * n). You can say it Is O(n * min(n,m)) where n Is length of input and m is sqrt of maximum element in input and min() Is the function that returns the smaller argument. There are many inputs that are not optimized by this, but there sure are inputs that are. I am reluctant to say which is more common, tho..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:41:48.050",
"Id": "473816",
"Score": "0",
"body": "Attempt to make the function run slow: `[2, 3, 4, ..., 101, 100000, 100001, 100002, ...]` this input is 2 groups of numbers on a very different scale, placing the \"root border\" at the center to create a worst case. Another O(n^2) case is an array where each element is smaller than the root of the next element, but you can add just a few such numbers before you reach int.max_value. I imagine most cases will contain numbers that are more evenly distributed, placing the \"root border\" close to the lower edge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:50:21.720",
"Id": "473817",
"Score": "0",
"body": "Also, mathematically speaking there are way more variations of evenly distributed numbers than the more \"extreme\" cases, so I think it's fair enough to call it: O(n√n) on average, worst case O(n^2) and best case O(n log n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T05:05:18.777",
"Id": "489196",
"Score": "0",
"body": "Hey, I have added your second snippet to the benchmark (see edit on my answer) but it seems to be slower then mine O(n^2 * log(n)) solution. Not sure what's going on..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:46:29.323",
"Id": "489217",
"Score": "0",
"body": "@slepic Maybe it has to do with the fact that when you have N random numbers of value `0 ≤ r < N`, the result of the function call is almost always `N - 1`, so both functions almost always perform at their (almost) best case speed, which for my function is slower because of overhead (mainly the creation of the `HashSet`). Try testing it for N much bigger than the array length to reduce the probability of the best case, but not too big to avoid the result always being `-1` due to small probability of getting numbers under `√N`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T12:14:00.893",
"Id": "489242",
"Score": "0",
"body": "I just tested it with 3 versions of the data: 1) Same as you did. 2) Bigger N, resulting in diverse values returned by the function. 3) Even bigger N, resulting in `-1` being returned pretty much every time. In the 1st case the results were similar to yours, but in the other 2 cases my function outperformed yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T18:00:41.057",
"Id": "489283",
"Score": "0",
"body": "@slepic I'd love to see your benchmarks with my `O(n√n log n)` function! (see last snippet in my answer) Now that I got rid of the `HashSet` overhead you should be able to see the difference in complexity even with `0 ≤ r < N` and array of length `N` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T18:52:46.513",
"Id": "489289",
"Score": "0",
"body": "FYI this post was auto-flagged for its edit history - please note every edit bumps the question back onto the front page, which *can* be abused (hence the auto-flag): please try to make fewer, more substantial edits going forward. Cheers!"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T10:11:22.803",
"Id": "241359",
"ParentId": "241200",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:28:47.550",
"Id": "241200",
"Score": "6",
"Tags": [
"c#",
"performance",
"beginner",
"array",
"linq"
],
"Title": "Find greatest number in array that is a product of some two elements in the same array"
}
|
241200
|
<p>I am beginner in programming and I did the task "manually" by logically creating the sum of costs for each route. But I wanted to ask if it is possible to automatic (dynamic) counting of costs for a given route? </p>
<pre class="lang-py prettyprint-override"><code>original_route = [0, 4, 2, 1, 3, 0]
route_2 = [0, 3, 5, 2, 4, 6, 0]
route_3 = [0, 7, 6, 4, 1, 5, 0]
distance_matrix = [[0, 6, 12, 11, 6, 13, 8, 20, 7],
[6, 0, 7, 9, 7, 9, 12, 15, 13],
[12, 7, 0, 13, 10, 11, 16, 13, 19],
[11, 9, 13, 0, 15, 4, 19, 12, 14],
[6, 7, 10, 15, 0, 16, 6, 21, 12],
[13, 9, 11, 4, 16, 0, 21, 8, 18],
[8, 12, 16, 19, 6, 21, 0, 27, 10],
[20, 15, 13, 12, 21, 8, 27, 0, 26],
[7, 13, 19, 14, 12, 18, 10, 26, 0]]
cost_route = distance_matrix[0][4] + distance_matrix[4][2] + distance_matrix[2][1] + distance_matrix[1][3] + distance_matrix[3][0]
print("The cost of the original route: " + str(cost_route))
cost_route2 = distance_matrix[0][3] + distance_matrix[3][5] + distance_matrix[5][2] + distance_matrix[2][4] + distance_matrix[4][6] + distance_matrix[6][0]
print("The cost of route 2: " + str(cost_route2))
cost_route3 = distance_matrix[0][7] + distance_matrix[7][6] + distance_matrix[6][4] + distance_matrix[4][1] + distance_matrix[1][5] + distance_matrix[5][0]
print("The cost of route 3: " + str(cost_route3))
value = ['1, ' + str(cost_route), '2, ' + str(cost_route2), '3, ' + str(cost_route3)]
print('Best value has route ' + str(min(value)) + ' is the value.')
print('Worst value has route ' + str(max(value)) + ' is the value.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T05:36:39.420",
"Id": "473349",
"Score": "0",
"body": "(Didn't know how far I should go trying to improve the English in this post.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T10:58:15.917",
"Id": "473364",
"Score": "0",
"body": "You're basically asking for a major rewrite of the code. That's not something we do here, please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T15:23:40.163",
"Id": "473390",
"Score": "0",
"body": "@greybeard not everyone have to speak English...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T14:38:41.287",
"Id": "473500",
"Score": "0",
"body": "(Not the least reason I don't feel called to iron out everything I feel wrong in a post I edit is English (most obviously) not being my first language. I just wanted to give a reason why I stop halfways (e.g., not supplying a pronoun in the first four words). (At least as long as edits are reviewed,) The guideline is *notably* less mistakable/more readable.)"
}
] |
[
{
"body": "<p>The general trick to \"automating\" code where you have multiple values that all work the same way is to:</p>\n\n<ol>\n<li>Put them in a collection, like a list or a dict.</li>\n<li>Take whatever you're doing to all those values and define it as a function.</li>\n</ol>\n\n<p>In the case of this code, rather than having three variables for your routes, you should put them in a collection you can iterate over, and rather than having three copy and pasted expressions that translate the routes into costs, write a function that takes a route and calculates the cost. This greatly reduces the risk that you'll end up with a bug because you copied+pasted something incorrectly, or forgot to update one piece of data in two different places (e.g. the values of the routes, which are currently duplicated in a sort of non-obvious way).</p>\n\n<p>I don't actually understand what your code represents, but the pattern is easy enough to spot that I was able to write a script that at least produces roughly the same output while avoiding the copy+paste pitfalls.</p>\n\n<pre><code>from typing import List\n\nroutes = {\n '1': [0, 4, 2, 1, 3, 0],\n '2': [0, 3, 5, 2, 4, 6, 0],\n '3': [0, 7, 6, 4, 1, 5, 0],\n}\n\ndistance_matrix = [\n [0, 6, 12, 11, 6, 13, 8, 20, 7],\n [6, 0, 7, 9, 7, 9, 12, 15, 13],\n [12, 7, 0, 13, 10, 11, 16, 13, 19],\n [11, 9, 13, 0, 15, 4, 19, 12, 14],\n [6, 7, 10, 15, 0, 16, 6, 21, 12],\n [13, 9, 11, 4, 16, 0, 21, 8, 18],\n [8, 12, 16, 19, 6, 21, 0, 27, 10],\n [20, 15, 13, 12, 21, 8, 27, 0, 26],\n [7, 13, 19, 14, 12, 18, 10, 26, 0]\n]\n\n\ndef cost_for_route(route: List[int], distance_matrix: List[List[int]]) -> int:\n route_shifted = route[1:] + route[0:0]\n return sum(distance_matrix[i][j] for i, j in zip(route, route_shifted))\n\n\nroute_costs = {\n name: cost_for_route(route, distance_matrix)\n for name, route in routes.items()\n}\n\nfor name, cost in route_costs.items():\n print(f\"The cost of route {name}: {cost}\")\n\nbest = min(route_costs.keys(), key=route_costs.get)\nworst = max(route_costs.keys(), key=route_costs.get)\nprint(f\"Best value has route {best}, {route_costs[best]} is the value.\")\nprint(f\"Worst value has route {worst}, {route_costs[worst]} is the value.\")\n</code></pre>\n\n<p>Now that <code>routes</code> is simply a dict that the rest of the code iterates through, you can add more routes just by adding them to that dict; you don't need to manually generate the code to calculate the cost of the new route, or update the code that finds the best/worst routes or the code that prints them all out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:30:12.650",
"Id": "473311",
"Score": "1",
"body": "Thank you very much for such a good explanation and help! I really appreciate, this is my first steps in programming in Uni and because of the lack of lectures we have to learn how to create programs ourselves."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:22:28.493",
"Id": "241205",
"ParentId": "241201",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:30:46.447",
"Id": "241201",
"Score": "-1",
"Tags": [
"python",
"beginner"
],
"Title": "Automatization of the cost calculation process"
}
|
241201
|
<p>I am trying to solve the <a href="https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays" rel="nofollow noreferrer">following Hackerrank Problem</a>.</p>
<p><a href="https://i.stack.imgur.com/Poou4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Poou4.png" alt="pixel raster of Hackerrank's problem statement"></a></p>
<p>I have written the code for the problem. However, it runs for some of the test cases while for others it doesn't. It shows the message : "Your code did not execute within the time limits"</p>
<p>I know that bubble sort is not required for the problem. However, I have seen many people doing it using bubble sort.</p>
<p>I want to do the problem by employing bubble sort. Please tell me what changes do I need to make in the code in order to do so. Thanks for helping.</p>
<pre><code>int N = 0 ,I = 0;
int flag = 0;
int n = q.length;
int temp = 0;
int noOfSwaps = 0;
for(int i = 0 ; i < q.length ; i++)
{
N = q[i];
I = i;
if((N-I)>3)
{
flag = 1;
break;
}
}
if(flag == 1)
{
System.out.println("Too chaotic");
}
else if(flag == 0)
{
//System.out.println("Find Exchanges");
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(q[j-1] > q[j]){
//swap elements
temp = q[j-1];
q[j-1] = q[j];
q[j] = temp;
noOfSwaps++;
}
}
}
System.out.println(noOfSwaps);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:28:21.117",
"Id": "473310",
"Score": "2",
"body": "\"it runs for some of the test cases while for others it doesn't\" - Are you getting TLE or WA?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:40:09.857",
"Id": "473317",
"Score": "0",
"body": "Right idea but as mentioned above, it's not clear what you're asking. Does the code work? Either way, the algorithm [here](https://codereview.stackexchange.com/a/220263/171065) might help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T06:23:23.827",
"Id": "473352",
"Score": "0",
"body": "@vnp It displayed the following message for some of the test cases : Your code did not execute within the time limits"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T06:23:46.303",
"Id": "473353",
"Score": "0",
"body": "@ggorlen It displayed the following message for some of the test cases : \" Your code did not execute within the time limits\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T06:46:19.323",
"Id": "473354",
"Score": "1",
"body": "Good. Time Limit Exceeded makes the question on topic (Wrong Answer would disqualify it immediately)."
}
] |
[
{
"body": "<h2>Time limit improvements</h2>\n\n<ul>\n<li>You don't need to implement a full bubble sort (as the maximum distance is 2 bribes!)</li>\n<li>You can skip if a person is in the correct position if you know the processed part is correct.</li>\n<li>You don't need to process the list twice, you only need to check if the person you are checking is within the maximum swap distance.</li>\n</ul>\n\n<p>I commented my algorithm below; it is basically a bubble sort, only with a limit on how far the inner loop goes.</p>\n\n<pre><code>public class Solution {\n\n static final int MAX_SWAPS = 2;\n\n // Complete the minimumBribes function below.\n static void minimumBribes(int[] q) {\n int bribes = 0;\n\n int n=q.length;\n\n //we process from right to left\n for (int i=n-1; i>=0; i--)\n { \n int pos = i+1;\n int s;\n\n //if we are correct, we can proceed LEFT, \n //we know the right tail is correctly sorted\n //so after this step, the tail is 1 longer ans STILL correctly sorted\n if (q[i] == pos) continue;\n\n //try swap our position with previous positions, look MAX_SWAPS left.\n\n //for example: 1 5 2 4 3\n\n //if we are investigating position 5 (currently number 3)\n //we start swapping the items at position 3 and 4 if number 5 is at position 3.\n\n //if number 5 was not at position 3, \n //we try to find it at position 4\n //if number 5 was also not at position 4, we are too chaotic, as you \n //cannot bribe yourself more than MAX_SWAPS to the left.\n //so we are TOO CHAOTIC!\n\n //for example: 1 2 5 4 3\n\n //if number 5 is in position 5, we can skip it\n //(it is not)\n //if number 5 is at position 3\n //we swap the numbers 5 and 4 (at position 3 and 4) and have 1 bribe (bribes++)\n //situation becomes: 1 2 4 5 3\n //if now number 5 is at position 4, we have bribed again (bribes++)\n //situation becomes: 1 2 4 3 5\n\n //now we know 5 is in the correct position, and can scan from position 4\n //situation becomes: 1 2 4 3 [5] // [] mark list that is DONE :)\n //if number 4 is in position 4, we add it\n //(it is not)\n //now if number 4 is in position 2, swap,\n //(it is not) \n //now if number 4 is in position 3, swap\n //it IS, swap them and bribes++\n //1 2 3 [4 5]\n\n //if number 3 is in position 3, we add it\n //1 2 [3 4 5]\n //etc.\n\n for (int m = MAX_SWAPS; m>0; m--)\n {\n int left = i-m;\n if (left>=0 && q[left]==pos)\n {\n s = q[left];\n q[left]= q[left+1];\n q[left+1] = s;\n bribes++;\n }\n else \n {\n if (m == 1) //if we didn't find the correct number at the last left position\n //after MAX swaps left, we are too chaotic \n {\n System.out.println(\"Too chaotic\"); return;\n }\n }\n }\n }\n System.out.println(bribes);\n\n\n }\n\n private static final Scanner scanner = new Scanner(System.in);\n\n public static void main(String[] args) {\n int t = scanner.nextInt();\n scanner.skip(\"(\\r\\n|[\\n\\r\\u2028\\u2029\\u0085])?\");\n\n for (int tItr = 0; tItr < t; tItr++) {\n int n = scanner.nextInt();\n scanner.skip(\"(\\r\\n|[\\n\\r\\u2028\\u2029\\u0085])?\");\n\n int[] q = new int[n];\n\n String[] qItems = scanner.nextLine().split(\" \");\n scanner.skip(\"(\\r\\n|[\\n\\r\\u2028\\u2029\\u0085])?\");\n\n for (int i = 0; i < n; i++) {\n int qItem = Integer.parseInt(qItems[i]);\n q[i] = qItem;\n }\n\n minimumBribes(q);\n }\n\n scanner.close();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T22:16:32.937",
"Id": "241401",
"ParentId": "241206",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:24:36.817",
"Id": "241206",
"Score": "3",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Find the number of swaps that has taken place. New Year Chaos. Hackerrank"
}
|
241206
|
<p>I have some code which is working, but I would be interested if anyone could review it and tell me if there is a more efficient way of achieving my goal.</p>
<p>I receive input from a data source as an array such as ["Y","Y",,"Y","Y",,"Y"].</p>
<p>The values relate to investment fund names and I am outputting a string such as "Balanced, Cash, High Growth, Moderate and Growth options".</p>
<p>If there is only one value populated with "Y" the string could be "Conservative option".</p>
<p>If there are two values, the string could be "Conservative and Cash options".</p>
<p>For more than two values, the string could be "Conservative, Cash and Moderate options".</p>
<p>I know that the order of the values will always be the same, eg the first value will always be the Balanced option. Here is the code:</p>
<pre><code>
// balanced, cash, high growth, moderate and growth
var params = ["Y","Y",,"Y","Y",,"Y"];
getString(params)
function getString(values) {
// map for the values
var fundMap = {
0: "Balanced",
1: "Cash",
2: "Conservative",
3: "High Growth",
4: "Moderate",
5: "Shares",
6: "Growth"
}
var fundArray = [];
// get fund names from map and push to array
for (var i = 0; i < values.length; i++) {
if (values[i] == "Y") {
fundArray.push(fundMap[i]);
}
}
console.log(fundArray);
var fundString = "";
if (fundArray.length == 1) {
fundString = fundArray + " option";
}
else if (fundArray.length == 2) {
fundString = fundArray[0] + " and " + fundArray[1] + " options";
}
else {
for (var i = 0; i < fundArray.length -2; i++) {
fundString = fundString + fundArray[i] + ", ";
}
fundString = fundString + fundArray[fundArray.length -2] + " and ";
fundString = fundString + fundArray[fundArray.length -1] + " options";
}
console.log(fundString);
}
</code></pre>
<p>I would love to know if there is a more efficient or just a neater way of writing this code please.</p>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T22:24:42.380",
"Id": "473331",
"Score": "1",
"body": "You have a sparse array here: `var params = [\"Y\",\"Y\",,\"Y\",\"Y\",,\"Y\"];` Sparse arrays are almost always a mistake, consider fixing the data source to use a well-formatted array instead, if possible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T10:27:15.880",
"Id": "473361",
"Score": "0",
"body": "Thank you for this tip - I hadn't heard of the term \"sparse array\" before and I'm still not sure why it's to be avoided. Regarding the data source - yes I could fix that as I'm exporting it from Access, but that would require writing queries in Access which is what I'm trying to avoid as they have to be run manually. In addition, we often get data supplied to us as csv so in those instances I have no control over the input at all."
}
] |
[
{
"body": "<p>A few stylistic nitpicks: the function body should be indented and there should be a space following the <code>-</code> signs.</p>\n\n<p><code>getString</code> should be changed to take an array of boolean values, instead of a sparse array of \"Y\" strings. You can write a separate function to convert your original format to a bool array.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function optionsToBoolArray(array){\n var converted = [];\n for(var i = 0; i < array.length; i++){\n converted[i] = array[i] === \"Y\";\n }\n return converted;\n}\n</code></pre>\n\n<p><code>getString</code> is also a undescriptive name for your function. You should change it to something along the lines of <code>optionsToReadableString</code>.</p>\n\n<p><code>fundMap</code> doesn't need to be an object. Since you are currently using like an array, explicitly make it an array for clarity.</p>\n\n<p><code>fundString = fundArray + \" option\";</code> should be <code>fundString = fundArray[0] + \" option\";</code> to avoid implicit conversions for readability.</p>\n\n<p>The code for multiple options can also be simplified by using array methods: </p>\n\n<pre><code>else {\n fundString = fundArray.slice(0,fundArray.length - 1).join(\", \") + \" and \" + fundArray[fundArray.length - 1] + \" options\";\n}\n</code></pre>\n\n<p>This also lets you eliminate the <code>else if</code> branch.</p>\n\n<p>You should also extract the <code>console.log</code> out of the function to separate the logic. After doing this, you can eliminate <code>fundString</code> completely by just returning the value from each branch of the if/else.</p>\n\n<p>You should also look into learning ES6 features such as using <code>let</code> instead of <code>var</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T22:00:18.573",
"Id": "473327",
"Score": "0",
"body": "Cool - thank you! That's just the kind of thing I was looking for. Gonna play with it this afternoon when my little boy's asleep :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T10:13:50.417",
"Id": "473358",
"Score": "0",
"body": "OK - I've managed to confuse myself pretty well :-) so here are a couple of questions:\n\nArray.prototype.map - is this an overall term for array.map(function)? After the function to get a boolean array I tried to use\n`let fundArray = array.map(function(boolValue, i) {\n return boolValue ? fundMap[i] : array.splice(i, 1);\n });\n return fundArray;\n`\nI wanted to remove those elements where boolValue === false but I see that it messes with the index i so I'd have to write more code to fix that. Does it then mean that I would actually be writing more code than the original for loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T19:15:33.493",
"Id": "473408",
"Score": "0",
"body": "On second thought, the string conversion code is fine. map would probably introduce more complexity. Also, any `something.prototype.something` functions are just methods you can call on any instance of an object, including map for arrays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T09:48:11.027",
"Id": "473475",
"Score": "0",
"body": "Thank you so much for your help. I posted the completed code https://jsfiddle.net/malcolmwhild/fzhwc13o/"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T21:21:50.333",
"Id": "241213",
"ParentId": "241210",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241213",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:01:04.073",
"Id": "241210",
"Score": "2",
"Tags": [
"javascript",
"strings",
"array"
],
"Title": "Receive an array input and output a string"
}
|
241210
|
<p>I need to generate a huge array from a few words, and not random, I must get the same array always for the same words.</p>
<p>I wrote this code which will generate 3050 from 51 letters, but I'm sure there is a better way to do it.</p>
<p>The idea is to convert the letters to ASCII numbers and put them into an array, then manipulate this array to get a new big array.</p>
<pre><code>this.otpOne = 'OrangePie'
this.otpTwo = 'ClearBlueSky'
this.otpThree = 'RedApplePie'
this.otpFour = 'MakeItEasy'
this.otpFive = 'blueBerry'
gen();
function gen() {
let otpString = this.otpOne + this.otpTwo + this.otpThree + this.otpFour + this.otpFive;
let otpStringArray = otpString.split('').map(char => char.charCodeAt(0));
let otpStringSorted = otpStringArray.sort();
let median = this.median(otpStringSorted);
Array.prototype.swap = function () {
let len = this.length;
let d = [];
for (let y = 0; y < len; y++) {
if (y + 1 < len) {
let tempOne = this[y];
let tempTwo = this[y + 1];
d.push(tempTwo, tempOne);
tempOne = '';
tempTwo = '';
}
}
return d;
};
let left = [], right = [], odd = [], even = [];
odd.push(otpStringSorted.filter(num => Math.abs(num) % 2 === 1));
even.push(otpStringSorted.filter(num => Math.abs(num) % 2 === 0));
right.push(otpStringSorted.filter(num => Math.abs(num) > median));
left.push(otpStringSorted.filter(num => Math.abs(num) < median));
let chunksOne = this.makeChunks(otpStringSorted, 2);
let chunksTwo = this.makeChunks(otpStringSorted, 3);
let chunksThree = this.makeChunks(otpStringSorted, 4);
let chunksFour = this.makeChunks(odd.concat(right).flat(), 2);
let chunksFive = this.makeChunks(even.concat(left).flat(), 2);
let otpStringSortedRev = Array.from(otpStringSorted).reverse();
let stringsArraysV1 = [
...odd.flat(),
...left.flat(),
...even.flat(),
...right.flat(),
...chunksOne.flat(),
...chunksTwo.flat(),
...chunksThree.flat(),
...chunksFour.flat(),
...chunksFive.flat(),
...otpStringSortedRev.flat()];
let stringsArraysV2 = [
...even.flat(),
...right.flat(),
...odd.flat(),
...even.flat(),
...chunksFive.flat(),
...chunksFour.flat(),
...chunksThree.flat(),
...chunksTwo.flat(),
...chunksOne.flat(),
...otpStringSortedRev.flat()];
let stringsArraysV3 = stringsArraysV1.filter(num => Math.abs(num) % 2 === 1 ? num / 2 : num)
let stringsArraysV4 = stringsArraysV2.filter(num => Math.abs(num) % 2 === 1 ? num / 2 : num)
this.stringsArrays = [
...stringsArraysV1,
...stringsArraysV2,
...stringsArraysV3,
...stringsArraysV4,
...otpStringSorted.swap(),
...stringsArraysV1.swap(),
...stringsArraysV2.swap(),
...stringsArraysV3.swap(),
...stringsArraysV4.swap(),
];
$('.key').text(this.stringsArrays)
$('.len').text('len: ' + otpString.length + ' to ' + this.stringsArrays.length)
}
function makeChunks(array, size) {
let add = (a, b) => a + b,
newArray = [],
i = 0;
while (i < array.length) {
newArray.push(array.slice(i, i += size).reduce(add) % (33 - 126));
}
let finalArray = newArray.map(num => num < 34 ? ((92 - num) + num) : num);
return finalArray;
}
function median(values) {
values.sort(function (a, b) {
return a - b;
});
let half = Math.floor(values.length / 2);
if (values.length % 2)
return values[half];
else
return (values[half - 1] + values[half]) / 2.0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:50:40.530",
"Id": "473319",
"Score": "0",
"body": "what's the big array requirement? element length? uniqueness? Will the big array be sorted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T21:02:16.323",
"Id": "473322",
"Score": "0",
"body": "no specific requirement, but it should be created again when needed, as big as can be, no need to be sorted, and it will not be unique."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T21:22:22.897",
"Id": "473323",
"Score": "0",
"body": "if you don't have any requirement, you can just use all letters in those string and split them into an array, you can create a bigger array by manipulate permutation, subsequence, etc from the string array. I think you can generate way more than 3050 results from 51 letters. Your code seems make an easy problem complex"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T21:26:34.627",
"Id": "473324",
"Score": "0",
"body": "No problem, but this won't overload the user browser? this is how I know to increase the size, would suggest a better way or do you have additional code may increase the size, or maybe more simple way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T21:31:07.293",
"Id": "473325",
"Score": "0",
"body": "I mean if you don't have any requirement, can you use a loop to generate an array with all the same string in it and you can pick any size you want? It won't overload user browser. Your code seems too complex and may be overloaded with all those built in functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T21:42:44.520",
"Id": "473326",
"Score": "0",
"body": "Well, then I will search how to array permutation. Thanks."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T20:45:29.047",
"Id": "241212",
"Score": "3",
"Tags": [
"javascript",
"array"
],
"Title": "Generate big an array from a few words"
}
|
241212
|
<p>I am trying to abstract data from a complex and create a EventDto.
And I was able to do it using foreach but the syntax is dreadful.
Is there a better way of writing this code? </p>
<pre><code> public class EventDtO
{
public string Id { get; set; }
public string Title { get; set; }
public string CategoryTitle { get; set; }
public DateTime DateTime { get; set; }
}
</code></pre>
<p>This is the complex object that I am trying to get the data from:</p>
<pre><code>public class RootObject
{
public List<Event> Events { get; set; }
}
public class Event
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public List<Category> Categories { get; set; }
public List<Geometry> Geometries { get; set; }
}
public class Geometry
{
public DateTime Date { get; set; }
public string Type { get; set; }
public List<object> Coordinates { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Title { get; set; }
}
</code></pre>
<p>The mapping relationship I want is</p>
<pre class="lang-none prettyprint-override"><code>EventDto.Id->Event.Id
EventDto.Title->Event.Title
Event.CategoryTitle->Category.Title
Event.DateTime->Geometry.Date
</code></pre>
<p>The Category class will only contain one value, but the geometry.Date can have multiple values.</p>
<p>So the output I want is:</p>
<pre class="lang-none prettyprint-override"><code>Title Categories Date
"Iceberg B42" Sea and Lake Ice 2020-04-23T14:24:00Z
"Iceberg B42" Sea and Lake Ice 2017-09-15T00:00:00Z
</code></pre>
<p>I am able to get the correct information if I use the following code:</p>
<pre><code>var Event = new List<EventDTO>();
foreach (var con in content.Events)
{
var data = new EventDTO
{
Title = con.Title,
Id = con.Id
};
foreach (var cat in con.Categories)
{
data.CategoriesTitle = cat.Title;
}
foreach (var geo in con.Geometries)
{
data.DateTime = geo.Date;
Event.Add(data);
}
}
</code></pre>
<p>An example of the JSON:</p>
<pre><code> {
"id": "EONET_2881",
"title": "Iceberg B42",
"description": "",
"categories": [
{
"id": 15,
"title": "Sea and Lake Ice"
}
]
"geometries": [
{
"date": "2017-04-21T00:00:00Z",
"type": "Point",
"coordinates": [ -107.19, -74.63 ]
},
{
"date": "2017-09-15T00:00:00Z",
"type": "Point",
"coordinates": [ -107.11, -74.08 ]
}
]
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, there is a bug in your example. In this loop:</p>\n\n<pre><code>foreach (var geo in con.Geometries)\n{\n data.DateTime = geo.Date;\n Event.Add(data);\n}\n</code></pre>\n\n<p>You are just overwriting date in the same object. You should create a new object instead. Your final list will have the same object twice with the same date.</p>\n\n<p>As for better solution for this, you can use linq and create something like this:</p>\n\n<pre><code>IEnumerable<EventDTO> events = \n from e in content.Events\n from c in e.Categories\n from g in e.Geometries\n select new EventDTO { Id = e.Id, Title = e.Title, CategoryTitle = c.Title, DateTime = g.Date };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T13:03:43.497",
"Id": "241244",
"ParentId": "241231",
"Score": "0"
}
},
{
"body": "<p>This is the solution i went in the end </p>\n\n<pre><code> var Event = content.Events.SelectMany(con => \n con.Geometries.Select(geo => \n new EventDTO\n {\n Title = con.Title,\n Id = con.Id,\n CategoriesTitle = con.Categories.FirstOrDefault().Title,\n DateTime = geo.Date\n })\n ).ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T14:46:07.330",
"Id": "476812",
"Score": "1",
"body": "Always select your chosen answer even if you wrote it yourself."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T13:06:30.487",
"Id": "241245",
"ParentId": "241231",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T08:45:37.133",
"Id": "241231",
"Score": "0",
"Tags": [
"c#"
],
"Title": "How to refactor code to abstract data from a complex object into a single object without using foreach statements"
}
|
241231
|
<p>In python the itertools module is a good tool to generate combinations of elements. In this case I want to generate all combinations (without repetition) having a subsets of specified length but also with a product limit. For example, given a list of integer numbers I want all subsets of length 4 which product is bellow a given numerical limit, like bellow:</p>
<pre><code>import functools, operator
LST = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 ]
prod = lambda A : functools.reduce(operator.mul, A )
def combinations_with_limit( LST, length,lim ) :
''':Description: LST - array of integers,
length = number of elements in each subset ,
lim = product limit of each subset '''
H = list(range(length)) # H - represents the index array
B = [ LST[ii] for ii in H ] # B - the main array with elements
while H[0] <= len(LST)-length :
for i in range( H[-1], len(LST)) :
H = H[:-1] + [i]
B = [ LST[ii] for ii in H ]
if prod(B) > lim : ### LIMIT THE OUTCOME PART . It skips the rest of the iteration
H[-1] = len(LST) - 1
elif prod(B) <= lim :
yield B
if H[-1] == len(LST) - 1 : # We reset the index array here
j = len(H)-1
while H[j] == len(LST)-length+j :
j -=1
H[j] +=1
for l in range(j+1, len(H)) :
H[l] = H[l-1] +1
for i in combinations_with_limit(LST, 4 , 1000 ) :
print(i ,end=' ' )
</code></pre>
<p>The output will look as follows:</p>
<pre><code>[2, 3, 5, 7] [2, 3, 5, 11] [2, 3, 5, 13] [2, 3, 5, 17] [2, 3, 5, 19]
[2, 3, 5, 23] [2, 3, 5, 29] [2, 3, 5, 31] [2, 3, 7, 11] [2, 3, 7, 13]
[2, 3, 7, 17] [2, 3, 7, 19] [2, 3, 7, 23] [2, 5, 7, 11] [2, 5, 7, 13]
</code></pre>
<p>And this is correct. All the products subsets are bellow the requested limit. However, I think that the above code is non-elegant and has some major loop inefficiency as I tested it for larger lists with > thousands of elements.</p>
<p>Do you have any ideas on how to improve it?</p>
|
[] |
[
{
"body": "<p>Welcome to Python programming!</p>\n\n<p>Your code has various formatting issues, including the fact that when copying it here, you messed up the indentation of the docstring in your function – copying what you write here into my development environment will not work because of that. But let's look at the semantics.</p>\n\n<p>On a high level view, this sounds like a problem I would try to solve recursively.</p>\n\n<p>All the products of one number that are less than or equal to a target (you don't state that equal-to is permitted, but the line <code>if prod(B) > lim :</code> makes me think that is what you want) are exactly the numbers <code>n <= limit</code>, and from there we can generalize to implementing ‘The product of <code>k</code> numbers ≤ <code>p</code> if <code>x</code> is the first number and the product of the remaining <code>k-1</code> numbers ≤ <code>p//x</code>.’ Note that this works with integer division – If you allow floats or if your limit is exclusive, you need float division.</p>\n\n<p>For that recursive solution, I would use a generator and <code>yield</code> every partial solution up the call chain until I get to the original loop that wants my results.</p>\n\n<p>But let us assume that, for whatever reason, you indeed want a function that solves this iteratively, not recursively.</p>\n\n<p>Then, even before I look at your function, it has issue: 2*3*11*13 = 858 < 1000, but that combination does not appear in your list, so you would do well trying to manually generate maybe two examples where you know the answer, and try to produce them using your function.</p>\n\n<p>If you feel it difficult to use the mental arithmetics, trust the tools you mention:</p>\n\n<pre><code>def combinations_with_limit(lst, length, lim):\n return [x for x in itertools.combinations(lst, length)\n if prod(x) <= lim]\n</code></pre>\n\n<p>is quite a readable and explicit process. It might throw away a lot of things, but it should help you get test cases.</p>\n\n<p>Once you have a working solution, there are several things in your code to look out for.</p>\n\n<ul>\n<li>Calculating the product separately for various combinations, and even twice in your middle loop, will be expensive. Store it somewhere and manipulate it while moving about, instead of running <code>prod</code> too often, in particular if you have a need to access it twice, like in your <code>if</code> and <code>elif</code>.</li>\n<li>You are manipulating both <code>H</code> and <code>B</code> in parallel. That feels dangerous: You need great care to make sure that <code>H</code> goes through all combinations, keeping the right length, and never gains any duplicate elements, and then you add the computational overhead of a full list comprehension on top to generate your <code>B</code>s. That sounds easy to get wrong, and as your results show, one of the conditions indeed goes wrong.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T12:21:54.350",
"Id": "241240",
"ParentId": "241232",
"Score": "2"
}
},
{
"body": "<h2>Pass 1</h2>\n\n<p>Here is some example code; it changes nothing about your algorithm:</p>\n\n<pre><code>from functools import reduce\nfrom operator import mul\nfrom typing import Iterable, List, Sequence\n\n\ndef prod(a):\n return reduce(mul, a)\n\n\ndef combinations_with_limit(\n lst: Sequence[int], \n length: int, \n lim: int\n) -> Iterable[List[int]]:\n \"\"\":Description: LST - array of integers,\n length = number of elements in each subset ,\n lim = product limit of each subset\"\"\"\n\n H = list(range(length)) # H - represents the index array\n B = [lst[ii] for ii in H] # B - the main array with elements\n while H[0] <= len(lst) - length:\n for i in range(H[-1], len(lst)):\n H = H[:-1] + [i]\n B = [lst[ii] for ii in H]\n\n # Limit the outcome part. It skips the rest of the iteration\n if prod(B) > lim:\n H[-1] = len(lst) - 1\n elif prod(B) <= lim:\n yield B\n if H[-1] == len(lst) - 1: # We reset the index array here\n j = len(H) - 1\n while H[j] == len(lst) - length + j:\n j -= 1\n H[j] += 1\n for l in range(j+1, len(H)):\n H[l] = H[l-1] + 1\n\n\nprint(' '.join(\n str(c) for c in \n combinations_with_limit(\n (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31),\n 4, 1000\n )\n))\n</code></pre>\n\n<p>Things to note:</p>\n\n<ul>\n<li>Standard PEP8 indentation in more places</li>\n<li>Type hints to clarify function signature</li>\n<li>Don't use a lambda when a plain function will suffice</li>\n<li>Use <code>join</code> for the output</li>\n<li>Use a <code>tuple</code> for input since we don't need to mutate it</li>\n</ul>\n\n<h2>Tests</h2>\n\n<p>Using your <code>original</code> function as well as the solution from <code>anaphory</code>, write a basic test:</p>\n\n<pre><code>def test():\n inp = ((2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31), 4, 1000)\n ref = tuple(anaphory(*inp))\n for alt in (original,):\n act = tuple(tuple(li) for li in alt(*inp))\n refs, acts = set(ref), set(act)\n\n miss_r = acts - refs\n miss_s = refs - acts\n len_diff = len(act) != len(ref)\n if miss_r or miss_s or len_diff:\n print(f'Method {alt.__name__} failed -')\n if miss_r:\n print(' ref missing from act:', miss_r)\n if miss_s:\n print(' act missing from ref:', miss_s)\n if len_diff:\n print(f' Length mismatch: {len(act)} != {len(ref)}')\n print()\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n\n<p>This demonstrates which values your method is missing - as indicated in the other answer, <code>(2, 3, 11, 13)</code>.</p>\n\n<h2>Other improvements</h2>\n\n<ul>\n<li>Store <code>len(lst)</code> in a local variable for reuse</li>\n<li><code>H = H[:-1] + [i]</code> can be <code>H[-1] = i</code>, assuming there are no adverse effects of keeping the same list</li>\n<li><code>elif prod(B) <= lim:</code> should simply be <code>else</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T15:00:33.507",
"Id": "241248",
"ParentId": "241232",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T09:24:03.590",
"Id": "241232",
"Score": "4",
"Tags": [
"python"
],
"Title": "combinations of an integer list with product limit"
}
|
241232
|
<p>My <a href="https://github.com/Anaphory/dispersal-simulation/blob/master/supplement/dispersal_model/dispersal.py" rel="nofollow noreferrer">agent-based simulation</a> spends about 60% of its runtime in one function, as the profiler shows.</p>
<p><a href="https://i.stack.imgur.com/DqekM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DqekM.png" alt="gprof2dot-generated profile of the simulation"></a></p>
<p>That function looks as follows.</p>
<pre><code># That is, for those locations, the family knows actual
# available resources and size and culture vectors of all agents located there
# at the moment.
@cython.inline
@cython.ccall
@cython.exceptval(check=False)
def observe_neighbors(
family: Family,
patches: dict,
all_families: dict,
neighbors: list) -> list:
"""Summarize what a family know about their surroundings.
From the sensory data, the family estimates whether agents in patches under
consideration agents will likely be cooperators (cultural distance less
than `params.cooperation_threshold`) or competitors.
"""
result: list
dest: hexgrid.Index
f: Family
c: cython.ulong
c = family.culture
result = []
for dest in known_location(family.location_history, neighbors):
if dest not in patches:
# Don't walk into the water
continue
cooperators, competitors = 0, 0
if dest not in all_families:
all_families[dest] = []
for f in all_families[dest]:
if similar_culture(f.culture, c):
cooperators += f.effective_size
else:
competitors += f.effective_size
result.append((dest, patches[dest], cooperators, competitors))
return result
# The actual split into cooperators and competitors is actualized only by the
# formation of collectives (see [Section 4.9](#4.9-Collectives)) in [Submodule
# 7.5](#7.5-Cooperative-Resource-Extraction)
</code></pre>
<p><code>Family</code> is a <code>@cython.cclass</code> with only a handful of attributes and a single property.</p>
<pre><code>@cython.cclass
class Family:
"""A family group agent
Families are the decision-making agent in our model. Families can migrate
between cells and form links to other families in the context of
cooperation to extract resources.
"""
descendence = cython.declare(str, visibility="public")
# The agent's history of decendence, also serving as unique ID
culture = cython.declare(cython.ulong, visibility="public")
# The family's shared culture
location_history = cython.declare(list, visibility="public")
# A list of cells indices.
number_offspring = cython.declare(int, visibility="public")
# The number of descendant families this family has given rise to so far
effective_size = cython.declare(int, visibility="public")
# The effective size of the family in number of adults. One adult is
# assumed to consume the same amount of food/energy and to contribute the
# same labor to foraging as any other adult.
stored_resources = cython.declare(float, visibility="public")
# The amount of stored resources, in kcal, the family has access to
seasons_till_next_child = cython.declare(int, visibility="public")
# The number of seasons to wait until the next child (reset to 2 when
# starvation happens)
seasons_till_next_mutation = cython.declare(int, visibility="public")
# A bookkeeping quantity. Instead of mutation happening in each time step
# with a tiny probability, the same distribution of times between mutations
# is generated by drawing a number of season from a geometric distribution
# and counting it down by one each time step, which is useful because
# random number generation is computationally expensive.
@property
def location(self) -> hexgrid.Index:
return self.location_history[0]
def __init__(self,
descendence: str,
culture: cython.ulong,
location_history: List[hexgrid.Index],
stored_resources: kcal = 0,
seasons_till_next_child: int = 4,
effective_size: int = 2):
self.descendence = descendence
self.culture = culture
self.stored_resources = stored_resources
self.location_history = location_history
self.seasons_till_next_child = seasons_till_next_child
self.effective_size = effective_size
</code></pre>
<p>Like <code>observe_neighbors</code>, <code>known_location</code> is a C function, an <code>inline cdef int</code>.</p>
<pre><code># ## 4.5 Learning
#
# - Agents are guaranteed to have knowledge of the locations they visited
# within the previous 2 years, and of all locations within the maximum
# half-year migration distance that they visited in the previous 4 years.
@cython.inline
@cython.ccall
@cython.exceptval(check=False)
def known_location(
history: list,
nearby: list) -> list:
"""Tell a family which locations nearby they might know about
"""
# The sub-module that uses this function asserts that the first result of
# the iterator be the location of the family itself, but the locations can
# be returned in any order, even in parallel.
result = []
for location in history[:4]:
result.append(location)
for location in nearby:
if location not in history[:4]:
if (location in history[:8]) or attention():
result.append(location)
return result
</code></pre>
<p>That <code>attention</code> function is defined <a href="https://github.com/Anaphory/dispersal-simulation/blob/cbbea60718c781ce1d0c90aafe94a152e0171926/supplement/dispersal_model/c_util.pyx" rel="nofollow noreferrer">in an actual Cython file</a> as</p>
<pre><code>from libc.stdlib cimport rand, RAND_MAX
cdef double p_attention = 0.1
cpdef int attention():
return rand() < RAND_MAX * p_attention
</code></pre>
<p>The dictionary <code>patches</code> maps a fixed set of 150909 integers between 599018402652094463 and 602909426126422015 to mutable <code>Patch</code> objects (also a <code>@cython.cclass</code>). <a href="https://github.com/Anaphory/dispersal-simulation/blob/cbbea60718c781ce1d0c90aafe94a152e0171926/supplement/dispersal_model/dispersal.py" rel="nofollow noreferrer">The full code of my module is on GitHub</a>, for context.</p>
<p>How do I refactor and annotate this function run faster? (How do I switch on line tracing for this function only, so that I know which lines need refactoring and annotation to run faster?)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T14:06:09.667",
"Id": "473380",
"Score": "0",
"body": "Please show more of your code, especially the `Family` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T14:16:25.033",
"Id": "473384",
"Score": "0",
"body": "Links expire. CodeReview policy is that any important code be included directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T14:21:19.843",
"Id": "473387",
"Score": "1",
"body": "They expire, and they also fail to be at the current state, as in this case where a push did not actually go through. Sigh. But yes, I'll copy my Family over, and known_location is probably also worth seeing then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T14:31:23.663",
"Id": "473388",
"Score": "0",
"body": "Done. I have also pinned the two later GitHub links to the specific commits, to slightly increase their half life."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T10:31:07.920",
"Id": "241234",
"Score": "1",
"Tags": [
"performance",
"cython"
],
"Title": "Cooperator/competitor agent-based simulation"
}
|
241234
|
<p>This is a basic map that was built:</p>
<p><a href="https://i.stack.imgur.com/Yy0gA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yy0gA.jpg" alt="basic map"></a></p>
<p>To render it, you would put this in the .html.slim files</p>
<pre><code>.acme-map-container-4 data=map_identifier(resource: @warehouse.id)
</code></pre>
<p>What actually happens is, the <code>map_identifer()</code> (a rails helper) inserts some data attributes,
and the javascript code uses that to initialize the google map.</p>
<p>A basic google map can be done with <a href="https://developers.google.com/maps/documentation/javascript/examples/map-simple" rel="nofollow noreferrer">about 11 lines of code</a>. This code has many more lines,
because it lets us do the following things:</p>
<ul>
<li>add labels to markers</li>
<li>these labels can be made clickable (user is redirected)</li>
<li>the icon for the pin is overridable</li>
<li>the architecture is conducive to polling via ajax - so for example on a office display, you can track your delivery driver if he's recording his latLng to a postgres backend</li>
<li>maps in modals/tabs are "late initialized" for faster page loads</li>
<li>the ruby code can override the default map type, for example hybrid, satellite, roadmap</li>
<li>a series of latLngs can be rendered as a route</li>
<li>multiple routes and multiple markers can co-exist in a single map</li>
<li>a page can have multiple maps</li>
<li>infoWindows or tooltips can be made to appear onClick</li>
<li>interactive filtering of what pins are shown</li>
<li>polygons can be drawn on a map, and persist when copied to the simple_form</li>
<li>in editable mode above, custom controls are overlayed so cor example the 'clear map' button clears the drawings from the map</li>
<li>when a user needs to specify a latLng in a form field, they can point it out in the map by clicking on it</li>
</ul>
<p>This is how the javascript is structured:</p>
<pre><code>├── acme
│ ├── index.js
│ ├── map.js
│ ├── marker.js
│ ├── polygon.js
│ └── polyline.js
</code></pre>
<p>I'm pasting <code>marker.js</code> here because the others (polyline.js, polygon.js) are pretty much in the same league when it comes to coding style.</p>
<pre class="lang-js prettyprint-override"><code>// app/assets/javascripts/acme/marker.js
// namespace
var Acme = Acme || {};
// Marker
Acme.Marker = function(geoJson) {
// Functions
// attach marker to google map
this.setMap = function(m) {
this.marker.setMap(m)
this.infoWindow && this.geoJson.properties.infoWindowInitialState && this.geoJson.properties.infoWindowInitialState == "opened" && this.infoWindow.setMap(m)
}
// extend given bounds to include self
this.extendBoundsToFit = function(bounds) {
if (geoJson.geometry.coordinates[1]<-90 && geoJson.geometry.coordinates[1]>90) { return bounds } //exit if invalid
if (geoJson.geometry.coordinates[0]<-180 && geoJson.geometry.coordinates[0]>180) { return bounds } //exit if invalid
bounds.extend(
new google.maps.LatLng(
geoJson.geometry.coordinates[1],
geoJson.geometry.coordinates[0]
)
)
return bounds
}
// create associated infoWindow
this.createInfoWindow = function() {
if (this.geoJson.properties.infoWindowContent == undefined) { return }
var infoWindow = new google.maps.InfoWindow({
content: this.geoJson.properties.infoWindowContent
})
infoWindow.setPosition({lat: geoJson.geometry.coordinates[1], lng: geoJson.geometry.coordinates[0]})
return infoWindow
}
// possibly open infoWindow or redirect to a path on click.
this.clickHandler = function() {
console.log("click")
if (this.parent.infoWindow && this.parent.geoJson.properties.clickBehavior && this.parent.geoJson.properties.clickBehavior == "openInfoWindow") {
this.parent.infoWindow.open(this.getMap())
}
if (this.parent.geoJson.properties.clickBehavior && this.parent.geoJson.properties.clickBehavior == "openLink") {
Turbolinks.visit(this.parent.geoJson.properties.clickDestination)
}
return
}
// /Functions
this.geoJson = geoJson
this.labelVisible = $.trim(this.geoJson.properties.label).length ? true : false
opts = {
labelStyle: {opacity: 0.9},
labelInBackground: true,
icon: geoJson.properties.markerIcon, // can be a hash specifing an offset
labelClass: 'acme-map-marker-label',
labelVisible: this.labelVisible,
labelContent: geoJson.properties.label,
title: geoJson.properties.tooltip,
position: new google.maps.LatLng(geoJson.geometry.coordinates[1],
geoJson.geometry.coordinates[0]),
}
this.marker = new MarkerWithLabel(opts)
this.marker.set('parent', this)
this.infoWindow = this.createInfoWindow()
google.maps.event.addListener(this.marker, 'click', this.clickHandler)
}
</code></pre>
<p>The main frontend code is in map.js, so it is that who would call upon marker.js to create markers for example. here it is:</p>
<pre class="lang-js prettyprint-override"><code>// app/assets/javascripts/acme/map.js
// namespace
var Acme = Acme || {};
// Map
Acme.Map = function(elem) {
// Functions
// create empty map and send ajax request to fetch objects
this.init = function() {
return this.makeMap() // a bare map
.getMapData()
}
// creates empty map
this.makeMap = function() {
this.googleMap = new google.maps.Map(this.elem, {
center: this.defaultCenter(),
zoom: 16,
mapTypeId: "satellite"
});
this.googleMap.set('parent', this)
return this
}
// downloads latitudes, longitudes for pins, polygons etc
this.getMapData = function(options) {
console.log("getMapData")
if (! this.mapIdentifier()) { return this } // return early there's not enough info
$.ajax({ url: '/api/maps/map.json', context: this, data: this.mapIdentifier(),
success: function(ajaxData) { this.processMapData(ajaxData) }
})
return this
}
// executes after fetching map data from api
this.processMapData = function(ajaxData) {
console.log("processMapData")
if (Object.keys(ajaxData).length != 2 || ajaxData.settings == undefined) { return } //invalid resp.
this.ajaxData = ajaxData
this.setSize().
setType()
.draw()
.postZoom()
.filtrationHooks()
.editability()
.finalize()
}
// allow ruby backend to influence the eventual width/height of map
this.setSize = function() {
$(this.elem).css('width', this.ajaxData.settings.width)
$(this.elem).css('height', this.ajaxData.settings.height)
return this
}
// returns something like {"map_secondary_resource":1128,"map_controller":"warehouses","map_resource":1335,"map_action":"edit"}
this.mapIdentifier = function() {
if (! $(this.elem).data('controller')) { return } // return if weird
var data = {}
$.each( $(this.elem).data(), function (name, value) {
(!name.startsWith("default")) && (data[('map_'+name)] = value) //not need to send defaults
});
return data
}
// set map type
this.setType = function() {
this.googleMap.setMapTypeId( this.ajaxData.settings.mapTypeId )
return this
}
// focus camera when objects are present in map
this.postZoom = function() {
console.log("postZoom")
if (this.mapObjects.length == 0) { return this } // nothing to do
this.tempLimitZoom() // alternative solution https://stackoverflow.com/a/4709017
var bounds = new google.maps.LatLngBounds();
this.mapObjects.forEach(function(item, index) {
bounds = item.extendBoundsToFit(bounds)
})
this.googleMap.fitBounds(bounds)
setTimeout( function() {
this.tempUnLimitZoom()
this.singularZoom()
}.bind(this), 500)
return this
}
// gt - greater than
this.tempLimitZoom = function() {
if (this.ajaxData.settings.preventOverzoom) {
this.googleMap.setOptions({maxZoom: this.ajaxData.settings.preventOverzoomGt})
}
return this
}
// undoing tempLimitZoom
this.tempUnLimitZoom = function() {
if (this.ajaxData.settings.preventOverzoom) {
this.googleMap.setOptions({maxZoom: undefined})
}
return this
}
// interactive filtering
this.filterByMarkerLabelContent = function(ev) {
var input = $(ev.target)
var phrase = $(input).val()
this.mapObjects.forEach(function(item, index) {
if (! (item instanceof Acme.Marker)) { return } // filtering by marker properties only atm
if (item.marker && item.marker.labelContent && item.marker.labelContent.indexOf(phrase)>-1) {
item.marker.setVisible(true)
} else {
item.marker.setVisible(false)
}
})
}
// listen for key presses
// assumes only 1 filter (.map-marker-filter) exists in dom
this.filtrationHooks = function() {
$(elem).closest('.row').on('keyup','.map-marker-filter', this.filterByMarkerLabelContent.bind(this) )
return this
}
// editability related code
// make map editable - if asked
this.editability = function() {
if (! this.ajaxData.settings.isEditableMap) { return this }
console.log("editability")
this.createToolbar()
this.markerEditability()
this.polygonEditability()
return this
}
this.createToolbar = function() {
var toolbar = document.createElement('div');
this.createCloseButton(toolbar, this.googleMap)
this.createClearButton(toolbar, this.googleMap)
toolbar.index = 1;
this.googleMap.controls[google.maps.ControlPosition.TOP_CENTER].push(toolbar);
return this
}
this.polygonEditability = function() {
//polygon creation event handler
var drawingManager = this.createDrawingManager()
drawingManager.setMap(this.googleMap);
$.each(this.allPolygons(), function(index, item) { // marks polygons as editable
item.polygon.setEditable(true)
})
//polygon creation event handler
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
console.log("polygoncomplete " + polygon)
this.getMap().parent.addDrawnPolygon(polygon)
})
// to fully clear a map, overlays need to be removed as well
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(arg) {
this.getMap().parent.overlays.push(arg.overlay)
})
}
this.markerEditability = function() {
// allow moving marker (1) on click
google.maps.event.addListener(this.googleMap, 'click', function(event) {
this.parent.moveMarker1(event.latLng)
})
}
// custom control - CLEAR MAP button
this.createClearButton = function(toolbar, googleMap) {
var that = this
var clearButton = this.makeButton(
'CLEAR MAP',
'CLEAR ALL POLYGONS IN THIS MAP',
toolbar)
google.maps.event.addDomListener(clearButton, 'click', function (something) {
$(document).trigger("acme:map:clear_polygons_clicked")
this.clearPolygons()
}.bind(this));
}
// custom control - close button
this.createCloseButton = function(toolbar, googleMap) {
var closeButton = this.makeButton(
'CLOSE WINDOW',
'Closes this pop up only. Changes are saved when you save the parent form.',
toolbar)
// handle CLOSE button click in dialog
google.maps.event.addDomListener(closeButton, 'click', function (_) {
$(document).trigger("acme:map:close_clicked", googleMap)
});
}
// nice toolbar at geojson.io btw
this.makeButton = function(label, tooltip, toolbar) {
var buttonDiv = this.makeButtonDiv(tooltip)
toolbar.appendChild(buttonDiv)
var buttonLabel = this.makeButtonLabel(label)
buttonDiv.appendChild(buttonLabel)
return buttonDiv
}
this.makeButtonDiv = function(tooltip) {
var div = document.createElement('div');
div.style.backgroundColor = '#fff';
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px';
div.style.borderColor = '#ccc';
div.style.marginTop = '4px';
div.style.marginLeft = '36px';
div.style.cursor = 'pointer';
div.style.textAlign = 'center';
div.title = tooltip;
return div
}
this.makeButtonLabel = function(label) {
var div = document.createElement('div');
div.style.fontFamily = 'Roboto, Arial, sans-serif';
div.style.fontSize = '9px';
div.style.paddingLeft = '4px';
div.style.paddingRight = '4px';
div.style.paddingTop = '7px';
div.style.paddingBottom = '7px';
div.innerHTML = label;
return div
}
this.moveMarker1 = function(latLng) {
console.log("moveMarker1")
this.createMarkerIfNotExist(latLng)
//console.log("moveMarker1 " + latLng.toJSON() )
this.firstMarker().marker.setPosition( latLng )
}
this.firstMarker = function() {
return this.allMarkers()[0]
}
this.markerGeoJsonTemplate = function() {
return {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": []
},
"properties": {}
}
}
// creates a (plain) marker in map if one doesn't exist
this.createMarkerIfNotExist = function(latLng) {
if (this.allMarkers().length > 0) { return }
var markerGeoJson = this.markerGeoJsonTemplate()
markerGeoJson.geometry.coordinates[0] = latLng.lng()
markerGeoJson.geometry.coordinates[1] = latLng.lat()
marker = new Acme.Marker(markerGeoJson)
marker.setMap(this.googleMap)
this.mapObjects.push( marker )
return marker
}
this.createDrawingManager = function() {
var dm = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [ 'polygon'] // ['marker', 'circle', 'polygon', 'polyline', 'rectangle']
},
polygonOptions: {
fillColor: 'red',
strokeColor: 'red',
fillOpacity: 0.2,
strokeWeight: 6,
clickable: false,
editable: true,
zIndex: 1
}
});
return dm;
}
// add a polygon that the user has drawn
this.addDrawnPolygon = function(polygon) {
var polygon = new Acme.Polygon( this.toPolygonFeature(polygon) )
polygon.setMap(this.googleMap)
this.mapObjects.push(polygon)
return this
}
// clearing map involves,
// 1 setMap(null) for mapObjects
// 2 making sure mapObjects is purged
// 3 remove overlays
this.clearPolygons = function() {
console.log("clearPolygons")
for (var i = 0; i<this.mapObjects.length; i++) {
if (this.mapObjects[i].polygon) { this.mapObjects[i].polygon.setMap(null) }
//if (this.mapObjects[i].marker) { this.mapObjects[i].marker.setMap(null) }
}
$.each(this.overlays, function(i,ov) { ov.setMap(null) }) //stackoverflow.com/a/7882263
this.filterInPlace(this.mapObjects, function(value) { return (!(value instanceof Acme.Polygon)) })
}
// /editability related code
// helps avoid the need for capybara to poll/sleep
this.finalize = function() {
$(elem).addClass('acme-map-inited') // to precent double initialization
return this
}
// draws pins etc on map
this.draw = function() {
console.log("draw")
this.makeObjects().assignObjects() // assign aka setMap()
return this
}
// makes MarkerWithLabel/google.maps.Polygon/google.maps.Polyline etc objects
this.makeObjects = function() {
var that = this
$.each(this.ajaxData.data.features, function(index, item) {
item.geometry.type == "Point" && that.mapObjects.push( new Acme.Marker(item) )
item.geometry.type == "LineString" && that.mapObjects.push( new Acme.PolyLine(item) )
item.geometry.type == "Polygon" && that.mapObjects.push( new Acme.Polygon(item) )
})
this.savedState = this.currentState()
return this
}
// objects are "assigned" to a google map using setMap()
this.assignObjects = function() {
var that = this
$.each(this.mapObjects, function() {
this.setMap(that.googleMap)
})
}
this.totalMarkers = function() {
var markers = $.grep( this.mapObjects, function( n, i ) {
return n instanceof Acme.Marker
});
return markers.length
}
// https://stackoverflow.com/a/37319954
this.filterInPlace = function(a, condition) {
let i = 0, j = 0;
while (i < a.length) {
const val = a[i];
if (condition(val, i, a)) a[j++] = val;
i++;
}
a.length = j;
return a;
}
this.allMarkers = function() {
return $.grep( this.mapObjects, function( n, i ) {
return n instanceof Acme.Marker
});
}
this.allMarkerCoords = function() {
return $.map(this.allMarkers(), function(m, i) {
return m.marker.position.toString()
}).join()
}
this.allPolygonCoords = function() {
return JSON.stringify(this.exportGeoJson(this.allPolygons()))
}
this.allPolygons = function() {
return $.grep( this.mapObjects, function( n, i ) {
return n instanceof Acme.Polygon
});
}
// singularZoom only comes in to effect if the ajax response asked for it
this.singularZoomApplicable = function() {
return (this.totalMarkers() == 1 && this.mapObjects.length == 1 && this.ajaxData.settings.singularZoom >= 0)
}
// singularZoom - a zoom for maps with 1 item in it
this.singularZoom = function() {
if (! this.singularZoomApplicable()) { return }
console.log("singularZoom")
this.googleMap.setZoom(this.ajaxData.settings.singularZoom)
}
// for centering, when 0 objects in map
this.defaultCenter = function() {
var defaultCenter = {lat: 40.7128, lng: -74.006} // somewhere in the state
if ( $(this.elem).data('defaultlat') && $(this.elem).data('defaultlng') ) {
defaultCenter.lat = $(this.elem).data('defaultlat')
defaultCenter.lng = $(this.elem).data('defaultlng')
}
return defaultCenter
}
// accepts a google.maps.Polygon object, returns GeoJson
// adaptation of https://stackoverflow.com/a/32752340
this.exportGeoJson = function(polygons) {
var geoJson = {
"type": "FeatureCollection",
"features": []
};
for (var j = 0; j < polygons.length; j++) {
var polygonFeature = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": []
},
"properties": {}
};
var polygon = polygons[j].polygon
for (var i = 0; i < polygon.getPath().getLength(); i++) {
var pt = polygon.getPath().getAt(i);
polygonFeature.geometry.coordinates.push([
pt.lng(), pt.lat()
]);
}
polygonFeature.geometry.coordinates = [ polygonFeature.geometry.coordinates ]
geoJson.features.push(polygonFeature);
}
return geoJson
}
this.toPolygonFeature = function(polygon) {
var polygonFeature = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": []
},
"properties": {}
};
for (var i = 0; i < polygon.getPath().getLength(); i++) {
var pt = polygon.getPath().getAt(i);
polygonFeature.geometry.coordinates.push([
pt.lng(), pt.lat()]);
}
//polygonFeature.geometry.coordinates = [ polygonFeature.geometry.coordinates ]
return polygonFeature
}
// the geoJson for all polygons in map
this.allPolygonsGeoJson = function() {
return this.exportGeoJson(this.allPolygons())
}
// coordinates of all markers aka pins in map
this.markersCoords = function() {
if (this.allMarkers().length == 0) { return [] }
return $.map( this.allMarkers(), function(m, i) {
return m.marker.getPosition().toJSON()
})
}
// like a checksum
this.currentState = function() {
return (this.allMarkerCoords() + this.allPolygonCoords())
}
// returns true when polygons added, point moved, after original ajax load
this.isDirty = function() {
if (this.currentState() != this.savedState) {
return true
}
}
// /Functions
// Main
this.elem = elem
this.ajaxData = {} // raw hash provided by backend
this.mapObjects = [] // array of google.maps.Polyline/MarkerWithLabel/etc objects
this.overlays = []
this.googleMap; // new google.maps.Map(... object
}
</code></pre>
<p>On the ruby side (backend), we have these files under app/models:</p>
<pre><code>├── map
│ ├── gig_edit_map.rb
│ ├── gig_map.rb
│ ├── tickets_map.rb
│ ├── courier_map.rb
│ ├── warehouses_map.rb
│ ├── drivers_map.rb
│ └── geo_json.rb
├── map.rb
</code></pre>
<p>I made map.rb is to be like a root namespace, much like how a gem developer would structure his <code>lib</code> directory. </p>
<pre class="lang-ruby prettyprint-override"><code># app/models/map.rb
# frozen_string_literal: true
# Maps - shown in various pages of the web-app.
#
module Map
DEFAULT_SETTINGS = {
width: '100%',
height: '400px',
map_type_id: 'satellite',
prevent_overzoom: true,
prevent_overzoom_gt: 16,
singular_zoom: nil,
poll: -1 # tbd
}.freeze
end
</code></pre>
<p>Mixins are a powerful concept in ruby, and favored <a href="https://golangbot.com/inheritance/" rel="nofollow noreferrer">by many</a> over inheritance.
<code>geo_json.rb</code> is a mixin that's <code>include</code> ed in most of the <code>.rb</code> files.
To show you how I did a mixins, here's geo_json.rb:</p>
<pre class="lang-ruby prettyprint-override"><code># app/models/map/geo_json.rb
# frozen_string_literal: true
module Map
# GeoJSON is a format for encoding a variety of geographic data structures.
#
# {
# "type": "Feature",
# "geometry": {
# "type": "Point",
# "coordinates": [125.6, 10.1]
# },
# "properties": {
# "name": "Dinagat Islands"
# }
# }
# GeoJSON supports the following geometry types: Point, LineString,
# Polygon, MultiPoint, MultiLineString, and MultiPolygon. Geometric
# objects with additional properties are Feature objects. Sets of
# features are contained by FeatureCollection objects.
#
# The GeoJSON Specification (RFC 7946) In 2015, the Internet Engineering
# Task Force (IETF), in conjunction with the original specification
# authors, formed a GeoJSON WG to standardize GeoJSON. RFC 7946 was
# published in August 2016 and is the new standard specification of the
# GeoJSON format, replacing the 2008 GeoJSON specification.
#
module GeoJson
def geo_json_feature_collection(arr)
raise unless arr.is_a?(Enumerable)
{
'type': 'FeatureCollection',
"features": arr.select(&:valid?).map(&:as_geo_json)
}
end
end
end
</code></pre>
<p>For every web page you would render a map, you would build a corresponding ruby class.
Here's the code for <code>warehouses.rb</code>:</p>
<pre class="lang-ruby prettyprint-override"><code># app/models/map/warehouses_map.rb
# frozen_string_literal: true
module Map
# The map shown at /warehouses
class WarehousesMap
include GeoJson
def initialize(warehouse_id)
@warehouse = Warehouse.find(warehouse_id)
end
def as_json
{ data: data,
settings: settings }
end
def settings
DEFAULT_SETTINGS.dup.merge({ map_type_id: 'hybrid' })
end
def data
geo_json_feature_collection([point_1, point_2, line_string])
end
# aka source
def point_1
Point.new(
@warehouse.latitude,
@warehouse.longitude,
label: "Source - #{@warehouse.name}",
markerIcon: '/images/custom.png'
)
end
# aka destination
def point_2
Point.new(
@warehouse.address.latitude,
@warehouse.address.longitude,
label: "Destination - #{@warehouse.address&.addressable&.city_name}"
)
end
# aka route
def line_string
LineString.new(
points_of_line_string,
snap_to_roads: true
)
end
def coords_of_line_string
@warehouse.positions.order(:location_at).pluck(:latitude, :longitude)
end
def points_of_line_string
coords_of_line_string.map do |lat_lng|
Point.new(lat_lng[0], lat_lng[1])
end
end
end
end
</code></pre>
<p>The <code>maps_controller.rb</code> plays a central role - it's the last mile for the backend code, and serves map settings for incoming Ajax requests originating from map.js:</p>
<pre class="lang-ruby prettyprint-override"><code># app/controllers/api/maps_controller.rb
module Api
class MapsController < ApplicationController
# a json response containing map metadata + pins/polygons for the map
# GET /api/maps/map.json
def map
case params
when warehouses_show_page?
resp = ::Map::WarehouseMap.new(params["map_resource"]).as_json
when admin_warehouses_show_page?
resp = ::Map::WarehouseMap.new(params["map_resource"]).as_json
when redacted_show_page?
resp = ::Map::RedactedMap.new(params["map_resource"]).as_json
when gigs_locations_show_page?
resp = ::Map::GigLocationsMap.new(params["map_resource"]).as_json
when gigs_map_page?
resp = ::Map::GigsMap.new(current_user).as_json
when drivers_index_page?
resp = ::Map::DriversMap.new(current_user, params["map_driver_status_id"]).as_json
when drivers_show_page?
resp = ::Map::DriverMap.new(current_user, params["map_resource"]).as_json
when drivers_edit_page?
resp = ::Map::DriverEditMap.new(current_user, params["map_resource"], params["map_secondary_resource"]).as_json
else
resp = {}
end
resp[:settings].transform_keys!{|k|k.to_s.camelize(:lower)}
render json: resp
end
private
def warehouses_show_page?
->(params) { params["map_controller"] == "warehouses" }
end
def admin_warehouses_show_page?
->(params) { params["map_controller"] == "admin/warehouses" }
end
def redacted_show_page?
->(params) { params["map_controller"] == "driver/tickets" }
end
def gigs_locations_show_page?
->(params) { params["map_controller"] == "gigs/locations" }
end
def gigs_map_page?
->(params) { params["map_controller"] == "gigs" }
end
def drivers_index_page?
->(params) { params["map_controller"] == "drivers" && params["map_action"] == "index" }
end
def drivers_show_page?
->(params) { params["map_controller"] == "drivers" && params["map_action"] == "show" }
end
def drivers_edit_page?
->(params) { params["map_controller"] == "drivers" && ['edit','update'].include?(params["map_action"]) }
end
end
end
</code></pre>
<p>This is demo of a map that has 'drawability' turned ON:</p>
<p><a href="https://i.stack.imgur.com/LI3Fz.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LI3Fz.gif" alt="drawable"></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T11:19:37.797",
"Id": "241237",
"Score": "1",
"Tags": [
"javascript",
"ruby"
],
"Title": "Building google maps inside a ruby on rails application"
}
|
241237
|
<p>I followed the Algorithms book implementation of quick sort.</p>
<pre class="lang-rust prettyprint-override"><code>pub fn quick_sort<T: PartialOrd>(a: &mut [T]) {
shuffle(a);
let low = 0;
let high = a.len() - 1;
inner_quick_sort(a, low, high);
}
pub fn inner_quick_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize) {
if high <= low {
return;
}
let j = partition(a, low, high);
// to avoid overflow;
let min_j = if j == 0 { 0 } else { j - 1 };
inner_quick_sort(a, low, min_j);
inner_quick_sort(a, j + 1, high);
}
pub fn partition<T: PartialOrd>(a: &mut [T], low: usize, high: usize) -> usize {
let mut i = low + 1;
let mut j = high;
loop {
while a[i] < a[low] {
i += 1;
if i == high {
break;
}
}
while a[j] > a[low] {
j -= 1;
if j == low {
break;
}
}
if i >= j {
break;
}
a.swap(j, i);
i += 1;
j -= 1;
}
a.swap(low, j);
j
}
</code></pre>
<p>First the review is more than welcome, but I was wondering how can I make it more idiomatic rust?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T11:25:46.407",
"Id": "241238",
"Score": "1",
"Tags": [
"rust",
"quick-sort"
],
"Title": "Quick Sort in rust"
}
|
241238
|
<p>I've been learning ReactJS by doing simple games.</p>
<p>I'm doing a memory game which is, for the most part, finished and I'm not sure how I should refactor the code to be better.</p>
<p>The user task is basically to remember the numbers flashed, and then click them, until the user can't hold them in memory anymore.</p>
<p>How should I divide/refactor the code?</p>
<p>Code:</p>
<pre class="lang-js prettyprint-override"><code>
function BoardScene() {
const [gameNumbers, setGameNumbers] = useState([]);
const [isPlayerTurn, setIsPlayerTurn] = useState(false);
const [currentScore, setCurrentScore] = useState(0);
const [bestScore, setBestScore] = useState(0);
const [flashCard, setFlashCard] = useState(null);
const [clickedNumber, setClickedNumber] = useState(null);
const [currentUserIndex, setCurrentUserIndex] = useState(0)
function startGame() {
addNewNumber()
}
function resetGame() {
setGameNumbers([])
setCurrentUserIndex(0)
if (bestScore < gameNumbers.length) return setBestScore(gameNumbers.length)
}
let count = 0;
const blinkCell = () => {
const timerID = setInterval(() => {
if (currentUserIndex === gameNumbers.length) {
clearInterval(timerID)
count = 0;
} else {
setFlashCard(gameNumbers[count])
count++
}
}, 500);
}
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function addNewNumber() {
console.log("Add new number")
let memoryNumber = generateRandomNumber(1, 9)
setGameNumbers(gameNumbers => [...gameNumbers, memoryNumber])
}
function clickedNumberHandle(number) {
setClickedNumber(number)
isMatch(number)
}
function isMatch(number) {
if (number === gameNumbers[currentUserIndex]) {
console.log("Correct")
if (currentUserIndex + 1 === gameNumbers.length) {
setCurrentUserIndex(0)
addNewNumber()
blinkCell();
} else {
setCurrentUserIndex(currentUserIndex + 1)
}
} else {
resetGame()
console.log("game over")
}
}
useEffect(() => {
blinkCell()
}, [gameNumbers])
return (
<>
<div className="game-container">
<div className="testing-stuff">
<div>
<button onClick={startGame}>Start Game</button>
</div>
<div onClick={addNewNumber}>
<button>Add new number</button>
</div>
<div>
<span>Game numbers: </span>
{gameNumbers.map((item, i) => {
return <span key={i}>{item}</span>
})}
</div>
<div>
<span>User Turn: {isPlayerTurn ? "True" : "False"}</span>
</div>
<div>
<span>Score: {gameNumbers.length}</span>
</div>
</div>
<div className="board">
{Array(9).fill().map((x, i) => {
return (
<Cell key={i} onClick={() => clickedNumberHandle(i + 1)} number={i + 1} active={i + 1 === flashCard ? true : false} />
)
})}
</div>
<div className="stats">
<div className="stats__score-wrap">
<span>Score: </span><span>{gameNumbers.length}</span>
</div>
<div className="stats__bestScore-wrap">
<span>Best Score: </span><span>{bestScore}</span>
</div>
</div>
</div>
</>
);
}
export default BoardScene;
</code></pre>
<p>Heres life example: <a href="https://memory-numbers-game.netlify.app/" rel="nofollow noreferrer">https://memory-numbers-game.netlify.app/</a></p>
<p>Here's GitHub: <a href="https://github.com/AurelianSpodarec/memory-numbers-game/blob/master/src/scenes/BoardScene/BoardScene.js" rel="nofollow noreferrer">https://github.com/AurelianSpodarec/memory-numbers-game/blob/master/src/scenes/BoardScene/BoardScene.js</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:14:05.987",
"Id": "473396",
"Score": "0",
"body": "Move this question to overflow. You will find more support."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:56:54.553",
"Id": "473400",
"Score": "0",
"body": "I thought this was for code review? I'm confused now xd"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T03:32:31.327",
"Id": "473566",
"Score": "0",
"body": "Please give a goal why you want to **divide/refactor** the code. That way, we can contribute in a structured manner. Is it to improve performance? Or is it to improve code readability/maintenance? Or to refactor it into a more functional approach? You get the idea..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T23:02:18.163",
"Id": "473707",
"Score": "0",
"body": "Right. Well, mainly about the modular approach e.g. generateRandomNumber would most likely go in ultilty.js fiel right.\n\nSince this is ReactJS, then it also had hooks, so I was wondering, is the logic I've made fine, or not really? And should I create something like 'gameEngine' and then connect it to the UI, or? Its mainly what you said with code redability/maintenance and functional approach, and I suppose just to make sure the optimization isn't going to kill the webapp after a few min, but I think that shouldn't be an issue here I think."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T11:38:15.990",
"Id": "241239",
"Score": "0",
"Tags": [
"javascript",
"react.js"
],
"Title": "Refactoring a memory numbers game in ReactJS"
}
|
241239
|
<p>I've been refactoring my OCaml solution for <a href="https://projecteuler.net/problem=54" rel="nofollow noreferrer">Project Euler problem 54</a>, which is about comparing poker hands.</p>
<p>While I'm mostly satisfied with my second iteration of the refactor, I stumbled upon <a href="https://zach.se/project-euler-solutions/54/" rel="nofollow noreferrer">two</a> <a href="https://codereview.stackexchange.com/a/111135/220716">solutions</a> in Haskell.
I was surprised by the brevity, and although I'm not familiar with Haskell, I found out that the both solutions utilize the "guard" syntax.</p>
<p>This is my current version in OCaml:</p>
<p><strong>Types & Utilities</strong></p>
<pre class="lang-ml prettyprint-override"><code>open Core
type value = N of int | J | Q | K | A [@@deriving eq, ord]
type suit = char
type card = value * suit
type rank = HighCard | OnePair | TwoPair | ThreeOfAKind | Straight | Flush
| FullHouse | FourOfAKind | StraightFlush (* contains royal flush *)
[@@deriving ord]
type score = rank * value list [@@deriving ord]
let get_suit : card -> suit = snd
let get_value : card -> value = fst
let eval_value = function
| N n -> n
| J -> 11
| Q -> 12
| K -> 13
| A -> 14
let get_eval (card : card) = eval_value (get_value card)
let rev_sort l cmp = List.sort l (fun a b -> -(cmp a b))
</code></pre>
<p><strong>Checking hand</strong></p>
<pre class="lang-ml prettyprint-override"><code>let check_straight hand =
let sorted = List.dedup_and_sort compare_int (List.map hand get_eval) in
if List.length sorted <> 5 then false
else if List.equal ( = ) sorted [2; 3; 4; 5; 14] then true
else List.last_exn sorted - List.hd_exn sorted = 4
let check_flush hand = (
hand
|> List.map ~f:get_suit
|> List.remove_consecutive_duplicates ~equal:equal_char
|> List.length
) = 1
let get_kind (n : int) ?(except : value option = None) (hand : card list) =
let values = List.map hand get_value in
List.find values (fun v ->
match except with
| Some v' when equal_value v v' -> false
| _ -> List.count values (equal_value v) = n
)
</code></pre>
<p><strong>Evaluation</strong></p>
<pre class="lang-ml prettyprint-override"><code>let get_score hand =
let values = rev_sort (List.map hand get_value) compare_value in
let is_straight = check_straight hand in
let is_flush = check_flush hand in
if is_straight && is_flush then (StraightFlush, values) else
match get_kind 4 hand with
| Some v -> (FourOfAKind, v :: values)
| None -> begin
let three_of_a_kind = get_kind 3 hand in
let pair = get_kind 2 hand in
match three_of_a_kind, pair with
| Some v1, Some v2 -> (FullHouse, [v1; v2])
| _ when is_flush -> (Flush, values)
| _ when is_straight -> (Straight, values)
| Some v, None -> (ThreeOfAKind, v :: values)
| None, Some v ->
begin
match get_kind 2 ~except:(Some v) hand with
| Some v' -> (TwoPair, (rev_sort [v; v'] compare_value) @ values)
| None -> (OnePair, v :: values)
end
| None, None -> (HighCard, values)
end
let get_winner hand1 hand2 =
match compare_score (get_score hand1) (get_score hand2) with
| 1 -> 1
| 0 -> 0
| -1 -> 2
| _ -> failwith "Impossible"
</code></pre>
<p><strong>Handle Input</strong></p>
<pre class="lang-ml prettyprint-override"><code>let parse str =
let value = match str.[0] with
| 'T' -> N 10
| 'J' -> J
| 'Q' -> Q
| 'K' -> K
| 'A' -> A
| c -> N (Char.get_digit_exn c)
in
let suit = str.[1] in
(value, suit)
let () =
let wins =
In_channel.read_lines "./054-poker.txt"
|> List.map ~f:(fun line ->
let cards = line |> String.split ~on:' ' |> List.map ~f:parse in
let hand1, hand2 = List.split_n cards 5 in
get_winner hand1 hand2
)
|> List.count ~f:(( = ) 1)
in
printf "Player 1 won %d times\n" wins
</code></pre>
<p>It relies on <a href="https://github.com/janestreet/core" rel="nofollow noreferrer">JaneStreet's Core</a> and the <a href="https://github.com/ocaml-ppx/ppx_deriving" rel="nofollow noreferrer">ppx_deriving</a>.
ppx_deriving is used to generate <code>equal_</code> and <code>compare_</code> methods.
I think it corresponds with <code>deriving (Eq, Ord)</code> of Haskell.</p>
<p>I'm not concerned with performance here, as it runs really fast: 2.5 s for a million lines of input.
However, the code is about 3~4 times longer than the Haskell counterparts.
Since Haskell seems to be generally more concise than OCaml, I don't expect it to get as short.</p>
<p>Yet I still wonder if it can get more concise, without sacrificing performance and/or readability, especially the <code>get_score</code> method of my code.
Is there a way to simplify the <code>get_score</code>, possibly by modifying the data structures I defined?</p>
<p><a href="https://github.com/Zeta611/project-euler/blob/master/054-poker-hands.ml" rel="nofollow noreferrer">This</a> is a link to my code, and I compiled with:</p>
<pre class="lang-sh prettyprint-override"><code>ocamlfind ocamlopt -o 054-poker-hands.out -linkpkg -package core,stdio,ppx_deriving.std -thread 054-poker-hands.ml
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T00:58:56.790",
"Id": "473438",
"Score": "1",
"body": "Or perhaps I should move on to Haskell..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T12:55:59.163",
"Id": "241242",
"Score": "2",
"Tags": [
"programming-challenge",
"haskell",
"playing-cards",
"ocaml"
],
"Title": "Project Euler Problem 54 poker hands in OCaml"
}
|
241242
|
<p>This is the question:</p>
<blockquote>
<p>The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:</p>
<p>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...</p>
<p>Let us list the factors of the first seven triangle numbers:</p>
<pre><code> 1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
</code></pre>
<p>We can see that 28 is the first triangle number to have over five divisors.</p>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<pre><code>import math
def triangulated(num):
x = 0
for num in range(1, num + 1):
x = x + num
return x
l = []
def factors(g):
for n in range(1, triangulated(g) + 1):
if triangulated(g) % n == 0:
l.append(n)
if len(l) > 500:
print(triangulated(g))
print(l)
l.clear()
for k in range(1, 10000000000):
factors(k)
print(k)
</code></pre>
<p>Help optimise this problem.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:32:37.650",
"Id": "473402",
"Score": "0",
"body": "If you've solved this, then the [overview](https://projecteuler.net/overview=012) at Project Euler should be accessible and offers clear optimizations for efficient arrival at the answer."
}
] |
[
{
"body": "<p>The first step of optimization is to remove the duplicate call to triangulated.</p>\n\n<p>The second step of optimization is to pick only the factors that are the divisors and ignore the numbers that aren't.</p>\n\n<p>Start from the reverse in the second function loop, if there is a divisor from reverse, all the factors of that divisor will definitely be a divisor, so find and all of them, so you can skip them in the loop.\nEg, if you start the loop from 200, then all the factors of 200, (100, 50, 25, 4...) can be ignored by adding them to a set. \nIn further loops do it only for the numbers that aren't present in this set.\nThis technique is what is followed in \"Seive of Erastosthenes\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T13:58:54.197",
"Id": "241247",
"ParentId": "241246",
"Score": "2"
}
},
{
"body": "<p>This is not a review, but an extended comment.</p>\n\n<p>Project Euler problems are about math, not programming. To optimize, you need to do the math homework first:</p>\n\n<ol>\n<li>The <span class=\"math-container\">\\$n\\$</span>'th triangular number is <span class=\"math-container\">\\$\\dfrac{n (n+1)}{2}\\$</span>. </li>\n<li>A number of divisors, aka <span class=\"math-container\">\\$\\sigma_0\\$</span>, is a <a href=\"https://en.wikipedia.org/wiki/Multiplicative_function\" rel=\"noreferrer\">multiplicative function</a>. The link to <a href=\"https://en.wikipedia.org/wiki/Divisor_function\" rel=\"noreferrer\">divisor function</a> may also be interesting.</li>\n<li><span class=\"math-container\">\\$n\\$</span> and <span class=\"math-container\">\\$n+1\\$</span> are coprime.</li>\n</ol>\n\n<p>That should be enough to get you started with optimization.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:09:22.060",
"Id": "241261",
"ParentId": "241246",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "241261",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T13:35:55.060",
"Id": "241246",
"Score": "5",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Euler 12: counting divisors of a triangle number"
}
|
241246
|
<p>I've recently discovered patterns and decided to implement Presenter pattern inside a pedagogical project. I spent few days playing around with different implementations, reading some Gem's source code.</p>
<p>However, I'm not sure I'm handling delegation and decoration appropriately. Could anyone give me feedback on my implementation?</p>
<p>Through this example I'll describe <code>BasePresenter</code> and <code>CartPresenter < BasePresenter</code>. You may find it <a href="https://gitlab.com/kawsay/stickers-shop/-/blob/54aa793cdd5d2b65078c792e65bcbf1bd1b20a48/app/presenters/cart_presenter.rb" rel="nofollow noreferrer">here</a> on GitLab if you prefer.</p>
<p>Here's how I did:</p>
<hr>
<p><strong>BASE PRESENTER</strong></p>
<pre class="lang-rb prettyprint-override"><code>class BasePresenter
def initialize(object, template)
@object = object
@template = template
end
# Dynamically defines a method to access @object
def self.presents(name)
define_method(name) do
@object
end
end
# Exposes the @template, allowing usage of helper methods (Drapper's way)
def h
@template
end
</code></pre>
<hr>
<p><strong>DISPLAY MODEL's DATA</strong></p>
<p>Here's a Presenter (<code>CartPresenter</code> goal is to summarize itself, and associated <code>Product</code> and <code>CartProduct</code> inside a <code><table></code>):</p>
<pre class="lang-rb prettyprint-override"><code>class CartPresenter < BasePresenter
presents :cart
def display_cart_amount(tag: :div, **opts)
amount = h.number_to_currency(cart_amount)
h.content_tag tag, class: opts[:class] do
h.content_tag :strong, amount
end
end
def cart_amount
cart.amount
end
</code></pre>
<p><strong>Q)</strong> At this point we can already see that <code>CartPresenter</code> (as others) needs to embed Model's data into HTML. As it violates the Single Responsibility Principle, do I need something like <code>Decorators</code> to take formatted data from Presenters and warp it inside HTML?</p>
<hr>
<p><strong>DELEGATION</strong></p>
<p>A <code>Presenter</code> may also need to delegate methods to associated <code>Presenters</code></p>
<pre class="lang-rb prettyprint-override"><code>class CartPresenter < BasePresenter
...
# Returns a tuple of 2 presenters <strike>based on product.id</strike>
def delegators
=> [
# [<ProductPresenter>, <CartProductPresenter>],
# [<ProductPresenter>, <CartProductPresenter>],
# ...
# ]
products.zip(cart_products)
end
def products
# => <ProductPresenter>
cart.products.map { |p| ProductPresenter.new(p, @template) }
end
def cart_products
# => <CartProductPresenter>
cart.cart_products.map { |cp| CartProductPresenter.new(cp, @template)}
end
</code></pre>
<p><strong>Q)</strong> I'm violating the SRP again. Would you recommend me to refactor this inside <code>BasePresenter</code> or to create a <code>Delegator</code> abstraction? Also, I used to memoized <code>:products</code> and <code>:cart_products</code> inside instance variable, but it make no sens as function are called once and data they returns is used directly (right?).</p>
<hr>
<p><strong>DISPLAY DELEGATORS' DATA</strong></p>
<p>Here's how I'm using those delegators:</p>
<pre class="lang-rb prettyprint-override"><code>class CartPresenter < BasePresenter
...
# Display table's rows to summarize delegators data (Product/CartProduct)
def display_summary
content = delegators.reduce('') do |c, delegators|
c << summaries_row(delegators)
end
content.html_safe
end
def summaries_row(delegators)
h.content_tag :tr, delegated_summaries(delegators)
end
# Each delegators implements ``:summary'' to interface with this method
def delegated_summaries(delegators)
content = delegators.reduce('') do |c, delegator|
c << delegator.summary
end
content.html_safe
end
</code></pre>
<p><strong>Q)</strong> <code>.html_safe</code> adds injection vulnerabilities right? I could try to rigorously validate data, but is there a way <strong>not</strong> to open that breach? As the <code>html_safe</code>'s doc says:</p>
<blockquote>
<p>It is your responsibility to ensure that the string contains no malicious content. [...] It should never be called on user input.</p>
</blockquote>
<hr>
<p><strong>INSTANTIATING PRESENTERS</strong></p>
<p>To instantite the main Presenter inside a Controller, the second way is the best, right? (as <code>@cart</code> is a useless instance variable)</p>
<pre class="lang-rb prettyprint-override"><code># Carts Controller
# 1st way
@cart = Cart.includes(:products, :cart_products, :image_attachments, :blobs).user_cart(current_user)
render 'carts/show', locals: { presenter: CartPresenter.new(@cart, view_context) }
# 2nd
cart = Cart.includes(:products, :cart_products, :image_attachments, :blobs).user_cart(current_user)
@presenter = CartPresenter.new cart, view_context
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>At this point we can already see that CartPresenter (as others) needs to embed Model's data into HTML. As it violates the Single Responsibility Principle, do I need something like Decorators to take formatted data from Presenters and warp it inside HTML?</p>\n</blockquote>\n\n<p>No, HTML belongs in your views. If you need to share HTML, you should create a partial. The presenter pattern wraps methods used in your views in an object to not 'pollute' the presented object and to keep your views more readable. You should not put HTML in your presenter.</p>\n\n<p>In your example, you could have a <code>CartRow</code> (or <code>CartRowPresenter</code>) class and then a <code>_cart_row.html.erb</code> partial. </p>\n\n<blockquote>\n <p>Q: Also, I used to memoized :products and :cart_products inside instance variable, but it make no sens as function are called once and data they returns is used directly (right?).</p>\n</blockquote>\n\n<p>Correct, memoization is \"optimization technique used primarily to speed up computer programs by storing the results of expensive function calls\". If you don't use the computation result several times, there is no need to memoization. </p>\n\n<blockquote>\n <p>Q: .html_safe adds injection vulnerabilities right? I could try to rigorously validate data, but is there a way not to open that breach?</p>\n</blockquote>\n\n<p>As mentioned in my first answer, you should avoid putting HTML in your Presenter (Model, PORO, etc). HTML belongs in your views (and helpers).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-08T09:43:11.827",
"Id": "243550",
"ParentId": "241249",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "243550",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T15:01:50.533",
"Id": "241249",
"Score": "3",
"Tags": [
"ruby",
"design-patterns",
"ruby-on-rails"
],
"Title": "Presenter pattern implementation"
}
|
241249
|
<p>I am going though Cracking the coding interview and trying to improve my coding interview skills.</p>
<p>The question is "Given a directed graph, design an algorithm to find out whether there is a route between two nodes. </p>
<p>I think the run time is N^2 but I could be wrong. </p>
<p>Is there a better way to do BFS? </p>
<pre><code>package TreesAndGraph;
import java.util.LinkedList;
import java.util.Queue;
public class PathSearch
{
public static void main(String[] args)
{
int[][] matrix = {
{0, 1, 0, 0, 1, 1},
{0, 0, 0, 1, 1, 0},
{0, 1, 0, 0, 0, 0},
{0, 0, 1, 0, 1, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0}};
//Following are all true.
System.out.println("0 -> 1: " + routeBetweenNode(matrix, 0, 1));
System.out.println("0 -> 4: " + routeBetweenNode(matrix, 0, 4));
System.out.println("0 -> 5: " + routeBetweenNode(matrix, 0, 5));
System.out.println("0 -> 3: " + routeBetweenNode(matrix, 0, 3));
System.out.println("0 -> 2: " + routeBetweenNode(matrix, 0, 2));
System.out.println("1 -> 1: " + routeBetweenNode(matrix, 1, 1));
System.out.println("2 -> 4: " + routeBetweenNode(matrix, 2, 4));
System.out.println("1 -> 2: " + routeBetweenNode(matrix, 1, 2));
}
private static boolean routeBetweenNode(int[][] matrix, int start, int end)
{
Queue<Integer> q = new LinkedList<>();
if (traverseMatrix(end, q, matrix[start])) return true;
while (!q.isEmpty())
{
Integer activeVisited = q.remove();
if (traverseMatrix(end, q, matrix[activeVisited])) return true;
}
return false;
}
private static boolean traverseMatrix(int end, Queue<Integer> q, int[] currentArray)
{
for (int i = 0; i < currentArray.length; i++)
{
int value = currentArray[i];
if (value == 1)
{
q.add(i);
if (i == end)
{
return true;
}
}
}
return false;
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T16:34:15.453",
"Id": "241253",
"Score": "1",
"Tags": [
"java",
"graph",
"breadth-first-search"
],
"Title": "Routes Between Node, Cracking the coding interview"
}
|
241253
|
<p>I've written this function to read matrices from the ROS parameter server.</p>
<pre><code>void read_matrix_from_param(ros::NodeHandle nodehandle, std::string param, cv::Mat &cv_matrix) {
// 1D vector for temporarily holding matrix elements
std::vector<double> _data;
// matrix dimensions
int _rows, _cols;
// read from param server
nodehandle.getParam(param + std::string("/data"), _data);
nodehandle.getParam(param + std::string("/rows"), _rows);
nodehandle.getParam(param + std::string("/cols"), _cols);
// create cv::Mat and copy into cv_matrix
cv::Mat(_rows, _cols, CV_64F, _data.data()).copyTo(cv_matrix);
}
</code></pre>
<p>called like this:</p>
<pre><code>cv::Mat test_matrix1, test_matrix2;
read_matrix_from_param(private_nh, std::string("camera_matrix"), test_matrix1);
read_matrix_from_param(private_nh, std::string("distortion_coefficients"), test_matrix2);
</code></pre>
<p>This works as expected but my editor gives me a style-guide warning for the function signature.</p>
<pre><code>runtime/references: Is this a non-const reference? If so, make const or use a pointer: cv::Mat &cv_matrix
</code></pre>
<p>So how should this be done? I have tried to do as the style-guide suggests but been unable to get working code again.</p>
|
[] |
[
{
"body": "<p>Assuming the matrix is always empty when passed into the function, the more normal way to write this would be to avoid any side effects and make cv_matrix the return type. i.e</p>\n\n<pre><code>cv::Mat read_matrix_from_param(ros::NodeHandle nodehandle, const std::string& param)\n{\n cv::Mat cv_matrix\n\n ...\n return cv_matrix;\n}\n</code></pre>\n\n<p>As a side point you should pass in param and possibly nodehandle, as const & to avoid unnecessary copies.</p>\n\n<p>If this is not the case and you may pass in non-empty matrices ( I think that wouldn't make sense here ), then I would say using a non-const ref is fine. Alternative you could use a pointer i.e.</p>\n\n<pre><code>void read_matrix_from_param(ros::NodeHandle nodehandle, std::string param, cv::Mat *cv_matrix)\n{\n ...\n\n cv::Mat(_rows, _cols, CV_64F, _data.data()).copyTo(*cv_matrix);\n}\n</code></pre>\n\n<p>called as</p>\n\n<p><code>read_matrix_from_param(private_nh, std::string(\"camera_matrix\"), &test_matrix1);</code></p>\n\n<p>Personally I wouldn't use a pointer and <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-conventional\" rel=\"nofollow noreferrer\">Core C++ Guidelines</a> recommends a reference, but looks like it is the style recommended by google see <a href=\"https://softwareengineering.stackexchange.com/questions/299021/non-optional-pointers-vs-non-const-references-in-c\">https://softwareengineering.stackexchange.com/questions/299021/non-optional-pointers-vs-non-const-references-in-c</a> . If you are using clang-tidy google style guidelines are an option in that I believe so that may be where this warning is coming from.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:13:07.600",
"Id": "241439",
"ParentId": "241254",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241439",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T16:37:10.860",
"Id": "241254",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Write to a CV::Mat from a higher scope within a function"
}
|
241254
|
<p>I'm currently getting data from an API every 15 seconds. This data contains a json with 100-2000 new items every time. Now i don't need all the items that are in there but still quite some of them and i want to store these items in a database. I will probably delete items that are added longer then 5-7 days.</p>
<p>Now i just want to check if the way i'm doing this now is "normal". Because i will run this all day and it's going to get a lot of items.</p>
<p>The script looks like this now:</p>
<pre><code>function fetchItems() {
axios
.get("http://lorem.com")
.then((response) => {
for (let i = 0; i < response.data.stashes.length; i++) {
if (some statements) { //filter some of the stashes here with some statements
stashes.push(filterItems(response.data.stashes[i])); //filter items in stashes and push to new array
}
}
//filtering done
//add all items to database
for (let i = 0; i < stashes.length; i++) {
for (let j = 0; j < stashes[i].items.length; j++) {
let item = { data i want to store };
let sql = 'INSERT INTO items SET ?';
let query = db.query(sql, item, (error, result) => {
if (error) console.log(error);
console.log('item added');
});
}
}
})
.catch((error) => {
console.log(error);
});
}
</code></pre>
<p>Is this the way this should be done? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:23:21.413",
"Id": "473397",
"Score": "2",
"body": "What SQL dialect is this? Does it work?"
}
] |
[
{
"body": "<p>Quickly overviewing the code - it would work.\nIf you are into a more readable approach, I may have just a few (minor) comments:</p>\n\n<p>Declare <code>fetchItems</code> as <code>async</code>, and use <code>await</code> for axios.</p>\n\n<p>Instead of a for loop, use <code>response.data.stashes.filter()</code>.\nAdding all items in separate queries seems odd, is there a way to push all of them in a single transaction? Build the query outside in a helper function.</p>\n\n<p>So your flow may look something like this:</p>\n\n<pre><code>const fetchItems = () => {/*... axios ...*/};\nconst filterItems = (item) => {/*.. return true or false */};\nconst buildQuery = (items) => {/*.. return SQL string ..*/};\n\nasync function execute() {\n try {\n const items = (await fetchItems()).filter(filterItems);\n const query = buildQuery(items);\n await db.query(sql);\n } catch (err) {\n /* handle it */\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T12:01:33.103",
"Id": "241363",
"ParentId": "241255",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:03:14.857",
"Id": "241255",
"Score": "0",
"Tags": [
"javascript",
"api",
"database",
"axios"
],
"Title": "Getting data from API every x seconds and store it in a database"
}
|
241255
|
<p>I wrote a little module for making quick CLIs in Python and I wanted to get your thoughts on areas of improvement (as well as to see what can break it).</p>
<p>One of the issues I had from the start was with looping and multi-threading, I wound up just adding a 1 second delay to make sure I've enough time to do some basic processing, but it seems a bit hackish. I'd like to perform some basic tests on the variable first (e.g. make sure it's not going to cause an overflow) and then actually copy the variable into an entirely separate memory space, although I'm not terribly knowledgeable about python's memory management practices and could use some guidance in the right direction.</p>
<p>A quick brief on how it works, functions which are to be made available to the user are stored in a dictionary with command:function key-pair, if a user enters a command which isn't recognized it will simply print the help screen message, right now it only has support for space separated values. It should be fairly trivial to add additional deliminator functionality like commas, dashes, etc. but I am also a bit worried about adding too many features as well and making it cumbersome to work with.</p>
<p>You can download the source on the <a href="https://github.com/NoahGWood/PyCLI" rel="nofollow noreferrer">GitHub repo</a> or install with pip/pip3:</p>
<pre><code>$ pip3 install -i https://test.pypi.org/simple/ pycli
</code></pre>
<p>And I've included the source code for reference:</p>
<pre><code>#!/usr/bin/python3
"""Basic CLI in Python3"""
import threading as th
import time
cont=True
text=None
class InputThread:
def __init__(self):
global cont
global text
while True:
self.loop_thread()
time.sleep(1)
text=None
cont=True
def loop_thread(self):
global cont
global text
text = input()
cont=False
class CLI:
def __init__(self):
self.cmds = {
'help':self.help,
}
self.init_message = ''
def help(self, args=None):
"""Use help 'command' for more information on a specific command."""
if args==None:
print("Available Commands:")
for key in self.cmds.keys():
print(key)
print(self.help.__doc__)
else:
print(self.cmds[args[0]].__doc__)
def set_message(self, message):
"""Sets the initialization message"""
self.init_message = message
def add_function(self, name, function):
"""Adds a function to the command dictionary"""
self.cmds[name] = function
def cli(self, a):
global cont
args = a.split(' ')
if args[0] not in self.cmds.keys():
print('Command "', args[0], '" Not Found.')
self.help()
else:
if len(args) == 1:
self.cmds[args[0]]()
else:
self.cmds[args[0]](args[1:])
cont=True
def loop(self):
global cont
global text
print(self.init_message)
th.Thread(target=InputThread, args=(), name='user_input_thread', daemon=True).start()
while True:
if not cont:
self.cli(text)
if __name__ in '__main__':
x = CLI().loop()
</code></pre>
<p>and here's an example CLI made using the module:</p>
<pre><code>#!/usr/bin/python3
from pycli import CLI as cli
import random
def random_function(x, y):
"""Generates a random number between x and y.
Usage:
random x y
"""
print(random.randint(x,y))
if __name__ in '__main__':
x = cli()
x.set_message("""Welcome to my super awesome python CLI!
With this new tool you can quickly generate command line
interfaces that capture user input without having to figure
out how to handle all those inputs yourself!
""")
x.add_function('random', random_function)
x.loop()
</code></pre>
<p>I've only tested this on Linux Mint (don't have Windows or Mac), so if you've got one of those OS's can you let me know if the code works as expected and any bugs?</p>
|
[] |
[
{
"body": "<p>Python originally works on windows just like it would on linux, the only differences being system-specific libraries and python extensions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:37:22.727",
"Id": "241264",
"ParentId": "241256",
"Score": "1"
}
},
{
"body": "<p>Your script consumes a lot of CPU due to the while loops. Using just the <code>input</code> function in a loop should be good enough for your purpose. I can't see the need for threading in a script that is quite basic for the moment.</p>\n\n<p>These:</p>\n\n<pre><code>global cont\nglobal text\n</code></pre>\n\n<p>don't belong in your class.\nA class is normally supposed to be self-contained and shouldn't have to rely on global variables defined elsewhere. They should go inside the class body.\nOn the other hand you can pass <strong>parameters</strong> to your class instantiation method or to some class functions.</p>\n\n<p>By the way <code>text</code> is not a good choice of variable since many objects have a <code>text</code> property and be careful with reserved keywords.</p>\n\n<hr>\n\n<p><strong>Exception handling</strong> is lacking. Any quality script should have at least basic exception handling (ten lines of code could do).</p>\n\n<hr>\n\n<p><strong>Validation of user input</strong> is also lacking.\nIf I type anything after <code>help</code> I have a KeyError exception and your script crashes too easily. The dictionary selection is rather clumsy but see below for suggestions.</p>\n\n<hr>\n\n<p><strong>Structure</strong>: I am wondering why you split the code in two classes ?\n<code>InputThread</code> could have been embedded in <code>CLI</code> as a subclass or simply implemented as a function. But they are not independent from each other.</p>\n\n<hr>\n\n<p><strong>Style</strong>: after:</p>\n\n<pre><code>if __name__ in '__main__':\n</code></pre>\n\n<p>the norm is to call <code>main()</code>, so it is customary to have a <code>main</code> method.</p>\n\n<p>You don't call a class like that:</p>\n\n<pre><code>x = CLI().loop()\n</code></pre>\n\n<p>Instead:</p>\n\n<pre><code>x = CLI()\n</code></pre>\n\n<p>with optional parameters inside the parentheses, or you run the code in multiple steps eg:</p>\n\n<pre><code># instantiation\nx = CLI()\n# or:\nx = CLI(prompt=\"Prompt message goes here\")\nx.start()\nx.stop()\n</code></pre>\n\n<p>Because you can perfectly instantiate a class without immediately running it.</p>\n\n<hr>\n\n<p><strong>Naming conventions</strong>: variable names (<code>a</code>, <code>text</code>) are not always well-chosen and <code>meaningful</code>.</p>\n\n<hr>\n\n<p><strong>Misc</strong>: your script does not recognize commands in <strong>uppercase</strong>. I would always convert the commands to lowercase and use <code>strip</code> to trim them (here the <code>split</code> command takes care of that).</p>\n\n<p>Overall impression: I think that this is a way of reinventing the wheel. There are modules that already exist for interactive cli programs, for example <a href=\"https://github.com/CITGuru/PyInquirer\" rel=\"nofollow noreferrer\">PyInquirer</a>. There is also <a href=\"https://pypi.org/project/clint/\" rel=\"nofollow noreferrer\">clint</a> and quite a few others (I have not tested and compared all of them).<br />\nSo I think I would build on the more mature solutions available, unless the problem you are trying to solve cannot be addressed adequately by the solutions that already exist.</p>\n\n<p>An alternative would be to use feature-rich <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a>. Because it can be used not only for command line options but in functions too (I haven't done that yet though but it's worth investigating). To give you an idea have a look at this post on SO: <a href=\"https://stackoverflow.com/a/46418808/6843158\">How to pass parameters to python function using argparse?</a>. Also have a look at the <a href=\"https://docs.python.org/3/library/argparse.html#sub-commands\" rel=\"nofollow noreferrer\">Sub-commands</a> section for more elaborate scenarios. As you can see this module is very powerful and very often underutilized.</p>\n\n<p>It seems to me that it could have fulfilled all your desired functionality, with increased flexibility since the commands could be passed in a different order, as long as the grouping of dependent parameters is respected.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T05:52:13.110",
"Id": "473457",
"Score": "0",
"body": "One of the reasons I'm using threading is to allow me to run (somewhat) asynchronous code to build a hardware abstraction layer, rather than stopping execution to get user input we're simply checking to see if the \"cont\"inue flag is pulled low. My idea is to basically implement something like the Serial.available() function on arduino in Python"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T21:56:24.217",
"Id": "241277",
"ParentId": "241256",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "241277",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:13:29.987",
"Id": "241256",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"console"
],
"Title": "Python Command Line Interface"
}
|
241256
|
<p>So I have been wondering about the standard way of structuring your files/code when it comes to reading data from the driver file.
So what I now have is a buffer that's supposed to store the data that we, as user, requested from the driver file. Since we can't pass arrays to the function (decays to a pointer), what I do is have a struct member variable <code>pRxBuff</code> point to <code>rxBuffer</code> array which is located in <code>main</code> instead of defining inside a function because once the function returns, the array is no longer valid, and inside the <code>Read()</code> function, I populate <code>rxBuffer</code> by dereferencing the data at specific index.</p>
<pre class="lang-c prettyprint-override"><code>
typedef struct {
I2C_TypeDef *pI2Cx;
I2C_Config_t I2C_Config;
I2C_State I2C_State;
uint8_t *txBuffer;
uint8_t *pRxBuffer;
uint8_t rxStartIndex;
uint8_t rxBufferSize;
uint8_t txBufferLength;
uint8_t rxBufferLength;
} I2C_Handle_t;
void ProcessData (uint8_t *rxBuffer) {
uint8_t startIndex = 0;
uint16_t temp;
// process data
uint8_t upperByte = rxBuffer[startIndex] & 0x1F; // mask out the 3 bits
uint8_t signBit = upperByte & 0x10;
if (signBit)
{
upperByte = upperByte & 0xF; // clear out the sign bit
temp = 256 - (upperByte << 4 | rxBuffer[startIndex+1] >> 4);
}
else
{
temp = upperByte << 4 | rxBuffer[startIndex+1] >> 4;
}
}
// sensor.c
void ReadData(I2C_Handle_t *I2C_handle)
{
// start I2C transaction
while (HAL_I2C_StartInterrupt(I2C_TX_BUSY) != I2C_READY);
I2C_handle->I2C_State = I2C_INIT;
// read the data from the sensor
for (int i = 0; i < I2C_handle->rxBufferSize/2; i++)
{
I2C_handle->I2C_State = I2C_INIT;
while (HAL_I2C_StartInterrupt(I2C_RX_BUSY) != I2C_READY);
}
// at this point, I have `rxBuffer` populated with raw data
// now I need to convert this raw data into human-readable
for (int i = 0; i < I2C_handle->rxBufferSize; i+=2)
{
ProcessData(I2C_handle->pRxBuffer, i); // currently not storing processed data anywhere
}
}
// main.c
const int bytesToRead = 6;
static uint8_t rxBuffer[bytesToRead];
I2C_Handle_t i2c;
void I2C_Initilization()
{
i2c.pI2Cx = I2C1;
i2c.I2C_Config.I2C_AckControl = I2C_ACK_ENABLE;
i2c.I2C_Config.I2C_SCLSpeed = I2C_SCL_SPEED_SM;
i2c.I2C_Config.I2C_DeviceAddress = MCP9808_ADDR;
i2c.I2C_Config.I2C_FMDutyCycle = I2C_FM_DUTY_2;
I2C_Init(&i2c);
}
uint16_t read_temp(uint8_t interrupt)
{
uint16_t temperature;
i2c.txBuffer = txBuffer;
i2c.txBufferLength = txSize;
i2c.pRxBuffer = rxBuffer;
i2c.rxStartIndex = 0;
i2c.rxBufferLength = BYTES_PER_TRANSACTION;
i2c.rxBufferSize = bytesToRead;
if (interrupt == SET)
{
temperature = read_temp_interrupt(&i2c);
}
else
{
read_temp_polling(&i2c, bytesToRead);
}
return temperature;
}
int main(void) {
I2C_Initilization();
read_temp(SET);
}
</code></pre>
<p>Issues with this:</p>
<ul>
<li>though I have been able to populate the <code>rxBuffer</code> which I can access
in the main, is this still the right way to do it?</li>
<li>what if <code>rxBuffer</code> is of different size than what the processed data
would need. For e.g: 2 raw bytes represent one processed decimal
value. How do I avoid creating two different buffers each for storing
raw and processed data?</li>
<li>With this approach, I had to create a separate member variable
<code>rxStartIndex</code> to keep track of the index where the data is to be
written.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:50:34.680",
"Id": "473398",
"Score": "3",
"body": "CodeReview does not include questions of the form \"Is there any way?\", but rather \"Is this the best way?\" In other words, you need to come to us with working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:55:21.157",
"Id": "473399",
"Score": "3",
"body": "the code works. maybe I should rephrase the question to \"is this the best way\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T22:20:35.130",
"Id": "473433",
"Score": "2",
"body": "To all who are in the close vote queue. The question meets the guidelines now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T04:45:06.660",
"Id": "473568",
"Score": "0",
"body": "`reading data from the driver[/application] file` starts in the middle of uncharted area: Please provide enough information about the execution environment of the code presented. The current state has me wondering about what \"the device\" shall be good for instead of thinking about the code. (I can take hints like `rx`, `tx`, `I2C`, `sensor`, `temp`: I rather wouldn't guess.)"
}
] |
[
{
"body": "<p>I will give you some tips about defining structs that later are going to be part of a file, of course you can do in other way but this is the way I follow in general. I understand that the following struct is the header of the file.</p>\n\n<pre><code>typedef struct {\n I2C_TypeDef *pI2Cx;\n I2C_Config_t I2C_Config;\n I2C_State I2C_State;\n uint8_t *txBuffer;\n uint8_t *pRxBuffer;\n uint8_t rxStartIndex;\n uint8_t rxBufferSize;\n uint8_t txBufferLength;\n uint8_t rxBufferLength;\n} I2C_Handle_t;\n</code></pre>\n\n<p>In general header files contains some bytes for identification(check libmagic library), the second tip is to have all the types group to avoid misalignment of data. So your struct will be </p>\n\n<pre><code>typedef struct {\n uint32_t magic; // The magic value\n I2C_Config_t I2C_Config;\n I2C_State I2C_State; \n I2C_TypeDef *pI2Cx;\n uint8_t *txBuffer;\n uint8_t *pRxBuffer;\n uint8_t rxStartIndex;\n uint8_t rxBufferSize;\n uint8_t txBufferLength;\n uint8_t rxBufferLength;\n} I2C_Handle_t;\n</code></pre>\n\n<p>Also you can use the attribute packed of the compiler if needed alignment of the data struct.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:02:27.893",
"Id": "241271",
"ParentId": "241258",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:32:34.267",
"Id": "241258",
"Score": "2",
"Tags": [
"c"
],
"Title": "Is there any better way of defining respective data structures to read the sensor data into from driver/application file?"
}
|
241258
|
<p>This application is the front end to a very basic database application. The front end assumes that the back end database would have fields as per the html form.</p>
<p>some concerns on db2form.js I have are:</p>
<ol>
<li><p>some very specific html doc references in the javascript - eg document.forms.searchform.elements.search.innerText = "Search";</p></li>
<li><p>current_contact_idx global variable doesn't seem right.</p></li>
</ol>
<p>As for the css file, that could probably be improved a lot.</p>
<p>Any feedback on this application would be very welcome.</p>
<p>The html page:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Itel Office</title>
<link rel="stylesheet" href="style.css">
<script src="db2form.js"></script>
</head>
<body>
<nav>
<a href="">Contacts</a>
<a href="call_identifier_pretty.html" target="_blank">Call Log</a>
</nav>
<section>
<h1>Contacts</h1>
<p>Enter text below and click Search button to find a contact</p>
<form name="searchform" action="/cgi-bin/database.exe" method="POST">
<label for="rowid">ID: </label>
<input id="rowid" type="text" name="rowid" value="" readonly disabled>
<br>
<label for="name">Name: </label>
<input id="name" type="text" name="name" value="">
<br>
<label for="company">Company: </label>
<input id="company" type="text" name="company" value="">
<br>
<label for="email">Email: </label>
<input id="email" type="email" name="email" value="">
<br>
<label for="ddi">Telephone: </label>
<input id="ddi" type="tel" name="ddi" value="">
<br>
<label for="mobile">Mobile: </label>
<input id="mobile" type="tel" name="mobile" value="">
<br>
<label for="switchboard">alt Telephone: </label>
<input id="switchboard" type="tel" name="switchboard" value="">
<br>
<label for="url">Web: </label>
<input id="url" type="text" name="url" value="">
<br>
<label for="address1">Address line 1: </label>
<input id="address1" type="text" name="address1" value="">
<br>
<label for="address2">Address line 2: </label>
<input id="address2" type="text" name="address2" value="">
<br>
<label for="address3">Address line 3: </label>
<input id="address3" type="text" name="address3" value="">
<br>
<label for="address4">Address line 4: </label>
<input id="address4" type="text" name="address4" value="">
<br>
<label for="postcode">Postcode: </label>
<input id="postcode" type="text" name="postcode" value="">
<br>
<label for="category">Category: </label>
<input id="category" type="text" name="category" value="">
<br>
<label for="notes">Notes: </label>
<textarea id="notes" name="notes"></textarea>
<br>
<div class="buttons">
<button name="search" type="button" onclick="process(document.forms.searchform.elements.search.innerText)">Search</button>
<button name="new" type="button" onclick="process('New')">New</button>
<button name="edit" type="button" onclick="process('Edit')" disabled>Edit</button>
<button name="save" type="button" onclick="process('Save')" disabled>Save</button>
<button name="delete" type="button" onclick="process('Delete')" disabled>Delete</button>
<button name="first" type="button" onclick="process('First')" disabled>First</button>
<button name="next" type="button" onclick="process('Next')" disabled>Next</button>
<button name="prior" type="button" onclick="process('Prior')"disabled>Prior</button>
<button name="last" type="button" onclick="process('Last')" disabled>Last</button>
</div>
</form>
<div id="status">
</div>
</section>
</body>
</html>
</code></pre>
<p>The css file, style.css:</p>
<pre><code>body{
background-color: #ffff00;
}
nav{
box-sizing:border-box;
background-color:#409fff; /* blue we like */
display: inline-block;
width: 20%;
min-width: 125px;
margin-right:15px;
height:100vh;
overflow: auto;
}
nav a{
display:block;
line-height: 45px;
height:45px;
color: #FFFFFF;
text-decoration: none;
padding-left: 50px;
margin:10px 0 10px 5px;
}
section{
display: inline-block;
width:70%;
height:100vh;
overflow: auto;
}
h1{
color: #409fff;
padding: 2px;
margin: 0;
}
form {
display: grid;
grid-template-columns: 150px 1fr;
border: 0;
}
label {
grid-column: 1 / 2;
margin: 0;
padding:0;
border: 0;
}
input{
grid-column: 2 / 3;
margin: 0;
padding:0;
border: 0;
border-radius: 5px;
}
/*input:focus{
background-color: #fcfab1;
}
*/
textarea{
border-radius: 5px;
height: 20px;
}
.buttons{
display: grid;
grid-column: 2 / 3;
grid-gap: 10px;
grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
}
</code></pre>
<p>The javascript file, db2form.js:</p>
<pre><code>let current_contact_idx = -1;
let records = null;
function search_mode() {
// now change button to say Search
document.forms.searchform.elements.search.innerText = "Search";
document.forms.searchform.elements.new.disabled = false;
document.forms.searchform.elements.edit.disabled = true;
document.forms.searchform.elements.save.disabled = true;
document.forms.searchform.elements.delete.disabled = true;
document.forms.searchform.elements.first.disabled = true;
document.forms.searchform.elements.next.disabled = true;
document.forms.searchform.elements.prior.disabled = true;
document.forms.searchform.elements.last.disabled = true;
}
function found_mode() {
// now change button to say Cancel
document.forms.searchform.elements.search.innerText = "Cancel";
document.forms.searchform.elements.new.disabled = false;
document.forms.searchform.elements.edit.disabled = false;
document.forms.searchform.elements.save.disabled = true;
document.forms.searchform.elements.delete.disabled = false;
document.forms.searchform.elements.first.disabled = false;
document.forms.searchform.elements.next.disabled = false;
document.forms.searchform.elements.prior.disabled = false;
document.forms.searchform.elements.last.disabled = false;
}
function new_edit_mode() {
// now change button to say Cancel
document.forms.searchform.elements.search.innerText = "Cancel";
document.forms.searchform.elements.new.disabled = true;
document.forms.searchform.elements.edit.disabled = true;
document.forms.searchform.elements.save.disabled = false;
document.forms.searchform.elements.delete.disabled = true;
document.forms.searchform.elements.first.disabled = true;
document.forms.searchform.elements.next.disabled = true;
document.forms.searchform.elements.prior.disabled = true;
document.forms.searchform.elements.last.disabled = true;
}
function server_response_callback_search(ajax) {
let form_elements = document.forms.searchform.elements;
if(ajax.responseText.length == 0) {
cancel_step(form_elements);
document.getElementById('status').innerHTML = "No record found for your search."
return;
}
console.log("server_response_callback_search response type: " + ajax.getResponseHeader('content-type'));
records = JSON.parse(ajax.responseText);
if (records.contacts.length > 0) {
current_contact_idx = 0;
populate_field(records.contacts[current_contact_idx]);
found_mode();
} else {
current_contact_idx = -1; // reset to no record found
search_mode(); // stay in search mode
}
// display message
if (current_contact_idx == -1) {
document.getElementById('status').innerHTML = "No record found which matches the criteria";
} else {
document.getElementById('status').innerHTML = "Displaying record " + (current_contact_idx + 1).toString() + " of " + records.contacts.length;
}
}
function server_response_callback_update(ajax, rowid) {
console.log("server_response_callback_update response type: " + ajax.getResponseHeader('content-type'));
let form_elements = document.forms.searchform.elements;
search_mode();
// empty all input and textarea fields
for (let element of form_elements) {
if(element.type != 'hidden') {
element.value = "";
}
}
document.getElementById('status').innerHTML = ajax.responseText;;
}
function server_response_callback_insert(ajax) {
console.log("server_response_callback_insert response type: " + ajax.getResponseHeader('content-type'));
let form_elements = document.forms.searchform.elements;
search_mode();
// empty all input and textarea fields
for (let element of form_elements) {
if(element.type != 'hidden') {
element.value = "";
}
}
document.getElementById('status').innerHTML = ajax.responseText;
}
// We need to display what it is that database.exe returns for these cases
function server_response_callback_delete(ajax, rowid) {
console.log("server_response_callback_delete response type: " + ajax.getResponseHeader('content-type'));
let form_elements = document.forms.searchform.elements;
search_mode();
// empty all input and textarea fields
for (let element of form_elements) {
if(element.type != 'hidden') {
element.value = "";
}
}
document.getElementById('status').innerHTML = ajax.responseText;
}
function populate_field(element) {
let formelements = document.forms.searchform.elements;
// formelements is an array
for (let i = 0; i < formelements.length; i++) {
if (formelements[i].name in element) {
formelements[i].value = element[formelements[i].name];
} else {
formelements[i].value = "";
}
}
document.getElementById('status').innerHTML = "Displaying record " + (current_contact_idx + 1).toString() + " of " + records.contacts.length;
}
function edit_step() {
new_edit_mode();
}
function cancel_step(form_elements) {
search_mode();
// empty all input and textarea fields
for (let element of form_elements) {
if(element.type != 'hidden') {
element.value = "";
}
}
document.getElementById('status').innerHTML = "";
}
function new_step(form_elements) {
new_edit_mode();
// empty all input and textarea fields
for (let element of form_elements) {
if(element.type != 'hidden') {
element.value = "";
}
}
document.getElementById('status').innerHTML = "Enter data for new contact, then click Save button to save to database";
}
function extract_form_values(form_elements) {
let query = "";
let first = "yes";
for (let element of form_elements) {
if(["text", "textarea", "tel", "email"].includes(element.type)) {
if(first == "no") {
query += "&";
}
first = "no";
query += element.name;
query += "=";
query += element.value;
}
}
return query;
}
function save_step(form_elements) {
let request_payload = extract_form_values(form_elements);
if(request_payload.length == 0) {
//alert("You need to enter some data to save to database");
document.getElementById('status').innerHTML = "You need to enter some data to save to database";
return;
}
// we determine whether to UPDATE or INSERT based on presence of rowid.
// if a rowid assume updating an existing contact, otherwise a new contact
if (document.forms.searchform.elements.rowid.value == "") {
// go down INSERT route
// remove rowid= from payload
let pos = request_payload.indexOf("rowid=&");
if (pos != -1) {
// remove string
request_payload = request_payload.replace("rowid=&", "");
}
request_payload += "&operation=INSERT";
console.log("sending query to database server: " + request_payload);
// setup ajax callback to handle response
ajax_post("/cgi-bin/database.exe", request_payload, server_response_callback_insert);
} else {
let rowid = parseInt(document.forms.searchform.elements.rowid.value, 10);
request_payload += "&operation=UPDATE";
console.log("sending query to database server: " + request_payload);
// setup ajax callback to handle response
ajax_post("/cgi-bin/database.exe", request_payload, server_response_callback_update, rowid);
}
}
function has_values(form_elements) {
for (let element of form_elements) {
if(["text", "textarea", "tel", "email"].includes(element.type) && element.name != "rowid" && element.value != "") {
return true;
}
}
return false;
}
function insert_step(form_elements) {
// check user actually entered some data in fields
if(!has_values(form_elements)) {
console.log("attempting to insert but no values populated");
document.getElementById('status').innerHTML = "Enter contact details to add a new contact";
return;
}
let request_payload = extract_form_values(form_elements);
if(request_payload.length == 0) {
document.getElementById('status').innerHTML = "You need to enter some update a contact";
return;
}
request_payload += "&operation=INSERT";
console.log("sending query to database server: " + request_payload);
// setup ajax callback to handle response
ajax_post("/cgi-bin/database.exe", request_payload, server_response_callback_insert);
}
function search_step(form_elements) {
let query = extract_form_values(form_elements);
query += query.length == 0 ? "operation=SELECT" : "&operation=SELECT";
console.log("sending query to database server: " + query);
// setup ajax callback to handle response
ajax_post("/cgi-bin/database.exe", query, server_response_callback_search);
}
function ajax_post(url, request, callback, arg) {
// setup ajax callback to handle response
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this, arg);
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(request);
}
function delete_step(form_elements) {
if(form_elements.rowid.value == "") {
const delete_msg = "Form not in correct state to delete a contact";
document.getElementById('status').innerHTML = delete_msg;
alert(delete_msg);
return;
}
let rowid = parseInt(form_elements.rowid.value, 10);
// DELETE FROM table_name WHERE condition;
let request = `rowid=${rowid}&operation=DELETE`;
console.log("sending request to database server: " + request);
let confirmation = confirm("Click Ok if you are absolutely sure you want to delete this contact from the database");
if (confirmation) {
// setup ajax callback to handle response
ajax_post("/cgi-bin/database.exe", request, server_response_callback_delete, rowid);
}
}
function process(buttontext) {
console.log(`buttontext=${buttontext}`);
let form_elements = document.forms.searchform.elements;
if (buttontext == "New") {
new_step(form_elements);
}else if (buttontext == "Edit") {
edit_step();
} else if (buttontext == "Save") {
save_step(form_elements);
} else if (buttontext == "Search") {
search_step(form_elements);
} else if (buttontext == "Cancel") {
cancel_step(form_elements);
} else if (buttontext == "Delete") {
delete_step(form_elements);
} else if (buttontext == "First") {
if (records.contacts.length != 0) {
current_contact_idx = 0;
populate_field(records.contacts[current_contact_idx]);
}
} else if (buttontext == "Next") {
if (records.contacts.length > (current_contact_idx + 1)) {
populate_field(records.contacts[++current_contact_idx]);
} else {
document.getElementById('status').innerHTML = "You are on the last record";
}
} else if (buttontext == "Prior") {
if (current_contact_idx > 0) {
populate_field(records.contacts[--current_contact_idx]);
} else {
document.getElementById('status').innerHTML = "You are on the first record";
}
} else if (buttontext == "Last") {
if (records.contacts.length != 0) {
current_contact_idx = records.contacts.length - 1;
populate_field(records.contacts[current_contact_idx]);
}
} else {
document.getElementById('status').innerHTML = "something has gone wrong - button text incorrectly set";
}
}
// user can press Enter key to invoke search, Esc key to cancel (go back to ready to search mode)
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
var isEnter = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
isEnter = (evt.key === "Enter");
} else {
isEscape = (evt.keyCode === 27);
isEnter = (evt.keyCode === 13);
}
if (isEscape) {
// only handle Escape if Cancel button enabled
if(document.forms.searchform.elements.search.innerText == "Cancel") {
process("Cancel");
}
} else if (isEnter) {
// only handle Enter if Search button enabled
if(document.forms.searchform.elements.search.innerText == "Search") {
process("Search");
}
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T11:36:33.817",
"Id": "473487",
"Score": "0",
"body": "What is `/cgi-bin/database.exe`? The hacker in me gets all warm and fuzzy when it sees an executable exposed to the internet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T14:58:40.757",
"Id": "473503",
"Score": "0",
"body": "@konijn You think this is less secure than if for example action was: /cgi-bin/database.pl or how about /cgi-bin/database.cgi?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:14:52.953",
"Id": "473505",
"Score": "0",
"body": "Yup, now I know you run Windows. https://owasp-aasvs.readthedocs.io/en/latest/requirement-8.1.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:20:00.840",
"Id": "473506",
"Score": "0",
"body": "@konijn Good point, noted"
}
] |
[
{
"body": "<p>On the Javascript side of things:</p>\n\n<p>Don't use inline handlers, they have <a href=\"https://stackoverflow.com/a/59539045\">way too many problems</a> to be worth using. Instead, attach listeners with Javascript and <code>addEventListener</code> instead.</p>\n\n<p>Since on every button click including <code>Search</code>, you want to pass the text content of the button to <code>process</code>, you can do that concisely by examining the <code>textContent</code> of the clicked button inside the handler.</p>\n\n<p>It's generally preferable to select elements with <code>querySelector</code> (which accepts concise, flexible CSS strings) rather than going through <code>document.forms</code>:</p>\n\n<pre><code>document.querySelector('.buttons').addEventListener('click', ({ target }) => {\n if (!target.matches('button')) return;\n process(target.textContent);\n});\n</code></pre>\n\n<p>Using the above code will allow you to remove <em>all</em> inline handlers from the <code>.buttons > button</code> elements, including the <code>onclick=\"process(document.forms.searchform.elements.search.innerText)\"</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const process = console.log;\ndocument.querySelector('.buttons').addEventListener('click', ({ target }) => {\n if (!target.matches('button')) return;\n process(target.textContent);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"buttons\">\n <button name=\"search\" type=\"button\">Search</button>\n <button name=\"new\" type=\"button\">New</button>\n <button name=\"edit\" type=\"button\" disabled>Edit</button>\n <button name=\"save\" type=\"button\" disabled>Save</button>\n <button name=\"delete\" type=\"button\" disabled>Delete</button>\n <button name=\"first\" type=\"button\" disabled>First</button>\n <button name=\"next\" type=\"button\" disabled>Next</button>\n <button name=\"prior\" type=\"button\" disabled>Prior</button>\n <button name=\"last\" type=\"button\" disabled>Last</button>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Best to use <code>textContent</code>, the standard way to extract text from an element, not <code>innerText</code>, a peculiar property from Internet Explorer that has <a href=\"http://perfectionkills.com/the-poor-misunderstood-innerText/\" rel=\"nofollow noreferrer\">pretty strange behavior</a>. <code>innerText</code> is almost never what you want.</p>\n\n<p>Rather than selecting the buttons over and over again in <code>search_mode</code>, <code>found_mode</code>, <code>new_edit_mode</code>, consider selecting them <em>once</em>, and construct an object indexed by element type instead:</p>\n\n<pre><code>const buttons = {};\nfor (const button of document.querySelectorAll('.buttons > button')) {\n buttons[button.textContent.toLowerCase()] = button;\n}\n\nfunction enableDisableButtons(newVal) {\n for (const button of buttons) {\n button.disabled = newVal;\n }\n}\nfunction search_mode() {\n buttons.search.textContent = 'Search';\n enableDisableButtons(true);\n buttons.new.disabled = false;\n}\n\nfunction found_mode() {\n buttons.search.textContent = 'Cancel';\n enableDisableButtons(false);\n buttons.save.disabled = true;\n}\n\nfunction new_edit_mode() {\n buttons.search.textContent = 'Cancel';\n enableDisableButtons(true);\n buttons.save.disabled = false;\n}\n</code></pre>\n\n<p>You can also save a reference to the <code>status</code> element instead of re-selecting it frequently.</p>\n\n<pre><code>const status = document.querySelector('#status');\n// ...\nstatus.innerHTML = \"Displaying record \" + (current_contact_idx + 1).toString() + \" of \" + records.contacts.length;\n</code></pre>\n\n<p>The above code also points to another issue - unless you're <em>deliberately</em> inserting HTML markup, you should set text content of elements by assigning to <code>textContent</code>, not <code>innerHTML</code>. Using <code>innerHTML</code> can result in arbitrary code execution if the code is untrustworthy, in addition to being slower than <code>textContent</code> and more confusing for script readers. So, for the above, you'd want to instead do</p>\n\n<pre><code>status.textContent = \"Displaying record \" + (current_contact_idx + 1).toString() + \" of \" + records.contacts.length;\n</code></pre>\n\n<p>In your <code>process</code> function, rather than a whole bunch of <code>if</code>/<code>else</code> checks on the argument, you could consider making an object indexed by the button text instead, whose values are the function you'd want to run when that button needs to be processed. In the handler, just look up the function on the object and run it:</p>\n\n<pre><code>const actionsByButtonText = {\n New: new_step,\n Edit: edit_step,\n Save: save_step,\n // ...\n};\nfunction process(buttontext) {\n console.log(`buttontext=${buttontext}`);\n const fn = actionsByButtonText[buttontext];\n if (fn) fn();\n else status.textContent = \"something has gone wrong - button text incorrectly set\";\n}\n</code></pre>\n\n<p>(No need to pass <code>form_elements</code> to those functions - they can iterate through the <code>buttons</code> object above, it doesn't make much sense as an argument, since it never changes)</p>\n\n<p>It looks like you're using <code>let</code> by default when declaring variables. Best to <a href=\"https://www.vincecampanale.com/blog/2017/06/22/const-or-let/\" rel=\"nofollow noreferrer\">always use <code>const</code></a> - don't use <code>let</code> unless you have to reassign, and never use <code>var</code> (like in your <code>ajax_post</code>). Using <code>const</code> indicates to later readers of the script, including you, that the variable name will never be reassigned, which results in less cognitive overhead than permitting reassignment with <code>let</code>.</p>\n\n<p>In Javascript, variables are almost always named using <code>camelCase</code>, which you might want to consider if you want to conform.</p>\n\n<p>The script is <em>a bit long</em> - originally, 371 lines. Once you have a script with more than 3-4 functions, I'd strongly consider organizing it using modules instead. Having separate modules which each do their own thing is more maintainable than having one big file. Modules are also useful because the dependencies between them are explicit, rather than everything being global and being able to potentially reference everything else - that can make things a bit confusing when the code isn't trivial. Look into something like <a href=\"https://webpack.js.org/\" rel=\"nofollow noreferrer\">webpack</a>.</p>\n\n<p>You should also consider using proper indentation in the HTML, it'll make the structure more readable at a glance. Eg, this:</p>\n\n<pre><code> </nav>\n <section>\n <h1>Contacts</h1>\n\n<p>Enter text below and click Search button to find a contact</p>\n<form name=\"searchform\" action=\"/cgi-bin/database.exe\" method=\"POST\">\n<label for=\"rowid\">ID: </label>\n<input id=\"rowid\" type=\"text\" name=\"rowid\" value=\"\" readonly disabled>\n</code></pre>\n\n<p>should probably be</p>\n\n<pre><code></nav>\n<section>\n <h1>Contacts</h1>\n <p>Enter text below and click Search button to find a contact</p>\n <form name=\"searchform\" action=\"/cgi-bin/database.exe\" method=\"POST\">\n <label for=\"rowid\">ID: </label>\n <input id=\"rowid\" type=\"text\" name=\"rowid\" value=\"\" readonly disabled>\n ...\n</code></pre>\n\n<p>There are other improvements that can be made as well, but this should be a good start.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T01:12:12.787",
"Id": "241280",
"ParentId": "241259",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241280",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:38:03.017",
"Id": "241259",
"Score": "3",
"Tags": [
"javascript",
"css",
"html5"
],
"Title": "Simple html5/javascript web database application front end"
}
|
241259
|
<p>I'm drawing a background into kivy, and then wrap and place a transparent image on top of it. Each second I move the location of the transparent a little bit. </p>
<pre><code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.image import Image
from kivy.clock import Clock
class ScrollApp(App):
def build(self):
self.bkg = Background()
self.clock = Clock.schedule_interval(self.bkg.scroll_texture, 1)
return self.bkg
class Background(Widget):
plx_2 = ObjectProperty(None)
def __init__(self, **kwargs):
super().__init__(**kwargs)
# set as texture
self.plx_2 = Image(source=r"assets\plx-2.2.png").texture
self.plx_2.wrap = 'repeat'
self.plx_2.uvsize = (1,-1)
def scroll_texture(self, time_passed):
# update uvpos
x,y = self.plx_2.uvpos
x = x - 0.05 % 1 # this magic number will change later
self.plx_2.uvpos = (x, y)
# redraw the image
texture = self.property('plx_2')
texture.dispatch(self)
if __name__=='__main__':
ScrollApp().run()
</code></pre>
<p>And the <code>.kv</code> file:</p>
<pre><code>#:kivy 1.11.1
<Background>:
canvas.before:
Rectangle:
size : self.size
pos : self.pos
source: "assets\plx-1.png"
Rectangle:
size : self.size
texture: self.plx_2
</code></pre>
<p>The code works, but I feel very odd about the way I'm redrawing the texture with dispatching itself as an event. Is there a better way? Second, now if I were to add multiple transparent images on top, I would have to add a lot of code. Is there a a better way than just adding another <code>Rectangle</code> in the <code>.kv</code> file, adding another <code>ObjectProperty</code> in the <code>Background</code> class etc, etc.?</p>
|
[] |
[
{
"body": "<p>The only really odd thing I see is this:</p>\n\n<pre><code>x - 0.05 % 1\n</code></pre>\n\n<p>Modulation takes precedence over subtraction, and <code>0.05 % 1 == 0.05</code>, so the modulation has no effect. Is this what you intended?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:39:46.187",
"Id": "473592",
"Score": "1",
"body": "I intended it to constrain x between 0 and 1, by only giving me the remainder. It should use brackets to first execute the `x-0.05`. Thanks for the catch!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T16:44:09.290",
"Id": "241306",
"ParentId": "241260",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T17:47:22.367",
"Id": "241260",
"Score": "2",
"Tags": [
"python",
"kivy"
],
"Title": "Scrolling background in kivy"
}
|
241260
|
<p>This is my first question on this website and I hope it goes well.</p>
<p>I have created a <strong>Kotlin</strong> factory pattern and I am using it <strong>very</strong> frequently. the code I use it consists of functions inside a class. This is not a static class however, it does not mutate any field inside this class. </p>
<p>When I look at this code, I can tell there is a pattern, so I thought I could improve it. That's why I am asking this question, for ideas & thoughts on how to improve the structure. The code is the following</p>
<pre class="lang-kotlin prettyprint-override"><code>class Client() {
fun dispatchFollowEvent(followerID: Int, destination: Server, callback: (success: Any?) -> Unit) {
val packet: FollowUserPacket = this.factory.makePacket(PacketType.FOLLOW_USER) as FollowUserPacket
packet.payload = FollowUserPacket.FollowUserPayload(this, followerID)
sendToServer(packet, this, destination, callback)
}
fun dispatchRegisterEvent(destination: Server) {
val packet: RegistrationPacket = this.factory.makePacket(PacketType.REGISTRATION) as RegistrationPacket
packet.payload = RegistrationPacket.RegistrationPayload(this)
sendToServer(packet, this, destination)
}
fun dispatchUploadEvent(image: String, destination: Server) {
val packet: UploadImagePacket = this.factory.makePacket(PacketType.UPLOAD_IMAGE) as UploadImagePacket
packet.payload = UploadImagePacket.UploadImagePayload(this, image)
sendToServer(packet, this, destination)
}
fun dispatchListUsersEvent(destination: Server, callback: (usersIDs: Any?) -> Unit) {
val packet: ListUsersPacket = this.factory.makePacket(PacketType.LIST_USER_IDS) as ListUsersPacket
packet.payload = ListUsersPacket.ListUsersPayload(this)
sendToServer(packet, this, destination, callback)
}
fun dispatchGetFollowRequestsEvent(destination: Server, callback: (requests: Any?) -> Unit) {
val packet: GetFollowRequestsPacket = this.factory.makePacket(PacketType.GET_FOLLOW_REQUESTS) as GetFollowRequestsPacket
packet.payload = GetFollowRequestsPacket.GetFollowRequestsPayload(this)
sendToServer(packet, this, destination, callback)
}
}
</code></pre>
<p>The class is simplified just so that it can be easier to read. I'm sure that all of you can see a pattern in this code, but it's beyond my knowledge to know how to make it more structured. </p>
<p>Do not worry about the functionality, the focus of this question is about improving the structure.</p>
<p>The factory code</p>
<pre class="lang-kotlin prettyprint-override"><code>class PacketFactory : Serializable {
@Throws(Exception::class)
fun makePacket(type: PacketType): Packet {
return when (type) {
PacketType.REGISTRATION -> RegistrationPacket()
PacketType.UPLOAD_IMAGE -> UploadImagePacket()
PacketType.LIST_USER_IDS -> ListUsersPacket()
PacketType.FOLLOW_USER -> FollowUserPacket()
PacketType.GET_FOLLOW_REQUESTS -> GetFollowRequestsPacket()
else -> throw Exception("Type is not provided for the factory!")
}
}
}
</code></pre>
<p>The sendToServer function</p>
<pre class="lang-kotlin prettyprint-override"><code>fun sendToServer(
payload: Packet,
sender: Client,
receiver: Server,
callback: ((data: Any?) -> Unit)? = null
): Unit {
// Code that sends payload to receiver and then invokes the callback
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T21:07:05.180",
"Id": "473422",
"Score": "3",
"body": "Welcome to code review. Right now this question is off-topic because the code for some of the functions are missing. Specifically we need to see the functions `sendToServer()`, the function `facory.makePacket()`, and probably the definitions of the class `packet`. Currently there is not enough code to review and provide good suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T22:37:58.040",
"Id": "473435",
"Score": "4",
"body": "\"The class is simplified just so that it can be easier to read.\" Please don't do that. The devil is in the details; hiding these details causes the likely hood of an incorrect answer to increase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T08:11:34.910",
"Id": "473468",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>First of all, a client-server relationship is kind of a 1:1 relation. That means that the client should probably have a connection to a server (or, if abstracted, a server) to talk with. Currently you are using a <code>server</code> parameter, but I would argue that this should be a field. This will also free one parameter of <em>every</em> method. Furthermore, currently it seems allowed to call just any server from the client class. First register and then call a totally different server.</p>\n\n<p>Furthermore, if such a generic & relatively static parameter is present then it should probably be the first parameter. Currently the location of the <code>server</code> parameter seems to change per function, and that makes reading the functions harder.</p>\n\n<p>The <code>dispatchFollowEvent</code> seems to be used to \"follow a user\", but that's only clear to me after reading the code. Similarly we have an <code>upload</code> method that seemingly uploads an image. Why not just <code>followUser</code> or <code>uploadImage</code>? It's a <em>client</em>, we expect it to \"dispatch\" and that it creates an \"event\" at the server.</p>\n\n<p>I'm not sure why you would use a factory in above code. The <code>makePacket</code> code is really just an intermediate to the specific packets that you need anyway. So now you go: \"packet specific method -> packet enum -> packet specific method\". Sure you <strong>can</strong> do that, but why should you?</p>\n\n<p>A more grievous thing is that your factory method seems to create partial packets without a payload. That means that packets are initially in an invalid state. The whole idea is that you manufacture concrete products inside a factory.</p>\n\n<p>Another minor issue is the <code>send</code> part of the <code>sendToServer</code> method. A <code>send</code> method generally doesn't receive any data back. If you have a callback handler, why not call it <code>call</code> instead? You can leave the <code>server</code> part out of it maybe, that a client calls a server seems kind of logical.</p>\n\n<p>Unfortunately I have to leave it at this, not just because it is late, but also because I don't think I've seen enough of your code / architecture to refactor the given code. It's not terrible code or anything, but it seems rather over-engineered and especially the naming suffers from it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T13:58:49.867",
"Id": "476437",
"Score": "0",
"body": "Thank you! I agree with everything you said! I won't refactor this code because its a university project and the project is over, but I will remember your words. My initial question still remains unanswered though. My question is \"How can I make the client code more structured since I can see. a pattern which in the end of the day is just copy and pasting\". I thought about. making a function dispatch and then pass the type and. figure out then what to do. In any case, thanks for your. answer, you helped me a lot in realizing what things are wrong and what things are not needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T22:24:25.927",
"Id": "476493",
"Score": "0",
"body": "At least removing the server parameter will get you less copy paste. You can also remove `this` from that call, and assume `this`. For the other parts you first have to refactor the factory code I think; as indicated, I don't think I have enough info to propose a way of handling that. Glad if this was of help to you :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-17T00:54:50.160",
"Id": "242435",
"ParentId": "241263",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:30:16.407",
"Id": "241263",
"Score": "1",
"Tags": [
"performance",
"kotlin",
"factory-method"
],
"Title": "Using a factory pattern many times"
}
|
241263
|
<p>I'm implementing some basic data structures in Python. How does my LinkedList look like?
My experience in testing is quite low and I would really appreciate a review.</p>
<p>Implementation:</p>
<pre><code>class LinkedList:
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def __eq__(self, other):
return self.value == other.value and self.next == other.next
EMPTY_LIST_ERROR_MSG = 'List is empty!'
def __init__(self):
self.__head = None
def add_first(self, value):
""" A -> B -> C -> D -> None
E -> A -> B -> C -> D -> None"""
new_node = self.Node(value=value)
if self.__head:
new_node.next = self.__head
self.__head = new_node
def add_last(self, value):
""" A -> B -> C -> D -> None
A -> B -> C -> D -> E -> None"""
new_node = self.Node(value)
last_node = None
for node in self.__node_iter():
last_node = node
if last_node:
last_node.next = new_node
else:
self.__head = new_node
def insert_after(self, item, value):
"""Inserting F after C:
A -> B -> C -> D -> None
A -> B -> C -> F -> D -> None"""
if not self.__head:
raise IndexError(self.EMPTY_LIST_ERROR_MSG)
node = self.__head
while node and node.value != item:
node = node.next
if node:
node_next = node.next
node.next = self.Node(value, node_next)
else:
raise ValueError(f'No such item {item}')
def remove(self, value):
""" Removing C:
A -> B -> C -> D -> None
A -> B -> D -> None"""
if not self.__head:
raise IndexError(self.EMPTY_LIST_ERROR_MSG)
if self.__head.value == value:
self.remove_first()
else:
previous = self.__head
node = self.__head.next
while node and node.value != value:
previous = node
node = node.next
if node:
previous.next = node.next
else:
raise ValueError(f'No such value: {value}')
def remove_first(self):
""" A -> B -> C -> D -> None
B -> C -> D -> None"""
if not self.__head:
raise IndexError(self.EMPTY_LIST_ERROR_MSG)
self.__head = self.__head.next
def remove_last(self):
""" A -> B -> C -> D -> None
A -> B -> C -> None"""
if not self.__head:
raise IndexError(self.EMPTY_LIST_ERROR_MSG)
previous = None
node = self.__head
while node.next:
previous = node
node = node.next
if previous:
previous.next = None
else:
self.__head = None
def reverse(self):
""" A -> B -> C -> D -> None
D -> C -> B -> A -> None"""
previous = None
node = self.__head
while node:
node_next = node.next
node.next = previous
previous = node
node = node_next
self.__head = previous
def __node_iter(self):
node = self.__head
while node:
yield node
node = node.next
def __contains__(self, item):
for value in self:
if item == value:
return True
return False
def __len__(self):
count = 0
for _ in self:
count += 1
return count
def __str__(self):
return "[{}]".format(", ".join(map(str, self)))
def __iter__(self):
""":returns values iterator"""
return iter(map(lambda node: node.value, self.__node_iter()))
</code></pre>
<p>Tests:</p>
<pre><code>import pytest
from linear.linked_list import LinkedList
class TestLinkedList:
def setup_method(self):
"""[12, 8, 2, 5]"""
self.prepared_linked_list = LinkedList()
self.prepared_linked_list.add_first(5)
self.prepared_linked_list.add_first(2)
self.prepared_linked_list.add_first(8)
self.prepared_linked_list.add_first(12)
assert list(self.prepared_linked_list) == [12, 8, 2, 5]
def test_add_first(self):
linked_list = LinkedList()
linked_list.add_first(1)
assert list(linked_list) == [1]
linked_list.add_first(3)
assert list(linked_list) == [3, 1]
linked_list.add_first(5)
assert list(linked_list) == [5, 3, 1]
linked_list.add_first(4)
assert list(linked_list) == [4, 5, 3, 1]
def test_add_last(self):
linked_list = LinkedList()
linked_list.add_last(1)
assert list(linked_list) == [1]
linked_list.add_last(3)
assert list(linked_list) == [1, 3]
linked_list.add_last(5)
assert list(linked_list) == [1, 3, 5]
linked_list.add_last(4)
assert list(linked_list) == [1, 3, 5, 4]
def test_insert_after(self):
self.prepared_linked_list.insert_after(2, 4)
assert list(self.prepared_linked_list) == [12, 8, 2, 4, 5]
self.prepared_linked_list.insert_after(2, 3)
assert list(self.prepared_linked_list) == [12, 8, 2, 3, 4, 5]
self.prepared_linked_list.insert_after(12, 1)
assert list(self.prepared_linked_list) == [12, 1, 8, 2, 3, 4, 5]
self.prepared_linked_list.insert_after(5, 50)
assert list(self.prepared_linked_list) == [12, 1, 8, 2, 3, 4, 5, 50]
with pytest.raises(ValueError):
self.prepared_linked_list.insert_after(16, 40)
linked_list = LinkedList()
with pytest.raises(IndexError):
linked_list.insert_after(5, 12)
linked_list.add_first(3)
linked_list.insert_after(3, 4)
assert list(linked_list) == [3, 4]
def test_remove_first(self):
self.prepared_linked_list.remove_first()
assert list(self.prepared_linked_list) == [8, 2, 5]
self.prepared_linked_list.remove_first()
assert list(self.prepared_linked_list) == [2, 5]
self.prepared_linked_list.remove_first()
assert list(self.prepared_linked_list) == [5]
self.prepared_linked_list.remove_first()
assert list(self.prepared_linked_list) == []
with pytest.raises(IndexError):
self.prepared_linked_list.remove_first()
def test_remove_last(self):
self.prepared_linked_list.remove_last()
assert list(self.prepared_linked_list) == [12, 8, 2]
self.prepared_linked_list.remove_last()
assert list(self.prepared_linked_list) == [12, 8]
self.prepared_linked_list.remove_last()
assert list(self.prepared_linked_list) == [12]
self.prepared_linked_list.remove_last()
assert list(self.prepared_linked_list) == []
with pytest.raises(IndexError):
self.prepared_linked_list.remove_last()
def test_remove(self):
self.prepared_linked_list.remove(2)
assert list(self.prepared_linked_list) == [12, 8, 5]
self.prepared_linked_list.remove(12)
assert list(self.prepared_linked_list) == [8, 5]
with pytest.raises(ValueError):
self.prepared_linked_list.remove(12)
assert list(self.prepared_linked_list) == [8, 5]
self.prepared_linked_list.remove(5)
assert list(self.prepared_linked_list) == [8]
self.prepared_linked_list.remove(8)
assert list(self.prepared_linked_list) == []
with pytest.raises(IndexError):
self.prepared_linked_list.remove(8)
def test_reverse(self):
self.prepared_linked_list.reverse()
assert list(self.prepared_linked_list) == [5, 2, 8, 12]
linked_list = LinkedList()
linked_list.reverse()
assert list(linked_list) == []
linked_list.add_first(5)
linked_list.reverse()
assert list(linked_list) == [5]
def test_contains(self):
assert 12 in self.prepared_linked_list
assert 2 in self.prepared_linked_list
assert 5 in self.prepared_linked_list
assert 8 in self.prepared_linked_list
assert 11 not in self.prepared_linked_list
assert 28 not in self.prepared_linked_list
linked_list = LinkedList()
assert 5 not in linked_list
linked_list.add_first(5)
assert 5 in linked_list
def test_len(self):
assert len(self.prepared_linked_list) == 4
self.prepared_linked_list.remove_last()
assert len(self.prepared_linked_list) == 3
self.prepared_linked_list.remove_first()
assert len(self.prepared_linked_list) == 2
self.prepared_linked_list.remove_first()
assert len(self.prepared_linked_list) == 1
self.prepared_linked_list.remove_last()
assert len(self.prepared_linked_list) == 0
def test_iter(self):
assert next(iter(self.prepared_linked_list)) == 12
iterator = iter(self.prepared_linked_list)
assert next(iterator) == 12
assert next(iterator) == 8
assert next(iterator) == 2
assert next(iterator) == 5
with pytest.raises(StopIteration):
next(iterator)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:40:40.873",
"Id": "473403",
"Score": "3",
"body": "Please fix the indentation in the first code block."
}
] |
[
{
"body": "<h2>Error constants</h2>\n\n<p>There's less value in doing this:</p>\n\n<pre><code>EMPTY_LIST_ERROR_MSG = 'List is empty!'\n</code></pre>\n\n<p>and passing it like</p>\n\n<pre><code> raise IndexError(self.EMPTY_LIST_ERROR_MSG)\n</code></pre>\n\n<p>into a built-in exception. There's more value in making an exception type of your own, maybe derived from <code>IndexError</code>. I don't think it's really worth externalizing such strings into constants unless</p>\n\n<ol>\n<li>the string constant is very long;</li>\n<li>the string constant's purpose cannot be understood by looking at its contents alone; or</li>\n<li>you care about i18n.</li>\n</ol>\n\n<h2>Cascading comparison</h2>\n\n<p>Are you sure that this:</p>\n\n<pre><code> def __eq__(self, other):\n return self.value == other.value and self.next == other.next\n</code></pre>\n\n<p>does what you want? I believe that, as written, due to the reference to <code>next</code> it will cascade to comparing every single value in the list after the current one. This is not likely what you want. If all you want to do is check whether <code>next</code> is the same <em>reference</em> without a cascaded equality comparison, then use <code>is</code> instead of <code>==</code>.</p>\n\n<h2>Private variables</h2>\n\n<p>Use <code>self._head</code> instead of <code>self.__head</code>, which has a different meaning.</p>\n\n<h2>Method names</h2>\n\n<p>Consider attempting to match Python's built-in collection terminology, i.e. <a href=\"https://docs.python.org/3.8/tutorial/datastructures.html#more-on-lists\" rel=\"nofollow noreferrer\"><code>pop</code></a> instead of <code>remove_last</code>. A more useful interface would do what <code>pop</code> does and return the removed item as well.</p>\n\n<h2>Predicate generators</h2>\n\n<pre><code> for value in self:\n if item == value:\n return True\n return False\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return any(item == value for value in self)\n</code></pre>\n\n<p>Also,</p>\n\n<pre><code> count = 0\n for _ in self:\n count += 1\n return count\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return sum(1 for _ in self)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T16:29:03.557",
"Id": "241305",
"ParentId": "241265",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241305",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:37:35.890",
"Id": "241265",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"linked-list"
],
"Title": "Python LinkedList implementation and tests"
}
|
241265
|
<p>I have to find a method (using backtracking) to list all possible combinations, in lexicographical order,of k numbers out of the interval [1,n].. duplicates are not allowed. <br>i.e: input: 5 3<br>output:<br>1 2 3<br>1 2 4<br>1 2 5<br> 1 3 4<br>1 3 5<br>1 4 5<br> 2 3 4<br>2 3 5<br>2 4 5<br>3 4 5</p>
<p>I know <code>using namespace std;</code> is bad practice, but that's the way we've been taught to write code, we always use <code>iostream</code> library and sometimes <code>cmath</code> <code>iomanip</code> and <code>string</code>, so the point is that I don't have a lot of knowledge in C++.. All I would like is a faster method than the one that I implemented, and if you can, don't use advanced syntax.. I understand that "advanced" might mean different things for different people, but maybe the code bellow will give you an uderstanding of the level of C++ knowledge I have</p>
<pre><code>#include <iostream>
using namespace std;
int sol[20], n , el_maxim;
void display()
{
for (int i = 0; i < n; i++)
cout << sol[i] << " ";
cout << endl;
}
int okay()
{
for (int i = 0; i < n - 1; i++)
if (sol[i] >= sol[i + 1])
return 0;
return 1;
}
void bkt(int poz)
{
if (poz == n)
{
okay();
if (okay() == 1)
display();
}
else
for (int i = 1; i <= el_maxim; i++)
{
sol[poz] = i;
bkt(poz + 1);
}
}
int main()
{
cin >> el_maxim >> n;
bkt(0);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Preface:</strong></p>\n\n<blockquote>\n <p>if you can, don't use advanced syntax</p>\n</blockquote>\n\n<p>I understand why you say this, but do not shy away from strange looking syntax. When you encounter something you cannot read, take the time to lookup what the syntax does (even experienced developers do this). The weird looking syntax may be doing useful stuff. And after you understand what's going on, the syntax usually doesn't look weird anymore.</p>\n\n<p><strong>Another algorithm:</strong></p>\n\n<p>First off, for a beginner, this is a great start. It's very simple code which is good.</p>\n\n<p>If you want faster code, the first thing to do is make sure your general approach is reasonable or better yet optimal. Your algorithm generates all possible sets of length <code>K</code> with elements from <code>{1,2,...N}</code> and then checks if the sets are sorted. Note that I have used <code>N</code> for the size of the input set and <code>K</code> for the size of the combinations -- this is a convention I have seen in many places but is different from your code.</p>\n\n<p>There are <span class=\"math-container\">$$K^N$$</span> possible sets of length <code>K</code> from a set of <code>N</code> objects. For the same set of <code>N</code> objects, there are <span class=\"math-container\">$$\\frac{N!}{K!(N-K)!}$$</span> combinations. Since the combinations are a subset of the possible sets, they are a smaller set and in many cases they are a much smaller set. Interestingly there are some non integer solutions for <code>K^N < (N choose K)</code> e.g. <code>K</code> = 0.5 and <code>N</code> = 1.5. maybe someone else can shed some light on that. But they key takeaway is that only generating combinations will be a lot faster.</p>\n\n<p>How can you only generate combinations? There's more than one way to do this, but I will describe one way.</p>\n\n<p>Consider the n=5, k=3 example. The set of numbers to maybe print is <code>1,2,3,4,5</code>, and the set of numbers to definitely print is <code>{}</code> (empty set). I'll simplify this as <code>({}, {1,2,3,4,5})</code>. Some of the combinations have <code>1</code> and some don't. So we now have to consider both the possibilities <code>({1},{2,3,4,5})</code> and <code>({}, {2,3,4,5})</code>. We repeat this recursively, and when we have a set of things of size <code>el_maxim</code> (or, by convention, <code>k</code>), we print. In psuedo-code:</p>\n\n<pre><code>void recurse(int indexK, int indexN) {\n if (indexK == K) {\n print(result);\n return;\n }\n\n // \"if there more slots to fill than numbers to fill them\"\n // could also say `if (indexN == N)` ... correct but slower\n if (N - indexN < K - indexK) {\n return;\n }\n\n result[indexK] = indexN;\n\n recurse(indexK + 1, indexN + 1);\n recurse(indexK, indexN + 1);\n}\n</code></pre>\n\n<p>I encourage you to try getting this function to compile and then benchmarking to make sure you see the speedup you would expect. You'll have to try a few different values of N and K. For some inputs <10, the improved algorithm should run 1000s of times faster!</p>\n\n<p><strong>Review of your code:</strong></p>\n\n<p>Since my main advice is to use a better algorithm, I haven't given any specific comments on your code. I'll do that here:</p>\n\n<p>Your program should be based around a function that can generate combinations. The function should take <code>N</code> and <code>K</code> as input, and it should return all the combinations. Something like this:</p>\n\n<pre><code>/// This function generates all combinations of integers {1,2,...,N}\n/// @param N the size of the set\n/// @param K the size of the combinations\nResultType generateCombinations(int N, int K) { ... }\n</code></pre>\n\n<p>Then your <code>main</code> function should call <code>generateCombinations</code>. This has several advantages over your method:</p>\n\n<ul>\n<li><p>The compiler will make sure you set all the inputs. In your version, if you forget to set a global variable, then you'll get the wrong answer.</p></li>\n<li><p>You have a convenient place to put a big comment about what the function does. The comment I've placed above is in Doxygen's format so you can generate documentation from your comments. It also looks pretty good in my opinion.</p></li>\n<li><p>You can easily call the function in several places.</p></li>\n<li><p>You don't have to worry about name collisions.</p></li>\n<li><p>The compiler can optimize arguments better than global variables. In general, compilers are really good with functional code and not so good with code that uses lots of memory.</p></li>\n<li><p>I could go on but I think you get the point.</p></li>\n</ul>\n\n<hr>\n\n<p>Separate printing the combinations from generating the combinations. You've sort of done that with the <code>display</code> function, but not really since anyone who calls <code>bkt</code> is forced to print the result. There are two main ways to do this. The first way is to return a big data structure, and then print it:</p>\n\n<pre><code>std::vector<std::vector<int>> generateCombinations(int N, int K) { ... }\n\nfor (auto& vec : genCombinations(5, 3)) { print(vec); }\n</code></pre>\n\n<p>This way is pretty easy/simple. The downside is it uses a lot of memory.</p>\n\n<p>The second way is to accept an argument that says what to do with each result:</p>\n\n<pre><code>void genCombinations(int N, int K, std::function<void(vector<int>&)> func) { ... }\n\ngenCombinations(5, 3, [](auto& vec) { print(vec); });\n</code></pre>\n\n<p>This is probably harder to read for many people, but it saves a large amount of memory in this case!</p>\n\n<hr>\n\n<p>Your names are a little weird. <code>el_maxim</code> instead of <code>maximum_element</code> or <code>N</code> as dictated by convention. <code>n</code> instead of <code>num_elements</code> or <code>K</code> per the convention. Also <code>bkt</code> and <code>okay</code> seem like they were chosen because they are short rather than because they are good descriptions of what they do.</p>\n\n<hr>\n\n<pre><code>okay();\nif (okay() == 1)\n</code></pre>\n\n<p>Is this intended?</p>\n\n<p><strong>P.S.</strong></p>\n\n<p>I encourage you to rewrite and post another code review using a faster algorithm! You may get more comments on your code rather than on your approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T03:25:04.743",
"Id": "241285",
"ParentId": "241266",
"Score": "1"
}
},
{
"body": "<p>Of course it's too low. You're building <em>all</em> the sequences of n numbers ≤ el_maxim and then display only those increasing. So, for m=5 and n=3 you print ten sequences out of 125, but you build and check all those 125.</p>\n\n<p>Build them incrementally: once you've set the first array element to 1 you only need to iterate from 2 to e_m - (n - 2) for the second element; and once that latter reaches 3, then the third element only goes from 4 to e_m - (n - 3), etc. And you wouldn't need to check them (which btw you currently do twice, first time discarding the result of the check).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T14:48:28.313",
"Id": "473501",
"Score": "0",
"body": "I don't know how to generate them directly, could you share a code snippet please? I tried this:https://ideone.com/K2w9zr"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T17:40:23.520",
"Id": "473522",
"Score": "1",
"body": "nevermind, I managed, thanks!!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T07:03:14.520",
"Id": "241290",
"ParentId": "241266",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T18:45:35.040",
"Id": "241266",
"Score": "2",
"Tags": [
"c++",
"combinatorics",
"backtracking"
],
"Title": "Performance is too low, online compiler wants a faster way to find all possible combinations of k numbers out of 1...n"
}
|
241266
|
<p>So, I happen to know a bit about front-end development, and I'll make a seminar at the university about it where I share that knowledge with my fellow students. A few years ago, I've made a PacMan in JavaScript and SVG. Now I've refactored it in an attempt to make code easier to understand, because I think it may be interesting to students. So, what do you think about it?<br/>
I think it will be more approachable by my fellow students if the comments are in Croatian, rather than English, however, I may be wrong about that.</p>
<pre class="lang-php prettyprint-override"><code><?php
$browser=$_SERVER['HTTP_USER_AGENT'];
if (substr($browser,0,strlen("Opera"))!=="Opera" &&
substr($browser,0,strlen("Mozilla/5.0"))!=="Mozilla/5.0")
exit("Please access this URL with a proper browser!\n");
?>
<!--
Koristeni programski jezici i preporuceni materijali za ucenje:
Javacript - https://www.w3schools.com/js/default.asp
SVG - https://www.w3schools.com/graphics/svg_intro.asp
PHP (vrti se na serveru) - https://www.w3schools.com/php/default.asp
HTML - https://www.w3schools.com/html/default.asp
CSS (inline na nekoliko mjesta) - https://www.w3schools.com/css/default.asp
-->
<html lang="en">
<head>
<title>PacMan in Javacript</title>
<meta name="author" content="Teo Samarzija">
<meta name="description" content="A PacMan game made using SVG and JavaScript, playable on most smartphones.">
<meta name="keywords" content="Retrocomputing, HTML5, PacMan, SVG, JavaScript">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<!-- Sprijeci zoomiranje na smartphonima (ako netko slucajno dodirne neko mjesto u labirintu dvaput umjesto jedanput). -->
<style type="text/css">
#natpis { /*CSS od natpisa za novi level.*/
position:absolute;
background-color:#AAFFFF;
color:red;
top:180px;
width:200px;
height:50px;
border-radius:100%; /*Neka bude u obliku elipse.*/
text-align:center;
font-family:Arial;
font-size:24px;
line-height:50px;
}
#startButton {
background-color:red;
top:275px;
color:yellow;
font-size:36px;
width:200px;
position:absolute;
left:-webkit-calc(50% - (200px / 2)); /*Za Android Stock Browser 4 i Safari 6, oni nece parsirati "calc" ako ne stavimo prefiks.*/
left:calc(50% - (200px / 2));
}
#zaslon {
background:black;
display:block;
width: 300px;
height: 450px;
border:0px;
margin-bottom: 0px;
overflow: hidden; /*Inace ce u Internet Exploreru 11 duhovi doci na bijelu pozadinu kad prolaze kroz onaj prolaz sa strane.*/
}
#bodovi { /*Zuti pravokutnik na kojem pise highscore.*/
position: absolute;
top:458px;
width:300px;
line-height:50px;
font-family: Lucida;
background-color: yellow;
text-align:center;
margin-bottom:5px;
margin-top:0px;
left:-webkit-calc(50% - (300px / 2));
left:calc(50% - (300px / 2));
}
#instructions {
position: absolute;
top:-webkit-calc(458px + 50px + 5px);
top:calc(458px + 50px + 5px);
width:-webkit-calc(100% - 2 * 8px);
width:calc(100% - 2 * 8px);
}
</style>
</head>
<body>
<?php
$datoteka=fopen("pachigh.txt","r");
$highscore=intval(fgets($datoteka));
$player=fgets($datoteka);
fclose($datoteka);
if (strpos($player," ") || strpos($player,"<") || strpos($player,">") ||
strpos($player,"&") || strpos($player,"\t") || strpos($player,"&gt;")
|| strlen($player)==0)
$player="anonymous";
?>
<button id="startButton" onclick="onStartButton()">START!</button>
<center>
<svg id="zaslon">
<defs>
<linearGradient id="leftGradient" x1="0%" x2="100%" y1="0%" y2="0%">
<!-- Boja lijeve tipke. -->
<stop offset="0%" stop-color="gray"/>
<stop offset="100%" stop-color="white"/>
</linearGradient>
<linearGradient id="rightGradient" x1="0%" x2="100%" y1="0%" y2="0%">
<!-- Boja desne tipke. -->
<stop offset="0%" stop-color="white"/>
<stop offset="100%" stop-color="gray"/>
</linearGradient>
<linearGradient id="upGradient" x1="0%" x2="0%" y1="0%" y2="100%">
<!-- Boja gornje tipke. -->
<stop offset="0%" stop-color="gray"/>
<stop offset="100%" stop-color="white"/>
</linearGradient>
<linearGradient id="downGradient" x1="0%" x2="0%" y1="0%" y2="100%">
<!-- Boja donje tipke. -->
<stop offset="0%" stop-color="white"/>
<stop offset="100%" stop-color="gray"/>
</linearGradient>
</defs>
<rect x=130 y=360
fill="url(#upGradient)"
onMouseOver="this.style.fill = 'lightGray'"
onMouseOut="this.style.fill = 'url(#upGradient)'"
width=40 height=40 onClick="onButtonUp()"></rect>
<!-- Gornja tipka -->
<rect x=85 y=405
fill="url(#leftGradient)"
onMouseOver="this.style.fill = 'lightGray'"
onMouseOut="this.style.fill = 'url(#leftGradient)'"
width=40 height=40 onClick="onButtonLeft()"></rect>
<!-- Lijeva tipka -->
<rect x=130 y=405
fill="url(#downGradient)"
onMouseOver="this.style.fill = 'lightGray'"
onMouseOut="this.style.fill = 'url(#downGradient)'"
width=40 height=40 onClick="onButtonDown()"></rect>
<!-- Donja tipka -->
<rect x=175 y=405
fill="url(#rightGradient)"
onMouseOver="this.style.fill = 'lightGray'"
onMouseOut="this.style.fill = 'url(#rightGradient)'"
width=40 height=40 onClick="onButtonRight()"></rect>
<!-- Desna tipka -->
<text x=175 y=385 fill="white"
style="font-size: 18px; font-family:'Lucida Console'"
id="score">Score: 0</text>
</svg>
<br>
<div id="bodovi" style="">Highscore: <i><?php echo $highscore; ?></i> by <i><?php echo $player; ?></i>.</div>
<div id="instructions">The game does NOT respond to keyboard buttons. On smartphones, the Pacman is supposed to follow your finger, to go in the direction where you last tapped. In case that doesn't work, you have buttons below the maze. On computers, it's playable by mouse.<br/>You can see the source code, with the comments in Croatian, <a href="https://github.com/FlatAssembler/SVG-Pacman/blob/master/pacman.php">here</a>.<noscript><br/>Of course, nothing of this can work without JavaScript enabled in your browser.</noscript></div>
</center>
<script type="text/javascript">
if (document.getElementById("startButton").offsetLeft<=document.getElementById("zaslon").offsetLeft) { //Safari 5, recimo, ne podrzava CSS-ovu naredbu "calc", ali podrzava dovoljno JavaScripta i SVG-a da pokrene ovaj PacMan. Zato cemo tamo CSS-ov "calc" simulirati u JavaScriptu.
window.onresize=function() {
var sredinaEkrana=document.body.clientWidth/2;
var startButton=document.getElementById("startButton");
if (startButton)
startButton.style.left=(sredinaEkrana-100)+"px";
var bodovi=document.getElementById("bodovi");
bodovi.style.left=(sredinaEkrana-150)+"px";
var instructions=document.getElementById("instructions");
instructions.style.top=(458+50+5)+"px";
instructions.style.width=(sredinaEkrana*2-2*8)+"px";
};
window.onresize();
}
window.setTimeout(function(){document.body.removeChild(document.body.children[document.body.children.length-1]);},1000); //Ukloni "Powered by 000webhost", da ne smeta na smartphonima.
var isGameFinished=false;
var highscore=<?php echo "\"".$highscore."\";"; ?> //Ovaj podatak u JavaScript kod umece PHP program koji se vrti na serveru.
var kolikoJePacmanuPreostaloZivota = 3, time1 = 0, time2 = 0, score = 0, kadaJePacmanPojeoVelikuTocku = -100 /*"Plavi" duhovi se mogu "pojesti". Duhovi prestanu biti plavi nakon sto prode odredeno vrijeme (koje se broji varijablom 'brojacGlavnePetlje').*/
var howManyDotsAreThere = 0 /*Broj tocaka u svakom nivou, PacMan ih mora pojesti sve da prijede na iduci nivo.*/
var howManyDotsHasPacmanEaten = 0;
var level = 0;
var XML_namespace_of_SVG = "http://www.w3.org/2000/svg"; //Ovo je potrebno jer SVG ne koristi HTML DOM, nego XML DOM s drugim namespaceom.
var brojacGlavnePetlje = 0, brojacAnimacijskePetlje = 0, kolikoJePutaDuhPromijenioSmjer=0;
var hasPacmanChangedDirection = false; //Je li za vrijeme izvrsavanja animacijske petlje promijenjen smjer kretanja PacMan-a.
var pocetnoStanjeLabirinta = new Array(19);
/*
W - zid
B - velika tockica (koja, kada ju PacMan pojede, ucini da duhovi poplave).
P - mala tockica (donosi bodove, te, ako ih PacMan sve pojede, prelazi na iduci level).
C - PacMan (gdje se nalazi na pocetku nivoa)
1 - crveni duh
2 - ruzicasti duh
3 - narancasti duh
*/
pocetnoStanjeLabirinta[ 0] = " ";
pocetnoStanjeLabirinta[ 1] = " WWWWWWWWWWWWW ";
pocetnoStanjeLabirinta[ 2] = " WBPPPPWPPPPBW ";
pocetnoStanjeLabirinta[ 3] = " WPWWWPWPWWWPW ";
pocetnoStanjeLabirinta[ 4] = " WPW WPWPW WPW ";
pocetnoStanjeLabirinta[ 5] = " WPWWWPWPWWWPW ";
pocetnoStanjeLabirinta[ 6] = " WPPPPP PPPPPW ";
pocetnoStanjeLabirinta[ 7] = "WWWWPWW WWPWWWW";
pocetnoStanjeLabirinta[ 8] = " PW123WP ";
pocetnoStanjeLabirinta[ 9] = "WWWWPWWWWWPWWWW";
pocetnoStanjeLabirinta[10] = " WPP C PPW ";
pocetnoStanjeLabirinta[11] = " WWWPWWWWWPWWW ";
pocetnoStanjeLabirinta[12] = " WPPPPPPPPPPPW ";
pocetnoStanjeLabirinta[13] = " WPWWWWPWWWWPW ";
pocetnoStanjeLabirinta[14] = " WPW WPW WPW ";
pocetnoStanjeLabirinta[15] = " WPWWWWPWWWWPW ";
pocetnoStanjeLabirinta[16] = " WPPPPPBPPPPPW ";
pocetnoStanjeLabirinta[17] = " WWWWWWWWWWWWW ";
pocetnoStanjeLabirinta[18] = " ";
var smjer={ //Ovako se u JavaScriptu radi ono sto se u C-u radi naredbom "enum".
"gore":0,
"desno":1,
"dolje":2,
"lijevo":3,
"stop":4
};
var xKomponentaSmjeraPacmana = [0, 1, 0, -1, 0];
var yKomponentaSmjeraPacmana = [-1, 0, 1, 0, 0];
var duhovi={
"crveni":0,
"ruzicasti":1,
"narancasti":2
};
var smjerDuha = [smjer.desno, smjer.gore, smjer.lijevo], smjerPacmana = smjer.desno;
var pocetnaXKoordinataPacmana, pocetnaYKoordinataPacmana, pocetnaXKoordinataDuha = new Array(3), pocetnaYKoordinataDuha = new Array(3);
var xKoordinataPacmana = 0;
var yKoordinataPacmana = 0;
var xKoordinataDuha = new Array(3);
var yKoordinataDuha = new Array(3);
var jeLiPacmanPojeoDuha = [false, false, false];
var bojaDuha = ["red", "pink", "orange"];
var smjerKretanjaSiluete = [smjer.stop, smjer.stop, smjer.stop];
var xKoordinataSiluete = new Array(3);
var yKoordinataSiluete = new Array(3);
var xKoordinataCiljaSiluete = 7;
var yKoordinataCiljaSiluete = 6;
var zaslon = document.getElementById("zaslon"); //AST od SVG-a (njegovom manipulacijom odredujemo sto ce se crtati na zaslonu).
function onButtonDown()
{
hasPacmanChangedDirection = true;
if (pocetnoStanjeLabirinta[yKoordinataPacmana + 1].charAt(xKoordinataPacmana) != "W")
smjerPacmana = smjer.dolje;
}
function onButtonUp()
{
hasPacmanChangedDirection = true;
if (pocetnoStanjeLabirinta[yKoordinataPacmana - 1].charAt(xKoordinataPacmana) != "W")
smjerPacmana = smjer.gore;
}
function onButtonLeft()
{
hasPacmanChangedDirection = true;
if (pocetnoStanjeLabirinta[yKoordinataPacmana].charAt(xKoordinataPacmana - 1) != "W")
smjerPacmana = smjer.lijevo;
}
function onButtonRight()
{
hasPacmanChangedDirection = true;
if (pocetnoStanjeLabirinta[yKoordinataPacmana].charAt(xKoordinataPacmana + 1) != "W")
smjerPacmana = smjer.desno;
}
function drawLine(x1, x2, y1, y2) //Za crtanje labirinta, 'W' iz 'pocetnoStanjeLabirinta'.
{
var crta = document.createElementNS(XML_namespace_of_SVG, "line");
crta.setAttribute("x1", x1);
crta.setAttribute("x2", x2);
crta.setAttribute("y1", y1);
crta.setAttribute("y2", y2);
crta.setAttribute("stroke-width", 3);
crta.setAttribute("stroke", "lightBlue");
zaslon.appendChild(crta);
}
function drawSmallCircle(x, y, id) //Mala tockica, 'P' iz 'pocetnoStanjeLabirinta'.
{
var krug = document.createElementNS(XML_namespace_of_SVG, "circle");
krug.setAttribute("cx", x);
krug.setAttribute("cy", y);
krug.setAttribute("r", 3);
krug.setAttribute("fill", "lightYellow");
krug.setAttribute("id", id);
zaslon.appendChild(krug);
}
function drawBigCircle(x, y, id) //Velika tocka, 'B' iz 'pocetnoStanjeLabirinta'
{
var krug = document.createElementNS(XML_namespace_of_SVG, "circle");
krug.setAttribute("cx", x);
krug.setAttribute("cy", y);
krug.setAttribute("r", 5);
krug.setAttribute("fill", "lightGreen");
krug.setAttribute("id", id);
zaslon.appendChild(krug);
}
function drawGhost(x, y, color, id, transparent) //Duhovi su geometrijski likovi omedeni crtama (dno) i kubicnom Bezierovom krivuljom (vrh).
{
var path = document.createElementNS(XML_namespace_of_SVG, "path");
path.setAttribute("fill", color);
var d = "M " + (x - 8) + " " + (y + 8);
d += "C " + (x - 5) + " " + (y - 16) + " " + (x + 5) + " " + (y - 16) + " " + (x + 8) + " " + (y + 8);
d += " l -4 -3 l -4 3 l -4 -3 Z";
path.setAttribute("d", d);
path.setAttribute("id", id);
if (transparent)
path.setAttribute("fill-opacity",0.5); //Siluete (bijeli duhovi).
zaslon.appendChild(path);
}
function drawGhosts()
{
for (var i = 0; i < 3; i++) {
if (jeLiPacmanPojeoDuha[i] && brojacGlavnePetlje - kadaJePacmanPojeoVelikuTocku < 30)
{
drawGhost(xKoordinataSiluete[i]*20+10,yKoordinataSiluete[i]*20+10,"white","bijeli"+(i+1),true);
document.getElementById("bijeli"+(i+1)).
setAttribute("transform","translate(0 0)");
}
else
{
drawGhost(xKoordinataDuha[i] * 20 + 10, yKoordinataDuha[i] * 20 + 10,
(brojacGlavnePetlje - kadaJePacmanPojeoVelikuTocku > 30) ? (bojaDuha[i]) : ("blue"), "duh" + (i + 1));
document.getElementById("duh" + (i + 1))
.setAttribute("transform", "translate(0 0)");
}
}
}
function drawPacMan() //PacMan se sastoji od zutog kruga i crnog trokuta (usta).
{
var krug = document.createElementNS(XML_namespace_of_SVG, "circle");
krug.setAttribute("cx", xKoordinataPacmana * 20 + 10);
krug.setAttribute("cy", yKoordinataPacmana * 20 + 10);
krug.setAttribute("r", 10);
krug.setAttribute("fill", "yellow");
krug.setAttribute("id", "PacMan");
krug.setAttribute("transform", "translate(0 0)");
zaslon.appendChild(krug);
var usta = document.createElementNS(XML_namespace_of_SVG, "polygon");
usta.setAttribute("points", "0,0 10,-10 10,10");
usta.setAttribute("fill", "black");
usta.setAttribute("id", "usta");
usta.setAttribute("transform", "translate(" + (xKoordinataPacmana * 20 + 10) + " " + (yKoordinataPacmana * 20 + 10) + ")");
if (!((xKoordinataPacmana + yKoordinataPacmana) % 2) || smjerPacmana == smjer.stop) //Pacman zatvori usta kad se nade na neparnoj dijagonali i kada stoji.
usta.setAttribute("transform", usta.getAttribute("transform") + " scale(1 0)");
usta.setAttribute("transform",
usta.getAttribute("transform") + " rotate(" + (90 * smjerPacmana - 90) + ")");
zaslon.appendChild(usta);
}
function nextLevel()
{
level++;
setTimeout(function(){
score += 90 + 10 * level;
kadaJePacmanPojeoVelikuTocku = -100;
howManyDotsHasPacmanEaten = 0;
howManyDotsAreThere = 0;
for (var i = 0; i < 3; i++) {
xKoordinataDuha[i] = pocetnaXKoordinataDuha[i];
yKoordinataDuha[i] = pocetnaYKoordinataDuha[i];
}
xKoordinataPacmana = pocetnaXKoordinataPacmana;
yKoordinataPacmana = pocetnaYKoordinataPacmana;
smjerPacmana = smjer.desno;
smjerDuha[duhovi.crveni] = smjer.desno;
smjerDuha[duhovi.narancasti] = smjer.gore;
smjerDuha[duhovi.ruzicasti] = smjer.lijevo;
for (var i = 0; i < 19; i++)
for (var j = 0; j < 15; j++)
{
if (pocetnoStanjeLabirinta[i].charAt(j) == "P")
{
drawSmallCircle(j * 20 + 10, i * 20 + 10, "krug" + (i * 20 + j));
howManyDotsAreThere++;
}
if (pocetnoStanjeLabirinta[i].charAt(j) == "B")
{
drawBigCircle(j * 20 + 10, i * 20 + 10, "krug" + (i * 20 + j));
howManyDotsAreThere++;
}
}
}
,1950); //Novi level se postavlja tek kada natpis o novom levelu nestane (nakon 1950 milisekunda).
showLevel();
}
function touchScreenInterface(event) //Gdje se nalazi polje u labirintu koje je korisnik dotaknuo? Je li, na primjer, vise lijevo ili vise prema gore od PacMana?
{
var x = Math.floor((event.clientX-(document.body.clientWidth/2-300/2)) / 20);
var y = Math.floor(event.clientY / 20);
if (Math.abs(xKoordinataPacmana - x) > Math.abs(yKoordinataPacmana - y))
{
if (x < xKoordinataPacmana)
onButtonLeft();
else
onButtonRight();
} else
{
if (y < yKoordinataPacmana)
onButtonUp();
else
onButtonDown();
}
}
function mainLoop() //Glavna petlja, prati u kojem se polju iz 'pocetnoStanjeLabirinta' trenutno nalaze PacMan i duhovi.
{
hasPacmanChangedDirection = false;
brojacGlavnePetlje++;
brojacAnimacijskePetlje = 0;
var pacman = zaslon.getElementById("PacMan");
if (pacman != null) { //PacMan se crta svaki put kada se ude u 'mainLoop'.
zaslon.removeChild(pacman);
zaslon.removeChild(zaslon.getElementById("usta"));
zaslon.removeChild(zaslon.getElementById("TouchScreenInterface"));
}
if (pocetnoStanjeLabirinta[yKoordinataPacmana + yKomponentaSmjeraPacmana[smjerPacmana]].charAt(xKoordinataPacmana + xKomponentaSmjeraPacmana[smjerPacmana]) == "W") //Ako se PacMan nabio u zid, mora stati.
smjerPacmana = smjer.stop;
for (var i = 0; i < 3; i++) {
var duh = zaslon.getElementById("duh" + (i + 1));
if (duh != null) //Duhovi se crtaju svaki put iznova kada se ude u 'mainLoop'.
zaslon.removeChild(duh);
var bijeli = zaslon.getElementById("bijeli"+(i+1));
if (bijeli!=null)
zaslon.removeChild(bijeli);
var kolikoJePutaDuhPromijenioSmjer = 0;
for (var j = 0; j < 4; j++)
if (pocetnoStanjeLabirinta[yKoordinataDuha[i] + yKomponentaSmjeraPacmana[j]].charAt(xKoordinataDuha[i] + xKomponentaSmjeraPacmana[j]) != "W") //Nalazi li se duh na krizistu hodnika iz labirinta?
kolikoJePutaDuhPromijenioSmjer++;
var suprotniSmjer = (smjerDuha[i] + 2) % 4;
if (pocetnoStanjeLabirinta[yKoordinataDuha[i] + yKomponentaSmjeraPacmana[smjerDuha[i]]].charAt(xKoordinataDuha[i] + xKomponentaSmjeraPacmana[smjerDuha[i]]) == "W" || kolikoJePutaDuhPromijenioSmjer > 2) {
if (Math.abs(xKoordinataPacmana - xKoordinataDuha[i]) > Math.abs(yKoordinataPacmana - yKoordinataDuha[i]) //Ako je PacMan vise udaljen od duha u smjeru lijevo-desno.
&& !((yKoordinataDuha[i] == 7 || yKoordinataDuha[i] == 8) && xKoordinataDuha[i] > 4 && xKoordinataDuha[i] < 9) /*Ako duh nije u "kucici" u sredini labirinta (gdje je bio na pocetku nivoa).*/)
{
//Crveni duh od treceg nivoa nadalje pokusava pratiti PacMana.
if (xKoordinataPacmana < xKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] - 1) != "W"
&& level > 1) {
smjerDuha[i] = smjer.lijevo; //Ako je PacMan lijevo, usmjeri crvenog duha lijevo.
continue;
}
if (xKoordinataPacmana > xKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] + 1) != "W"
&& level > 1) {
smjerDuha[i] = smjer.desno; //Ako je PacMan desno, usmjeri crvenog duha desno.
continue;
}
if (yKoordinataPacmana < yKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i] - 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level > 1) {
smjerDuha[i] = smjer.gore; //Ako je PacMan gore, usmjeri crvenog duha gore.
continue;
}
if (yKoordinataPacmana > yKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i] + 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level > 1) {
smjerDuha[i] = smjer.dolje; //Ako je PacMan dolje, usmjeri crvenog duha dolje.
continue;
}
//Narancasti duh od drugog nivoa nadalje "bjezi" od PacMana.
if (xKoordinataPacmana < xKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] + 1) != "W"
&& level) {
smjerDuha[i] = smjer.desno; //Ako je PacMan lijevo, usmjeri narancastog duha desno.
continue;
}
if (xKoordinataPacmana > xKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] - 1) != "W"
&& level) {
smjerDuha[i] = smjer.lijevo; //Ako je PacMan desno, usmjeri narancastog duha lijevo.
continue;
}
if (yKoordinataPacmana < yKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i] + 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level) {
smjerDuha[i] = smjer.dolje; //Ako je PacMan gore, usmjeri narancastog duha dolje.
continue;
}
if (yKoordinataPacmana > yKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i] - 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level) {
smjerDuha[i] = smjer.gore; //Ako je PacMan dolje, usmjeri narancastog duha gore.
continue;
}
} else if (!((yKoordinataDuha[i] == 7 || yKoordinataDuha[i] == 8) && xKoordinataDuha[i] > 4 && xKoordinataDuha[i] < 9)) //Ako je PacMan vise udaljen od duha u smjeru gore-dolje, a duh nije u "kucici" u sredini labirinta.
{
if (yKoordinataPacmana < yKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i] - 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level > 1) {
smjerDuha[i] = smjer.gore; //Crveni prema gore
continue;
}
if (yKoordinataPacmana > yKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i] + 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level > 1) {
smjerDuha[i] = smjer.dolje; //Crveni prema dolje
continue;
}
if (xKoordinataPacmana < xKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] - 1) != "W"
&& level > 1) {
smjerDuha[i] = smjer.lijevo; //Crveni prema lijevo
continue;
}
if (xKoordinataPacmana > xKoordinataDuha[i] && i == duhovi.crveni && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] + 1) != "W"
&& level > 1) {
smjerDuha[i] = smjer.desno; //Crveni prema desno
continue;
}
if (yKoordinataPacmana < yKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i] + 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level) {
smjerDuha[i] = smjer.dolje; //Narancasti prema dolje
continue;
}
if (yKoordinataPacmana > yKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i] - 1].charAt(xKoordinataDuha[i]) != "W"
&& !(xKoordinataDuha[i] == 7 && yKoordinataDuha[i] == 6) && level) {
smjerDuha[i] = smjer.gore; //Narancasti prema gore
continue;
}
if (xKoordinataPacmana < xKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] + 1) != "W"
&& level) {
smjerDuha[i] = smjer.desno; //Narancasti prema desno
continue;
}
if (xKoordinataPacmana > xKoordinataDuha[i] && i == duhovi.narancasti && pocetnoStanjeLabirinta[yKoordinataDuha[i]].charAt(xKoordinataDuha[i] - 1) != "W"
&& level) {
smjerDuha[i] = smjer.lijevo; //Narancasti prema lijevo
continue;
}
}
do
{
smjerDuha[i] = Math.floor(Math.random() * 4); //Ruzicasti duh, svi duhovi u kucici, te crveni i narancasti duh prije treceg ili drugog nivoa gibaju se nasumicno.
} while (pocetnoStanjeLabirinta[yKoordinataDuha[i] + yKomponentaSmjeraPacmana[smjerDuha[i]]].charAt(xKoordinataDuha[i] + xKomponentaSmjeraPacmana[smjerDuha[i]]) == "W"
|| (smjerDuha[i] == suprotniSmjer && ((xKoordinataDuha[i]!=xKoordinataCiljaSiluete-1 && xKoordinataDuha[i]!=xKoordinataCiljaSiluete+1) || yKoordinataDuha[i]!=yKoordinataCiljaSiluete+2))); //Nije pozeljno da duh na krizistu putova krene u suprotnom smjeru no sto je prije isao.
}
if (Math.abs(xKoordinataDuha[i] - xKoordinataPacmana) < 2 && Math.abs(yKoordinataDuha[i] - yKoordinataPacmana) < 2 && brojacGlavnePetlje - kadaJePacmanPojeoVelikuTocku > 30) { //Ako se duh i PacMan sudare, a od posljednjeg konzumiranja velike tocke proslo je vise od 30 sekundi.
if (kolikoJePacmanuPreostaloZivota) {
zaslon.removeChild(zaslon.getElementById("live" + (kolikoJePacmanuPreostaloZivota)));
kolikoJePacmanuPreostaloZivota--;
for (var i = 0; i < 3; i++) {
xKoordinataDuha[i] = pocetnaXKoordinataDuha[i];
yKoordinataDuha[i] = pocetnaYKoordinataDuha[i];
}
xKoordinataPacmana = pocetnaXKoordinataPacmana;
yKoordinataPacmana = pocetnaYKoordinataPacmana;
smjerPacmana = smjer.desno;
smjerDuha[duhovi.crveni] = smjer.desno;
smjerDuha[duhovi.ruzicasti] = smjer.gore;
smjerDuha[duhovi.narancasti] = smjer.lijevo;
return;
} else //Ako vise nema zivota.
{
if (isGameFinished)
return; //Ako se ovaj blok pozove dvaput.
else
isGameFinished=true;
alert("Game over! Your score: " + score + ". Hope you enjoyed. Author: Teo Samarzija.");
clearInterval(time1); //Prestani pratiti gdje se nalazi PacMan, a gdje duhovi.
clearInterval(time2); //Zaustavi animacije.
if (score>(highscore)*1)
{
document.body.onresize=function(){return;}; //Safari 5.
document.getElementById("instructions").style.top=(458+2*50+5)+"px";
var player;
do {
player=window.prompt("Enter your name, new highscore! Your name mustn't contain whitespaces or special characters.","player");
}
while (player && (player.indexOf("<")+1 || player.indexOf(">")+1 || player.indexOf("&")+1 || player.indexOf(" ")+1));
if (player==null)
player="anonymous";
var hash=7;
for (var i=0; i<score/127; i++)
{
hash+=i;
hash%=907;
}
var submit="http://flatassembler.000webhostapp.com/pacHigh.php?score="+score+"&player="+player+"&hash="+hash;
var link=document.createElement("a");
link.setAttribute("href",submit);
link.appendChild(document.createTextNode("Submit the new highscore!"));
link.setAttribute("target","_blank"); //Otvori u novom prozoru, da se moze zatvoriti iz JavaScripta.
document.getElementById("bodovi").appendChild(document.createElement("br"));
document.getElementById("bodovi").appendChild(link);
}
else window.close();
}
}
if (Math.abs(xKoordinataDuha[i] - xKoordinataPacmana) < 2 && Math.abs(yKoordinataDuha[i] - yKoordinataPacmana) < 2 && brojacGlavnePetlje - kadaJePacmanPojeoVelikuTocku < 30) //Ako PacMan pojede "plavog" duha.
{
xKoordinataSiluete[i]=xKoordinataDuha[i];
yKoordinataSiluete[i]=yKoordinataDuha[i];
score += 10 + 2 * level;
jeLiPacmanPojeoDuha[i] = true;
xKoordinataDuha[i] = pocetnaXKoordinataDuha[i];
yKoordinataDuha[i] = pocetnaYKoordinataDuha[i];
continue;
}
}
for (var i=0; i<3; i++)
{
if (xKoordinataSiluete[i]==xKoordinataCiljaSiluete && (yKoordinataSiluete[i]==yKoordinataCiljaSiluete || yKoordinataSiluete[i]==yKoordinataCiljaSiluete+1)) //Ako je bijeli duh pred vratima...
{smjerKretanjaSiluete[i]=smjer.dolje; continue;} //... neka ude u kucicu.
if (xKoordinataSiluete[i]==xKoordinataCiljaSiluete && yKoordinataSiluete[i]==yKoordinataCiljaSiluete+2 && smjerKretanjaSiluete[i]==2) //Ako je bijeli duh upravo usao u kucicu...
{smjerKretanjaSiluete[i]=smjer.lijevo; continue;} //... neka ide lijevo.
if (xKoordinataSiluete[i]==xKoordinataCiljaSiluete && yKoordinataSiluete[i]==yKoordinataCiljaSiluete+2) //Ako je bijeli duh na sredini kucice...
continue; //Neka zadrzi smjer.
if (xKoordinataSiluete[i]==xKoordinataCiljaSiluete-1 && yKoordinataSiluete[i]==yKoordinataCiljaSiluete+2) //Ako je bijeli duh na lijevom zidu kucice
{smjerKretanjaSiluete[i]=smjer.desno; continue} //... neka ide desno.
if (xKoordinataSiluete[i]==xKoordinataCiljaSiluete+1 && yKoordinataSiluete[i]==yKoordinataCiljaSiluete+2) //Ako je bijeli duh na desnom zidu kucice...
{smjerKretanjaSiluete[i]=smjer.lijevo; continue;} //... neka ide lijevo.
if ((Math.abs(xKoordinataSiluete[i]-xKoordinataCiljaSiluete)==1 || Math.abs(xKoordinataSiluete[i]-xKoordinataCiljaSiluete)==2) &&
pocetnoStanjeLabirinta[yKoordinataSiluete[i]+yKomponentaSmjeraPacmana[smjerKretanjaSiluete[i]]].charAt(xKoordinataSiluete[i]+xKomponentaSmjeraPacmana[smjerKretanjaSiluete[i]])!='W' && smjerKretanjaSiluete[i]-4)
continue; //Greedy algoritam za odabiranje smjera ne funkcionira u nekim slucajevima, tada je bolje zadrzati smjer.
if (yKoordinataSiluete[i]>yKoordinataCiljaSiluete && pocetnoStanjeLabirinta[yKoordinataSiluete[i]-1].charAt(xKoordinataSiluete[i])!='W') //Ako je bijeli duh ispod cilja...
{smjerKretanjaSiluete[i]=smjer.gore; continue;} //... usmjeri ga prema gore.
if (yKoordinataSiluete[i]<yKoordinataCiljaSiluete && pocetnoStanjeLabirinta[yKoordinataSiluete[i]+1].charAt(xKoordinataSiluete[i])!='W') //Ako je bijeli duh iznad cilja...
{smjerKretanjaSiluete[i]=smjer.dolje; continue;} //... usmjeri ga prema dolje.
if (xKoordinataSiluete[i]>xKoordinataCiljaSiluete && pocetnoStanjeLabirinta[yKoordinataSiluete[i]].charAt(xKoordinataSiluete[i]-1)!='W') //Ako je bijeli duh desno od cilja...
{smjerKretanjaSiluete[i]=smjer.lijevo; continue;} //... usmjeri ga prema lijevo.
if (xKoordinataSiluete[i]<xKoordinataCiljaSiluete && pocetnoStanjeLabirinta[yKoordinataSiluete[i]].charAt(xKoordinataSiluete[i]+1)!='W') //Ako je bijeli duh lijevo od cilja...
{smjerKretanjaSiluete[i]=smjer.desno; continue;} //... usmjeri ga prema desno.
if (xKoordinataSiluete[i]==xKoordinataCiljaSiluete && yKoordinataSiluete[i]>yKoordinataCiljaSiluete && pocetnoStanjeLabirinta[yKoordinataSiluete[i]-1].charAt(xKoordinataSiluete[i])=='W') //Ako je bijeli duh ravno ispod cilja, a iznad njega zid...
{smjerKretanjaSiluete[i]=smjer.lijevo; continue;} //... usmjeri ga prema lijevo.
}
if (zaslon.getElementById("krug" + (yKoordinataPacmana * 20 + xKoordinataPacmana)) != null) { //Ako pojede tockicu.
zaslon.removeChild(zaslon.getElementById("krug" + (yKoordinataPacmana * 20 + xKoordinataPacmana)));
if (pocetnoStanjeLabirinta[yKoordinataPacmana].charAt(xKoordinataPacmana) == "B") //Ako je upravo pojedena velika tocka.
{
kadaJePacmanPojeoVelikuTocku = brojacGlavnePetlje;
score += 4 + level;
jeLiPacmanPojeoDuha = [false, false, false];
}
score += 1 + level;
howManyDotsHasPacmanEaten++;
var bodovi = document.getElementById("score");
bodovi.removeChild(bodovi.lastChild);
bodovi.appendChild(document.createTextNode("Score: " + score));
}
drawGhosts();
drawPacMan();
var touch = document.createElementNS(XML_namespace_of_SVG, "rect"); //Prozirni pravokutnik preko labirinta prima evente kada korsnik dodirne negdje u labirint.
touch.setAttribute("x", 0);
touch.setAttribute("y", 20);
touch.setAttribute("width", 300);
touch.setAttribute("height", 340);
touch.setAttribute("id", "TouchScreenInterface");
touch.setAttribute("fill-opacity", 0);
touch.addEventListener("click", touchScreenInterface);
zaslon.appendChild(touch);
for (var i = 0; i < 3; i++)
{
if (jeLiPacmanPojeoDuha[i] && brojacGlavnePetlje - kadaJePacmanPojeoVelikuTocku < 30)
{
xKoordinataSiluete[i]+=xKomponentaSmjeraPacmana[smjerKretanjaSiluete[i]];
yKoordinataSiluete[i]+=yKomponentaSmjeraPacmana[smjerKretanjaSiluete[i]];
continue;
}
xKoordinataDuha[i] += xKomponentaSmjeraPacmana[smjerDuha[i]];
yKoordinataDuha[i] += yKomponentaSmjeraPacmana[smjerDuha[i]];
if (xKoordinataDuha[i] > 14) //Ako duh prode kroz krajnji desni prolaz u labirintu...
xKoordinataDuha[i] = 0; //...prebaci ga na krajnji lijevi.
if (xKoordinataDuha[i] < 0) //Ako duh prode kroz krajnji lijevi prolaz u labirintu...
xKoordinataDuha[i] = 14; //...prebaci ga na krajnji desni.
}
xKoordinataPacmana += xKomponentaSmjeraPacmana[smjerPacmana];
yKoordinataPacmana += yKomponentaSmjeraPacmana[smjerPacmana];
if (xKoordinataPacmana > 14) //Ako PacMan prode kroz desni prolaz.
xKoordinataPacmana = 0;
if (xKoordinataPacmana < 0) //Ako PacMan prode kroz lijevi prolaz.
xKoordinataPacmana = 14;
if (howManyDotsHasPacmanEaten == howManyDotsAreThere)
nextLevel();
}
function animationLoop()
{
if (brojacGlavnePetlje < 2)
return; //Ne pokusavaj animirati PacMana i duhove ako jos nisu nacrtani.
brojacAnimacijskePetlje++;
for (var i = 0; i < 3; i++) {
if (jeLiPacmanPojeoDuha[i] && brojacGlavnePetlje - kadaJePacmanPojeoVelikuTocku < 30) //Ako je PacMan nedavno pojeo duha, animiraj bijelu siluetu...
zaslon.getElementById("bijeli" + (i + 1)).setAttribute("transform",
"translate(" + (20 / 5) * brojacAnimacijskePetlje * xKomponentaSmjeraPacmana[smjerKretanjaSiluete[i]] + " " + (20 / 5) * brojacAnimacijskePetlje * yKomponentaSmjeraPacmana[smjerKretanjaSiluete[i]] + ")");
else //... inace animiraj duha.
zaslon.getElementById("duh" + (i + 1)).setAttribute("transform",
"translate(" + (20 / 5) * brojacAnimacijskePetlje * xKomponentaSmjeraPacmana[smjerDuha[i]] + " " + (20 / 5) * brojacAnimacijskePetlje * yKomponentaSmjeraPacmana[smjerDuha[i]] + ")");
}
if (hasPacmanChangedDirection == true) //Nemoj animirati PacMana ukoliko on upravo mijenja smjer.
return;
zaslon.getElementById("PacMan").setAttribute("transform",
"translate(" + (20 / 5) * brojacAnimacijskePetlje * xKomponentaSmjeraPacmana[smjerPacmana] + " " + (20 / 5) * brojacAnimacijskePetlje * yKomponentaSmjeraPacmana[smjerPacmana] + ")");
var usta = zaslon.getElementById("usta");
usta.setAttribute("transform",
"translate(" + ((20 / 5) * brojacAnimacijskePetlje * xKomponentaSmjeraPacmana[smjerPacmana] + ((xKoordinataPacmana - xKomponentaSmjeraPacmana[smjerPacmana]) * 20 + 10))
+ " " + ((20 / 5) * brojacAnimacijskePetlje * yKomponentaSmjeraPacmana[smjerPacmana] + (yKoordinataPacmana - yKomponentaSmjeraPacmana[smjerPacmana]) * 20 + 10) + ")");
if (!((xKoordinataPacmana + yKoordinataPacmana) % 2) /*Na poljima na parnim dijagonalama ce usta biti zatvorena, a na neparnima otvorena.*/ && (smjerPacmana == 1 || smjerPacmana == 3))
usta.setAttribute("transform",
usta.getAttribute("transform") + " scale(1 " + (brojacAnimacijskePetlje * 0.2) + ")");
else if (smjerPacmana == smjer.desno || smjerPacmana == smjer.lijevo)
usta.setAttribute("transform",
usta.getAttribute("transform") + " scale(1 " + (1 - brojacAnimacijskePetlje * 0.2) + ")");
else if (!((xKoordinataPacmana + yKoordinataPacmana) % 2) && (smjerPacmana == smjer.dolje || smjerPacmana == smjer.gore))
usta.setAttribute("transform",
usta.getAttribute("transform") + " scale(" + (brojacAnimacijskePetlje * 0.2) + " 1)");
else if (smjerPacmana == smjer.dolje || smjerPacmana == smjer.gore)
usta.setAttribute("transform",
usta.getAttribute("transform") + " scale(" + (1 - brojacAnimacijskePetlje * 0.2) + " 1)");
else if (smjerPacmana == smjer.stop) //PacMan, ako se ne mice, uvijek drzi usta zatvorenima.
usta.setAttribute("transform",
usta.getAttribute("transform") + " scale(1 0)");
usta.setAttribute("transform",
usta.getAttribute("transform") + " rotate(" + (90 * smjerPacmana - 90) + ")");
}
//Crtanje labirinta na pocetku igre.
for (var i = 0; i < 19; i++)
for (var j = 0; j < 15; j++)
{
if (pocetnoStanjeLabirinta[i].charAt(j) == 'W')
{
if (pocetnoStanjeLabirinta[i - 1].charAt(j) == 'W')
drawLine(j * 20 + 10, j * 20 + 10, i * 20, i * 20 + 10);
if (pocetnoStanjeLabirinta[i + 1].charAt(j) == 'W')
drawLine(j * 20 + 10, j * 20 + 10, i * 20 + 10, i * 20 + 20);
if (pocetnoStanjeLabirinta[i].charAt(j - 1) == 'W')
drawLine(j * 20, j * 20 + 10, i * 20 + 10, i * 20 + 10);
if (pocetnoStanjeLabirinta[i].charAt(j + 1) == 'W')
drawLine(j * 20 + 10, j * 20 + 20, i * 20 + 10, i * 20 + 10);
}
if (pocetnoStanjeLabirinta[i].charAt(j) == 'P')
{
drawSmallCircle(j * 20 + 10, i * 20 + 10, "krug" + (i * 20 + j));
howManyDotsAreThere++;
}
if (pocetnoStanjeLabirinta[i].charAt(j) == 'B')
{
drawBigCircle(j * 20 + 10, i * 20 + 10, "krug" + (i * 20 + j));
howManyDotsAreThere++;
}
if (pocetnoStanjeLabirinta[i].charAt(j) == 'C')
{
xKoordinataPacmana = pocetnaXKoordinataPacmana = j;
yKoordinataPacmana = pocetnaYKoordinataPacmana = i;
}
if (pocetnoStanjeLabirinta[i].charAt(j) > '0' && pocetnoStanjeLabirinta[i].charAt(j) < '4') //Duhovi.
{
//charCodeAt - vraca ASCII vrijednost znaka iz stringa (broj), to je vazno zbog arraysova, arr['0'] ne znaci isto sto i arr[0].
xKoordinataDuha[pocetnoStanjeLabirinta[i].charCodeAt(j) - "1".charCodeAt(0)] = j;
yKoordinataDuha[pocetnoStanjeLabirinta[i].charCodeAt(j) - "1".charCodeAt(0)] = i;
pocetnaYKoordinataDuha[pocetnoStanjeLabirinta[i].charCodeAt(j) - "1".charCodeAt(0)] = i;
pocetnaXKoordinataDuha[pocetnoStanjeLabirinta[i].charCodeAt(j) - "1".charCodeAt(0)] = j;
}
}
//Crtanje PacMana u lijevom donjem kutu koji oznacaju preostale zivote.
for (var i = 0; i < kolikoJePacmanuPreostaloZivota; i++)
{
var krug = document.createElementNS(XML_namespace_of_SVG, "circle");
krug.setAttribute("fill", "yellow");
krug.setAttribute("cx", 25 + i * 25);
krug.setAttribute("cy", 380);
krug.setAttribute("r", 10);
krug.setAttribute("id", "live" + (i + 1));
zaslon.appendChild(krug);
var usta = document.createElementNS(XML_namespace_of_SVG, "polygon");
usta.setAttribute("points",
(25 + i * 25) + ",380 " + (35 + i * 25) + ",370 " + (35 + i * 25) + " 390");
usta.setAttribute("fill", "black");
zaslon.appendChild(usta);
}
drawGhosts();
drawPacMan();
function onStartButton()
{
document.body.removeChild(document.getElementById("startButton"));
showLevel(); //U funkciji "showlevel" se postavlja timer.
}
function nestajanje() //Natpis o tome na kojem smo levelu ne iscezava odjednom, nego postupno.
{
var natpis=document.getElementById("natpis");
if (kolikoJePutaDuhPromijenioSmjer<16)
{
kolikoJePutaDuhPromijenioSmjer++;
natpis.style.opacity-=1/15;
natpis.style.left=(document.body.clientWidth/2-300/2+50+kolikoJePutaDuhPromijenioSmjer)+"px"; //Kako natpis nestaje, polako se pomice udesno.
setTimeout(nestajanje,100);
}
else
document.body.removeChild(natpis);
}
function showLevel()
{
clearInterval(time1);
clearInterval(time2);
//Pacman i duhovi se ne smiju pomicati iza natpisa da smo presli na novi level.
var natpis=document.createElement("div");
natpis.style.opacity=1.0;
natpis.style.left=document.body.clientWidth/2-300/2+50;
natpis.innerHTML="<b>LEVEL #"+(level+1)+"<\/b>"; //Ovako se mogu pozivati naredbe iz HTML-a u JavaScript programu.
natpis.id="natpis";
document.body.appendChild(natpis);
kolikoJePutaDuhPromijenioSmjer=0;
setTimeout(nestajanje,500); //Neka natpis o tome na kojem smo levelu pocne iscezavati nakon 500 milisekundi.
setTimeout(function(){
time1 = window.setInterval(mainLoop, 500);
time2 = window.setInterval(animationLoop, 100);
},2000); //Neka se glavna i animacijska petlja pocnu vrtiti nakon 2000 milisekunda od trenutka kada prijedemo na novi level.
}
</script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>There will certainly be users that can review your javascript operations better than me, so I'll only review the php.</p>\n\n<ul>\n<li>When checking for the existence of substrings at the start of your input string, you are calling too many functions and using verbose techniques -- <code>strpos()</code> will do just fine, there's no need to count substring lengths.</li>\n<li>Always use curly braces to avoid mistakes about how many lines of code following the condition should be executed. </li>\n<li>Give your users specific advice about which browsers you feel are \"proper\". IOW, remove the ambiguity by explicitly stating which browsers are acceptable.</li>\n<li>In accordance with php coding standards, using appropriate spacing.</li>\n</ul>\n\n<p>Revision:</p>\n\n<pre><code>$browser = $_SERVER['HTTP_USER_AGENT'];\nif (strpos($browser, 'Opera') !== 0 && strpos($browser, 'Mozilla/5.0') !== 0) {\n exit(\"Please access this URL with a proper browser!\\n\");\n}\n</code></pre>\n\n<hr>\n\n<p>Much of the above advice applies here as well:</p>\n\n<pre><code>if (strpos($player,\" \") || strpos($player,\"<\") || strpos($player,\">\") ||\n strpos($player,\"&\") || strpos($player,\"\\t\") || strpos($player,\"&gt;\")\n || strlen($player)==0)\n $player=\"anonymous\";\n</code></pre>\n\n<p>...but also, these checks will permit characters in the first position which should be forbidden because you are performing a loose comparison upon the return value of <code>strpos()</code>. IOW, if the the first character of the player's name is <code><</code>, the return value is <code>0</code> (which is falsey) and that will not be \"caught\" by your condition.</p>\n\n<p>If the goal is to fallback to <code>anonymous</code> if the player name is empty or contains any characters in this list: <code><,>,&,\\t, &gt;</code>, perhaps a single regex call will tidy up the expression. Logically, <code>&</code> will also catch <code>&gt;</code>. (<a href=\"https://3v4l.org/gOKjq\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>if (!preg_match('~^[^ <>&\\t]+$~', $player)) {\n $player = 'anonymous';\n}\n</code></pre>\n\n<p>This will require that the player name consists of 1 or more valid characters, otherwise <code>anonymous</code> will be applied. If you want to consider only allowing alphanumeric characters, it will be simpler to call <code>if (!ctype_alnum($player)) { $player = 'anonymous'; }</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T03:08:49.113",
"Id": "473445",
"Score": "0",
"body": "OK, thanks! I haven't studied PHP."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T21:53:31.190",
"Id": "241276",
"ParentId": "241268",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T19:32:42.120",
"Id": "241268",
"Score": "1",
"Tags": [
"javascript",
"php",
"svg"
],
"Title": "PacMan in JavaScript and SVG"
}
|
241268
|
<p>I am trying to implement a motion detection algorithm using state of the art on an esp32camera.
This board has 512kB RAM and I don't want to use too much CPU.
So I wanted to get a review on what I implemented if there is piece of code which could be optimized.
I tried to comment as much as possible and put link on existing code I took and reshaped.</p>
<p><strong>Context</strong>:</p>
<p>I try to implement <a href="https://en.wikipedia.org/wiki/Lucas%E2%80%93Kanade_method" rel="nofollow noreferrer">Lucas-Kanade optical flow</a>.</p>
<p>My code is composed of :</p>
<ul>
<li><p>conv : <a href="https://stackoverflow.com/questions/24518989/how-to-perform-1-dimensional-valid-convolution">full convolution 1D</a>.</p></li>
<li><p>transpose : rescale the input vector to 0..255 and transpose the equivalent array into a buffer.</p></li>
<li><p>LK_optical_flow : The main code that perform a 2D convolution with Sobel filters and input images. Then compute optical flow magnitude.</p></li>
</ul>
<p><strong>Code:</strong></p>
<pre><code>/** Rescale vector to 0..255 and transpose
* @param[in] src vector from convolution unscaled
* @param[out] dst pointer of buffer image*/
template<typename T>
void transpose(std::vector<T> src, uint8_t *dst, const int w, const int h) {
auto max = *std::max_element(src.begin(), src.end());
auto min = *std::min_element(src.begin(), src.end());
for(int n = 0; n< w * h; n++) {
const int i = n / h;
const int j = n % h;
dst[n] = (uint8_t)(src[w * j + i] - min) * 255.0 / max;
}
}
/** convolution 1D between flattened image and strel
* from : https://stackoverflow.com/questions/24518989/how-to-perform-1-dimensional-valid-convolution
* @param f pointer of flattened image buffer
* @param g structurant element (strel)
* @return convolved image as vector*/
template<typename T>
std::vector<T> conv(uint8_t *f, const std::vector<T> &g, const int nf) {
int const ng = g.size();
int const n = nf + ng - 1;
std::vector<T> out(n, T());
for(auto i(0); i < n; ++i) {
int const jmn = (i >= ng - 1)? i - (ng - 1) : 0;
int const jmx = (i < nf - 1)? i : nf - 1;
for(auto j(jmn); j <= jmx; ++j)
out[i] += (f[j] * g[i - j]);
}
out.erase(out.begin(), out.begin() + ng / 2 + 1); // remove edge due to full convolution
return out;
}
/// Optical flow Lucas-Kanade
/** Implement LK optical flow source from wiki:
* https://en.wikipedia.org/wiki/Lucas%E2%80%93Kanade_method
* @param src1 pointer to grayscale buffer image instant t
* @param src2 pointer to grayscale buffer image diff Image between t and t+1
* @param output Magnitude output image in RGB */
void LK_optical_flow(uint8_t *src1, uint8_t *src2, uint8_t *output, int w, int h)
{
//Allocate 1D strel
std::vector<int> Kernel_Dy = {1, 2, 1};
std::vector<int> Kernel_Dx = {-1, 0, 1};
std::vector<int> Kernel_Dt = {1, 1, 1};
//Allocate fy only. Too much memory on the heap.
std::vector<int> tmp;
uint8_t *fx = src1;
uint8_t *fy = new uint8_t[w * h];
uint8_t *ft = src2;
memset(output, 0, w * h * sizeof(uint8_t));
memcpy(fy, fx, w * h * sizeof(uint8_t));
// Compute equivalent of 2D convolution decompose of two 1D convolution.
// Sobel Dx
tmp = conv(fx, Kernel_Dx, w*h);
transpose(tmp, fx, w, h);
tmp = conv(fx, Kernel_Dy, w*h);
transpose(tmp, fx, w, h);
// Sobel Dy
tmp = conv(fy, Kernel_Dy, w*h);
transpose(tmp, fy, w, h);
tmp = conv(fy, Kernel_Dx, w*h);
transpose(tmp, fy, w, h);
// Dt
tmp = conv(ft, Kernel_Dt, w*h);
transpose(tmp, ft, w, h);
tmp = conv(ft, Kernel_Dt, w*h);
transpose(tmp, ft, w, h);
std::vector<int>().swap(tmp); // deallocate tmp
//TODO: Create a function for all above : Mag = opticalflow(fx, fy, ft, window=3)
const int window = 3; //half window size
float AtA[2][2];
float Atb[2];
std::vector<unsigned> Mag(w*h);
// Lucas Kanade optical flow algorithm
for(int i=window; i<=w-window;++i){
for(int j=window; j<h-window;++j){
memset(Atb, 0, sizeof(float) * 2);
memset(AtA, 0, sizeof(float) * 4);
for(int m=-window; m<window;++m){
const unsigned index = (j + m) * w + (i + m);
const float Ix = (float) fx[index];
const float Iy = (float) fy[index];
const float It = (float) ft[index];
AtA[0][0] += Ix * Ix;
AtA[1][1] += Iy * Iy;
AtA[0][1] += Ix * Iy;
AtA[1][0] = AtA[0][1];
Atb[0] += - Ix * It;
Atb[1] += - Iy * It;
}
//Compute inverse of 2x2 array AtA: 1/(ad-bc)[[d -b][-c a]]
const float det = AtA[0][0] * AtA[1][1] - AtA[0][1] * AtA[1][0];
const float iAtA[2][2] = {
{AtA[1][1] / det, - AtA[0][1] / det},
{iAtA[0][1] , AtA[0][0] / det}
};
//Compute optical flow : [Vx Vy] = inv[AtA] . Atb
const float Vx = iAtA[0][0] * Atb[0] + iAtA[0][1] * Atb[1];
const float Vy = iAtA[1][0] * Atb[0] + iAtA[1][1] * Atb[1];
Mag[i + j * w] = hypotf(Vx, Vy); //sqrt(Vx²+Vy²)
}
}
delete [] fy;
int max = *std::max_element(Mag.begin(), Mag.end());
if(max == 0)
return;
ESP_LOGI(TAG, "maxMag = %i \n", max);
//compute output which is Mag rescaled nothing interesting here.
}
</code></pre>
<p>My next step would be to complete the <strong><em>TODO</em></strong> comments.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T19:55:51.413",
"Id": "241270",
"Score": "1",
"Tags": [
"c++",
"embedded"
],
"Title": "Optical flow implementation on esp32"
}
|
241270
|
<p>I have m x n grid. m >= 1 ; n >= 1</p>
<p>I have item in the top-left corner and need to reach bottom-right corner of the grid.</p>
<p>Item can only move either down or right.</p>
<p>I need to find possible unique paths to do it.</p>
<p>I made two solutions for the problem: recursion (slower than the below one) and the one below.</p>
<p>The problem is that I run out of memory when m and n are big e.g. m == 20 and n >= 15 (more than 4 Gb is used - all free memory I have).</p>
<p>How can I improve my solution or there should be absolutely other way to solve the problem?</p>
<pre class="lang-py prettyprint-override"><code>
def unique_paths(m, n):
assert isinstance(m, int), "m should be integer"
assert isinstance(n, int), "n shoudl be integer"
assert m >= 1, "m should be >= 1"
assert n >= 1, "n should be >= 1"
if m == 1 and n == 1: # border case
return 1
ch = [(m, n,)] # for first start
s = 0 # number of unique paths
while True:
new_ch = []
while ch:
i = ch.pop() # I assumed that if decrease len of list it would decrease memory use
if i[0] == 1 and i[1] == 1: # we reached opposite corner
s += 1
# all other cases:
elif i[0] != 1 and i[1] != 1:
new_ch.append((i[0], i[1] - 1, ))
new_ch.append((i[0] - 1, i[1]))
elif i[0] == 1 and i[1] != 1:
new_ch.append((i[0], i[1] - 1,))
else:
new_ch.append((i[0] - 1, i[1],))
del i # do not need i anymore
if not new_ch:
return s
del ch
ch = new_ch
del new_ch
if __name__ == '__main__':
print(unique_paths(7, 3)) # = 28 - test case
</code></pre>
<p>Edit:</p>
<p>lru_cache is really amazing:</p>
<pre><code>
from functools import lru_cache
@lru_cache(128)
def numberOfPaths(m, n):
if m == 1 and n == 1: # border case
return 1
if m != 1 and n != 1:
return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1)
if m != 1 and n == 1:
return numberOfPaths(m - 1, n)
if m == 1 and n != 1:
return numberOfPaths(m, n - 1)
if __name__ == '__main__':
print(numberOfPaths(100, 100)) # 22750883079422934966181954039568885395604168260154104734000
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:11:10.500",
"Id": "473413",
"Score": "0",
"body": "Hello downvoters, please share the reason why you downvoted the question? =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:19:39.540",
"Id": "473415",
"Score": "2",
"body": "I didn't downvote, but this seems like it's less a matter of improving the code and more a matter of improving the underlying algorithm. Not sure how much a review of the code on its own will help you. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:29:38.210",
"Id": "473416",
"Score": "1",
"body": "I *think* `def unique_paths(m, n): return unique_paths(m - 1, n) + unique_paths(m, n - 1) if m > 1 and n > 1 else 1` will do ya if you just slap a `@functools.lru_cache` on there to memoize it. Runs fine for me with values in excess of 100 (eventually you hit maximum recursion depth issues tho)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:41:06.753",
"Id": "473417",
"Score": "3",
"body": "Close / down voter, this is not off-topic as it works with smaller bounds. Please read meta where we have explicitly allowed performance and memory improvements. We have a tag for this with ~150 questions, how's it off-topic "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:42:55.810",
"Id": "473418",
"Score": "3",
"body": "@Samwise Please keep the comments for discussing how the question can be improved and the answers for how the question's code can be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T21:01:57.380",
"Id": "473421",
"Score": "1",
"body": "@Samwise many many thanks to you, now it works really fast!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T21:25:16.637",
"Id": "473426",
"Score": "5",
"body": "As they say, the right algorithm is the key. As long as you bruteforce, `lru_cache` is just a pair of crutches. OTOH, math does wonders. The answer to this problem is \\$\\binom{m+n-2}{m-1}\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T06:19:36.433",
"Id": "473459",
"Score": "0",
"body": "@vnp thank you, can you explain how to read formula in brackets?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T06:43:21.887",
"Id": "473460",
"Score": "2",
"body": "It's a [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient)"
}
] |
[
{
"body": "<p>Solution: recursion with memoization works really well! Many thanks to <strong>Samwise</strong> and <strong>vnp</strong>.</p>\n\n<p><strong>With the help of python lru_cache decorator:</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@lru_cache(128)\ndef number_of_paths(m, n):\n if m == 1 and n == 1: # border case\n result = 1\n\n elif m != 1 and n != 1:\n result = number_of_paths(m - 1, n) + number_of_paths(m, n - 1)\n\n elif m != 1 and n == 1:\n result = number_of_paths(m - 1, n)\n\n elif m == 1 and n != 1:\n result = number_of_paths(m, n - 1)\n\n else:\n raise Exception(\"Something went wrong!\")\n\n return result\n</code></pre>\n\n<p><strong>With the help of dictionary to store results:</strong></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>storage = {}\ndef number_of_paths_no_lru(m, n):\n if storage.get((m, n,)):\n return storage[(m, n)]\n\n if m == 1 and n == 1: # border case\n result = 1\n\n elif m != 1 and n != 1:\n result = number_of_paths_no_lru(m - 1, n) + number_of_paths_no_lru(m, n - 1)\n\n elif m != 1 and n == 1:\n result = number_of_paths_no_lru(m - 1, n)\n\n elif m == 1 and n != 1:\n result = number_of_paths_no_lru(m, n - 1)\n\n else:\n raise Exception(\"Something went wrong!\")\n\n storage[(m, n, )] = result\n return result\n</code></pre>\n\n<p><strong>Tests:</strong></p>\n\n<pre><code>if __name__ == '__main__':\n print(number_of_paths(100, 100))\n print(number_of_paths_no_lru(100, 100))\n # Answers:\n # 22750883079422934966181954039568885395604168260154104734000\n # 22750883079422934966181954039568885395604168260154104734000\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T08:16:49.403",
"Id": "241292",
"ParentId": "241272",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241292",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:08:33.350",
"Id": "241272",
"Score": "1",
"Tags": [
"python",
"algorithm",
"memory-optimization"
],
"Title": "Find number of unique paths to reach opposite grid corner"
}
|
241272
|
<p>The class <code>WalkingData</code> storages a "date" and a "walked distance". The class also read the stored data.</p>
<pre><code> public class WalkingData
{
public DateTime Date { get; set; }
public int WalkedDistance { get; set; }
private string _filePath = @"c:\Data\Json.txt";
//Read Data from Json File
public List<WalkingData> GetAll()
{
//If file does not exist returns an empty list
if (!File.Exists(_filePath)) return new List<WalkingData>();
string jsonData;
//Read the existing Json file
using (StreamReader readtext = new StreamReader(_filePath))
{
jsonData = readtext.ReadToEnd();
}
//Deserialize the Json and returs a list of WalkingData
return JsonConvert.DeserializeObject<List<WalkingData>>(jsonData);
}
//save an instance of WalkingData in Json file
public void Save()
{
List<WalkingData> lstExistingWalkingData = new List<WalkingData>();
//if existing data, load it into lstExistingWalkingData
if (File.Exists(_filePath))
lstExistingWalkingData = GetAll();
//Add the current instace into lstExistingWalkingData
lstExistingWalkingData.Add(this);
//Serialize lstExistingWalkingData
string output = JsonConvert.SerializeObject(lstExistingWalkingData);
//Save the Json file
using (StreamWriter w = new StreamWriter(_filePath))
{
w.WriteLine(output);
}
}
}
</code></pre>
<p>After I applied the Single Responsibility Principle I have the new code that I would like to confirm if I applied the principle in a reasonable way:</p>
<pre><code>//This class is located on a library called BOL and has a reference to DAL library
public class WalkingData
{
public DateTime Date { get; set; }
public int WalkedDistance { get; set; }
}
//This class is located on a library called BOL and has a reference to DAL library
public class WalkingDataManager
{
WalkingDataRepository walkingDataRepository = new WalkingDataRepository();
public List<WalkingData> GetAll()
{
return walkingDataRepository.GetAll();
}
public void Save(WalkingData walkingData)
{
walkingDataRepository.Save(walkingData);
}
}
//this class is located in library Called DAL
internal class WalkingDataRepository
{
private string _filePath = @"c:\Data\Json.txt";
//Read Data from Json File
internal List<WalkingData> GetAll()
{
//If file does not exist returns an empty list
if (!File.Exists(_filePath)) return new List<WalkingData>();
string jsonData;
//Read the existing Json file
using (StreamReader readtext = new StreamReader(_filePath))
{
jsonData = readtext.ReadToEnd();
}
//Deserialize the Json and returs a list of WalkingData
return JsonConvert.DeserializeObject<List<WalkingData>>(jsonData);
}
//save an instance of WalkingData in Json file
internal void Save(WalkingData walkingData)
{
List<WalkingData> lstExistingWalkingData = new List<WalkingData>();
//if existing data, load it into lstExistingWalkingData
if (File.Exists(_filePath))
lstExistingWalkingData = GetAll();
//Add the current instace into lstExistingWalkingData
lstExistingWalkingData.Add(walkingData);
//Serialize lstExistingWalkingData
string output = JsonConvert.SerializeObject(lstExistingWalkingData);
//Save the Json file
using (StreamWriter w = new StreamWriter(_filePath))
{
w.WriteLine(output);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:55:29.790",
"Id": "473419",
"Score": "1",
"body": "Welcome to code review, where we review working code from one of your projects and provide suggestions on how that code can be improved. Unfortunately we can't help you re-write / refactor code. If you write a solution that separates the CRUD from the rest of the class we will be happy to review that code and tell you what you might improve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T22:37:30.253",
"Id": "473434",
"Score": "0",
"body": "I made the re-factorization, can you please confirm if the new code has applied the SRP?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T08:12:30.830",
"Id": "473469",
"Score": "2",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T08:44:51.730",
"Id": "473471",
"Score": "0",
"body": "9 times out of 10, \"Manager\" classes are named so because you couldn't think of a name for \"this thing that does some work\". Try defining the responsibility of the class better and finding a better name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T11:21:07.247",
"Id": "473483",
"Score": "1",
"body": "@pacmaninbw I think this basically boils down to a request for review of the second piece of code. The validation part is a bit off, but I imagine one of the answers could identify whether this code can be improved SRP-wise or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T11:22:48.850",
"Id": "473484",
"Score": "0",
"body": "Can you please verify you've tested this code? Does it produce the correct output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T14:08:45.403",
"Id": "473495",
"Score": "0",
"body": "If you violate IoC, you violate SRP. You violate IoC. Also how is the manager different from the repo? They seem to do exactly the same..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T05:34:24.473",
"Id": "473575",
"Score": "1",
"body": "\"classes located on some library\": If this is code *not* under your control and included for completeness, only, please a) properly attribute (hyperlink for reference welcome) b) present as a block quote."
}
] |
[
{
"body": "<p>The 3 classes now follow the SRP.</p>\n\n<p>You may want to allow the file path to be updated by a parameter passed into the WalkingDataRepository constructor. This would allow a user to set the file path by command line arguments, question and answer at runtime or environment variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T22:54:26.453",
"Id": "241278",
"ParentId": "241273",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241278",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T20:26:19.447",
"Id": "241273",
"Score": "0",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Re-factorize a program using single responsibility principle - SOLID- SRP"
}
|
241273
|
<p>I'm making an AI agent (blue entity) that pursues a target (green entity) while avoiding an obstacle (red entity).</p>
<p>The code works as it should most of the times, but will fail if all the entities are aligned in either the X or Y axis or any direction diagonally. I suspect this is due to dividing by zero.</p>
<p>I fixed the problem by simply checking if the axes were zero and then applying a slight offset.</p>
<pre><code>if (vectorTargetX === 0) vectorTargetX += 0.1;
if (vectorTargetY === 0) vectorTargetY += 0.1;
</code></pre>
<p>However, this feels like a cheap fix and it seems like there might be some underlying problems in my code. Are there any better ways to go about this, maybe even more efficient?</p>
<p>You can see the how the AI agent fails by clicking the buttons in the example below.
<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 ctx = document.getElementById('canvas').getContext('2d');
let targetX = 150;
let targetY = 100;
let obstacleX = 200;
let obstacleY = 100;
let agentX = 300;
let agentY = 101;
function loop() {
requestAnimationFrame(loop);
// Calculate difference vectors
let vectorTargetX = targetX - agentX;
let vectorTargetY = targetY - agentY;
let vectorObstacleX = obstacleX - agentX;
let vectorObstacleY = obstacleY - agentY;
// Calculate length between vectors
const lengthTarget = Math.sqrt(vectorTargetX * vectorTargetX + vectorTargetY * vectorTargetY);
const lengthObstacle = Math.sqrt(vectorObstacleX * vectorObstacleX + vectorObstacleY * vectorObstacleY);
// Normalize vectors
vectorTargetX = vectorTargetX / lengthTarget;
vectorTargetY = vectorTargetY / lengthTarget;
vectorObstacleX = vectorObstacleX / lengthObstacle;
vectorObstacleY = vectorObstacleY / lengthObstacle;
// Check if agent is within collision distance
if (lengthObstacle < 60) {
// Append displacement vector
vectorTargetX -= vectorObstacleX * 0.7;
vectorTargetY -= vectorObstacleY * 0.7;
const displacedLength = Math.sqrt(vectorTargetX * vectorTargetX + vectorTargetY * vectorTargetY);
// Move agent towards target while adding avoidance force
agentX += vectorTargetX / displacedLength;
agentY += vectorTargetY / displacedLength;
} else {
// Move agent towards target
agentX += vectorTargetX;
agentY += vectorTargetY;
}
if (lengthTarget < 12) {
unaligned();
}
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.fillStyle = '#00ff00';
ctx.arc(targetX, targetY, 6, 0, Math.PI * 2, false);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = '#ff0000';
ctx.arc(obstacleX, obstacleY, 6, 0, Math.PI * 2, false);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = '#0000ff';
ctx.arc(agentX, agentY, 6, 0, Math.PI * 2, false);
ctx.fill();
ctx.font = '18px sans-serif';
ctx.fillStyle = "#000000";
ctx.fillText("X: " + agentX.toFixed(2), 10, 20);
ctx.fillText("Y: " + agentY.toFixed(2), 10, 40);
}
function aligned() {
agentX = 300;
agentY = 100;
}
function unaligned() {
agentX = 300;
agentY = 101;
}
loop();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas><br>
<button onclick="aligned()">Spawn agent aligned</button>
<button onclick="unaligned()">Spawn agent unaligned</button></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T01:20:09.380",
"Id": "473440",
"Score": "0",
"body": "If the main issue is that you're trying to fix a situation in which the code doesn't work as expected, wouldn't the right site for this be Stack Overflow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T01:26:06.760",
"Id": "473441",
"Score": "0",
"body": "@CertainPerformance it works when applying the fix I included. But the fix doesn't feel proper and I felt like Code Review is better as it's more of a \"is there a better way\" sort of question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T09:54:57.267",
"Id": "473476",
"Score": "0",
"body": "With an aligned target, `targetY` and `agentY` and `obstacleY` are the same, making both `vectorTargetY` and `vectorObstacleY` zero. You use these values in multiplications, multiplying anything by zero becomes zero. It all goes downhill from there."
}
] |
[
{
"body": "<h1>⚔️ A.I. vs. Physics</h1>\n\n<p>To solve this, you need to think a bit about the physics of your simulation, because it creates a problem for your A.I.</p>\n\n<p>The funny thing is, you solved it by just altering the vectors a bit, but you seem to not understand why, so let us change that!</p>\n\n<p><br/></p>\n\n<hr>\n\n<p><br/></p>\n\n<h1> May the force be with you</h1>\n\n<p>To put it simply: when you put two vectors on the same axis perfectly aligned, all that will happen is that the stronger force (i.e. greater vector) wins. Applying that to your simulation: when you align the agents on the same axis, the force of attraction towards the green agent wins over the repulsion from the red agent, forcing it ever closer towards it. I assume we all know what happens when the distances become zero, and you inevitably divide by zero? If you don't know: you can't. Other languages would panic, and Javascript just gives back <code>NaN</code>. Doing arithmetic with <code>NaN</code> will always yield <code>NaN</code> so the program still crashes somewhere down the line.</p>\n\n<p>So that is the problem. But why did your \"hack\" fix it, and how do you embrace the fix as a proper solution?</p>\n\n<p><br/></p>\n\n<hr>\n\n<p><br/></p>\n\n<h1> Solution</h1>\n\n<p>This is where the A.I. comes in. Think about it as if you were the blue agent: if you were walking straight towards an obstacle you are not allowed to touch, what would you do? I presume you would pick a direction, and turn into that direction to avoid the obstacle. Your agent is not as smart as you, so it does nothing and keeps its direction. When you added a tiny offset to its target vector, you decided <em>it should <strong>change direction</strong></em>, albeit in a clunky way.</p>\n\n<p>I propose you add a \"preference\" to the blue agent, deciding which direction to turn when it is perfectly aligned on some axis. You can use your fix, but I would personally prefer a solution to be more <em>deliberate</em>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const degreesToRadians = degrees => degrees * (Math.PI / 180);\nconst rotate = (x, y, radians) => [\n x * Math.cos(radians) - y * Math.sin(radians),\n x * Math.sin(radians) + y * Math.cos(radians)\n];\n\nconst preference = degreesToRadians(15);\nconst inProximity = lengthObstacle < 60;\nconst aligned = vectorTargetX === 0 || vectorTargetY === 0;\n\nif (inProximity && aligned) {\n [agentX, agentY] = rotate(agentX, agentY, preference);\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T04:34:11.967",
"Id": "474149",
"Score": "0",
"body": "Thank you! I understood the problem and why my quick fix worked but it felt a bit botched and I was thinking it might lead to bigger problems down the line because of an underlying problem to my entire AI logic. Btw, change `turnAway` to `rotate` or the other way around in your answer :) Have a nice weekend."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T11:04:22.633",
"Id": "474165",
"Score": "0",
"body": "@superlaks Whoops, yeah that should have been `rotate`. Great catch, happy to help :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T14:41:12.703",
"Id": "241558",
"ParentId": "241281",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241558",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T01:13:58.450",
"Id": "241281",
"Score": "1",
"Tags": [
"javascript",
"ai"
],
"Title": "AI agent fails when aligned with its target"
}
|
241281
|
<p>I would like to know if this code of the database for my Pokemon clone game follows general practices in syntax and general readability. I feel like I could cut down on my comment usage, and place comments in other places. All variables here are static, and as far as I've read static variables must be Uppercase. As for the constant variables, they should be ALL_UPPERCASE. I don't follow neither conventions, as you will see. I'm using <a href="https://playcanvas.com/" rel="nofollow noreferrer">PlayCanvas</a>. Any feedback is appreciated.</p>
<pre><code>var Database = pc.createScript('database');
// this is where all the static objects are stored
canInteract = true;
isPlayerIdle = true;
isSpeechFinished = true;
speechLine = 0; // used for animations in the middle of a speech
curRivalBattle = 0;
currentTalkingNPC = null;
enemyScript = null; // used by the battle script trio
dirArray = [new pc.Vec2(0,-1), new pc.Vec2(0,1), new pc.Vec2(-1,0), new pc.Vec2(1,0)];
oppDirArray = [1, 0, 3, 2]; // used by NPCs to face the player when talking
// saved variables
time = 0;
money = 5000;
worldMenuState = 0; // used to show the POKEDEX and POKEMON buttons in the world menu
rivalStarter = 0;
playerName = "~";
rivalName = "RIVAL";
fColor = new pc.Color(0, 0.8, 1, 1);
sColor = new pc.Color(0, 1, 1, 1);
lastPlaces = [0, 4];
lastPlaceTile = new pc.Vec2(-3.2, 4);
// specific variables (all are saved)
rivalBattleChecks = [false]; // this array keeps track of all rival's battles (as they should only be done once)
hasOldManDemo = false; // has the grandpa showed a demo at least once?
// option variables (all are saved)
optionVars = [0, 0, 0, 0, 0];
// controls
dirKeys = [pc.KEY_DOWN, pc.KEY_UP, pc.KEY_LEFT, pc.KEY_RIGHT];
buttonA = pc.KEY_A;
buttonB = pc.KEY_S;
buttonSt = pc.KEY_ENTER;
Database.prototype.initialize = function() {
// saved variables for easiear access of the following entities and scripts
database = this;
root = this.app.root;
HUD = root.findByName('HUD');
menuList = this.entity.script.menuList;
world = root.findByName('World');
pkmnFunctions = HUD.script.pkmnFunctions;
player = root.findByName('Player').script.player;
debugText = HUD.findByName('Debug Text');
speechBox = HUD.findByName('Speech Box').script.speechBox;
battleIntro = HUD.findByName('Battle Scene').script.battleIntro;
trainerSprites = this.app.assets.find('Trainer frames').resource;
backPkmnSprites = this.app.assets.find('Pokemon (back) frames').resource;
frontPkmnSprites = this.app.assets.find('Pokemon (front) frames').resource;
this.menu = HUD.findByName('World Menu');
};
Database.prototype.update = function(dt) {
kb = this.app.keyboard; // shortens all input code, for readability
time += dt;
if(kb.wasPressed(buttonSt) && isPlayerIdle) {
if(player.enabled) {
HUD.findByName('World Menu').script.worldMenu.changeState(true);
}
else if(HUD.findByName('World Menu').enabled) {
HUD.findByName('World Menu').script.worldMenu.changeState(false);
}
}
};
// item ID, item amount
inventory = [[2, 1]];
pStatXp = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
statusNames = ['OK', 'PSN', ''];
typeNames = ['BUG', 'DRAGON', 'ELECTRIC', 'FIGHTING', 'FIRE', 'FLYING', 'GHOST', 'GRASS', 'GROUND', 'ICE', 'NORMAL', 'POISON', 'PSYCHIC', 'ROCK', 'WATER'];
// player pkmn's stats during a battle (for stat moves)
pBattleStats = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]];
// ID, level, currentHP, maxHP, status, attack, defense, speed, special
ePkmn = [[-1, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 0, 0, 0, 0, 0]];
// pkmnID, name, level, xpPoints, currentHP, maxHP, status, attack, defense, speed, special, isTraded
pPkmn = [[-1, "??????????", 0, 0, 0, 0, 0, 0, 0, 0, 0, false],
[-1, "??????????", 0, 0, 0, 0, 0, 0, 0, 0, 0, false],
[-1, "??????????", 0, 0, 0, 0, 0, 0, 0, 0, 0, false],
[-1, "??????????", 0, 0, 0, 0, 0, 0, 0, 0, 0, false],
[-1, "??????????", 0, 0, 0, 0, 0, 0, 0, 0, 0, false],
[-1, "??????????", 0, 0, 0, 0, 0, 0, 0, 0, 0, false]];
// move ID, curernt PP (haha)
pMoves = [
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
];
// same as pMoves
eMoves = [
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1]],
];
// all arrays below will be added with more of their respective data throughout the development of the game
itemNames = ['OAK\'S PARCEL', 'POTION', 'SUPER POTION', 'HYPER POTION', 'MAX POTION'];
// (xy: position, zw: destination), next direction, place, variation ID (if needed)
teleTiles = [[new pc.Vec4(-3.2, 4, -15.2, 1.6), -1, 1], // Pallet Town to Mom House 0
[new pc.Vec4(-11.2, 6.4, -18.4, 6.4), 0, 2], // Mom House 0 to Mom House 1
[new pc.Vec4(-18.4, 6.4, -11.2, 6.4), 2, 1], // Mom House 1 to Mom House 0
[new pc.Vec4(3.2, 4, -24, -5.6), -1, 3, 0], // Pallet Town to Generic House #0 (Rival's Sister)
[new pc.Vec4(2.4, -0.8, -15.2, -8.8), -1, 4], // Pallet Town to Oak's Lab
[new pc.Vec4(8, 50.4, 20, 40.8), -1, 7, 0], // Viridian City to Poke-Mart #0
[new pc.Vec4(3.2, 45.6, 20, 48), -1, 8, 0], // Viridian City to Poke-Center #0
[new pc.Vec4(1.6, 53.6, -24, -5.6), -1, 3, 1]];
// colors actually range 0-1, but for ease of use the max value here is 255
// entrance type: 0 - two tiles horizontal, 1 - two tiles vertical
// xy: tile pos, 1st Color, 2nd Color, entrance type, places
placeTiles = [[new pc.Vec2(0.8, 8.8), new pc.Color(0, 200, 255, 1), new pc.Color(0,255,255,1), 0, 0, 5], // Route 1 to Pallet Town
[new pc.Vec2(0.8, 9.6), new pc.Color(127, 247, 31, 1), new pc.Color(87,183,247,1), 0, 5, 6, 0], // Pallet Town to Route 1
[new pc.Vec2(0.8, 37.6), new pc.Color(157, 255, 61, 1), new pc.Color(137,233,255,1), 0, 5, 6], // Route 1 to Viridian City
[new pc.Vec2(0.8, 36.8), new pc.Color(127, 247, 31, 1), new pc.Color(87,183,247,1), 0, 5, 6, 0]]; // Viridian City to Route 1
// (xy: min X and Y, zw: max X and Y), min level, max level, encounter chance (by 100%), encounter ratio (by pokedex ID)
wildTiles = [[new pc.Vec4(0.4, 8, 1.6, 11.2), 4, 7, 25, [18, 15]], // Pallet Town - Route 1
[new pc.Vec4(-4, 12, -1.6, 12.8), 4, 7, 25, [18, 15]], // Route 1
[new pc.Vec4(-2.4, 13.6, 0, 14.4), 4, 7, 25, [18, 15]], // Route 1
[new pc.Vec4(2.4, 12, 4.8, 12.8), 4, 7, 25, [18, 15]], // Route 1
[new pc.Vec4(4, 13.6, 6.4, 14.4), 4, 7, 25, [18, 15]], // Route 1
[new pc.Vec4(2.4, 16.8, 4.8, 19.2), 4, 7, 25, [18, 15]]]; // Route 1
// attack types: status 0, physical 1, special 2
// name, type, attack type, power, accuracy, max PP, affected stat, stat change, status change
moves = [['TACKLE', 10, 1, 40, 100, 35],
['GROWL', 10, 0, 0, 100, 40, 0, -1, -1],
['SCRATCH', 10, 1, 40, 100, 35],
['TAIL WHIP', 10, 0, 0, 100, 30, 1, -1, -1],
['GUST', 5, 2, 40, 100, 35],
['LEECH SEED', 7, 0, 0, 90, 10]];
// moveID, required level
lvlPkmnMoves = [
[[0,1], [1,1], [5, 7]], // 0
[[]], // 1
[[]], // 2
[[1, 1], [2, 1]], // 3
[[]], // 4
[[]], // 5
[[0, 1], [3, 1]], // 6
[[]], // 7
[[]], // 8
[[]], // 9
[[]], // 10
[[]], // 11
[[]], // 12
[[]], // 13
[[]], // 14
[[4, 1]], // 15
[[]], // 16
[[]], // 17
[[0, 1], [3, 1]], // 18
];
// Bug 0, Dragon 1, Electric 2, Fighting 3, Fire 4, Flying 5, Ghost 6, Grass 7, Ground 8, Ice 9, Normal 10, Poison 11, Psychic 12, Rock 13, Water 14
// name, health, attack, defense, speed, special, type 1, type 2, yield group, base yield, iconID
pkmn = [["BULBASAUR", 45, 49, 49, 45, 65, 7, 11, 2, 64, 1], // 0
["IVYSAUR", 60, 62, 63, 60, 80, 7, 11, 2, 142], // 1
["VENUSAUR", 80, 82, 83, 80, 10, 7, 11, 2, 263], // 2
["CHARMANDER", 39, 52, 43, 65, 50, 4, -1, 2, 62], // 3
["CHARMELEON", 58, 64, 58, 80, 65, 4, -1, 2, 142], // 4
["CHARIZARD", 78, 84, 78, 100, 85, 4, 5, 2, 267], // 5
["SQUIRTLE", 44, 48, 65, 43, 50, 14, -1, 2, 63], // 6
["WARTORTLE", 59, 63, 80, 58, 65, 14, -1, 2, 142], // 7
["BLASTOISE", 79, 83, 100, 78, 85, 14, -1, 2, 265], // 8
["CATERPIE", 45, 30, 35, 45, 20, 0, -1, 1, 39], // 9
["METAPOD", 50, 20, 55, 30, 25, 0, -1, 1, 72], // 10
["BUTTERFREE", 60, 45, 50, 70, 80, 0, 5, 1, 198], // 11
["WEEDLE", 40, 35, 30, 50, 20, 0, 11, 1, ], // 12
["KAKUNA", 45, 25, 50, 35, 25, 0, 11, 1, ], // 13
["BEEDRILL", 65, 80, 40, 75, 45, 0, 11, 1], // 14
["PIDGEY", 40, 45, 40, 56, 35, 10, 3, 1, 55], // 15
["PIDGEOTTO", 63, 60, 55, 71, 50, 10, 3], // 16
["PIDGEOT", 83, 80, 75, 91, 70, 10, 3], // 17
["RATTATA", 30, 56, 35, 72, 25, 10, -1, 1, 57], // 18
["RATICATE", 55, 81, 60, 97, 50, 10, -1], // 19
["SPEAROW", 40, 60, 30, 70, 31],
["FEAROW", 65, 90, 65, 100, 61],
["EKANS", 35, 60, 44, 55, 40],
["ARBOK", 60, 85, 69, 80, 65],
["PIKACHU", 35, 55, 30, 90, 50],
["RAICHU", 60, 90, 55, 100, 90],
["SANDSHREW", 50, 75, 85, 40, 30],
["SANDSLASH", 75, 100, 110, 65, 55],
["NIDORAN#", 55, 47, 52, 41, 40],
["NIDORINA", 70, 62, 67, 56, 55],
["NIDOQUEEN", 90, 82, 87, 76, 75],
["NIRDORAN@", 46, 57, 40, 50, 40],
["NIDORINO", 61, 72, 57, 65, 55],
["NIDOKING", 81, 92, 77, 85, 75],
["CLEFAIRY", 70, 45, 48, 35, 60],
["CLEFABLE", 95, 70, 73, 60, 85],
["VUPLIX", 38, 41, 40, 65, 65],
["NINETALES", 73, 76, 75, 100, 100],
["JIGGLYPUFF", 115, 45, 20, 20, 25],
["WIGGLYTUFF"],
["ZUBAT"],
["GOLBAT"],
["ODDISH"],
["GLOOM"],
["VILEPLUME"],
["PARAS"],
["PARASECT"],
["VENONAT"],
["VENOMOTH"],
["DIGLETT"],
["DUGTRIO"],
["MEOWTH"],
["PERSIAN"],
["PSYDUCK"],
["GOLDUCK"],
["MANKEY"],
["PRIMEAPE"],
["GROWLITHE"],
["ARCANINE"],
["POLIWAG"],
["POLIWHIRL"],
["POLIWRATH"],
["ABRA"],
["KADABRA"],
["ALAKAZAM"],
["MACHOP"],
["MACHOKE"],
["MACHAMP"],
["BELLSPROUT"],
["WEEPINBELL"],
["VICTREEBELL"],
["TENTACOOL"],
["TENTACRUEL"],
["GEODUDE"],
["GRAVELER"],
["GOLEM"],
["PONYTA"],
["RAPIDASH"],
["SLOWPOKE"],
["SLOWBRO"],
["MAGNEMITE"],
["MAGNETON"],
["FARFETCH\'D"],
["DODUO"],
["DODRIO"],
["SEEL"],
["DEWGONG"],
["GRIMER"],
["MUK"],
["SHELDER"],
["CLOYSTER"],
["GASTLY"],
["HAUNTER"],
["GENGAR"],
["ONIX"],
["DROWZEE"],
["HYPNO"],
["KRABBY"],
["KINGLER"],
["VOLTORB"],
["ELECTRODE"],
["EXEGGCUTE"],
["EXEGGUTOR"],
["CUBONE"],
["MAROWAK"],
["HITMONLEE"],
["HITMONCHAN"],
["LIKITUNG"],
["KOFFING"],
["WEEZING"],
["RHYHORN"],
["RHYDON"],
["CHANSEY"],
["TANGELA"],
["KANGASKHAN"],
["HORSEA"],
["SEADRA"],
["GOLDEEN"],
["SEAKING"],
["STARYU"],
["STARMIE"],
["MR. MIME"],
["SCYTHER"],
["JYNX"],
["ELECTABUZZ"],
["MAGMAR"],
["PINSIR"],
["TAUROS"],
["MAGIKARP"],
["GYARADOS"],
["LAPRAS"],
["DITTO"],
["EEVEE"],
["VAPOREON"],
["JOLTEN"],
["FLAREON"],
["PORYGON"],
["OMANYTE"],
["OMASTAR"],
["KABUTO"],
["KABUTOPS"],
["AERODACTYL"],
["SNORLAX"],
["ARTICUNO"],
["ZAPDOS"],
["MOLTRES"],
["DRATINI"],
["DRAGONAIR"],
["DRAGONITE"],
["MEWTWO"],
["MEW"]];
regPkmn = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false];
boxedPkmn = [[], [], [], [], [], [], [], [], [], []];
boxedMoves = [[], [], [], [], [], [], [], [], [], []];
boxedStatXp = [[], [], [], [], [], [], [], [], [], []];
</code></pre>
|
[] |
[
{
"body": "<p>You are not declaring any of your variables. This will</p>\n\n<ul>\n<li>throw errors, if the script is running in strict mode (which it should be - best to always use strict mode, it can turn hard-to-identify bugs into explicit errors that can be fixed)</li>\n<li>Or, if you aren't running in strict mode, every undeclared variable will become implicitly global, as well as putting a property on the global object.</li>\n</ul>\n\n<p>Always declare variables. In modern Javascript, declare them with <code>const</code> whenever possible, and <code>let</code> when you must reassign them. For example:</p>\n\n<pre><code>const oppDirArray = [1, 0, 3, 2]; // this will never be reassigned\n// ...\nlet money = true; // this may be reassigned later\n</code></pre>\n\n<p>Most of your variables are on the top level. Even if they were declared properly, this is a potential code smell - <a href=\"https://softwareengineering.stackexchange.com/a/388055\">variable scope should be as narrow as reasonable</a>, usually. For example, your</p>\n\n<pre><code>speechLine = 0; // used for animations in the middle of a speech\n</code></pre>\n\n<p>sounds like it would probably be better if it were scoped only to a part of the code that handles animations or speech. The same thing can be said for most of your variables.</p>\n\n<p>If you <em>don't</em> constrain the scope of your variables, figuring out what all a particular function has access to, <em>should</em> be able to access, and <em>should</em> be able to change given its responsibilities can become a messy headache.</p>\n\n<p>If you're going to declare a variable, make sure to use it later. For example, you do <code>debugText = HUD.findByName('Debug Text');</code>, but then never reference <code>debugText</code> again. If it's really not being used anywhere, might as well just delete it. (If you <em>do</em> keep it, the <code>debugText</code> variable should only be used within its <code>initialize</code> function - if another part of the code needs to be able to see it, call <em>another</em> function within <code>initialize</code> to pass it around, instead of reassigning a global variable.) Same thing for most of the other variables in <code>initialize</code>.</p>\n\n<p>Consider using a linter like <a href=\"https://eslint.org/\" rel=\"nofollow noreferrer\">eslint</a> to automatically prompt you to correct many of these potential mistakes.</p>\n\n<p>In <code>Database.prototype.update</code>, instead of repeating <code>HUD.findByName('World Menu').script.worldMenu.changeState</code> multiple times, you can define a function that calls it with the desired argument, and you can save <code>HUD.findByName('World Menu')</code> in another variable:</p>\n\n<pre><code>if (kb.wasPressed(buttonSt) && isPlayerIdle) {\n const worldMenu = HUD.findByName('World Menu');\n const changeState = arg => worldMenu.script.worldMenu.changeState(arg);\n if(player.enabled) {\n changeState(true);\n } else if(worldMenu.enabled) {\n changeState(false);\n }\n}\n</code></pre>\n\n<p>Commenting on the point of a variable is fine in general, though usually it'd be preferable for the point of a variable to be clearly indicated by a combination of its <em>scope</em> (hopefully narrow, discussed above) and its <em>name</em>. Don't be afraid to use descriptive names; being able to understand the code at a glance is more important than being concise. If you can't figure out a way to constrain the scope and create a name such that the meaning of the variable is obvious, a comment is not only fine, but it's probably <em>preferable</em> over the alternative. (But, that situation should be uncommon - <em>usually</em> you should be able to precisely name a variable or constrain its scope enough such that its meaning is obvious without a comment)</p>\n\n<p>For example, rather than</p>\n\n<pre><code>hasOldManDemo = false; // has the grandpa showed a demo at least once?\n</code></pre>\n\n<p>maybe use</p>\n\n<pre><code>let oldManHasShownPokeballDemo = false;\n</code></pre>\n\n<p>Note that using grammar like the above results in logical checks looking extremely readable, eg:</p>\n\n<pre><code>if (oldManHasShownPokeballDemo) {\n // Then the old man has shown the pokeball demo\n}\n</code></pre>\n\n<p>Ideally, for organizational purposes such a variable would exist in an object indicating the map state that can be looked up when required, rather than being global.</p>\n\n<p>I wouldn't worry much about naming conventions, given that you're already using <code>camelCase</code>, which is pretty common even for completely static variables. Better to get the fundamentals of script organization down than to worry about more opinionated subjects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T02:24:46.027",
"Id": "473444",
"Score": "0",
"body": "Thanks for the feedback, that was a lot quicker than I expected. However, I feel like long variables like 'oldManHasShownPokeballDemo' may be a little too long, which is why I decided to describe it with a comment. Are these types of names really acceptable, or should I only use them a few times? I feel like accepting these long names as a standard would clutter code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T06:57:21.840",
"Id": "473462",
"Score": "0",
"body": "If you make it shorter, it will be less obvious what it refers to, and you may need to add a comment or go to the place where it's defined to read the comment describing what the variable is. I'd make it long enough such that you'd expect someone reading the code to be able to understand what it's representing upon reading the variable name. If you define it in a narrow scope, it shouldn't have to be long - eg, in an `OldMan` module or object, you could define it as `hasShownDemo`. That would be a better choice than having a long variable name on the top level."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T02:05:15.047",
"Id": "241284",
"ParentId": "241282",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T01:21:28.767",
"Id": "241282",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"game",
"database",
"static"
],
"Title": "Static Arrays and Variables (JavaScript)"
}
|
241282
|
<p>1) This code's task is to create graphs of various algebraic, logarithmic and trigonometric functions and relations using Python's <code>matplotlib.plyplot</code> module. Turning code into a graph is a process. First, I secure a list of <code>xs</code> using <code>set_width(width)</code>. Then I iterate through the list by substituting each <code>x</code> into the function's equation. The result is a same-length list of the ys of the xs. Now that I have the <code>xs</code> and the functions of the <code>xs</code>, I can plug the two list into <code>ply.plot()</code> and display the result. The exceptions to this process are the logarithmic and square root functions due to math domain errors.</p>
<p>2) How would I be able to graph a circle algebraically without creating two separate parts?</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import math
def set_width(width):
"""Sets how many xs will be included in the graphs (\"width\" of the graph)"""
return list(range(-width, width + 1))
def linear(width):
"""Graphs a linear function via slope intercept form"""
xs = set_width(width)
def ys(m=1.0, b=0):
return [m * x + b for x in xs]
'''
"xs" and "ys" are not labeled "domain" and "range" because "all real numbers" will be limited to just a certain
list of xs and ys
'''
plt.plot(xs, ys())
plt.plot(xs, ys(3, 2))
plt.plot(xs, ys(5, -3))
plt.grid()
plt.show()
def quadratic(width):
"""Graphs a quadratic function via vertex form"""
xs = set_width(width)
def ys(a=1.0, h=0, k=0):
return [a * (x - h) ** 2 + k for x in xs]
plt.plot(xs, ys())
plt.plot(xs, ys(1, 10, -50))
plt.plot(xs, ys(-4))
plt.grid()
plt.show()
def exponential(width):
"""Graphs an exponential function"""
xs = set_width(width)
def ys(a=1.0, b=2.0, h=0, k=0):
return [a * b ** (x - h) + k for x in xs]
plt.plot(xs, ys())
plt.plot(xs, ys(3, 2, 4, 20))
plt.plot(xs, ys(5, 0.75))
plt.grid()
plt.show()
def absolute(width):
"""Graphs an absolute function"""
xs = set_width(width)
def ys(a=1.0, h=0, k=0):
return [a * abs(x - h) + k for x in xs]
plt.plot(xs, ys())
plt.plot(xs, ys(4, 7))
plt.plot(xs, ys(-0.5, -4, -15))
plt.grid()
plt.show()
def square_root(width):
"""Graphs a square root function"""
def transform(a=1.0, h=0, k=0):
xs = [x for x in set_width(width) if x - h >= 0]
ys = [a * np.sqrt(x - h) + k for x in xs]
return xs, ys
parent = transform()
plt.plot(parent[0], parent[1])
twice_r5 = transform(2, 5)
plt.plot(twice_r5[0], twice_r5[1])
half_l2_u5 = transform(.5, -2, 5)
plt.plot(half_l2_u5[0], half_l2_u5[1])
plt.grid()
plt.show()
def cube_root(width):
"""Graphs a cube root function"""
xs = set_width(width)
def ys(a=1.0, h=0, k=0):
return [a * np.cbrt(x - h) + k for x in xs]
plt.plot(xs, ys())
plt.plot(xs, ys(-3, 0, 1))
plt.plot(xs, ys(2, 4, -3))
plt.grid()
plt.show()
def sideways_parabola(height):
"""Graphs a sideways parabola (quadratic relation)"""
ys = set_width(height)
def xs(a=1.0, h=0, k=0):
return [a * (y - k) ** 2 + h for y in ys]
plt.plot(xs(), ys)
plt.plot(xs(3, 3, 3), ys)
plt.plot(xs(-2, -7, 0), ys)
plt.grid()
plt.show()
def logarithms(width):
"""Graphs a logarithmic function"""
def ys(b=2.0, a=1.0, h=0, k=0):
xs = [x for x in set_width(width) if x - h > 0]
ys = [a * math.log(x - h, b) + k for x in xs]
return xs, ys
parent = ys()
plt.plot(parent[0], parent[1])
three_r3 = ys(3, 2, 1000)
plt.plot(three_r3[0], three_r3[1])
plt.grid()
plt.show()
def sine(width):
"""Graphs a sine function"""
xs = set_width(width)
def ys(a=1.0, h=0, k=0):
return [a * np.sin(x - h) + k for x in xs]
plt.plot(xs, ys())
plt.plot(xs, ys(3, 5))
plt.plot(xs, ys(0.5, 0, -3))
plt.grid()
plt.show()
def cosine(width):
"""Graphs a cosine function"""
xs = set_width(width)
def ys(a=1.0, h=0, k=0):
return [a * np.cos(x - h) + k for x in xs]
plt.plot(xs, ys())
plt.plot(xs, ys(-1))
plt.plot(xs, ys(2, 7, 9))
plt.grid()
plt.show()
def tangent(width):
"""Graphs the tangent function"""
xs = set_width(width)
def ys(a=1.0, h=0, k=0):
return [a * math.tan(x - h) + k for x in xs]
plt.plot(xs, ys())
plt.plot(xs, ys(1, -10))
plt.plot(xs, ys(6, -8, 20))
plt.grid()
plt.show()
linear(15)
quadratic(15)
exponential(7)
absolute(15)
square_root(16)
cube_root(27)
sideways_parabola(15)
logarithms(10000)
sine(15)
cosine(15)
tangent(25)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:26:59.017",
"Id": "473507",
"Score": "0",
"body": "What is your objective here - to get a review, or to fix up the _exceptions to this process [, the] math domain errors_ ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:35:29.823",
"Id": "473511",
"Score": "0",
"body": "OK; well keep in mind that CodeReview policy requires working code. If this code is \"working enough\" for reviewers to be able to meaningfully run it and suggest improvements, fine; but break-fix is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:38:34.110",
"Id": "473512",
"Score": "0",
"body": "@Reinderien It is working code. The logarithmic and square root functions are just coded differently due to math domain errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T09:25:18.327",
"Id": "475273",
"Score": "0",
"body": "@miAK Apart from logarithmic and square root functions, rest of the functions have very similar structure. Wouldn't it be much more cleaner if you make one plot function and input different arguments for different plots?"
}
] |
[
{
"body": "<h2>Usage of numpy</h2>\n\n<p>You have it as an <code>import</code>, but there are places where you could benefit from using it where you currently aren't.</p>\n\n<p>For one,</p>\n\n<pre><code>list(range(-width, width + 1))\n</code></pre>\n\n<p>should use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.arange.html?highlight=arange#numpy.arange\" rel=\"nofollow noreferrer\"><code>arange</code></a>.</p>\n\n<pre><code>[m * x + b for x in xs]\n</code></pre>\n\n<p>should not use a list comprehension; instead,</p>\n\n<pre><code>m*xs + b\n</code></pre>\n\n<p>where <code>xs</code> is an <code>ndarray</code>. Your other list comprehensions in the graphing functions should be likewise vectorized.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:50:11.487",
"Id": "241338",
"ParentId": "241287",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T04:14:50.857",
"Id": "241287",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"mathematics"
],
"Title": "Graphing various mathematical functions in Python"
}
|
241287
|
<p>So in this problem I am given an NxN matrix, in which each value of the matrix represents an altitude. I need to find the best path from the top-left corner to the bottom-right one, my moves being limited to down and right.
Also, the path needs to be chosen in such way that the differences in altitude are the smallest, basically finding the path that has the smallest sum of differences in altitude.
I think I am using dynamic programming in my solution.(I am still a beginner, I am not so sure of this) </p>
<p>First I begin by creating another matrix that has the sums of the differences in altitude of the edges of the matrix, being the easiest to calculate because there is a single way that those sums can be computed. (S is the new matrix, while A is the matrix that is given)</p>
<pre><code> S[0][0]=0;
for(int i=1;i<=n-1;i++)
{S[0][i]=S[0][i-1]+abs(A[0][i]-A[0][i-1]);
S[i][0]=S[i-1][0]+abs(A[i][0]-A[i-1][0]);}
</code></pre>
<p>Secondly, I am traversing the matrix by comparing the sums of the already calculated paths(the edges at first)+ the two ways (up or down). Whichever one is smallest, will be put in the new matrix.</p>
<pre><code>for(int i=1;i<=n-1;i++)
for(int j=1;j<=n-1;j++)
if(S[i-1][j]+abs(A[i][j]-A[i-1][j])<S[i][j-1]+abs(A[i][j]-A[i][j-1]))
S[i][j]=S[i-1][j]+abs(A[i][j]-A[i-1][j]);
else
S[i][j]= S[i][j-1]+abs(A[i][j]-A[i][j-1]);
</code></pre>
<p>This problem worked for the examples that I tried, but I am wondering if there is a more efficient way. Also, i could have made a mistake (or many :) ), so please feel free to tell me if you think it is a good solution, a bad one and if you have any advice for me. </p>
<p>Thank you for the attention anyways!</p>
<p>The complete code:</p>
<pre><code>#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
ifstream fin("data.in");
ofstream fout("data.out");
int A[21][21],n,S[21][21],D[42][4];
int main()
{ //reading the matrix
fin>>n;
for(int i=0;i<=n-1;i++)
for(int j=0;j<=n-1;j++)
fin>>A[i][j];
//computing the edges of the new matrix
S[0][0]=0;
for(int i=1;i<=n-1;i++)
{S[0][i]=S[0][i-1]+abs(A[0][i]-A[0][i-1]);
S[i][0]=S[i-1][0]+abs(A[i][0]-A[i-1][0]);}
//comparing the sums
for(int i=1;i<=n-1;i++)
for(int j=1;j<=n-1;j++)
if(S[i-1][j]+abs(A[i][j]-A[i-1][j])<S[i][j-1]+abs(A[i][j]-A[i][j-1]))
S[i][j]=S[i-1][j]+abs(A[i][j]-A[i-1][j]);
else
S[i][j]= S[i][j-1]+abs(A[i][j]-A[i][j-1]);
//a new matrix to identify the path and memorize the down/right moves
int i,j,x;
i=n-1;
j=n-1;
x=1;
D[0][0]=A[n-1][n-1];
while(i!=0&&j!=0)
{if(S[i-1][j]<S[i][j-1])
{
D[x][0]=A[i-1][j];
D[x][1]=1; //1 for down
x++;
i=i-1;}
else
{
D[x][0]=A[i][j-1];
D[x][1]=2; //2 for right
x++;
j=j-1;
}}
if(S[1][0]>S[0][1])
D[x][1]=2;
else
D[x][1]=1;
D[x][0]=A[0][0];
//showing the path
fout<<"The path:"<<endl;
for(i=x;i>=0;i--)
{ fout<<endl<<D[i][0];
if(i!=0)
{if(D[i][1]==1)
fout<<endl<<"down";
else
if(D[i][1]==2)
fout<<endl<<"right";}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T11:16:45.560",
"Id": "473482",
"Score": "1",
"body": "Welcome to Code Review. Are you aware the code in your question is absolutely terrible with regards to readability? Do you have tests written for this verifying it works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T13:17:54.717",
"Id": "473490",
"Score": "0",
"body": "@Mast Hello! Yes, I have tried a few matrices and so far they worked fine. I am sorry for the readability, as I said I am new to this and I try to improve. I wish I knew how I could make it better. Do you have any advice for me?"
}
] |
[
{
"body": "<p>Don't take this the wrong way, but my first thought when I looked at your code was \"ugh do I really want to read this?\" You have (probably) been thinking a lot about <code>A</code>, <code>S</code>, <code>n</code>, and <code>D</code> over the last few hours, but if you look at this again in 2 years, it will look like nonsense. So your number one goal should be to fix readability. Then you can start thinking about correctness and performance.</p>\n\n<p>I would recommend reading through a C++ style guide for general tips. <a href=\"https://google.github.io/styleguide/cppguide.html\" rel=\"nofollow noreferrer\">Here is one</a>, but there are many others. I'll still list a few of the biggest mistakes:</p>\n\n<ul>\n<li>You should avoid single letter variable names</li>\n<li>Try to express your logic in functions</li>\n<li>Don't use global variables</li>\n<li>Indent consistently (or better yet, automatically with help from your IDE)</li>\n</ul>\n\n<p>All of these have been written about extensively in style guides, programming manuals, other code reviews, etc...</p>\n\n<hr>\n\n<pre><code>fin>>n;\n</code></pre>\n\n<p>What if <code>n > 21</code>? If you have some reason to believe it cannot be, then you should <code>assert(n < 22)</code>. But in this case, it's easy enough to support any <code>n</code> with <code>std::vector</code>.</p>\n\n<hr>\n\n<pre><code>i<=n-1\n</code></pre>\n\n<p>The canonical way to write this is <code>i < n</code>.</p>\n\n<hr>\n\n<pre><code>`S[i-1][j]+abs(A[i][j]-A[i-1][j])`\n</code></pre>\n\n<p>I think this section is correct, but I have more style comments!</p>\n\n<ol>\n<li><p>This is complicated looking for no reason. You're making yourself think harder than you have to which means you will accomplish less stuff with your mental bandwidth. How about something like <code>costOfStep(i-1, j)</code>?</p></li>\n<li><p>This gets exactly repeated twice and a very similar statement is also repeated twice. That's a telltale sign you should at least use a variable or better yet write a function to compute this.</p></li>\n</ol>\n\n<p>Isn't the snipped below easier to read?</p>\n\n<pre><code>for(int i = 1; i < n; i++) {\n for(int j = 1; j < n; j++) {\n int costOfStepDown = costOfStep(i - 1, j);\n int costOfStepRight = costOfStep(i, j - 1);\n minCosts[i - 1][j] = std::min(costOfStepDown, costOfStepRight);\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>//a new matrix to identify the path and memorize the down/right moves\nint i,j,x;\ni=n-1;\nj=n-1;\nx=1;\n</code></pre>\n\n<p>From this point on, I think you are using more time/memory than necessary. I believe you can refactor your code so that you only store one matrix for both the input array and one for the cumulative array (or two matrices if it's clearer, but not more). And you can store your path as a 1D vector. Doing two passes leads to unnecessary code which leads to pointless bugs and wasted time. Keep it minimal! You were following a decently minimal algorithm until this part...</p>\n\n<p>Also, here are my thoughts while reading this snippet:</p>\n\n<ol>\n<li><p>Nice a comment... Where is the new matrix?</p></li>\n<li><p>Oh some single named variables. No idea what these do. Hopefully I can figure it out.</p></li>\n<li><p>Huh they are not initialized. I hope the author was careful not to use uninitialized values.</p></li>\n</ol>\n\n<p>That's a lot of thinking for not very much action. How about this:</p>\n\n<pre><code>Matrix path;\npath[0][0] = inputMatrix[size - 1][size - 1];\nfor (int i = 0, j = 0; i < size && j < size; /*increment in body*/) {\n ...\n</code></pre>\n\n<hr>\n\n<p>This is more of a general tip than a specific comment. I hope you find it useful.</p>\n\n<p>Many dynamic programming problems are easy to solve with recursion. Here's some pseudo-code for this problem:</p>\n\n<pre><code>// return the min cost of traveling from pos to the bottom-right of inputMatrix\nint minCost(Matrix const& input, Position const pos = top-left) {\n if (pos == bottom-right) {\n return 0;\n }\n return std::min(minCost(input, pos.right), minCost(input, pos.down));\n}\n</code></pre>\n\n<p><code>Position</code> could be <code>std::pair<int, int></code> and <code>Matrix</code> could be <code>std::vector<std::vector<int>></code>.</p>\n\n<p>This function will calculate the correct answer, but it is slow because it repeatedly calculates the min cost of the same position many times. Fix that:</p>\n\n<pre><code>int minCostHelper(Matrix const& input, Position const pos, Cache cache) {\n if (cache.hasSeen(pos)) {\n return cache.valueOf(pos);\n }\n if (pos == bottom-right) {\n return 0;\n }\n auto result = std::min(minCost(input, pos.right), minCost(input, pos.down));\n cache.insert(pos, result);\n return result;\n}\n\nint minCost(Matrix const& input) {\n Cache cache;\n return minCostHelper(input, top-left, cache);\n}\n</code></pre>\n\n<p><code>Cache</code> could be an <code>std::map</code>.</p>\n\n<p>The technical term for \"fix\" in this case is \"memoize.\" I think this style is easier to read/debug than manually creating arrays. It's a question of personal preference though.</p>\n\n<p>Here is a challenge: can you write a function that will memoize another function?</p>\n\n<pre><code>template <typename Function>\nFunction memoize(Function);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:28:49.023",
"Id": "241335",
"ParentId": "241289",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T06:25:27.673",
"Id": "241289",
"Score": "1",
"Tags": [
"c++",
"matrix",
"dynamic-programming"
],
"Title": "Matrix problem, the path that is the flattest"
}
|
241289
|
<p>In the <code>main()</code> function of the following code, I wrote a very naive command parsing. Is there any more efficient way? </p>
<p>This program is aim to deal with <em>ADD, SUB, MUL, DIV</em> these four arithmetic operations for integers. The input would be in form like: <code>ADD 1 1</code>, <code>MUL 12 90</code>. And also there would be a special input character <code>%</code> which means use the last result. For example, <code>ADD 1 1</code> would return <code>2</code>, then <code>ADD % 1</code> would return <code>3</code>.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (*calc_function)(int, int);
typedef struct operation {
char *name;
calc_function calculate;
} Operation;
int add(int a, int b) { return a+b; }
int sub(int a, int b) { return a-b; }
int mul(int a, int b) { return a*b; }
int divi(int a, int b) { return a/b; }
int calc(int a, int b, int (*c)(int, int)) {
return c(a, b);
}
int main() {
char *command = malloc(9);
int result = 0;
int a;
int b;
Operation ADD = {"ADD", add};
Operation SUB = {"SUB", sub};
Operation MUL = {"MUL", mul};
Operation DIV = {"DIV", divi};
Operation ops[4] = {ADD, SUB, MUL, DIV};
while((command = fgets(command, 9, stdin)) != NULL) {
for(int i = 0; i < 4; ++i) {
if (0 == strncmp(ops[i].name, command, 3)) {
command = strchr(command, ' ');
command++;
if (*command == '%') {
a = result;
} else {
sscanf(command, "%d", &a);
}
command = strchr(command, ' ');
command++;
if (*command == '%') {
b = result;
} else {
sscanf(command, "%d", &b);
}
result = ops[i].calculate(a, b);
printf("%d\n", result);
}
}
}
free(command);
return 0;
}
</code></pre>
<p>Also, any advice on improving the performence and style of this program would be highly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T08:10:50.637",
"Id": "473467",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<h2>Overall Impression</h2>\n\n<p>The code is pretty good. The structure of the code is good, good use of <code>typedef</code>. The code uses that safe version of string comparison <code>strncmp(string1, string2, maxLength)</code>. Each Variable is declared on a separate line.</p>\n\n<p>One overall observation is the code is not very extendable.</p>\n\n<p>The program might be more understandable to the user if <code>=</code> is used to get the result rather than <code>%</code>. This would also possibly allow the addition of a <code>modulus</code> operation.</p>\n\n<h2>Error Checking</h2>\n\n<p>There are at least 2 places in the code where error checking should be performed, the first is always check the return value of <code>malloc(size_t size)</code>. If <code>malloc()</code> fails for some reason, it returns <code>NULL</code> access through a null pointer results in UB (Unknown Behavior). Quite often it terminates the program in some nasty manner.</p>\n\n<p>It's always best to check user input for errors so that they can be reported and the user can correct their error.</p>\n\n<h2>Magic Numbers</h2>\n\n<p>There are Magic Numbers in the <code>main()</code> function (<code>9</code>, <code>4</code> and <code>3</code>), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n\n<p>In the case of the array of <code>Operations</code> called <code>ops</code> you don't need to specify <code>4</code> in the array definition, and you can get the size after the creation of the array using this formula: <code>sizeof(ops)/sizeof(*ops);</code> </p>\n\n<p>In the cases of using <code>9</code> and <code>3</code> define a constant values that can change the value throughout the program:</p>\n\n<p>At the top of the file:</p>\n\n<pre><code>#define INPUT_COMMAND_SIZE 9\n#define OPERATION_SIZE 3\n</code></pre>\n\n<h2>Complexity</h2>\n\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility</a> Principle that applies here. The Single Responsibility Principle states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<h2>Declare Variables When Needed</h2>\n\n<p>The original version of the C programming language did require variables to be defined at the top of the function, however, this hasn't been true since 1989. It is better to declare the variables when they are necessary to reduce the scope of the variables and make the code easier to understand and maintain.</p>\n\n<h2>Initialize Local Variables</h2>\n\n<p>The C programming language does not automatically initialize variables. Uninitialized variables can sometimes be the cause of UB. It is generally a best practice to always initialize variables when they are declared.</p>\n\n<h2>Horizontal Spacing</h2>\n\n<p>Code is much more readable when there is a space separating operators and operands in an expression: <code>return a - b;</code>.</p>\n\n<h2>System Macros for Exit Status</h2>\n\n<p>The code already includes <code>stdlib.h</code> for the definitions of <code>malloc()</code> and <code>free()</code>. Since <code>stdlib.h</code> is already included it would be better to use the system constants <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> which can make the code more portable. These constants are defined in <code>stdlib.h</code>.</p>\n\n<h2>Example Using Suggestions</h2>\n\n<p>Note error checking on user input hasn't been added.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define INPUT_COMMAND_SIZE 9\n#define OPERATION_SIZE 3\n\ntypedef int (*calc_function)(int, int);\n\ntypedef struct operation {\n char *name;\n calc_function calculate;\n\n} Operation;\n\nint add(int a, int b)\n{\n return a + b;\n}\n\nint sub(int a, int b)\n{\n return a - b;\n}\nint mul(int a, int b)\n{\n return a * b;\n}\n\nint divi(int a, int b)\n{\n return a / b;\n}\n\nint programLoop(Operation *ops, int opsCount)\n{\n int programStatus = EXIT_SUCCESS;\n char *command = malloc(INPUT_COMMAND_SIZE);\n if (command != NULL){\n while((command = fgets(command, INPUT_COMMAND_SIZE, stdin)) != NULL) {\n\n for(int i = 0; i < opsCount; ++i) {\n int result = 0;\n int a = 0;\n int b = 0;\n if (0 == strncmp(ops[i].name, command, OPERATION_SIZE)) {\n command = strchr(command, ' ');\n command++;\n if (*command == '%') {\n a = result;\n } else {\n sscanf(command, \"%d\", &a);\n }\n command = strchr(command, ' ');\n command++;\n if (*command == '%') {\n b = result;\n } else {\n sscanf(command, \"%d\", &b);\n }\n result = ops[i].calculate(a, b);\n printf(\"%d\\n\", result);\n }\n }\n }\n free(command);\n }\n else\n {\n fprintf(stderr, \"Malloc returned NULL\\n\");\n programStatus = EXIT_FAILURE;\n }\n\n return programStatus;\n}\n\nint main() {\n Operation ADD = {\"ADD\", add};\n Operation SUB = {\"SUB\", sub};\n Operation MUL = {\"MUL\", mul};\n Operation DIV = {\"DIV\", divi};\n\n Operation ops[] = {ADD, SUB, MUL, DIV};\n\n int opsCount = sizeof(ops)/sizeof(*ops);\n\n return programLoop(ops, opsCount);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:04:36.907",
"Id": "241302",
"ParentId": "241291",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241302",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T07:22:34.347",
"Id": "241291",
"Score": "2",
"Tags": [
"c",
"parsing"
],
"Title": "Parsing input in form of 'CMD NUM NUM' (num could be special char '%')"
}
|
241291
|
<p>I am a newbie to rust and wanted to know if this code is following idiomatic rust or can be improved.</p>
<pre><code>
use std::cmp::Ordering;
pub fn find(array: &[i32], key: i32) -> Option<usize> {
if array.is_empty(){
return None;
}
let mut start = 0;
let mut end = array.len() - 1;
let mut middle;
loop {
middle = (end - start) / 2;
let middle_element = array[start + middle];
match key.cmp(&middle_element){
Ordering::Less => end -= middle,
Ordering::Greater => start += middle,
Ordering::Equal => {return Some(start+middle as usize);} ,
}
//The slicing syntax produces an unborrowed slice
//(type: [i32]) which we must then borrow (to give a &[i32]),
//even if we are slicing a borrowed slice.//More can be read at
//https://github.com/nrc/r4cppp/blob/master/arrays.md
if end - start <= 1 {
break;
};
}
if array[start] == key {
return Some(start as usize);
}
if array[end] == key {
return Some(end as usize);
}
None
}
</code></pre>
<p>It has passed all the tests listed on Exercism for binary_search problem.</p>
|
[] |
[
{
"body": "<h2>Style</h2>\n\n<h3>Spaces and punctuation</h3>\n\n<pre><code>if array.is_empty(){\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if array.is_empty() {\n</code></pre>\n\n<p>(likewise <code>match key.cmp(&middle_element){</code> → <code>match key.cmp(&middle_element) {</code>, etc.)</p>\n\n<pre><code>Ordering::Equal => {return Some(start+middle as usize);} ,\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>Ordering::Equal => return Some(start + middle as usize),\n</code></pre>\n\n<p>although really, the comma at the end isn't necessary; you can remove that too.</p>\n\n<p>And there should only be one new line below <code>use std::cmp::Ordering</code> and none above.</p>\n\n<h3>Scope</h3>\n\n<p><code>middle</code> isn't used outside the <code>loop</code>, so you can replace:</p>\n\n<pre><code>let mut middle;\n\nloop {\n middle = (end - start) / 2;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>loop {\n let middle = (end - start) / 2;\n</code></pre>\n\n<p>Note how the <code>mut</code> can go away, because the value of <code>middle</code> is only set once (per loop).</p>\n\n<h3>Unnecessary cast (<code>as</code>)</h3>\n\n<pre><code>Ordering::Equal => {\n return Some(start + middle as usize);\n},\n</code></pre>\n\n<p>The <code>as usize</code> is unnecessary; Rust already knows that you're returning <code>Option<usize></code>. In fact, both <code>start</code> and <code>middle</code> are already <code>usize</code>, as is <code>start + middle</code>, so Rust isn't even doing anything fancy to get this to work. However, writing <code>as usize</code> makes it <em>seem</em> like those <em>aren't</em> <code>usize</code>, which could end up confusing your reader quite a lot.</p>\n\n<p>(Same with <code>start as usize</code> → <code>start</code> and <code>end as usize</code> → <code>end</code>.)</p>\n\n<h3>Misleading comments</h3>\n\n<p>This comment:</p>\n\n<pre><code>//The slicing syntax produces an unborrowed slice\n//(type: [i32]) which we must then borrow (to give a &[i32]),\n//even if we are slicing a borrowed slice.//More can be read at\n//https://github.com/nrc/r4cppp/blob/master/arrays.md\nif end - start <= 1 {\n</code></pre>\n\n<p>is misleading, for two reasons:</p>\n\n<ul>\n<li>It's right above (hence attached to) the wrong piece of code.</li>\n<li>You don't use the slicing syntax (<code>array[4..6]</code>) anywhere in your code; you use the <em>indexing</em> syntax.</li>\n</ul>\n\n<p>Just remove it; perhaps replace it with</p>\n\n<pre><code>let middle_element = array[start + middle];\n// cmp requires a reference\nmatch key.cmp(&middle_element) {\n</code></pre>\n\n<p>or something if you think it would be helpful. Though be aware that <code>let middle_element = array[start + middle]</code> makes a copy of <code>middle_element</code>, so the reference is to <code>middle_element</code> on the stack, not <code>array[start + middle]</code> wherever <code>array</code> is stored.</p>\n\n<h3><code>loop</code> with <code>if</code> and <code>break</code></h3>\n\n<pre><code>if end - start <= 1 {\n break;\n};\n</code></pre>\n\n<p>You're trying to make a <code>do</code> <code>while</code> loop here. However, if <code>end - start <= 1</code> already, <em>you don't need to enter this <code>loop</code> in the first place</em>. This means you can just use a regular <code>while</code>:</p>\n\n<pre><code>while end - start > 1 {\n let middle = (end - start) / 2;\n let middle_element = array[start + middle];\n // cmp requires a reference\n match key.cmp(&middle_element) {\n Ordering::Less => end -= middle,\n Ordering::Greater => start += middle,\n Ordering::Equal => return Some(start + middle),\n }\n}\n</code></pre>\n\n<p>And now <code>cargo fmt</code> doesn't change the code, and <code>cargo clippy</code> doesn't give any suggestions. Hooray!</p>\n\n<h2>Implementation</h2>\n\n<h3><code>middle</code></h3>\n\n<p>In my mind, <code>middle</code> should be the index of the middle element – not the difference between <code>start</code> and the middle element. You might want to calculate this as <code>(start + end) / 2</code> but that risks overflow; fortunately, <code>start + (end - start) / 2</code> works fine.</p>\n\n<p>So this:</p>\n\n<pre><code>let middle = (end - start) / 2;\nlet middle_element = array[start + middle];\n// cmp requires a reference\nmatch key.cmp(&middle_element) {\n Ordering::Less => end -= middle,\n Ordering::Greater => start += middle,\n Ordering::Equal => return Some(start + middle)\n}\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>while end - start > 1 {\n let middle = start + (end - start) / 2;\n let middle_element = array[middle];\n // cmp requires a reference\n match key.cmp(&middle_element) {\n Ordering::Less => end = middle,\n Ordering::Greater => start = middle,\n Ordering::Equal => return Some(middle)\n }\n}\n</code></pre>\n\n<h3>Unnecessary variable</h3>\n\n<p>Now we've made that change, I think <code>array[middle]</code> is obviously the middle element; so much so that we can remove <code>middle_element</code> entirely and get clearer code:</p>\n\n<pre><code>let middle = start + (end - start) / 2;\n// cmp requires a reference\nmatch key.cmp(&array[middle]) {\n</code></pre>\n\n<h3><code>Ordering</code> ordering</h3>\n\n<p>I actually think it'd be clearer if these were in <code>Less</code>, <code>Equal</code>, <code>Greater</code> order:</p>\n\n<pre><code>match key.cmp(&array[middle]) {\n Ordering::Less => end = middle,\n Ordering::Equal => return Some(middle),\n Ordering::Greater => start = middle\n}\n</code></pre>\n\n<h3>Implicit <code>return</code></h3>\n\n<p>At the end, it might be clearer to use the implicit return form:</p>\n\n<pre><code>if array[start] == key {\n Some(start)\n} else if array[end] == key {\n Some(end)\n} else {\n None\n}\n</code></pre>\n\n<h2>Addendum: Tests</h2>\n\n<p>To make sure I didn't break your code while making these changes, I wrote a test. Tests are good to have (not that this is a particularly good test).</p>\n\n<pre><code>#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_find() {\n assert_eq!(find(&[2, 4, 5, 7, 11, 12, 17], 5), Some(2));\n assert_eq!(find(&[], 5), None);\n assert_eq!(find(&[2, 4, 5, 7, 11, 12, 17], 6), None);\n assert_eq!(find(&[-63, -42, 1, 2, 4, 5, 7, 11, 12, 17, 17, 18], 12), Some(8));\n\n call_find(&[-10, -7, 0, 2, 4, 4, 5, 16, 27, 37, 38, 40, 40, 40, 40, 63, 628, 844, 10000000, 41230456]);\n }\n\n fn call_find(array: &[i32]) {\n for i in 0..array.len() {\n assert_eq!(array[find(array, array[i]).unwrap()], array[i]);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:24:41.157",
"Id": "241457",
"ParentId": "241293",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T09:19:14.160",
"Id": "241293",
"Score": "4",
"Tags": [
"rust"
],
"Title": "Binary search in Rust"
}
|
241293
|
<p><strong>The Problem</strong></p>
<p>I am currently writing a script that converts images into numerical array representation and then calculates "in-between" images based on linear interpolation between the start and end array.</p>
<p>My code does exactly what I want but goes over many nested loops which strikes me as something that will lead to very high computation times for many interpolation steps or big images.</p>
<p><strong>The Code</strong></p>
<p>The code is in python</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
# Helper function that calculates the interpolation between two points
def interpolate_points(p1, p2, n_steps=3):
# interpolate ratios between the points
ratios = np.linspace(0, 1, num=n_steps)
# linear interpolate vectors
vectors = list()
for ratio in ratios:
v = (1.0 - ratio) * p1 + ratio * p2
vectors.append(v)
return np.asarray(vectors)
# final function that interpolates arrays
def interpolate_arrays(start_array,end_array,n_steps=10):
n = 0
array_interpolation = []
while n < n_steps:
i = 0
x = []
while i < len(start_array):
e = interpolate_points(start_array[i],end_array[i],n_steps)[n]
x.append(e)
i += 1
array_interpolation += [x]
n += 1
return array_interpolation
</code></pre>
<p>This results in:</p>
<pre class="lang-py prettyprint-override"><code>#Test
X1 = [1,1]
X2 = [3,3]
interpolate_arrays(X1,X2,n_steps=3)
#[[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]
</code></pre>
|
[] |
[
{
"body": "<p>There are some easy wins here. Your <code>interpolate_points</code> doesn't need a loop:</p>\n\n<pre><code>def interpolate_points(p1, p2, n_steps=3):\n \"\"\"Helper function that calculates the interpolation between two points\"\"\"\n # interpolate ratios between the points\n ratios = np.linspace(0, 1, num=n_steps)\n # linear interpolate vectors\n vectors = (1.0 - ratios) * p1 + ratios * p2\n return vectors\n</code></pre>\n\n<p>Also, even without further vectorization, you should be making use of <code>range</code> in your main function:</p>\n\n<pre><code>def interpolate_arrays(start_array, end_array, n_steps=10):\n \"\"\"final function that interpolates arrays\"\"\"\n array_interpolation = []\n for n in range(n_steps):\n x = []\n for i in range(len(start_array)):\n e = interpolate_points(start_array[i], end_array[i], n_steps)[n]\n x.append(e)\n array_interpolation += [x]\n return array_interpolation\n</code></pre>\n\n<p>However, all of that can be replaced with a call to <code>interp1d</code>:</p>\n\n<pre><code>import numpy as np\nfrom scipy.interpolate import interp1d\n\n\ndef interpolate_arrays(bounds, n_steps=10):\n \"\"\"final function that interpolates arrays\"\"\"\n bounds = np.array(bounds)\n\n fun = interp1d(\n x=[0, 1],\n y=bounds.T,\n )\n y = fun(np.linspace(0, 1, n_steps))\n\n return y\n\n\ndef test():\n X1 = [1.5, 1]\n X2 = [5.5, 3]\n\n y = interpolate_arrays([X1, X2], n_steps=3)\n assert y.T.tolist() == [[1.5, 1.0], [3.5, 2.0], [5.5, 3.0]]\n</code></pre>\n\n<p>Even easier:</p>\n\n<pre><code>def interpolate_arrays(X1, X2, n_steps=10):\n \"\"\"final function that interpolates arrays\"\"\"\n return np.linspace(X1, X2, n_steps)\n\n\ndef test():\n X1 = [1.5, 1]\n X2 = [5.5, 3]\n\n y = interpolate_arrays(X1, X2, n_steps=3)\n assert y.tolist() == [[1.5, 1.0], [3.5, 2.0], [5.5, 3.0]]\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>If you use <code>interp1d</code>, it would be better if your inputs and outputs are both two-dimensional <code>np.ndarray</code>; in their current form they need a transposition</li>\n<li>Write some unit tests such as the one shown, although it would be a better idea to call <code>isclose</code> since this is floating-point math</li>\n<li>If you want, it is trivial to make this extrapolate as well as interpolate</li>\n</ul>\n\n<p>Basically: if there is a math thing in your head, before even thinking about what it would take to implement it yourself, do a search through <code>scipy</code>/<code>numpy</code> to see if it has already been done for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:28:21.047",
"Id": "473509",
"Score": "1",
"body": "Thanks a lot, this is answer is both a helpful guide for improvements as well as a good \"SO just give me the final code\"-style answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T14:26:53.650",
"Id": "241301",
"ParentId": "241295",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241301",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T10:09:00.000",
"Id": "241295",
"Score": "6",
"Tags": [
"python",
"performance",
"array"
],
"Title": "Improving the performance of interpolating between two arrays"
}
|
241295
|
<p>Suppose we have variables, <code>num</code> and <code>let</code>, that may be (possibly nested) <code>list</code>, <code>tuple</code>, or <code>None</code>. The combination is to be such that:</p>
<ol>
<li>Neither <code>== None</code> -> <code>num + let</code></li>
<li><code>num == None</code> -> <code>let</code></li>
<li><code>let == None</code> -> <code>num</code></li>
<li>Both <code>== None</code> -> <code>None</code></li>
<li>Return type is <code>list</code> or <code>None</code></li>
<li>1-5 should hold for any number of variables, including one, and >2</li>
<li>Be a one-liner (one statement)</li>
</ol>
<p>My approach, with test:</p>
<pre class="lang-py prettyprint-override"><code>def join(_vars):
return [x for v in _vars if v for x in v] or None
num = ((1, 2), None, [1, (2, 3)], None)
let = (('a', 'b'), ['a', ('b', 'c')], None, None)
vars_all = (let, num)
for i, _vars in enumerate(zip(*vars_all)):
print(f"Case {i + 1}:", join(_vars))
</code></pre>
<pre><code>Case 1: ['a', 'b', 1, 2]
Case 2: ['a', ('b', 'c')]
Case 3: [1, (2, 3)]
Case 4: None
</code></pre>
<p>Any better way to accomplish this? E.g. shorter, or more readable, or more intuitive than nested comprehensions. </p>
<p>(For readability I'd opt for less abstract naming: <code>[x for var in _vars if bool(var) for x in var]</code>. Parentheses should also help, though unsure if can insert without changing results.)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T13:59:11.333",
"Id": "473493",
"Score": "0",
"body": "Your SE handle sounds like a Final Fantasy boss."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:00:51.153",
"Id": "473648",
"Score": "0",
"body": "@Reinderien The sage of the six paths, from Naruto. Unfamiliar with FF, but which boss, I wonder?"
}
] |
[
{
"body": "<p>As you mentioned, the nested comprehension is not very intuitive. I had to write it out for understanding.</p>\n\n<p>I am also not sure I understood your requirements correctly. Please correct any wrong assumptions. These are the attempts:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import chain\n\ndef join(vars_):\n filtered = (element for element in vars_ if element)\n return chain.from_iterable(filtered)\n\n\nnum = ((1, 2), None, [1, (2, 3)], None)\nlet = (('a', 'b'), ['a', ('b', 'c')], None, None)\nvars_all = (let, num)\n\nfor i, vars_ in enumerate(zip(*vars_all), start=1):\n print(f\"Case {i}:\", join(vars_))\n</code></pre>\n\n<p>It returns</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>Case 1: <itertools.chain object at 0x00000221C73F3940>\nCase 2: <itertools.chain object at 0x00000221C73F3940>\nCase 3: <itertools.chain object at 0x00000221C73F3940>\nCase 4: <itertools.chain object at 0x00000221C73F3940>\n</code></pre>\n\n<p>So not what you really asked for. However, the <code>chain object</code> behaves like a normal list in most circumstances. It supports the <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence\" rel=\"nofollow noreferrer\"><code>Sequence</code> interface</a> (but not the <code>MutableSequence</code> interface):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections.abc import MutableSequence, Sequence\nfrom itertools import chain\n\n\ndef join(vars_):\n filtered = (element for element in vars_ if element)\n return chain.from_iterable(filtered)\n\n\nnum = ((1, 2), None, [1, (2, 3)], None)\nlet = ((\"a\", \"b\"), [\"a\", (\"b\", \"c\")], None, None)\nvars_all = (let, num)\n\nfor i, vars_ in enumerate(zip(*vars_all), start=1):\n print(f\"Case {i}:\", list(join(vars_)))\n print(\"\\tIs Sequence:\", isinstance(vars_, Sequence))\n print(\"\\tIs MutableSequence:\", isinstance(vars_, MutableSequence))\n print(\n \"\\tIs MutableSequence (cast to list):\", isinstance(list(vars_), MutableSequence)\n )\n</code></pre>\n\n<p>will print</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>Case 1: ['a', 'b', 1, 2]\n Is Sequence: True\n Is MutableSequence: False\n Is MutableSequence (cast to list): True\nCase 2: ['a', ('b', 'c')]\n Is Sequence: True\n Is MutableSequence: False\n Is MutableSequence (cast to list): True\nCase 3: [1, (2, 3)]\n Is Sequence: True\n Is MutableSequence: False\n Is MutableSequence (cast to list): True\nCase 4: []\n Is Sequence: True\n Is MutableSequence: False\n Is MutableSequence (cast to list): True\n</code></pre>\n\n<p>So if a caller requires a list, they can cast to that type specifically. It is perhaps more pythonic to not do that in the function already (duck-typing).</p>\n\n<p>Another point to note is that if both elements are <code>None</code>, an empty iterable is returned. This will still behave similar to <code>None</code> in boolean contexts. It allows for simpler code and maybe more predictable returns. See if that still fulfills your requirements. If not, this final suggestion will fulfill your tests as specified:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import chain\n\n\ndef join(vars_):\n if not any(vars_):\n return None\n filtered = (element for element in vars_ if element)\n return list(chain.from_iterable(filtered))\n\n\nnum = ((1, 2), None, [1, (2, 3)], None)\nlet = ((\"a\", \"b\"), [\"a\", (\"b\", \"c\")], None, None)\nvars_all = (let, num)\n\nfor i, vars_ in enumerate(zip(*vars_all), start=1):\n print(f\"Case {i}:\", join(vars_))\n</code></pre>\n\n<p>will return</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>Case 1: ['a', 'b', 1, 2]\nCase 2: ['a', ('b', 'c')]\nCase 3: [1, (2, 3)]\nCase 4: None\n</code></pre>\n\n<p>for Python 3.8.1.\nI hope you agree that this is more readable, intuitive and also debuggable.\nThe early <code>return</code> makes it easier to understand. The additional <code>itertools</code> import is very cheap.</p>\n\n<p>Finally, a one-liner version of the above is</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def join(vars_):\n return list(chain.from_iterable(elem for elem in vars_ if elem)) or None\n</code></pre>\n\n<p>Lastly, two notes:</p>\n\n<ol>\n<li>notice the <code>start</code> keyword for <code>enumerate</code></li>\n<li>leading underscores denote (private) implementation details; use <a href=\"https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles\" rel=\"nofollow noreferrer\"><em>trailing</em> underscores</a> for variable names that otherwise shadow built-ins; better to avoid these all-together, though</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:58:04.363",
"Id": "473647",
"Score": "1",
"body": "I'll look at your solution more closely a bit later; it looks like you can meet the one-line requirement for the last solution via `list(chain.from_iterable(elem for elem in vars_ if elem)) or None`. Currently my impression is, it's about which Python the user is more comfortable with - a library or a nested comprehension (I for one never used `itertools.chain`). As for the requirement, if two lines offer far superior readability (and spare an import), I'll take it - but the idea is reusability without making it into a function, which treads on \"don't repeat yourself\" more the longer it is"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:44:55.533",
"Id": "473659",
"Score": "0",
"body": "For your last point, I argue that even a one-liner is, if repeated at all, not following *DRY*. In that case, I would even suggest a `lambda` if you really want to avoid `def`. But a truly *named* function will do wonders for code readability and maintainability. Also, I think the \"beauty\" about `chain` is its name... it is a very simple operation, where *chain* says everything the user needs to know. `itertools` is part of the standard library, so in my view can be considered part of the core language ([\"batteries included\"](https://docs.python.org/3/tutorial/stdlib.html#batteries-included))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T15:50:18.730",
"Id": "474072",
"Score": "0",
"body": "1. `not any(x not in (None, [], {}) for x in arr)` is an expression that can be repeated, but we don't consider it 'violating' a coding practice since it's sufficiently short - the idea's the same here, to repeat without defining a function. 2. The problem with `chain` is the need to dig up and study its docs if one is unfamiliar with it (as I was), and it adds an import; the core language is much preferred to this end. -- Nonetheless, your approach is a viable alternative to mine - just include the one-liner version somewhere, and I'll accept it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T16:17:29.313",
"Id": "474076",
"Score": "0",
"body": "The answer is now edited accordingly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T12:04:41.210",
"Id": "241298",
"ParentId": "241296",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "241298",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T10:47:55.310",
"Id": "241296",
"Score": "4",
"Tags": [
"python"
],
"Title": "Combining None and lists in one line"
}
|
241296
|
<p><a href="https://i.stack.imgur.com/XzgsG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XzgsG.png" alt="enter image description here"></a></p>
<h2>Introduction</h2>
<p>For the purpose of learning how to work with pictures in Java, I created an ASCII-Art Generator. The program can do two things:</p>
<ol>
<li>Convert pictures into ASCII-Art</li>
<li>Convert text into ASCII-Art</li>
</ol>
<p>I splitted the task into several steps:</p>
<ol>
<li>Convert text to image</li>
<li>Read image and its height and width</li>
<li>Saving data of each pixel</li>
<li>Convert pixel data into ASCII-char</li>
<li>Printing</li>
</ol>
<hr>
<h2>Code</h2>
<p><code>Control.java</code></p>
<p>This class is responsible for the user-interaction and the creation of an instance of the needed class(-es).</p>
<pre><code>import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Control {
public static void main(String[] args) {
System.out.println("Picture to ASCII (1) or text to ASCII (2)?");
Scanner scan = new Scanner(System.in);
int decision;
while(true) {
try {
decision = scan.nextInt();
if(decision > 2 || decision < 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) { //User enters not a number or a number > 2 or < 1
System.out.println("Enter (1) or (2):");
scan.nextLine(); //Clear Scanner
}
}
scan.nextLine(); //To clear scanner
switch(decision) {
case(1):
System.out.println("Want to reverse brightness? (yes = 1, no = 2)");
int reverse;
while(true) {
try {
reverse = scan.nextInt();
if(reverse > 2 || reverse < 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) { //User enters not a number or a number > 2 or < 1
System.out.println("Enter (1) or (2):");
scan.nextLine();
}
}
boolean reverseBrightness;
reverseBrightness = reverse == 1 ? true : false; //if(reserve == 1) {reverseBrightness = true} else {reverseBrightness = false};
System.out.println("Enter filename:");
scan.nextLine();
String filename;
while(true) {
try {
filename = scan.nextLine();
Picture picture = new Picture(filename, reverseBrightness);
System.out.println("Successful!");
break;
}
catch(IOException e) { //IIOException occurs when file not found
System.out.println("File not found. Enter filename:");
}
}
break;
case(2):
System.out.println("Enter text:");
String str = scan.nextLine();
try {
AsciiText text = new AsciiText(str);
}
catch(IOException e) {
e.printStackTrace();
}
System.out.println("Successful!");
break;
default:
System.out.println("An Error occured!"); //Impossible to happen, just to adhere to best practice
break;
}
scan.close();
}
}
</code></pre>
<p><code>Picture.java</code></p>
<p>Responsible for the conversion of pictures into ASCII-art.</p>
<pre><code>import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Picture {
private BufferedImage img;
private int height;
private int width;
private Triplet[][] array;
private int[][] brightness;
private final int MAX_BRIGHTNESS = 255;
private char[][] ascii;
private final String str = "$@B%8&MW#*oahkbdpqwmZ0OQLCJUYXzcvunxrjft/\\\\(|)1{}][?-_+~i!Il:;,\"\\^`"; //ASCII-chars
public Picture(String filename, boolean reverse) throws IOException {
img = ImageIO.read(new File(filename));
this.height = img.getHeight();
this.width = img.getWidth();
this.fillArray();
this.fillBrightnessArray();
if(reverse) {
this.reverseBrightness();
}
this.fillAscii();
this.printAscii();
}
//Saving the proportion of red, green and blue of each pixel
private void fillArray() {
array = new Triplet[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
int getRGB = img.getRGB(j, i);
int red = (getRGB>>16) & 0xff;
int green = (getRGB>>8) & 0xff;
int blue = getRGB & 0xff;
array[i][j] = new Triplet(red, green, blue);
}
}
}
//Calculating the brightness of each pixel
private void fillBrightnessArray() {
brightness = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
brightness[i][j] = (array[i][j].getFirst() + array[i][j].getSecond() + array[i][j].getThird()) / 3;
}
}
}
//Reversing the brightness-values
private void reverseBrightness() {
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
brightness[i][j] = MAX_BRIGHTNESS - brightness[i][j];
if(brightness[i][j] < 0) {
brightness[i][j] *= -1;
}
}
}
}
//Converting brightness into appropriate ASCII-char
private void fillAscii() {
ascii = new char[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
ascii[i][j] = str.charAt(brightness[i][j] / 4);
}
}
}
//print completed ASCII-art to file
private void printAscii() {
try {
FileWriter writer = new FileWriter("ascii.txt");
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
writer.write(ascii[i][j] + "" + ascii[i][j] + "" + ascii[i][j]);
}
writer.write("\n");
}
writer.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p><code>AsciiText.java</code></p>
<p>Responsible for the second task: The conversion of text.</p>
<pre><code>import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class AsciiText {
private final String filename = "text.jpg";
public AsciiText(String text) throws IOException {
int width = 200;
int height = 40;
int imageType = BufferedImage.TYPE_INT_RGB;
//Creating image with text
BufferedImage image = new BufferedImage(width, height, imageType);
Graphics graphic = image.getGraphics();
int fontSize = 15;
graphic.setFont(new Font("Arial", Font.PLAIN, fontSize));
Graphics2D graphics = (Graphics2D) graphic;
int xCoordinate = 5;
int yCoordinate = 25;
graphics.drawString(text, xCoordinate, yCoordinate);
ImageIO.write(image, "jpg", new File(filename));
//Converting created image to ASCII-art
Picture picture = new Picture(filename, true);
}
}
</code></pre>
<p><code>Triplet.java</code></p>
<p>Simple datastructure that is able to save three integers (a triplet of the form (a, b, c)); in this case the (RGB-values).</p>
<pre><code>public class Triplet {
private int first;
private int second;
private int third;
public Triplet(int first, int second, int third) {
this.first = first;
this.second = second;
this.third = third;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
public int getThird() {
return third;
}
}
</code></pre>
<hr>
<h2>Attribution</h2>
<pre><code>/*
* Attribution:
* The code in this question was created with the help of the following question(s) and their answer(s).
* These come from the Stack Exchange network, where content is licensed under CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/):
* Question by Jeel Shah (https://stackoverflow.com/users/681159/jeel-shah): https://stackoverflow.com/questions/7098972/ascii-art-java
* Answer by Peter Lawrey (https://stackoverflow.com/users/57695/peter-lawrey)
* Question by aneuryzm (https://stackoverflow.com/users/257022/aneuryzm): https://stackoverflow.com/questions/6010843/java-how-to-store-data-triple-in-a-list
* Answer by Bala R (https://stackoverflow.com/users/273200/bala-r)
*/
</code></pre>
<hr>
<h2>Example</h2>
<p>One example of the text to ascii-art-conversion is the "Hello World!"-message at the beginning of this question.</p>
<p>To demonstrate the conversion of pictures, I used the well known poison-symbol, which you can find <a href="https://commons.wikimedia.org/wiki/File:Skull_and_Crossbones.svg" rel="nofollow noreferrer">here</a>:</p>
<p><a href="https://i.stack.imgur.com/5E9OC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5E9OC.png" alt="enter image description here"></a></p>
<hr>
<h2>Question</h2>
<p>How can I improve the code? What about the general code structure? Did I miss anything significant? Do you have any other suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T22:57:15.877",
"Id": "473542",
"Score": "1",
"body": "I have no idea what the Triplet class does, other than hold 3 integer values. Your Control class is one main method. See if you can create some methods to better document what's going on in the code. Usually, because ASCII characters are approximately 8 pixels high and 5 pixels wide, there's not a one to one conversion of pixels to ASCII characters. I can't tell from your ASCII images, but I suspect the aspect ratio of your ASCII images isn't the same as the original picture."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T04:47:11.030",
"Id": "473569",
"Score": "0",
"body": "Thanks for your feedback! I just added some information about the triplet-class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T05:22:04.110",
"Id": "473573",
"Score": "0",
"body": "It's funny that the JPEG artifacts are clearly visible in the generated ASCII version."
}
] |
[
{
"body": "<p><strong>Control.java</strong></p>\n\n<p>This is just my opinion, but interactive specialized command line interfaces are weird. Did you consider command line arguments with a ready made command line parser library (free software)?</p>\n\n<p>Anyway, you have duplicated the code for handling a \"1 or 2\" input twice. You should refactor that into a reusable utility method or class.</p>\n\n<p><strong>Triplet.java</strong></p>\n\n<p>Java specifically does not have a generic class for a tuple or triple, for the sole reason that they would be abused as specific types everwhere making code less maintainable and readable. Same here, instead of defining a generic type for a specific purpose, you should define a specific <code>Rgb</code> class with fields \"red\", \"green\" and \"blue\". Or first, shuffle through the standard libraries to see if there is one already. <code>java.awt.Color</code> comes to mind but I don't remember if it fits your purpose.</p>\n\n<p>I the color components have minimum and maximum values (0 to 255 for example) your class should document and enforce them.</p>\n\n<p><strong>Picture.java</strong></p>\n\n<pre><code>private Triplet[][] array;\n</code></pre>\n\n<p>Use descriptive field names. Array means just an array and that information already is in the field type (it's actually a two dimensional array, so the name is a bit misleading now). Maybe name it \"rgbValues\". When I do image processing, I like to store the image data in a one dimensional array and onvert x/y coordinates if needed. If it's not needed, the operations on the arrays become much simpler. This may come the fact that the image manipulation operations in the Java standard libraries also use one dimensional arrays so I adopted it from there.</p>\n\n<p>It's also quite common to use a plain integer to represent an RGB value in the standard libraries with each component (and alpha) assigned 8 bits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T06:01:33.107",
"Id": "473577",
"Score": "1",
"body": "Sorry, I had to cut this short. Have to run errands."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T06:01:01.400",
"Id": "241346",
"ParentId": "241311",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "241346",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T17:41:39.657",
"Id": "241311",
"Score": "8",
"Tags": [
"java",
"ascii-art"
],
"Title": "ASCII-Art Generator"
}
|
241311
|
<p>I have implemented a min heap and looking for a simpler solution.</p>
<p>Is there anyone for suggesting a simpler solution for this?</p>
<p>Thanks.</p>
<pre><code>import com.sun.org.apache.xalan.internal.xsltc.dom.MultiValuedNodeHeapIterator;
import java.util.Arrays;
public class MinHeap {
private int capacity = 10;
private int size = 0;
int[] items = new int[capacity];
private int getLeftChildIndex(int parentIndex) { return 2 * parentIndex + 1 ;}
private int getRightChildIndex(int parentIndex) { return 2 * parentIndex + 2 ;}
private int getParentIndex(int childIndex) { return (childIndex -1) / 2 ;}
private boolean hasLeftChild(int index) { return getLeftChildIndex(index) < size; }
private boolean hasRightChild(int index) { return getRightChildIndex(index) < size; }
private boolean hasParent(int index) { return getParentIndex(index) >= 0; }
private int leftChild(int index) { return items[getLeftChildIndex(index)]; }
private int rightChild(int index) { return items[getRightChildIndex(index)]; }
private int parent(int index) { return items[getParentIndex(index)]; }
private void swap(int indexOne, int indexTwo){
int temp = items[indexOne];
items[indexOne] = items[indexTwo];
items[indexTwo] = temp;
}
private void ensureExtraCapacity() {
if (size == capacity) {
items = Arrays.copyOf(items, capacity * 2);
capacity *= 2;
}
}
private int peek() {
if (size == 0) throw new IllegalStateException();
return items[0];
}
private int poll() {
if (size == 0) throw new IllegalStateException();
int item = items[0];
items[0] = items[size - 1];
size--;
heapifyDown();
return item;
}
public void add(int item) {
ensureExtraCapacity();
items[size] = item;
size++;
heapifyUp();
}
public void heapifyUp() {
int index = size - 1;
while ( hasParent(index) && parent(index) > items[index] ) {
swap (getParentIndex(index),index);
index = getParentIndex(index);
}
}
public void heapifyDown() {
int index = 0;
while ( hasLeftChild(index) ) {
int smallerChildIndex = getLeftChildIndex(index);
if (hasRightChild(index) && rightChild(index) < leftChild(index)) {
smallerChildIndex = getRightChildIndex(index);
}
if (items[index] < items[smallerChildIndex]) {
break;
} else {
swap(index, smallerChildIndex);
}
index = smallerChildIndex;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have one suggestion for your code.</p>\n\n<ol>\n<li>Create a method to check if the current size is invalid, and reuse it (MinHeap#peek and MinHeap#poll methods).</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void assertCurrentSizeIsValid() {\n if (size == 0) {\n throw new IllegalStateException();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T10:41:53.077",
"Id": "473916",
"Score": "0",
"body": "Almost the same with the current code that's ok."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T17:42:31.573",
"Id": "241384",
"ParentId": "241313",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T18:25:31.170",
"Id": "241313",
"Score": "4",
"Tags": [
"java",
"heap"
],
"Title": "Min Heap Java Implementation"
}
|
241313
|
<p>I'm fairly new to Javascript and am writing a piece of code to create a filtering system for a portfolio grid (a grid of work examples that filter by category when a button is selected).</p>
<p>While the code works just fine, I feel like the way I'm writing it is overly clunky. Can someone please let me know if there's a way I can streamline/improve this code block?</p>
<p>Any help would be much appreciated - thanks! :D</p>
<pre><code>var gridItem = document.querySelectorAll('.grid div');
var featuredItem = document.querySelector('.featured');
var filterBtn = document.querySelectorAll('.filter-btn');
function getAttributes(event) {
event.preventDefault();
var thisValue = event.target.getAttribute('data-filter');
// Get grid item filter attributes
for (let a = 0; a < gridItem.length; a++) {
const gridFilterAttr = gridItem[a].getAttribute('data-filterType');
if (thisValue == gridFilterAttr) {
gridItem[a].classList.add('active')
gridItem[a].classList.remove('not-active')
} else if (thisValue == 'all') {
gridItem[a].className = 'active';
featuredItem.className = 'featured active'
} else {
gridItem[a].classList.remove('active')
gridItem[a].classList.add('not-active')
}
}
}
for (let b = 0; b < filterBtn.length; b++) {
filterBtn[b].addEventListener('click', getAttributes);
}
</code></pre>
<p>HTML:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Js Projects</title>
<link rel="stylesheet" href="/assets/css/app.css">
</head>
</code></pre>
<p></p>
<pre><code> <div class="container">
<button data-filter="all" class="filter-btn">All</button>
<button data-filter="web" class="filter-btn">Web Project</button>
<button data-filter="app" class="filter-btn">App</button>
<button data-filter="ux" class="filter-btn">UX/UI</button>
<div class="grid">
<div class="featured" data-filterType="web">Featured Item</div>
<div data-filterType="web">Web item</div>
<div data-filterType="app">App item</div>
<div data-filterType="ux">UX item</div>
<div data-filterType="web">Web item</div>
<div data-filterType="ux">UX item</div>
<div data-filterType="app">App item</div>
</div>
</div>
<!-- Scripts -->
<script src="/assets/js/grid.js"></script>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T20:51:34.807",
"Id": "473531",
"Score": "1",
"body": "It's rather difficult to judge this without the HTML, and the filter data. Can each grid item only respond to one filter button? That seems a bit weird. We basically can't test-run your code. Also, there's something to say for implementing this in pure JS, but I've gotten so used to JQuery that this stuff seems a bit verbose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T07:28:48.487",
"Id": "473579",
"Score": "0",
"body": "Hi! I've now added the HTMl for you to view :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T09:22:35.777",
"Id": "473595",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>As mentioned in comment, it is harder to be more specific without being able to run the code, but what can I say:</p>\n\n<ul>\n<li>Separate event code function and then the function, that will \"do the work\" itself, with all necessary parameters.</li>\n<li>Extract for into separate function.</li>\n</ul>\n\n<p>That will overall make it easier to read and cleaner + easier to test. Something like:</p>\n\n<pre><code>function getAttributes(event) {\n event.preventDefault();\n var thisValue = event.target.getAttribute('data-filter');\n setGridItems(gridItem, thisValue);\n}\n\nfunction setGridItems(gridItems, dataFilter) {\n for (let a = 0; a < gridItems.length; a++) {\n setGridItem(gridItems[a], dataFilter);\n }\n}\n\nfunction setGridItem(singleGridItem, dataFilter) {\n const gridFilterAttr = singleGridItem.getAttribute('data-filterType');\n if (dataFilter == gridFilterAttr) {\n singleGridItem.classList.add('active')\n singleGridItem.classList.remove('not-active')\n } else if (dataFilter == 'all') {\n singleGridItem.className = 'active';\n featuredItem.className = 'featured active'\n } else {\n singleGridItem.classList.remove('active')\n singleGridItem.classList.add('not-active')\n }\n\n}\n\n</code></pre>\n\n<p>Would be cool to use foreach there, but it is a bit problematic with <code>NodeList</code> and support is not that broad yet, but maybe you could do that. Now when you have it a bit separated, you can continue with refactoring. I don't like that some variables are pre-cached and \"global\", that's why I passed <code>gridItem</code> variable anyway to make it local in function, but <code>featuredItem</code> is still global.\nLast function could use more of refactoring, but I'd need more info about problem for that :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T22:01:14.213",
"Id": "473538",
"Score": "0",
"body": "Maybe I'm missing something because I'm not that strong on JavaScript, but can't the if (cond) else if (cond) else be simplified If (thisValue == 'all') ... else ... ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T23:55:25.617",
"Id": "473543",
"Score": "0",
"body": "`NodeList.prototype.forEach` is reasonably well supported. If you don't trust it, you can just spread it into an array first. `[...gridItems].forEach(` (if IE support is required, use Babel, as always)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T07:30:49.930",
"Id": "473580",
"Score": "0",
"body": "Hey! Thanks for your comments and answers - I have added my HTML now if that helps?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:41:35.703",
"Id": "473593",
"Score": "0",
"body": "Yeah I know it is reasonably supported, just didn't want to complicate it too much :-) Especially with IE missing."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:14:32.043",
"Id": "241318",
"ParentId": "241315",
"Score": "1"
}
},
{
"body": "<p>In my comment I said that this would be a lot shorter if you used <a href=\"https://jquery.com\" rel=\"nofollow noreferrer\">JQuery</a>. Now I don't want to say that JQuery is better than plain Javascript. There may be a good reason to not use JQuery. But I do want to show what the code would look like in JQuery.</p>\n\n<pre><code>$(\".filter-btn\").click(function() {\n let type = $(this).data(\"filter\");\n let filter = (type == \"all\") ? \"*\" : \"[data-filterType='\"+type+\"']\";\n $(\".grid div\").hide().filter(filter).show(); \n});\n</code></pre>\n\n<p>As you can see, this is a lot less verbose. You can see <a href=\"https://jsfiddle.net/KIKO_Software/psz6g0f2\" rel=\"nofollow noreferrer\">a live demo here</a>.</p>\n\n<p>I think it goes too far to explain this JQuery code in detail. In broad terms it does this:</p>\n\n<ol>\n<li>Bind an event handler to the \"click\" JavaScript event of your buttons.</li>\n<li>Extract the filter type from the data attribute of the clicked button.</li>\n<li>Based on that it creates a filter variable that selects the grid items to be shown.</li>\n<li>First hide all grid items and then only show the filtered ones.</li>\n</ol>\n\n<p>It is the last line that does all the work.</p>\n\n<p>I intentionally didn't change the HTML so this works on the same HTML as you have now. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T10:05:44.870",
"Id": "473599",
"Score": "1",
"body": "The code isn't really shorter because you are using jQuery. It is shorter, because you are using a different approach. You could use a very simular approach with pure JS/DOM and without jQuery and still be almost just as short."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:19:53.057",
"Id": "473639",
"Score": "0",
"body": "@RoToRa Everybody knows that jQuery has a certain size, however if you use a CDN version then it is very likely that the user has already downloaded it. I also don't have to read the jQuery code, so the code you have to read is shorter than in the question. The challenge to you is to prove your statement: Show us a version in pure JS/DOM which is almost just as short. PS: Shortness isn't everything, we should concentrate on readability."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:42:41.373",
"Id": "241353",
"ParentId": "241315",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T19:37:12.707",
"Id": "241315",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "How can I streamline my code?"
}
|
241315
|
<p>How would I go about making this script much faster? Essentially it reads from a file and the slowest part is populating the words. In the words file there are over 100k words and I was looking for a way to speed it up since this script is going to be used to populate the database with over 200 languages. </p>
<pre class="lang-py prettyprint-override"><code>import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE","eureka.settings")
django.setup()
from django.contrib.auth.models import User
from django.contrib import admin
from wordDictionary.models import Genus, Word, Feature, Dimension, Language, Lemma, Family, TagSet, POS
import multiprocessing
# Dimensions
def dimensionPop():
dimData = open("data/models/dimensions.txt","r")
for x in dimData:
a = x.split("\n")
dimName = a[0]
# Create Object
nextDim = Dimension(name=dimName)
nextDim.save()
#print(f":{nextDim.name}:")
dimData.close()
print("Dimension done")
# Features
def featurePop():
featData = open("data/models/features.txt","r")
for x in featData:
line = x.split(";")
featName = line[1]
dimName = line[0]
# Create Object
nextFeature = Feature(name=featName)
dimObject = Dimension.objects.get(name=dimName)
nextFeature.dimension = dimObject
#print(f"{nextFeature.dimension.name}")
nextFeature.save()
featData.close()
print("Feature done")
# Part of Speech
def posPop():
posData = open("data/models/POS.txt","r")
for x in posData:
line = x.split(";")
posName = line[1]
# Create Object
nextPOS = POS(name=posName)
#print(f"{nextPOS.name}")
nextPOS.save()
posData.close()
print("Part of Speech done")
# Genus
def genusPop():
genusData = open("data/models/genus.txt","r")
for x in genusData:
genusName = x.split("\n")[0]
# Create Object
nextGenus = Genus(name=genusName)
#print(f":{nextGenus.name}:")
nextGenus.save()
genusData.close()
print("Genus done")
# Family
def familyPop():
famData = open("data/models/families.txt","r")
for x in famData:
FamilyName = x.split(";")[0]
# Create Object
nextFamily = Family(name=FamilyName)
#print(f":{nextFamily.name}:")
nextFamily.save()
famData.close()
print("Family done")
def languagePop():
#Populate only english for now
nextLang = Language(name="English")
nextLang.walsCode = "eng"
nextLang.genus = Genus.objects.get(name="Germanic")
nextLang.family = Family.objects.get(name="Indo-European")
nextLang.save()
print("Language done")
def lemmaPop():
lemmaData = open("data/models/lemmas.txt","r",encoding="utf8")
for x in lemmaData:
x = x.split("\n")
lemmaName = x[0]
nextLemma = Lemma(name=lemmaName)
langName = Language.objects.get(name="English")
nextLemma.language = langName
posName = POS.objects.get(name="Verb")
nextLemma.pos = posName
nextLemma.save()
lemmaData.close()
print("Lemma done")
findFeature={}
def readAppendix():
fileContent = open("data/models/features.txt","r")
for row in fileContent:
rowWords = row.split(";")
dimension = rowWords[0]
feature = rowWords[1]
label =(rowWords[2].rstrip()).upper()
findFeature[label]=feature # assign feature to label
fileContent.close()
print("\nStarting with words...")
usedTagset = {}
def wordPop():
wordData = open("data/langs/English.txt","r",encoding="utf8")
it = 0
for line in wordData:
it += 1
if it % 1000 :
print(f"> {it}...")
rowContent = line.split()
if(len(rowContent)>=3): # checks if line is valid
tagsetName = rowContent[-1]
tagSetObject = None
try:
if usedTagset[tagsetName] == 1:
someTagset = TagSet.objects.get(name=tagsetName)
tagSetObject = someTagset
except KeyError:
usedTagset[tagsetName]=1
tagSetObject = TagSet(name=tagsetName)
rootWord = rowContent[0]
currWordList = rowContent[1:-1] # it can be more than a single words
currWord = ""
for temp in currWordList:
currWord += temp + " "
currWord = currWord[:-1] # remove last space
allLabels = tagsetName.split(";") # last block of words corrensponds to allLabels
for currLabel in allLabels:
try:
currFeature = findFeature[currLabel.upper()]
featObject = Feature.objects.get(name=currFeature)
tagSetObject.features.add(featObject)
except KeyError:
print(f"{currLabel} label doesn't exist.")
# print(tagSetObject.features.all())
tagSetObject.save()
# Defining the Word/Form
wordObject = Word(name=currWord)
lemmaObject = Lemma.objects.get(name=rootWord)
wordObject.lemma = lemmaObject
wordObject.tagset = tagSetObject
wordObject.language = lemmaObject.language
# print(f"{wordObject.name} : {wordObject.lemma} : {wordObject.tagset} : {wordObject.language}")
wordObject.save()
wordData.close()
# * uncomment below to populate !!in order!! *
dimensionPop()
featurePop()
genusPop()
posPop()
familyPop()
languagePop()
lemmaPop()
readAppendix()
wordPop()
#
# processes = []
# for _ in range(16):
# p = multiprocessing.Process(target=wordPop)
# p.start()
# processes.append(p)
# for proc in processes:
# process.join()
# Just in case it goes wrong
def emptyDatabase():
Word.objects.all().delete()
Lemma.objects.all().delete()
TagSet.objects.all().delete()
Language.objects.all().delete()
Family.objects.all().delete()
Dimension.objects.all().delete()
Genus.objects.all().delete()
POS.objects.all().delete()
print("Database is empty...")
# emptyDatabase()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:54:07.260",
"Id": "473660",
"Score": "0",
"body": "btw ``tqdm`` is a great module for reporting progress on a loop with very little overhead. Might be a good alternative to the manual iteration tracking in your word loop."
}
] |
[
{
"body": "<p>Just looking at <code>wordPop</code> since that's where you say the most time is being taken:</p>\n\n<ul>\n<li><p>I think your validity check is broken. There's an <code>if</code> statement to make sure the line is valid, but no <code>else</code>, and the code after the <code>if</code> uses variables defined within the conditional block.</p></li>\n<li><p>Use <code>\" \".join(currWordList)</code> instead of manually concatenating a bunch of strings. That'll save you the creation of a bunch of intermediate string objects.</p></li>\n<li><p>You're storing values of <code>1</code> in <code>usedTagset</code>, but that's meaningless. What you're actually doing each time is fetching the object from the database. Sure, that's a \"fast\" lookup if the <code>name</code> field is indexed, but nowhere near as fast as just fetching the object from the dictionary. Instead, consider something like the following:</p>\n\n<pre><code>if tagsetName not in usedTagset:\n usedTagset[tagsetName] = TagSet.objects.create(name=tagsetName)\ntagSetObject = usedTagset[tagsetName]\n</code></pre></li>\n<li><p>Same thing for the <code>findFeature</code> chunk in the <code>allLabels</code> loop. If you're just doing a couple lookups, <code>.get</code> on an indexed column is super fast... but that's \"fast\" relative to database speeds. In this context, \"fast\" means a few milliseconds or most of a ms, most likely. That's completely intolerable when you're doing a loop of hundreds of thousands or millions of rows. Fetch the objects once, cache them in memory, and do direct lookups using a dictionary. You can initialize the cache as follows:</p>\n\n<pre><code>usedTagset = {tag.name: tag for tag in TagSet.objects.all()}\n</code></pre>\n\n<p>and then, as discussed above, save any newly created objects as you create them rather than re-fetch them each time. If you're not sure if something already exists in the database, use <code>get_or_create</code>:</p>\n\n<pre><code>if tagsetName not in usedTagset:\n # get_or_create returns a tuple, the first element of which is the ORM object\n usedTagset[tagsetName] = TagSet.objects.get_or_create(name=tagsetName)[0]\ntagSetObject = usedTagset[tagsetName]\n</code></pre></li>\n</ul>\n\n<p>Cutting the DB and associated driver/network/ORM overhead out of the loop will likely be all you need to get reasonably performant code.</p>\n\n<ul>\n<li><p>I'm also a fan of <code>...objects.create</code>. It's more explicit that constructing the object one bit at a time.</p>\n\n<pre><code>lemma = lemma_lookup[rootWord]\nWord.objects.create(\n name=currWord,\n lemma=lemma,\n tagset=tagSetObject,\n language=lemma.language\n)\n</code></pre></li>\n<li><p>And finally, not performance related, but for the love of other Python developers, please follow <a href=\"https://realpython.com/python-pep8/#naming-conventions\" rel=\"nofollow noreferrer\">PEP8 naming conventions</a>, particularly using lower-case underscore-separated names for variables; e.g., <code>word_object</code> instead of <code>wordObject</code>, and <code>tag_set_object</code> instead of <code>tagSetObject</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T16:20:18.440",
"Id": "241380",
"ParentId": "241317",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241380",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T19:50:42.700",
"Id": "241317",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"django",
"mongodb"
],
"Title": "Speed up Python Script to populate MongoDB"
}
|
241317
|
<p>I recently created this Income Tax calculator based off your filing status (Single, or Married Filing Jointly) and which tax bracket you fall into for the 2020 tax year, taking into account the Standard deduction. I know the code is a little robust, but the math checks out as compared to several other tax calculators. I first posted it on Stack Overflow, which I now know was not the place for this, but please give any constructive advice you have.</p>
<p>How can I make this cleaner, as in, accomplish the same task with less code? Or if you have a different/more efficient way of writing any of this, I'm also interested.
<strong>Update:</strong> Thank you everyone for your advice and input! I'll be taking this back to the whiteboard and making the suggested changes as I learn more. Your time and advice is appreciated, immensely! </p>
<pre><code>marital_status = input("Filing Status (M / S): ")
household_income = int(input("household income: "))
if marital_status == "M":
standard_deduction = "24800"
# marrital standard deduction
elif marital_status == "S":
standard_deduction = "12400"
# single standard deduction
taxable_income = int(household_income) - int(standard_deduction)
married_bracket_caps = [19750, 80250, 171050, 326600, 414700, 622050]
# the above rates are the max dollar amount in the Married-filing-joint tax bracket(m/j)
single_bracket_caps = [9875, 40125, 85525, 163300, 207350, 518400]
# the above rates are the max dollar amount in the filing Single tax bracket
if marital_status == "M":
bracket = married_bracket_caps
elif marital_status == "S":
bracket = single_bracket_caps
#if M is entered, the future tax rates will abide by the m/j tax rates; #if
# S is entered than the taxt rates will abide by the Filing Single tax rates.
# ie. enter: M, the first tax rate will be "19750", computed as
if taxable_income <= int(bracket[0]):
tax = taxable_income * .1
elif taxable_income <= int(bracket[1]):
tax = (int(bracket[0]) * .1)+(.12*(taxable_income - int(bracket[0])))
elif taxable_income <= int(bracket[2]):
tax = (int(bracket[0]) * .1)+(.12*(int(bracket[1]) - int(bracket[0])))+(.22 * (taxable_income - int(bracket[1])))
elif taxable_income <= int(bracket[3]):
tax = (int(bracket[0]) * .1)+(.12*(int(bracket[1]) - int(bracket[0])))+(.22 * (int(bracket[2]) - int(bracket[1])))+(.24 * (taxable_income - int(bracket[2])))
print("taxable income: ", taxable_income)
print("owed in Federal tax: ", tax)
</code></pre>
<p><strong>Note:</strong> The brackets for this calculator only go up four brackets because if I didn't want to do all the way up if I was going to need to rewrite it anyway. Again, thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:27:59.210",
"Id": "473532",
"Score": "0",
"body": "Is it really `12` in the last two branches, or should it be `.12`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:30:22.143",
"Id": "473533",
"Score": "0",
"body": "_cleaner_ in which sense exactly?. Can you elaborate please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:35:13.087",
"Id": "473534",
"Score": "0",
"body": "@vnp You're exactly right. I accidentally deleted the \".\" while editing. A lesson in oversight. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:35:30.070",
"Id": "473535",
"Score": "0",
"body": "@πάνταῥεῖ The math that's done in each bracket is correct (except for what VNP pointed out), but I'm wondering if I can't accomplish the same with less written code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:38:35.927",
"Id": "473536",
"Score": "0",
"body": "@Erik Always add additional information by [edit]ing your question, instead of burying it into comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:50:30.317",
"Id": "473537",
"Score": "5",
"body": "@Erik Also note that less lines of code doesn't automatically means _cleaner_. In fact it's often the opposite."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T15:40:05.460",
"Id": "473948",
"Score": "0",
"body": "Alcohol wipes, Lysol, etc... ;)"
}
] |
[
{
"body": "<p>The main principle here is DRY (Don't Repeat Yourself). The trickiest part of your code is where you're successively applying the tax rates to the different brackets; a lot of the code is copied and pasted, including the rates themselves. Ideally you'd want to specify those rates in exactly one place and then have reusable code that's able to apply them in different situations. For a data-driven app like this, I think it's better to define all the data in one place in a set of tables rather than have it embedded throughout the rest of the code.</p>\n\n<p>Here's what I came up with after pulling the data from your code out into a set of lists, dicts, and enumerations:</p>\n\n<pre><code>from enum import Enum\n\n\nclass FilingStatus(Enum):\n \"\"\"Tax filing status.\"\"\"\n MARRIED = \"M\"\n SINGLE = \"S\"\n\n\nSTANDARD_DEDUCTION = {\n # Standard deduction by filing status.\n FilingStatus.MARRIED: 24800,\n FilingStatus.SINGLE: 12400,\n}\n# Tax rates for income up to each bracket cap.\nBRACKET_TAX_RATES = [.1, .12, .22, .24, .32, .35, .37]\n# Bracket caps by filing status.\nBRACKET_CAPS = {\n FilingStatus.MARRIED: [\n 0, 19750, 80250, 171050, 326600, 414700, 622050\n ],\n FilingStatus.SINGLE: [\n 0, 9875, 40125, 85525, 163300, 207350, 518400\n ],\n}\n\nassert all(\n len(bracket) == len(BRACKET_TAX_RATES)\n for bracket in BRACKET_CAPS.values()\n)\n\nfiling_status = FilingStatus(input(\"Filing Status (M / S): \"))\ngross_income = int(input(\"household income: \"))\ntaxable_income = gross_income - STANDARD_DEDUCTION[filing_status]\n\ntax = 0.0\ncaps = BRACKET_CAPS[filing_status]\nfor i in range(len(BRACKET_TAX_RATES)):\n rate = BRACKET_TAX_RATES[i]\n if i+1 >= len(caps) or taxable_income < caps[i+1]:\n # Income is under the next cap (or we're at the highest one already).\n # Apply the current rate to the income above the current cap and stop.\n tax += rate * (taxable_income - caps[i])\n break\n else:\n # Income is at or above the next cap.\n # Apply the current rate to the diff of the next and current caps.\n tax += rate * (caps[i+1] - caps[i])\n\nprint(\"taxable income: \", taxable_income)\nprint(\"owed in Federal tax: \", tax)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T00:41:33.240",
"Id": "473546",
"Score": "0",
"body": "Thanks Samwise! I see the changes, and please correct me if I'm wrong, but if the tax rates were to change than I would only need to change the BRACKET_TAX_RATES[ ] without having to make changes throughout the app. Thank you for your time and advice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T00:44:54.937",
"Id": "473549",
"Score": "3",
"body": "Yep, that's the idea! The `assert` is to make sure that if you change the number of brackets in one place you remember to do it in other places; you might end up with a subtle bug otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T10:18:46.920",
"Id": "473600",
"Score": "3",
"body": "instead of looping over the index (`for i in range(len(BRACKET_TAX_RATES))`), I would zip the brackets and rates in reverse order, and iterate over those. Doing it in reverse allows you to simplify the edge case. also refactor this part into a separate function: `def tax_calculation(gross_income, caps, rates):\n tax = 0;\n for cap, rate in zip(reversed(caps), reversed(rates), ):\n income_in_bracket = gross_income - cap;\n tax += income_in_bracket * rate;\n gross_income = min(gross_income, cap);\n return tax`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T08:24:27.337",
"Id": "473737",
"Score": "1",
"body": "Although there's no point in editing this answer, given @MaartenFabré's comment, in general, `for i in range(len(X)): x = X[i]` is better expressed as `for i, x in enumerate(X):`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:24:09.923",
"Id": "473801",
"Score": "1",
"body": "IMO an exception is when you need to manipulate `i` in some way, since I find an expression involving (`X[i]` and `X[i+1]`) clearer than one involving (`x` and `X[i+1]`), according to the \"make alike look alike\" principle -- but I understand some have strong feelings about this. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T22:55:03.673",
"Id": "241323",
"ParentId": "241319",
"Score": "9"
}
},
{
"body": "<p>You have 1 reputation point, and you make no use of functions or complex data structures. Because of this, I'm going to assume you're a beginner to coding. </p>\n\n<p>Congratulations, beginner, on finishing a program and on submitting it for review! You will find that you can learn a huge amount from reviews, probably more stuff faster than by any other method.</p>\n\n<p><strong>Control & Data structures</strong></p>\n\n<p>You don't show any loops or functions, so I won't suggest using them. Yet.</p>\n\n<p><strong>PEP 8</strong> </p>\n\n<p>I will suggest that you take a look at <a href=\"https://pep8.org/\" rel=\"noreferrer\">PEP-8</a>. It's \"THE standard\" for writing Python code, so the sooner you start drinking the Kool-Aid, the sooner you'll stop getting criticized for not following it. </p>\n\n<p><strong>CAPS are for constants</strong></p>\n\n<p>One thing you'll find in PEP 8 is the notion of different letter-case conventions for different kinds of name. Variable names that change are generally in what is called <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"noreferrer\"><code>snake_case</code></a>, while \"variables\" that <em>don't change</em> (that are called \"constants\" despite the fact that you <em>could</em> change them) are spelled using <code>ALL_CAPS</code>.</p>\n\n<p>In your code, you have some symbols that meet these criteria. Specifically, <code>married_bracket_caps</code> and <code>single_bracket_caps</code> are constants, and should be spelled that way.</p>\n\n<p>You can argue about whether other symbols, that are initialized based on a single choice and never change later, are constant or not. And people do. ;-)</p>\n\n<p><strong>Error Checking</strong></p>\n\n<p>You don't check for errors. At this point, with no way to loop and try again, your only option would be to exit the program. But you should still get in the habit of validating your inputs, especially inputs that come from those pesky humans. Humans are notorious for providing bad inputs. You have this:</p>\n\n<pre><code>if marital_status == \"M\":\n standard_deduction = \"24800\"\n # marrital standard deduction\nelif marital_status == \"S\":\n standard_deduction = \"12400\"\n # single standard deduction\n</code></pre>\n\n<p>Add this:</p>\n\n<pre><code>else:\n print(\"Eat flaming death, vile Terry!\")\n sys.exit(1)\n</code></pre>\n\n<p>(Or some other message, if you'd like.)</p>\n\n<p><strong>Don't Repeat Yourself</strong></p>\n\n<p>There is a currently-popular \"principle\" of programming called \"DRY\" -- short for \"Don't Repeat Yourself.\" A good programmer has dry code, dry socks, and a dry wit.</p>\n\n<p>In your case, you are repeating a test:</p>\n\n<pre><code>if marital_status == \"M\":\n standard_deduction = \"24800\"\n... \n\ntaxable_income = int(household_income) - int(standard_deduction)\n\nif marital_status == \"M\":\n bracket = married_bracket_caps\n...\n</code></pre>\n\n<p>Instead of repeating yourself, move the check down until you have all the data you need, and then do the test one time:</p>\n\n<pre><code>if marital_status == \"M\":\n bracket = MARRIED_BRACKET_CAPS\n standard_deduction = MARRIED_STANDARD_DEDUCTION\n</code></pre>\n\n<p><strong>DRY your code, redux</strong></p>\n\n<p>Also, you have this:</p>\n\n<pre><code>elif taxable_income <= int(bracket[1]):\n tax = (int(bracket[0]) * .1)+(.12*(taxable_income - int(bracket[0])))\n</code></pre>\n\n<p>This is bad because it repeats a lot, and because it puts too much work in a single expression. Let's look at it:</p>\n\n<pre><code>tax = bracket-0-cap * some rate + (income - bracket-0-cap) * some other rate\n</code></pre>\n\n<p>You can dry this out by eliminating a lot of the calls. For example, why are you calling <code>int()</code> on numbers that YOU put into YOUR array as <code>integers</code>? They're already <code>int</code>s, you don't need to do that!</p>\n\n<p><strong>No Magic Numbers</strong></p>\n\n<p>What's .1? What's .12? Those are called <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\"><strong>magic numbers</strong></a> and they're bad.</p>\n\n<p>Use constants (which you now know should be in ALL_CAPS) to replace these. Or use a lookup of an array (which is constant). Like:</p>\n\n<pre><code>tax = RATE_0 * income\n</code></pre>\n\n<p>or</p>\n\n<pre><code>tax = TAX_RATES[0] * income\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T01:01:29.517",
"Id": "473553",
"Score": "3",
"body": "You hit the nail on the head Austin! Very beginner (2-3 weeks in). I've found the PEP 8 and am already starting to read through it (I'll continue to study it). I've heard/read the suggestions about DRY and error checking. Thank you so much for your input, I'll definitely be incorporating your lessons. And I hope Terry meets his flaming end. Thank you for that laugh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T01:10:03.607",
"Id": "473717",
"Score": "2",
"body": "@Erik the Terries are us! It's a 60's sci-fi reference, uttered by the slime-fingered Groaci, Jaime Retief's eternal opponents in the Corps Diplomatique Terrestrienne."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T23:02:54.180",
"Id": "241324",
"ParentId": "241319",
"Score": "28"
}
},
{
"body": "<p>You could move the declaration of <code>married_bracket_caps</code> and <code>single_bracket_caps</code> to the beginning of the code, and then combine the first couple of if/elif blocks as they are both <code>if marital_status == 'M'</code>, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T00:44:14.487",
"Id": "473548",
"Score": "0",
"body": "Right! I basically repeated myself. Thank you Aiden!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T23:02:59.090",
"Id": "241325",
"ParentId": "241319",
"Score": "4"
}
},
{
"body": "<p>I'm not a Python dev, so I'm going to focus specifically on one area: the mathematical calculations themselves.</p>\n\n<p>Okay, so if you're making $X - how do you calculate your taxes? You're taking the 'Figure Out Which Bracket You Are In and then Calculate for that specific bracket' approach, but how about this (and I apologize for any syntax issues; like I said, it's not my language.): </p>\n\n<pre><code>alreadyTaxedIncome = 0\nremainingIncome = taxable_income\ntaxesDueFromPriorSegments = 0\n\nif remainingIncome <= int(bracket[0]):\n return taxesDueFromPriorSegments + remainingIncome * .1\nalreadyTaxedIncome = bracket[0]\nremainingIncome = taxable_income - bracket[0]\ntaxesDueFromPriorSegments = taxesDueFromPriorSegments + (bracket[0]-0) * 0.1\n\nif remainingIncome <= int(bracket[1]):\n return taxesDueFromPriorSegments + remainingIncome * .12\nalreadyTaxedIncome = bracket[1]\nremainingIncome = taxable_income - bracket[1]\ntaxesDueFromPriorSegments = taxesDueFromPriorSegments + (bracket[1]-bracket[0]) * 0.12\n\nif remainingIncome <= int(bracket[2]):\n return ... etc, repeating the above segment of 5 lines for each bracket\n</code></pre>\n\n<p>See what I did there? I redid the logic a bit so that it's \"flattened\" - if you have 20 brackets, you're not going to have an IF clause that results in a calculation that's 20 terms long. Instead, it just figures out how the taxes apply for the specific bracket, and continues going through until you've reached a bracket that no longer applies.</p>\n\n<p>Not only does this simplify the logic, it makes it possible to loop. Because... why wouldn't you have a loop? After all, that segment of 5 lines is going to be repeated over and over again, differing only in the array slot you're pulling from bracket[] and the marginal tax rate for that bracket.</p>\n\n<p>Next up would be OOP principles and refactoring code. In terms of objects, you've got two main ones:</p>\n\n<pre><code>TaxStructure - consists of a sorted array of TaxBrackets\nTaxBracket - consists of a top income and marginal tax rate\n</code></pre>\n\n<p>... and you're going to want a function that takes in a TaxStructure and an income amount, and returns back the taxes owed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T19:10:24.153",
"Id": "241449",
"ParentId": "241319",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:23:22.907",
"Id": "241319",
"Score": "19",
"Tags": [
"python",
"python-3.x"
],
"Title": "How can I make this tax calculator cleaner?"
}
|
241319
|
<p>I gave an attempt at reinventing the wheel and recreate list methods using my own Array Class to broaden my understanding about lists. I would like advice regarding efficiency, and in implementing negative indexes, since my code only works for positive ones.</p>
<pre class="lang-py prettyprint-override"><code>class Array:
def __init__(self, List=[]):
self.array = List
def display(self):
print(self.array)
def len(self):
array = self.array
count = 0
for _ in array:
count += 1
return count
def append(self, value):
array = self.array
length = self.len()
results = [None] * (length+1)
for i in range(length):
results[i] = array[i]
results[length] = value
self.array = results
def search(self, value):
array = self.array
pos = -1
for index in range(self.len()):
if array[index] == value:
pos = index
return pos
def insert(self, index, value):
array = self.array
length = self.len()
results = [None] * (length+1)
if index > length:
raise IndexError
elif index == length:
self.append(value)
results = self.array
else:
for i in range(length):
if i == index:
for j in range(index + 1, length + 1):
results[j] = array[j-1]
results[index] = value
break
else:
results[i] = array[i]
self.array = results
def delete(self, value):
array = self.array
length = self.len()
results = [None] * (length-1)
pos = self.search(value)
if pos == -1:
raise "Index Error: Element Not Found"
else:
for i in range(length):
if i != pos:
results[i] = array[i]
else:
for j in range(pos+1, length):
results[j-1] = array[j]
break
self.array = results
def pop(self):
array = self.array
length = self.len()
results = [None] * (length-1)
if length == 0:
raise IndexError
value = array[-1]
for i in range(length-1):
results[i] = array[i]
self.array = results
return value
</code></pre>
|
[] |
[
{
"body": "<p>Seems like cheating to re-implement a list using a list... I feel like the real challenge would be doing so without a list of any sort, say creating a linked list or a tree or something like that. That might be pedantic, but it'd clarify what your limitation are and thus what efficient solutions are available versus what you're making needlessly hard for yourself because it's fun.</p>\n\n<p>Most of your functions are going to be very expensive because you're constantly copying memory around. A more common approach is to over-allocate space and then keep two values, \"length\" and \"_allocated\". The first is how many valid elements your array contains; the second is how much space you've reserved to store values. When you want to append X to your array, you can just assign X to <code>self.array[self.length]</code> and then increment <code>self.length</code>. If that would take you beyond what you've allocated, only then you do the expensive act of allocating a new chunk of memory (in your case, the <code>[None] * (length + 1)</code> line) and copying the data. To minimize the number of copies, it's common practice to double the length of the array each time you resize it (maybe up to some maximum, at which point you add on new 4K element blocks or whatever rather than multiplying, to prevent running out of memory prematurely). When inserting, then, you'd just need to shift the later values rather than copy everything; similarly, when popping values off, just decrement <code>self.length</code> to mark that last element as unimportant and available to be overwritten.</p>\n\n<p>To complement that approach, if you want to optimize for mid-array insertions and deletions, you can maintain a parallel bit-array of which values are valid and which aren't. Iterating through the array becomes trickier (you need to zip the values with the validity flags and only return the valid ones), but deleting an item becomes cheaper since you only need to find the element and mark it as deleted (no shifting required), and inserting an item only requires shifting things until you find an unused element that can be overwritten instead of shifted.</p>\n\n<p>Caching the length of the array is a good idea in general (though not necessary if you don't over-allocate). It requires extra code and care to keep synchronized with the rest of the array, but checking a list's length is a very common thing for users to want to do, and the O(N) computation each time can get painful.</p>\n\n<p>As a general Python'ism, I'd say use <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__len__\" rel=\"nofollow noreferrer\"><code>def __len__</code></a> instead of <code>def len</code> and implement <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__getitem__\" rel=\"nofollow noreferrer\"><code>__get_item__</code></a>, as well as any other magic methods that generally correspond to an array. For reference see <a href=\"https://docs.python.org/3/library/collections.abc.html\" rel=\"nofollow noreferrer\">this documentation page</a>, and consider that most people think of an array as some combination of a <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.Collection\" rel=\"nofollow noreferrer\">\"Collection\"</a> and <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableSequence\" rel=\"nofollow noreferrer\">\"[Mutable]Sequence\"</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T22:21:29.740",
"Id": "241322",
"ParentId": "241320",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241322",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T21:55:52.003",
"Id": "241320",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"array",
"reinventing-the-wheel"
],
"Title": "Re-implementing an Array Class in Python"
}
|
241320
|
<p>So I'm writing a hobby programming language interpreter in C. It works but has serious performance problems.</p>
<p>According to <code>gprof</code>, the following function takes 30% of the running time (after excluding the time spent in the profiler itself). 75% of the 30% is spent only inside the function itself, <em>not</em> including its called children.</p>
<pre><code>bool table_get_value_directly(Table* table, Value key, Value* out) {
if (table->capacity == 0) {
return false;
}
unsigned long hash;
if (!value_hash(&key, &hash)) {
FAIL("Couldn't hash");
}
int slot = hash % table->capacity;
Node* root_node = table->entries[slot];
Node* node = root_node;
while (node != NULL) {
if (keys_equal(node->key, key)) {
*out = node->value;
return true;
}
node = node->next;
}
return false;
}
</code></pre>
<p>The function doesn't seem to do anything so slow that it would take up that much of the running time.</p>
<p><strong>Important to note:</strong> the <code>while</code> loop in the function never does more than one iteration, because a table in this test case (please see test case description below) <em>never has more than one entry</em>. So it can't be the loop I guess (?).</p>
<p>There's also the option that it's just called <em>a lot</em>, which it is. But according to <code>gprof</code>, the function's average running time does seem to be considerably high compared to all other functions in the system. Please consider <code>self ns/call</code> column of <code>gprof</code> output:</p>
<pre><code> % cumulative self self total
time seconds seconds calls ns/call ns/call name
33.40 24.94 24.94 _mcount_private
22.80 41.96 17.02 __fentry__
11.16 50.29 8.33 vm_interpret_frame
10.41 58.06 7.77 269775125 28.80 37.77 table_get_value_directly
3.67 60.80 2.74 get_string_from_cache
1.89 62.21 1.41 125659994 11.22 53.29 table_get_cstring_key
1.58 63.39 1.18 266250220 4.43 4.43 object_thread_push_eval_stack
1.38 64.42 1.03 321615299 3.20 4.48 value_compare
1.23 65.34 0.92 266250219 3.46 3.46 object_thread_pop_eval_stack
1.08 66.15 0.81 57173998 14.17 16.91 table_iterate
1.03 66.92 0.77 18455049 41.72 50.03 table_set_value_directly
0.84 67.55 0.63 269775227 2.34 4.82 value_hash
0.74 68.10 0.55 new_stack_frame.constprop.0
0.71 68.63 0.53 107205032 4.94 61.41 cell_table_get_value_cstring_key
0.71 69.16 0.53 18454948 28.72 156.39 cell_table_set_value_cstring_key
0.66 69.65 0.49 144115145 3.40 3.40 hash_string_bounded
0.62 70.11 0.46 144115059 3.19 40.96 table_get
0.51 70.49 0.38 gc_mark_table
0.44 70.82 0.33 181025001 1.82 1.82 cstrings_equal
0.42 71.13 0.31 144114987 2.15 2.15 object_string_copy
0.42 71.44 0.31 144114946 2.15 2.15 object_string_copy_from_null_terminated
0.36 71.71 0.27 107205046 2.52 56.46 cell_table_get_cell_cstring_key
0.36 71.98 0.27 36910241 7.32 28.69 table_free
0.36 72.25 0.27 18454950 14.63 68.96 table_set_cstring_key
0.32 72.49 0.24 load_extension_module
0.24 72.67 0.18 125660109 1.43 1.43 object_hash
0.24 72.85 0.18 18454935 9.75 9.75 vm_call_function
0.23 73.02 0.17 57174015 2.97 3.57 pointer_array_free
0.19 73.16 0.14 92275417 1.52 1.52 table_init
0.19 73.30 0.14 collect_values
0.16 73.42 0.12 18454935 6.50 16.26 vm_call_object
0.13 73.52 0.10 167904869 0.60 0.60 deallocate
0.13 73.62 0.10 18455019 5.42 5.42 object_cell_new
0.12 73.71 0.09 25492005 3.53 4.59 pointer_array_write
</code></pre>
<p>So what we have is a function that doesn't look like it does much (again, the loop only ever iterates once), but we still spend a very long time in.</p>
<p>So I would like to hear from those who are good at optimization and might have a clue what this function might do that may cause it to run so slow.</p>
<p><strong>EDIT:</strong></p>
<p>After reading the remarks by @vnp and other comments, adding a few things here.</p>
<p><strong>A. Stats on hash tables in the program</strong></p>
<p>I measured the stats. Please note, <strong>table->capacity is the number of <em>root nodes</em> being currently allowed in the base array of the table.</strong></p>
<pre><code>Total times function is called: 18455028
Avg capacity: 8
Max capacity: 32
Avg bucket count: 1
Avg entries count: 1
</code></pre>
<p><strong>B. The test case</strong></p>
<p>@vnp mentioned that "<em>table_get_value_directly is called quarter of trillion times [corrected to quarter of a billion]. Either you have a seriously large test case, or the calling code does something seriously wrong</em>".</p>
<p>The test case is the following: I run a recursive <code>fibonacci(35)</code> function in the interpreter programming langauge. This means the <code>fibonacci</code> function should be called 18454929 times.</p>
<p>The code for it is:</p>
<pre><code>fib = { takes n to
if n < 0 {
print("Incorrect input")
} elsif n == 1 {
return 0
} elsif n == 2 {
return 1
} else {
return fib(n - 1) + fib(n - 2)
}
}
</code></pre>
<p>For each of these iterations, it seems we should access the table for the local variable <code>n</code> between 1 and 5 times. That would bring us to approximately 1/8 of a billion... I'm not really sure where the other accesses come from (I will check), but would you say it still looks extremely problematic, or reasonable for this type of test case?</p>
<p><strong>C. The entire hash table code and related files</strong></p>
<p><strong>table.h</strong></p>
<pre><code>#ifndef plane_table_h
#define plane_table_h
#include "common.h"
#include "value.h"
#include "pointerarray.h"
typedef struct {
Value key;
Value value;
} EntryNew;
typedef struct Node {
struct Node* next;
Value key;
Value value;
} Node;
typedef struct {
int capacity;
int bucket_count;
Node** entries;
bool is_memory_infrastructure;
bool is_growing; // for debugging
size_t num_entries;
} Table;
struct ObjectString;
Table table_new_empty(void);
void table_init(Table* table);
void table_init_memory_infrastructure(Table* table);
void table_set(Table* table, struct Value key, Value value);
bool table_get(Table* table, struct Value key, Value* out);
void table_set_value_directly(Table* table, struct Value key, Value value);
bool table_get_value_directly(Table* table, Value key, Value* out);
void table_set_cstring_key(Table* table, const char* key, Value value);
bool table_get_cstring_key(Table* table, const char* key, Value* out);
bool table_delete(Table* table, Value key);
void table_free(Table* table);
PointerArray table_iterate(Table* table, const char* alloc_string);
void table_print_debug_as_buckets(Table* table, bool show_empty_buckets);
void table_debug_print_general_stats(void);
#endif
</code></pre>
<p><strong>table.c</strong></p>
<pre><code>#include <string.h>
#include "table.h"
#include "plane_object.h"
#include "memory.h"
#include "common.h"
#include "value.h"
/* For debugging */
static size_t times_called = 0;
static size_t capacity_sum = 0;
static size_t max_capacity = 0;
static size_t bucket_sum = 0;
static size_t avg_bucket_count = 0;
static size_t entries_sum = 0;
static size_t avg_entries_sum = 0;
static double avg_capacity = 0;
/* ..... */
void table_debug_print_general_stats(void) {
printf("Times called: %" PRI_SIZET "\n", times_called);
printf("Sum capacity: %" PRI_SIZET "\n", capacity_sum);
printf("Avg capacity: %g\n", avg_capacity);
printf("Max capacity: %" PRI_SIZET "\n", max_capacity);
printf("Sum buckets: %" PRI_SIZET "\n", bucket_sum);
printf("Avg bucket count: %" PRI_SIZET "\n", avg_bucket_count);
printf("Entries sum: %" PRI_SIZET "\n", entries_sum);
printf("Avg entries: %" PRI_SIZET "\n", avg_entries_sum);
}
#define MAX_LOAD_FACTOR 0.75
static void* allocate_suitably(Table* table, size_t size, const char* what) {
if (!table->is_memory_infrastructure) {
return allocate(size, what);
}
return allocate_no_tracking(size);
}
static void deallocate_suitably(Table* table, void* pointer, size_t size, const char* what) {
if (!table->is_memory_infrastructure) {
deallocate(pointer, size, what);
return;
}
deallocate_no_tracking(pointer);
}
static bool keys_equal(Value v1, Value v2) {
int compare_result = -1;
bool compare_success = value_compare(v1, v2, &compare_result);
return compare_success && (compare_result == 0);
}
static void grow_table(Table* table) {
DEBUG_MEMORY("Growing table.");
if (table->is_growing) {
FAIL("grow_table() called while table is already growing."); // For current debugging, remove later
}
table->is_growing = true;
int old_capacity = table->capacity;
Node** old_entries = table->entries;
table->capacity = GROW_CAPACITY(table->capacity);
table->bucket_count = 0;
table->num_entries = 0;
table->entries = allocate_suitably(table, sizeof(Node*) * table->capacity, "Hash table array");
for (size_t i = 0; i < table->capacity; i++) {
table->entries[i] = NULL;
}
DEBUG_MEMORY("Old capacity: %d. New capacity: %d", old_capacity, table->capacity);
for (size_t i = 0; i < old_capacity; i++) {
Node* old_entry = old_entries[i];
while (old_entry != NULL) {
table_set_value_directly(table, old_entry->key, old_entry->value);
Node* current = old_entry;
old_entry = old_entry->next;
deallocate_suitably(table, current, sizeof(Node), "Table linked list node");
}
}
DEBUG_MEMORY("Deallocating old table array.");
deallocate_suitably(table, old_entries, sizeof(Node*) * old_capacity, "Hash table array");
table->is_growing = false;
}
void table_init(Table* table) {
table->bucket_count = 0;
table->capacity = 0;
table->is_memory_infrastructure = false;
table->is_growing = false;
table->entries = NULL;
table->num_entries = 0;
}
void table_init_memory_infrastructure(Table* table) {
table_init(table);
table->is_memory_infrastructure = true;
}
void table_set_cstring_key(Table* table, const char* key, Value value) {
Value copied_key = MAKE_VALUE_OBJECT(object_string_copy_from_null_terminated(key));
table_set_value_directly(table, copied_key, value);
}
void table_set_value_directly(Table* table, struct Value key, Value value) {
if (table->bucket_count + 1 > table->capacity * MAX_LOAD_FACTOR) {
grow_table(table);
}
unsigned long hash;
if (!value_hash(&key, &hash)) {
FAIL("Couldn't hash");
}
int slot = hash % table->capacity;
Node* root_node = table->entries[slot];
Node* node = root_node;
if (root_node == NULL) {
table->bucket_count++;
}
while (node != NULL) {
if (keys_equal(node->key, key)) {
node->value = value;
break;
}
node = node->next;
}
if (node == NULL) {
Node* new_node = allocate_suitably(table, sizeof(Node), "Table linked list node");
new_node->key = key;
new_node->value = value;
new_node->next = root_node;
table->entries[slot] = new_node;
table->num_entries++;
}
}
bool table_get_cstring_key(Table* table, const char* key, Value* out) {
Value value_key = MAKE_VALUE_OBJECT(object_string_copy_from_null_terminated(key));
return table_get_value_directly(table, value_key, out);
}
bool table_get_value_directly(Table* table, Value key, Value* out) {
if (table->capacity == 0) {
return false;
}
unsigned long hash;
if (!value_hash(&key, &hash)) {
FAIL("Temporary FAIL: Couldn't hash in table_get.");
}
int slot = hash % table->capacity;
Node* root_node = table->entries[slot];
Node* node = root_node;
while (node != NULL) {
if (keys_equal(node->key, key)) {
*out = node->value;
return true;
}
node = node->next;
}
/* Temporary: just for stats for this question */
times_called++;
capacity_sum += table->capacity;
avg_capacity = capacity_sum / times_called;
if (table->capacity > max_capacity) {
max_capacity = table->capacity;
}
bucket_sum += table->bucket_count;
avg_bucket_count = bucket_sum / times_called;
entries_sum += table->num_entries;
avg_entries_sum = entries_sum / times_called;
/* ....... */
return false;
}
bool table_delete(Table* table, Value key) {
if (table->capacity == 0) {
return false;
}
unsigned long hash;
if (!value_hash(&key, &hash)) {
return false;
}
int slot = hash % table->capacity;
Node* root_node = table->entries[slot];
Node* node = root_node;
Node* previous = NULL;
while (node != NULL) {
if (keys_equal(node->key, key)) {
if (previous != NULL) {
previous->next = node->next;
deallocate_suitably(table, node, sizeof(Node), "Table linked list node");
} else {
table->entries[slot] = node->next;
deallocate_suitably(table, node, sizeof(Node), "Table linked list node");
}
if (table->num_entries <= 0) {
FAIL("table->num_entries <= 0 while deleting entry.");
}
table->num_entries--;
return true;
} else {
previous = node;
node = node->next;
}
}
return false;
}
PointerArray table_iterate(Table* table, const char* alloc_string) {
PointerArray array;
pointer_array_init(&array, alloc_string);
// TODO: Is it correct to iterate on table->capacity instead of table->count?
for (size_t i = 0; i < table->capacity; i++) {
Node* node = table->entries[i];
while (node != NULL) {
pointer_array_write(&array, node);
node = node->next;
}
}
return array;
}
void table_print_debug_as_buckets(Table* table, bool show_empty_buckets) {
for (size_t i = 0; i < table->capacity; i++) {
Node* node = table->entries[i];
if (node != NULL || (node == NULL && show_empty_buckets)) {
printf("Bucket [%3" PRI_SIZET "Z]", i);
while (node != NULL) {
printf(" ---> ");
printf("<");
value_print(node->key);
printf(" : ");
value_print(node->value);
printf(">");
node = node->next;
}
printf("\n");
}
}
}
void table_free(Table* table) {
PointerArray entries = table_iterate(table, "table free table_iterate buffer");
for (size_t i = 0; i < entries.count; i++) {
Node* node = entries.values[i];
deallocate_suitably(table, node, sizeof(Node), "Table linked list node");
}
pointer_array_free(&entries);
deallocate_suitably(table, table->entries, sizeof(Node*) * table->capacity, "Hash table array");
table_init(table);
}
Table table_new_empty(void) {
Table table;
table_init(&table);
return table;
}
</code></pre>
<p><strong>value.h</strong></p>
<pre><code>#ifndef plane_value_h
#define plane_value_h
#include "bytecode.h"
#include "common.h"
#include "dynamic_array.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_NIL,
VALUE_RAW_STRING,
VALUE_CHUNK,
VALUE_OBJECT,
VALUE_ALLOCATION, // Internal
VALUE_ADDRESS // Internal
} ValueType;
typedef struct {
const char* data;
int length;
unsigned long hash;
} RawString;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
RawString raw_string;
Bytecode chunk;
struct Object* object;
Allocation allocation;
uintptr_t address;
} as;
} Value;
#define MAKE_VALUE_NUMBER(n) (Value){.type = VALUE_NUMBER, .as.number = (n)}
#define MAKE_VALUE_BOOLEAN(val) (Value){.type = VALUE_BOOLEAN, .as.boolean = (val)}
#define MAKE_VALUE_NIL() (Value){.type = VALUE_NIL, .as.number = -1}
#define MAKE_VALUE_RAW_STRING(cstring, the_length, the_hash) (Value){.type = VALUE_RAW_STRING, .as.raw_string \
= (RawString) {.data = (cstring), .length = (the_length), .hash = (the_hash)}}
#define MAKE_VALUE_OBJECT(o) (Value){.type = VALUE_OBJECT, .as.object = (struct Object*)(o)}
#define MAKE_VALUE_CHUNK(the_chunk) (Value){.type = VALUE_CHUNK, .as.chunk = (the_chunk)}
#define MAKE_VALUE_ALLOCATION(the_name, the_size) (Value) {.type = VALUE_ALLOCATION, \
.as.allocation = (Allocation) {.name = the_name, .size = the_size}}
#define MAKE_VALUE_ADDRESS(the_address) (Value) {.type = VALUE_ADDRESS, .as.address = (uintptr_t) the_address }
#define ASSERT_VALUE_TYPE(value, expected_type) \
do { \
if (value.type != expected_type) { \
FAIL("Expected value type: %d, found: %d", expected_type, value.type); \
} \
} while (false)
void value_print(Value value);
bool value_compare(Value a, Value b, int* output);
bool value_hash(Value* value, unsigned long* result);
#endif
</code></pre>
<p><strong>value.c</strong></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <math.h>
#include "value.h"
#include "plane_object.h"
#include "memory.h"
void value_print(Value value) {
switch (value.type) {
case VALUE_NUMBER: {
printf("%g", value.as.number);
return;
}
case VALUE_OBJECT: {
object_print(value.as.object);
return;
}
case VALUE_BOOLEAN: {
printf(value.as.boolean ? "true" : "false");
return;
}
case VALUE_RAW_STRING: {
RawString string = value.as.raw_string;
printf("\"%.*s\"", string.length, string.data);
return;
}
case VALUE_CHUNK: {
Bytecode chunk = value.as.chunk;
printf("< Chunk of size %d pointing at '%p' >", chunk.count, chunk.code);
return;
}
case VALUE_NIL: {
printf("nil");
return;
}
case VALUE_ADDRESS: {
printf("%" PRIxPTR , value.as.address);
return;
}
case VALUE_ALLOCATION: {
Allocation allocation = value.as.allocation;
printf("<Internal: allocation marker of '\%s' size %" PRI_SIZET ">", allocation.name, allocation.size);
return;
}
}
FAIL("Unrecognized VALUE_TYPE: %d", value.type);
}
bool value_compare(Value a, Value b, int* output) {
if (a.type != b.type) {
*output = -1;
return true;
}
switch (a.type) {
case VALUE_NUMBER: {
double n1 = a.as.number;
double n2 = b.as.number;
if (n1 == n2) {
*output = 0;
} else if (n1 > n2) {
*output = 1;
} else {
*output = -1;
}
return true;
}
case VALUE_BOOLEAN: {
bool b1 = a.as.boolean;
bool b2 = b.as.boolean;
if (b1 == b2) {
*output = 0;
} else {
*output = -1;
}
return true;
}
case VALUE_OBJECT: {
bool objectsEqual = object_compare(a.as.object, b.as.object);
if (objectsEqual) {
*output = 0;
} else {
*output = -1;
}
return true;
}
case VALUE_NIL: {
*output = 0;
return true;
}
case VALUE_ADDRESS: {
uintptr_t addr1 = a.as.address;
uintptr_t addr2 = b.as.address;
if (addr1 == addr2) {
*output = 0;
} else if (addr1 < addr2) {
*output = -1;
} else {
*output = 1;
}
return true;
}
case VALUE_ALLOCATION: {
Allocation alloc1 = a.as.allocation;
Allocation alloc2 = b.as.allocation;
*output = (alloc1.size == alloc2.size) && (strcmp(alloc1.name, alloc2.name) == 0); /* BUG ??? */
return true;
}
case VALUE_CHUNK: {
FAIL("Attempting to compare chunks. Shouldn't happen.");
return false;
}
case VALUE_RAW_STRING: {
RawString s1 = a.as.raw_string;
RawString s2 = b.as.raw_string;
if (cstrings_equal(s1.data, s1.length, s2.data, s2.length)) {
*output = 0;
} else {
*output = -1;
}
return true;
}
}
FAIL("Couldn't compare values. Type A: %d, type B: %d", a.type, b.type);
return false;
}
bool value_hash(Value* value, unsigned long* result) {
switch (value->type) {
case VALUE_OBJECT: {
unsigned long hash;
if (object_hash(value->as.object, &hash)) {
*result = hash;
return true;
}
return false;
}
case VALUE_CHUNK: {
FAIL("Since Bytecode values aren't supposed to be reachable directly from user code, this should never happen.");
return false;
}
case VALUE_BOOLEAN: {
*result = value->as.boolean ? 0 : 1;
return true;
}
case VALUE_NUMBER: {
*result = hash_int(floor(value->as.number)); // TODO: Not good at all, redo this
return true;
}
case VALUE_NIL: {
*result = 0;
return true;
}
case VALUE_RAW_STRING: {
RawString string = value->as.raw_string;
*result = string.hash;
return true;
}
case VALUE_ADDRESS: {
*result = hash_int(value->as.address); // Not good at all, but should logically work
return true;
}
case VALUE_ALLOCATION: {
return false;
}
}
FAIL("value.c:hash_value - shouldn't get here.");
return false;
}
</code></pre>
<p><strong>pointerarray.h</strong></p>
<pre><code>#ifndef plane_pointerarray_h
#define plane_pointerarray_h
typedef struct {
int count;
int capacity;
void** values;
const char* alloc_string; /* Kind of ugly, purely for debugging */
} PointerArray;
void pointer_array_init(PointerArray* array, const char* alloc_string);
void pointer_array_write(PointerArray* array, void* value);
void pointer_array_free(PointerArray* array);
void** pointer_array_to_plain_array(PointerArray* array, const char* what);
#endif
</code></pre>
<p><strong>memory.h</strong></p>
<pre><code>#ifndef plane_memory_h
#define plane_memory_h
#include "common.h"
typedef struct {
const char* name;
size_t size;
} Allocation;
#define GROW_CAPACITY(capacity) (capacity) < 8 ? 8 : (capacity) * 2
size_t get_allocated_memory();
size_t get_allocations_count();
void memory_init(void);
void* allocate(size_t size, const char* what);
void deallocate(void* pointer, size_t oldSize, const char* what);
void* reallocate(void* pointer, size_t oldSize, size_t newSize, const char* what);
void* allocate_no_tracking(size_t size);
void deallocate_no_tracking(void* pointer);
void* reallocate_no_tracking(void* pointer, size_t new_size);
void memory_print_allocated_entries(); // for debugging
#endif
</code></pre>
<p><strong>plane_object.h</strong></p>
<pre><code>#ifndef plane_object_h
#define plane_object_h
#include <Windows.h>
#include "bytecode.h"
#include "common.h"
#include "table.h"
#include "value.h"
#include "cell_table.h"
typedef enum {
OBJECT_STRING,
OBJECT_FUNCTION,
OBJECT_CODE,
OBJECT_TABLE,
OBJECT_CELL,
OBJECT_MODULE,
OBJECT_THREAD,
OBJECT_CLASS,
OBJECT_INSTANCE,
OBJECT_BOUND_METHOD
} ObjectType;
typedef enum {
METHOD_ACCESS_SUCCESS,
METHOD_ACCESS_NO_SUCH_ATTR,
METHOD_ACCESS_ATTR_NOT_BOUND_METHOD
} MethodAccessResult;
typedef struct Object {
ObjectType type;
struct Object* next;
CellTable attributes;
bool is_reachable;
} Object;
typedef struct ObjectString {
Object base;
char* chars;
int length;
unsigned long hash;
} ObjectString;
typedef struct ObjectTable {
Object base;
Table table;
} ObjectTable;
typedef struct ObjectCode {
Object base;
Bytecode bytecode;
} ObjectCode;
typedef bool (*NativeFunction)(Object*, ValueArray, Value*);
typedef struct ObjectCell {
Object base;
Value value;
bool is_filled;
} ObjectCell;
typedef struct ObjectFunction {
Object base;
char* name;
char** parameters;
int num_params;
bool is_native;
CellTable free_vars;
union {
NativeFunction native_function;
ObjectCode* code;
};
} ObjectFunction;
typedef struct ObjectModule {
Object base;
ObjectString* name;
ObjectFunction* function;
HMODULE dll;
} ObjectModule;
#define THREAD_EVAL_STACK_MAX 255
#define THREAD_CALL_STACK_MAX 255
typedef struct {
uint8_t* return_address;
ObjectFunction* function;
Object* base_entity;
CellTable local_variables;
bool is_entity_base;
bool is_native;
bool discard_return_value;
} StackFrame;
typedef struct ObjectThread {
Object base;
char* name;
struct ObjectThread* previous_thread;
struct ObjectThread* next_thread;
uint8_t* ip;
ObjectFunction* base_function;
Value* eval_stack_top;
Value eval_stack[THREAD_EVAL_STACK_MAX];
StackFrame* call_stack_top;
StackFrame call_stack[THREAD_CALL_STACK_MAX];
} ObjectThread;
typedef struct ObjectInstance ObjectInstance;
typedef void (*DeallocationFunction)(struct ObjectInstance *);
typedef Object** (*GcMarkFunction)(struct ObjectInstance *);
typedef struct ObjectClass {
/* TODO: Make distinction between plane and native classes clearer. Different types? Flag? Union? */
Object base;
char* name;
int name_length;
ObjectFunction* base_function;
size_t instance_size;
DeallocationFunction dealloc_func;
GcMarkFunction gc_mark_func;
} ObjectClass;
typedef struct ObjectInstance {
Object base;
ObjectClass* klass;
bool is_initialized;
} ObjectInstance;
typedef struct ObjectBoundMethod {
Object base;
Object* self;
ObjectFunction* method;
} ObjectBoundMethod;
ObjectString* object_string_copy(const char* string, int length);
ObjectString* object_string_take(char* chars, int length);
ObjectString* object_string_clone(ObjectString* original);
ObjectString** object_create_copied_strings_array(const char** strings, int num, const char* allocDescription);
ObjectString* object_string_copy_from_null_terminated(const char* string);
ObjectFunction* object_user_function_new(ObjectCode* code, char** parameters, int numParams, CellTable free_vars);
ObjectFunction* object_native_function_new(NativeFunction nativeFunction, char** parameters, int numParams);
void object_function_set_name(ObjectFunction* function, char* name);
ObjectFunction* make_native_function_with_params(char* name, int num_params, char** params, NativeFunction function);
ObjectCode* object_code_new(Bytecode chunk);
ObjectTable* object_table_new(Table table);
ObjectTable* object_table_new_empty(void);
ObjectCell* object_cell_new(Value value);
ObjectCell* object_cell_new_empty(void);
ObjectClass* object_class_new(ObjectFunction* base_function, char* name);
ObjectClass* object_class_native_new(
char* name, size_t instance_size, DeallocationFunction dealloc_func,
GcMarkFunction gc_mark_func, ObjectFunction* constructor, void* descriptors[][2]);
void object_class_set_name(ObjectClass* klass, char* name, int length);
ObjectInstance* object_instance_new(ObjectClass* klass);
ObjectModule* object_module_new(ObjectString* name, ObjectFunction* function);
ObjectModule* object_module_native_new(ObjectString* name, HMODULE dll);
ObjectBoundMethod* object_bound_method_new(ObjectFunction* method, Object* self);
ObjectThread* object_thread_new(ObjectFunction* function, char* name);
void object_thread_push_eval_stack(ObjectThread* thread, Value value);
Value object_thread_pop_eval_stack(ObjectThread* thread);
void object_thread_push_frame(ObjectThread* thread, StackFrame frame);
StackFrame object_thread_pop_frame(ObjectThread* thread);
StackFrame* object_thread_peek_frame(ObjectThread* thread, int offset);
bool object_compare(Object* a, Object* b);
bool object_strings_equal(ObjectString* a, ObjectString* b);
void object_free(Object* object);
void object_print(Object* o);
void object_print_all_objects(void);
void object_thread_print(ObjectThread* thread);
void object_thread_print_diagnostic(ObjectThread* thread);
bool object_hash(Object* object, unsigned long* result);
// MethodAccessResult object_get_method(Object* object, const char* method_name, ObjectFunction** out);
MethodAccessResult object_get_method(Object* object, const char* method_name, ObjectBoundMethod** out);
#define OBJECT_AS_STRING(o) (object_as_string(o))
#define OBJECT_AS_FUNCTION(o) (object_as_function(o))
ObjectString* object_as_string(Object* o);
ObjectFunction* object_as_function(Object* o);
bool object_value_is(Value value, ObjectType type);
void object_set_attribute_cstring_key(Object* object, const char* key, Value value);
bool object_load_attribute(Object* object, ObjectString* name, Value* out);
bool object_load_attribute_cstring_key(Object* object, const char* name, Value* out);
bool load_attribute_bypass_descriptors(Object* object, ObjectString* name, Value* out); /* Internal: only external to be used by some tests */
ObjectInstance* object_descriptor_new(ObjectFunction* get, ObjectFunction* set);
ObjectInstance* object_descriptor_new_native(NativeFunction get, NativeFunction set);
bool is_instance_of_class(Object* object, char* klass_name);
bool is_value_instance_of_class(Value value, char* klass_name);
ObjectFunction* object_make_constructor(int num_params, char** params, NativeFunction function);
#define VALUE_AS_OBJECT(value, object_type, cast) object_value_is(value, object_type) ? (cast*) value.as.object : NULL
#define ASSERT_VALUE_AS_OBJECT(variable, value, object_type, cast, error) \
do { \
variable = VALUE_AS_OBJECT((value), object_type, cast); \
if (variable == NULL) { \
FAIL(error); \
} \
} while (false);
#define ASSERT_VALUE_IS_OBJECT(value, object_type, error_message) \
do { \
if (!object_value_is(value, object_type)) { \
FAIL(error_message); \
} \
} while (false); \
#endif
</code></pre>
<p><strong>common.h</strong></p>
<pre><code>#ifndef plane_common_h
#define plane_common_h
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <inttypes.h>
#include <assert.h>
/* Generally keep these OFF unless you need them specifically */
#define DISABLE_GC 0 // Only set to 1 for debugging purposes when you need the GC to not run
#define DEBUG 0 // General debug printing
#define DEBUG_TRACE_EXECUTION 0 // Show stack operations
#define DEBUG_THREADING 0
#define DEBUG_GC 0 // Show GC operations
#define DEBUG_OBJECTS 0 // Show object operations
#define DEBUG_MEMORY_EXECUTION 0 // Show low-level memory operations
#define DEBUG_SCANNER 0 // Show low level lexing output and such
#define DEBUG_PAUSE_AFTER_OPCODES 0 // Wait for user input after each opcode
#define DEBUG_TABLE_STATS 0 // Collect statistics on general hash table behavior
/* ****************** */
/* Probably leave this ON most of the time during DEV. Disable for release. */
#define GC_STRESS_TEST 0 // Run GC every loop iteration. Used to help GC bugs surface. Obviously really bad for performance
/* ************** */
/* Always leave these two ON in DEV. Probably disable for release */
#define MEMORY_DIAGNOSTICS 0 // Usually leave on in dev. Disable for release
#define DEBUG_IMPORTANT 1 // Pretty much always leave this on, at least in dev - printing critical diagnosis and such
/* **************** */
#if DEBUG
#define DEBUG_PRINT(...) do { \
fprintf(stdout, "DEBUG: "); \
fprintf (stdout, __VA_ARGS__); \
fprintf(stdout, "\n"); \
} while (false)
#else
#define DEBUG_PRINT(...) do {} while(false)
#endif
#if DEBUG_MEMORY_EXECUTION
#define DEBUG_MEMORY(...) do { \
fprintf(stdout, "MEMORY: "); \
fprintf (stdout, __VA_ARGS__); \
fprintf(stdout, "\n"); \
} while (false)
#else
#define DEBUG_MEMORY(...) do {} while(false)
#endif
#if DEBUG_THREADING
#define DEBUG_THREADING_PRINT(...) do { \
fprintf (stdout, __VA_ARGS__); \
} while (false)
#else
#define DEBUG_THREADING_PRINT(...) do {} while(false)
#endif
#if DEBUG_IMPORTANT
#define DEBUG_IMPORTANT_PRINT(...) do { \
fprintf (stdout, __VA_ARGS__); \
} while (false)
#else
#define DEBUG_IMPORTANT_PRINT(...) do {} while(false)
#endif
#if DEBUG_TRACE_EXECUTION
#define DEBUG_TRACE(...) do { \
fprintf (stdout, __VA_ARGS__); \
fprintf (stdout, "\n"); \
} while (false)
#else
#define DEBUG_TRACE(...) do {} while(false)
#endif
#if DEBUG_SCANNER
#define DEBUG_SCANNER_PRINT(...) do { \
fprintf (stdout, "Scanner: " __VA_ARGS__); \
fprintf (stdout, "\n"); \
} while (false)
#else
#define DEBUG_SCANNER_PRINT(...) do {} while(false)
#endif
#if DEBUG_OBJECTS
#define DEBUG_OBJECTS_PRINT(...) do { \
fprintf (stdout, __VA_ARGS__); \
fprintf (stdout, "\n"); \
} while (false)
#else
#define DEBUG_OBJECTS_PRINT(...) do {} while(false)
#endif
#if DEBUG_GC
#define DEBUG_GC_PRINT(...) do { \
fprintf (stdout, __VA_ARGS__); \
fprintf (stdout, "\n"); \
} while (false)
#else
#define DEBUG_GC_PRINT(...) do {} while(false)
#endif
// TODO: actual assertion or error mechanisms
#define FAIL(...) do { \
fprintf(stdout, "\nFAILING! Reason:'"); \
fprintf(stdout, __VA_ARGS__); \
fprintf(stdout, "'\n"); \
exit(EXIT_FAILURE); \
} while(false)
#endif
#define PRINTLN(str) do { \
printf("\n"); \
printf(str); \
printf("\n"); \
} while (false)
#ifdef _WIN32
# ifdef _WIN64
# define PRI_SIZET PRIu64
# else
# define PRI_SIZET PRIu32
# endif
#else
# define PRI_SIZET "zu"
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T03:53:31.393",
"Id": "473567",
"Score": "4",
"body": "How large is `table->capacity`? Just a ballpark estimate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T04:49:10.467",
"Id": "473570",
"Score": "1",
"body": "What is the average collision chain length, what is the average number of loop iterations in each a) successful b) unsuccessful search? There'd be nothing wrong with 2…. 42 would hurt one way, 1.007 the other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T04:51:54.800",
"Id": "473571",
"Score": "1",
"body": "`% is spent only inside the function itself, not including its called children` Did you control/check inlining? How and to what result?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:15:23.507",
"Id": "473981",
"Score": "0",
"body": "This question needs an answer from people who are very good at optimization. For that I am assisting the OP with a bounty of 200 pts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T22:24:42.527",
"Id": "473995",
"Score": "0",
"body": "Calling `std::unordered_map::find` takes about 20ns per call if it only contains a few integers. So it's faster, but not by a lot. Are you sure you're not calling this too often?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T13:14:18.587",
"Id": "474052",
"Score": "0",
"body": "@AvivCohn You need to accept an answer if it works. The only way the bonus can be applied is if the answer is accepted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T17:12:42.527",
"Id": "474086",
"Score": "0",
"body": "If you were to cache the last retrieved entry, and compare first with the cache, wouldn't that speed up quite a bit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T18:33:14.127",
"Id": "474096",
"Score": "0",
"body": "@konijn: that will help if it is very likely that you are looking up the last retrieved entry. If not, it will waste a comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T20:19:24.270",
"Id": "474583",
"Score": "0",
"body": "Do you want to accept any of the answers? The bounty runs out tomorrow."
}
] |
[
{
"body": "<h1>Code review</h1>\n\n<p>I am just going to review <code>table_get_value_directly()</code> for efficiency. However, the findings might or might not be relevant for the performance figures you are getting, since it depends a lot on how the program is compiled (optimization level, whether LTO is used or not), and what data is is actually hashing.</p>\n\n<pre><code>bool table_get_value_directly(Table* table, Value key, Value* out) {\n</code></pre>\n\n<p>Already at the start there is room for improvement: you can make <code>table</code> <code>const</code>, since this function should not change the contents of the hash tabel. Furthermore, <code>key</code> is copied by value here, it is likely to be more efficient to pass it as a <code>const</code> pointer.</p>\n\n<pre><code> if (table->capacity == 0) {\n return false;\n }\n</code></pre>\n\n<p>The first thing you are doing is checking whether the capacity is zero. However, if you would ensure that a valid <code>Table</code> always has a non-zero capacity, you can omit this check.</p>\n\n<pre><code> unsigned long hash;\n if (!value_hash(&key, &hash)) {\n FAIL(\"Couldn't hash\");\n }\n</code></pre>\n\n<p>Here is error checking for the case that someone provides a <code>Value</code> that cannot be hashed. It would be better if there was no possibility for an error here. Either make sure all possible <code>Value</code>s have a valid hash value, or just return a special value for hash errors. This will cause a lookup in the rest of the code, but then it will discard the result because <code>keys_equal()</code> will return false. Since it is hopefully very unlikely that you call <code>table_get_value_directly()</code> with an unhashable <code>Value</code>, this extra check will not hurt the average performance.</p>\n\n<pre><code> int slot = hash % table->capacity;\n</code></pre>\n\n<p>The modulo operation does an integer division, which can be very slow (it is typically tens of CPU cycles, but the exact speed depends on your CPU model). If you ensure that the table capacity is always a power of two, you could instead do a bitwise AND instead, which is very fast, like so:</p>\n\n<pre><code> int slot = hash & (table->capacity - 1);\n</code></pre>\n\n<p>If you ensure you store capacity as the actual number minus 1, you can omit the -1 here.</p>\n\n<pre><code> Node* root_node = table->entries[slot];\n Node* node = root_node;\n\n while (node != NULL) {\n if (keys_equal(node->key, key)) {\n *out = node->value;\n return true;\n }\n</code></pre>\n\n<p>This bit is making a lot of copies. First, <code>keys_equal()</code> makes copies of the two <code>Value</code>s. The compiler could optimize that away since it is a static function, however it in turn calls <code>value_compare()</code> which also takes the parameter by value, so copies still have to be made.</p>\n\n<p>Furthermore, once the right node is found, this is making a copy of <code>node->value</code>. It will likely be more efficient to just return a const pointer to <code>node->value</code>.</p>\n\n<p>All this of course depends on how big a <code>Value</code> is, but since it is a large <code>union</code> that includes some non-trivial types, I think it is better to use pointers.</p>\n\n<pre><code> node = node->next;\n }\n\n return false;\n}\n</code></pre>\n\n<p>One issue with your use of a linked list per hash bucket is that, if you were to have many items in each bucket, the above code would have to do pointer lookups for each node in the list. That would be slower than using linear probing. However, your statistics suggest that you only have one entry in there, so this won't matter in this case.</p>\n\n<h1>Analysis of the assembler output</h1>\n\n<p>I compiled your <code>table_get_value_directly()</code>, as well as an version that I optimized according to what I wrote above, and looked at the <a href=\"https://godbolt.org/e#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qgA%2BhOSkAzpnbICeOpUy10AYVSsArgFtaXAGylV6ADJ5amAHJ6ARpmJcADAHZSAB1TTCS2pp19I09vXzoLK1tdBydONxk5TAU/BgJmYgIAvQNOY1l5RTpU9IIIm3tHF3dpNIysoNyZWtLLcujKuNcAShlUbWJkDgByAFIAJgBmS2QdLABqEYn1Gvx6ADoERewR5wBBcanaGe15xeWCdDtULQ2tnf3J6dnMBaWV1jw7W4ntvYOnk4vM7aWh4FbfX4PQ7HU5vC5KCH3e4EACeHkwWCocxqxG0CgWrgAQvc5qS5mhaDVyQh0gAqOa0Zi6TCLYl7MnYvAAL0wYgInJ5rKRrgAInNdqxWKgWIVaEK/ntUejMdiCLj8SMiSSyRSqcgacR6ehmGl5bsOZZ%2BexRARNhM2eaySCfMArOg5lLRHMadI7Q7NWKAErMADuqWIlmAZuRaIxmCxqj0BIdHIAarszABVbBiayZgCyhOwgdI2tJ6azOcJAHlq2ZsLtrKX2WSK9ncwBJMzNx3ljPtwO7ADqYgYABVAx3rABxHtp/s59QACUz1gA0nPWwuxNXCQApbDqMebvuVsQZszV9S7Mcd6tNuYAekfcw79EcjNYZbmbZzuxFIqBtgDAME%2BL5vgQH5sMKYqpmw2iYGOsbRoqsYqjieL8nBOhAlqLblvBiGxnMSosva34gn4ybfhy6B9HY7AMhUxBmhyHJXFocwcewIisWxpLBmGaqRnMxChmIOKRnx/EYfi1Z2HwSQEPSqAKUp0lsRKUoylRbDaSafgaRy2iWh4ap8nMzDoOgxCYNI0gaQGlkOeRfyij%2BhEobspHoWqmHUfhHk4XMADWmAohp2EIXMABunmufs7nYPQxAotYmAhl5Pnxqq6r8tYGC4SmZKyflhX0lYAAeBCRYRoXhbVwVxTh0buQVWBZWhOWlQFvZzJa5LMB4zDIIQEUJRa9BcXiYUEGIaAgjVE1ku1mC0vSqjCXZGncf10hiMyugkCiYiWFQYmlf0ZHFaSu1gmIwDEKgIZSfaYFzDQxBzFgdjaMAwBSYFPg8hZtB6GIm0RttCVOWOzAMddSJ7M%2BczYNVUGsB9ILJHQDl7DFqB4O6ABiuxdhAur8vq6RzLSOJdGau3NQhYg%2BggEBRWtsWEaQczOngroYh6dDAPStnSNorAEAzCVM4R82oLow22RzdXMLznNcbzloqdoBAeHrMv%2BnsNQGcgXHXJjYUovtmAAI7aGwqtNZwGt1TFYxdL1k1U4ryu8uLkv8osYoALScDtlvkn76S8hLyCDPZrxiszvJoErscQDFruxWMvPjIY6f%2B2IgdS0b362QQ/S0NHGe2RJeKJ9ICxjIYBdzBTMf16XwcTCKIdzM45duf3Cq7LtaQIw9mBzanYj4LZCisCiEBwwj9KT%2BwbvBdb28Ibr0ve2SeBYhAm%2BYKHWwsMNo2osnA9D0f/GV9XH1sLIjmikjfX84L7qesAb0zBfQaRPh3MAYA55swgAXXeLdDBsy6F7TUN02Kk3JuMMYmhJboFoGAIY/I2aYOHn1AM38fbYilL3MUbMW4AFYSLw3YJfH418RpjQ0qtMW1w5q0EKsnRhCMWHYEhngbadDCTSCoSMOh/dlqki4QyfhA8nqoF4YVLyHIQwIDwIxCAfD5gQIHnmMwZhkF4T6haU%2B1tbYOydgYi%2BWw4HWyQU/fiZJaR9GoUorAwjU5GXcS/YgNc/KI0ChyMhY93E%2BKBH3GJwiqpLVQZE/YgUgk1yoO/MJiVR6pLySjNGkFglsCxkcWUzdbQmksgTIm0cPBiLxrsX%2BbphZeigcAhAYhUBmTwLobkGJO6UiwnVWkqcSFyxwgrOuvJumKD6TydAgyqSa1pOraOQygrRVpHYI2710kVNxC8MB9tHZfjHpTTZLxaTn2nrPeWC8lLLy6T0%2BZAyLlr3YBvJhmBeYXJWS4txzShYAKAb6AR7TfTPLmf0xZLjNHHymlItRAjaHtzPt84RbDb4ojmKHOYnASEcguatWmqj1GwjFOfYRojxGSOkbIjSxL%2BG0gcQIslYgHHwtJNo3RLx9H8KMXEkxZi3FWI7nPIuscoW9JhTA1uDjhHOPCq4lBNFAkz1fgXBVWx/HyLYiktVpJWUD21T8RJn9ckVw1cEuYwrWq5KGD0VgIAhh0KGKQAwQxnDutQC69Q2I%2BgDCBJMTg7qCAuu9Ug0gIUQB0NcGsAAHBMXIzgACcSbW6GAmM4POzqhjcHdZ671pBfVDHddIEAzhSDhq9Y60gcBYBICLrysgFBO5KxbSgYAqaJikCoLoopFaIB2Aje6uwlh0gohdaG0g6dmT0GrLQZeo7SBYF0CIYA7AV0POSDFOyK7MCVSSHrYYxbLRyBXR8OwYlUqaCwNOsNEZdAPp6DQegTA2AcB4PwQQwhRAgAkPNIQnwK2QB6LMvwFahih2rGMctiQcYGAgKYeoOQTBqDKFEGIggvA%2BFlKhnDoRZSYeYoIfISkUjNAI67cjiHigZBI%2B0WITQSjUZYwx1oWGOg9GkIGwYXAnUurdR6ldpbKoJsMKHQw3A5jAATnMVNawJgd1wIQEgLdk2800B29gX0DgErmOoMNo6o0xu4GMNYuQk2pucLkVwEwJiGHTUIF1BbSDPriFWotPqXXlsrdWkzgmhhwZE7WktvmAu1qjXu4gPhlDcCAA%3D\" rel=\"nofollow noreferrer\">generated assembly</a>.</p>\n\n<p>Looking at raw instruction counts, your version has 75 instructions, while the optimized version only uses 34 instructions. But looking more closely, your version results in a <code>div</code> instruction for the modulo (which is quite slow), but it also spends 17 <code>mov</code> and 8 <code>push</code> instructions on the inlined call to <code>keys_equal()</code>, which are there to prepare the arguments of the call to <code>value_compare()</code>. For the line <code>*out = node->value</code>, it seems GCC manages to combine a lot of moves into a few SSE instructions.</p>\n\n<p>The optimized version, which uses (<code>const</code>) pointers to <code>Value</code>s where possible, uses much less <code>mov</code> and <code>push</code> instructions, and has no <code>div</code>. So that means less instructions to execute, less memory bandwidth used, and less CPU cycles to spend.</p>\n\n<h1>Reason for the large self-time</h1>\n\n<p>Proper hash tables are O(1), however that doesn't mean that a lookup will be fast, only that it will not get slower the more entries you have in a hash table. There still is an overhead for doing a hash table lookup. And if the keys you are looking up are very small, then that overhead will be large compared to a call to <code>value_compare()</code>, and thus a relatively large time will be spent in the hash table lookup logic itself.</p>\n\n<h1>About performance measurements</h1>\n\n<p>Measuring performance is always a bit tricky, since it often is the case that the mere act of instrumenting your code to measure its performance changes the performance.</p>\n\n<p>If you can run your code on Linux, then instead of using <code>gprof</code>, I would consider using <a href=\"https://perf.wiki.kernel.org/index.php/Main_Page\" rel=\"nofollow noreferrer\">Linux <code>perf</code></a>. It does not need the binary to be instrumented, just ensure it is compiled with debugging symbols. It uses statistical profiling, where it interrupts the program at random times to check at which instruction it is. Use the <code>perf record -g</code> command to capture call graphs, so you can get similar information as with <code>gperf</code>. However, <code>perf record</code> will also capture exact locations within the binary, so you can also use it to zoom in on a function, and see the assembly code annotated with how often each instruction is hit, which can give you hints to which lines of code are the largest contributors to the performance.</p>\n\n<p>For Windows, there are <a href=\"https://stackoverflow.com/questions/34641644/is-there-a-windows-equivalent-of-the-linux-command-perf-stat\">alternatives</a> such as Intel VTune and Visual Studio Profiler that might be able to give similar insights.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T12:55:43.897",
"Id": "241552",
"ParentId": "241321",
"Score": "4"
}
},
{
"body": "<p><strong>Suspect: Weak hash</strong></p>\n<p><code>GROW_CAPACITY()</code> only makes for powers of 2 in <code>table->capacity</code> ...</p>\n<pre><code>#define GROW_CAPACITY(capacity) (capacity) < 8 ? 8 : (capacity) * 2 \n...\nvalue_hash(&key, &hash)\nint slot = hash % table->capacity;\n</code></pre>\n<p>... so all that work to make a good hash results in only using the last few bits from <code>value_hash()</code> as code is modding by a power-of-2. The entire quality of the hash is thus dependent of its least significant bits.</p>\n<p>If <code>value_hash()</code> is a <em>real good hash</em>, then using any bits is OK. Yet if <code>value_hash()</code> has weaknesses, (say it favors forming even <code>hash</code> values or not uniformly distributed for the keys given to it in its least significant bits), then the later code will call <code>keys_equal()</code> more often than with a good hash due to increased collisions, potentially reducing performance to that of a linked-list. This is a source of inefficiency.</p>\n<pre><code>while (node != NULL) {\n if (keys_equal(node->key, key)) { \n</code></pre>\n<hr />\n<p>To help along weak hash functions, simply use a prime capacity, rather than doubling at each step.</p>\n<p>Then <code>slot</code> will depend on all bits of <code>hash</code>.</p>\n<p>I recommend using a table of primes just lower than powers of 4 for the capacity.</p>\n<pre><code>size_t prime2[capacity_index] = { 3, 13, 61, 251, ... }\n</code></pre>\n<blockquote>\n<p>Conclusion: Performing <code>% table->capacity</code> with a prime will not harm a good hash function, yet will improve weaker ones and reduce collisions.</p>\n</blockquote>\n<p>[Edit] Hmmm. OP has "though only ever iterating through one entry" so this may not be the case. OP does have "never does more than one iteration" yet that <em>never</em> seems suspicious as that is too perfect.</p>\n<hr />\n<p><strong>Use function pointers</strong></p>\n<p>For a linear improvement, use a pointer to various hash functions rather than one hash function with a <code>switch()</code>.</p>\n<pre><code>typedef bool (*)(Value* value, unsigned long* result) func_t;\n\nbool value_hash(Value* value, unsigned long* result) {\n // switch (value->type) {\n // ...\n \n func_t hash_func[VALUE_ADDRESS + 1] = {value_hash_NUMBER, value_hash_BOOLEAN, ... };\n return hash_func[value->type](value, result);\n}\n</code></pre>\n<p>Same for <code>value_compare()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T02:46:12.130",
"Id": "474880",
"Score": "0",
"body": "@Aviv Cohn I hope the ideas resulted in noticeable performance improvements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T12:55:36.683",
"Id": "241612",
"ParentId": "241321",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T22:13:02.930",
"Id": "241321",
"Score": "7",
"Tags": [
"performance",
"c"
],
"Title": "Hash table lookup is very slow - though only ever iterating through one entry"
}
|
241321
|
<p>While using a <code>JOptionPane</code>, recently, it struck me as odd that the Java Library doesn't seem to have any standard icons for the dialogs. So I decided to create an enum for them. Instead of mapping the icons directly to the enum, I used a map.</p>
<pre><code>import javax.swing.*;
import java.util.Map;
public enum MessageIcons {
PLAIN(-1),
ERROR(0),
INFORMATION(1),
WARNiNG(2),
QUESTION(3);
private Icon value;
private final Map<Integer, Icon> icons = Map.of(
-1,new ImageIcon("Plain.png"),
0,new ImageIcon("Error.png"),
1,new ImageIcon("Information.png"),
2,new ImageIcon("Warning.png"),
3,new ImageIcon("Question.png")
);
MessageIcons(int value){
this.value = icons.get(value);
}
public Icon getIcon(){
return value;
}
}
</code></pre>
<p>Images:
<a href="https://i.stack.imgur.com/jyRlu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jyRlu.png" alt="Plain.png"></a> <a href="https://i.stack.imgur.com/SVSA4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SVSA4.png" alt="Error.png"></a> <a href="https://i.stack.imgur.com/N4pDT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N4pDT.png" alt="Information.png"></a> <a href="https://i.stack.imgur.com/rKQa1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rKQa1.png" alt="Warning.png"></a> <a href="https://i.stack.imgur.com/pbXqy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pbXqy.png" alt="Question.png"></a></p>
<p>I've mapped these to the same values as those in the <code>JOptionsPane</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T13:14:23.583",
"Id": "473618",
"Score": "3",
"body": "Please do not update the code in the question to invalidate answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:07:33.633",
"Id": "473752",
"Score": "0",
"body": "Not wrong, but it might be a good idea to have some kind of configuration instead so designers can quickly test different icons without having to rename / change the source. Depends a bit on the project of course; for a one-off tool this would not be necessary."
}
] |
[
{
"body": "<p>In my opinion, binding the file to the enum is a better choice. This will make the code shorter and give the same performance. Also, the <code>MessageIcons#WARNiNG</code> have a lowercase in the name (<code>MessageIcons#WARNiNG</code> -> <code>MessageIcons#WARNING</code>).</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public enum MessageIcons {\n PLAIN(\"Plain.png\"),\n ERROR(\"Error.png\"),\n INFORMATION(\"Information.png\"),\n WARNING(\"Warning.png\"),\n QUESTION(\"Question.png\");\n private final Icon icon;\n\n MessageIcons(String fileName) {\n icon = new ImageIcon(fileName);\n }\n\n public Icon getIcon() {\n return icon;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T21:15:45.457",
"Id": "473701",
"Score": "1",
"body": "What is the use of `code`? It is final and private and not used? Also `value` is not a great name for an `icon` ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T23:31:44.917",
"Id": "473708",
"Score": "0",
"body": "For the `value` variable, I kept the original name, but you're right, it's a bad name. I will rename it to `icon`. For the `code` variable, there's no use in this case :P. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T12:39:10.153",
"Id": "241364",
"ParentId": "241327",
"Score": "6"
}
},
{
"body": "<p>For me it is a bit weird to see an enum representing a resource, even if it is in memory. It's not wrong or anything, but currently even the loading takes place during construction of the enum. Furthermore, as mentioned in a comment, I can see where another icon needs to be tested / substituted. In that case it might make sense to update the file name for a specific configuration.</p>\n\n<p>That aside, I would do more of a code review rather than giving a good solution, because that's been taken care of.</p>\n\n<p>First of all, I'd put empty lines around the <code>value</code> field declaration and in between the methods and constructors. That would improve readability by a lot.</p>\n\n<hr>\n\n<pre><code>public enum MessageIcons {\n</code></pre>\n\n<p>I would not use plural <code>MessageIcons</code> but just <code>MessageIcon</code>. That way you get <code>MessageIcon.PLAIN</code> which reads better than <code>MessageIcons.PLAIN</code>. I hope you agree, because this is how it is used everywhere that I've seen.</p>\n\n<pre><code>PLAIN(-1),\n</code></pre>\n\n<p>Maybe it's a leftover from before, but it seem strange that you start counting with <code>-1</code>. Generally we don't number enums at all; it is just not required. And otherwise you can simply call the <code>ordinal()</code> method on the enum value. But before you do, read up on the documentation of it (!).</p>\n\n<pre><code>private final Map<Integer, Icon> icons = Map.of(...);\n</code></pre>\n\n<p>If you would create a map for enums then there is absolutely no need to use an <code>Integer</code>. It is much more simple to directly use enum values themselves, giving you a <code>Map<MessageIcons, Icon></code>.</p>\n\n<p>Remember that each enum is really a singleton. What you are doing here is to create 5 separate maps, one for <code>PLAIN</code>, one for <code>ERROR</code>, etc.! If you create a map (which is one option to create a two way table for a value -> enum on top of enum -> value) then it should be <code>static</code>.</p>\n\n<pre><code>-1,new ImageIcon(\"Plain.png\"),\n</code></pre>\n\n<p>There should be a space after the comma. That's common code style as well.</p>\n\n<pre><code>MessageIcons(int value){\n</code></pre>\n\n<p>Generally the constructor of an enum is only used for the enumerated enum values. So generally you should make it <code>private</code>. This and the next method <code>getIcon</code> also do not have a space between the closing parenthesis and the brace. That's almost universal for Java and other C-like languages.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T17:43:58.843",
"Id": "241446",
"ParentId": "241327",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T23:27:15.960",
"Id": "241327",
"Score": "5",
"Tags": [
"java"
],
"Title": "Message Icon enum"
}
|
241327
|
<p>I've implemented a singly linked list in Java and would like a code review as I am still learning
and this is a different method I've found to do this. The logic is still fuzzy as well to me and
writing it out took ages and I'm sure I may have messed up a bit but still have time to mess
around with this.</p>
<p>Instructions</p>
<ul>
<li>private data members in list class </li>
<li>public methods must correspond to operations in data structure</li>
<li>data members include the head, there will be a get size method
and elementcounter for the number of elements in the linked list.</li>
<li>only the link class can be referenced. </li>
<li>find method must generate a new list of integers to refer
to all positions where given item was found </li>
<li>no user input output</li>
<li>Inside the find and deleteItem methods, use the 'equals' method of the data
entries to compare values.</li>
<li><p>Inside the toString method, use the toString methods of the data entries (implicitly) to
display the
properties of each entry. </p>
<pre><code>public class List {
private Link head;
private Link tail;
private int elementCount;
public List() {
head = null;
tail = head;
elementCount = 0;
}
public void insert(int position, Object data) {
if (position < 1 || position > elementCount + 1) {
System.out.println("Sorry could not insert due to position problems"
+ "Position can't be less than 1, or position is "
+ "greater than element exists");
return;
}
// insert head
if (isEmpty() && position == 1) {
head = tail = new Link(data, null);
elementCount++;
return;
}
if (!isEmpty() && position == 1) {
Link temp = head;
head = new Link(data, temp);
elementCount++;
return;
}
// insert middle
if (position <= elementCount) {
int i = 1;
Link current = head;
Link previous = null;
while (i != position) {
previous = current;
current = current.next;
i++;
}
previous.next = new Link(data, current);
elementCount++;
return;
}
// insert at end
insertAtEnd(data);
}
public void insertAtEnd(Object data) {
tail.next = new Link(data, null);
tail = tail.next;
elementCount++;
}
//
public List find(Object toFind) {
if (isEmpty()) {
System.out.println("This List is empty");
return null;
}
List listOfpositions = new List();
Link current = head;
int position = 1;
while (current != null) {
if (isEmpty(listOfpositions)) {
if (current.data.equals(toFind)) {
listOfpositions.insert(1, position);
}
} else {
if (current.data.equals(toFind)) {
listOfpositions.insertAtEnd(position);
}
}
position++;
current = current.next;
}
return listOfpositions;
}
public void deleteRange(int start, int end) {
if (isEmpty()) {
System.out.println("The list is empty");
return;
}
if (start > end) {
System.out.println("Your range is inverted");
return;
}
if (start == end) {
deleteAtIndex(start);
System.out.println("Operation Complete...");
return;
}
int deleteCount = end - start + 1;
for (int i = 0; i < deleteCount; i++) {
deleteAtIndex(start);
}
System.out.println("Operation Complete...");
}
public Object getSize() {
return elementCount;
}
public void deleteItem(Object item) {
if (isEmpty()) {
System.out.println("This List is empty");
return;
}
Link current = head;
int index = 1;
while (current != null) {
if (current.data.equals(item)) {
deleteAtIndex(index);
index--;
}
current = current.next;
index++;
}
System.out.println("Operation Complete...");
}
public Link retrieve(int index) {
if (isEmpty()) {
System.out.println("List is empty");
return null;
}
if (index > elementCount || index < 1) {
System.out.println("Out of bound");
return null;
}
if (index == 1) {
return head;
}
if (index == elementCount) {
return tail;
}
Link current = head;
int i = 1;
while (current != null && i != index) {
current = current.next;
i++;
}
return current;
}
@Override
public String toString() {
String linkedList = "This is your list" +
"\n[";
Link node = head;
while (node != null) {
linkedList += (node);
linkedList += ",";
node = node.next;
}
int lastComma = linkedList.lastIndexOf(",");
if (lastComma != -1) {
linkedList = linkedList.substring(0, linkedList.length() - 1);
}
linkedList += ']';
return linkedList;
}
private void deleteAtIndex(int index) {
if (isEmpty()) {
return;
}
if (index < 1) {
return;
}
if (index > elementCount) {
return;
}
if (index == 1) {
head = head.next;
elementCount--;
return;
}
if (index == elementCount) {
Link currentLink = head;
while (currentLink.next != tail) {
currentLink = currentLink.next;
}
tail = currentLink;
currentLink.next = null;
elementCount--;
return;
}
int i = 1;
Link current = head;
Link previous = null;
while (i != index) {
previous = current;
current = current.next;
i++;
}
previous.next = current.next;
elementCount--;
}
private boolean isEmpty(List listOfpositions) {
return listOfpositions.head == null;
}
private boolean isEmpty() {
return head == null;
}
}
</code></pre></li>
</ul>
<hr>
<p>link class</p>
<pre><code> public class Link {
public Object data;
public Link next;
/*
* OR USE THIS CODE
* public Object data;
* public Node next;
*
* public Node (Object _data) {
* data = _data
* next = null
* }
*/
// have each link include a reference to an object
public Link(Object _data, Link node) {
data = _data;
next = node;
}
@Override
public String toString() {
return "Links data:" + data;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T07:43:32.840",
"Id": "473582",
"Score": "1",
"body": "`this is a different method I've found` Please clarify, in your question, whether you yourself coded an algorithm you found vs. present code you found. See [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T07:45:00.563",
"Id": "473583",
"Score": "1",
"body": "`empty list represented as null` will exclude Java instance methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:26:59.140",
"Id": "473687",
"Score": "0",
"body": "Coded it myself, and I messed it up totally. I am working on revising it now as I got feed back from my professor on the same issue you brought up, as well as, it being a doubly (the use of previous should have tipped me off). My logic wasn't just fuzzy, it was totally off, I'm stripping most of it to change and now working on the deleteatindex or scrapping it all together as the assignment is easier than previously thought. Thanks for your help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:51:12.670",
"Id": "473692",
"Score": "2",
"body": "A data type does not become doubly linked due to the naming of some external reference into its innards. In the current state (lack of indentation and [doc comments](https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#styleguide), I for one am not willing to try and read the code presented. Do you agree with vnp's presentation of the instructions? Where do these come from? Please give an/your interpretation of `only the link class can be referenced`."
}
] |
[
{
"body": "<p>The code as presented is poorly formatted, which makes it difficult to read. If this is how it is in your editor, then you should consider reformatting it to a standard indentation. Most IDEs / code editors can do this automatically for you.</p>\n<pre><code>public class List {\n</code></pre>\n<p>The list you've implemented is a linked list. This impacts on how it performs. Consider giving it a name that reflects this. The standard library defines a <code>List<T></code> interface, which is then implemented by concrete implementations (such as LinkedList). This gives a common interface that can be used for working with lists, but allows different concrete selections to be made if particular performance charactersistics are required.</p>\n<pre><code> private Link head;\n private Link tail;\n private int elementCount;\n\n public List() {\n\n head = null;\n tail = head;\n</code></pre>\n<p>Consider <code>tail = null</code>, it's more explicit.</p>\n<pre><code> elementCount = 0;\n }\n\n public void insert(int position, Object data) {\n</code></pre>\n<p>The levels of abstraction in this method are mixed. Some clauses directly change the list, whereas others delegate to member functions. Consider consolidating these levels of abstraction. On approach might be:</p>\n<ul>\n<li><p>If Invalid position, handle</p>\n</li>\n<li><p>If Position == Start, call insertHead</p>\n</li>\n<li><p>If Position == End, call insertEnd</p>\n</li>\n<li><p>Otherwise, call insertMiddle</p>\n<pre><code> if (position < 1 || position > elementCount + 1) {\n System.out.println("Sorry could not insert due to position problems"\n + "Position can't be less than 1, or position is "\n + "greater than element exists");\n</code></pre>\n</li>\n</ul>\n<p>Whilst you may be writing this list with user interaction in mind, it's generally better to separate the user interaction from the actual logic of the list. If this list was being used from a different program, you might not want it outputting directly to the console like this.</p>\n<pre><code> return;\n</code></pre>\n<p>Whilst you've indicated to the console that the insert has failed, the caller has no way to know that the insertion has failed.</p>\n<pre><code> }\n// insert head\n if (isEmpty() && position == 1) {\n head = tail = new Link(data, null);\n elementCount++;\n return;\n }\n if (!isEmpty() && position == 1) {\n Link temp = head;\n head = new Link(data, temp);\n</code></pre>\n<p>Consider, if the list was empty, what temp would be if this code was executed, rather than the clause above. Really, the only difference between your processing for an empty list and a list with items is that the empty list also assigns the tail to head...</p>\n<pre><code> elementCount++;\n return;\n }\n// insert middle\n if (position <= elementCount) {\n int i = 1;\n Link current = head;\n Link previous = null;\n while (i != position) {\n previous = current;\n current = current.next;\n i++;\n }\n previous.next = new Link(data, current);\n elementCount++;\n return;\n }\n// insert at end\n</code></pre>\n<p>Comments should add meaning to the code, otherwise they just add noise. Would the code be any harder to understand without the comment above?</p>\n<pre><code> insertAtEnd(data);\n }\n\n public void insertAtEnd(Object data) {\n</code></pre>\n<p>This method is called from <code>insert</code> and it appears to be written with that in mind. However, it's declared as a <code>public</code> method. Consider what would happen if it was called on an empty list.</p>\n<pre><code> tail.next = new Link(data, null);\n tail = tail.next;\n elementCount++;\n }\n\n //\n</code></pre>\n<p>Is something important missing from this comment section?</p>\n<pre><code> public List find(Object toFind) {\n if (isEmpty()) {\n System.out.println("This List is empty");\n return null;\n</code></pre>\n<p>Returning <code>null</code> makes it necessary for the caller to handle the <code>null</code>. Consider using <code>Optional<List></code> instead to give the caller a hint that the list might not be returned. Or, consider if a better approach would be to return a list of no items instead. This would allow the caller to iterate over zero to many items, without needing to handle the null case explicitly.</p>\n<pre><code> }\n List listOfpositions = new List();\n Link current = head;\n int position = 1;\n\n while (current != null) {\n if (isEmpty(listOfpositions)) {\n</code></pre>\n<p>If <code>insertAtEnd</code> could be called on an empty list, would you need this branch?</p>\n<pre><code> if (current.data.equals(toFind)) {\n listOfpositions.insert(1, position);\n }\n } else {\n if (current.data.equals(toFind)) {\n listOfpositions.insertAtEnd(position);\n }\n }\n position++;\n current = current.next;\n }\n return listOfpositions;\n }\n\n public void deleteRange(int start, int end) {\n if (isEmpty()) {\n System.out.println("The list is empty");\n</code></pre>\n<p>Again, whilst the console knows nothing has happened the caller doesn't. If these are error conditions, consider if you should be throwing exceptions, rather than just printing and returning.</p>\n<pre><code> return;\n }\n if (start > end) {\n System.out.println("Your range is inverted");\n return;\n }\n if (start == end) {\n deleteAtIndex(start);\n System.out.println("Operation Complete...");\n</code></pre>\n<p>Your other operations like <code>insert</code> don't output this kind of message, does it make sense for this one to?</p>\n<pre><code> return;\n }\n int deleteCount = end - start + 1;\n</code></pre>\n<p>Would this logic still work if <code>start == end</code>?</p>\n<pre><code> for (int i = 0; i < deleteCount; i++) {\n deleteAtIndex(start);\n</code></pre>\n<p>The way deleteAtIndex is implemented, it starts from the head of the list, iterates through to the target item, then removes it. It'll do the same thing for the next item, starting again from the beginning. This is really inefficient. Consider if there's a better way to remove multiple items at once, without having to start from the beginning of the list each time.</p>\n<pre><code> }\n System.out.println("Operation Complete...");\n }\n\n public Object getSize() {\n</code></pre>\n<p>Size seems like it's a number, should this really be returning an <code>Object</code>?</p>\n<pre><code> return elementCount;\n }\n\n public void deleteItem(Object item) {\n if (isEmpty()) {\n System.out.println("This List is empty");\n return;\n }\n Link current = head;\n int index = 1;\n while (current != null) {\n if (current.data.equals(item)) {\n deleteAtIndex(index);\n index--;\n }\n current = current.next;\n index++;\n }\n System.out.println("Operation Complete...");\n }\n\n public Link retrieve(int index) {\n</code></pre>\n<p>Do you want the caller to be able to iterate through the Links themselves? If not, consider returning the <code>Object</code> contained in the list, rather than the <code>Link</code> itself.</p>\n<pre><code> if (isEmpty()) {\n System.out.println("List is empty");\n return null;\n }\n if (index > elementCount || index < 1) {\n System.out.println("Out of bound");\n return null;\n }\n if (index == 1) {\n return head;\n }\n if (index == elementCount) {\n return tail;\n }\n Link current = head;\n int i = 1;\n while (current != null && i != index) {\n current = current.next;\n i++;\n }\n return current;\n }\n\n @Override\n public String toString() {\n String linkedList = "This is your list" +\n "\\n[";\n Link node = head;\n while (node != null) {\n linkedList += (node);\n linkedList += ",";\n node = node.next;\n }\n int lastComma = linkedList.lastIndexOf(",");\n if (lastComma != -1) {\n linkedList = linkedList.substring(0, linkedList.length() - 1);\n }\n linkedList += ']';\n\n\n return linkedList;\n }\n\n\n private void deleteAtIndex(int index) {\n</code></pre>\n<p>This is a private method. You do a lot of checks in your public methods to make sure that you are operating on valid list elements. Do you still need all of these checks here?</p>\n<pre><code> if (isEmpty()) {\n return;\n }\n if (index < 1) {\n return;\n }\n if (index > elementCount) {\n return;\n }\n if (index == 1) {\n head = head.next;\n elementCount--;\n return;\n }\n if (index == elementCount) {\n Link currentLink = head;\n while (currentLink.next != tail) {\n currentLink = currentLink.next;\n }\n tail = currentLink;\n currentLink.next = null;\n elementCount--;\n return;\n }\n int i = 1;\n Link current = head;\n Link previous = null;\n while (i != index) {\n previous = current;\n current = current.next;\n i++;\n }\n previous.next = current.next;\n elementCount--;\n }\n\n private boolean isEmpty(List listOfpositions) {\n</code></pre>\n<p>It's unclear why this method exists. Why wouldn't the client call <code>listOfpositions.isEmpty()</code> ? If you do want it, consider making it a <code>static</code> method.</p>\n<pre><code> return listOfpositions.head == null;\n }\n\n private boolean isEmpty() {\n return head == null;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T09:02:44.603",
"Id": "244773",
"ParentId": "241328",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T23:45:50.303",
"Id": "241328",
"Score": "1",
"Tags": [
"java",
"eclipse"
],
"Title": "Implementing a singly linked list with empty list represented as null"
}
|
241328
|
<p>I have a <code>headers</code> dictionary value being passed to one of my constructors and based on that dictionary value I am extracting individual headers I need and setting all my variables.</p>
<pre><code>public Tester(IDictionary<string, StringValues> headers)
{
int textId = 0;
if (headers == null)
{
ProcId = GenerateProcId();
DbId = GenerateDbId();
ThetaId = GenerateThetaId();
return;
}
ProcIdHeader = GetHeaderValue(headers, PROC_HEADER);
if (string.IsNullOrWhiteSpace(ProcIdHeader))
{
ProcId = GenerateProcId();
}
else
{
ProcId = ProcIdHeader;
}
DbIdHeader = GetHeaderValue(headers, DB_HEADER);
if (string.IsNullOrWhiteSpace(DbIdHeader))
{
DbId = GenerateDbId();
}
else
{
DbId = DbIdHeader;
}
ThetaId = GenerateThetaId();
var textIdStr = GetHeaderValue(headers, TEXT_HEADER);
int.TryParse(textIdStr, out textId);
TextIdValue = textId;
TextId = textId;
AlphaHeader = GetHeaderValue(headers, ALPHA_HEADER);
if (!string.IsNullOrWhiteSpace(AlphaHeader))
{
AlphaContent = AlphaHeader;
}
TimeoutIdHeader = GetHeaderValue(headers, TIMEOUT_HEADER);
if (!string.IsNullOrWhiteSpace(TimeoutIdHeader))
{
TimeoutId = TimeoutIdHeader;
}
FilterHeader = GetHeaderValue(headers, FILTER_HEADER);
if (!string.IsNullOrWhiteSpace(FilterHeader))
{
FilterId = FilterHeader;
}
PreviewHeader = GetHeaderValue(headers, PREVIEW_HEADER);
if (!string.IsNullOrWhiteSpace(PreviewHeader))
{
PreviewId = PreviewHeader;
}
AntHeader = GetHeaderValue(headers, ANT_HEADER);
if (!string.IsNullOrWhiteSpace(AntHeader))
{
AntId = AntHeader;
}
LocalHeader = GetHeaderValue(headers, LOCAL_HEADER);
AppHeader = GetHeaderValue(headers, APP_HEADER);
if (!string.IsNullOrWhiteSpace(AppHeader))
{
AppId = AppHeader;
}
ContextHeader = GetHeaderValue(headers, CONTEXT_HEADER);
if (ContextHeader != null)
{
try
{
ContextStr = JsonSerializer.Deserialize<ContextStr>(ContextHeader);
}
catch (Exception e)
{
ContextStr = new ContextStr();
}
}
if (LocalHeader != null)
{
try
{
LocalStr = JsonSerializer.Deserialize<LocalStr>(LocalHeader);
}
catch (Exception e)
{
LocalStr = new LocalStr();
}
}
PageHeader = GetHeaderValue(headers, PAGE_HEADER);
if (!string.IsNullOrWhiteSpace(PageHeader))
{
PageStr = PageHeader;
}
ChannelId = GetHeaderValue(headers, CHANNEL_HEADER);
}
private string GetHeaderValue(IDictionary<string, StringValues> headers, string headerKey)
{
headers.TryGetValue(headerKey, out var headerValues);
if (headerValues.Count > 0) return headerValues[0];
return null;
}
</code></pre>
<p>I wanted to see if there is any better way to rewrite the constructor logic that I have. As of now it looks very bulky with bunch of if/else block. Anything that can be improve in my code?</p>
<p><strong>Note:</strong> It's a legacy code base system so changing whole design might be difficult but little refactoring by splitting it into various methods is possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T01:53:04.857",
"Id": "473555",
"Score": "0",
"body": "use `Factory` design pattern, and work with each header individually, make strong-typed headers. Then, group your work under one class that would initiate them all (or prepare them for use)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T01:55:35.813",
"Id": "473556",
"Score": "0",
"body": "yeha Factory pattern might work for me but I was thinking instead of that can we simplify if/else block by making some sort of method that can do all the work and we will just pass headers or header values to it? Something like that. Since it's a legacy code base so don't want to touch multiple things by using factor pattern here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:04:29.283",
"Id": "473557",
"Score": "0",
"body": "`Since it's a legacy code base so don't want to touch multiple things by using factor pattern here` you should mention that in your post, so others will know what are you dealing with, and what is your expectation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:14:46.737",
"Id": "473558",
"Score": "0",
"body": "@iSR5 just edited my question. thanks for pointing it out."
}
] |
[
{
"body": "<p>You can simplify that portion of code. First, you'll need to create an array that will holds the header keys such as <code>PROC_HEADER</code> ..etc. then you can go from there. </p>\n\n<p>Here is an example (NOTE, keys are just placeholders in this example, so you know which const needs to be replaced). </p>\n\n<pre><code>public Tester(IDictionary<string, StringValues> headers)\n {\n // these will be overwritten if their customer global are not null. \n DbId = GenerateDbId();\n ProcId = GenerateProcId();\n ThetaId = GenerateThetaId();\n\n if (headers == null) { return; }\n\n var headerKeys = new[]{\n \"PROC_HEADER\",\n \"DB_HEADER\",\n \"TEXT_HEADER\",\n \"ALPHA_HEADER\",\n \"TIMEOUT_HEADER\",\n \"FILTER_HEADER\",\n \"PREVIEW_HEADER\",\n \"ANT_HEADER\",\n \"APP_HEADER\",\n \"PAGE_HEADER\",\n \"LOCAL_HEADER\",\n \"CONTEXT_HEADER\", \n \"CHANNEL_HEADER\"\n };\n\n foreach(var key in headerKeys)\n {\n headers.TryGetValue(key, out var headerValue);\n\n if (headerValue.Count > 0)\n { \n switch(key)\n {\n case \"PROC_HEADER\":\n SetHeaderValue(headerValue[0], \"ProcIdHeader\", \"ProcId\");\n break;\n case \"DB_HEADER\":\n SetHeaderValue(headerValue[0], \"DbIdHeader\", \"DbId\"); \n break; \n case \"TEXT_HEADER\":\n int.TryParse(headerValue[0], var textId);\n TextIdValue = textId;\n TextId = textId; \n break; \n case \"ALPHA_HEADER\":\n SetHeaderValue(headerValue[0], \"AlphaHeader\", \"AlphaContent\");\n break;\n case \"TIMEOUT_HEADER\":\n SetHeaderValue(headerValue[0], \"TimeIdHeader\", \"TimeId\"); \n break; \n case \"FILTER_HEADER\":\n SetHeaderValue(headerValue[0], \"FilterHeader\", \"FilterId\"); \n break; \n case \"PREVIEW_HEADER\":\n SetHeaderValue(headerValue[0], \"PreviewHeader\", \"PreviewId\"); \n break; \n case \"ANT_HEADER\":\n SetHeaderValue(headerValue[0], \"AntHeader\", \"AntId\"); \n break; \n case \"APP_HEADER\":\n SetHeaderValue(headerValue[0], \"AppHeader\", \"AppId\"); \n break; \n case \"PAGE_HEADER\":\n SetHeaderValue(headerValue[0], \"PageHeader\", \"PageStr\"); \n break; \n case \"CHANNEL_HEADER\":\n ChannelId = headerValue[0]; \n break; \n case \"LOCAL_HEADER\":\n LocalHeader = headerValue[0];\n LocalStr = DeserializeHeader<LocalStr>(LocalHeader);\n break; \n case \"CONTEXT_HEADER\":\n ContextHeader = headerValue[0];\n ContextStr = DeserializeHeader<ContextStr>(ContextHeader);\n break; \n } \n } \n }\n}\n\nprivate T DeserializeHeader<T>(string str) where T : new()\n{\n if(!string.IsNullOrEmpty(str))\n {\n try\n {\n return JsonSerializer.Deserialize<T>(str);\n }\n catch (Exception e)\n {\n return new T();\n }\n }\n\n return default;\n}\n\npublic void SetHeaderValue(string headerValue, string customerPropertyName, string serverPropertyName)\n{\n var custProperty = this.GetType().GetProperty(customerPropertyName); \n\n if(custProperty != null) { custProperty.SetValue(this, headerValue); }\n\n if(!string.IsNullOrWhiteSpace(headerValue))\n { \n var serverProperty = this.GetType().GetProperty(serverPropertyName);\n\n if(serverProperty != null) { serverProperty.SetValue(this, headerValue); } \n } \n\n} \n</code></pre>\n\n<p>I've decided to use <code>switch</code> to group them up, as it would be more readable, and also it has an a performance advantage over if/else blocks as it would be compiled into jump table which would be faster than if/else blocks. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:24:29.720",
"Id": "473640",
"Score": "0",
"body": "thanks for your solution. can you also explain why this is better than my original solution so that I can understand better? I had bunch of if/else block but you have bunch of cases. Just trying to understand advantages of this over original."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:44:10.030",
"Id": "473644",
"Score": "0",
"body": "@dragons sure, I've updated my answer, let me know if you need anything else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T16:36:51.570",
"Id": "473666",
"Score": "0",
"body": "cool. going through your answer now. There is a spell check on this line `if (headerValues.Count > 0)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T16:43:32.993",
"Id": "473667",
"Score": "0",
"body": "@dragons good catch, I've fixed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T17:07:47.137",
"Id": "473669",
"Score": "0",
"body": "I think you are missing one more thing. For some headers - I have two fields for example I have `ProcId` and `ProcIdHeader` for `PROC_HEADER` and I need to use both bcoz they both will be sent to db. In your example you removed one and just using `ProcId`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T17:12:16.053",
"Id": "473670",
"Score": "0",
"body": "@dragons that's what made me confused, both will have mostly the same value, why declaring both as global variables in the first place I didn't know, but since you cleared that out, I will fix it. but this is a really bad design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:35:51.350",
"Id": "473859",
"Score": "0",
"body": "@dragons yes it's true and also it depends on the collection type. You might find some cases a foreach would be faster than a for loop. So, it depends on the collection type optimization, and what your code is optimized for. but in most cases, a for loop is much cheaper than foreach loop. You can do some tests on various of collections using different kind of loops to measure their performance against each collection type to see the difference yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:38:53.063",
"Id": "473860",
"Score": "0",
"body": "@dragons the other hand is readability, in a dictionary for instance, a foreach loop is more readable than using a for loop. you can test the difference, and decide if is it worth the change or not."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T04:04:07.317",
"Id": "241342",
"ParentId": "241331",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241342",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T01:24:31.217",
"Id": "241331",
"Score": "1",
"Tags": [
"c#",
".net"
],
"Title": "Initialize bunch of variables in constructor by extracting value from dictionary"
}
|
241331
|
<p>Is it good practice to give a value to a variable, then change its value immediately after, like that for example? </p>
<pre><code>def get_user_id_from_username(username):
user_id = db.execute("SELECT id FROM user WHERE username = ?", (username, ))
for row in user_id:
user_id = row[0]
return user_id
</code></pre>
<p>Basically, I say that user_id is equal to something that's returned by a SQL query. Then whatever is returned is then passed into user_id. Is that a good thing to do or should I have get_id = sql, and then pass the result into user_id... Or is that completely irrelevant?</p>
<p>By the way, unless I completely missed something, that function always work and the query should never return no row because the username is confirmed to exist with a login function. The idea is that the user logs in and once that's successful, then it does a few things, such as save a timestamp for login history, create a session token, get the user id to search for all the data in the database that use this user_id as a foreign key, etc.</p>
<p>So I really just want you to review that single block of code regardless of its context.</p>
<p>Thank you in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:35:11.337",
"Id": "473559",
"Score": "3",
"body": "Briefly: no, the loop you've shown is very poor practice. But this question is off-topic because it isn't concrete code. In other words, _review that single block of code regardless of its context_ is not something we support."
}
] |
[
{
"body": "<p>Your piece of code is logically incorrect in the following: your select query will return list of already filtered by username IDs - all ID will be the same. So there is no need to iterate over the list of identical IDs and assign each of them to <code>user_id</code>.</p>\n\n<p>The idea to reassign data of different type and origin to the same variable (though this works) is bad since it decreases readability of the code and - worse - confuses your way of thinking when constructing the code.</p>\n\n<p>I'd suggest the following code:</p>\n\n<pre><code>import sqlite3\n\ndef get_user_id_from_usermane(db: sqlite3.Cursor, username: str) -> str:\n user_id_row = db.execute(\"SELECT id FROM user WHERE username = ? LIMIT 1\", (username, ))\n return user_id_row[0]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:09:46.793",
"Id": "241352",
"ParentId": "241333",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241352",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:21:48.940",
"Id": "241333",
"Score": "-4",
"Tags": [
"python"
],
"Title": "Is it good practice to give a value to a variable, then change its value immediately after?"
}
|
241333
|
<p>I'm learning Rust and looking for better/cleaner ways to list all file names that do not start with <code>filter</code>, given a <code>pathname</code> as a parameter.</p>
<pre><code> fn list_files(&self, pathname: &PathBuf, filter: &str) -> Result<Vec<PathBuf>, Error> {
fs::read_dir(pathname).map(|read_dir| {
read_dir
.filter_map(|res| {
res.map(|entry| {
entry
.path()
.strip_prefix(pathname)
.ok()
.map(|path| {
if path.starts_with(filter) {
None
} else {
Some(path.to_path_buf())
}
})
.flatten()
})
.ok()
.flatten()
})
.collect()
})
}
</code></pre>
|
[] |
[
{
"body": "<p>As far as I can tell, you're returning error only in case of <code>read_dir</code> failure. Not sure if anyone ever really needs it, but you could change upmost <code>Some()</code> to <code>Ok()</code>, remove <code>.ok()</code> and fix the signature so that my version works just like yours. Note: the code below wasn't tested. I didn't like nested structure of your function, so I came up with this:</p>\n\n<pre><code>use std::fs;\nuse std::path::PathBuf;\n\nfn list_files(pathname: &PathBuf, filter: &str) -> Option<Vec<PathBuf>> {\n Some(fs::read_dir(pathname).ok()?\n .filter_map(|entry| {\n Some(\n entry\n .ok()?\n .path()\n .strip_prefix(pathname)\n .ok()?\n .to_path_buf(),\n )\n })\n .filter(|path| path.starts_with(filter))\n .collect())\n}\n</code></pre>\n\n<p>Explanation: <code>.ok()</code> maps <code>Result<T, K></code> to <code>Option<T></code>, <code>?</code> operator returns early in case if <code>Option</code> or <code>Result</code> aren't <code>Some()</code>/<code>Ok()</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:39:54.920",
"Id": "473795",
"Score": "0",
"body": "Thanks a lot! This definitely looks better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T22:51:58.893",
"Id": "241404",
"ParentId": "241334",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241404",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:26:26.680",
"Id": "241334",
"Score": "3",
"Tags": [
"file-system",
"rust"
],
"Title": "List and filter files in Rust"
}
|
241334
|
<p>I have this code:</p>
<pre><code> def apply_all (fs, x):
def reducer (acc, f):
(seq, x) = acc
next = f (x)
print((seq + [next], next))
return (seq + [next], next)
return [x] + reduce(reducer, fs, ([], x)) [0]
print(apply_all(f_list,4))
</code></pre>
<p>It works perfectly to accomplish what I need. However, I need to turn this into one line using the map() and reduce() functions, and presumably lambda functions too. Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T03:29:25.607",
"Id": "473565",
"Score": "0",
"body": "@Reinderien My bad! I fixed it now (:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:35:24.263",
"Id": "473591",
"Score": "0",
"body": "May I ask why a one-liner is required? `map`, `reduce` and `lambda` are all code-smells to me, where more verbose and clearer approaches are likely to exist. Those would then take multiple lines to write however. Other than that, your code is hard to understand. Please make it executable (`f_list` is not defined, `reduce` is not imported, an example for `f_list` would be nice)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T11:04:30.727",
"Id": "473604",
"Score": "0",
"body": "Why create a function inside a function?"
}
] |
[
{
"body": "<p>As I could get from your code you're trying to implement a simple sum accumulator function. This should look like:</p>\n\n<pre><code>def apply_all(some_list, initial_value):\n return reduce(lambda x, y: x + y, some_list, initial_value)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T07:30:07.073",
"Id": "241350",
"ParentId": "241337",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T02:45:50.137",
"Id": "241337",
"Score": "-3",
"Tags": [
"python",
"python-3.x",
"functional-programming",
"lambda"
],
"Title": "Printing the steps of a function composition"
}
|
241337
|
<p>(See the <a href="https://codereview.stackexchange.com/questions/241490/data-mining-in-java-finding-undrawn-lottery-rows-follow-up">next iteration</a>.)</p>
<p><strong><em>Introduction</em></strong></p>
<p>Suppose Evil Lottery Inc is interested in not paying millions of dollars back to players. They gather the drawn lottery rows first, after which they mine rows that does not appear in the dataset. </p>
<p>The Evil Lottery Inc's approach is this: it first builds a radix tree of the drawn lottery rows:</p>
<p><a href="https://i.stack.imgur.com/NsD13.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NsD13.png" alt="Radix tree for representing lottery rows data"></a></p>
<p>After the tree is ready, the Evil Algorithm mines for all the lottery rows that do not appear in the data set, and chooses it as the next show result.</p>
<p><strong><em>Output</em></strong></p>
<p>The output for 40M randomly generated lottery rows in Finnish Veikkaus lottery (40 balls, 7 drawn, 40 choose 7 = 18643560) is:</p>
<pre><code>1,2,3
1,2,5
1,3,4
1,4,5
2,3,4
2,3,5
Seed = 1588051533998
Data generated in 49625 milliseconds.
Duration: 115987 milliseconds.
Missing lottery rows: 2181642
</code></pre>
<p><strong><em>Memory note</em></strong>
Please specify in invocation of <code>java ...</code> <code>-XmsNm -XmxNm</code> with large enough <code>N</code>.</p>
<p><strong><em>Code</em></strong></p>
<p><strong><em><code>net.coderodde.datamining.lottery.LotteryConfiguration.java</code></em></strong></p>
<pre><code>package net.coderodde.datamining.lottery;
/**
* This class specifies the lottery game configuration.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Jan 18, 2020)
* @since 1.6 (Jan 18, 2020)
*/
public final class LotteryConfiguration {
/**
* The maximum ball integer value.
*/
private final int maximumNumberValue;
/**
* The length of each lottery row.
*/
private final int lotteryRowLength;
/**
* Construct a new lottery configuration.
*
* @param maximumNumberValue the maximum ball integer value.
* @param lotteryRowLength the lottery row length.
*/
public LotteryConfiguration(final int maximumNumberValue,
final int lotteryRowLength) {
checkArgs(maximumNumberValue, lotteryRowLength);
this.maximumNumberValue = maximumNumberValue;
this.lotteryRowLength = lotteryRowLength;
}
/**
* Returns the maximum ball value/number.
*
* @return the maximum bill value/number.
*/
public int getMaximumNumberValue() {
return this.maximumNumberValue;
}
/**
* Returns the number of drawn balls.
*
* @return the number of drawn balls.
*/
public int getLotteryRowLength() {
return this.lotteryRowLength;
}
private static void checkArgs(int maximumNumber, int numberCount) {
if (maximumNumber < 1) {
throw new IllegalArgumentException(
"maximumNumber(" + maximumNumber + ") < 1");
}
if (numberCount < 1) {
throw new IllegalArgumentException(
"numberCount(" + numberCount + ") < 1");
}
if (numberCount > maximumNumber) {
throw new IllegalArgumentException(
"numberCount(" + numberCount + ") > " +
"maximumNumber(" + maximumNumber + ")");
}
}
}
</code></pre>
<p><strong><em><code>net.coderodde.datamining.lottery.LotteryRow.java</code></em></strong></p>
<pre><code>package net.coderodde.datamining.lottery;
import java.util.Arrays;
import java.util.Objects;
/**
* This class implements a single lottery row.
*
* @author Rodion "rodde" Efremove
* @version 1.61 (Apr 27, 2020) ~ removed manual sorting.
* @version 1.6 (Apr 18, 2020) ~ initial version.
* @since 1.6 (Apr 18, 2020)
*/
public final class LotteryRow {
/**
* The configuration object.
*/
private final LotteryConfiguration lotteryConfiguration;
/**
* The actual lottery numbers.
*/
private final int[] lotteryNumbers;
/**
* Stores the index of the internal storage array at which the next lottery
* number will be inserted.
*/
private int size = 0;
/**
* Constructs an empty lottery row with given configuration.
*
* @param lotteryConfiguration the lottery row configuration.
*/
public LotteryRow(LotteryConfiguration lotteryConfiguration) {
this.lotteryConfiguration =
Objects.requireNonNull(lotteryConfiguration);
this.lotteryNumbers =
new int[lotteryConfiguration.getLotteryRowLength()];
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
boolean isFirst = true;
for (final int number : this.lotteryNumbers) {
if (isFirst) {
isFirst = false;
stringBuilder.append(number);
} else {
stringBuilder.append(",").append(number);
}
}
return stringBuilder.toString();
}
/**
* Appends a number to the tail of this lottery row.
*
* @param number the number to append.
*/
public void appendNumber(int number) {
checkNumber(number);
checkHasSpaceForNewNumber();
this.lotteryNumbers[this.size++] = number;
Arrays.sort(this.lotteryNumbers, 0, size);
}
/**
* Returns the <code>index</code>th number.
*
* @param index the index of the desired number.
* @return the <code>index</code>th number.
*/
public int getNumber(int index) {
checkIndex(index);
return this.lotteryNumbers[index];
}
/**
* Returns the length of the lottery row in numbers.
*
* @return the length of the lottery row.
*/
public int size() {
return this.lotteryConfiguration.getLotteryRowLength();
}
/**
* Returns the configuration object of this row.
*
* @return the configuration object.
*/
public LotteryConfiguration getLotteryConfiguration() {
return this.lotteryConfiguration;
}
/**
* Checks that there is more space for lottery numbers in this row.
*/
private void checkHasSpaceForNewNumber() {
if (size == lotteryNumbers.length) {
throw new IllegalStateException(
"The lottery row cannot accommodate more numbers.");
}
}
/**
* Checks that the input number is within the lottery number range.
*
* @param number the number to check.
*/
private void checkNumber(int number) {
if (number < 1) {
throw new IllegalArgumentException("number(" + number + ") < 1");
}
if (number > this.lotteryConfiguration.getMaximumNumberValue()) {
throw new IllegalArgumentException(
"number (" + number + ") > " +
"this.lotteryConfiguration.getMaximumNumberValue()[" +
this.lotteryConfiguration.getMaximumNumberValue() + "]");
}
}
/**
* Checks that the index is withing the range <code>[0, n)</code>.
*
* @param index the index to check.
*/
private void checkIndex(int index) {
if (index < 0) {
throw new IllegalArgumentException("index(" + index + ") < 0");
}
if (index >= this.size) {
throw new IllegalArgumentException(
"index(" + index + ") >= this.index(" + this.size + ")");
}
}
}
</code></pre>
<p><strong><em><code>net.coderodde.datamining.lottery.LotteryRowGenerator.java</code></em></strong></p>
<pre><code>package net.coderodde.datamining.lottery;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
/**
* This class implements a facility for creating random lottery rows.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 18, 2020)
* @since 1.6 (Apr 18, 2020)
*/
public final class LotteryRowGenerator {
/**
* The lottery configuration object.
*/
private final LotteryConfiguration lotteryConfiguration;
/**
* The random number generator.
*/
private final Random random;
/**
* The storage array for.
*/
private final int[] numbers;
/**
* Constructs a {@code LotteryRowGenerator} with a given configuration.
*
* @param lotteryConfiguration the lottery configuration object.
*/
public LotteryRowGenerator(LotteryConfiguration lotteryConfiguration) {
this(lotteryConfiguration, new Random());
}
/**
* Constructs a {@code LotteryRowGenerator} with a given configuration and
* a seed value.
*
* @param lotteryConfiguration the lottery configuration object.
* @param seed the seed value.
*/
public LotteryRowGenerator(LotteryConfiguration lotteryConfiguration,
long seed) {
this(lotteryConfiguration, new Random(seed));
}
/**
* Constructs a {@code LotteryRowGenerator} with a given configuration and
* a random number generator.
*
* @param lotteryConfiguration the lottery configuration object.
* @param random the random number generator.
*/
public LotteryRowGenerator(LotteryConfiguration lotteryConfiguration,
Random random) {
this.random = Objects.requireNonNull(random,
"The input Random is null.");
this.lotteryConfiguration =
Objects.requireNonNull(
lotteryConfiguration,
"The input LotteryConfiguration is null.");
this.numbers = new int[lotteryConfiguration.getMaximumNumberValue()];
for (int i = 0; i < this.numbers.length; i++) {
this.numbers[i] = i + 1;
}
}
/**
* Generates and returns a list of random lottery rows.
*
* @param numberOfLotteryRows the requested number of lottery rows.
* @return a list of random rows.
*/
public List<LotteryRow>
generateLotteryRows(int numberOfLotteryRows) {
List<LotteryRow> rows = new ArrayList<>(numberOfLotteryRows);
for (int i = 0; i < numberOfLotteryRows; i++) {
rows.add(generateRow());
}
return rows;
}
private LotteryRow generateRow() {
LotteryRow lotteryRow = new LotteryRow(this.lotteryConfiguration);
shuffleInternalNumbers();
loadLotteryRow(lotteryRow);
return lotteryRow;
}
private void shuffleInternalNumbers() {
for (int i = 0, n = this.lotteryConfiguration.getMaximumNumberValue();
i < n;
i++) {
final int i2 = getRandomIndex();
swap(i, i2);
}
}
public void loadLotteryRow(LotteryRow lotteryRow) {
for (int i = 0, n = this.lotteryConfiguration.getLotteryRowLength();
i < n;
i++) {
lotteryRow.appendNumber(this.numbers[i]);
}
}
private int getRandomIndex() {
return this.random.nextInt(
this.lotteryConfiguration.getMaximumNumberValue());
}
private void swap(final int index1, final int index2) {
int tmp = this.numbers[index1];
this.numbers[index1] = this.numbers[index2];
this.numbers[index2] = tmp;
}
}
</code></pre>
<p><strong><em><code>net.coderodde.datamining.lottery.MissingLotteryRowsGenerator</code></em></strong></p>
<pre><code>package net.coderodde.datamining.lottery;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* This class implements a tree data structure for infering missing lottery
* rows.
*
* @author Rodion "rodde" Efremov
* @version 1.61 (Apr 27, 2020) ~ renamed the class.
* @version 1.6 (Apr 20, 2020) ~ initial version.
* @since 1.6 (Apr 20, 2020)
*/
public final class MissingLotteryRowsGenerator {
/**
* This inner class implements an integer tree node type.
*/
private static final class IntegerTreeNode {
/**
* Children map.
*/
private SortedMap<Integer, IntegerTreeNode> children;
/**
* Returns the textual representation of this
* {@linkplain net.coderodde.datamining.lottery.LotteryRowsIntegerTree.IntegerTreeNode}.
*
* @return the textual representation of this tree node.
*/
@Override
public String toString() {
return "{children: " + children.toString() + "}";
}
}
/**
* The root node of this integer tree.
*/
private IntegerTreeNode root = new IntegerTreeNode();
/**
* The lottery configuration.
*/
private final LotteryConfiguration lotteryConfiguration;
/**
* Caches the length of the lottery rows.
*/
private final int length;
/**
* Implements the main constructor.
*
* @param lotteryConfiguration the lottery configuration object.
* @param root the root node of the radix tree.
*/
private MissingLotteryRowsGenerator(
final LotteryConfiguration lotteryConfiguration,
final IntegerTreeNode root) {
this.lotteryConfiguration =
Objects.requireNonNull(
lotteryConfiguration,
"lotteryConfiguration == null");
this.root = Objects.requireNonNull(root, "The root node is null.");
this.length = this.lotteryConfiguration.getLotteryRowLength();
}
/**
* Constructs a missing rows generator with given lottery configuration.
*
* @param lotteryConfiguration the lottery configuration.
*/
public MissingLotteryRowsGenerator(
final LotteryConfiguration lotteryConfiguration) {
this(lotteryConfiguration, new IntegerTreeNode());
}
/**
* Adds a list of lottery rows to this generator.
*
* @param lotteryRows the lottery rows to add one by one.
* @return this generator for chaining.
*/
public MissingLotteryRowsGenerator
addLotteryRows(final List<LotteryRow> lotteryRows) {
for (final LotteryRow lotteryRow : lotteryRows) {
addLotteryRow(lotteryRow);
}
return this;
}
/**
* Adds a single lottery row to this generator.
*
* @param lotteryRow the lottery row to add.
* @return this generator for chaining.
*/
public MissingLotteryRowsGenerator
addLotteryRow(final LotteryRow lotteryRow) {
Objects.requireNonNull(lotteryRow, "lotteryRow == null");
checkLotteryRow(lotteryRow);
IntegerTreeNode node = root;
for (int i = 0, sz = this.length; i < sz; i++) {
final IntegerTreeNode nextNode;
final int number = lotteryRow.getNumber(i);
if (node.children == null) {
node.children = new TreeMap<>();
}
if (!node.children.containsKey(number)) {
node.children.put(number, nextNode = new IntegerTreeNode());
if (i < sz - 1) {
nextNode.children = new TreeMap<>();
}
} else {
nextNode = node.children.get(number);
}
node = nextNode;
}
return this;
}
/**
* Computes and returns all the <i>missing</i> lottery rows. A lottery row
* is <i>missing</i> if and only if it was not drawn in the population of
* players.
*
* @return the list of missing lottery rows.
*/
public List<LotteryRow> computeMissingLotteryRows() {
List<LotteryRow> lotteryRows = new ArrayList<>();
final int[] numbers = getInitialNumbers();
do {
LotteryRow lotteryRow = convertNumbersToLotteryRow(numbers);
if (!treeContains(lotteryRow)) {
lotteryRows.add(lotteryRow);
}
} while (increment(numbers));
return lotteryRows;
}
private boolean treeContains(final LotteryRow lotteryRow) {
IntegerTreeNode node = root;
for (int i = 0; i < this.length; i++) {
final int number = lotteryRow.getNumber(i);
final IntegerTreeNode nextNode = node.children.get(number);
if (nextNode == null) {
return false;
}
node = nextNode;
}
return true;
}
private boolean increment(final int[] numbers) {
final int maximumNumber =
this.lotteryConfiguration.getMaximumNumberValue();
for (int i = this.length - 1, j = 0; i >= 0; i--, j++) {
if (numbers[i] < maximumNumber - j) {
numbers[i]++;
for (int k = i + 1; k < this.length; k++) {
numbers[k] = numbers[k - 1] + 1;
}
return true;
}
}
return false;
}
/**
* Converts a number integer array into a
* {@link net.coderodde.datamining.lottery.LotteryRow}.
* @param numbers the raw number array in ascending order.
* @return the lottery row with exactly the same numbers as in
* {@code numbers}.
*/
private LotteryRow convertNumbersToLotteryRow(final int[] numbers) {
LotteryRow lotteryRow = new LotteryRow(this.lotteryConfiguration);
for (final int number : numbers) {
lotteryRow.appendNumber(number);
}
return lotteryRow;
}
private int[] getInitialNumbers() {
final int[] numbers = new int[this.length];
for (int i = 0, number = 1; i < this.length; i++, number++) {
numbers[i] = number;
}
return numbers;
}
private void checkLotteryRow(final LotteryRow lotteryRow) {
if (lotteryRow.size() != this.length) {
throw new IllegalArgumentException(
"Wrong length of a row (" + lotteryRow.size() + ", " +
"must be exactly " +
this.lotteryConfiguration.getLotteryRowLength() +
".");
}
}
}
</code></pre>
<p><strong><em><code>net.coderodde.datamining.lottery.Demo.java</code></em></strong></p>
<pre><code>package net.coderodde.datamining.lottery;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* This class demonstrates the functionality of the missing lottery row data
* mining algorithm.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 25, 2020)
* @since 1.6 (Apr 25, 2020)
*/
public class Demo {
// 40 choose 7 = 18_643_560 combinations:
private static final int LOTTERY_ROW_LENGTH = 7;
private static final int LOTTERY_MAXIMUM_NUMBER = 40;
private static final int LOTTERY_ROWS = 40_000_000;
public static void main(String[] args) throws IOException {
smallDemo();
final long seed = System.currentTimeMillis();
final LotteryConfiguration lotteryConfiguration =
new LotteryConfiguration(LOTTERY_MAXIMUM_NUMBER,
LOTTERY_ROW_LENGTH);
System.out.println("Seed = " + seed);
final List<LotteryRow> data = benchmarkAndObtainData(seed);
benchmark(lotteryConfiguration, data);
}
private static List<LotteryRow> benchmarkAndObtainData(final long seed) {
final LotteryConfiguration lotteryConfiguration =
new LotteryConfiguration(LOTTERY_MAXIMUM_NUMBER,
LOTTERY_ROW_LENGTH);
// Warmup run:
new LotteryRowGenerator(lotteryConfiguration, seed)
.generateLotteryRows(LOTTERY_ROWS);
long startTime = System.nanoTime();
// Data generation:
final List<LotteryRow> data =
new LotteryRowGenerator(lotteryConfiguration)
.generateLotteryRows(LOTTERY_ROWS);
long endTime = System.nanoTime();
System.out.println(
"Data generated in " +
((endTime - startTime) / 1_000_000L) +
" milliseconds.");
return data;
}
// Warms up and benchmarks the
private static void benchmark(
final LotteryConfiguration lotteryConfiguration,
final List<LotteryRow> data) throws IOException {
final long startTime = System.nanoTime();
final List<LotteryRow> missingLotteryRows =
new MissingLotteryRowsGenerator(lotteryConfiguration)
.addLotteryRows(data)
.computeMissingLotteryRows();
final long endTime = System.nanoTime();
System.out.println(
"Duration: "
+ ((endTime - startTime) / 1_000_000L)
+ " milliseconds.");
System.out.println(
"Missing lottery rows: " + missingLotteryRows.size());
// boolean isFirst = true;
//
// for (final LotteryRow lotteryRow : missingLotteryRows) {
// if (isFirst) {
// isFirst = false;
// } else {
// System.out.println();
// }
//
// System.out.print(lotteryRow);
// }
}
// Runs a small demo:
private static void smallDemo() {
LotteryConfiguration lotteryConfiguration =
new LotteryConfiguration(5, 3);
LotteryRow lotteryRow1 = new LotteryRow(lotteryConfiguration); // 1, 2, 4
LotteryRow lotteryRow2 = new LotteryRow(lotteryConfiguration); // 2, 4, 5
LotteryRow lotteryRow3 = new LotteryRow(lotteryConfiguration); // 1, 3, 5
LotteryRow lotteryRow4 = new LotteryRow(lotteryConfiguration); // 3, 4, 5
lotteryRow1.appendNumber(1);
lotteryRow1.appendNumber(4);
lotteryRow1.appendNumber(2);
lotteryRow2.appendNumber(4);
lotteryRow2.appendNumber(5);
lotteryRow2.appendNumber(2);
lotteryRow3.appendNumber(1);
lotteryRow3.appendNumber(3);
lotteryRow3.appendNumber(5);
lotteryRow4.appendNumber(3);
lotteryRow4.appendNumber(4);
lotteryRow4.appendNumber(5);
List<LotteryRow> drawnLotteryRows = Arrays.asList(lotteryRow1,
lotteryRow2,
lotteryRow3,
lotteryRow4);
MissingLotteryRowsGenerator generator =
new MissingLotteryRowsGenerator(lotteryConfiguration);
List<LotteryRow> missingLotteryRows = generator
.addLotteryRows(drawnLotteryRows)
.computeMissingLotteryRows();
missingLotteryRows.forEach((row) -> { System.out.println(row);});
}
}
</code></pre>
<p>(You can find the repository <a href="https://github.com/coderodde/MissingLotteryRowsMiner" rel="nofollow noreferrer">here</a>.)</p>
<p><strong><em>Critique request</em></strong></p>
<p>I am most interested in comments regarding how idiomatic code I produced. For example, is it O.K. to use <code>final</code> and <code>this</code> here and there?</p>
|
[] |
[
{
"body": "<p>You are bound to get different opinions on this one, but I personally do <em>not</em> like the use of <code>final</code> and <code>this</code> in various places:</p>\n\n<pre><code>public final class LotteryConfiguration\n</code></pre>\n\n<p>Here, final means \"you cannot subclass this\". Why? Is there a specific reason to forbid subclassing for once and for all? (In real-life projects, 95% of all times it was a bad idea to make a class final, though it always \"seemed a good idea at that time\".)</p>\n\n<p><code>final</code> in local variables:</p>\n\n<pre><code>public LotteryConfiguration(final int maximumNumberValue,\n final int lotteryRowLength) {\n ...\n}\n\nfinal int maximumNumber = this.lotteryConfiguration.getMaximumNumberValue();\n\nfor (final int number : numbers) {\n ...\n}\n</code></pre>\n\n<p>Here, <code>final</code> is just noise. OK, you explicitly declare that you will no assign a new value to a local variable, but who cares? Nobody needs this information, and - as your code in general is very readable and understandable - every reader sees this in a single glance without you explicitly telling them.</p>\n\n<p>There are some situations, where the compiler needs an explicit <code>final</code> variable (even though \"effectively final\" has been introduced in java 8 to reduce this), but apart from that, I'd never use final on a local.</p>\n\n<p>And while we are at compilers: no, todays compilers do not need this information for \"optimizing\" anymore.</p>\n\n<p><code>final</code> in class fields:</p>\n\n<p><em>YES</em></p>\n\n<p>Used correctly, this can make the class immutable (i.e. suitable for use as a hash-key), makes the intention clear, and is great information for the reader.</p>\n\n<p><code>this</code>: I normally use it only where it is needed (i.e. mostly when assigning a value in a constructor.)</p>\n\n<p>Here:</p>\n\n<pre><code>public void appendNumber(int number) {\n checkNumber(number);\n checkHasSpaceForNewNumber();\n this.lotteryNumbers[this.size++] = number;\n Arrays.sort(this.lotteryNumbers, 0, size);\n}\n</code></pre>\n\n<p>I would leave out the <code>this</code>. Again, it does not convey any additional information (there is no local <code>lotteryNumbers</code> which I could mistake it for) and adds noise. Apart from that, I use an IDE (this is not the 80s anymore) and see fields and local variables in different colors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T07:07:29.913",
"Id": "241349",
"ParentId": "241345",
"Score": "4"
}
},
{
"body": "<p>@mtj already provided a great answer; but I will add mine as I couldn't resist this. </p>\n\n<h2>Needless comments</h2>\n\n<p>The whole point of comments in code (IMHO) is to add information that is not there yet. Most often to describe WHY something is done in a way. The HOW, we can read from code if it is clean enough :).</p>\n\n<p>Take a look a this comment for example. What does it add?</p>\n\n<pre><code>/**\n * The lottery configuration.\n */\nprivate final LotteryConfiguration lotteryConfiguration;\n</code></pre>\n\n<p>Nothing valuable. It just repeats the code. It also makes refactoring harder, because you need to keep the comments in sync with the code.</p>\n\n<h2>Missing comments</h2>\n\n<p>This piece of code goes without comments, but would be an excellent candidate for clarification; WHY is the array initialized with <code>1</code> to <code>numbers.length</code> ? Can't tell from this code. (I can tell from the shuffle later on)</p>\n\n<pre><code> for (int i = 0; i < this.numbers.length; i++) {\n this.numbers[i] = i + 1;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T21:12:57.327",
"Id": "241398",
"ParentId": "241345",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241349",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T05:45:46.257",
"Id": "241345",
"Score": "2",
"Tags": [
"java",
"algorithm",
"tree",
"data-mining"
],
"Title": "Data mining in Java: finding undrawn lottery rows"
}
|
241345
|
<p>I hope you can help with improving my code. I am defining a function which draws out elements of a certain mass, one by one, from a distribution constrained by the function <code>imf()</code>, until I have used up all the mass given to the function. The code takes a very long time between 1 minute to 45 minutes depending on the input mass. I am wondering if there is any way to make this code more effective?
In the code there are certain parameters that give trivial answers such as log10(mnorm) this was done to ensure I could in the future alter the parameters. The focus of my problem is the while loop and how it draws from the distribution given by <code>imf()</code>, I have identified that this part is the root course of the long performance time for the code. Any help would be greatly appreciated.</p>
<pre><code>class Mod_MyFunctions:
def __init__(self):
pass
def imf(self, x, imf_type):
# Chabrier (2003) IMF for young clusters plus disk stars: lognorm and power-law tail
mnorm = 1.0
A1 = 0.158
mc = 0.079
sigma = 0.69
A2 = 4.43e-2
x0 = -1.3
if imf_type == 0:
ml = numpy.asarray((x <= log10(mnorm)).nonzero())[0]
mh = numpy.asarray((x > log10(mnorm)).nonzero())[0]
y = numpy.zeros(len(x))
for i in ml: y[i] = A1 * exp(-(x[i] - log10(mc))**2/2./sigma**2)
for i in mh: y[i] = A2 * (10.**x[i])**(x0-1)
return y
def mass_dist(self,
mmin=0.01,
mmax=100,
Mcm=10000,
imf_type=0,
SFE=0.03):
result = []
while sum(10**(np.array(result))) < SFE*Mcm:
x=numpy.random.uniform(log10(mmin), log10(mmax),size=1)
y=numpy.random.uniform(0, 1, size=1)
result.extend(x[numpy.where(y < myf.imf(x, imf_type))])
md=numpy.array(result)
return 10**md, len(md)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:20:43.260",
"Id": "473588",
"Score": "0",
"body": "Hi thanks for the notice, It was meant to say improve not improvise. I have now edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:22:48.913",
"Id": "473589",
"Score": "0",
"body": "`I have now edited` and not improved the title of the question in accordance to the recommendations hyperlinked from the help centre (& my above comment). (There's a residual `improvising` in the first sentence.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T09:23:01.193",
"Id": "473596",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Improvise means something different then you think :)</p>\n\n<p><code>log10(mnorm)</code> seems to be needed to compute only once. And you can do it in your head. It is 0.</p>\n\n<p>Same for <code>log10(mc)</code> (well not in your head this one :)).</p>\n\n<p><code>imf_type</code> seems useless when not zero. I am not pythonist, so, what does imf() return if imf_type is nonzero?</p>\n\n<p><code>sigma**2</code> can also be computed once.</p>\n\n<p><code>log10(mmin)</code> and <code>log10(mmax)</code> can be computed once per <code>mass_dist</code> call.</p>\n\n<p><code>myf.imf(x, imf_type)</code> can be computed once per call to extend (or mass_dist, im not sure what that statement means, but I am almost sure that imf call can be moved at least one level up). This one is probably the biggest performance killer. </p>\n\n<p>And there're probably more instances of this (anti)pattern.</p>\n\n<p>As for the algorithm itself, I leave that to others :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:23:59.417",
"Id": "473590",
"Score": "0",
"body": "Hi there thanks for the comment. It was meant to say improve not improvise haha thank you for the notice. I see your point with the small edits of things I could do very easily, it was written that way so that I could change the parameters. And in my original script there are other values for imf_type so that is way it is written as such. I will edit my post so that I incorporate more detail for others. Thank you again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T10:39:23.413",
"Id": "473602",
"Score": "0",
"body": "@ThomasJones you can still compute those values as soon as they becomes constants for the block. Ie log(mnorm) can be computed in constructor. It does not change for the lifetime of the object, but you can still create the object with different value... precomputing something before a loop if it does not change during iterations will turn the time complexity of the loop from n^m to n^(m-1) if the computation is O(n) which the imf function is. It gets worse for more complex computations ofc, but it may still be nonneglegable for O(1) as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T07:48:22.460",
"Id": "241351",
"ParentId": "241347",
"Score": "3"
}
},
{
"body": "<h1>Class</h1>\n\n<p>You use classes here without any benefit. Your methods don't use the <code>self</code> argument. If you use the class as a namespace, I would suggest you use a module.</p>\n\n<h1><code>np</code></h1>\n\n<p>Convention is to do <code>import numpy as np</code>. </p>\n\n<p>You also probably did <code>from numpy import log10, exp</code>. I would not import those independently, just do <code>np.exp</code>.</p>\n\n<h1>vectorise</h1>\n\n<p>You can use <code>np.where</code> to select between the 2 formula's. This allows you to vectorise <code>imf</code> </p>\n\n<pre><code>def imf_numpy(x, imf_type):\n\n # Chabrier (2003) IMF for young clusters plus disk stars: lognorm and power-law tail\n mnorm = 1.0\n A1 = 0.158\n mc = 0.079\n sigma = 0.69\n A2 = 4.43e-2\n x0 = -1.3\n\n if imf_type == 0:\n a1 = A1 * np.exp(-((x - np.log10(mc)) ** 2) / 2.0 / sigma ** 2)\n a2 = 2 * (10.0 ** x) ** (x0 - 1)\n return np.where(x <= np.log10(mnorm), a1, a2)\n</code></pre>\n\n<p>I gave them <code>a1</code> and <code>a2</code> variable names, but I don't have any domain knowledge. If in the literature these get assigned other names, use these.</p>\n\n<p>In the <code>mass_dist</code>, you can vectorise a lot.</p>\n\n<p>By limiting your <code>x</code> and <code>y</code> to <code>size=1</code>, you don't get any particular benefit from using numpy. I would take larger jumps and then select how far you need them. You also use a list and <code>extend</code>. I would stay in <code>numpy</code>-land, and use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.hstack.html#numpy.hstack\" rel=\"nofollow noreferrer\"><code>hstack</code></a>. You can then limit the result to <code>SFE * Mcm</code>:</p>\n\n<p>I would keep result as the <code>10**</code> already. this makes the rest easier to comprehend.</p>\n\n<pre><code>def mass_dist_numpy(mmin=0.01, mmax=100, Mcm=10000, imf_type=0, SFE=0.03):\n mmin_log = numpy.log10(mmin)\n mmax_log = numpy.log10(mmax)\n\n chunksize = 10\n result = np.array([], dtype=np.float64)\n while result.sum() < SFE * Mcm:\n x = np.random.uniform(mmin_log, mmax_log, size=chunksize)\n y = np.random.uniform(0, 1, size=chunksize)\n result = np.hstack((result, 10 ** x[y < imf_numpy(x, imf_type)]))\n\n return result[result.cumsum() < SFE * Mcm]\n</code></pre>\n\n<p>You can experiment with different chunk sizes, depending on the relative costs of calculating the <code>imf</code>, concatenating the results, the native python loop. You could pass it on as parameter and do a sensitivity analysis on it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:15:30.020",
"Id": "473651",
"Score": "0",
"body": "Thank you so much! This is exactly what I was looking for so glad I know vectorisation now :) It now runs 30x faster just on initial try, much appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T09:49:37.907",
"Id": "241357",
"ParentId": "241347",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241357",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T06:30:15.137",
"Id": "241347",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Initial Mass Function for young star clusters and disk field stars"
}
|
241347
|
<p>I have written a simple Tic Tac Toe game using some ASCII art. Is there anything I can do to improve upon the logic and structure of the program?</p>
<pre class="lang-py prettyprint-override"><code>"""A basic command line tic tac toe game"""
import os
import sys
gameBoard = [['' for j in range(3)] for i in range(3)]
displayBoard = [[' ' for j in range(46)] for i in range(25)]
def main():
"""Main method to control game"""
player = 'X'#Player x to go first
moveCounter = 1 #Keeps track of how many turns have been taken
#Setup game
initGame()
printInitScreen()
while True:
#Get player input
square = input(f"Player {player}, choose your square ->")
if validateInput(square):
updateGameBoard(square, player)
updateDisplayBoard(square, player)
printDisplayBoard()
if moveCounter >= 4:
checkIfWon(player)
#Switch player
if player == 'X':
player = 'O'
else:
player = 'X'
moveCounter += 1
else:
print("Please try again")
def initGame():
"""Create and set up game components"""
#Fill board
for i in range(25):
#If on a row boarder set to _
if i == 8 or i == 17:
for j in range(46):
displayBoard[i][j] = '_'
else:
for j in range(46):
#If on column boarder set |
if j == 15 or j == 31:
displayBoard[i][j] = '|'
#Put numbers in corner of square
displayBoard[0][0] = '1'
displayBoard[0][16] = '2'
displayBoard[0][32] = '3'
displayBoard[9][0] = '4'
displayBoard[9][16] = '5'
displayBoard[9][32] = '6'
displayBoard[18][0] = '7'
displayBoard[18][16] = '8'
displayBoard[18][32] = '9'
def validateInput(input):
"""Validates user input"""
#Check given char is allowed
try:
square = int(input[0]) #Check first char of input is number
except:
return False
#Check nothing already in that square
#Get the gameBoard index of users chosen square
index = numToIndex(input)
if gameBoard[index[0]][index[1]] != '':
return False
#If all ok
return True
def updateGameBoard(input, player):
"""Keeps track of users moves"""
#Update the array with new move
index = numToIndex(input[0])
gameBoard[index[0]][index[1]] = player
def printDisplayBoard():
"""Prints a string representation of board"""
os.system('cls' if os.name == 'nt' else 'clear') # Clear screen
for row in displayBoard:
print(''.join(row))
print("")
def checkIfWon(player):
"""Checks to see if the last move won the game"""
gameWon = False
#Check Horiz
for row in gameBoard:
if row[0] == row[1] == row[2] == player:
gameWon = True
#Check Vert
for i in range(3):
if gameBoard[0][i] == gameBoard[1][i] == gameBoard[2][i] == player:
gameWon = True
#Check Diag
if gameBoard[0][0] == gameBoard[1][1] == gameBoard[2][2] == player:
gameWon = True
if gameBoard[0][2] == gameBoard[1][1] == gameBoard[2][0] == player:
gameWon = True
if gameWon:
print(f"Congratualtions player {player}, you won!")
sys.exit()
def printGameBoard():
"""For debugging, prints gameboard"""
for row in gameBoard:
print(row)
def printInitScreen():
"""Prints the initial welcome screen"""
header = """
888 d8b 888 888
888 Y8P 888 888
888 888 888
888888888 .d8888b888888 8888b. .d8888b888888 .d88b. .d88b.
888 888d88P" 888 "88bd88P" 888 d88""88bd8P Y8b
888 888888 888 .d888888888 888 888 88888888888
Y88b. 888Y88b. Y88b. 888 888Y88b. Y88b. Y88..88PY8b.
"Y888888 "Y8888P "Y888"Y888888 "Y8888P "Y888 "Y88P" "Y8888
"""
os.system('cls' if os.name == 'nt' else 'clear') # Clear screen
print(header)
input("Press enter to start!")
printDisplayBoard()
def updateDisplayBoard(num, player):
"""Add the players shape to the chosen position on display board"""
shapes = {"X":
[[' ',' ',' ',' ','?','8','8','8','8','P',' ',' ',' ',' '],
[' ',' ',' ',' ',' ','`','8','8','`',' ',' ',' ',' ',' '],
['8','b',',','_',' ',' ','8','8',' ',' ','_',',','d','8'],
['8','8','8','8','8','S','I','C','K','8','8','8','8','8'],
['8','P','~',' ',' ',' ','8','8',' ',' ',' ','~','?','8'],
[' ',' ',' ',' ',' ',',','8','8','.',' ',' ',' ',' ',' '],
[' ',' ',' ',' ','d','8','8','8','8','b',' ',' ',' ',' ']],
"O":
[[' ',' ',' ',' ',' ',' ','%','%',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ','%','%',' ',' ','%','%',' ',' ',' ',' '],
[' ',' ','%','%',' ',' ',' ',' ',' ',' ','%','%',' ',' '],
['%','%',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','%','%'],
[' ',' ','%','%',' ',' ',' ',' ',' ',' ','%','%',' ',' '],
[' ',' ',' ',' ','%','%',' ',' ','%','%',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ','%','%',' ',' ',' ',' ',' ',' ']]}
shape = shapes[player]
num = int(num[0])
offsets = [[0 ,0],[0 ,16],[0 ,32],
[9 ,0],[9 ,16],[9 ,32],
[17,0],[17,16],[17,32]]
iOffset = offsets[num-1][0]
jOffset = offsets[num-1][1]
for i in range(iOffset, iOffset + 7):
for j in range(jOffset, jOffset + 14):
displayBoard[i+1][j] = shape[i - iOffset][j - jOffset]
def numToIndex(num):
"""Returns index [i,j] for given 'square' on board"""
num = int(num[0])
indexList = []
for i in range (3):
for j in range(3):
indexList.append([i,j])
return indexList[int(num)-1]
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<pre><code>gameBoard = [['' for j in range(3)] for i in range(3)]\ndisplayBoard = [[' ' for j in range(46)] for i in range(25)]\n</code></pre>\n\n<p>For me, time spend aligning source code is time wasted. It takes too much time initially. Moreover, if any variable is renamed throughout the code (or cleaned up etc. etc.), the aligning will get messed up. So it actively interferes with refactoring. This is highly subjective though, and I like to <strong>look</strong> at aligned code.</p>\n\n<hr>\n\n<pre><code>gameBoard = [['' for j in range(3)] for i in range(3)]\n</code></pre>\n\n<p>A game board (or game board state, more precisely) consists of squares, filled with X'es or O's. What's missing is an object to represent those. For me, this is a bit too \"stringly typed\".</p>\n\n<pre><code>displayBoard = [[' ' for j in range(46)] for i in range(25)]\n</code></pre>\n\n<p>This is the start of a problem in the code: unexplained numeric literals. Why 46 or 25? Just perform the calculations and let the computer compute. Make named constants out of the calculations and then use those.</p>\n\n<pre><code>player = 'X'#Player x to go first\n</code></pre>\n\n<p>If you name the identifier <code>currentPlayer</code> then the comment would not be necessary. Often choosing a good name will make comments unnecessary.</p>\n\n<p>I'd try and avoid trailing comments as they tend to disappear on long lines. Again, this is somewhat subjective.</p>\n\n<p>Use spaces before and after <code>#</code> please.</p>\n\n<pre><code>updateGameBoard(square, player)\nupdateDisplayBoard(square, player)\n</code></pre>\n\n<p>I spot a design issue here. The UI should display the state of the game, captured in <code>gameBoard</code>. So I would expect a <code>printDisplayBoard(gameBoard)</code> instead. Currently the game logic and UI is mixed <em>and</em> duplicated.</p>\n\n<pre><code>if moveCounter >= 4:\n checkIfWon(player)\n</code></pre>\n\n<p>This is not so intuitive to me. The game ends when a row, column or diagonal of three elements is formed. Currently you may have two winning players! If the board is filled without this happening then the game is a draw.</p>\n\n<p>Deviating from this game logic is not a good idea as it is easy to make mistakes. Moreover, and more importantly, it fails if the application is ever extended to, for instance, a 4x4 board. Now I don't expect \"tic tac toe too\" to happen soon, but for actual application code, this is rather important.</p>\n\n<p>My SudokuSolver was programmed as generically as possible. When I was done it literally took a minute to support differently sized and even special Sudoku's with additional diagonals and such. This shows the importance of programming as generically as possible.</p>\n\n<pre><code>def initGame():\n</code></pre>\n\n<p>I'd create <code>drawHorizontalLine</code> and <code>drawVertialLine</code> functions or similar.</p>\n\n<pre><code>displayBoard[0][0] = '1'\ndisplayBoard[0][16] = '2'\ndisplayBoard[0][32] = '3'\n</code></pre>\n\n<p>I like how you clearly mark the squares of the board. However, this also is one of the clearest examples of you doing the computing instead of the computer. It should be relatively easy to create a single <code>for</code> loop and compute the <code>x</code> and <code>y</code> of the positions.</p>\n\n<p>Basically you're buffering the image before displaying it, rather than making a single <code>print</code> with spaghetti code. That's very good.</p>\n\n<pre><code>os.system('cls' if os.name == 'nt' else 'clear') # Clear screen\n.\n.\n.\nos.system('cls' if os.name == 'nt' else 'clear') # Clear screen\n</code></pre>\n\n<p><strong>Repeat 10 times: \"I will keep to DRY principles\".</strong></p>\n\n<p>If you repeat such a line, then put the line in a function and call that. If you add another method of clearing the screen then likely one of the locations with the same line of code will be forgotten. Looking at the comment, you've already thought of a name and started typing.</p>\n\n<p>Of course, there is a lot of DRY (don't repeat yourself) failures where the same code is used but with different integer values, but this one stood out.</p>\n\n<pre><code>shapes = [...]\n</code></pre>\n\n<p>Do you really want that variable to be assigned the entire shape all the time? That needs to be a constant or - in real code - a resource that is being read <em>once</em>.</p>\n\n<pre><code>num = int(num[0])\n</code></pre>\n\n<p>Wait, what? Why? If the reason for code is not immediately clear, then I expect a comment!</p>\n\n<pre><code>offsets = [[0 ,0],[0 ,16],[0 ,32],\n [9 ,0],[9 ,16],[9 ,32],\n [17,0],[17,16],[17,32]]\n</code></pre>\n\n<p>Which offsets would that be? End of code, must be Friday :)</p>\n\n<pre><code>def numToIndex(num):\n</code></pre>\n\n<p>Finally, a function that calculates things! I <em>knew</em> you could do it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T09:44:30.620",
"Id": "473598",
"Score": "0",
"body": "Hi, thank you for taking the time to read through and help me with my code. I have learnt a lot from your answer. I'm sometimes cautious of using functions where maybe I don't need to, but you've cleared some things up for me. `printDisplayBoard(gameBoard)` This especially makes perfect sense now I have seen it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T10:26:55.810",
"Id": "473601",
"Score": "0",
"body": "Some people try and create methods with just a few lines, say 5-7 (for a higher level language). That's a bit too extreme for me, but in general large functions / methods are more troublesome than shorter ones, especially if they use a lot of branching (loops, if statements and switches). This is referred to as the *cyclomatic complexity* of a function. Programming is basically fighting complexity."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T09:06:09.827",
"Id": "241356",
"ParentId": "241348",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241356",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T06:57:59.743",
"Id": "241348",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tic-tac-toe",
"ascii-art"
],
"Title": "Tic Tac Toe with ASCII art"
}
|
241348
|
<p>I am remaking a very obscure old game called <strong>Rival Realms</strong>.</p>
<blockquote>
<p><em>The full source is <a href="https://github.com/Danjb1/open-rival/tree/master/Open-Rival" rel="noreferrer">here</a> if you're interested.</em></p>
</blockquote>
<p>I come from a Java background so C++ is still fairly new to me.</p>
<p>I recently performed a refactor to move all the textures and sprites into one class. The intention is that I will create a <code>Resources</code> instance when the game first starts, which will load all the required resources, and then I can pass around a pointer to this object so that other classes can easily retrieve the resources they need. This object will be "alive" until the game exits.</p>
<p><strong>Does this sound like a reasonable approach? How can the code be improved?</strong></p>
<blockquote>
<p><em>In particular I am still a little confused by the rule of 5, and when to use smart pointers. For example, here I have a <code>std::unique_ptr<std::map<UnitType, Spritesheet>></code> - but would it be better to have a <code>std::map<UnitType, std::unique_ptr<Spritesheet>></code> instead?</em></p>
</blockquote>
<h2>Resources.h</h2>
<pre><code>#ifndef RESOURCES_H
#define RESOURCES_H
#include <map>
#include <string>
#include <vector>
#include "Palette.h"
#include "Spritesheet.h"
#include "Texture.h"
#include "Unit.h"
namespace Rival {
class Resources {
public:
// Directories
static const std::string mapsDir;
static const std::string txDir;
Resources();
~Resources();
// Prevent moving or copying (rule of 5)
Resources(const Resources& other) = delete;
Resources(Resources&& other) = delete;
Resources& operator=(const Resources& other) = delete;
Resources& operator=(Resources&& other) = delete;
// Retrieval
Texture& getPalette() const;
Spritesheet& getTileSpritesheet(int index) const;
std::map<UnitType, Spritesheet>& getUnitSpritesheets() const;
Spritesheet& getMapBorderSpritesheet() const;
private:
// Texture constants
static const int numTextures = 96;
static const int txIndexUnits = 0;
static const int txIndexTiles = 50;
static const int txIndexUi = 53;
// Loaded textures
std::unique_ptr<std::vector<Texture>> textures =
std::make_unique<std::vector<Texture>>();
std::unique_ptr<Texture> paletteTexture;
// Spritesheets
std::unique_ptr<std::map<UnitType, Spritesheet>> unitSpritesheets =
std::make_unique<std::map<UnitType, Spritesheet>>();
std::unique_ptr<std::map<int, Spritesheet>> tileSpritesheets =
std::make_unique<std::map<int, Spritesheet>>();
std::unique_ptr<Spritesheet> mapBorderSpritesheet;
// Initialisation
void loadTextures();
void initPaletteTexture();
void initUnitSpritesheets();
void initTileSpritesheets();
void initUiSpritesheets();
void initUnitSpritesheet(UnitType type, int txIndex);
void initTileSpritesheet(int type, int txIndex);
};
}
#endif // RESOURCES_H
</code></pre>
<h2>Resources.cpp</h2>
<pre><code>#include "pch.h"
#include "Resources.h"
#include "RenderUtils.h"
namespace Rival {
const std::string Resources::mapsDir = "res\\maps\\";
const std::string Resources::txDir = "res\\textures\\";
Resources::Resources() {
loadTextures();
initPaletteTexture();
initUnitSpritesheets();
initUiSpritesheets();
initTileSpritesheets();
}
Resources::~Resources() {
// Delete Textures
for (Texture& texture : *textures.get()) {
const GLuint texId = texture.getId();
glDeleteTextures(1, &texId);
}
textures->clear();
}
void Resources::loadTextures() {
textures->reserve(numTextures);
// Units - Human
textures->push_back(Texture::loadTexture(txDir + "unit_human_ballista.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_battleship.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_bowman.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_chariot_of_war.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_fire_master.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_knight.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_light_cavalry.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_peasant.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_pegas_rider.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_priest.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_sea_barge.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_thief.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_wizard.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_human_zeppelin.tga"));
// Units - Greenskin
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_balloon.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_catapult.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_gnome_boomer.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_horde_rider.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_landing_craft.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_necromancer.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_priest_of_doom.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_rock_thrower.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_rogue.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_serf.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_storm_trooper.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_troll_galley.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_warbat.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_greenskin_warlord.tga"));
// Units - Elf
textures->push_back(Texture::loadTexture(txDir + "unit_elf_archer.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_arquebusier.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_bark.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_bombard.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_centaur.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_druid.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_dwarf_miner.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_enchanter.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_mage.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_magic_chopper.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_scout.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_sky_rider.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_warship.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_elf_yeoman.tga"));
// Units - Monsters
textures->push_back(Texture::loadTexture(txDir + "unit_monster_devil.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_monster_dragon.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_monster_golem.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_monster_gryphon.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_monster_hydra.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_monster_sea_monster.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_monster_skeleton.tga"));
textures->push_back(Texture::loadTexture(txDir + "unit_monster_snake.tga"));
// Tiles
textures->push_back(Texture::loadTexture(txDir + "tiles_meadow.tga"));
textures->push_back(Texture::loadTexture(txDir + "tiles_wilderness.tga"));
textures->push_back(Texture::loadTexture(txDir + "tiles_fog.tga"));
// UI
textures->push_back(Texture::loadTexture(txDir + "ui_cursor_select.tga"));
textures->push_back(Texture::loadTexture(txDir + "ui_map_border.tga"));
}
void Resources::initPaletteTexture() {
paletteTexture = std::make_unique<Texture>(
Palette::createPaletteTexture());
}
void Resources::initUnitSpritesheets() {
int nextIndex = txIndexUnits;
// Human
initUnitSpritesheet(UnitType::Ballista, nextIndex++);
initUnitSpritesheet(UnitType::Battleship, nextIndex++);
initUnitSpritesheet(UnitType::Bowman, nextIndex++);
initUnitSpritesheet(UnitType::ChariotOfWar, nextIndex++);
initUnitSpritesheet(UnitType::FireMaster, nextIndex++);
initUnitSpritesheet(UnitType::Knight, nextIndex++);
initUnitSpritesheet(UnitType::LightCavalry, nextIndex++);
initUnitSpritesheet(UnitType::Peasant, nextIndex++);
initUnitSpritesheet(UnitType::PegasRider, nextIndex++);
initUnitSpritesheet(UnitType::Priest, nextIndex++);
initUnitSpritesheet(UnitType::SeaBarge, nextIndex++);
initUnitSpritesheet(UnitType::Thief, nextIndex++);
initUnitSpritesheet(UnitType::Wizard, nextIndex++);
initUnitSpritesheet(UnitType::Zeppelin, nextIndex++);
// Greenskin
initUnitSpritesheet(UnitType::Balloon, nextIndex++);
initUnitSpritesheet(UnitType::Catapult, nextIndex++);
initUnitSpritesheet(UnitType::GnomeBoomer, nextIndex++);
initUnitSpritesheet(UnitType::HordeRider, nextIndex++);
initUnitSpritesheet(UnitType::LandingCraft, nextIndex++);
initUnitSpritesheet(UnitType::Necromancer, nextIndex++);
initUnitSpritesheet(UnitType::PriestOfDoom, nextIndex++);
initUnitSpritesheet(UnitType::RockThrower, nextIndex++);
initUnitSpritesheet(UnitType::Rogue, nextIndex++);
initUnitSpritesheet(UnitType::Serf, nextIndex++);
initUnitSpritesheet(UnitType::StormTrooper, nextIndex++);
initUnitSpritesheet(UnitType::TrollGalley, nextIndex++);
initUnitSpritesheet(UnitType::Warbat, nextIndex++);
initUnitSpritesheet(UnitType::Warlord, nextIndex++);
// Elf
initUnitSpritesheet(UnitType::Archer, nextIndex++);
initUnitSpritesheet(UnitType::Arquebusier, nextIndex++);
initUnitSpritesheet(UnitType::Bark, nextIndex++);
initUnitSpritesheet(UnitType::Bombard, nextIndex++);
initUnitSpritesheet(UnitType::Centaur, nextIndex++);
initUnitSpritesheet(UnitType::Druid, nextIndex++);
initUnitSpritesheet(UnitType::DwarfMiner, nextIndex++);
initUnitSpritesheet(UnitType::Enchanter, nextIndex++);
initUnitSpritesheet(UnitType::Mage, nextIndex++);
initUnitSpritesheet(UnitType::MagicChopper, nextIndex++);
initUnitSpritesheet(UnitType::Scout, nextIndex++);
initUnitSpritesheet(UnitType::SkyRider, nextIndex++);
initUnitSpritesheet(UnitType::Warship, nextIndex++);
initUnitSpritesheet(UnitType::Yeoman, nextIndex++);
// Monsters
initUnitSpritesheet(UnitType::Devil, nextIndex++);
initUnitSpritesheet(UnitType::Dragon, nextIndex++);
initUnitSpritesheet(UnitType::Golem, nextIndex++);
initUnitSpritesheet(UnitType::Gryphon, nextIndex++);
initUnitSpritesheet(UnitType::Hydra, nextIndex++);
initUnitSpritesheet(UnitType::SeaMonster, nextIndex++);
initUnitSpritesheet(UnitType::Skeleton, nextIndex++);
initUnitSpritesheet(UnitType::Snake, nextIndex++);
}
void Resources::initUnitSpritesheet(UnitType type, int txIndex) {
unitSpritesheets->emplace(std::piecewise_construct,
std::forward_as_tuple(type),
std::forward_as_tuple(
textures->at(txIndex),
RenderUtils::unitWidthPx,
RenderUtils::unitHeightPx));
}
void Resources::initUiSpritesheets() {
mapBorderSpritesheet = std::make_unique<Spritesheet>(
textures->at(txIndexUi + 1),
RenderUtils::tileSpriteWidthPx,
RenderUtils::tileSpriteHeightPx);
}
void Resources::initTileSpritesheets() {
int nextIndex = txIndexTiles;
initTileSpritesheet(0, nextIndex++); // Meadow
initTileSpritesheet(1, nextIndex++); // Wilderness
initTileSpritesheet(2, nextIndex++); // Fog
}
void Resources::initTileSpritesheet(int type, int txIndex) {
tileSpritesheets->emplace(std::piecewise_construct,
std::forward_as_tuple(type),
std::forward_as_tuple(
textures->at(txIndex),
RenderUtils::tileSpriteWidthPx,
RenderUtils::tileSpriteHeightPx));
}
Spritesheet& Resources::getTileSpritesheet(int index) const {
return tileSpritesheets->at(index);
}
std::map<UnitType, Spritesheet>& Resources::getUnitSpritesheets() const {
return *unitSpritesheets.get();
}
Spritesheet& Resources::getMapBorderSpritesheet() const {
return *mapBorderSpritesheet.get();
}
Texture& Resources::getPalette() const {
return *paletteTexture.get();
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Does this sound like a reasonable approach?</p>\n</blockquote>\n\n<p>What is your target system? Although I had a look at a gameplay video, I am not sure if sprites need dynamic loading. I guess not, so the answer is: Yeah, sure. If your target has enough resources (TM)</p>\n\n<blockquote>\n <p>In particular I am still a little confused by the rule of 5, and when to use smart pointers.</p>\n</blockquote>\n\n<p>For rule of five; you can look it up on google: <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">An adequately informative result</a>. In case these do not make sense; I see you use a user-defined destructor, so you may need to implement user-defined copy constructor and user-defined copy assignment operator. Though I don't think you will move your Resources object, so no need for \"rule of five\" in this case.</p>\n\n<p>What I would do in your case though is not to bother and just define constructor & destructor since I would not use unique_ptr, and you are not using anything else that is not RAII-compatible.</p>\n\n<p>Use unique_ptr if you have to and use shared_ptr otherwise for a \"safe\" start. If you utilise generic programming practices, you can easily change the declaration later on for some performance benefits and better declaration of your intent.</p>\n\n<blockquote>\n <p>For example, here I have a <code>std::unique_ptr<std::map<UnitType, Spritesheet>></code> - but would it be better to have a <code>std::map<UnitType, std::unique_ptr<Spritesheet>></code> instead?</p>\n</blockquote>\n\n<p>I vote for neither since I see no need for pointers at all. My answer would change if had looked at your code (which you provided, yes).</p>\n\n<p><strong>Other improvements:</strong></p>\n\n<ul>\n<li>Your function <code>void Resources::loadTextures()</code> seems unnecessarily long. You can define a list of strings and iterate over it for this redundant procedure.</li>\n</ul>\n\n<pre><code>textures->push_back(Texture::loadTexture(txDir + \"unit_human_ballista.tga\"));\ntextures->push_back(Texture::loadTexture(txDir + \"unit_human_battleship.tga\"));\ntextures->push_back(Texture::loadTexture(txDir + \"unit_human_bowman.tga\"));\ntextures->push_back(Texture::loadTexture(txDir + \"unit_human_chariot_of_war.tga\"));\n</code></pre>\n\n<p>would be easier to manage with</p>\n\n<pre><code>std::list<std::string> t = { \"unit_human_ballista.tga\", \"unit_human_battleship.tga\", \"unit_human_bowman.tga\", \"unit_human_chariot_of_war.tga\" /* etc */ };\nfor ( auto it = t.begin(); it != t.end(); ++t ) {\n textures->push_back(Texture::loadTexture(txDir + *t));\n}\n</code></pre>\n\n<ul>\n<li><p>If you want to use range-based for loops, do it as you wish after you watch <a href=\"https://www.youtube.com/watch?v=OAmWHmwlMwI\" rel=\"nofollow noreferrer\">this wonderful presentation</a> specifically at 42 minutes mark.</p></li>\n<li><p>Do these two functions need to be seperated?</p></li>\n</ul>\n\n<pre><code>void Resources::initTileSpritesheet(UnitType type, int txIndex)\nvoid Resources::initTileSpritesheets()\n\n</code></pre>\n\n<p>You can combine them and get a single function that does the same thing. Please refer to <a href=\"https://www.youtube.com/watch?v=yFeVRX02jVQ\" rel=\"nofollow noreferrer\">this another great video</a>.</p>\n\n<p>Same goes for <code>void Resources::initUnitSpritesheets()</code> and <code>void Resources::initUnitSpritesheet(int type, int txIndex)</code> [grunt] and the rest of your code, <strong>within reason</strong>.</p>\n\n<p>[grunt] Actually I do not like this default-constructed-object-as-type approach in initUnitSpritesheets but I can't think of a better alternative. You can probably hear me grunting.</p>\n\n<ul>\n<li>Why do you use</li>\n</ul>\n\n<pre><code>std::unique_ptr<std::vector<Texture>> textures = std::make_unique<std::vector<Texture>>();\n</code></pre>\n\n<p>in the header file when you can initialize <code>textures</code> at the constructor?</p>\n\n<ul>\n<li><code>*unitSpritesheets.get();</code> at definition of getUnitSpritesheets()</li>\n</ul>\n\n<p>Either your code does not compile with this, or I am missing something. I think you meant</p>\n\n<pre><code>return *unitSpritesheets;\n</code></pre>\n\n<p>See <a href=\"https://godbolt.org/z/nWPPlE\" rel=\"nofollow noreferrer\">this example</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:46:54.690",
"Id": "473680",
"Score": "1",
"body": "(1) Regarding the rule of 5, I have deleted the copy constructor / copy assignment operator since the class will never be moved (as you say). (2) I understand that `unique_ptr` is about ownership - so why not use them if Resources owns the sprites? How do you know if you \"need\" them? (3) What is the advantage of initialising `textures` in the constructor as opposed to at the declaration? (4) How do you suggest combining `initUnitSpritesheet` and `initUnitSpritesheets`? (5) The code compiles as-is, but it seems `return *unitSpritesheets` works just as well - can you explain this to me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:57:31.500",
"Id": "473681",
"Score": "0",
"body": "1) To be precise, copy counterparts are related with \"rule of three\", move counterparts are related with \"rule of five\". Move and copy semantics are slightly different. The point is, will you copy or move the Resources object? Even if you do not explicitly copy or move, there might be some copying/moving happening already. For example, initUnitSpritesheets creates default-initialized objects, copies them when you call initUnitSpritesheet, and passes that as reference to tuples. This copy is not obvious. I can't say anything more without looking up at your (planned) use of Resources object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:06:31.800",
"Id": "473684",
"Score": "0",
"body": "2) unique_ptr and shared_ptr are objects which hold a pointer to other objects. One can copy a shared_ptr but not a unique_ptr. If you copy a shared_ptr, its copy also \"owns\" the pointed object. You can only move a unique pointer, which transfers ownership. \"How do you know...\" is a question that may be a little bit hard for me to answer clearly. I do it mostly by trial and error. I have instincts, but reserve the actual answer to someone else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:12:45.193",
"Id": "473685",
"Score": "0",
"body": "3) Clearer interface and good habit, I would say. Headers are mostly for declaration and source files are for definition. You have some statics in the declaration and they are fine.\n4) I have no idea, and looking up at internet returned no quick answer. C++ is not really a reflective language yet. There are some tips and tricks, but it is not as easy as initTileSpritesheets. That is why I have said \"[...]but I can't think of a better alternative. You can probably hear me grunting.\". Not a native speaker so my wording might be somewhat off."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:28:15.237",
"Id": "473688",
"Score": "0",
"body": "5) The link I provided has some short explanations. You can also play with that example. But let me restate fully. `unitSpritesheets.get()` returns the \"naked pointer\" which pointer object holds. `*unitSpritesheets` is the way you should dereference it (to reach the object it points to). In function `getUnitSpritesheets`, `return *unitSpritesheets` would dereference the pointer and your return type `std::map<UnitType, Spritesheet>&` would pass it as a reference. Currently you are returning a pointer. With a quick look at your repo, I could not see how do you use `getUnitSpritesheets`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:40:58.113",
"Id": "473689",
"Score": "1",
"body": "Thank you for all your responses, I am learning a lot. If I understand correctly, using the `*` operator on a smart pointer is equivalent to dereferencing the raw pointer returned by .`get()`: https://en.cppreference.com/w/cpp/memory/unique_ptr/operator*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:47:43.730",
"Id": "473691",
"Score": "0",
"body": "I am not sure if it is exactly how you put it, but I think (and think I know) that is the case. There may be some nuances a more experienced person might point us at. C++ is really complicated (for me) as I go deeper.\n\nAnother thing is, my first comment stated \"[..] creates default-initialized objects, copies them when you call initUnitSpritesheet, and [...]\". This might be slightly (!) incorrect and compiler may be free to optimise that copy as a move. Maybe not. Again, not that experienced. These are the nuances I am talking about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T20:58:39.333",
"Id": "473700",
"Score": "0",
"body": "You're right about C++ being complicated! I've been spoiled by Java. If you're interested, I've made the suggested changes [here](https://github.com/Danjb1/open-rival/commit/66871447fe469382696499bcb0d2269c0073b329). However, I've stuck with range for-loops (IIUC, they are safe except for rare cases of proxy iterators, and I find them clearer), and I have left the unique_ptrs alone for now until I get a better understanding of exactly when they should / shouldn't be used."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:05:14.033",
"Id": "241373",
"ParentId": "241354",
"Score": "4"
}
},
{
"body": "<p>Transitioning between languages ain't easy. I remember my move from C to Java, where I had to learn that Java passes everything via pointer. Now that I know C++ I would argue that it passes everything by <code>std::shared_ptr</code>. So, the main element of learning a new language, beside the syntax, is to learn about good practices, which are different based on the language. Some constructs of Java, like the way they deal with enumerations are frowned upon in the C++ world, see <a href=\"https://stackoverflow.com/a/57346836/2466431\">this stack overflow post</a>.</p>\n\n<p>In general, I think your approach is sound. I'm positively surprised to see you using a <code>std::map<UnitType, ...></code> with this UnitType being a enum class. To be fair, as soon as you start optimizing, you want to get rid of <code>std::map</code> as it is way too much overhead and you better use a <code>std::vector</code> (This can even result in <code>O(1)</code> lookup and a lot less cache misses). Though, for the time being, it works and it allows you to get to get everything working.</p>\n\n<p>As my intro already alluded to, java uses pointers for everything. Most likely that's why you are using <code>std::unique_ptr</code> all over the place. C++ uses value semantics. In short: Instead of allocating all data on the heap, we store this on the stack by default. This causes huge performance gains as data is packed closed together and one has less cache misses. Not to mention all the allocate/deallocate code that doesn't need to be executed. With modern C++ (which is now the C++17 standard), there ain't that much reason to allocate. See more about that in an earlier post of mine on stackoverflow: <a href=\"https://stackoverflow.com/a/53898150/2466431\">when (not to) allocate memory</a>. In this specific case, remove ALL <code>std::unique_ptr</code> from the Resource class.</p>\n\n<p>Than, we have the rule of 5 you asked about. Again, this has something to do with value semantics.</p>\n\n<pre><code>void f(Class c); //< Function has it's own copy of Class, similar to being called with f(c.clone()); in Java\nvoid g(Class &c); //< Function can adapt the original instance\nvoid h(const Class &c); //< Function gets the original instance, though, ain't allowed to modify (If the original gets modified another way, it will see it)\nvoid i(Class &&c); //< Function requires you to move the original instance. (Original instance stays in valid but unspecified state)\nvoid j(const Class &&c); //< Really useless signature.\nvoid k(Class *c); //< Same as Class &c, however, c is allowed to be nullptr\nvoid l(const Class *c); //< Same as const Class &c, however, c is allowed to be nullptr\n</code></pre>\n\n<p>The above are all the different ways a function can be defined and let's the function implementor decide what behaviour the argument should have. This is really important to understand.</p>\n\n<p>So what happens when we call these functions?</p>\n\n<pre><code>Class a; //< Class can be changed\nconst Class b; //< No changes allowed after construction\nClass *c{nullptr}; //< Pointer to a changable class, can be nullptr and can be updated to refer to another class\nconst Class *d{nullptr}; //< Pointer to a class that can't be changed via d, can be nullptr and can be updated to refer to another class\nClass &e = a; //< See c, can't be nullptr\nconst Class &f = a; //< See d, can't be nullptr\n</code></pre>\n\n<p>So let's assume we can call this (ignoring the double name of f):</p>\n\n<pre><code>f(a); //< Passes a copy of a to f\ng(a); //< g gets a reference to a, can update a\nh(a); //< h gets a reference to a, can't update\ni(a); //< Doesn't compile, needs to be i(std::move(a))\nk(&a);\nl(&a);\n</code></pre>\n\n<p>(I'll leave the others as exercise to the reader)</p>\n\n<p>What does this have to do with the rule of 5? It requires you to define what the <code>Class</code> executes as code when copied, moved, assigned.</p>\n\n<pre><code>Class(); //< Default constructor (not part of rule of 5)\nClass(int i); //< Regular constructor (not part of rule of 5\n~Class(); //< Destructor: Gets executed when the class gets destroyed (C++ has deterministic destruction, so you can actually write useful code here, as closing a file handle. Often linked to RAII (You can Google this))\n\n Class(const Class &other); //< Copy constructor: How should the class be copied, should the new class share some elements with the `other` instance or not? Implementer can decide.\n Class(Class &&other); //< Move constructor: Similar to the copy constructor, however, one is allowed to `steal` from the `other` instance, as long as it leaves it in a valid/unspecified state (aka: program doesn't crash when destructor gets called)\n\n Class &operator(const Class &rhs); //< Copy assignment: In short: Destructor followed by Copy Construction, with some details for self-assign and optimization.\n Class &operator(Class &&rhs); //< Move assignment: In short: Destructor followed by Move Construction, with some details for self-assign and optimization.\n</code></pre>\n\n<p>The rule of 0-or-5 states that you should specify either none or all 5 of:</p>\n\n<ul>\n<li>Destructor</li>\n<li>Copy constructor</li>\n<li>Move constructor</li>\n<li>Copy assignment</li>\n<li>Move assignment</li>\n</ul>\n\n<p>This in order to have something easily understandable for the reader, while ensuring bug-free usage of your classes. (<code>= delete</code> is considered an implementation, stating: This ain't allowed to be used) </p>\n\n<p>More about the rule of 5 on <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all\" rel=\"nofollow noreferrer\">the cpp core guidelines</a></p>\n\n<p>Let me stop here with the review, I have some other remarks which I'll keep for myself as I find it more important for you to first grasp these idioms.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-03T13:24:30.467",
"Id": "474248",
"Score": "1",
"body": "This was immensely helpful, in particular the explanation of the stack usage - thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-03T08:08:12.323",
"Id": "241647",
"ParentId": "241354",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241373",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T08:48:41.330",
"Id": "241354",
"Score": "8",
"Tags": [
"c++",
"game",
"opengl"
],
"Title": "Remaking a 1998 RTS game in C++"
}
|
241354
|
<h2>Idea</h2>
<p>Consider the following snippet:</p>
<pre class="lang-py prettyprint-override"><code>import inspect
from pathlib import Path
def path_relative_to_caller_file(*pathparts: str) -> Path:
"""Provides a new path as a combination of the caller's directory and a subpath.
When creating a Path like Path("resources", "log.txt"), the containing Python script
has to be called from within the directory where the subdirectory "resources" is
found. Otherwise, the relative path breaks with an error.
This function provides a new path to always assure those relative paths are found,
no matter from where the script containing the relative path definition is called.
Example:
A/
└── B/
└── C/
├── script.py
└── D/
└── E/
└── config.txt
File script.py contains a Path("D", "E", "config.txt") to access data in that config
file. If the script is called from the "C" directory, the relative path resolves
fine, since the "D" subdirectory is immediately visible.
However, if the script is called from e.g. "A", it breaks, because there is no
"D/E/config.txt" in "A". If the script uses this function instead, the paths get
resolved correctly to absolute paths.
Here, Path("D", "E", "config.txt") is the 'subpath'.
Note: this function can also be called without an argument to get the caller's
file's containing directory, or with ".." (as many as needed) to move up.
If called with one argument, a file name, this script can replace
`Path(__file__).with_name("new_file")` to get a new file path in the same directory
as the caller's file, while being much clearer in syntax.
Attributes:
pathparts: As many arguments as the subpath needs. The new Path will be
created as e.g. Path("x", "y", "z"). This gets rid of ambiguities
surrounding usage of forward or backward slashes.
"""
current_frame = inspect.currentframe() # This function's frame
previous_frame = current_frame.f_back # One up: the caller's frame
caller_filename = inspect.getsourcefile(previous_frame)
# Construct a Path relative to the caller's directory:
caller_dir = Path(caller_filename).parent
sub_path = Path(*pathparts) # Can be anything: file, dir, links
return caller_dir.joinpath(sub_path).resolve()
</code></pre>
<p>The docstring explains it in detail. The synopsis is: there is a Python file, here <code>script.py</code>, that relies on a file that is found in a fixed location <em>relative</em> to it. In this case, <code>D/E/config.txt</code>. It can be <em>any</em> relative path, including <code>..</code> parts.</p>
<p>The <code>script.py</code> file can be called from anywhere. If it is called from anywhere <em>but</em> the <code>C/</code> directory, the discovery for <code>config.txt</code> can break easily with many naive approaches.</p>
<p>As such, a <code>script.py</code> file can import <code>path_relative_to_caller_file</code>. It can do so from wherever, that part should not matter. The function fully resolves paths <em>relative</em> to the file from which it is called.</p>
<h2>Directory Structure</h2>
<p>The directory structure is as follows:</p>
<pre class="lang-bsh prettyprint-override"><code>~$ tree A
A
└── B
└── C
├── D
│ └── E
│ └── config.txt
├── path_relative_to_caller_file.py
└── script.py
</code></pre>
<p>where <code>path_relative_to_caller_file.py</code> contains only the code shown above.
<code>script.py</code> is:</p>
<pre class="lang-py prettyprint-override"><code>from pathlib import Path
from path_relative_to_caller_file import path_relative_to_caller_file
paths = [
path_relative_to_caller_file(),
path_relative_to_caller_file(".."),
path_relative_to_caller_file("..", ".."),
path_relative_to_caller_file("D"),
path_relative_to_caller_file("D", "E"),
path_relative_to_caller_file("D", "E", "config.txt"),
path_relative_to_caller_file("nonexistent_directory"),
]
plain_path = Path("D", "E", "config.txt")
print("path_relative_to_caller_file:")
for path in paths:
print("\t", path, path.exists())
print("Plain path in script.py:")
print("\t", plain_path, plain_path.exists())
</code></pre>
<h2>Output</h2>
<p>This works if called from the parent directory of <code>A/</code>, so <code>~</code>:</p>
<pre class="lang-bsh prettyprint-override"><code>~$ python3 A/B/C/script.py
path_relative_to_caller_file:
/home/hansA/B/C True
/home/hans/A/B True
/home/hans/A True
/home/hans/A/B/C/D True
/home/hans/A/B/C/D/E True
/home/hans/A/B/C/D/E/config.txt True
/home/hans/A/B/C/nonexistent_directory False
Plain path in script.py:
D/E/config.txt False
</code></pre>
<p>The plain, "naive" approach works only if called from <code>~/A/B/C/</code>:</p>
<pre class="lang-bsh prettyprint-override"><code> ~/A/B/C$ python3 script.py
path_relative_to_caller_file:
/home/hansA/B/C True
/home/hans/A/B True
/home/hans/A True
/home/hans/A/B/C/D True
/home/hans/A/B/C/D/E True
/home/hans/A/B/C/D/E/config.txt True
/home/hans/A/B/C/nonexistent_directory False
Plain path in script.py:
D/E/config.txt True
</code></pre>
<p>The above approach keeps working however. It even works when navigating up the tree:</p>
<pre class="lang-bsh prettyprint-override"><code> ~/A/B/C/D/E$ python3 ../../script.py
path_relative_to_caller_file:
/home/hans/A/B/C True
/home/hans/A/B True
/home/hans/A True
/home/hans/A/B/C/D True
/home/hans/A/B/C/D/E True
/home/hans/A/B/C/D/E/config.txt True
/home/hans/A/B/C/nonexistent_directory False
Plain path in script.py:
D/E/config.txt False
</code></pre>
<p>Now, the <code>inspect</code> module seems a bit overkill for this. I also wonder about security (can the frame be injected maliciously by the caller?) and performance (an entire inspection for what is not much more than some string-fu) issues. When looking at the problem at a distance, it seems like there should be an easier solution.</p>
<p>It is also possible I got this entirely backwards and am missing the bigger picture.</p>
<h2>Alternative</h2>
<p>An obvious alternative would be to just have a function that requires a <code>Path</code> object to do the relative work on. Callers of that function would then just pass their <code>__file__</code> variable (part of <code>globals()</code>), followed by the same <code>*pathargs</code> that will work relative on that <code>__file__</code> path and return the (resolved) result. This would be straighforward. In fact, this is how I had it at first. However, then all function calls have <code>__file__</code> as their first argument. As such, I came up with the above to rid the code of this perceived redundancy (DRY).</p>
<p>Tested on Python 3.7.7 (Debian) and Python 3.8.2 (Win10).</p>
|
[] |
[
{
"body": "<p>I think you understand the tradeoffs: you can either use <code>__file__</code> everywhere or trust the stack to rewind to the caller's frame of reference. The former looks redundant, but the latter makes your function kinda weird and may behave oddly if the user isn't aware of what's going on. For example, if they decorated your function, then they might get the file path relative to the decorator's file rather than the caller's file. There are ways around this (namely, taking an explicit argument for how far back the call stack to go), but it gets ugly fast.</p>\n\n<p>Python doesn't have macros, so there's no super-clean way to create a function whose global closure is that of the caller rather than where that function is defined. There are, of course, ways to do this, but it adds complexity to the calling code which is what you're trying to avoid.</p>\n\n<p>I'd argue that passing <code>__file__</code> each time doesn't break DRY, because even though that variable has the same name in every context, it means something different each time. You're not repeating yourself, you just have the different value in the same name each time. Doing this makes the calling code more explicit, reduces the opportunity for bugs, simplifies your code, and increases the usability of your function. E.g., the calling code could ask for the file path relative to a parent module if the project was set up such that, say, a function was imported and exposed via an <code>__init__.py</code> up a folder or two.</p>\n\n<p>So in summary, I think the simpler approach that requires passing <code>__file__</code> doesn't break DRY and does conform to KISS.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T06:10:53.527",
"Id": "473727",
"Score": "0",
"body": "Function wrapping/decoration is a good point I had not anticipated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:51:22.610",
"Id": "241377",
"ParentId": "241360",
"Score": "2"
}
},
{
"body": "<h3>importlib.resources</h3>\n\n<p>As of Python 3.7 you can make put the data files in packages and use <code>importlib.resources</code></p>\n\n<pre><code>A/\n└── B/\n └── C/\n ├── script.py\n └── D/\n ├── __init__.py <== could be an empty file\n └── E/\n ├── __init__.py <== could be an empty file\n └── config.txt\n</code></pre>\n\n<p>Then use <code>read_binary</code> or <code>read_text</code> to read a file. <code>open_binary</code> and <code>open_text</code> return a file-like object.</p>\n\n<pre><code>from importlib.resources import open_text\n\nwith open_text(\"D.E\", \"config.txt\") as f:\n for line in f:\n print(line)\n</code></pre>\n\n<p>I believe it will work going up the directory tree if they are all packages (have <code>__init__.py</code> files), but I haven't tried it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T06:29:10.720",
"Id": "473728",
"Score": "0",
"body": "That looks like exactly what I wanted, thanks. Supplying `A/` and `B/` with `__init__.py` files and then calling `python -m A.B.C.script` from `~` works. In that case, as you said, it will also find a `config.txt` if that is in `B/` (so one up from its containing `script.py` in `C/`) if called as `with open_text(\"A.B\", \"config.txt\") as f:`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T05:11:51.653",
"Id": "241410",
"ParentId": "241360",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241410",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T10:29:19.993",
"Id": "241360",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"file-system"
],
"Title": "Resolving Paths relative to script file, independent of calling location"
}
|
241360
|
<p>I wrote a program which visualizes a doubly linked list in C++/SFML. The code is working as intended, and does exactly what I want. Could you give me some feedback / criticism on some do's and or don'ts?</p>
<p>This Node class represent a node within the doubly linked list. It inherits both from sf::RectangleShape and sf::Vertex so I can a)visualise the node, and b)put the nodes into an sf::VertexArray so I can draw the links in between them easily.</p>
<pre><code>#ifndef NODE_H
#define NODE_H
#include <SFML/Graphics.hpp>
#include "Globals.h"
template<typename T>
struct Node : public sf::RectangleShape, public sf::Vertex
{
T data;
Node<T>* next = nullptr;
Node<T>* previous = nullptr;
sf::Vector2f initialposition; // unsorted position
sf::Vector2f sortedposition; //sorted position which is based on its position in the list array.
sf::Vector2f distance; //used to calculate velocity.
sf::Vector2f velocity;
Node(const T& data, sf::Vector2f&& position);
void setAllPositions(const sf::Vector2f& position); //since it is both an sf vertex and sf rectangleshape, this function allows me to move both at once
void moveall(const sf::Vector2f& vel); //ditto with velocity.
};
template<typename T>
Node<T>::Node(const T& value, sf::Vector2f&& position)
:data(value), initialposition(position)
{
setAllPositions(position);
this->setFillColor(sf::Color::Transparent);
this->setOutlineColor(sf::Color::White);
this->setOutlineThickness(3);
this->setSize(sf::Vector2f{ static_cast<float>(NODE_WIDTH), static_cast<float>(NODE_WIDTH) });
this->setOrigin(this->getSize() / static_cast<float>(2));
}
template<typename T>
void Node<T>::setAllPositions(const sf::Vector2f& pos)
{
this->setPosition(pos);
position = pos;
}
template<typename T>
void Node<T>::moveall(const sf::Vector2f& vel)
{
this->move(vel);
position += vel;
}
#endif
</code></pre>
<p>This is my List class, which manages all the nodes. I have chosen to inherit from sf::Drawable so as to make it directly drawable. It contains so that I am able to spawn nodes at random locations.</p>
<pre><code>#ifndef LIST_H
#define LIST_H
#include <deque>
#include <random>
#include "Node.h"
#include <algorithm>
template<typename T>
class List : public sf::Drawable
{
protected:
mutable sf::VertexArray arr{ sf::LineStrip }; //this stores the nodes as individual verticies.
std::deque<Node<T>*> m_nodeStorage;
Node<T>* head = nullptr;
Node<T>* tail = nullptr;
virtual void draw(sf::RenderTarget& target, sf::RenderStates state) const override; //draws nodes, as well as the verticies in the array above.
static inline Node<T>* createnode(const T& val);
static inline sf::Vector2f getrandompos(); //creates a random vector within screen using distributions below
static std::mt19937 m_randomGenerator;
static std::uniform_real_distribution<float> m_gaussian_position;
public:
List();
List(const T& val); //value constructor
List(const List<T>& other); //copy constructor
List(const List<T>&& other); //move constructor
List<T>& operator= (List<T>& other); //copy assignment operator
List<T>& operator=(List<T>&& other); //move assignment operator
~List();
void append(const T& val);
bool insert(const T& val, const int& index);
bool indexerase(const int& index);
bool valueerase(const T& val);
void clear();
void pop();
inline void setheadandtail(); //called after insertion or deletion, makes sure head and tail are correct
bool isempty() const;
decltype(auto) getnodestorage() const;
void traverseforward();
void traversebackward();
};
template<typename T>
List<T>::List(const T& val)
{
head = createnode(val);
m_nodeStorage.push_back(head);
setheadandtail();
}
template<typename T>
List<T>::List()
{
}
template<typename T>
List<T>::List(const List<T>& other)
{
for (const Node<T>* node : other.m_nodeStorage)
{
append(node->data);
}
setheadandtail();
}
template<typename T>
List<T>::List(const List<T>&& other)
{
for (const Node<T>* node : other.m_nodeStorage)
{
m_nodeStorage.push_back(node);
}
setheadandtail();
}
template<typename T>
List<T>& List<T>::operator=(List<T>& other)
{
m_nodeStorage.clear();
for (const Node<T>* node : other.m_nodeStorage)
{
append(node->data);
}
setheadandtail();
}
template<typename T>
List<T>& List<T>::operator=(List<T>&& other)
{
for (const Node<T>* node : other.m_nodeStorage)
{
m_nodeStorage.push_back(node);
}
setheadandtail();
}
template<typename T>
List<T>::~List()
{
clear();
}
template<typename T>
void List<T>::draw(sf::RenderTarget& target, sf::RenderStates state) const
{
arr.clear();
for (Node<T>* node : this->m_nodeStorage)
{
target.draw(*node);
arr.append(*node);
}
target.draw(arr);
}
template<typename T>
bool List<T>::insert(const T& val, const int& index)
{
if (index > m_nodeStorage.size()) return false;
if (index < 0) return false;
Node<T>* newnode = createnode(val);
if (index == 0 )
{
if (m_nodeStorage.size() != 0) //if a head already exists
{
newnode->next = head;
head->previous = newnode;
}
head = newnode;
m_nodeStorage.push_front(newnode);
return true;
}
else //if inserted at non 0 index.
{
if (index == m_nodeStorage.size()) // if appending
{
Node<T>* lastnode = m_nodeStorage.back();
lastnode->next = newnode;
newnode->previous = lastnode;
m_nodeStorage.push_back(newnode);
}
else
{
Node<T>* previousNode = m_nodeStorage[index -1];
Node<T>* nextNode = m_nodeStorage[index];
previousNode->next = newnode;
newnode->previous = previousNode;
nextNode->previous = newnode;
newnode->next = nextNode;
m_nodeStorage.insert(m_nodeStorage.begin() + index, newnode);
}
tail = m_nodeStorage.back();
return true;
}
return false;
}
template<typename T>
void List<T>::clear()
{
for (Node<T>* node : m_nodeStorage)
{
delete node;
}
m_nodeStorage.clear();
}
template<typename T>
void List<T>::append(const T& val)
{
insert(val, m_nodeStorage.size());
}
template<typename T>
bool List<T>::valueerase(const T& val)
{
auto deletenode = std::find_if(m_nodeStorage.begin(), m_nodeStorage.end(),[&](Node<T>* node)
{
return node->data == val;
});
if (deletenode != m_nodeStorage.end())
{
return indexerase(static_cast<int>(std::distance(m_nodeStorage.begin(), deletenode)));
}
return false;
}
template<typename T>
bool List<T>::indexerase(const int& index)
{
if (index < 0 || index >= m_nodeStorage.size()) return false;
if (m_nodeStorage.empty()) return false;
Node<T>* currentnode = m_nodeStorage[index];
if(index > 0 && index < m_nodeStorage.size() - 1)
{
Node<T>* previousnode = m_nodeStorage[index - 1];
Node<T>* nextnode = m_nodeStorage[index + 1];
previousnode->next = nextnode;
nextnode->previous = previousnode;
}
delete currentnode;
m_nodeStorage.erase(m_nodeStorage.begin() + index);
setheadandtail();
return true;
}
template<typename T>
void List<T>::pop()
{
indexerase(static_cast<int>(m_nodeStorage.size() - 1));
}
template<typename T>
void List<T>::setheadandtail()
{
if (!m_nodeStorage.empty())
{
head = m_nodeStorage[0];
tail = m_nodeStorage[m_nodeStorage.size() - 1];
head->previous = nullptr;
tail->next = nullptr;
}
}
template<typename T>
bool List<T>::isempty() const
{
return m_nodeStorage.empty();
}
template<typename T>
void List<T>::traverseforward()
{
Node<T>* currentNode = head;
while (currentNode != nullptr)
{
currentNode->setOutlineColor(sf::Color::Green);
currentNode = currentNode->next;
}
}
template<typename T>
void List<T>::traversebackward()
{
Node<T>* currentnode = m_nodeStorage.back();
while (currentnode != nullptr)
{
currentnode->setOutlineColor(sf::Color::Red);
currentnode = currentnode->previous;
}
}
template<typename T>
decltype(auto) List<T>::getnodestorage() const
{
return &m_nodeStorage;
}
//statics
template<typename T>
Node<T>* List<T>::createnode(const T& val)
{
Node<T>* newnode = new Node<T>(val, getrandompos());
return newnode;
}
template<typename T>
sf::Vector2f List<T>::getrandompos()
{
return sf::Vector2f{ m_gaussian_position(m_randomGenerator), m_gaussian_position(m_randomGenerator) };
}
template<typename T>
std::mt19937 List<T>::m_randomGenerator{ 3 };
template<typename T>
std::uniform_real_distribution<float> List<T>::m_gaussian_position{ 0,WIDTH };
#endif
</code></pre>
<p>This is my engine class, which manages the velocities of each node.</p>
<pre><code>#ifndef ENGINE_H
#define ENGINE_H
#include "List.h"
template<typename T>
class Engine : public List<T>
{
protected:
float maximumvelocity = 1000;
float maximumdistance = sqrt(pow(WIDTH, 2) + pow(HEIGHT, 2));
float G = maximumvelocity / maximumdistance;
public:
Engine(const T& val);
void calculatesortedpositions();
void update();
static sf::Vector2f normalisedvector(const sf::Vector2f& vec);
static float vectormagnitude(const sf::Vector2f& vec);
};
template<typename T>
Engine<T>::Engine(const T& freq)
:List<T>(freq)
{
for (int i = 0; i < freq; i++)
{
this->append(freq);
}
calculatesortedpositions();
}
template<typename T>
void Engine<T>::calculatesortedpositions()
{
int i = 0;
for (Node<T>* node : this->m_nodeStorage)
{
node->sortedposition.x = (NODE_WIDTH / 2) + ((i) % (NCOLS)) * NODE_WIDTH;
node->sortedposition.y = (NODE_WIDTH / 2) + ((i) / (NCOLS)) * NODE_WIDTH;
i++;
}
}
template<typename T>
void Engine<T>::update()
{
for (Node<T>* node : this->m_nodeStorage)
{
node->distance = node->sortedposition - node->getPosition();
node->velocity = normalisedvector(node->distance) * G;
node->moveall(node->velocity);
}
}
//statics
template<typename T>
float Engine<T>::vectormagnitude(const sf::Vector2f& vec)
{
return sqrt(pow(vec.x, 2) + pow(vec.y, 2));
}
template<typename T>
sf::Vector2f Engine<T>::normalisedvector(const sf::Vector2f& vec)
{
return vec / vectormagnitude(vec);
}
#endif
</code></pre>
<p>Here are my globals variables</p>
<pre><code>#ifndef GLOBALS_H
#define GLOBALS_H
#define WIDTH 700
#define HEIGHT 700
#define NODE_WIDTH 30
#define NCOLS WIDTH / NODE_WIDTH
#endif
</code></pre>
<p>Here is main.cpp</p>
<pre><code>#include <iostream>
#include "Node.h"
#include "Globals.h"
#include "Engine.h"
int main()
{
sf::RenderWindow myWindow(sf::VideoMode(WIDTH, HEIGHT), "Doubly Linked List", sf::Style::Default);
sf::View screen;
screen.setCenter(sf::Vector2f{ WIDTH / 2,HEIGHT / 2 });
screen.setSize(sf::Vector2f{ WIDTH,HEIGHT });
Engine<float> myEngine(600);
while (myWindow.isOpen())
{
sf::Event evnt;
while (myWindow.pollEvent(evnt))
{
switch (evnt.type)
{
case sf::Event::EventType::Closed:
{
myWindow.close();
}
case sf::Event::EventType::KeyPressed:
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W))
{
screen.zoom(0.99);
myWindow.setView(screen);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S))
{
screen.zoom(1.01);
myWindow.setView(screen);
}
}
}
}
myWindow.clear();
myWindow.draw(myEngine);
myEngine.update();
myWindow.display();
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Globals.h</h1>\n\n<ol>\n<li>I generally don't mind globals as much; I think there are scenarios where they are useful, but this isn't it. These <code>NODE_WIDTH</code> and <code>NCOLS</code> are part of your <code>Node</code> class, and as such should be tightly coupled with it.</li>\n<li>Don't use <code>#define</code> unless you need to. It's the C way of defining globals, it does not maintain type safety of the expression; instead use <code>constexpr size_t</code> or <code>constexpr unsigned int</code>.</li>\n<li>Instead of defining them in a separate header, define them as <code>static constexpr</code> members in your class. Better yet, define them as regular data members, so you customize the appearance of each linked list.</li>\n</ol>\n\n<h1>Node.h</h1>\n\n<ol>\n<li>Prefer using smart pointer to raw pointers; it's fine in this case, since you're deleting them, but it's something to keep in mind for future.</li>\n<li>Naming is out of place. You have a method <code>setAllPositions</code> which is pascal case, but you have <code>moveall</code> which all lower caps. Also your data members are all lower case, which makes it harder to read.</li>\n<li>Don't use <code>this</code> unless you need to explicitly address the current object.</li>\n<li><code>velocity</code> serves no role; the <code>moveall</code> method acts directly upon the positions. You don't need a <code>velocity</code> member since you're not using it.</li>\n<li>Naming could a lot better. <code>moveall</code> makes me think that <code>Node</code> contains more than one positions that need to be updated. A simple <code>move</code> is good enough. Similarly, <code>setPosition</code> works just as well, without confusing the reader.</li>\n</ol>\n\n<h1>List.h</h1>\n\n<ol>\n<li>Again, naming is bit weird. You have members <code>arr</code>, <code>head</code>, <code>tail</code>, but also have <code>m_nodeStorage</code>, <code>m_randomGenerator</code>, etc. with the <code>m_</code> prefix. Pick a single style. Also there is weird mix of pascal case and snake case. Methods are hard to read because they're all lower.</li>\n<li>Why do you have an <code>std::deque</code>? A list should only contain pointers to head and tail. Storing all the nodes again defeats the purpose of a list.</li>\n<li>You don't need <code>inline</code>. The compiler is smarter than anyone who decides to <code>inline</code> their functions and methods.</li>\n<li>Why are the random utilities <code>static</code>? A better approach would be have them as instance members, so each list has its own random utilities. You're also seeding the generator with the same value, which defeats the purpose of a random generator.</li>\n<li>Why is an <code>uniform_real_distribution</code> called <code>m_gaussian_position</code>? It's just confusing; C++ has a normal distribution if you want to use it.</li>\n</ol>\n\n<h1>Engine.h</h1>\n\n<ol>\n<li>I don't understand the purpose of this class. All it is doing is inheriting from a <code>List</code>, with a few additional functions. And it seems like some methods can be directly be a part of <code>List</code>, such as <code>calculatedsortedpositions</code>. A better approach would be to have List as a member of the class.</li>\n<li><code>G</code> provides me with no information about its purpose. </li>\n<li><code>normalisedvector</code> and <code>vectormagnitude</code> have absolutely nothing to with any of those class. A better approach would be have them as standalone functions, wrapped in a namespace.</li>\n<li>Naming.</li>\n</ol>\n\n<p>Also, use a namespace.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T19:32:28.810",
"Id": "241451",
"ParentId": "241361",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T11:22:33.590",
"Id": "241361",
"Score": "2",
"Tags": [
"c++",
"sfml"
],
"Title": "C++/SFML Visualisaiton of doubly linked list"
}
|
241361
|
<p>As I have recently been selected to participate in my country's final preselection to the IOI -- this took me aback -- I have decided to get a bit more serious about competetitive programming.</p>
<p>The Rock-Paper-Scissors Tournament is an old question form the Waterloo Programming Contest 2005-09-17, available on <a href="https://open.kattis.com/problems/rockpaperscissors" rel="nofollow noreferrer">kattis</a>.</p>
<p>What it asks you to do is: </p>
<p>You first get two numbers n and k for the number of participants and the number of games played in the tournament.
And then you get k lines detailing every one of those games.
Using this data you have to output the winrate for each contestant in three decimal places.
A player that has not played a single game throughout the tournament should get a '-' as output.</p>
<p>A zero for the number of players terminates the program.</p>
<pre><code>2 4
1 rock 2 paper
1 scissors 2 paper
1 rock 2 rock
2 rock 1 scissors
2 1
1 rock 2 paper
0
</code></pre>
<p>Should give the output</p>
<pre><code>0.333
0.667
0.000
1.000
</code></pre>
<p>As far as I know my solution, which follows below, solves this problem perfectly, but, sadly, it is too slow.</p>
<p>My question is, does anyone see where I made a suboptimal choice in the datatype I used or how I calculated a result that causes my program to fail to beat the timelimit? I hope that understanding what I could have done better here allows me to become a better programmer in the future.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <iomanip>
#include <vector>
#include <unordered_map>
std::unordered_map< std::string, std::unordered_map<std::string, int> >
result(
{
{
"rock",
{
{"rock", 0},
{"paper", -1},
{"scissors", 1}
}
},
{
"paper",
{
{"rock", 1},
{"paper", 0},
{"scissors", -1}
}
},
{
"scissors",
{
{"rock", -1},
{"paper", 1},
{"scissors", 0}
}
}
});
int main() {
int n,
k,
p1,
p2;
std::string m1,
m2;
while (1) {
std::cin >> n;
if (n == 0) {
break;
}
std::cin >> k;
std::vector<int> wins(n, 0);
std::vector<int> losses(n, 0);
while (k--) {
std::cin >> p1;
std::cin >> m1;
std::cin >> p2;
std::cin >> m2;
int v = result[m1][m2];
if (v == 1) {
wins[p1-1]++;
losses[p2-1]++;
} else if (v == -1) {
losses[p1-1]++;
wins[p2-1]++;
}
}
std::cout << std::fixed;
std::cout << std::setprecision(3);
for (int i = 0; i < n; i++) {
float numOfWins = (float)wins[i];
float numOfGames = (float)(wins[i]+losses[i]);
if (numOfGames != 0) {
std::cout << numOfWins/numOfGames << std::endl;
} else {
std::cout << '-' << std::endl;
}
}
std::cout << std::endl;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>The choice of data structure is fundamentally sound (but more on that later).</p>\n\n<p>The first thing that jumped out to me in your code is actually not directly related to performance: you could drastically improve readability by declaring variables where you use them rather than at the beginning, and by assigning better names. Don’t be afraid that declaring variables inside a loop will lead to performance degradation! First off, in most cases <em>it doesn’t</em>. And secondly, where it does the difference in performance is usually negligible, and <em>will not contribute sufficiently to be noticed</em>. If, <em>and only if</em>, that’s not the case does it make sense to change this.</p>\n\n<p>Some more points regarding readability:</p>\n\n<ol>\n<li>Since you’re already using uniform initialisation, use <code>{…}</code> instead of <code>(…)</code> in your initialisation of <code>result</code>. Writing <code>({…})</code> is pretty unusual and consequently tripped me up.</li>\n<li>Since C++11 there’s no need to put a space between template argument list terminators (<code>> ></code> vs. <code>>></code>).</li>\n<li>Don’t use integer literals in place of boolean values: don’t write <code>while (1)</code>, write <code>while (true)</code>.</li>\n<li>Your (C-style) casts to <code>float</code> are unnecessary. Remove them.</li>\n<li>Make more variables <code>const</code> — in particular <code>result</code>! You don’t want to accidentally modify that. You will also need to change your lookup to using <code>find</code> then, unfortunately.</li>\n</ol>\n\n<p>Now on to performance improvements. There are effectively two things to improve.</p>\n\n<p>First off, two things about <code>unordered_map</code>:</p>\n\n<ol>\n<li>Although the choice of this structure is algorithmically correct, C++’s standard library specification of it is <em>poor</em> due to a fault in the standard wording, which forbids efficient implementations. The structure is therefore a cache killer.</li>\n<li>In your case a general string hash is overkill: you only need to check the first letter of each word to determine which move was played.</li>\n</ol>\n\n<p>You could exploit the second point by providing a custom <code>Hash</code> template argument to <code>std::unordered_map</code> which only returns the first character. But given the first point, I would suggest ditching <code>std::unordered_map</code> altogether and just using a 256×256 array as a lookup table (or, if you want to optimise space, subtract some common value from the first character or find a <a href=\"https://en.wikipedia.org/wiki/Perfect_hash_function\" rel=\"nofollow noreferrer\">perfect hash function</a> for the letters “r”, “p” & “s”).<sup>1</sup></p>\n\n<p>And now something more mundane, since the execution time of your program is at any rate completely dominated by IO: <code>std::cin</code> and <code>std::cout</code> are by default synchronised with C’s buffered standard IO, which makes them excruciatingly slow. To fix this, put <a href=\"https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio\" rel=\"nofollow noreferrer\"><code>std::ios_base::sync_with_stdio(false)</code></a> a the beginning of your <code>main</code> function. Similarly, untie standard output from standard input via <a href=\"https://en.cppreference.com/w/cpp/io/basic_ios/tie\" rel=\"nofollow noreferrer\"><code>std::cin.tie(nullptr)</code></a>. Secondly, replace <code>std::endl</code> with <code>\"\\n\"</code>. <code>std::endl</code> flushes the stream each time, which is slow. It’s also unnecessary to set the stream format manipulators in every loop (although I don’t expect this to change the performance).</p>\n\n<p>— It’s worth noting that none of that had a measurable impact on the performance of the code on my machine. In fact, <em>formatted input via <code>std::cin</code></em> totally dominates the runtime. This is surprising and disappointing (because there’s no reason for it: it hints at a broken standard library implementation). Using <code>scanf</code> is significantly faster, which should not happen. Of course using <code>scanf</code> also requires changing the type of <code>m1</code> and <code>m2</code> (you can use a static buffer of size <code>sizeof \"scissors\"</code>). It’s worth emphasising that it’s really IO that’s slow, and not the <code>std::string</code>s: simply replacing the <code>std::strings</code> with static buffers has almost no perceptible impact on runtime (likely due to <a href=\"https://stackoverflow.com/a/21710033/1968\">SSO</a>). It’s really <code>std::cin</code> vs <code>scanf</code>.</p>\n\n<hr>\n\n<p><sup>1</sup> We’re in luck, and the character codes of “r”, “p” and “s” in common encodings differ in the lower two bits, so that we only need a 4×4 lookup and minimal recoding:</p>\n\n<pre><code>static int const result[4][4] = {\n// p r s\n { 0, 0, 1, -1}, // paper\n { 0, 0, 0, 0},\n {-1, 0, 0, 1}, // rock\n { 1, 0, -1, 0} // scissors\n};\n\n…\n\nint const winner = result[move1[0] & 3][move2[0] & 3];\n</code></pre>\n\n<p>But of course given what I said about the IO bottleneck that’s completely unnecessary obfuscation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:08:28.167",
"Id": "473787",
"Score": "0",
"body": "You forgot to untie the input and output streams. The reason `std::cin` is slow is that reading from it forces a flush of `std::cout` first. `std::cin.tie(nullptr);` For interactive programs this is required but for streaming applications like coding competitions this just degrades performance. When you think the compiler or standard library are broken its usually you forgetting something. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:14:13.120",
"Id": "473789",
"Score": "1",
"body": "Niece optimization of the lookup array. I would argue that this is less expressive than the original in terms of intent and thus for maintenance (and general good programming practice) should be highly commented or wrapped in its own class (with comments)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:20:33.330",
"Id": "473791",
"Score": "0",
"body": "@MartinYork `std::cin.tie(nullptr)` doesn’t change the performance measurably. And yes, of course the lookup array is terrible for readability and maintainability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:21:45.793",
"Id": "473810",
"Score": "0",
"body": "When I use tie. The `fscanf()` vs `std::cin versions run in the same time. If I don't use `tie(nullptr)` then `std::cin` version runs three times slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:29:40.280",
"Id": "473812",
"Score": "0",
"body": "See me answer for the code I use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:29:51.207",
"Id": "473813",
"Score": "0",
"body": "@MartinYork Can’t reproduce this on Apple LLVM 10.0.1, nor with g++ 7.5.0 on Ubuntu 18.04, and `scanf` is also not just three times faster but (on a sufficiently large input) more like ten times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:37:54.673",
"Id": "473814",
"Score": "0",
"body": "I provided the code I used below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:41:25.360",
"Id": "473815",
"Score": "0",
"body": "@MartinYork Funny enough your code doesn’t show the difference either. However, if I compile it with `-DUSE_SCANF` it actually becomes *slower*. My command line is `g++ -std=c++17 -pedantic -Wall -Wextra -O3 martin.cpp -o martin`. But the variation is well within the noise."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T13:13:26.627",
"Id": "241365",
"ParentId": "241362",
"Score": "2"
}
},
{
"body": "<p>Using Konrad's recomendations.</p>\n\n<p>Did some more work. Now it runs in 0.03 second on the site. <a href=\"https://open.kattis.com/problems/rockpaperscissors/statistics\" rel=\"nofollow noreferrer\">Rock Paper Scissors Info</a> Currently at position 7 using C++ streams.</p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <unordered_map>\n#include <locale>\n\nstatic int const result[4][4] = {\n // p r s\n { 0, 0, 1, -1}, // paper\n { 0, 0, 0, 0},\n {-1, 0, 0, 1}, // rock\n { 1, 0, -1, 0} // scissors\n};\n\n\nclass FastInt\n{\n int& val;\n public:\n FastInt(int& v): val(v) {}\n\n friend std::istream& operator>>(std::istream& str, FastInt const& data)\n {\n auto buf = str.rdbuf();\n\n int c;\n while (std::isspace(c = buf->sbumpc()))\n {}\n\n data.val = c - '0';\n while (std::isdigit(c = buf->sbumpc())) {\n data.val = (data.val * 10) + (c - '0');\n }\n\n return str;\n }\n};\n\nclass FastString\n{\n char* val;\n public:\n FastString(char* v): val(v) {}\n\n friend std::istream& operator>>(std::istream& str, FastString const& data)\n {\n auto buf = str.rdbuf();\n\n int c;\n while (std::isspace(c = buf->sbumpc()))\n {}\n\n data.val[0] = c;\n int loop = 1;\n for (;!std::isspace(c = buf->sbumpc()); ++loop) {\n data.val[loop] = c;\n }\n data.val[loop] = '\\0';\n\n return str;\n }\n};\n\nint main()\n{\n //std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n\n std::cout << std::fixed\n << std::setprecision(3);\n\n struct T {\n int wins = 0;\n int loss = 0;\n };\n\n char lineBreak[] = \"\\0\";\n while (true)\n {\n int n = 0;\n std::cin >> FastInt(n);\n\n if (n == 0) {\n break;\n }\n\n int k;\n if (std::cin >> FastInt(k))\n {\n std::vector<T> games(n);\n\n std::cout << lineBreak;\n lineBreak[0] = '\\n';\n\n for (int gameCount = (k * n * (n -1))/2; gameCount; --gameCount)\n {\n int p1;\n int p2;\n char n1[20];\n char n2[20];\n if (std::cin >> FastInt(p1) >> FastString(n1) >> FastInt(p2) >> FastString(n2))\n {\n p1--;\n p2--;\n\n int v = result[n1[0] & 3][n2[0] & 3];\n\n if (v != 0)\n {\n games[(v == 1) ? p1 : p2].wins++;\n games[(v == 1) ? p2 : p1].loss++;\n }\n }\n }\n\n for (auto const& game: games)\n {\n int numOfWins = game.wins;\n int numOfGames = game.wins + game.loss;\n if (numOfGames != 0) {\n std::cout << (1.0 * numOfWins / numOfGames) << \"\\n\";\n } else {\n std::cout << \"-\\n\";\n }\n }\n }\n }\n //std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();\n //std::cerr << \"Time: \" << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << \"\\n\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:27:03.167",
"Id": "241435",
"ParentId": "241362",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241365",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T11:33:48.150",
"Id": "241362",
"Score": "2",
"Tags": [
"c++",
"performance",
"rock-paper-scissors"
],
"Title": "How can I speed up this solution to the \"Rock-Paper-Scissors Tournament\""
}
|
241362
|
<p>I feel like my code has way too much for what it is, this is my first project and would love to learn some tips in making code more efficient for the future, any other tips for my code here would be greatly appreciated.</p>
<pre><code>#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(0));
// yn = yes / no
string yn;
cout << "Do you want to play Rock, Paper, Scissors? (Enter: y or n) ";
cin >> yn;
if (yn == "y")
{
// rps = rock paper scissors
string rps;
cout << "Choose, Rock, Paper, or Scissors\n";
cin >> rps;
if (rps == "Rock")
{
// This outputs one of three choices and tells you if you've won, lost, or drew.
// rpslist is just the array list
// rpsnumber is just a random number to pick from the array
rock:
string rpslist[3] = { "Rock", "Paper", "Scissors " };
int rpsnumber = rand() % 3;
cout << "I choose: " << rpslist[rpsnumber];
if (rpslist[rpsnumber] == "Rock")
{
// One of three options here, win / lost / drew and a loop if you want to play again
// yna = yes or no, a is because the "Rock" option comes first, and b, c follows after
string yna;
cout << ", we draw! Do you want to play again? (Enter: y or n) ";
cin >> yna;
if (yna == "y") goto rock;
else (yna == "n"); goto exit;
}
else if (rpslist[rpsnumber] == "Paper")
{
string yna;
cout << ", you lose! Do you want to play again? (Enter: y or n) ";
cin >> yna;
if (yna == "y") goto rock;
else (yna == "n"); goto exit;
}
else if (rpslist[rpsnumber] == "Scissors");
{
string yna;
cout << ", you win! Do you want to play again? (Enter: y or n) ";
cin >> yna;
if (yna == "y") goto rock;
else (yna == "n"); goto exit;
}
}
else if (rps == "Paper")
{
paper:
string rpslist[] = { "Rock", "Paper", "Scissors" };
int rpsnumber = rand() % 3;
cout << rpslist[rpsnumber];
if (rpslist[rpsnumber] == "Rock")
{
string ynb;
cout << ", you win! Do you want to play again? (Enter: y or n) ";
cin >> ynb;
if (ynb == "y") goto paper;
else (ynb == "n"); goto exit;
}
else if (rpslist[rpsnumber] == "Paper")
{
string ynb;
cout << ", we draw! Do you want to play again? (Enter: y or n) ";
cin >> ynb;
if (ynb == "y") goto paper;
else (ynb == "n"); goto exit;
}
else if (rpslist[rpsnumber] == "Scissors");
{
string ynb;
cout << ", you lose! Do you want to play again? (Enter: y or n) ";
cin >> ynb;
if (ynb == "y") goto paper;
else (ynb == "n"); goto exit;
}
}
else if (rps == "Scissors")
{
scissors:
srand(time(0));
string rpslist[] = { "Rock", "Paper", "Scissors" };
int rpsnumber = rand() % 3;
cout << rpslist[rpsnumber];
if (rpslist[rpsnumber] == "Rock")
{
string ync;
cout << ", you lose! Do you want to play again? (Enter: y or n) ";
cin >> ync;
if (ync == "y") goto scissors;
else (ync == "n"); goto exit;
}
else if (rpslist[rpsnumber] == "Paper")
{
string ync;
cout << ", you win! Do you want to play again? (Enter: y or n) ";
cin >> ync;
if (ync == "y") goto scissors;
else (ync == "n"); goto exit;
}
else if (rpslist[rpsnumber] == "Scissors");
{
string ync;
cout << ", we draw! Do you want to play again? (Enter: y or n) ";
cin >> ync;
if (ync == "y") goto scissors;
else (ync == "n"); goto exit;
}
}
}
else yn == "n";
exit:
{
exit;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:04:55.573",
"Id": "473650",
"Score": "2",
"body": "Have you learned about functions yet, that generally reduces the repetition in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T17:47:48.463",
"Id": "473673",
"Score": "3",
"body": "@BCdotWEB We have at least 132 rock-paper-scissors questions, I think most of the good titles are taken."
}
] |
[
{
"body": "<ol>\n<li>The include statements are a weird mix of C++ and C header files. Use <code><chrono></code> for time, and use <code><random></code> for random functions.</li>\n<li><code>using namespace std;</code> is generally frowned upon. See here: <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a></li>\n<li>Again, use C++ STL random facilities instead of <code>srand</code> and <code>rand</code>. </li>\n<li>Don't use <code>goto</code>. You hardly need it nowadays, if ever. See here: <a href=\"https://stackoverflow.com/questions/3517726/what-is-wrong-with-using-goto\">https://stackoverflow.com/questions/3517726/what-is-wrong-with-using-goto</a></li>\n<li>Prefer using <code>std::array</code> to C-style arrays. It is just as performant, and allows you to utilize value semantics and STL iterator-based algorithms.</li>\n<li>You're creating <code>rpslist</code> in every conditional block. Instead, just create it once at the start, and keep using that.</li>\n</ol>\n\n<p>A lot of this code can be avoided using functions. Think about how control 'flows', and structure your program accordingly. You functions judiciously; make sure each function does one task only, and does it well. If a function is getting too big, identify parts which can be separated from it and put them into their own functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T06:58:33.013",
"Id": "241413",
"ParentId": "241366",
"Score": "3"
}
},
{
"body": "<p>(In addition to the <a href=\"https://codereview.stackexchange.com/a/241413/188857\">accepted answer</a>)</p>\n\n<p>We can first extract some commonly used code snippets in functions. Let's start with confirmation:</p>\n\n<pre><code>bool confirm_continue()\n{\n std::cout << \"Do you want to play again (y/n)? \";\n\n for (std::string input; std::getline(std::cin, input);) {\n if (input == \"y\") {\n return true;\n } else if (input == \"n\") {\n return false;\n }\n\n std::cout << \"Invalid input. Do you want to play again (y/n)? \";\n }\n\n throw std::runtime_error{\"Failed to read input\"};\n}\n</code></pre>\n\n<p>Note that invalid inputs are handled properly.</p>\n\n<p>Then, the winning criteria:</p>\n\n<pre><code>enum class Choice { rock, paper, scissors };\n\nenum class Result { draw, win, lose };\n\nvoid evaluate(Choice user_choice, Choice computer_choice)\n{\n static const std::map<Result, std::string_view> messages {\n { Result::draw, \"It's a draw.\" },\n { Result::win, \"You won.\" },\n { Result::lose, \"You lost.\" }\n };\n\n auto result = static_cast<Result>(\n (static_cast<int>(user_choice) - static_cast<int>(computer_choice) + 3) % 3\n );\n std::cout << messages.at(result) << '\\n';\n}\n</code></pre>\n\n<p>Choice input:</p>\n\n<pre><code>Choice input_choice()\n{\n static const std::map<std::string_view, Choice> table {\n { \"rock\" , Choice::rock },\n { \"paper\" , Choice::paper },\n { \"scissors\", Choice::scissors }\n };\n\n std::cout << \"Enter your choice (rock/paper/scissors): \";\n for (std::string input; std::getline(std::cin, input);) {\n if (auto it = table.find(input); it != table.end()) {\n return it->second;\n } else {\n std::cout << \"Invalid input. Enter your choice (rock/paper/scissors): \";\n }\n }\n\n throw std::runtime_error{\"Failed to read input\"};\n}\n</code></pre>\n\n<p>We can also use a choice generator:</p>\n\n<pre><code>Choice generate_choice()\n{\n static std::mt19937 engine{std::random_device{}()};\n\n std::uniform_int_distribution dist{0, 2};\n return static_cast<Choice>(dist(engine));\n}\n</code></pre>\n\n<p>Now the hard-to-follow structure with <code>goto</code>s can be improved by writing code that reflects the logic of the game:</p>\n\n<pre><code>do {\n auto user_choice = input_choice();\n auto computer_choice = generate_choice();\n\n show_choice(computer_choice);\n evaluate(user_choice, computer_choice);\n} while (confirm_continue());\n</code></pre>\n\n<hr>\n\n<p>Putting everything together:</p>\n\n<pre><code>#include <iostream>\n#include <map>\n#include <random>\n#include <string>\n#include <string_view>\n\nenum class Choice { rock, paper, scissors };\n\nenum class Result { draw, win, lose };\n\nvoid evaluate(Choice user_choice, Choice computer_choice)\n{\n static const std::map<Result, std::string_view> messages {\n { Result::draw, \"It's a draw.\" },\n { Result::win, \"You won.\" },\n { Result::lose, \"You lost.\" }\n };\n\n auto result = static_cast<Result>(\n (static_cast<int>(user_choice) - static_cast<int>(computer_choice) + 3) % 3\n );\n std::cout << messages.at(result) << '\\n';\n}\n\nbool confirm_continue()\n{\n std::cout << \"Do you want to play again (y/n)? \";\n\n for (std::string input; std::getline(std::cin, input);) {\n if (input == \"y\") {\n return true;\n } else if (input == \"n\") {\n return false;\n }\n\n std::cout << \"Invalid input. Do you want to play again (y/n)? \";\n }\n\n throw std::runtime_error{\"Failed to read input\"};\n}\n\nChoice generate_choice()\n{\n static std::mt19937 engine{std::random_device{}()};\n\n std::uniform_int_distribution dist{0, 2};\n return static_cast<Choice>(dist(engine));\n}\n\nChoice input_choice()\n{\n static const std::map<std::string_view, Choice> table {\n { \"rock\" , Choice::rock },\n { \"paper\" , Choice::paper },\n { \"scissors\", Choice::scissors }\n };\n\n std::cout << \"Enter your choice (rock/paper/scissors): \";\n for (std::string input; std::getline(std::cin, input);) {\n if (auto it = table.find(input); it != table.end()) {\n return it->second;\n } else {\n std::cout << \"Invalid input. Enter your choice (rock/paper/scissors): \";\n }\n }\n\n throw std::runtime_error{\"Failed to read input\"};\n}\n\nvoid show_choice(Choice choice)\n{\n static const std::map<Choice, std::string_view> table {\n { Choice::rock , \"rock\" },\n { Choice::paper , \"paper\" },\n { Choice::scissors, \"scissors\" }\n };\n std::cout << \"I chose \" << table.at(choice) << \".\\n\";\n}\n\nint main()\n{\n std::cout << \"Welcome to Rock, Paper, Scissors.\\n\";\n\n do {\n auto user_choice = input_choice();\n auto computer_choice = generate_choice();\n\n show_choice(computer_choice);\n evaluate(user_choice, computer_choice);\n } while (confirm_continue());\n}\n</code></pre>\n\n<p>Example session:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Welcome to Rock, Paper, Scissors.\nEnter your choice (rock/paper/scissors): rock\nI chose scissors.\nYou won.\nDo you want to play again (y/n)? y\nEnter your choice (rock/paper/scissors): scissors\nI chose rock.\nYou lost.\nDo you want to play again (y/n)? y\nEnter your choice (rock/paper/scissors): paper\nI chose scissors.\nYou lost.\nDo you want to play again (y/n)? n\n</code></pre>\n\n<p>(<a href=\"https://godbolt.org/z/mrF-md\" rel=\"nofollow noreferrer\">live demo</a>; the output is a mess because of non-interactive stdin)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T10:04:44.010",
"Id": "474164",
"Score": "0",
"body": "Thanks alot for this, I didnt expect anyone to put this much effort into a response, I am sure to take notes of this for later projects, thank you again :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T03:02:57.713",
"Id": "241594",
"ParentId": "241366",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241413",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T13:29:16.810",
"Id": "241366",
"Score": "1",
"Tags": [
"c++",
"rock-paper-scissors"
],
"Title": "C++, Reducing the amount of repeated code in a Rock Paper Scissors game"
}
|
241366
|
<p>I am rather new to python and am porting my R functions into python. I have written the functions below and the primary function is called <code>thetaMax</code>. That function minimizes a likelihood function or optionally minimizes a posterior distribution, depending on the option selected by method. The function works exactly as intended and I have unit tested this against my R code.</p>
<p>However, because I am not familiar with pythonic ways of doing this, I am curious what parts of the code below could be improved to 1) write less/more compact code and 2) to improve speed and take advantage of vectorization when possible? </p>
<p>A complete reproducible example is below</p>
<pre><code>import numpy as np
from scipy.stats import binom
from scipy.optimize import minimize
from scipy.stats import norm
def prob3pl(theta, a, b, c, D = 1.7):
result = c + (1 - c) / (1 + np.exp(-D * a * (theta - b)))
return(result)
def gpcm(theta, d, score, a, D = 1.7):
Da = D * a
result = np.exp(np.sum(Da * (theta - d[0:score])))/np.sum(np.exp(np.cumsum(Da * (theta - d))))
return(result)
def thetaMax(x, indDichot, a, b, c, D, d, method = 'mle', **kwargs):
method_options = ['mle', 'map']
optional_args = kwargs
if method not in method_options:
raise ValueError("Invalid method. Expected one of: %s" % method_options)
if method == 'map' and 'mu' not in optional_args:
raise ValueError("You must enter a value for 'mu' for the posterior distribution. Example, mu = 0")
if method == 'map' and 'sigma' not in optional_args:
raise ValueError("You must enter a value for 'sigma' for the posterior distribution. Example, sigma = 1")
x1 = x[indDichot]
x2 = np.delete(x, indDichot)
result = [0] * len(x2)
def fn(theta):
if(len(x1) > 0):
p = prob3pl(theta, a, b, c, D = D)
logDichPart = np.log(binom.pmf(x1,1,p)).sum()
else:
logPolyPart = 0
if(len(x2) > 0):
for i in range(0,len(x2)):
result[i] = gpcm(theta, d = d[i], score = x2[i], a = 1, D = D)
logPolyPart = np.log(result).sum()
else:
logPolyPart = 0
if(method == 'mle'):
LL = -(logDichPart + logPolyPart)
elif(method == 'map'):
normal = np.log(norm.pdf(theta, loc = optional_args['mu'], scale = optional_args['sigma']))
LL = -(logDichPart + logPolyPart + normal)
return(LL)
out = minimize(fn, x0=0)
return(out)
### In order to run
d = np.array([[0, -1, .5, 1],[0,-.5,.2,1]])
a = np.array([1,1,1,1,1])
b = np.array([-1,.5,-.5,0,2])
c = np.array([0,0,0,0,0])
#x = np.array([1,1,0,1,0])
x = np.array([1,1,0,1,0,1,1])
indDichot = range(0,5,1)
object = py.thetaMax(x,indDichot,a,b,c,D=1,d = d)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:10:20.810",
"Id": "473676",
"Score": "0",
"body": "This is not a \"complete reproducible example\": `NameError: name 'py' is not defined`"
}
] |
[
{
"body": "<h1>PEP-8 Violations</h1>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> enumerates many conventions that all Python code should follow. You have deviated from these conventions in several areas:</p>\n\n<ol>\n<li><code>mixedCase</code> is discouraged. Function names, methods and variable should all be <code>snake_case</code>. This means <code>thetaMax</code> should be called <code>theta_max</code>. (Exceptions are allowed for things like <code>Da</code>, where consistency with mathematical notation is more important than consistency with Python style.)</li>\n<li><code>return</code> is not a function call; it should not have parenthesis. Ie) <code>return(result)</code> should be written as <code>return result</code>.</li>\n<li><code>if</code> is also not a function call, nor is Python a C-like language; it should not have parenthesis. <code>if(method == 'mle'):</code> should be written as <code>if method == 'mle':</code></li>\n<li>Binary operators should have one space before and after it. This is only violated by the division operation in <code>gpcm</code> from my quick perusal of the code.</li>\n<li>Commas should be followed by one space.</li>\n<li>The equal sign used in <code>keyword=parameter</code> should not have a space before or after it. This applies both to the function definitions <code>def gpcm(theta, d, score, a, D=1.7):</code> and function calls <code>p = prob3pl(theta, a, b, c, D=D)</code></li>\n<li>Builtin Python identifiers should not be redefined without reason. <code>object</code> is such an identifier. A better name should be used.</li>\n</ol>\n\n<h1>Truthiness of lists.</h1>\n\n<p>A container used in a boolean context is <code>True</code> if the container is not empty, and <code>False</code> if the container is empty. There is no need to fetch the length of the container, test that value is greater than zero:</p>\n\n<pre><code>if x1:\n</code></pre>\n\n<p>is more \"Pythonic\" than:</p>\n\n<pre><code>if(len(x1) > 0):\n</code></pre>\n\n<h1>Ranges Start at Zero by Default</h1>\n\n<p>By default, all ranges start at 0. This means <code>range(0, len(x2))</code> is much more commonly written as <code>range(len(x2))</code>.</p>\n\n<h1>Iteration over a container</h1>\n\n<p>Python is a scripting language, where the script can assign its own implementation for many operations including subscripting, and iteration. This makes it impossible for Python to optimize code like:</p>\n\n<pre><code>for i in range(0, len(x2)):\n ... use the value x2[i] ...\n</code></pre>\n\n<p>It will usually be more efficiently written as:</p>\n\n<pre><code>for x2_i in x2:\n ... use the value x2_i ...\n</code></pre>\n\n<p>If the index is needed along with the values, then <code>enumerate()</code> is used for the most efficient result:</p>\n\n<pre><code>for i, x2_i in enumerate(x2):\n result[i] = gpcm(theta, d=d[i], score=x2_i, a=1, D=D)\n</code></pre>\n\n<p>Iterating over two (or more) parallel list (<code>d</code> and <code>x2</code>) would be done using zip:</p>\n\n<pre><code>for d_i, x2_i in zip(d, x2):\n ... = gpcm(theta, d=d_i, score=x2_i, a=1, D=D)\n</code></pre>\n\n<p>And if the indices are also needed, <code>enumerate(zip(...))</code>:</p>\n\n<pre><code>for i, (d_i, x2_i) in enumerate(zip(d, x2)):\n result[i] = gpcm(theta, d=d_i, score=x2_i, a=1, D=D)\n</code></pre>\n\n<p>But building up a complete array is more commonly done with list comprehension:</p>\n\n<pre><code>result = [ gpcm(theta, d=d_i, score=x2_i, a=1, D=D) for d_i, x2_i in zip(d, x2) ]\n</code></pre>\n\n<p>which eliminates the need for the <code>result = [0] * len(x2)</code> pre-allocation.</p>\n\n<h1>Keyword Arguments</h1>\n\n<p>What arguments can be passed to <code>thetaMax()</code>?</p>\n\n<p>The answer is \"any\". The user has no way of knowing what is possible, or allowed. You can pass <code>optimization_level=18</code> without error ... and without effect.</p>\n\n<p>It would be safer to define the function with the allowed keyword arguments explicitly:</p>\n\n<pre><code>def thetaMax(x, indDichot, a, b, c, D, d, method='mle', *, mu=None, sigma=None):\n\n if method not in {'mle', 'map'}:\n raise ValueError(\"Invalid method\")\n if method == 'map':\n if mu is None or sigma is None:\n raise ValueError(\"Both mu= and sigma= keyword arguments must be given\")\n elif method == 'mle':\n if mu is not None or sigma is not None:\n raise ValueErorr(\"Neither mu= or sigma= is appropriate for 'mle'\")\n</code></pre>\n\n<p>As a bonus, having the values already extracted into their own variables is faster than repeatedly looking up <code>optional_args['mu']</code> and <code>optional_args['sigma']</code> during each and every call of <code>fn()</code> during the minimize function.</p>\n\n<p>Additional speed may come from defining different <code>fn()</code> functions for the 6 different combinations of <code>len(x1) > 0</code>, <code>len(x2) > 0</code>, and <code>method</code>, thus removing the conditionals from inside the nested calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T20:13:52.060",
"Id": "473696",
"Score": "0",
"body": "wow, what a thorough and helpful review. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:34:07.333",
"Id": "241390",
"ParentId": "241367",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:13:04.330",
"Id": "241367",
"Score": "4",
"Tags": [
"python"
],
"Title": "Python Minimization Functions: Is the code optimal?"
}
|
241367
|
<p>I am learning Vue after working for some time with Angular and I'd like to hear experienced programmers concerning the implementation of my Progressive Bar service <em>(in Vue it's called Plugin)</em>.</p>
<p>The idea behind it is to have a solid service which is responsible for the progress bar indicator.</p>
<p>I've got there a component with the logic for displaying and hiding and CSS with HTML Mark-up. And the core which serves as a middleware (or a service in Angular) between the component and Providers <em>(vueRouter and Apollo)</em>.</p>
<p>I wasn't sure if it's a good practice to use RxJS in Vue. I've always thought that it's reactive itself but here I found it useful to have it. Is it a good practice?</p>
<p>It's still raw. Later on I'd like to make it customizable with options, but for now I'd like to know if I'm on the right way.</p>
<p>main.js</p>
<pre><code>import Vue from "vue";
import VueRx from 'vue-rx'
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { createProvider } from './vue-apollo'
import ProgressBar from '@/plugins/progressBarPlugin';
Vue.use(ProgressBar);
Vue.use(VueRx)
Vue.config.productionTip = false;
export default new Vue({
router,
store,
apolloProvider: createProvider(),
render: h => h(App)
}).$mount("#app");
</code></pre>
<p>index.js (progressBarPlugin)</p>
<pre><code>import ProgressBarComponent from './progress-bar/progress-bar.vue';
import apolloHook from './apolloHook.js';
import vueRouterHook from './vueRouterHook.js';
import { Subject } from 'rxjs'
import { distinctUntilChanged } from 'rxjs/operators'
export const state = new Subject().pipe(distinctUntilChanged());
const ProgressBarPlugin = {
install(Vue) {
Vue.component(ProgressBarComponent.name, ProgressBarComponent);
Vue.mixin({
created() {
if (this.$options.name === ProgressBarComponent.name) {
apolloHook(state, this.$apolloProvider);
vueRouterHook(state, this.$router)
}
}
})
},
request() {
state.next('request');
},
response() {
state.next('response');
},
done() {
state.next('done');
}
};
export default ProgressBarPlugin;
</code></pre>
<p>apolloHook</p>
<pre><code>export default function apollo(state, apolloProvider) {
if (apolloProvider) {
apolloProvider.watchLoading = function (loading) {
// This function can also accept param counter: -1 / 1
(loading) ? state.next('request') : state.next('done');
};
}
}
</code></pre>
<p>vueRouterHook</p>
<pre><code>export default function vueRouter(state, router) {
if (router) {
router.beforeEach((to, from, next) => {
state.next('request');
next();
state.next('response');
})
router.afterEach(() => {
state.next('done');
})
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:40:46.423",
"Id": "241368",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"vue.js"
],
"Title": "Progressive bar service in Vue"
}
|
241368
|
<p>I am a recent graduate in computer programming and failed so far to get an internship or a job in the business so I am trying my best to learn from online source.
I am trying to implement a dir-like command on Windows, going through a folder and list all files and folder.</p>
<p>What I've learned is to avoid <code>using namespace std;</code> and making the includes in alphabetical orders.</p>
<p>In this code, I am obviously mixing c and c++, good or bad?
I am also using Digital Mars as a compiler, I'm trying to avoid installing heavy IDEs and compilers like VS.</p>
<p>All thoughts and critiques are welcome.</p>
<pre><code>#include <iostream>
#include <io.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <windows.h>
bool DirectoryExists( const char* absolutePath ){
if( _access( absolutePath, 0 ) == 0 ){
struct stat status;
stat( absolutePath, &status );
return (status.st_mode & S_IFDIR) != 0;
}
return false;
}
char* replace(const char *s){
char* p = new char[strlen(s)+1];
int i=0;
for (i=0;s[i];i++)
if (s[i]=='\\')
p[i] ='/';
else
p[i]=s[i];
if (p[i-1] == '/')
p[i]='\0';
else
{
p[i]='/';
p[i+1]='\0';
}
return p;
}
void dirc (const char* destpath){
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
char filename[256];
size_t i=1;
if((hFind = FindFirstFile(destpath, &FindFileData)) != INVALID_HANDLE_VALUE)
{
do {
sprintf (filename, "echo %d-%s", i, FindFileData.cFileName);
system (filename);
i++;
}
while(FindNextFile(hFind, &FindFileData));
FindClose(hFind);
}
}
int main(int argc, char**argv) {
const char* path = argv[1];
char* fspath;
if (argv[1] == NULL)
{
std::cout <<"No path provided"<<std::endl;
return 0;
}
else
if ( DirectoryExists(path) )
std::cout <<"Provided path is "<<path<<std::endl;
else
{
std::cout <<"Path doesn't exist"<<std::endl;
return 0;
}
fspath = replace(path);
char* destpath = (char *) malloc (strlen(fspath)+6);
destpath = strcat (fspath,"*.*");
dirc (destpath);
free (destpath);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T13:38:23.507",
"Id": "473925",
"Score": "2",
"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 you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T18:31:31.190",
"Id": "473963",
"Score": "0",
"body": "Any reason this is tagged as `C`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T19:12:07.357",
"Id": "473970",
"Score": "0",
"body": "I took into consideration vdaghan comments and converted the whole stuff to C but it was against the rules."
}
] |
[
{
"body": "<p>Thous shalt not mix C/C++ unless you have a good reason to do so. Jokes aside, using pure C++ will lead more bug-free code (in terms of memory management etc.) especially since your statement</p>\n\n<blockquote>\n <p>What I've learned is to avoid using namespace std; and making the includes in alphabetical orders.</p>\n</blockquote>\n\n<p>implies (to me) you are a newcomer. You're welcome, by the way. That being said, learning C way of doing things is really helpful, especially if you are not familiar with pointers etc. You will experience first hand, say why C++ smart pointers and containers are a thing.</p>\n\n<p>My advice would be to study exactly why </p>\n\n<blockquote>\n <p>You should not mix C/C++ unless you have a good reason to do so.</p>\n</blockquote>\n\n<p>What you are doing with this code is nothing but plain C (except iostream methods). I did not check your code thoroughly though. So why do you want to use C++? If you want to use C++, why do you write C code and compile as C++ (again, except iostream, which can be as well stdio.h)?</p>\n\n<p>Since you are using Digital Mars, for which I can't find any standard compliance information, I am not sure if you can use C++17 STL. If you can, there is a <a href=\"https://en.cppreference.com/w/cpp/header/filesystem\" rel=\"noreferrer\">filesystem library</a> which can be used to do what you are trying to accomplish with a <a href=\"https://en.cppreference.com/w/cpp/filesystem/directory_iterator\" rel=\"noreferrer\">few lines of code</a>. If you can't, you can try to find a more up-to-date compiler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T12:26:28.010",
"Id": "473781",
"Score": "0",
"body": "Thanks, yes I am a newcomer, you're right, as for digital mars compiler, it is really a small zip file that can be uncompressed and used on any PC without downloading GB of stuff that I have no idea (at least now) what it does. Another question, assume I work at Microsoft and asked to implement such program, is this the way to present it to my manager or each method should be in a separate file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T00:40:09.393",
"Id": "473879",
"Score": "1",
"body": "No, I wouldn't do that unless explicitly asked for. This format is fine (except indentation), assuming it works. Note that I did not, and won't check platform-specific (essentially) C code and embarrass myself. There are many people who knows much more about these. But I insist on using a \"proper\" compiler with C++17 support if you can. If not, try to get rid of malloc/free, char* to make your code \"more C++\". If we are talking about modern C++, get rid of new/delete too. I am emphasizing this because I can see you have `new` character array in `replace()` which is not `delete`d."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T21:01:53.443",
"Id": "241397",
"ParentId": "241369",
"Score": "5"
}
},
{
"body": "<p>Welcome to the C++ community. You will find a lot of people with outspoken opinions about C++, variating from finding compatibility with C very important to those who find it very dangerous (even in a single person). My opinion: Avoid C unless you have a valid reason to do so, in which case, provide a C API and write the other code in pure C.</p>\n\n<p>Before diving into the code, a small remark: C++17 has <code>std::file_system</code> with a better API than the Windows API. </p>\n\n<p>So to the code:</p>\n\n<ul>\n<li><code>const char *</code> is something to avoid, <code>std::string_view</code> and <code>std::string</code> are much better alternatives.</li>\n<li>Don't write <code>struct stat status;</code>, <code>stat status;</code> is sufficient and will confuse less c++ programmers</li>\n<li>Don't declare variables at the top of the function (main), just declare them where you need them</li>\n<li>Use <code>nullptr</code> instead of <code>NULL</code></li>\n<li>Don't mix <code>malloc</code> and <code>new</code>, use the latter in C++</li>\n</ul>\n\n<p>(PS: For the details, please search online, they can motivate it much better than myself)</p>\n\n<p>If I would be doing your review for a C++ job, I don't like this kind of code to show up. HOWEVER even with that, you could still be hired, cause those things can be taught. What's more important is that you can show how to think about a problem and that you understand C++ concepts.</p>\n\n<p>My next question to you let you show off your knowledge about how to write classes. Public, protected, private, and when to use it. Member functions and variables. How the this-pointer works. What RAII is ...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T19:19:41.190",
"Id": "473971",
"Score": "0",
"body": "I am using C because to the best best of my knowledge both Windows and Unix were written in C and I really love low level programming. The weird thing that ```new``` compiled in Digital Mars only using C headers. My online search gave me basically 2 options either declare ```*p``` as static or free it in main. Any suggestions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T19:56:29.093",
"Id": "473978",
"Score": "0",
"body": "Switch to LLVM or MSVC as compiler?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T12:58:46.063",
"Id": "474051",
"Score": "0",
"body": "Why not, but I was reading that I should learn about compilers and their files and structures, it is hard enough with a 10 MB compiler let alone these 2 and their huge installation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T18:30:52.413",
"Id": "241515",
"ParentId": "241369",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241397",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:44:55.420",
"Id": "241369",
"Score": "3",
"Tags": [
"c++",
"c"
],
"Title": "A primitive folder listing implementation on Windows"
}
|
241369
|
<p>I'm a beginner python programmer..I recently started reading a python book called: <strong><em>"Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming"</em></strong>...And I found an interesting challenge...The challenge is to copy the elements of the list to another list and change the elements to make them become lowercase...I solved the challenge by myself and wrote two versions for it...</p>
<p>Here is my first attempt:</p>
<pre><code>#Method1: Using the slice method
currentUsers = ['MrSplash', 'MrRobot', 'Peter1234', 'Steve', 'James']
newUsers = ['Davidpeterson', 'Elliot345', 'STEVE', 'mrRobOt', 'NickB3ns0N']
currentUsersLower = currentUsers[:]
for i in range(0, 5):
currentUsersLower[i] = currentUsersLower[i].lower()
</code></pre>
<p>And here is my second attempt:</p>
<pre><code>#Method2: Using a normal for loop
currentUsers = ['MrSplash', 'MrRobot', 'Peter1234', 'Steve', 'James']
newUsers = ['Davidpeterson', 'Elliot345', 'STEVE', 'mrRobOt', 'NickB3ns0N']
currentUsersLower = []
for user in currentUsers:
currentUsersLower.append(user.lower())
</code></pre>
<p>My first question is this: Imagine we are working with around a million elements here. <strong>Which of these methods is efficient?</strong></p>
<p>I define <strong><em>efficient</em></strong> as:</p>
<ul>
<li>Easy to maintain and read</li>
<li>Performance-wise(Because let's face it, a million elements requires a lot of performance here)</li>
</ul>
<p>My second question is this: <strong>Are there better ways to do this task than the ones I presented here?</strong>
If so please share them as an answer here</p>
<p><strong>Note</strong>: The code works on both Python 3 and 2.</p>
|
[] |
[
{
"body": "<p>Your second version is better than your first version, for two reasons:</p>\n\n<ol>\n<li>All else being equal, building a new list is IMO easier to reason about than changing a list you're iterating over.</li>\n<li>You're iterating using <code>for...in</code> rather than iterating by index using a range (and the range in your first example is hardcoded rather than being over the <code>len</code> of the list, which is doubly bad).</li>\n</ol>\n\n<p>The most efficient/pythonic way is to use the comprehension syntax:</p>\n\n<pre><code>currentUsersLower = [user.lower() for user in currentUsers]\n</code></pre>\n\n<p>(Also, standard Python style would be to name these <code>current_users</code> and <code>current_users_lower</code>!)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:26:55.873",
"Id": "473655",
"Score": "0",
"body": "Thank you for your answer...I really like the list comprehension method but at the time I was programming, I totally forgot about this method too(LOL...I guess I was tired)...But one thing...Is it actually bad to use camel case method for naming variables and lists here?(I'm asking because I want to make sure If it's a bad practice or not)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:30:57.937",
"Id": "473656",
"Score": "2",
"body": "It's not \"bad\" in terms of making your code not work, but it will make it not look like most other Python code, and almost everyone who reviews your code will comment on it. Best to just drink the kool-aid. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:32:58.867",
"Id": "473657",
"Score": "2",
"body": "See: https://www.python.org/dev/peps/pep-0008/#function-and-variable-names It's pretty common for Python devs to use a linter that will auto-correct and/or complain when you violate these style guidelines, so violations of them stand out like misspellings once you're thoroughly indoctrinated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:59:48.320",
"Id": "241371",
"ParentId": "241370",
"Score": "2"
}
},
{
"body": "<p>A1) Apart from efficiency issues, neither of these methods are <code>pythonic</code> from the Python point of view. But, If I had to choose one, I would choose the second one.\nBecause, First is not general way in python.</p>\n\n<p>A2) I think it would be better to use <code>List comprehension</code> because it is the most efficient in terms of memory performance. You can check it out on <a href=\"https://nyu-cds.github.io/python-performance-tips/08-loops/\" rel=\"nofollow noreferrer\">this site</a></p>\n\n<p>In the case of me,</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Using list comprehension\n\nIn [1]: current_users = ['MrSplash', 'MrRobot', 'Peter1234', 'Steve', 'James']\n\nIn [2]: current_users_lower = [user.lower() for user in current_users]\n\nIn [3]: print(current_users_lower)\n['mrsplash', 'mrrobot', 'peter1234', 'steve', 'james']\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code># Another way is to use map\n\nIn [5]: current_users_lower = list(map(str.lower, current_users))\n\nIn [6]: print(current_users_lower)\n['mrsplash', 'mrrobot', 'peter1234', 'steve', 'james']\n\n</code></pre>\n\n<p>I think it would be written as above.</p>\n\n<p>cc. python official convention about variable is <code>snake_case</code> not <code>camelCase</code> (I recommend to read PEP8 which is python official style guide)</p>\n\n<p>Happy Coding~</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T13:00:34.740",
"Id": "241492",
"ParentId": "241370",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:51:59.027",
"Id": "241370",
"Score": "1",
"Tags": [
"python",
"beginner",
"comparative-review"
],
"Title": "Copying List Elements To Another List And Changing Them"
}
|
241370
|
<p>Is my approach to insertion Sort in Python efficient?</p>
<p>What can be improved efficiency wise?</p>
<pre><code>def insertion_sort(array):
sorted_array = []
for elem in array:
insertion_index = len(sorted_array) #insert at end of list by default
for elem_sorted in sorted_array:
if elem_sorted > elem:
insertion_index = sorted_array.index(elem_sorted)
break
sorted_array.insert(insertion_index, elem)
return sorted_array
num_elems = int(input('Number Of Elements?: '))
array = [int(input(f'Enter Number#{i+1}: ')) for i in range(num_elems)]
a = insertion_sort(array)
print(a)
</code></pre>
|
[] |
[
{
"body": "<p>You are looping over the array elements, and once you find an element greater than the element you are about to insert, you have to again find that element in the array of elements.</p>\n\n<pre><code> insertion_index = len(sorted_array)\n for elem_sorted in sorted_array:\n if elem_sorted > elem:\n insertion_index = sorted_array.index(elem_sorted)\n break\n</code></pre>\n\n<p>You could instead use <code>enumerate</code> to extract both the element and its index:</p>\n\n<pre><code> insertion_index = len(sorted_array)\n for index, elem_sorted in sorted_array:\n if elem_sorted > elem:\n insertion_index = index\n break\n</code></pre>\n\n<p>When you search for an element using a <code>for</code> loop and <code>break</code> when you find the element of interest, if you don't find the element, the <code>for</code> loop will execute an optional <code>else:</code> clause, so you don't need to preset the <code>insertion_index</code>:</p>\n\n<pre><code> for index, elem_sorted in sorted_array:\n if elem_sorted > elem:\n insertion_index = index\n break\n else:\n insertion_index = len(sorted_array)\n</code></pre>\n\n<h1>Biggest inefficiency</h1>\n\n<p><code>sorted_array</code> is in sorted order. You could use a binary search to find the insertion location, <span class=\"math-container\">\\$O(\\log N)\\$</span>, instead of a linear search <span class=\"math-container\">\\$O(N)\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T04:58:11.373",
"Id": "473722",
"Score": "1",
"body": "Second advice is very wrong. Search will be necessarily followed by insertion, which is \\$O(N)\\$, and binary serch will drive the overall complexity to \\$O(N*(N + \\log N))\\$. Insertion sort uses linear search for the reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T05:07:59.397",
"Id": "473724",
"Score": "0",
"body": "@vnp Linear search + linear insertion is \\$O(N + N)\\$, which is \\$O(N)\\$. Binary search + linear search is \\$O(\\log N + N)\\$, which is still \\$O(N)\\$, since \\$O(\\log N) \\lt O(N)\\$. Total complexity is \\$O(N^2)\\$ either way. A binary search should still speed up the algorithm, but without improving the overall time complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T18:38:33.250",
"Id": "473846",
"Score": "0",
"body": "Linear search + linear insertion is _not_ \\$O(N + N)\\$. This would be the case if the insertion started from the beginning. On the contrary, the insertion starts from the insertion point, which search would return. Together search and insertion do one pass over the array. Compare it with the binary search worst case (all insertions are into the beginning of the array)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T22:33:34.610",
"Id": "473867",
"Score": "1",
"body": "@vnp Shall we continue this in [chat](https://chat.stackexchange.com/rooms/107376/insertion-sort-discussion-vnp-ajneufeld)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T22:30:53.623",
"Id": "241402",
"ParentId": "241374",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241402",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:22:18.213",
"Id": "241374",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"sorting",
"reinventing-the-wheel"
],
"Title": "Insertion Sort Implementation Efficiency"
}
|
241374
|
<p>Here i have javascript code where is 'animals' object and 'people' array of objects. User selects the data from select box and accordingly table fills with selected data(which is array of objects) and when user wants to reset everything to the state before selected data, user just clicks 'backtozero' button.
the code is a little complicated to understand for beginners specially two 'for loops'(i know foreach but maybe someting else ?) and also information which is inside of 'addEventListeners function' any suggestion for making whole thing easier to read for beginners ? feel free to make changes : </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>let animals
let animalCols = ['Animal', 'Animal 2']
let peopleCols = ['Person', 'Person 2']
function myFunction() {
paivitys(animals, animalCols)
}
function paivitys(dataa, arvvoja) {
console.log(dataa);
//----
if (dataa.hasOwnProperty("animal")) {
document.getElementById("1name").innerHTML = dataa.animal;
} else {
document.getElementById("1name").innerHTML = dataa.person;
}
//----
if (dataa.hasOwnProperty("animal2")) {
document.getElementById("2name").innerHTML = dataa.animal2;
} else {
document.getElementById("2name").innerHTML = dataa.person2;
}
document.getElementById("1name1").innerHTML = arvvoja[0];
document.getElementById("2name1").innerHTML = arvvoja[1];
//-----
document.getElementById("id").innerHTML = dataa.id;
}
function paivitaselekt(araytassa, arvvoja) {
var i, j;
for (i = 0; i < araytassa.length; i++) {
var ssellecct = document.getElementById("Select");
var oppttion = document.createElement("option");
for (j = 0; j < arvvoja.length; j++) {
oppttion.textContent += araytassa[i][arvvoja[j]] + " ";
}
ssellecct.appendChild(oppttion);
}
}
animals = {
"animal": "tiger",
"animal2": "lion",
"id": "54321",
"dole": {
"Key": "fhd699f"
}
}
paivitys(animals, animalCols);
let infoarray;
people = [{
"person": "kaka",
"person2": "julle",
"id": "9874",
},
{
"person": "Ronaldo",
"person2": "jussi",
"id": "65555",
}
]
infoarray = people;
paivitaselekt(infoarray, ["person", "id"]);
document.getElementById("Select").addEventListener("change", function(event) {
const chosenid = event.target.value.split(" ")[1];
const choseninfo = infoarray.filter((dataa) => dataa.id === chosenid)[0];
paivitys(choseninfo, peopleCols);
}); </code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous"
/>
<style>
</style>
</head>
<body>
<div class="">
<table class="table ">
<thead>
<tr>
<th id="1name1" class="table-success">Animal</th>
<th id="2name1" class="table-success">Animal</th>
<th class="table-success">id</th>
</tr>
</thead>
<tbody>
<th id="1name"></th>
<th id="2name"></th>
<th id="id"></th>
</tbody>
</table>
<select id="Select" ></select>
<button onclick="myFunction()">backtozero</button>
</div>
</body>
</html>
</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T20:30:09.267",
"Id": "473698",
"Score": "1",
"body": "https://codereview.stackexchange.com/q/240745 ??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T20:31:34.757",
"Id": "473699",
"Score": "2",
"body": "Does this answer your question? [Suggestion for improving this code to be more readable and easy for beginners?](https://codereview.stackexchange.com/questions/240745/suggestion-for-improving-this-code-to-be-more-readable-and-easy-for-beginners)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T21:44:29.247",
"Id": "473703",
"Score": "2",
"body": "Better to edit the earlier identical question to make it clearer rather than to post a new one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T05:15:39.737",
"Id": "473726",
"Score": "0",
"body": "(You could try and use a spelling checker.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T11:13:18.433",
"Id": "473760",
"Score": "0",
"body": "Dear close voters, whilst the code is a duplicate lets take a step back and actually examine the situation. user222442's other post was closed for lacking a description, this post has a description. This post is on-topic the other post is not. Closing this question will only cause unnecessary grief for the OP and additional work for the community; we'll have to not only close this question but also reopen the other question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:06:23.200",
"Id": "473786",
"Score": "1",
"body": "@Peilonrayz Yes, but the proper way to handle this would be for the original question to be improved with the updates and go through the reopen process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:15:01.303",
"Id": "473790",
"Score": "0",
"body": "I agree, the proper way to fix an off-topic question is to edit it and enter the re-open process. However since the OP didn't do that; the proper way is to only close off-topic questions."
}
] |
[
{
"body": "<ul>\n<li>Indent your code!</li>\n<li><p>Naming convention</p>\n\n<ul>\n<li>Only use English\n\n<ul>\n<li>paivitys -> update -> though really this should be with a subject, so <code>updateObjekt</code>?</li>\n<li>dataa -> data</li>\n<li>arvvoja -> values</li>\n<li>paivitaselekt -> updateSelection</li>\n</ul></li>\n<li>Dont mispel\n\n<ul>\n<li>ssellecct -> selectElement</li>\n<li>oppttion -> option</li>\n</ul></li>\n<li><p>Use lowerCamelCase</p>\n\n<ul>\n<li>infoarray -> infoArray</li>\n<li>chosenid -> chosenId</li>\n<li>choseninfo -> chosenInfo</li>\n</ul></li>\n<li><p>myFunction -> this is an unfortunate name, it does not say anything about its functionality</p></li>\n<li>The names of your HTML elements id's can be improved</li>\n</ul></li>\n<li>Dont mix <code>var</code> and <code>const</code>/<code>let</code></li>\n<li>Don't <code>console.log()</code> in production code</li>\n<li>Comments should improve understanding, <code>//------</code> does not do that, just use newlines/whitespace</li>\n<li>Dont assign onclick events in html with <code>onclick</code>, use <code>addEventLister()</code></li>\n<li>It seems <code>people</code> is a global variable, don't create global variables</li>\n<li>It seems you create <code>people</code> and <code>infoarray</code>, then assign <code>people</code> to <code>infoarray</code>, and then never use <code>people</code> again. It does not seem to make sense</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T16:34:11.483",
"Id": "241381",
"ParentId": "241378",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:54:23.890",
"Id": "241378",
"Score": "0",
"Tags": [
"javascript",
"array",
"html",
"css",
"html5"
],
"Title": "Data selection and filtering"
}
|
241378
|
<p>I am working on this project where I like to PreserveIds once inserted into the database. The id are auto incrementing and I return them once the data in inserted. I like to know if there is a better way using inheritance vs using a for each loop and checking if the value is 0?</p>
<pre><code> class Program
{
static void Main(string[] args)
{
var States = new List<StatesModel>();
var CaliforniaCity = new List<CityModel>();
CaliforniaCity.Add(new CityModel() { Id = 2, Name = "Los Angeles" });
CaliforniaCity.Add(new CityModel() { Id = 3, Name = "Sacramento" });
CaliforniaCity.Add(new CityModel() { Id = 4, Name = "San Francisco" });
States.Add(new StatesModel() { Id = 1, Name = "California", CityModels = CaliforniaCity });
var PhiladelphiaCity = new List<CityModel>();
PhiladelphiaCity.Add(new CityModel() { Id = 5, Name = "Philadelphia" });
PhiladelphiaCity.Add(new CityModel() { Id = 6, Name = "Pittsburgh" });
PhiladelphiaCity.Add(new CityModel() { Id = 7, Name = "Harrisburg" });
States.Add(new StatesModel() { Id = 8, Name = "Pennsylvania", CityModels = PhiladelphiaCity });
var MichiganCity = new List<CityModel>();
MichiganCity.Add(new CityModel() { Id = 9, Name = "Detroit" });
MichiganCity.Add(new CityModel() { Id = 10, Name = "Lansing" });
MichiganCity.Add(new CityModel() { Id = 11, Name = "Grand Rapids" });
States.Add(new StatesModel() { Id = 12, Name = "Michigan", CityModels = MichiganCity });
///Insert Data in database
PreserveIds(States)
///Update data in database
foreach (var State in States)
{
Console.WriteLine(string.Format("{0}", State.Name));
Console.WriteLine(string.Format("{0} = {1}", State.Id ,State.OriginaId));
foreach (var city in State.CityModels)
{
Console.WriteLine(string.Format("{0}", city.Name));
Console.WriteLine(string.Format("{0} = {1}", city.Id, city.OriginaId));
}
}
}
public static void PreserveIds(IEnumerable<StatesModel> States)
{
if (States != null)
{
foreach (var State in States)
{
if (State.OriginaId == 0)
{
State.OriginaId = State.Id;
}
foreach (var city in State.CityModels)
{
if (city.OriginaId == 0)
{
city.OriginaId = city.Id;
}
}
}
}
}
}
Model
public class StatesModel
{
public int Id { get; set; }
public int OriginaId { get; set; }
public string Name { get; set; }
public List<CityModel> CityModels { get; set; }
public StatesModel()
{
CityModels = new List<CityModel>();
}
}
public class CityModel
{
public int Id { get; set; }
public int OriginaId { get; set; }
public string Name { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:23:56.913",
"Id": "473792",
"Score": "0",
"body": "I've got the feeling this is a \"Your Princess is in Another Castle\" problem. As in: you want to do something, but you cannot express what or why. What is the point of `OriginaId`? Why do you need to store this ID? Why do you use the old `String.Format`? Why don't you use \"modern\" initializers ( https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers )? To me, this question is far too vague."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:21:48.233",
"Id": "473811",
"Score": "0",
"body": "id is a database auto incrementing number which i get once I save the data into the database. But I also want that id to be inserted into the OriginaId field. there will be iterations of inserts and I will need a pointer to the original id from the first insert."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:51:11.813",
"Id": "473863",
"Score": "0",
"body": "I still can't make heads or tails of it. Why would you insert the same info again into another record? And what good would it do to have the ID of the first record stored into another record? Based on your example I don't even see the need for multiple inserts: things like cities and states don't just randomly change from day to day. Why would you have multiple records of Detroit for instance?"
}
] |
[
{
"body": "<p>I would change implementation if <code>Id</code> property in both your models into:</p>\n\n<pre><code>public class StatesModel\n{\n private int id;\n\n public int Id\n {\n get\n {\n return id;\n }\n set\n {\n id = value;\n\n if (OriginalId == 0)\n OriginalId = value;\n }\n }\n\n public int OriginalId { get; private set; }\n\n // (...)\n}\n\n// The same for CityModel\n</code></pre>\n\n<p>and remove your <code>PreserveIds</code> method all together. You can also add private setter to <code>OriginalId</code> just to make sure that nobody would override this value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:44:47.817",
"Id": "473679",
"Score": "0",
"body": "Can I do this if I am getting the Id from the database?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T17:57:28.247",
"Id": "241385",
"ParentId": "241379",
"Score": "1"
}
},
{
"body": "<p>If you're using Entity Framework, then you don't need to. Whenever you <code>SaveChanges()</code> it'll automatically update the current object with the auto generated id from the database.</p>\n\n<p>so the basic usage would be for instance like this : </p>\n\n<pre><code>var california = new StatesModel() { Name = \"California\", CityModels = CaliforniaCity };\nConsole.WriteLine($\"Id: {california.Id}\"); // here will be zero \ncontext.States.Add(california); \ncontext.SaveChanges(); \nConsole.WriteLine($\"Id: {california.Id}\"); // the new updated Id\n</code></pre>\n\n<p><a href=\"https://www.entityframeworktutorial.net/faq/how-to-get-id-of-saved-entity-in-entity-framework.aspx\" rel=\"nofollow noreferrer\">read more</a> about it</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T09:26:12.383",
"Id": "473745",
"Score": "0",
"body": "Right that part understand but that about the update for the OriginalId? I will need the id returned from the database then sql for the update ? I am using Linqtosql"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:20:08.083",
"Id": "473754",
"Score": "0",
"body": "@Jefferson in Linq To SQL, `context.SubmitChanges();` does the same. What's the purpose of the `OriginalId` ? as you already have `Id` .."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:45:50.337",
"Id": "473756",
"Score": "0",
"body": "I will different iterations of inserts and I will need a pointer to the original id from the First insert"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:53:09.087",
"Id": "473757",
"Score": "0",
"body": "@Jefferson if your `original id` is a reference to another `Id` that has been already inserted, then why not using foreign key (self-reference). ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T11:42:14.073",
"Id": "473773",
"Score": "0",
"body": "But this would be the same table. I was thinking a FOREIGN KEY is a field in one table that refers to the PRIMARY KEY in another table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T12:00:19.090",
"Id": "473777",
"Score": "0",
"body": "@Jefferson yes, that is true also. you can reference a PK column in the same table or a different table. so your case is called (self-reference) where the FK is referencing the same table's PK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T12:22:14.280",
"Id": "473780",
"Score": "0",
"body": "How would I do that with linq to sql?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:00:36.817",
"Id": "473800",
"Score": "0",
"body": "@Jefferson probably you need to read this https://www.codeproject.com/Articles/39104/LINQ-to-SQL-Many-to-Many-Relationships"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:19:11.433",
"Id": "473808",
"Score": "0",
"body": "is that the same thing? there is three table in that example I am just working with one table?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T02:10:36.493",
"Id": "241406",
"ParentId": "241379",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T16:11:11.423",
"Id": "241379",
"Score": "2",
"Tags": [
"c#",
"inheritance"
],
"Title": "PreserveIds using inheritance id db auto incrementing"
}
|
241379
|
<p>I know I never have to reinvent the wheel, but I did, because I need speed performance, also I need this features:</p>
<ul>
<li>introspection or metaprogramming </li>
<li>actuate like api backend</li>
<li>private variables interpolation</li>
<li>embedded perl code inside template like text template </li>
<li>avoid in the minimal no core modules</li>
<li>work with eval in environment secure (Eval::Closure)</li>
<li>have block or macros to procces behavior like subroutines when you used block html and code perl</li>
</ul>
<p>Template::Toolkit, has almost all features listed above but is slow</p>
<p>Is this code good?</p>
<pre><code>package Myapp::Template;
use strict;
use warnings;
use Eval::Closure;
use B qw( perlstring );
use Carp qw( confess );
sub new {
my $class = shift;
return bless {}, $class;
}
sub parser {
my ($self, $html_file, $hash ) = @_;
my @delims = qw( [% %] );
my $regexp = join('|', map quotemeta($_), @delims);
my @code;
push @code, 'sub {';
push @code, 'my $OUT = q();';
map { push @code, 'my $'.$_.' = "'.$hash->{$_}.'"; ' } (keys %{$hash} );
my @parts = split /($regexp)/, $html_file;
my $mode = 'text';
while (@parts) {
my $next = shift @parts;
if ($next eq $delims[0]) {
$mode = ($mode eq 'text') ? 'code' : confess("Impossible state");
next;
}
if ($next eq $delims[1]) {
$mode = ($mode eq 'code') ? 'text' : confess("Impossible state");
next;
}
if ($mode eq 'text') {
$code[-1] .= sprintf('$OUT .= %s;', perlstring($next));
}
elsif ($next =~ /\A=/) {
$next =~ s/(\(\)|\(\s+?\))/\($self->{id_plugin}\)/g if exists $self->{id_plugin};
$code[-1] .= sprintf('$OUT .= do { %s };', unpack("x1A*", $next), );
}
elsif ($next =~ /\A\sBLOCK/) {
my $theblock = "sub " . unpack("x6A*", $next) . ' { my $OUT; ';
$code[-1] .= sprintf(" %s;", $theblock);
}
elsif ($next =~ /\A\sPROCESS/) {
my $runsub = unpack("x8A*", $next);
$code[-1] .= sprintf('$OUT .= %s;', $runsub . "();");
}
elsif ($next =~ /\A\sEND/) {
my $theblock = 'return $OUT; } ';
$code[-1] .= sprintf(" %s;", $theblock);
}
else {
$code[-1] .= sprintf(" %s;", $next);
}
}
push @code, '$OUT;';
push @code, '}';
my ($thecode) = \@code;
return eval_closure( source => $thecode )->();
}
sub get_blocks {
my $self = shift;
my $html_file = shift;
my $thisblock = shift;
my $id_plugin = shift;
if (!defined $thisblock){
my @blocks = $html_file =~ /(?>BLOCK\s+)(\w+)/g;
return join "<br>", (@blocks);
}
else{
$self->{id_plugin} = $id_plugin;
my @blockprocess;
my @main_block;
my $check_block = sub {
my $the_block = shift;
for (split /\n/, $html_file) {
if (/(?>BLOCK\s+)($the_block)/../(END)/){
push @blockprocess, $1 if $_ =~ /(?>PROCESS\s+)(\w+)/;
push @main_block, $_;
}
}
};
$check_block->($thisblock);
map{ $check_block->($_) } @blockprocess;
push @main_block, "[% PROCESS $thisblock %]";
my $allbkocks = join "", @main_block;
return $self->parser($allbkocks);
}
}
1;
</code></pre>
<p>Example html with block and process</p>
<pre><code> [% BLOCK function_sub %]
<div class="box">example</div>
[% use Module::Runtime;
my $var = 'this is not printing here';
%]<div class="another">bla</div>
[%= $var; #print %]
[% END %]
<div class="dashboard widgetBox">
<div class="widgetTopBar">
[% PROCESS function_sub %]
</div>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T08:51:42.427",
"Id": "473908",
"Score": "0",
"body": "Can you give an example of how you use the code in a Perl script?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T17:01:58.927",
"Id": "241382",
"Score": "5",
"Tags": [
"template",
"perl"
],
"Title": "Custom template system with introspection in Perl"
}
|
241382
|
<p>**</p>
<p>Write the beginnings of a class for a Table implemented with a Binary Search Tree. (done)
Then create a Table class with only one data member for the root. (done)
Provide the following methods:
a constructor that produces an empty table (done)<br>
a method to insert a given item, (done)
Create a separate class for a Node, with public data members (data, left, right) to support the Table class. (done)
Use the following interface to declare the type of the data.
interface Sortable{ public int compareTo( Sortable b );} (done)
This does not have to be compiled and tested</p>
<p>**
Yes, this is a hw assignment (I'm not asking for it to be done for me, it should already be done if I understood it correctly), I'm asking for a code review and any help with commenting on my code (if anything is wrong would be lovely to know (like if my logic is off in a section so I can go to it and address it). I don't have access to tutors as easily now so using this to hopefully check my work and research what I am lacking in understanding is my goal. Otherwise, my train of thought I hope is on the right path to understanding this. Thanks</p>
<pre><code>package com.stackexchange.codereview;
interface Sortable {
public int compareTo(Sortable other);
// a.compareTo(b) returns 0 if a == b,
// -1 if a < b, and +1 if a > b
}
class TreeNode { // This is the separate class for node
public Sortable _data; // this is the data variable
public TreeNode left; // this stores left field
public TreeNode right; // this stores right field
}
class Table {
private TreeNode _root = null; // This is the table class with only data member head
public void insert(Sortable item) { // This insert a new item to the table
int compare = 0;
TreeNode current = _root;
TreeNode parent = null;
while (current != null) {
parent = current;
compare = item.compareTo(current._data);
if (compare == 0)
return;
if (compare < 0)
current = current.left;
else
current = current.right;
}
TreeNode add = new TreeNode();
add._data = item;
add.left = add.right = null;
if (parent == null)
_root = add;
else if (compare <= 0)
parent.left = add;
else
parent.right = add;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:43:19.327",
"Id": "473678",
"Score": "1",
"body": "Doesn't look like this will compile. `If` shouldn't be capitalized. `Sortabe` is missing an L, and so on. Copy the code from Eclipse and paste it in the question body; don't try to transcribe it in by hand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T19:20:03.593",
"Id": "473686",
"Score": "0",
"body": "Fixed the Sortable issue, and other mistakes created by putting it into a text editor first. I've been given conflicting information (some say use an ide to code, others say write it by hand first), was working on writing it by hand but that leads to other unforeseen issues, also thank you for looking it over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T22:27:33.457",
"Id": "473705",
"Score": "0",
"body": "I've added indentation. See it as a code review remark: terrible indentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T23:53:09.083",
"Id": "473714",
"Score": "0",
"body": "Yes, I should have ctrl +I another mistake (is ctrl +i) an acceptable/normal way to indent or?"
}
] |
[
{
"body": "<pre><code>// a.compareTo(b) returns 0 if a == b\n</code></pre>\n\n<p>That's a JavaDoc description, so put it between <code>/**</code> and <code>*/</code> and before the method. We never document anything on the next line. Preferably comments are before a code line, and sometimes behind it.</p>\n\n<pre><code>class TreeNode { // This is the separate class for node\n</code></pre>\n\n<p>The class should probably be a <code>static class</code> within the <code>Table</code> class instead. We try and only use one class per file in Java (and only one <code>public</code> class is actually allowed). You are using <code>public</code> fields, but that's not a good idea; you can give them package access level (no modifier) as long as you don't expose such an implementation class.</p>\n\n<pre><code>public Sortable _data; // this is the data variable\n</code></pre>\n\n<p>In Java we never start any data, including fields, with an underscore. Besides that, it is no different than <code>left</code> and <code>right</code>.</p>\n\n<pre><code>private TreeNode _root = null; // This is the table class with only data member head\n</code></pre>\n\n<p>Wrong place to document <code>Table</code>, again, JavaDoc. Fields are assigned <code>0</code>, <code>0.0</code> or indeed <code>null</code> by default, so there is no reason to do that explicitly.</p>\n\n<p>int compare = 0;</p>\n\n<p>This is a common mistake. The first thing you do with the variable is to assign it a value. In that case there is absolutely no need to assign it zero - and it might even hide errors later on.</p>\n\n<pre><code>if (compare == 0)\n return;\n</code></pre>\n\n<p>Always put code blocks between braces. Put an empty between the <code>if</code> and the next if so they don't look part of the same branching instruction.</p>\n\n<pre><code>TreeNode add = new TreeNode();\n</code></pre>\n\n<p><code>add</code> is not a good name for a variable. First of all, it's a verb, and variables are not actions. Try <code>nodeForItem</code>.</p>\n\n<pre><code>add.left = add.right = null;\n</code></pre>\n\n<p>A maximum of one assignment per line should be used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T23:45:05.603",
"Id": "473712",
"Score": "0",
"body": "1. Noted on how to document comments.\n2. noted on the use of public (typically we use private in class) that was my mistake.\n3.The underscore thing is something my professor does (No idea why), it is somewhat of a habit at this point that I know is a bad one, noted.\n4. Noted on the incorrect placement of table and my use of null.\n5. That was an initialization error I had in eclipse that fixed it, but I see why that is a mistake.\n6. my naming conventions were straight out of the notes he gave us so, that was lazy of me, apologies.\nI appreciate the review and will work on this more!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T22:47:02.840",
"Id": "241403",
"ParentId": "241386",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:02:46.847",
"Id": "241386",
"Score": "-1",
"Tags": [
"java",
"eclipse"
],
"Title": "Table with a Binary search tree"
}
|
241386
|
<p>So, I am trying to make people interested in my <a href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler" rel="nofollow noreferrer">compiler</a> project (in the early stages of development) by making some simple and clear programs in my programming language. Here is my implementation of the Pascal's Triangle in it. Do you think it's clear? If so, what do you think might be unclear to an average programmer?</p>
<pre><code>;Pascal's triangle
AsmStart ;Inline assembly in AEC starts with "AsmStart" and ends with "AsmEnd".
macro pushIntegerToTheSystemStack decimalNumber ;This is why I've chosen FlatAssembler for the back-end of my compiler: powerful and easy-to-use preprocessor.
{
sub esp,4 ;"esp" is the CPU register which points right below the data at the top of the system stack.
fld dword [decimalNumber]
fistp dword [esp] ;"fistp" is the x86 assembly language directive for converting decimal numbers to integers.
}
macro pushPointerToTheSystemStack pointer
{
sub esp,4
lea ebx,[pointer]
mov [esp],ebx
}
macro pushStringToTheSystemStack string
{
sub esp,4
mov dword [esp],string
}
format PE console ;"PE" means 32-bit Windows executable.
entry start
include 'win32a.inc' ;FlatAssembler macros for importing functions from DLLs.
section '.text' code executable
start:
jmp howManyRowsString$
howManyRowsString:
db "How many rows of Pascal's triangle do you want to be printed?",10,0 ;10 is '\n', and 0 is '\0'.
howManyRowsString$:
pushStringToTheSystemStack howManyRowsString
call [printf] ;printf(howManyRowsString)
jmp theFloatSymbol$
theFloatSymbol:
db "%f",0
theFloatSymbol$:
pushPointerToTheSystemStack numberOfRows
pushStringToTheSystemStack theFloatSymbol
call [scanf] ;scanf(theFloatSymbol,&numberOfRows)
AsmEnd
currentRow := 0
While currentRow < numberOfRows | currentRow = numberOfRows
AsmStart
jmp currentRowString$
currentRowString:
db "Row #%d:",9,0 ;9 is '\t' (the tabulator).
currentRowString$:
pushIntegerToTheSystemStack currentRow
pushStringToTheSystemStack currentRowString
call [printf] ;printf(currentRowString,currentRow)
AsmEnd
currentColumn:=0
While currentColumn < currentRow | currentColumn = currentRow
If currentColumn = 0
array (currentRow * numberOfRows + currentColumn) := 1 ;When I haven't programmed the compiler to deal with 2-dimensional arrays...
ElseIf currentColumn = currentRow
array (currentRow * numberOfRows + currentColumn) := 1
Else
numberImmediatelyAbove := array ( (currentRow - 1) * numberOfRows + currentColumn)
numberBeforeTheImmediatelyAboveOne := array ( (currentRow - 1) * numberOfRows + currentColumn - 1)
array (currentRow * numberOfRows + currentColumn) := numberBeforeTheImmediatelyAboveOne + numberImmediatelyAbove
EndIf
numberToBePrinted := array (currentRow * numberOfRows + currentColumn)
AsmStart
jmp integerSignWithTabulator$
integerSignWithTabulator:
db "%.0f",9,0 ;"%.0f\t", "%.0f" means for "printf" to round the decimal number to the nearest integer.
integerSignWithTabulator$:
fld dword [numberToBePrinted]
fstp qword [esp] ;"qword" means "double", because "printf" from "MSVCRT.DLL" can't print "float" which hasn't been converted to "double". When writing in Assembly, you need to deal with that kind of annoying stuff.
pushStringToTheSystemStack integerSignWithTabulator
call [printf] ;printf(integerSignWithTabulator,numberToBePrinted)
AsmEnd
currentColumn := currentColumn + 1
EndWhile
AsmStart
jmp newLineString$
newLineString:
db 10,0 ;"\n"
newLineString$:
pushStringToTheSystemStack newLineString
call [printf] ;printf(newLineString)
AsmEnd
currentRow := currentRow + 1
EndWhile
AsmStart
pushStringToTheSystemStack pauseString
call [system] ;system(pauseString), the "Press any key to continue..." message so that the console window doesn't immediately close.
invoke exit,0 ;exit(0)
pauseString db "PAUSE",0
section '.rdata' readable writable
result dd ? ;A variable used internally by the AEC compiler.
numberOfRows dd ?
currentRow dd ?
currentColumn dd ?
numberBeforeTheImmediatelyAboveOne dd ?
numberImmediatelyAbove dd ?
numberToBePrinted dd ?
array dd 30000 DUP(?)
section '.idata' data readable import
library msvcrt,'msvcrt.dll' ;"Microsoft Visual C Runtime Library", available as "C:\Windows\System32\msvcrt.dll" on Windows 98 and newer.
import msvcrt,printf,'printf',system,'system',exit,'exit',scanf,'scanf',clock,'clock'
AsmEnd
</code></pre>
|
[] |
[
{
"body": "\n\n<p>I find it very confusing that you consider all of this assembly as <em>inline</em> assembly. I see the start and exit of a regular FASM assembly program, 2 things I don't expect to find in <em>inline</em> assembly.</p>\n\n<p>Am I correct when I say that your high level language only uses single precision float variables? If not then variables like <em>numberOfRows</em>, <em>currentRow</em>, and <em>currentColumn</em> should be treated like dword integers for speed and frankly because that's what they truly are.</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>numberBeforeTheImmediatelyAboveOne dd ?\nnumberImmediatelyAbove dd ?\n</code></pre>\n</blockquote>\n\n<p>While using descriptive names is encouraged, having source lines that are much longer than the visible screen's width makes reading a lot more difficult. Perhaps you could make use of FASM's line continuation character <code>\\</code> ?</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>While currentRow < numberOfRows | currentRow = numberOfRows\n</code></pre>\n</blockquote>\n\n<p>Why the OR operator? Does your project not have the compound <code><=</code> operator?<br>\nIf available then simply write: <code>While currentRow <= numberOfRows</code>.<br>\nIf not available then you could invert the condition to: <code>While numberOfRows > currentRow</code>.</p>\n\n<h2>This is wrong</h2>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>fld dword [numberToBePrinted]\nfstp qword [esp]\n</code></pre>\n</blockquote>\n\n<p>Here you convert a single precision float into a double precision float, but you forget to reserve space on the stack!</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>sub esp, 8 <<<< Making room on the stack\nfld dword [numberToBePrinted]\nfstp qword [esp]\n</code></pre>\n\n<h2>Optimizing for codesize where speed doesn't matter at all</h2>\n\n<p>Why do you prefer those macros so much? <code>pushPointerToTheSystemStack numberOfRows</code> is just <code>push numberOfRows</code>. What could be simpler?</p>\n\n<p>The <code>call</code> instruction can do some work for you. You don't need to use the <code>pushStringToTheSystemStack</code> macro:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>call howManyRowsString\ndb \"How many rows of Pascal's triangle do you want to be printed?\",10,0\nhowManyRowsString:\ncall [printf]\nadd esp, 4 <<<< Don't you need to cleanup the stack with msvcrt ?\n\npush numberOfRows <<<< Simple\ncall theFloatSymbol\ndb \"%f\",0\ntheFloatSymbol:\ncall [scanf]\nadd esp, 8 <<<< Don't you need to cleanup the stack with msvcrt ?\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T08:04:11.357",
"Id": "475034",
"Score": "0",
"body": "Yes, for now, the only data types my program supports are Float32 and Float32Array. I didn't know about cleaning up the stack after calling MSVCRT, thanks for letting me know."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T18:48:14.293",
"Id": "242046",
"ParentId": "241387",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "242046",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:16:02.310",
"Id": "241387",
"Score": "3",
"Tags": [
"assembly",
"compiler"
],
"Title": "Pascal's Triangle in AEC"
}
|
241387
|
<p>I am pretty new to DDD, so any help/ideas will be appreciated. I will explain my initial design and problem below.</p>
<p>The user can ask the system to generate products proposal, proposal is basically something, which has some ownership and set of products, which can be renewed if system evolves, new products should be automatically added to proposal and returned to the user. Proposal is designed as separate AR as following class.</p>
<pre><code>public class Proposal : AggregateRoot
{
public Ownership OwnedBy { get; internal set; }
public IProposalState State { get; internal set; } =
ProposalStateCollection.ProposalInitializedState;
internal Proposal(Ownership ownedBy)
=> SetIdentity(ownedBy.DeviceId, this);
public Result AttachTo(string meteringPoint)
{
if (string.IsNullOrWhiteSpace(meteringPoint))
return Result.Failure($"{nameof(meteringPoint)} cannot be null or empty.");
return State.AttachMeteringPoint(this, meteringPoint);
}
public Result AttachTo(OwnerAddress ownerAddress)
{
if (ReferenceEquals(null, ownerAddress))
return Result.Failure($"{nameof(ownerAddress)} cannot be null.");
return State.AttachOwnerAddress(this, ownerAddress);
}
internal Result<Product> PopulateWith(ProductType productType)
{
if (ReferenceEquals(null, productType))
return Result.Failure<Product>($"{nameof(productType)} cannot be null.");
return ProductSpecification
.Instance
.OwnedByProposal(Id)
.ForProductType(productType)
.InState(ProductStateCollection.ProductInitializedState)
.AndNoExistingIdentity()
.Build();
}
public Result ScheduleRecalculation()
=> State.ScheduleRecalculation(this);
</code></pre>
<p>That's pretty straight forward, user sends request to the system, then the Application service serves the request (checking existing of proposal, if it was generated before or creating one if not) and then calling <code>ScheduleRecalculation</code> method, which simply generate domain event based on current state of proposal.</p>
<p>When handler received event that proposal is recalculated itself (<code>ProposalRecalculationCompletedEvent</code>) it asks domain service to provide him all latest products + existing one and then start recalculation of each product. Something like this. Product is modeled as separate AR.</p>
<pre><code> public Task Handle(
DomainEventNotification<ProposalRecalculationCompletedEvent> notification,
CancellationToken cancellationToken)
{
var domainEvent = notification.DomainEvent;
return _proposalRepository.ProposalOfIdAsync(domainEvent.ProposalId, cancellationToken)
.Bind(proposalOrNone => proposalOrNone.ToResult(
$"Proposal [{domainEvent.ProposalId}] cannot be found. Won't be populated with latest products.'"))
.Bind(proposal => _productRepository.ProductsOfProposalAsync(proposal.Id)
.Tap(existing =>
{
_productService.LatestProductsOfProposal(proposal, existing)
.Tap(latest =>
{
var products = latest.ToList();
_productService.RecalculatePriceOfProducts(products);
_productRepository.PersistProductsAsync(products);
});
}))
.OnFailure(error =>
_logger.LogError(
"Error occured while populating proposal [{proposalId}] with the latest products. [{error}]",
domainEvent.ProposalId,
error));
}
</code></pre>
<p><code>RecalculatePriceOfProducts</code> is a simple wrapper around internal <code>SchedulePriceRecalculation</code> on <code>Product</code> AR, which send domain event for each product to start recalculation. Product AR itself.</p>
<pre><code>public class Product : AggregateRoot, IEnumerable<PriceOffer>
{
public string ProposalId { get; internal set; }
public IProductState State { get; internal set; } =
ProductStateCollection.ProductInitializedState;
public ProductType Type { get; internal set; }
public Maybe<PriceOffer> CurrentPriceOffer { get; internal set; }
= Maybe<PriceOffer>.None;
internal IList<PriceOffer> PriceOffers { get; set; }
private IDictionary<PriceOffer, PriceOffer> _priceOffersMap =>
PriceOffers.ToDictionary(p => p, p => p);
internal Product()
=> SetIdentity(Guid.NewGuid().ToString("D"), this);
internal Result SchedulePriceRecalculation(HourlyPrecisedDatePeriod forPeriod)
{
if (ReferenceEquals(null, forPeriod))
return Result.Failure($"{nameof(forPeriod)} cannot be null.");
if (HasValidPrice(forPeriod))
return Result.Success();
return State.SchedulePriceRecalculation(() =>
AddDomainEvent(this.ToProductPriceRecalculationScheduled(forPeriod)));
}
public Result EnrollPriceFor(
HourlyPrecisedDatePeriod validForPeriod,
IPriceOfferCalculation priceOfferCalculation)
{
if (ReferenceEquals(null, validForPeriod))
return Result.Failure($"{nameof(priceOfferCalculation)} cannot be null.");
if (ReferenceEquals(null, priceOfferCalculation))
return Result.Failure(
$"{nameof(priceOfferCalculation)} cannot be null.");
return State.EnrollPriceFor(() =>
priceOfferCalculation.Calculate(validForPeriod)
.Ensure(
priceOffer => !_priceOffersMap.ContainsKey(priceOffer),
"Price offer already enrolled within the product.")
.Tap(priceOffer =>
{
PriceOffers.Add(priceOffer);
CurrentPriceOffer = priceOffer;
}))
.Tap(state => State = state);
}
private bool HasValidPrice(HourlyPrecisedDatePeriod forPeriod)
=> CurrentPriceOffer.HasValue && CurrentPriceOffer.Value.IsValidForPeriod(forPeriod);
public IEnumerator<PriceOffer> GetEnumerator()
=> PriceOffers.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
}
</code></pre>
<p>Here is the question, as soon as I iterate products and schedule price recalculation for each (by domain event and eventually map it to command and sending to service bus), the products processed in parallel, after processing is done for ALL products (no matter if it was succeed or not) I need to sent another event to service bus. Any suggestion how I can do that? As soon as Products are separate ARs I need someway to know that for that particular recalculation all products were calculated with Success or Failed result.</p>
<p>Another question, if you look at <code>EnrollPriceFor</code> method, which accepts <code>IPriceOfferCalculation</code>. So basically, when price calculation is scheduled and command sent to service bus, the receiver builds <code>IPriceOfferCalculation</code> implementation and pass it to the <code>Product</code> AR, the requirements tell that if calculation failed, it should schedule another calculation with fallback calculation. So who should do that? The receiver? The Product AR itself, then what would be the best design for that?</p>
<p>Hope it is possible to understand...</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:16:23.543",
"Id": "241388",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"ddd"
],
"Title": "DDD design: Tracking price calculation progress and fallback price calculation"
}
|
241388
|
<p>I decided to make my own light DI container.</p>
<p>I know about Zenject, etc. I wanted a very light analog.</p>
<p>I'm concerned about a few things:</p>
<p>1) is it correct to use struct instead of class for reference in this context?</p>
<p>2) every time you access _player.Reference, there is a check for null (in the UnityEngine.After the destruction of the Object does not equal null, so use SafeIsUnityNull)</p>
<p>3) Double point. Can I overload the operator so that instead of <code>_player.Reference.AAAAAAAAAAAAA();</code>, it works <code>_player.AAAAAAAAAAAAA();</code> ??</p>
<p>Container itself:</p>
<pre><code> public static class DIContainer
{
private static readonly Dictionary<System.Type, Object> _references = new Dictionary<System.Type, Object>();
public static void Bind<T>(T value) where T : Object
{
_references[typeof(T)] = value;
}
public static T Resolve<T>() where T : Object
{
if (_references.TryGetValue(typeof(T), out Object value))
return (T)value;
throw new System.InvalidCastException($"DIContainer: invalid resolve object {typeof(T)}");
}
}
</code></pre>
<p>Field reference:</p>
<pre><code> public struct DIReference<T> where T : Object
{
private T _reference;
public T Reference => !_reference.SafeIsUnityNull() ? _reference : _reference = DIContainer.Resolve<T>();
}
</code></pre>
<p>Installer:</p>
<pre><code> public abstract class SceneInstaller : MonoBehaviour
{
private void Awake() => InstallBindings();
protected abstract void InstallBindings();
}
</code></pre>
<pre><code>public class LevelInstaller : SceneInstaller
{
}
</code></pre>
<p><strong>Using</strong></p>
<p>Bind:</p>
<pre><code> [SerializeField] private PlayerController _player;
protected override void InstallBindings()
{
DIContainer.Bind(_player);
}
</code></pre>
<p>Reference:</p>
<pre><code>public class Test
{
private DIReference<PlayerController> _player;
private void Foo()
{
_player.Reference.AAAAAAAAAAAAA();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>What you're actually doing is implementing Service Locator which is quite opposite to dependency injection. Please refer to <a href=\"https://stackoverflow.com/questions/4985455/dependency-injection-vs-service-location\">[THIS]</a> discussion about it.</p>\n\n<p><strong>Please use already existing solution.</strong></p>\n\n<p>Few points from my side, just to point out why I think that's wrong for your case:</p>\n\n<ol>\n<li>Why do you think you need more lightweight DI container? Have you performed benchmarks and they proved that your bottle neck is DI injection?</li>\n<li>Why have you choosen struct for DIReference? Struct is not good choice for a field, because you're unintenionally (I presume) allocating it on heap. Please refer to <a href=\"https://stackoverflow.com/questions/4853213/are-structs-always-stack-allocated-or-sometimes-heap-allocated\">[THIS]</a> discussion.</li>\n<li>Why would you need DIReference anyway? It's only complicating your code. You don't need to store it as field anywhere - instances that you need are already kept in _references in DIContainer.</li>\n<li>Just to point out, as your _references is static readonly field, then this Dictionary is singleton. It causes few potential problems, to name two:\n\n<ul>\n<li>Is it guaranteed that every time you install bindings there won't be any other threads that trying to do same thing?</li>\n<li>Every instance in this dictionary is also singleton-ish. What I mean by that - as soon as first class will install PlayerController into your _references in DIContainer then it'll be available for all classes that uses your DIContainer class. Yet you can still overwrite it. Why would that be a problem? It could cause huge GC pressure, because you'll constantly overwriting PlayerController in your dictionary and GC will have to clean that up which could lead to stopping all threads from running. You definitely want to avoid that especially in games.</li>\n</ul></li>\n</ol>\n\n<p>I want to strongly suggest to use already existing solution for DI. If you're worried about performance please refer to <a href=\"https://github.com/danielpalme/IocPerformance\" rel=\"nofollow noreferrer\">[THIS]</a> benchamrks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T11:21:14.507",
"Id": "241747",
"ParentId": "241389",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:31:23.573",
"Id": "241389",
"Score": "1",
"Tags": [
"c#",
".net",
"unity3d"
],
"Title": "My simple implementation of a DI container"
}
|
241389
|
<p>Assume $ is not the browser. Now have to implement $, it will take a string, which is a query, it will use the querySelector to select the element. (Reference: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector</a>)</p>
<pre><code>$('text')
</code></pre>
<p>Now implement jquery like functions addClass and removeClass. (Reference: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/classList" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Element/classList</a>)</p>
<pre><code>$('#test').removeClass('blue').addClass('red');
</code></pre>
<p>Now implement jquery like functions delay. (Reference: <a href="https://api.jquery.com/delay/" rel="nofollow noreferrer">https://api.jquery.com/delay/</a>)</p>
<pre><code>$('#test').removeClass('blue').delay(2000).delay(1000).addClass('red');
</code></pre>
<p>Code Sample</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>function $(selector) {
let element = document.querySelector(selector)
element.queue = []
element.active = false
return element
}
Element.prototype.next = function () {
if (this.queue.length) this.runTask(this.queue.shift())
}
Element.prototype.runTask = function (callBack) {
this.active = true
callBack().then(() => {
this.active = false
this.next()
})
}
Element.prototype.register = function(callBack){
if (this.active) {
this.queue.push(callBack)
} else {
this.runTask(callBack)
}
}
Element.prototype.addClass = function (className) {
that = this
let callBack = () => new Promise(resolve => setTimeout(function () {
that.classList.add(className)
resolve()
}, 0))
this.register(callBack)
return this
}
Element.prototype.removeClass = function (className) {
that = this
let callBack = () => new Promise(resolve => setTimeout(function () {
that.classList.remove(className)
resolve()
}, 0))
this.register(callBack)
return this
}
Element.prototype.delay = function (ms) {
that = this
let callBack = () => new Promise(resolve => setTimeout(function () {
resolve()
}, ms))
this.register(callBack)
return this
}
$('#test')
.removeClass("red").delay(500)
.addClass("blue").delay(500).delay(500).removeClass("blue")
.delay(500).addClass("red").delay(500).removeClass("red")
.delay(500).addClass("blue").delay(500).removeClass("blue")
.delay(500).addClass("red").delay(500).removeClass("red")</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<style>
.blue{
background-color: blue;
}
.red{
background-color: red;
}
</style>
</head>
<body>
<div id="test" style="width: 150px; height: 150px; margin:10px;" class="red"></div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>Can anyone please review the Code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T11:30:22.077",
"Id": "473767",
"Score": "1",
"body": "Welcome to Code Review. Does the code work successfully? Can you tell us more about what the code is supposed to do? References are good for bonus context, but the problem you solved should be clearly stated in the question itself. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T11:32:47.297",
"Id": "473769",
"Score": "1",
"body": "Does it boil down to writing an alternative for `addClass`, `removeClass` and `delay`? Any limitations on this? What prompted you to do this? How does this differ from something like `text.classList.add(\"foo\")`?"
}
] |
[
{
"body": "<p>Mutating built-in prototypes is not a good idea. It's not only inelegant, it can also lead to conflicts when other scripts on the page expect the prototypes to be unmutated. (It can even <a href=\"https://stackoverflow.com/a/55934491\">damage</a> future attempts to integrate functionality officially, if enough sites use the bad code.)</p>\n\n<p>Instead of using <code>Element.prototype</code>, create your own class, and put methods onto <em>its</em> prototype.</p>\n\n<p>If you want to emulate jQuery, you should probably select <em>all</em> elements that match the selector, not just the first one. (Using a collection of elements will also avoid errors if the collection is empty - jQuery doesn't error when methods are called on an empty collection)</p>\n\n<p>The <code>active</code> flag would be more informative if it was named more precisely, perhaps call it <code>methodInProgress</code>.</p>\n\n<p><code>that = this</code> <a href=\"https://github.com/airbnb/javascript#naming--self-this\" rel=\"nofollow noreferrer\">is an antipattern</a> in modern Javascript. If you need to use the calling context from the outer scope, use arrow functions instead. (You're already using ES2015 in multiple places)</p>\n\n<p><code>callback</code> is a single word, not two, so the proper way to camelCase it would be to keep it as-is. Calling the arguments <code>callBack</code> instead could result in bugs later when other readers/writers of the code expect it to be formatted conventionally.</p>\n\n<p>Promises should be reserved for <em>asynchronous</em> actions. If you're going to run something that's completely synchronous, using a Promise adds unnecessary and confusing noise. Consider having your functions return Promises <em>only if they're asynchronous</em>, and while processing the queue, if a callback returns a Promise, wait for the Promise to resolve before moving onto the next callback. If the callback <em>doesn't</em> return a Promise, you can still <code>await</code> it without errors, and the next queue callback will run immediately.</p>\n\n<p>Since you have multiple methods which add callback to the queue and <code>return this</code>, consider passing those methods through a helper function to make the code a bit more DRY.</p>\n\n<p>Refactored:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const $ = selector => new PsuedoJquery(selector);\nclass PsuedoJquery {\n constructor(selector) {\n this.elements = [...document.querySelectorAll(selector)];\n this.queue = [];\n }\n async runNext() {\n await this.queue.shift()();\n if (this.queue.length) {\n await this.runNext();\n } else {\n this.methodInProgress = false;\n }\n }\n register(callback) {\n this.queue.push(callback);\n // If errors are a possibility, catch them here\n if (!this.methodInProgress) {\n this.methodInProgress = true;\n this.runNext();\n }\n }\n makeChainable(callback) {\n this.register(callback);\n return this;\n }\n addClass(className) {\n return this.makeChainable(() => {\n for (const elm of this.elements) {\n elm.classList.add(className);\n }\n });\n }\n removeClass(className) {\n return this.makeChainable(() => {\n for (const elm of this.elements) {\n elm.classList.remove(className);\n }\n });\n }\n delay(ms) {\n return this.makeChainable(() => new Promise((resolve) => {\n setTimeout(resolve, ms);\n }));\n }\n}\n\n$('#test')\n .removeClass(\"red\").delay(500)\n .addClass(\"blue\").delay(500).delay(500).removeClass(\"blue\")\n .delay(500).addClass(\"red\").delay(500).removeClass(\"red\")\n .delay(500).addClass(\"blue\").delay(500).removeClass(\"blue\")\n .delay(500).addClass(\"red\").delay(500).removeClass(\"red\")</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.blue {\n background-color: blue;\n}\n\n.red {\n background-color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"test\" style=\"width: 150px; height: 150px; margin:10px;\" class=\"red\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T21:37:28.043",
"Id": "241400",
"ParentId": "241391",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "241400",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T18:50:48.437",
"Id": "241391",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html",
"queue",
"promise"
],
"Title": "Implement jquery like functions addClass, removeClass and delay in Javascript"
}
|
241391
|
<p>I had an assignment to create a circumference calculator in Java which I've already submitted. I would like feedback on my code.</p>
<p>The program works as intended, but I am not sure whether it's spaghetti code or not after realizing that I only called one method in main which calls all of the other methods. Here is the code: </p>
<pre><code>import java.util.Scanner;
public class circ
{
public static void main(String[]args)
{
mainMenu();
}//end main method
//----------------------- Main Menu --------------------------------//
public static void mainMenu()
{
String shape = "";
//while loop to repeat program
while (!shape.equals("q"))
{
System.out.println("\t\t\t\t\tCircumference Calculator \n");
System.out.println("\t\t\t\t\t--------Main Menu--------\n");
System.out.println("Square(1) \t\t Rectangle(2) \t\t Triangle(3) \t\t (Q)uit");
shape = menuInput().toLowerCase(); //call menu input method, parse to lower case so that user can input Q or q to quit
switch(shape.charAt(0))
{
case '1':
squareInput();
break;
case '2':
rectInput();
break;
case '3':
trInput();
break;
case 'q':
System.out.println("\nGoodbye!");
break;
default:
System.out.println("\n\n\t\tInvalid input! Please select 1, 2, 3, or Q\n\n");
break;
}//end switch
}//end while loop
}//end main menu method
// ------------- general input method for shapes -------------//
public static double input()
{
Scanner KB = new Scanner(System.in);
double value;
value = KB.nextDouble();
if(value < 0)
value = validation(value);
return value;
}//end input method
// -------------------------- input method for the main menu -----------------------//
public static String menuInput()
{
Scanner KB = new Scanner(System.in);
String choice = " ";
choice = KB.nextLine();
return choice;
}//end menu input
//--------------------------------shape input methods--------------------------------------------------------//
public static void squareInput()
{
double side, circ = 0.0;
System.out.println("Side: ");
side = input();
circ = squareCirc(side);
squareOutput(side, circ);
}//end square input
public static void rectInput()
{
double length, width, circ = 0.0;
System.out.println("Length: ");
length = input();
System.out.println("Width: ");
width = input();
circ = rectCirc(length, width);
rectOutput(length, width, circ);
}//end rectangle input method
public static void trInput()
{
double side1, side2, side3, circ = 0.0;
System.out.println("Side 1: ");
side1 = input();
System.out.println("Side 2: ");
side2 = input();
System.out.println("Side 3: ");
side3 = input();
circ = triCirc(side1,side2,side3);
triOutput(side1,side2,side3, circ);
}//end trInput()
//----------------------------- shape process methods ------------------//
public static double squareCirc(double x)
{
return(4 * x);
}
public static double rectCirc(double x, double y)
{
return(( 2 * x) + (2 * y));
}
public static double triCirc(double x, double y, double z)
{
return(x + y + z);
}
//----------------------output methods---------------------------//
public static double squareOutput(double x, double circ)
{
System.out.println("Square: \n");
System.out.println("Side = " + x);
System.out.println("Circumference = " + circ);
return 0;
}//end square output
public static double rectOutput(double x, double y, double circ)
{
System.out.println("Rectangle: \n");
System.out.println("Length = " + x);
System.out.println("Width = " + y);
System.out.println("Circumference = " + circ);
return 0;
}//end rectangle output
public static double triOutput(double x, double y, double z, double circ)
{
System.out.println("Triangle: \n");
System.out.println("Side 1 = " + x + " Side 2 = " + y + " Side 3 = " + z);
System.out.println("Circumference = " + circ);
return 0;
} //end triangle output
//------------------------input validation method --------------------//
public static double validation(double x)
{
Scanner KB = new Scanner(System.in);
while( x < 0)
{
System.out.println("\nValue must be greater than 0!\n");
x = KB.nextDouble();
}//end loop
return x;
}//end method
}//end class
</code></pre>
|
[] |
[
{
"body": "<p>It's not spaghetti code. Although it is a bit strange that main just calls mainMenu. It could contain a loop that would end when mainMenu returns false and mainMenu would return false if user wants to quit. </p>\n\n<p>There are a few minor gotchas, im sure someone else will point out... </p>\n\n<p>I just wanna say this Is a good candidate for OOP, especialy for Its polymorphism feature. But I suppose you're not that far yet, so I won't show you any code, unless you're really interested. </p>\n\n<p>It's quite a good code for the level I suppose you are on :) </p>\n\n<p>One note, there is hardly any value in those comments, use comments to clarify things that may not be obvious. Commenting on block ends and repeating what is clear from code itself just does not help, if not worse. And honestly i dont see a single useful comment in your code. It is just too simple to need any.</p>\n\n<p>Maybe one more, dont abbreviate names like <code>trInput</code>, it then starts to need comments... Code that is self documented is always better (in terms of readability) then having to explain everything in comments.</p>\n\n<p>It may be good to comment on complex formulae as to why they solve given problem as those things are often not clear at first glance, you may put a reference to mathematical proof in comment for example. Or if a function accepts integer, but it wont work if it is larger than 100, then put it in comment with explanation why it cannot work. And things like that...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T18:47:37.263",
"Id": "473849",
"Score": "0",
"body": "thanks for the feedback! I'll try writing another version with the loop you mentioned. And I'll admit, I have no idea what polymorphism is yet, but I wouldn't mind seeing some examples. I'm in my first year of college and OOP has just started to click for me recently"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T04:57:02.547",
"Id": "474295",
"Score": "0",
"body": "@shaggy Oh, In that case, I wouldn't recommend trying out implementing some polymorphism yet. You need some basics about classes first. I'll just say that polymorphism is feature that allow you to implement similar behaviour, yet different, in a way that one implementation is substituable by another one. In your case, it would be 3 classes (square, rectngle and triangle), all implementing the same interface (ie. shape) which would allow it to 1) load from user input 2) compute circumference 3) output its state into console. This allows to easily add more shapes in future."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T06:26:32.330",
"Id": "241412",
"ParentId": "241411",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T05:45:41.503",
"Id": "241411",
"Score": "3",
"Tags": [
"java"
],
"Title": "Console app for calculating circumference of various shapes defined by user input"
}
|
241411
|
<p>I am trying to create a robust, generic way to parse a bar delimited <code>usr</code> files, now I can read the file in and separate it by <code>|</code> then index with integers.</p>
<p>However, this always feels very rigid in its design and I want to try to avoid it.</p>
<p>What I would like is a way to map any bar delimited file to JSON or at least a Python <code>dict</code>. I'm looking for some from of Factory method I think.</p>
<p>Say if the file like this:</p>
<pre><code>Header|Header1|Header2|Header3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
Footer|Footer1|Footer2|Footer3
</code></pre>
<p>It would be relatively straight forward. However, it would become undesirable when you get files like this:</p>
<pre><code>Header|Header1|Header2|Header3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
Footer|Footer1|Footer2|Footer3
</code></pre>
<p>This represents a <code>Header</code>, <code>Tail</code> (which are always the same in every file) and 2 entries (2 sets of <code>Group1</code> and <code>Group2</code>)</p>
<p>So I need to also retain the fact that, files have groups and each set of group has to be 'scooped' up together. I.E: <code>File X</code> may have two groups (<code>A</code>and <code>B</code>) - if <code>File X</code> had one entry it would look like this:</p>
<pre><code>Header|Header1|Header2|Header3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
Footer|Footer1|Footer2|Footer3
</code></pre>
<p>Two entries would look like this:</p>
<pre><code>Header|Header1|Header2|Header3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
Footer|Footer1|Footer2|Footer3
</code></pre>
<p><em>All</em> the key names for <code>File X</code> are known, so I can use a lookup structure</p>
<p>At the moment I have a Pandas implementation looks like this:</p>
<pre><code>df = pd.read_csv('file1.usr', sep='|')
header_names = ["HeaderKey", "HeaderKey1", "HeaderKey2", "HeaderKey3"]
footer_names = ["FooterKey", "FooterKey1", "FooterKey2", "FooterKey3"]
groups = {'A': ['AValueKey', 'A2ValueKey', 'A3ValueKey'],
'B': ['BValueKey', 'B2ValueKey', 'B3ValueKey']}
first_group_name = 'A'
df1 = df.iloc[:-1]
s = df1.iloc[:, 0].eq(first_group_name).cumsum()
for i, x in df1.groupby(s):
group = {}
for k, v in x.set_index(x.columns[0]).T.to_dict('l').items():
group[k] = dict(zip(groups[k], v))
header = dict(zip(header_names, df.columns))
footer= dict(zip(footer_names, df.iloc[-1]))
file = {'header': header, 'groups': group, 'footer': footer}
print(file)
</code></pre>
<pre><code>{
'groups': {
'A': {
'AValueKey': 'Entry1', 'A2ValueKey': 'Entry2', 'A3ValueKey': 'Entry3'
},
'B': {
'BValueKey': 'Entry1', 'B2ValueKey': 'Entry2', 'B3ValueKey': 'Entry3'}
},
'header': {
'HeaderKey': 'Header'
'HeaderKey1': 'Header1',
'HeaderKey2': 'Header2',
'HeaderKey3': 'Header3',
},
'footers': {
'FooterKey': 'Footer',
'FooterKey1': 'Footer1',
'FooterKey2': 'Footer2',
'FooterKey3': 'Footer3',
}
}
</code></pre>
<p>So it relies on having the structure:</p>
<pre><code>header_names = ["HeaderKey", "HeaderKey1", "HeaderKey2", "HeaderKey3"]
trailer_names = ["FooterKey", "FooterKey1", "FooterKey2", "FooterKey3"]
groups = {'A': ['AValueKey', 'A2ValueKey', 'A3ValueKey'],
'B': ['BValueKey', 'B2ValueKey', 'B3ValueKey']}
first_group_name = 'A'
</code></pre>
<p>Are there any other ways that would be more efficient?</p>
<h1>EDIT based on @Reinderien answer</h1>
<ul>
<li>Updated data format</li>
</ul>
<pre><code>Header|Header1|Header2|Header3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
Footer|Footer1|Footer2|Footer3
</code></pre>
<p>Firstly, thanks for going out on a limb even though evidently I haven't provided a clear scope.</p>
<p>To address your points;</p>
<ul>
<li><p>Suggestions on global code, cap constants, tuples over lists and tail/trailer all noted, thanks :)</p>
</li>
<li><p>Indication of scale:</p>
</li>
</ul>
<p>Each file is up <5KB, with a volume of between 10,000-100,000/day. I.E this script would need to parse and load up to 100,000 5KB files daily.</p>
<ul>
<li>Case of repeated groups:</li>
</ul>
<p>File would look like this:</p>
<pre><code>Header|Header1|Header2|Header3
A|Entry1|Entry2|Entry3
B|Entry1|Entry2|Entry3
A|Entry2|Entry3|Entry4
B|Entry2|Entry3|Entry4
Footer|Footer1|Footer2|Footer3
</code></pre>
<p>I take full responsibility for not being clearer in my question, but this is undesirable behavior. In the case of repeated groups, we would need to retain all the data, but split it into two separate payloads. Header and Footers:) will be the same for both however the <code>group</code> part of the payload would contain the corresponding data.</p>
<p>The first entry in the group line is always the same, but the data leading from that can differ. I hope that clears things up, please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T09:37:47.237",
"Id": "473746",
"Score": "2",
"body": "With regards to \"implementation that looks something like this\", please note: Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T09:48:07.047",
"Id": "473749",
"Score": "2",
"body": "Is it actual code from a project rather than pseudo-code or hypothetical code?\n\nDetails matter! In order to give good advice, we need to see real, concrete code, and understand the context in which the code is used. Generic code (such as code containing placeholders like `foo`, `MyClass`, or `doSomething()`) leaves too much to the imagination."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T09:50:27.490",
"Id": "473751",
"Score": "0",
"body": "Yes, it was poor chose of language from me, but that is all I have in an implementation for converting the file to JSON. I have updated the question and thanks for the advice :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:59:00.367",
"Id": "473758",
"Score": "1",
"body": "Please keep reviews limited to one language. Additionally you have provided a lot of examples but they don't relate. The output for Python is talking about \"AValueKey\" but that's not defined in any of the examples. This is just incoherent, please just pick one story and stick with that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:02:58.050",
"Id": "473785",
"Score": "0",
"body": "What are you trying to improve the efficiency of, speed, memory, ...?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:30:28.650",
"Id": "473794",
"Score": "0",
"body": "I was more interested to see how someone else may implement this, and if I was on the right lines. Things to look out for, things I could maybe try, reference to any reading etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:43:29.150",
"Id": "473826",
"Score": "0",
"body": "_Since each row of this file has a different_ [...what?]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:56:34.510",
"Id": "473834",
"Score": "0",
"body": "I am so very confused by your data structure. You have three header columns but only two \"entry\" columns. Is the first header always associated with the group? If so, could you alter your sample data to show `HeaderG|Header1|Header2`? And why are the tails there at all? Why are the tail values repeated to be equal in every column? And why does your code show tail values that are _different_ in every column?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T17:11:31.810",
"Id": "473835",
"Score": "1",
"body": "Also, why does this: `'B': ['BValueKey', 'B2ValueKey', 'A3ValueKey']` have an `A` in it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T19:28:15.987",
"Id": "473853",
"Score": "0",
"body": "@Reinderien thanks, i've tried to update the Q to be clearer."
}
] |
[
{
"body": "<p>Some suggestions for you:</p>\n\n<ul>\n<li>Avoid global code</li>\n<li>Make constants capitalized</li>\n<li>Use tuples instead of lists for immutable constants</li>\n<li>The standard terminology for the opposite of \"header\" is \"footer\", not \"trailer\"</li>\n<li>Given your description of scale, this is a very parallelizable problem and could easily be framed as a standard Python multi-processing program</li>\n<li>The parsing of the serialized file format is shown in a separate generator function from the loading of the data into the dictionary format you've shown</li>\n<li>I have assumed that you wish to remain printing the dictionary out to <code>stdout</code>, in which case <code>pprint</code> is more appropriate. If you want to serialize this to JSON, that is trivial using the <code>json</code> module.</li>\n<li>I have assumed that in the case of repeated groups, they are aggregated to a list of lists with no regard for uniqueness</li>\n<li>In the other answer, the suggestion is good to pass the result of <code>zip</code> directly to the <code>dict</code> constructor. Basically: this takes two iterables, iterates over both of them at the same time; uses one as the key and the other as the value; and assumes that the order of the key iterable matches the order of the value iterable.</li>\n</ul>\n\n<p>The suggested code:</p>\n\n<pre><code>from collections import defaultdict\nfrom pprint import pprint\nfrom typing import Iterable, List, Sequence\n\nHEADER_NAMES = ('HeaderKey1', 'HeaderKey2', 'HeaderKey3')\nFOOTER_NAMES = ('FootKey1', 'FootKey2', 'FootKey3')\nGROUPS = {'A': ('A1ValueKey', 'A2ValueKey', 'A3ValueKey'),\n 'B': ('B1ValueKey', 'B2ValueKey', 'B3ValueKey')}\n\n\ndef parse(fn: str) -> Iterable[List[str]]:\n with open(fn) as f:\n yield from (\n line.rstrip().split('|')\n for line in f\n )\n\n\ndef load(lines: Iterable[Sequence[str]]) -> dict:\n lines = iter(lines)\n heads = next(lines)\n prev_line = next(lines)\n\n groups = defaultdict(list)\n\n for line in lines:\n group, *entries = prev_line\n groups[group].append(dict(zip(GROUPS[group], entries)))\n prev_line = line\n\n return {\n 'header': dict(zip(HEADER_NAMES, heads)),\n 'footer': dict(zip(FOOTER_NAMES, prev_line)),\n 'groups': groups,\n }\n\n\nif __name__ == '__main__':\n d = load(parse('file1.usr'))\n pprint(d)\n</code></pre>\n\n<p>This produces:</p>\n\n<pre><code>{'footer': {'FootKey1': 'Footer1',\n 'FootKey2': 'Footer2',\n 'FootKey3': 'Footer3'},\n 'groups': defaultdict(<class 'list'>,\n {'A': [{'A1ValueKey': 'Entry1',\n 'A2ValueKey': 'Entry2',\n 'A3ValueKey': 'Entry3'}],\n 'B': [{'B1ValueKey': 'Entry1',\n 'B2ValueKey': 'Entry2',\n 'B3ValueKey': 'Entry3'},\n {'B1ValueKey': 'Entry4',\n 'B2ValueKey': 'Entry5',\n 'B3ValueKey': 'Entry6'}]}),\n 'header': {'HeaderKey1': 'Header1',\n 'HeaderKey2': 'Header2',\n 'HeaderKey3': 'Header3'}}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T08:49:46.500",
"Id": "473907",
"Score": "0",
"body": "Thanks for this, I like the separation and use of the generator. I have edited my question to try and address your points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T13:53:22.220",
"Id": "473930",
"Score": "0",
"body": "@Bob Edited for performance commentary and aggregation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T14:23:58.240",
"Id": "473941",
"Score": "0",
"body": "Thanks :D - If we wanted to output 2 separate payloads for each 'set' of groups `A` and `B` and persist the Header and Footer rather then a `defaultdict` - How would this be achieved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T14:32:15.773",
"Id": "473944",
"Score": "1",
"body": "We're in somewhat dangerous territory: the \"evolving question/answer\" is not really supported in CodeReview. Let us please discuss this in chat: https://chat.stackexchange.com/rooms/107405"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T02:00:15.293",
"Id": "474010",
"Score": "0",
"body": "@Bob A very different, vectorized approach proposed in https://codereview.stackexchange.com/questions/241533"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T06:50:38.757",
"Id": "474033",
"Score": "0",
"body": "Thank you @Reinderien"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T20:48:52.650",
"Id": "241454",
"ParentId": "241415",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241454",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T07:32:49.310",
"Id": "241415",
"Score": "2",
"Tags": [
"python",
"design-patterns",
"pandas"
],
"Title": "What is an efficient ways to parse a bar separated usr file in Python"
}
|
241415
|
<p>I want to create a list of the <em>different</em> response headers I get when querying an URL, I succeeded in doing this this way:</p>
<pre><code>import requests
l= []
for _ in(5):
a = requests.get("https://google.com", allow_redirects=True).headers['Origin']
if a not in l:
l.append(a)
</code></pre>
<p>This is readable but I feel like this is very basic, how would an advanced Pythonista handle this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:40:16.180",
"Id": "473802",
"Score": "0",
"body": "You cannot substantially edit the question after receiving an answer post, as doing so invalidates the answer. See the [help] for what you can, should, and cannot do after receiving an answer. I have rolled back your most recent edit accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:20:56.803",
"Id": "473809",
"Score": "2",
"body": "I am not convinced that this code is on-topic. It seems like a snippet that would never be run in isolation. CodeReview does not support the reviewing of snippets. Is this all of the code in your program, or is there more? Why are you gathering origins? Will it actually be from Google, or is that just an example? (Hypotheticals are also off-topic.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:01:31.393",
"Id": "473819",
"Score": "0",
"body": "@Reinderien Yes, this is indeed a snippet and yes, Google is just an example. How should I proceed from now on? Post the whole thing as another question and delete this one, or do I edit this one, even though it has multiple comments and an answer now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:04:27.067",
"Id": "473821",
"Score": "0",
"body": "@Reinderien Also should I be editing my code in the question after I get feedback in the form of comments/answers? Because that's what I've been doing and that's why I go stuck with this stupid \"for _ in(5)\" which birthed a whole answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:11:32.987",
"Id": "473822",
"Score": "3",
"body": "That is a very good question. In theory, all of the code reviewers should have known that this is off-topic and should not have posted answers; this would have been voted-to-close, you would have improved it, and it would have then re-opened. In practice I'm going to ask on meta."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:17:22.260",
"Id": "473823",
"Score": "0",
"body": "https://codereview.meta.stackexchange.com/questions/10471/what-do-we-do-with-low-quality-questions-that-already-have-answers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:26:42.013",
"Id": "473824",
"Score": "4",
"body": "@KateVelasquez In the meantime I think it is safe for you to post a new question with more code and context, after having read https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions . I do not think it would be considered a duplicate. Thank you for your patience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T19:00:40.640",
"Id": "473851",
"Score": "1",
"body": "I'm sorry that your first experience is so poor Kate. Since this has now been closed please feel free to edit the post to become on-topic, as Reinderien has suggested. Additionally the more code you proved the better we can help you improve your code. However in the future please _do not_ edit the code in the question to address answers, this is because it causes icky situations like this where you're stuck with `for _ in(5)`. When you [edit] the question so that it includes a complete script please feel free to ping me to help kick start a potential reopen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T12:46:47.597",
"Id": "474339",
"Score": "0",
"body": "@Peilonrayz Considering more and more people are answering off-topic questions (which they shouldn't) and the mess it has created on this one, I'm in favour of putting the revised code in a new question this time."
}
] |
[
{
"body": "<p>As mentioned in <a href=\"https://codereview.stackexchange.com/a/241419/100620\">Thomas Weller's post</a>, your <code>for</code> loop only executes a single time. You want to loop over a <code>range(5)</code>.</p>\n\n<hr>\n\n<p>You may wish to use a <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=set#set\" rel=\"nofollow noreferrer\"><code>set</code></a> to collect your unique results. Test for containment using <code>a not in l</code> is an <span class=\"math-container\">\\$O(N)\\$</span> operation when <code>l</code> is a list, but is <span class=\"math-container\">\\$O(1)\\$</span> when <code>l</code> is a set, so can be significantly faster.</p>\n\n<p>Moreover, since a <code>set</code> naturally cannot contain duplicate entries, the test for containment before appending the item can be entirely removed and replace with a simple <code>.add(a)</code> call.</p>\n\n<hr>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8 -- Style Guide for Python Code</a> recommends a single space on both sides of the <code>=</code> assignment operator. So <code>l= []</code> should be written as <code>l = []</code>.</p>\n\n<hr>\n\n<p>The variable names <code>l</code> and <code>a</code> are not at all descriptive. You need to heavily comment the code to explain what these variables are, and what they are for, which you have not done.</p>\n\n<p>Using descriptive names significantly reduces the need to comment the code, as great naming will make the code self documenting. <code>l</code> could be <code>list_of_origin_headers</code> and <code>a</code> could be <code>an_origin_header</code>. While those names are very self documenting, they may be too long; brevity is also important. <code>origin_headers</code> and <code>origin</code> might be sufficient.</p>\n\n<hr>\n\n<p>First reworking, using above points:</p>\n\n<pre><code>import requests\n\norigin_headers = set()\n\nfor _ in range(5):\n origin = requests.get(\"https://google.com\", allow_redirects=True).headers['Origin']\n origin_headers.add(origin)\n\n# Convert set back into a list, to match the original design type\norigin_headers = list(origin_headers)\n</code></pre>\n\n<p>The only tricky point in this code is <code>origin_headers</code> starts off as a set, but becomes a list at the end of the code, so a comment was necessary.</p>\n\n<hr>\n\n<p>The code does something interesting enough to warrant its own function, which improves organization, and provides additional opportunity for documentation.</p>\n\n<pre><code>import requests\n\ndef fetch_origin_headers(url: str, repeat: int) -> list:\n \"\"\"\n Fetch the given URL several times, and return a list containing the unique\n 'Origin' headers.\n \"\"\"\n\n if repeat < 1:\n raise ValueError(\"Invalid repeat. Must be at least 1\")\n\n origin_headers = set()\n\n for _ in range(repeat):\n origin = requests.get(url, allow_redirects=True).headers['Origin']\n origin_headers.add(origin)\n\n # Return a list instead of the temporary set\n return list(origin_headers)\n\nif __name__ == '__main__':\n\n google_origins = fetch_origin_headers(\"https://google.com\", 5)\n</code></pre>\n\n<p>In addition to the new function, I've added some basic type-hints and the beginnings of a <code>\"\"\"docstring\"\"\"</code> to the function. I've also added a main-guard, so this \"test code\"(?) fetching the results of <code>https://google.com</code> is not always executed.</p>\n\n<hr>\n\n<p>Now that we've raise the bar a little, your Pythonista would look at the inner loop and think \"set comprehension\":</p>\n\n<pre><code>def fetch_origin_headers(url: str, repeat: int) -> list:\n \"\"\"\n Fetch the given URL several times, and return a list containing the unique\n 'Origin' headers.\n \"\"\"\n\n if repeat < 1:\n raise ValueError(\"Invalid repeat. Must be at least 1\")\n\n # Accumulate results in a set, to eliminate duplicates\n origin_headers = { requests.get(url, allow_redirects=True).headers['Origin']\n for _ in range(repeat) }\n\n # Return a list instead of the temporary set\n return list(origin_headers)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:55:06.993",
"Id": "473818",
"Score": "0",
"body": "Beat me to it! Funnily, our responses are very similar. Your explanations are way better however. Do you have a pointer/links as to how `set` containment is \\$ O(1) \\$? I did not know this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T17:43:02.250",
"Id": "473839",
"Score": "1",
"body": "@AlexPovel https://wiki.python.org/moin/TimeComplexity#set"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:45:18.097",
"Id": "241436",
"ParentId": "241416",
"Score": "2"
}
},
{
"body": "<p>Your code does not run as it is shown there.</p>\n\n<p>The problem, as mentioned in the comments, is that <code>int</code> <code>5</code> is not iterable.\n<code>range(5)</code> is, which would perform the action five times.</p>\n\n<p>Looking for</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if a not in l:\n l.append(a)\n</code></pre>\n\n<p>in each loop requires looking through that list each time.</p>\n\n<p>Using sets instead, this operation is still required somewhere under the hood, but likely faster (implemented on a lower level).\nWe also no longer have to care for it.\nIn the case here, a <code>set</code> can be used like the <code>list</code>, with the added benefit that <code>set</code>s can only hold unique entries.\nSince you care for the <em>different</em> values, and filter duplicates out manually with the code above, this is a step in the right direction.</p>\n\n<p>Generally, comprehensions are faster than manual looping and appending in Python.\nThere are also set comprehensions.</p>\n\n<p>One last issue I had was a <code>KeyError</code> for <code>\"Origin\"</code>.\nHowever, <code>\"Date\"</code> was available in the response, so I used that for demonstration purposes:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_google():\n return requests.get(\"https://google.com\", allow_redirects=True)\n\ndates = {get_google().headers[\"Date\"] for _ in range(5)}\n\nprint(dates)\n</code></pre>\n\n<p>My machine took more than one second for the five tries, so the output was:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>{'Wed, 29 Apr 2020 15:43:12 GMT', 'Wed, 29 Apr 2020 15:43:13 GMT'}\n</code></pre>\n\n<p>Two unique/different date entries (<code>str</code>) from five requests.</p>\n\n<p>If you want to build onto that, you can for example check if the response was <code>ok</code> (<code>200</code>) with the <code>ok</code> attribute of the <code>response.get()</code> object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:52:01.713",
"Id": "473833",
"Score": "0",
"body": "It is not `int 5`, it's `in(5)` and was `in (1,5)` before edits. Probably a tupel. When editing, he broke the code. Maybe wanted it to be `in (1,)` or something"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:49:43.690",
"Id": "241437",
"ParentId": "241416",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241436",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T07:34:06.313",
"Id": "241416",
"Score": "-1",
"Tags": [
"python",
"python-3.x",
"url"
],
"Title": "Collect a list of unique \"Origin\" headers from a repeated URL request"
}
|
241416
|
<p>I have the following code, that defines:</p>
<ol>
<li>A polynomial struct with some useful functions.</li>
<li>The newton Raphson algorithm for polynomials.</li>
</ol>
<p>and calculates <code>sqrt(2)</code>.
What can I improve?</p>
<p>There are some things I am unsure about myself:</p>
<ol>
<li><p>Is <code>size_t</code> a good datatype for my purposes? I needed to be very careful when writing the loop condition in the <code>eval</code> function. Is this a good place to switch to signed arithmetics?</p></li>
<li><p>Is my definition of <code>my_nan</code> a good way to ensure portability when switching to another floating point type?</p></li>
</ol>
<p>Things I am aware of:
I know, that the Newton Raphson for polynomials does not require the explicit construction of a derived polynomial and I am a bit wasteful on the memory.</p>
<pre><code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
typedef double real;
const real my_nan = ((real) 0.0) / ((real) 0.0);
typedef struct Polynomial {
real* coeffs;
size_t capacity;
} Polynomial;
Polynomial* create_poly(size_t capacity)
{
real* coeffs;
coeffs = malloc(capacity * sizeof(real));
if (coeffs == NULL) return NULL;
Polynomial* poly = malloc(sizeof(Polynomial));
if (poly == NULL) {
free(coeffs);
return NULL;
}
poly->coeffs = coeffs;
poly->capacity = capacity;
return poly;
}
void delete_poly(Polynomial* p)
{
free(p->coeffs);
free(p);
p = NULL;
}
size_t deg(const Polynomial*const p)
{
for (size_t i = p->capacity - 1; i > 0; i--) {
/* Here we actually want to compare reals exactly instead of |a - b| < eps */
if (p->coeffs[i] != 0.0) return i;
}
return 0;
}
void print(const Polynomial*const p)
{
size_t i;
for (i = 0; i < deg(p); ++i) {
printf("%f * x^%zu + ", p->coeffs[i], i);
}
printf("%f * x^%zu\n", p->coeffs[i], i);
}
real eval(const Polynomial*const p, real x)
{
/* Use Horner Scheme for evaluation */
size_t i = deg(p);
real res = p->coeffs[i];
for (; i-- > 0;) {
res = res * x + p->coeffs[i];
}
return res;
}
Polynomial* derive(const Polynomial*const p)
{
Polynomial* Dp = create_poly(p->capacity);
if (Dp == NULL) return NULL;
for (size_t i = 1; i < p->capacity; ++i) {
Dp->coeffs[i - 1] = ((real) i) * p->coeffs[i];
}
return Dp;
}
real newton_raphson_poly(const Polynomial*const p, real x0, real eps)
{
Polynomial* Dp = derive(p);
real x, prev = x0;
const int max_iter = 100;
for (int i = 0; i < max_iter; ++i) {
x = prev - eval(p, prev) / eval(Dp, prev);
if (fabs(x - prev) < eps) {
return x;
} else {
prev = x;
}
}
return my_nan;
}
int main()
{
Polynomial* p;
const real EPS = pow(10, -7);
p = create_poly(3);
p->coeffs[0] = -2;
p->coeffs[1] = 0;
p->coeffs[2] = 1;
printf("The result of sqrt(2) is given by the root of\n");
print(p);
printf("Its value is: %f \n", newton_raphson_poly(p, 1.0, EPS));
delete_poly(p);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Overall Impression</h2>\n\n<p>The code displays some good programming practices or habits. It is generally well structured, with well thought out functions. Good definitions of <code>typedef</code>s. The type <code>size_t</code> is used to index arrays instead of <code>int</code>.</p>\n\n<p>There are several potential bugs in the code. They are <code>potential</code> because they could happen, not that they would happen as the code is written currently.</p>\n\n<h2>Error Checking</h2>\n\n<p>While the return values of <code>malloc()</code> are checked, there should be some additional error checking in 2 places in the code. The first is that in <code>Polynomial* create_poly(size_t capacity)</code> before any memory allocation takes place, the value of the parameter <code>capacity</code> should be checked that is larger than zero, if not the memory allocation should not take place.</p>\n\n<p>The second place for additional error checking is in <code>main()</code>. If <code>p</code> after the call to <code>create_poly()</code> is NULL, assignments to <code>p</code> will fail, possibly causing a catastrophic error. This is one potential bug.</p>\n\n<h2>Memory Allocation</h2>\n\n<p>It might be better to use <a href=\"https://en.cppreference.com/w/c/memory/calloc\" rel=\"nofollow noreferrer\">calloc()</a> rather than <code>malloc()</code> in the following statement:</p>\n\n<pre><code> coeffs = malloc(capacity * sizeof(real));\n</code></pre>\n\n<p>The memory allocation function <code>calloc(size_t count, size_t size)</code> was written with arrays in mind. In addition to being slightly more readable, <code>calloc()</code> sets all of the values to zero when the array is allocated, which means the values in the array are initialized.</p>\n\n<pre><code> real* coeffs = calloc(capacity, sizeof(*coeffs));\n</code></pre>\n\n<p><em>Note</em> that in the example of <code>calloc()</code> usage the <code>sizeof()</code> argument is what <code>coeffs</code> points to. This allows who ever is maintaining the code to change the type of <code>coeffs</code> without have to modify more than the type itself. If the type <code>real</code> was used in the statement, there would be 2 places to change the code and not one.</p>\n\n<h2>Unnecessary Statement</h2>\n\n<p>In the function <code>void delete_poly(Polynomial* p)</code> the statement <code>p = NULL;</code> is unnecessary. Since <code>p</code> was passed in instead of a pointer to <code>p</code> it only affects the local value of <code>p</code>, it does not affect the value of <code>p</code> in <code>main()</code>.</p>\n\n<h2>Initialize Variables When They are Declared</h2>\n\n<p>In at lest 2 places in the code variables are declared on one line and then initialized on another line like the initialization is an after thought. A better habit to get into is to initialize the variables as they are declared. This can lead to less bugs and less debugging of code.</p>\n\n<p>In <code>main()</code>:</p>\n\n<pre><code> Polynomial* p;\n const real EPS = pow(10, -7);\n p = create_poly(3);\n</code></pre>\n\n<p>Versus</p>\n\n<pre><code> const real EPS = pow(10, -7);\n Polynomial* p = create_poly(3);\n</code></pre>\n\n<p>In <code>create_poly()</code></p>\n\n<pre><code> real* coeffs;\n\n coeffs = malloc(capacity * sizeof(real));\n if (coeffs == NULL) return NULL;\n</code></pre>\n\n<p>Versus</p>\n\n<pre><code> real* coeffs = malloc(capacity * sizeof(real));\n if (coeffs == NULL) return NULL;\n</code></pre>\n\n<h2>Magic Numbers</h2>\n\n<p>There are Magic Numbers in the <code>main()</code> function (10 and -7), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n\n<p>The code already has a symbolic constant defined in <code>real newton_raphson_poly(const Polynomial*const p, real x0, real eps)</code>.</p>\n\n<pre><code> const int max_iter = 100;\n</code></pre>\n\n<p>Write the code consistently.</p>\n\n<h2>Possible Optimizations</h2>\n\n<p>The code in <code>main()</code> could be more flexible or extensible if it modified to create an array of coefficients and get the size of the array as the capacity. The code to copy the coefficients into the Polynomial struct could be an additional function, or it could also be added to <code>create_poly(size_t capacity, real coeffs[])</code>.</p>\n\n<pre><code>int main()\n{\n real coeffs[] = {-2, 0, 1};\n size_t capacity = sizeof(coeffs) / sizeof(*coeffs);\n\n const real EPS = pow(10, -7);\n Polynomial* p = create_poly(capacity);\n\n real* poly_coeffs_ptr = &p->coeffs[0];\n real* coeffs_ptr = &coeffs[0];\n for (size_t i = 0; i < capacity; i++)\n {\n *poly_coeffs_ptr = *coeffs_ptr;\n }\n\n printf(\"The result of sqrt(2) is given by the root of\\n\");\n print(p);\n printf(\"Its value is: %f \\n\", newton_raphson_poly(p, 1.0, EPS));\n\n delete_poly(p);\n}\n</code></pre>\n\n<p>Reordering of <code>malloc()</code>s might lead to less code.</p>\n\n<pre><code>Polynomial* create_poly(size_t capacity)\n{\n if (capacity > 0)\n {\n Polynomial* poly = malloc(sizeof(Polynomial));\n if (poly != NULL)\n {\n poly->coeffs = calloc(capacity, sizeof(real));\n if (poly->coeffs == NULL)\n {\n free(poly);\n poly = NULL;\n }\n }\n return poly;\n }\n\n return NULL;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T07:26:57.210",
"Id": "473904",
"Score": "1",
"body": "Thank you very much for this thorough review. Regarding the inconsistent initialization in the declaration, I just realized an unconscious pattern in my code. I have to program a lot in Fortran and if you initialize something in the declaration it becomes a static variable (for whatever reason). So I had to hammer into my head to do this only for constants and especially not for local variables in a function. Apparently I took this over to C."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T17:39:12.957",
"Id": "241445",
"ParentId": "241418",
"Score": "2"
}
},
{
"body": "<p><strong>Weak EPS test</strong></p>\n\n<p>The following is only useful for differences on a narrow power-of-2 range. This approach is taking the float out of floating point.</p>\n\n<pre><code>if (fabs(x - prev) < eps) // weak\n</code></pre>\n\n<p>When <code>x, prev</code> are small like 10e-10 the result is always true. Not useful to find the of sqrt(10e-20).</p>\n\n<p>When <code>x, prev</code> are large like 10e+12 the result may never be true as the large difference wobbles around 0.0.</p>\n\n<p>Instead with <em>floating point</em>, this nearness test needs to consider the magnitudes of <code>x, prev</code>.</p>\n\n<p>Something like <code>fabs(x - prev)/fabs(x + prev) < eps</code> can make sense - with additional code to protect against division by zero and overflow.</p>\n\n<p>This is a deep subject and better tests exist. Usually what is best is depends on the situation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T02:57:23.063",
"Id": "241471",
"ParentId": "241418",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241445",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:05:22.613",
"Id": "241418",
"Score": "3",
"Tags": [
"beginner",
"c",
"numerical-methods"
],
"Title": "Newton Raphson and polynomials in C"
}
|
241418
|
<p>Below is a React useEffect hook I used in my application, basically what it does is:</p>
<p><code>data</code> is an array for objects such as <code>{round:number, date:dateString}</code>.</p>
<p>When the application starts running, <code>data</code> will be an empty array, whenever <code>round</code> gets updated, the <code>useEffect()</code> will be called:</p>
<ol>
<li>if the <code>data</code> array is empty, we update it with its very first object.</li>
<li>else the <code>data</code> array is not empty and if the last object of data array has its date property equal to <code>props.localeDate</code>, I make a new array with the its last object updated</li>
<li>else the data array is not empty and else the last object's date property is not equal to <code>props.localeDate</code>, I append a new object to data array.</li>
</ol>
<hr>
<pre><code>const Chart = ({ round, dateAndTime }) => {
const [data, setData] = useState([]);
const localeDate = dateAndTime.toLocaleDateString();
useEffect(() => {
if (data.length === 0) {
setData([
...data,
{
round: round,
date: localeDate,
},
]);
} else {
//update item if date matches
if (data[data.length - 1].date === localeDate) {
let newData = data.map((item) => {
let newItem =
item.date === localeDate ? { ...item, round: round } : item;
return newItem;
});
setData(newData);
} else {
setData([...data, { round: round, date: localeDate }]);
}
}
}, [round]);
return (jsx element);
}
</code></pre>
<p>My code works as expected, but I am wondering if there is any way to improve on it? Using if-else looks really ugly.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T20:51:22.857",
"Id": "473855",
"Score": "0",
"body": "@BCdotWEB, true, thanks. Updated as per your suggestion"
}
] |
[
{
"body": "<p>Note that you do the <em>same thing</em> if the array is empty or if the last item's <code>localeDate</code> doesn't match - you can combine those two paths.</p>\n\n<p>You only want to update the existing object if the last item exists and its date matches, so I'd first set a flag for that, which can be done concisely via optional chaining.</p>\n\n<p>Then, <code>.map</code> looks a bit verbose when all items of the array are unchanged <em>except for one</em> - you could consider using <code>.slice</code> instead to take all but the last item, spread them into a new array, then add the changed object as the last item.</p>\n\n<pre><code>useEffect(() => {\n // update item if date matches\n const changeExistingItem = data[data.length - 1]?.date === localeDate;\n const updatedData = changeExistingItem\n ? [...data.slice(0, data.length - 1), { ...data[data.length - 1], round }]\n : [...data, { round, date: localeDate }];\n setData(updatedData);\n}, [round]);\n</code></pre>\n\n<p>Also see that you can use shorthand property names to keep things concise: <code>{ someProp: someProp</code> simplifies to <code>{ someProp</code> in modern Javascript.</p>\n\n<p>As a side note: <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">always use <code>const</code></a> to declare variables, whenever possible. When you use <code>let</code>, you're warning readers of the code that you <em>may be reassigning</em> that variable name in the future, which results in more cognitive overhead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T11:29:56.820",
"Id": "473765",
"Score": "0",
"body": "thank you so much for your detailed answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T11:14:26.287",
"Id": "241423",
"ParentId": "241420",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241423",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:44:03.210",
"Id": "241420",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "Is there more elegant way than using if - else to append or update the data array in a React app?"
}
|
241420
|
<p>So, a long time ago, I've made a program that prints all the permutations of digits of a number in AEC. Now I have refactored it a bit, and I would be interested in what you think about it.</p>
<pre><code>;Advanced example: implementing the permutation algorithm.
AsmStart
debug=0
macro pushIntegerToTheSystemStack x
{
sub esp,4
fld dword [x]
fistp dword [esp]
}
macro pushPointerToTheSystemStack x
{
sub esp,4
lea ebx,[x]
mov [esp],ebx
}
macro pushStringToTheSystemStack x
{
sub esp,4
mov dword [esp],x
}
format PE console
entry start
include 'win32a.inc'
section '.text' code executable
start:
jmp enterNumber$
enterNumber db "Enter a whole number (1 - 1'000'000).",10,0
enterNumber$:
pushStringToTheSystemStack enterNumber
call [printf]
pushPointerToTheSystemStack original
jmp floatSign$
floatSign db "%f",0
floatSign$:
pushStringToTheSystemStack floatSign
call [scanf]
jmp permutationString$
permutationString db "The permutations of its digits are:",10,0
permutationString$:
pushStringToTheSystemStack permutationString
call [printf]
AsmEnd
numberOfPermutations:=0
numberOfDigits:=0
i:=0
While i<10
countDigits[i] := 0
i:=i+1
EndWhile
While original>0
numberOfDigits := numberOfDigits + 1
lastDigit := mod (original, 10)
countDigits [lastDigit] := countDigits (lastDigit) + 1
original := (original - lastDigit) / 10
EndWhile
AsmStart
if debug=1
AsmEnd
i:=0
While i<10
subscript:=4*i
AsmStart
fld dword [subscript]
fistp dword [subscript]
mov ebx,[subscript]
pushIntegerToTheSystemStack (countDigits+ebx)
pushStringToTheSystemStack integerSign
call [printf]
AsmEnd
i:=i+1
EndWhile
AsmStart
pushStringToTheSystemStack newLineString
call [printf]
AsmEnd
AsmStart
end if
AsmEnd
topOfMyStack:=1
myStack [ (numberOfDigits + 1) ] := 0
While topOfMyStack>0
currentNumberOfDigits := myStack ( topOfMyStack * ( numberOfDigits + 1 ) )
i:=0
While i<currentNumberOfDigits
currentNumber ( i ) := myStack ( topOfMyStack * ( numberOfDigits + 1 ) + ( i + 1 ) )
i:=i+1
EndWhile
AsmStart
if debug=1
AsmEnd
i:=0
While i<currentNumberOfDigits
subscript:=i*4
AsmStart
fld dword [subscript]
fistp dword [subscript]
mov ebx,[subscript]
pushIntegerToTheSystemStack (currentNumber+ebx)
pushStringToTheSystemStack integerSign
call [printf]
AsmEnd
i:=i+1
EndWhile
AsmStart
pushStringToTheSystemStack newLineString
call [printf]
AsmEnd
AsmStart
end if
AsmEnd
topOfMyStack:=topOfMyStack-1
If currentNumberOfDigits=numberOfDigits
numberOfPermutations:=numberOfPermutations+1
i:=0
While i<numberOfDigits
subscript:=i*4
AsmStart
fld dword [subscript]
fistp dword [subscript]
mov ebx,[subscript]
pushIntegerToTheSystemStack (currentNumber+ebx)
pushStringToTheSystemStack integerSign
call [printf]
AsmEnd
i:=i+1
EndWhile
AsmStart
pushStringToTheSystemStack newLineString
call [printf]
AsmEnd
Else
i:=0
While i<10
counter:=0
j:=0
While j<currentNumberOfDigits
If currentNumber(j)=i
counter:=counter+1
EndIf
j:=j+1
EndWhile
If counter < countDigits(i)
topOfMyStack := topOfMyStack + 1
myStack (topOfMyStack * (numberOfDigits + 1) ) := currentNumberOfDigits + 1
j:=0
While j < currentNumberOfDigits
myStack (topOfMyStack * (numberOfDigits + 1) + (j + 1)) := currentNumber (j)
j:=j+1
EndWhile
myStack (topOfMyStack * (numberOfDigits + 1) + (j + 1) ) := i
EndIf
i:=i+1
EndWhile
EndIf
EndWhile
AsmStart
jmp numberOfPermutationsString$
numberOfPermutationsString:
db "The total number of permutations was: %d",10,0
numberOfPermutationsString$:
pushIntegerToTheSystemStack numberOfPermutations
pushStringToTheSystemStack numberOfPermutationsString
call [printf]
invoke system,_pause
invoke exit,0
_pause db "PAUSE",0
integerSign db "%d",0
newLineString db 10,0
section '.rdata' readable writable
original dd ?
result dd ?
lastDigit dd ?
numberOfDigits dd ?
countDigits dd 11 dup(?)
subscript dd ?
myStack dd 1000 dup(?)
topOfMyStack dd ?
counter dd ?
i dd ?
currentNumber dd 11 dup(?)
currentNumberOfDigits dd ?
j dd ?
numberOfPermutations dd ?
section '.idata' data readable import
library msvcrt,'msvcrt.dll'
import msvcrt,printf,'printf',system,'system',exit,'exit',scanf,'scanf'
AsmEnd
</code></pre>
<p>The 32-bit Windows executable is available <a href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/ArithmeticExpressionCompiler.zip" rel="nofollow noreferrer">here</a>, it's called <code>permutations.exe</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:29:11.217",
"Id": "473793",
"Score": "1",
"body": "Why assembly? These days it's not a common choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:59:05.123",
"Id": "473798",
"Score": "0",
"body": "@Reinderien, Assembly is used to call C functions \"printf\" and \"scanf\". The algorithm is written in AEC. I thought it was obvious."
}
] |
[
{
"body": "\n\n<h2>Coding style</h2>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>numberOfDigits:=0\nnumberOfDigits := numberOfDigits + 1\ncountDigits[i] := 0\ncountDigits [lastDigit] := countDigits (lastDigit) + 1\nmyStack [ (numberOfDigits + 1) ] := 0\nmyStack (topOfMyStack * (numberOfDigits + 1) ) := currentNumberOfDigits + 1\n</code></pre>\n</blockquote>\n\n<p>Throughout the program your use of whitespace and brackets is inconsistent.<br>\nEven if you have the choice between <code>[]</code> and <code>()</code> to address array elements, you should choose one of them and stick with your choice.<br>\nThis fickleness is especially annoying in <code>countDigits [lastDigit] := countDigits (lastDigit) + 1</code></p>\n\n<h2>Alternative</h2>\n\n<p>You can remove the high level <code>subscript:=4*i</code> if you use a scaled address form:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> i:=0\n While i<10\n AsmStart\n fld dword [i]\n fistp dword [subscript]\n mov ebx, [subscript]\n pushIntegerToTheSystemStack (countDigits + ebx * 4)\n ...\n</code></pre>\n\n<h2>Warning</h2>\n\n<p>It's nice that you prompt the user for a non-zero number but your program should actually verify this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-10T20:26:53.680",
"Id": "242049",
"ParentId": "241421",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242049",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T10:48:31.413",
"Id": "241421",
"Score": "2",
"Tags": [
"combinatorics",
"assembly"
],
"Title": "Printing all permutations of digits of a number"
}
|
241421
|
<p>My code has mutiple checks for if staments which I think could be optimized into few lines if I take id into varibable. To give some background I want to disable a button based on length of characters in input box. But the thing is out of two buttons only one will be rendered at a time.
Below is my working version of code which I am hoping to optimize.</p>
<pre><code> var sortcodeError = document.getElementById("sortcodeError")
var accountnameError = document.getElementById("accountnameError")
if (sortcodeError != null) {
document.getElementById("sortcodeError").disabled = false;
}
if (accountnameError != null) {
document.getElementById("accountnameError").disabled = false;
}
if ($scope.data.branchTransitNumber && $scope.data.depositAccountNumber) {
if ($scope.data.branchTransitNumber.length < 6) {
if (sortcodeError != null) {
document.getElementById("sortcodeError").disabled = true;
}
if (accountnameError != null) {
document.getElementById("accountnameError").disabled = true;
}
}
if ($scope.data.depositAccountNumber.length < 8) {
if (sortcodeError != null) {
document.getElementById("sortcodeError").disabled = true;
}
if (accountnameError != null) {
document.getElementById("accountnameError").disabled = true;
// angular.element($('#btnSubmi')).addClass("gray");
}
}
}
</code></pre>
<p>My initial thought is if I could take <code>id</code> as varibale but then I don't think it is the best way</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T12:18:19.737",
"Id": "473778",
"Score": "0",
"body": "The current question title, which states your concerns about the code, 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. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:50:20.350",
"Id": "473796",
"Score": "0",
"body": "@Mast yes I will and change the title"
}
] |
[
{
"body": "<p>Since exactly one element will exist at a time, you can retrieve it by alternating with <code>||</code> between both <code>getElementById</code> calls. Then, there's no need for any existence test later.</p>\n\n<p>Since you set disabled to true in both <code>branchTransitNumber.length < 6</code> and <code>depositAccountNumber.length < 8</code>, you can combine those blocks together:</p>\n\n<pre><code>const button = document.getElementById('sortcodeError') || document.getElementById('accountnameError');\nbutton.disabled = false;\nif ($scope.data.branchTransitNumber && $scope.data.depositAccountNumber) {\n if ($scope.data.branchTransitNumber.length < 6 || $scope.data.depositAccountNumber.length < 8) {\n button.disabled = true;\n }\n}\n</code></pre>\n\n<p>(The above can be made even more concise via destructuring or optional chaining to avoid the double <code>if</code>s, but I think it'd look too confusing.)</p>\n\n<p>Or, if you need the <code>addClass</code> call <em>only</em> in the case of <code>$scope.data.depositAccountNumber.length < 8</code> <strong>and</strong> <code>accountnameError</code> existing:</p>\n\n<pre><code>const button = document.getElementById('sortcodeError') || document.getElementById('accountnameError');\nbutton.disabled = false;\nif ($scope.data.branchTransitNumber && $scope.data.depositAccountNumber) {\n const depositNumberProblem = $scope.data.depositAccountNumber.length < 8;\n if ($scope.data.branchTransitNumber.length < 6 || depositNumberProblem) {\n button.disabled = true;\n if (depositNumberProblem && button.id === 'accountnameError') {\n angular.element($('#btnSubmi')).addClass(\"gray\");\n }\n }\n}\n</code></pre>\n\n<p>Depending on the logic of your script, the above may be simplifiable. For example, you may wish to do <code>.addClass(\"gray\")</code> regardless when you disable the button.</p>\n\n<p>Other notes:</p>\n\n<ul>\n<li>It's 2020, best to <em>at least</em> use ES2015 syntax in new code by declaring variables with <code>const</code>, not <code>var</code> (which has too many gotchas)</li>\n<li>Whenever you do have to compare two different values, use strict equality with <code>===</code> or <code>!==</code> - avoid loose equality <code>==</code> and <code>!=</code>, since loose equality has <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">too many strange rules</a> that a developer should not have to memorize.</li>\n<li>If the alternation trick above weren't possible, you'd still be able to reference the variable names you saved the elements into to keep things concise. Eg, with <code>const sortcodeError = document.getElementById(\"sortcodeError\")</code>, you should never have to call <code>document.getElementById(\"sortcodeError\")</code> later - instead, just reference the <code>sortcodeError</code> variable.</li>\n<li>Use consistent indentation. If one statement is in the same block as another, it should begin at the same indentation level. This significantly improves a code's readability.</li>\n<li>Either use semicolons wherever appropriate, or don't. (If you're not an expert, I'd recommend using them, otherwise you'll occasionally run into strange bugs.) Consider using <a href=\"http://eslint.org/\" rel=\"nofollow noreferrer\">a linter</a> to automatically prompt you to fix potential mistakes (and to make the code nicer-looking).</li>\n<li>The overall logic looks a bit weird. Do you <em>really</em> need to check that both <code>branchTransitNumber</code> and <code>depositAccountNumber</code> exist, but disable a button if <em>either</em> of them fail a length test? In a validation situation, I'd expect to disable a button if either fail, rather than if <em>both exist <strong>and</strong> either fail</em>. Double-check the logical paths your code requires and results in, and consider what sort of effect you <em>really</em> want.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:55:56.847",
"Id": "473797",
"Score": "0",
"body": "About last point. I am really new to this and when I didn't check if they exist or not. It gave me length of null error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:59:09.707",
"Id": "473799",
"Score": "0",
"body": "If it's just to avoid the error, then check *separately*, not together. Eg `if ((branchTransitNumber && branchTransitNumber.length < 6) || (depositAccountNumber && depositAccountNumber.length < 8))`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T12:33:49.777",
"Id": "241425",
"ParentId": "241424",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241425",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T11:53:59.643",
"Id": "241424",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "multiple if statements check optimize"
}
|
241424
|
<p>I'm looking for input on how to improve a powershell script I wrote.
Im especially looking for suggestions, that I might be able to apply to future projects as well. Like (anti-)patterns I'm not aware of and such.
General things like "too many small functions" vs "use more functions" or "better collect all info in a certain object type" and stuff like that is what im looking for.<br>
If anyone has experience with the Cmd-lets I use and is willing to share, more specific suggestions are welcome aswell of course.</p>
<p>The script is used in a cluster of 4 HyperV hosts that each run about 30 Virtual Machines.
There is the concept of replication in Hyper-V. It works like this:<br>
You can create a replication of a VM running on one Hyper-V server and have this replication running (in a shutdown state) on another Hyper-V server in the cluster.
I will call these two the <strong>production-vm</strong> and the <strong>failover-vm</strong> . If the failover is done then the former production-vm becomes the failover-vm and vice versa.
In theory there can be replications of replications and so on. The script has to be scheduled to run every so often, because where vms (and their replications) are located is somewhat dynamically - changes happen a few times a year.</p>
<p>The script is executed on a 5th server outside of the cluster.</p>
<p>The script should accomplish the following: </p>
<ul>
<li>take the name of a production-vm and lookup what the corresponding failover-vm is.
This must work the other way around too!</li>
<li>create a VMGroup on all Hyper-V hosts with a name that resembles the vm we were looking up</li>
<li>add both the production-vm and the failover-vm to their groups.
<ul>
<li>since VMGroups are local to a Hyper-V host they can have the same name on all hosts but should usually contain either the <strong>production-vm</strong> or the <strong>failover-vm</strong> or <strong>no vm</strong> at all.</li>
</ul></li>
</ul>
<p>So here is the code:</p>
<pre><code># This script looks up VMs and their corresponding failover-vms (usually named xxx_replika) and adds them to VMGroups called LTR_<vmname>.
#
$LTR_VMs = $LTR_VMs = "VM-ELO01", "VM-FILE01", "VMs03", "VMs71", "VMs72", "VM-SBO02"
$HVhosts = "hv01.example.com", "hv02.example.com", "hv05.example.com", "hv06.example.com"
function Get_VM_and_Replica_by_name_remote([array]$HVhosts, [String]$VMname) {
$searchedVM = Get-VM -name $VMname -ComputerName $HVHosts
$searchedReplica = Get-VMReplication -VM $searchedVM ## can't get failoverVM directly since HyperV server A cannot authenticate vs HyperV server B
#construction of an array to return both vm-objects to the caller:
$searchedVM2 = Get_VM_by_VMReplication_remote -VMReplication $searchedReplica
$bothVMs = @()
$bothVMs += $searchedVM
$bothVMs += $searchedVM2
return ,$bothVMs
## returning to caller will 'deserialize' the vms in the array. This will be problematic later when we add those vm-objects to a VMGroup
}
function Get_VM_by_VMReplication_remote($VMReplication) {
# if this VMReplication-Object is a Primary, then get the VM-Object from the Replication Server (where the failover vm runs)
if ($VMReplication.Mode -eq "Primary") {
Invoke-Command -ComputerName $VMReplication.ReplicaServerName -ScriptBlock {
$VM = Get-VM -Id $Using:VMReplication.Id
$VM
}
}
# if this VMReplication-Object is a Replica, then get the VM-Object from the Primary Server (where the production VM runs)
if ($VMReplication.Mode -eq "Replica") {
Invoke-Command -ComputerName $VMReplication.PrimaryServerName -ScriptBlock {
$VM = Get-VM -Id $Using:VMReplication.Id
$VM
}
}
}
function Create_GroupName([String]$VMName){
$prefix = "LTR_"
$Groupname = $prefix + $VMName
return $Groupname
}
function RemoveVMs_from_Group_remote([array]$HVhosts, [String]$GroupName) {
foreach ( $HVhost in $HVhosts) {
Invoke-Command -ComputerName $HVhost -ScriptBlock {
$vms = (Get-VMGroup -Name $Using:GroupName).VMMembers
foreach ($vm in $vms) {
Remove-VMGroupMember -Name $Using:GroupName -VM $vm
}
}
}
}
# add all VMs to group on their respective HVhost:
# must use Invoke-Command because of deserialization issue with vms in our array
function Add_VMs_to_VMGroup_remote([array]$VMs, [String]$Groupname) {
foreach ( $VM in $VMs) {
Invoke-Command -ComputerName $VM.ComputerName -ScriptBlock {
$thisVM = Get-VM -Id $Using:VM.VMId
Write-Host "adding $($thisVM.VMName) to Group $($Using:Groupname) on $($Using:VM.ComputerName)."
Add-VMGroupMember -Name $Using:Groupname -vm $thisVM
}
}
}
foreach ($name in $LTR_VMs) {
$vmPair = (Get_VM_and_Replica_by_name_remote -HVHosts $HVHosts -VMname $name )
$myGroupName = Create_GroupName -VMName $name
# make sure group exists on all HyperV-hosts:
foreach ($HVhost in $HVHosts) {
$VMGroupX = Get-VMGroup -Name $myGroupName -ComputerName $HVhost
if (!$VMGroupX) {
New-VMGroup -Name $myGroupName -ComputerName $HVhost -GroupType VMCollectionType
Write-Host "Created group $myGroupName on $($HVhost)."
}
}
RemoveVMs_from_Group_remote -HVHosts $HVHosts -Groupname $myGroupName
Add_VMs_to_VMGroup_remote -VMs $vmPair -Groupname $myGroupName
}
#careful with vms with more than 1 replication like VMs33. Doesn't work fine because if you lookup the replicaname, you may get back two replicas and not the primary vm.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T12:55:36.043",
"Id": "473783",
"Score": "2",
"body": "The current question title, which states your concerns about the code, 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. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:59:31.650",
"Id": "473807",
"Score": "1",
"body": "@Mast thanks for your input. I edited the title accordingly"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T12:40:03.860",
"Id": "241426",
"Score": "4",
"Tags": [
"design-patterns",
"powershell"
],
"Title": "Add VMs and corresponding replications to VMGroups in a Hyper-V cluster"
}
|
241426
|
<p>I have an almost-json document in a file named "versions.json" like this:</p>
<pre><code>{
"package_a": {
"sha_darwin": "6d94f041d06670977b2e5604b827f7e8bd46a1d200d14545ba75c17314ec12ad",
"sha_linux": "6daa0fae252dc32e0af6ad89119555b277456349c55dfc9f276ee83718c6a9e2",
"url": "https://github.com/someone/package_a/releases/download/v\(.version)/package_a_\(.version)_\(.platform)_x86_64.tar.gz",
"version": "1.2.3"
}, "package_b": {
"sha_darwin": "6d94f041d06670977b2e5604b827f7e8bd46a1d200d14545ba75c17314ec12ad",
"sha_linux": "6daa0fae252dc32e0af6ad89119555b277456349c55dfc9f276ee83718c6a9e2",
"url": "https://storage.googleapis.com/package_b/release/v\(.version)/package_b_\(.version)_\(.platform)/amd64/package_b",
"version": "6.3.0"
}
}
</code></pre>
<p>It's input from a third party and I can't change it. What I need to do is interpolate the platform and version into the url. The problem is that that <code>version</code> value comes from the version in the file itself. I can't <em>quite</em> get it in the raw file because it's not actually valid json.</p>
<pre><code>jq -r . versions.json
parse error: Invalid escape at line 5, column 129
</code></pre>
<p>I can get this in two passes:</p>
<pre><code>echo '{"platform":"darwin","version":""}' |
jq -f versions.json |
jq -r '{version:.package_a.version,platform:"darwin"}' |
jq -f versions.json |
jq -r '"curl -sSL \(.package_a.url | @sh)"' |
sh
</code></pre>
<p>But I'm not happy with the number of pipes and invocations of jq here, and looking to improve this all around. I would prefer a solution that involves a single invocation of jq, if that can be done.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:54:40.553",
"Id": "241428",
"Score": "2",
"Tags": [
"json",
"sh"
],
"Title": "Re-interpolating a value from jq back into jq"
}
|
241428
|
<p>Below is a method used in my application that reassigns a vehicle to a depot. Is there a better way of handling these conditionals than the boolean statements I have in place? </p>
<p>Some things to note are <code>Vehicle</code> and <code>Depot</code> are classes and <code>Depot</code> has an ArrayList of <code>Vehicles</code> Inside it. <code>depoNo</code> is set earlier in the program in order for the program to know what depot to reference in the <code>Depots</code> arraylist.
<code>vehicleSelection</code> is used to get the users choice of vehicle.<code>depotSelection</code> is used in the same manner apart from applying to <code>Depots</code></p>
<p>Most of the error checking is handled by the boolean's, but this makes the code look extremely ugly and long winded, what would be the best case scenario for me to do here?</p>
<pre><code> public void reAssignVehicles()
{
String vehicleSelection;
String depotSelection = "";
boolean exit = false, validReg = false, validLocation = false;
int i = 0; // used to count which depot selected
Vehicle v;
if (!depots.get(depotNo).getVehicles().isEmpty())
{
do
{
System.out.println("Depots");
depots.get(depotNo).listVehicles();
System.out.printf("%nSelect the registration number of the vehicle you wish to reassign: %n");
vehicleSelection = input.nextLine();
for (Vehicle vehicle : depots.get(depotNo).getVehicles())
{
if (vehicleSelection.equals(vehicle.getRegNo()))
{
validReg = true;
System.out.printf("%nYou have selected vehicle: %s%n", vehicleSelection);
listDepots();
System.out.printf("%nPlease select the depot you want to reassign this vehicle to: %n");
depotSelection = input.nextLine();
for (Depot d : depots)
{
if (depotSelection.equals(d.getDepotLocation()) && !depotSelection.equals(vehicle.getDepot())) // if the vehicle exists at depot
{
validLocation = true;
System.out.printf("%nVehicle %s is now assigned to %s%n", vehicleSelection, depotSelection);
exit = true;
break;
}
else
{
validLocation = false;
}
i++;
}
}
else
{
validReg = false;
}
}
if (!validReg) //To prompt user to enter correct information
{
System.out.printf("Please select a valid registration%n%n");
}
if (!validLocation)
{
System.out.printf("%nThe vehicle is either already assigned to the depot, or the depot does not exist%n%n");
}
if (validLocation) {
v = depots.get(depotNo).getVehiclebyReg(vehicleSelection);
v.setDepot(getDepot(depotSelection));
depots.get(i).makeVehicle(v);
depots.get(depotNo).getVehicles().remove(v);
}
} while (!exit);
} else {
System.out.println("There are no vehicles in the Depot to reassign");
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T06:41:47.240",
"Id": "473896",
"Score": "1",
"body": "I do *not* want to guess what `depots` or `input` is: Please provide enough context to support meaningful reviews. Heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)"
}
] |
[
{
"body": "<p>First off, there is quite a bit of context missing for a good review, most importantly: What is the purpose of the class that this method belongs to? This method contains a mixture of frontend code and buiness code, suggesting that you generally haven't divided up your code properly.</p>\n\n<p>Also why does this class have a field <code>depotNo</code>, which only serves as the argument in the expression <code>depots.get(depotNo)</code> multiple times? At the very least this method should call <code>Depot depot = depots.get(depotNo);</code> once. Better would be that <code>Depot depot</code> be either a field in the class (replacing <code>depotNo</code>) or be an argument passed to this method.</p>\n\n<hr>\n\n<p>Don't define all your variables at the start of the method. Allways define them as late as possible in the smallest needed scope.</p>\n\n<hr>\n\n<p>Keep the number of indention levels as low as possible. For example, at the start instead of putting the whole functionallity inside the <code>if (!depots.get(depotNo).getVehicles().isEmpty())</code> block, exit the method there and then and put the rest of the code on the same level:</p>\n\n<pre><code>public void reAssignVehicles() {\n Depot depot = depots.get(depotNo);\n if (depot.getVehicles().isEmpty()) {\n System.out.println(\"There are no vehicles in the Depot to reassign\");\n return;\n }\n\n do {\n // ...\n</code></pre>\n\n<hr>\n\n<p>You also loop over the list of vehicles to find the selected vehicle, however have and use a method that already does that, so you are looking up the vehicle twice. </p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:01:41.750",
"Id": "473820",
"Score": "0",
"body": "The reason I only added this method is because much of the code is similar to this, with what you've suggested I have plenty to fix, including using depots.get throughout my code. So thank you for that you've said I have plenty to fix now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T17:52:44.297",
"Id": "473842",
"Score": "1",
"body": "Since it is definitely missing context this question should not have been answered, there should have been a comment and a vote to close."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T19:19:39.587",
"Id": "474110",
"Score": "0",
"body": "@David Next time, please don't forget to post the rest of the context as well."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:03:05.950",
"Id": "241433",
"ParentId": "241429",
"Score": "1"
}
},
{
"body": "<pre><code>if (!depots.get(depotNo).getVehicles().isEmpty())\n{\n ... lots of code\n} else {\n System.out.println(\"There are no vehicles in the Depot to reassign\");\n}\n</code></pre>\n\n<p>Here the <code>println</code> is performed and then the method returns. In that case it is better to perform a <strong>positive</strong> if and then exit early:</p>\n\n<pre><code>if (depots.get(depotNo).getVehicles().isEmpty()) {\n System.out.println(\"There are no vehicles in the Depot to reassign\");\n return;\n}\n</code></pre>\n\n<p>... lots of code</p>\n\n<p>That does the same thing, but it means you don't have to indent the code. It immediately makes clear what the program does if the depot is empty, and then lets the reader forget about it.</p>\n\n<p>Note that you either use Egyptian brackets (braces) or you don't. Most Java programmers do use it, so I would place the brace at the end of the <code>if</code> statement. However, if you don't then:</p>\n\n<pre><code>} else {\n</code></pre>\n\n<p>is not consequent, you would use:</p>\n\n<pre><code>}\nelse\n{\n</code></pre>\n\n<p>instead.</p>\n\n<hr>\n\n<pre><code> do\n</code></pre>\n\n<p>Generally there is no need to document a <code>do ... while</code> loop, but if the <code>while</code> is that far away, you need to make clear what the loop does here.</p>\n\n<hr>\n\n<pre><code>String depotSelection = \"\";\n</code></pre>\n\n<p>This is not very Java-like. In Java you declare the variable as late as possible. And if you assign it a value anyway, then you don't first need to assign the empty string to it.</p>\n\n<hr>\n\n<pre><code>int i = 0; // used to count which depot selected\n</code></pre>\n\n<p>Why not call it <code>selectedDepotNr</code> in that case? Then you don't need the comment anymore. Besides, a <em>count</em> is not an identifier.</p>\n\n<p>And it defaults to zero? Why? Is zero some kind of magic value?</p>\n\n<hr>\n\n<pre><code>System.out.println(\"Depots\");\n</code></pre>\n\n<p>You are mixing the user interface code with the \"business logic\", which is not a good idea. If you create a method then you need to separate the retrieval of user input and the actual running of the code. That of course also goes for <code>input.nextLine</code>.</p>\n\n<hr>\n\n<pre><code>depots.get(depotNo).listVehicles();\n</code></pre>\n\n<p>There there is a depot that performs output. First of all, it is entirely unclear that <code>listVehicles</code> produces output at all (<code>printVehicles</code> is better), but nowadays we try and not let the data object perform the output itself, let alone let it choose where to output it.</p>\n\n<hr>\n\n<pre><code>depots.get(depotNo).listVehicles();\nSystem.out.printf(\"%nSelect the registration number of the vehicle you wish to reassign: %n\");\nvehicleSelection = input.nextLine();\nfor (Vehicle vehicle : depots.get(depotNo).getVehicles())\n</code></pre>\n\n<p>Here <code>depots.get(depotNo)</code> gets called twice in quick succession, with the same <code>depotNo</code>. In that case you should assign to a <code>depot</code> variable so the method is only called <em>once</em>. Lookup the DRY principle.</p>\n\n<hr>\n\n<pre><code>!depotSelection.equals(vehicle.getDepot())\n</code></pre>\n\n<p>So the source must not equal the destination, but that's kind of added to an afterthought. And it seems to break if <code>getDepot()</code> return a <code>Depot</code> type instead of a <code>String</code>. If it returns a <code>String</code> representing a location then certainly the method is not named correctly. So it is wrong either way.</p>\n\n<hr>\n\n<pre><code>i++;\n</code></pre>\n\n<p>Oh, dear, that doesn't happen at the right place at all. First of all, how do you determine if <code>i</code> remains valid? Doesn't it overflow, because it is 2 loops deep? If the <code>do ... while</code> gets executed twice then you're in trouble, right?</p>\n\n<hr>\n\n<pre><code>System.out.printf(\"%nThe vehicle is either already assigned to the depot, or the depot does not exist%n%n\");\n</code></pre>\n\n<p>Ah, right, so how would you feel as a user if you got this message? Now you will have to find out which one of the two errors is happening?</p>\n\n<hr>\n\n<pre><code>if (validLocation) {\n</code></pre>\n\n<p>Wait, I'm pretty sure that I just saw an <code>if (!validLocation)</code>! what about <code>else</code>?</p>\n\n<hr>\n\n<pre><code>} while (!exit);\n</code></pre>\n\n<p>I don't know but I presume that we could use <code>break LABEL</code> if that's necessary. Removes an unnecessary boolean, for instance.</p>\n\n<hr>\n\n<pre><code>depots.get(i).makeVehicle(v);\n</code></pre>\n\n<p>I've never seen a depot make a vehicle. If the code doesn't seem to fit reality then the code is wrong. It really is that simple. You are reassigning, why not <code>assignVehicle</code>?</p>\n\n<hr>\n\n<p>What you've programmed is unfortunately what we call spaghetti-code. All kinds of loops and branches (<code>if</code> and such) and mixing of methods, UI code.</p>\n\n<p>The design is not correct either. <code>vehicle.getDepot()</code> means that a vehicle has got a specific depot assigned to it. Is that a changing depot? In that case it is not part of the vehicle object. Maybe there is a <em>map</em> somewhere with a vehicle -> depot mapping, but making a depot part of a vehicle is not a good design.</p>\n\n<p>Besides that, the depots already list which vehicles are present. Having two related references stored at different locations is just asking for the program to get into an invalid state. If that's present then the update needs to be performed <em>within a single, indivisible method</em>, i.e. more or less at the same time.</p>\n\n<p>I would expect at least the following methods to implement the UI logic (in a separate UI class):</p>\n\n<ul>\n<li><code>Depot selectOriginatingDepot()</code>;</li>\n<li><code>void listVehiclesByRegistration(Depot depot)</code>;</li>\n<li><code>Vehicle selectVehicleByRegistration()</code>;</li>\n<li><code>Depot selectTargetDepot(Depot originatingDepot)</code>.</li>\n</ul>\n\n<p>Furthermore, I would expect the following methods for the business logic (so no printing or scanner usage, use a logger if you have to):</p>\n\n<ul>\n<li><code>Optional<Depot> getDepotByLocation(String location)</code>;</li>\n</ul>\n\n<p>This is already there, but it requires some rewriting using <code>Optional</code>.</p>\n\n<ul>\n<li><code>Optional<Vehicle> Depot#getVehicleByRegistration(String registration)</code>;</li>\n</ul>\n\n<p>Now if the <code>Optional</code> is \"empty\" then you can simply let UI code ask again.</p>\n\n<hr>\n\n<p>By using more methods you will have fewer boolean to worry about for each specific method. Furthermore, by using smarter constructs such as <code>Optional</code> and e.g. <code>HashTable</code> you might find that you can program this entire piece of code without using a single booleanor nested loops for that matter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T00:31:17.667",
"Id": "241585",
"ParentId": "241429",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241433",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:01:31.223",
"Id": "241429",
"Score": "-1",
"Tags": [
"java"
],
"Title": "More elegant way of handling this method?"
}
|
241429
|
<p>I wrote a NavigationBar component in React, using hooks, react-bootstrap, react-i18next and css. Now the component works as I expect it, but the code seems ugly. (I'm new with hooks)</p>
<p>Features:</p>
<ul>
<li>It's transparent at the beginning but if we scroll down it will be "dark" (from react-bootstrap)</li>
<li>If there's no enough space to show everything (768px) then the menu collapses and a hamburger menu will be shown</li>
<li>If the hamburger menu opens then the background will be always "dark". It goes back to transparent if it closes and it should be transparent. </li>
</ul>
<p>Can be this component refactored, so it's easier to read/understand to a new developer? (Or maintain it for that matter)</p>
<p>How?</p>
<p>Also, I'm a bit baffled about the component tests. To check if the background of the navigation bar changes properly as I scroll down and up I would need an environment where I can scroll (an actual browser?) which seems quite complicated with react testing library and jest. Any suggestion here? Maybe I should mock the window values somehow? Or just test the functions and not doing any scrolling?</p>
<p>Thank you!</p>
<p><i>Note:</i> LanguageSelector component is a NavDropdown with 2 elements to change the language accordingly. When user clicks on one of the items "changeLanguage(language:string): void" function is called from NavigationBar component (it is passed via props as you can see in the code)</p>
<p>You can try the component here: <a href="https://codesandbox.io/s/cranky-blackburn-htxc5" rel="nofollow noreferrer">https://codesandbox.io/s/cranky-blackburn-htxc5</a></p>
<pre><code>import React, { useState, useCallback, useEffect, useRef } from 'react';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import throttle from 'lodash/throttle';
import { useTranslation } from 'react-i18next';
import LangaugeSelector from '../LanguageSelector/LanguageSelector';
import './NavigationBar.css';
function NavigationBar() {
const startingNavbarColor = 'transparent';
const navbarColor = 'dark';
const compactLayoutWidth = 768;
// State: NavBackground, Event: Scroll
const [navBackground, setNavBackground] = useState(false);
const navRef: React.MutableRefObject<boolean> = useRef(false);
navRef.current = navBackground;
const handleScroll = useCallback(event => {
if (!navRef.current && window.scrollY > 200) {
setNavBackground(true);
}
else if (navRef.current && window.scrollY <= 200) {
setNavBackground(false);
}
}, []);
useEffect(() => {
window.addEventListener('scroll', throttle((event) => handleScroll(event), 100));
return () => window.removeEventListener('scroll', handleScroll);
}, [handleScroll]);
// State: CompactLayout, Event: Resize
const [compactLayout, setCompactLayout] = useState(window.innerWidth <= compactLayoutWidth);
const layoutRef: React.MutableRefObject<boolean> = useRef(false);
layoutRef.current = compactLayout;
const handleResize = useCallback(event => {
if (window.innerWidth > compactLayoutWidth && layoutRef.current) {
setCompactLayout(false);
setNavbarExpanded(false);
}
else if (window.innerWidth <= compactLayoutWidth && !layoutRef.current) {
setCompactLayout(true);
}
}, []);
useEffect(() => {
window.addEventListener('resize', throttle((event) => handleResize(event), 100));
return () => window.removeEventListener('resize', handleResize);
}, [handleResize]);
// State: NavbarExpanded, Event: OnToggle
const [navbarExpanded, setNavbarExpanded] = useState(false);
const navbarExpandedRef = useRef<boolean>(false);
navbarExpandedRef.current = navbarExpanded;
const handleExpand = (expanded: boolean) => {
if (expanded && !navbarExpandedRef.current) {
setNavbarExpanded(true);
} else if (!expanded && navbarExpandedRef.current) {
setNavbarExpanded(false);
}
};
// Calculating the navbar background
const getNavbarBackground = () => {
if (!navbarExpandedRef.current && !navRef.current) {
return startingNavbarColor;
} else {
return navbarColor;
}
}
// Language
const { t, i18n } = useTranslation();
const changeLanguage = (language: string) => {
i18n.changeLanguage(language);
handleExpand(false);
}
// Render
return (
<Navbar fixed="top" bg={getNavbarBackground()} variant="dark"
onToggle={handleExpand} expand="md" // if you change 'expand' value, don't forget to change 'compactLayoutWidth' accordingly as well
expanded={navbarExpandedRef.current} collapseOnSelect>
<Navbar.Brand href="#home"> {t('name')} </Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse>
<Nav id="collapseableNav">
<Nav.Link href="#aboutme">{t('aboutMe')}</Nav.Link>
<Nav.Link href="#contact">{t('contact')}</Nav.Link>
{
compactLayout &&
<LangaugeSelector languages={['en', 'hu']} changeLanguage={changeLanguage} alignRight={false} />
}
</Nav>
</Navbar.Collapse>
{
!compactLayout &&
<Nav id="separateLanguageNav" className="justify-content-end">
<LangaugeSelector languages={['en', 'hu']} changeLanguage={changeLanguage} alignRight={true} />
</Nav>
}
</Navbar>
);
}
export default NavigationBar;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T17:55:43.900",
"Id": "473843",
"Score": "0",
"body": "This question, `Can be this component refactored, so it's easier to read/understand to a new developer? (Or maintain it for that matter)` will only lead to a yes/no answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T00:17:48.840",
"Id": "473878",
"Score": "0",
"body": "Added the \"How?\" question, but I thought it's obvious that I expect more than a Yes/No. Otherwise it is not too useful, is it? :) (Also added a link to codesandbox where the component can be tried out)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:34:35.933",
"Id": "241430",
"Score": "2",
"Tags": [
"javascript",
"unit-testing",
"react.js"
],
"Title": "NavigationBar component with hooks. Can it be made more readable/maintainable?"
}
|
241430
|
<p>I wanted to compare radix_sort to quick_sort for values limited to 0..127 so I implemented this : </p>
<pre><code>void bin_radix_sort(int *a, const size_t size, int digits) {
assert(digits % 2 == 0);
int *b = malloc(size * sizeof(int));
for (int exp = 0; exp < digits; exp++) {
// Count elements
size_t count[2] = {0};
for (size_t i = 0; i < size; i++)
count[(a[i] >> exp) & 1]++;
// Cumulative sum
count[1] += count[0];
// Build output array
for (int i = size - 1; i >= 0; i--)
b[--count[(a[i] >> exp) & 1]] = a[i];
int *p = a; a = b; b = p;
};
free(b);
}
</code></pre>
<p>I was able to compare it to <code>qsort</code> with : </p>
<pre><code>struct timespec start;
void tic() {
timespec_get(&start, TIME_UTC);
}
double toc() {
struct timespec stop;
timespec_get(&stop, TIME_UTC);
return stop.tv_sec - start.tv_sec + (
stop.tv_nsec - start.tv_nsec
) * 1e-9;
}
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main(void) {
const size_t n = 1024 * 1024 * 50;
printf("Init memory (%ld MB)...\n", n / 1024 / 1024 * sizeof(int));
int *data = calloc(n, sizeof(int));
printf("Sorting n = %ld data elements...\n", n);
size_t O;
tic();
O = n * log(n);
qsort(data, n, sizeof(data[0]), cmpfunc);
printf("%ld %lf s\n", O, toc());
int d = 6;
tic();
O = d * (n + 2);
bin_radix_sort(data, n, d);
printf("%ld %lf s\n", O, toc());
}
</code></pre>
<p>This gives me this output:</p>
<pre><code>$ gcc -Os bench.c -lm
$ ./a.out
Init memory (200 MB)...
Sorting n = 52428800 data elements...
931920169 1.600909 s
314572812 0.963436 s
</code></pre>
<p>I guess my code needs code-review since I was expecting to be six times better than quick sort.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T01:53:54.237",
"Id": "473884",
"Score": "0",
"body": "\"values limited to 0..127\" is unclear here. All the values are 0 given `int *data = calloc(n, sizeof(int));`. I'd expect some random filller for `data[]`. Was it the intention to compare perforce with the special case of all zero value?"
}
] |
[
{
"body": "<p>Well, I guarantee that <code>qsort</code> doesn't start with a heap allocation. Benchmark several different sizes of array and graph the results, to see where the lines hit the Y-axis: how much of your benchmark is just measuring the speed of <code>malloc</code>?</p>\n\n<hr>\n\n<pre><code>size_t count[2] = {0};\n</code></pre>\n\n<p>Depending on the smartness of your compiler, an array that doesn't have to be an array <em>might</em> be a big performance hit. Arrays are often stored in memory, on the stack, as opposed to scalar variables which can be stored in registers without any real cleverness on the compiler's part. Plus, in this case, your code seems to be needlessly convoluted by the use of an array instead of two different variables <code>count0</code> and <code>count1</code>. Compare:</p>\n\n<pre><code>for (int exp = 0; exp < digits; ++exp) {\n // Count elements\n size_t count0 = 0;\n size_t count1 = 0;\n for (size_t i = 0; i < size; ++i) {\n if ((a[i] >> exp) & 1) {\n count1 += 1;\n } else {\n count0 += 1;\n }\n }\n\n // Cumulative sum\n count1 += count0;\n\n // Build output array\n for (int i = size - 1; i >= 0; --i) {\n if ((a[i] >> exp) & 1) {\n b[--count1] = a[i];\n } else {\n b[--count0] = a[i];\n }\n }\n int *p = a; a = b; b = p;\n}\n</code></pre>\n\n<hr>\n\n<p>After rewriting like this, it becomes apparent that after the first loop, <code>count0 + count1 == size</code>; and after the \"Cumulative sum\" step, <code>count1 == size</code>. So we can eliminate half of the code.</p>\n\n<pre><code> size_t count0 = 0;\n size_t count1 = size;\n for (size_t i = 0; i < size; ++i) {\n if (((a[i] >> exp) & 1) == 0) {\n count0 += 1;\n }\n }\n\n // Build output array\n for (int i = size - 1; i >= 0; --i) {\n if ((a[i] >> exp) & 1) {\n b[--count1] = a[i];\n } else {\n b[--count0] = a[i];\n }\n }\n</code></pre>\n\n<p>Then, the \"Build output array\" step is doing the <em>exact same workload</em> <code>(a[i] >> exp) & 1</code> a second time! That seems like a fruitful source of optimization. What if you folded the second loop into the first loop, something like this?</p>\n\n<pre><code>for (int exp = 0; exp < digits; ++exp) {\n size_t up = 0;\n size_t down = size;\n for (size_t i = 0; i < size; ++i) {\n int x = a[i];\n if ((x >> exp) & 1) {\n b[--down] = x;\n } else {\n b[up++] = x;\n }\n }\n assert(up == down);\n // Now elements [up..size) are in reversed order,\n // so we need to flip them back around.\n reverse_array(b + up, b + size);\n int *temp = a; a = b; b = temp;\n}\n</code></pre>\n\n<p>Writing <code>reverse_array</code> is left as an exercise for the reader.</p>\n\n<p>I'd be interested to see your benchmark results for this \"improved\" algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T22:14:23.217",
"Id": "473864",
"Score": "1",
"body": "0.27s for your optimized algorithm (. Changing the array for two registered variables does not change anything. Now we have the expected 6x faster than quick sort :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T22:17:25.590",
"Id": "473865",
"Score": "0",
"body": "heap allocation doesn't cost much, its effect is negligible on my machine. And yes, I don't like this need for a O(n) space buffer. It would be better to do it in place."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:58:00.680",
"Id": "241459",
"ParentId": "241431",
"Score": "3"
}
},
{
"body": "<p><strong>Limitations on <code>cmpfunc()</code> with <code>qsort()</code></strong></p>\n\n<p>Presently code only has a zero-filled array to sort, so <code>cmpfunc()</code> is OK.<br>\nThis makes for an <em>interesting</em> performance test.</p>\n\n<p>If the array was populated with [0..127] as suggested in the question, <code>cmpfunc()</code> is still OK.</p>\n\n<p>If the array was populated with [<code>INT_MIN...INT_MAX</code>], <code>cmpfunc()</code> is UB.</p>\n\n<p>For <code>qsort</code> to perform and complete, the follow is required: </p>\n\n<blockquote>\n <p>The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. §17dr 7.22.5.2 3</p>\n</blockquote>\n\n<p>Unfortunately <code>*(int*)a - *(int*)b</code> is prone to overflow (UB) and returning the wrong signed difference.</p>\n\n<pre><code>int cmpfunc (const void * a, const void * b) {\n return ( *(int*)a - *(int*)b ); // UB\n}\n</code></pre>\n\n<p>Suggest a stable alternative:</p>\n\n<pre><code>int cmpfunc (const void * a, const void * b) {\n int ia = * ((const int *)a);\n int ib = * ((const int *)b);\n return (ia > ib) - (ia < ib);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T02:10:59.540",
"Id": "241470",
"ParentId": "241431",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:35:24.227",
"Id": "241431",
"Score": "3",
"Tags": [
"c",
"sorting",
"quick-sort",
"radix-sort"
],
"Title": "Radix sort is deceiving"
}
|
241431
|
<p>Hi I've written a web scraper for tracking gold price. Can someone please review my code and suggest improvements. It gets the price of gold from a specific url then stores the price against date in a db file further makes a plot then uploads image to firebase. Further this image and gold price is sent to your whats-app by using the twilio dependency.</p>
<p>Also please suggest methods for deployment on web. Any suggestions on further improvements are also welcome.</p>
<pre><code>#Gold Price Tracker Everyday.
import sqlite3
import random
import numpy as np
from uuid import uuid4
import base64
import PyPDF2
import openpyxl as wb
import urllib.request,urllib.parse,urllib.error
from pdfminer.pdfdocument import PDFDocument
from matplotlib import pyplot as plt
import ssl
import os
import io
from twilio.rest import Client
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import ChatGrant
import sys
import requests
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
from firebase_admin import credentials
account_sid='my sid for twilio'
account_auth = "authorization id for twilio"
ctrx=ssl.create_default_context()
ctrx.check_hostname=False
ctrx.verify_mode=ssl.CERT_NONE
grams=1032.6/1000 # Denotes the number of grams that is present with you currently.
gold_prices=[]
print("Your Current Grams of Gold is %f"%grams)
global date
def get_price():
'''This module is to get the price of gold online'''
url='https://distributors.mmtcpamp.com/Downloads/PriceList.pdf'
html=urllib.request.urlopen(url,context=ctrx).read()# Sending the request to the #designated url
memoryFile=io.BytesIO(html)
reader = PyPDF2.PdfFileReader(memoryFile)
contents = reader.getPage(0).extractText().split('\n')# Parsing the gold price
gp=float(str(contents[298]).replace(',',''))# Today's gold price.
gold_prices.append(gp)
return gp # Returns today's gold price.
def message():# Prints the message
'''Prints the message that is required'''
g_p=get_price()
print("Selling at today's price will fetch Rs %f"%(g_p*grams))
def get_date_time():
'''Function to get present date and time from appspot'''
d=urllib.request.urlopen('http://just-the-time.appspot.com/')
d1=d.read().split()
date = str(d1[0]).replace('b','').replace('\'','')# Gets Date from appspot
time = str(d1[1]).replace('b','').replace('\'','')
return([date,time])
def populate_database(today_date,today_price):
# Here I am creating a database and populating the entries there
# Used to update the database with the current price
conn = sqlite3.connect('.\Price_tracker.db')
conn.row_factory = lambda cursor, row: row[0]
cur = conn.cursor()
cur.execute('''INSERT INTO dp_tracker(Date,Price) VALUES (?,?) ''',(today_date,today_price,))
dates_list=cur.execute('''SELECT Date FROM dp_tracker''').fetchall()
price_list=cur.execute('''SELECT Price FROM dp_tracker''').fetchall()
conn.commit()
cur.close()
return(dates_list,price_list)
def plot():
''' This function is used to plot the gold price scraped online'''
gp=get_price()# Today's gold Price
d=get_date_time()
date=d[0]#Todya's date
dp=populate_database(str(date),float(gp)) #Passing today's date and today's gold price and returns a list of all
dx=dp[0] #A list of dates obtained from database
dx_pos=np.arange(len(dx))
py=dp[1]#A list of prices obtained from excel file
fig = plt.figure()
plt.bar(dx_pos, py, align='center', alpha=0.5,figure=fig)
plt.xticks(dx_pos,dx,figure=fig)
plt.xlabel("Dates",figure=fig)
plt.ylabel("Price",figure=fig)
plt.title("Gold Price Tracker",figure=fig)
for i, v in enumerate(py):
plt.text(dx_pos[i] - 0.15, v + 0.01, str(v),figure=fig)
return fig
def upload2firebase():
cred = credentials.Certificate(
"./gold-price-tracker-caa9e-firebase-adminsdk-9e39d-72694e4d52.json")
firebase_admin.initialize_app(cred, {
'storageBucket': 'gold-price-tracker-caa9e.appspot.com'
})
img_src = "sample_image.png"
bucket = storage.bucket()
blob = bucket.blob(img_src)
# Create new token
new_token = uuid4()
# Create new dictionary with the metadata
metadata = {"firebaseStorageDownloadTokens": new_token}
# Set metadata to blob
blob.metadata = metadata
# Upload file
blob.upload_from_filename(filename="./Test.png", content_type='image/png')
blob.make_public()
return(blob.public_url)
#
#
# bucket = storage.bucket()
# image_data = ""
# with open("./Test.png", "rb") as img_file:
# image_data = base64.b64encode(img_file.read())
#
# blob = bucket.blob('test.png')
# blob.upload_from_string(image_data)
# return blob.public_url
def send2Phone(gram,price,r):
'''This function is to send the message to the phone'''
client=Client(account_sid , account_auth)
from_whats_app_number='whatsapp:+14155238886'
to_what_app_number='whatsapp:my number'
a="Your current grams of gold is "+str(gram)+" g.\n Selling at today's price will fetch Rs "+str(gram*price)
client.messages.create(body=a,media_url=r,from_=from_whats_app_number,to=to_what_app_number)
def loop():
# t=get_date_time()
# time=t[1].split(':')
# count=0
# if time[0] == '08' and time[1] == '57' and time[2]=='00' :
# count=1
# else:
# count=0
#
# if count==1:
message()
q = plot()
q.savefig('Test.png') #Saving image locally and upload to firebase.
r = upload2firebase() # Getting public url of the image from firebase
print(r)
send2Phone(grams,gold_prices[-1],r)
while True:
loop()
break
</code></pre>
|
[] |
[
{
"body": "<h2>General</h2>\n\n<p>There are so, so many examples of people scraping stock tracker sites. For beginners it's an understandable urge: you can see the data on the web, and you want to be able to translate those data using a script.</p>\n\n<p>The first thing you should reach for is an API, not a scraper. Scrapers are fragile, inefficient, and sometimes immoral - most website creators intend on human consumption, rather than bot consumption, and may be losing out on ad revenue. It's not clear to me what the business model of the MMTC is so I cannot confirm whether that is the case here, but there are many APIs that will give you the price of gold without having to go through the round trip of PDF-render-PDF-parse.</p>\n\n<h2>Import order</h2>\n\n<p>There are several different ways to do this; I recommend:</p>\n\n<ul>\n<li>Built-in libraries first, alphabetical</li>\n<li>External libraries second, alphabetical</li>\n</ul>\n\n<h2>Global constants</h2>\n\n<p>Things like <code>grams</code> should be <code>GRAMS</code> since they're global constants.</p>\n\n<p><code>ctrx</code>, <code>gold_prices</code> and <code>date</code> should not be at the global level and should be state as represented in function arguments and/or class members.</p>\n\n<p><code>date</code> needs its name changed to avoid shadowing the built-in <code>datetime.date</code>.</p>\n\n<p><code>account_*</code> variables should not be hard-coded, and should be saved to a secure secrets wallet. There are multiple ways to do this either via Python libraries or the OS that you are using.</p>\n\n<p>Strings like <code>\"./gold-price-tracker-caa9e-firebase-adminsdk-9e39d-72694e4d52.json\"</code> and <code>'gold-price-tracker-caa9e.appspot.com'</code> should be moved to global constants, if not made parametric configuration.</p>\n\n<h2>Indentation</h2>\n\n<p>Among other elements of the PEP8 standard, this:</p>\n\n<pre><code>gp=float(str(contents[298]).replace(',',''))# Today's gold price.\n</code></pre>\n\n<p>should have two spaces before the hash. In fact, it's deeply confusing StackExchange's Python highlighting parser.</p>\n\n<h2>Side-effects</h2>\n\n<p><code>get_price</code> does not just get the price. It also adds the price to <code>gold_prices</code>. Why? This appending should not be done in this function.</p>\n\n<h2><code>BytesIO</code></h2>\n\n<p>You stream-ify the result of <code>urlopen</code> to a <code>BytesIO</code>. There is a much better way to do this:</p>\n\n<ul>\n<li>Use <code>requests</code>, not <code>urlopen</code></li>\n<li>Use the streaming option of <code>requests.get</code></li>\n<li>Use the raw stream from the response object, which is already a stream, passing this to <code>PdfFileReader</code></li>\n<li>Do not make a <code>BytesIO</code></li>\n</ul>\n\n<h2>Getting the date and time</h2>\n\n<p>Python has this built-in: <code>datetime.datetime.now</code>. Do not make an HTTP request to get the current time. If you're worried that the client's time is not reliable, that's a different problem that should be solved at the operating system level with NTP.</p>\n\n<h2>Context managers</h2>\n\n<p>Read <a href=\"https://docs.python.org/3.8/library/sqlite3.html#using-the-connection-as-a-context-manager\" rel=\"nofollow noreferrer\">the docs</a>. Use a <code>with</code> statement for your SQLite variables. Also, your call to <code>close()</code> should be in a <code>finally</code>, since the context manager does not actually do a <code>close</code>.</p>\n\n<h2>No-op loop</h2>\n\n<p>Your final</p>\n\n<pre><code>while True:\n loop()\n break\n</code></pre>\n\n<p>does not have any effect. Replace it with a single call to <code>loop()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T03:38:07.230",
"Id": "473890",
"Score": "0",
"body": "Wow thanks a lot for that!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:49:53.723",
"Id": "241438",
"ParentId": "241432",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T14:58:03.570",
"Id": "241432",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"sqlite"
],
"Title": "Gold Price Tracker Web Scraper using Python"
}
|
241432
|
<p>The <a href="https://crates.io/crates/piston2d-graphics" rel="nofollow noreferrer"><code>piston2d-graphics</code></a> crate provides a trait, <a href="https://docs.rs/piston2d-graphics/0.36.0/graphics/trait.Graphics.html" rel="nofollow noreferrer"><code>Graphics</code></a>, which allows easy access to some graphics primitives. This would be a nice, easy-to-use API, if it weren't such a pain to end up with something that <em>implements</em> <code>Graphics</code>; for a time, there wasn't even a consistent set of crates that let you get one (that rendered anything to the screen, anyway).</p>
<p>I worked out a way of getting to a <code>Graphics</code>-implementing <code>struct</code> by the successive creation of six objects which take references to each other (one a <code>Builder</code>, so really five). This was still too convoluted for my needs, though, so I cracked out the Rustonomicon and simplified the interface down to:</p>
<pre><code>use graphics::Graphics;
mod display;
fn main() {
let mut d = display::Display::new();
loop {
let mut f = d.frame();
let mut g = f.graphics();
// g implements Graphics; do something with it
g.clear_color([1.0, 1.0, 1.0, 1.0]);
f.commit().unwrap();
}
}
</code></pre>
<p>I'm looking for suggestions for improving <a href="https://codeberg.org/wizzwizz4/sparkle/src/commit/bbde54f614ab2c933206fd3dd6c1ffe285858fee/src/display.rs" rel="nofollow noreferrer">the <code>display</code> module</a> and its API; I'm looking to making it a separate crate to use in other projects, but I want it to be good first.</p>
<hr>
<p><code>display.rs</code>:</p>
<pre><code>use glutin::event_loop::EventLoop;
use glium_graphics::{Glium2d, GliumGraphics, OpenGL};
use glium::{backend::glutin::Display as GDisplay, Frame as GFrame};
pub use graphics::Graphics;
use core::pin::Pin;
use core::mem::drop;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;
const OPENGL_VERSION: OpenGL = OpenGL::V4_5;
// I can't just use owning_ref because these don't deref.
pub struct Display {
el: *mut EventLoop<()>,
gdisplay: *mut GDisplay,
g2d: ManuallyDrop<Glium2d>
}
pub struct Frame<'d, 's> {
graphics: ManuallyDrop<GliumGraphics<'d, 's, GFrame>>,
frame: Option<NonNull<GFrame>>
}
impl Display {
pub fn new() -> Display {
let wb = glutin::window::WindowBuilder::new()
.with_title("Sparkle")
.with_inner_size(glutin::dpi::PhysicalSize::new(800.0, 600.0));
let cb = glutin::ContextBuilder::new();
let el = Box::into_raw(Box::new(EventLoop::new()));
let gdisplay = Box::into_raw(Box::new(GDisplay::new(
wb, cb, unsafe { &*el }
).unwrap()));
let g2d = glium_graphics::Glium2d::new(
OPENGL_VERSION, unsafe { &*gdisplay }
);
Display {
el: el,
gdisplay: gdisplay,
g2d: ManuallyDrop::new(g2d),
}
}
#[must_use]
pub fn frame<'a>(&'a mut self) -> Frame<'a, 'a> {
let gdisplay = unsafe { &*self.gdisplay };
let mut frame = Box::into_raw(Box::new(gdisplay.draw()));
let graphics = GliumGraphics::new(
&mut self.g2d, unsafe { &mut *frame }
);
Frame {
graphics: ManuallyDrop::new(graphics),
frame: NonNull::new(frame)
}
}
pub fn event_loop<'a>(&'a self) -> &'a EventLoop<()> {
// An immutable reference is okay, but there's
// another immutable reference to el (in self.gdisplay)
// so a mutable reference is right out.
unsafe { &*self.el }
}
}
impl Drop for Display {
fn drop(&mut self) {
unsafe {
// The order matters! Each references the next, so they
// must be dropped in that order to prevent use-after-free.
ManuallyDrop::drop(&mut self.g2d);
drop(Box::from_raw(self.gdisplay));
drop(Box::from_raw(self.el));
}
}
}
impl<'d, 's> Frame<'d, 's> {
pub fn commit(mut self) -> Result<(), glium::SwapBuffersError> {
// SEE ALSO: The Drop implementation.
unsafe {
// self.graphics is using self.frame; must drop it first.
ManuallyDrop::drop(&mut self.graphics);
// Now we can take it out of the box.
// Note that self.frame is always Some(_), because this
// function is the only thing that sets it to None.
Box::from_raw(self.frame.unwrap().as_ptr())
}.finish()?;
self.frame = None; // setting H2G2 flag for the Drop trait impl
Ok(())
}
pub fn graphics(&mut self) -> &mut GliumGraphics<'d, 's, GFrame> {
&mut self.graphics
}
}
impl Drop for Frame<'_, '_> {
fn drop(&mut self) {
// SEE ALSO: The .commit() implementation.
match self.frame {
Some(_) => panic!(concat!("sparkle::display::Frame must not ",
"be dropped! .commit() instead")),
None => () // Already cleaned up resources;
// let Rust free the struct.
};
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T15:18:01.053",
"Id": "241434",
"Score": "3",
"Tags": [
"rust",
"graphics"
],
"Title": "Simple graphics library from Sparkle"
}
|
241434
|
<p>I have made the solution for this question it is based on backtracking. Can anyone suggest me how to make it work faster, I haven't practiced backtracking that much, although my solution seems to work. Please check it out</p>
<pre class="lang-java prettyprint-override"><code> class Test {
static int ans = Integer.MAX_VALUE;
static void f(char[] a, String s, int r, boolean[] vis, int b) {
// System.out.println(s);
if (r == 0) {
int x = Integer.parseInt(s);
if (x > b && x < ans)
ans = Math.min(x, ans);
return;
}
for (int i = 0; i < a.length; i++) {
if (!vis[i]) {
s += a[i];
vis[i] = true;
f(a, s, r - 1, vis, b);
s = s.substring(0, s.length() - 1);
vis[i] = false;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] a = sc.next().toCharArray();
// System.out.println(Arrays.toString(a));
boolean[] vis = new boolean[a.length];
int b = sc.nextInt();
f(a, "", a.length, vis, b);
System.out.println(ans == Integer.MAX_VALUE ? -1 : ans);
}
}
</code></pre>
<ul>
<li><p>vis array is used to track which element is already picked same thing
which we do in DFS.</p></li>
<li><p>r is the count of remaining elements in a.</p></li>
</ul>
|
[] |
[
{
"body": "<h1>main()</h1>\n\n<p>When I started your program the first time, I didn't know what to do, because your program didn't tell me. Before scanning a user input, I would tell the user to input something:</p>\n\n<pre><code>Scanner sc = new Scanner(System.in);\nSystem.out.println(\"Please enter number a:\");\nchar[] a = sc.next().toCharArray();\nSystem.out.println(\"Please enter number b:\");\nint b = sc.nextInt();\n</code></pre>\n\n<hr>\n\n<p>For number a, I would also use an <code>int</code> instead of a <code>char[]</code>. Then I would convert it to a <code>char[]</code>, but not in the main-function:</p>\n\n<pre><code>System.out.println(\"Please enter number a:\");\nint a = sc.nextInt();\nSystem.out.println(\"Please enter number b:\");\nint b = sc.nextInt();\n</code></pre>\n\n<hr>\n\n<p>Another problem now is that your program doesn't validate the user input. The user could enter a letter instead of a number and your program would just break. This problem can be solved like this:</p>\n\n<pre><code>System.out.println(\"Please enter number a:\");\nint a;\nwhile(true) {\n try {\n a = sc.nextInt();\n break; \n }\n catch(InputMismatchException e) {\n System.out.println(\"That's not a number!\");\n sc.nextLine();\n }\n}\nSystem.out.println(\"Please enter number b:\");\nint b;\nwhile(true) {\n try {\n b = sc.nextInt();\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"That's not a number!\");\n sc.nextLine();\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>f()</h1>\n\n<p>Create a method <code>static void f(int numberA, int b)</code> that creates the char-array and the <code>boolean[] vis</code> and then calls the method <code>static void f(char[] a, String s, int r, boolean[] vis, int b)</code>. That way you don't have to do work in the main-method that doesn't belong to the main-method:</p>\n\n<pre><code>static void f(int numberA, int b) {\n char[] a = (\"\" + numberA).toCharArray();\n boolean[] vis = new boolean[a.length];\n\n f(a, \"\", a.length, vis, b);\n System.out.println(ans == Integer.MAX_VALUE ? -1 : ans);\n\n}\n</code></pre>\n\n<hr>\n\n<p>I don't like most of your variable names. You should (almost) always use names that tell the person who reads your code, what the variable does.</p>\n\n<hr>\n\n<p>Your algorithm looks solid. Well done.</p>\n\n<hr>\n\n<p>All in all it looks like this:</p>\n\n<pre><code>import java.util.Scanner;\nimport java.util.InputMismatchException;\n\nclass ChangeDigits {\n static int ans = Integer.MAX_VALUE;\n\n static void changeDigits(int numberA, int numberB) {\n char[] change = (\"\" + numberA).toCharArray();\n boolean[] pickedElements = new boolean[change.length];\n int remaining = change.length;\n changeDigits(change, \"\", remaining, pickedElements, numberB);\n System.out.println(\"Solution: \" + (ans == Integer.MAX_VALUE ? -1 : ans));\n\n }\n\n static void changeDigits(char[] change, String substring, int remaining, boolean[] pickedElements, int numberB) {\n if (remaining == 0) {\n int substrNumber = Integer.parseInt(substring);\n if (substrNumber > numberB && substrNumber < ans)\n ans = Math.min(substrNumber, ans);\n return;\n }\n\n for (int i = 0; i < change.length; i++) {\n if (!pickedElements[i]) {\n substring += change[i];\n pickedElements[i] = true;\n changeDigits(change, substring, remaining - 1, pickedElements, numberB);\n substring = substring.substring(0, substring.length() - 1);\n pickedElements[i] = false;\n }\n }\n }\n\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Please enter number a:\");\n int numberA;\n while(true) {\n try {\n numberA = sc.nextInt();\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"That's not a number!\");\n sc.nextLine();\n }\n }\n\n System.out.println(\"Please enter number b:\");\n int numberB;\n while(true) {\n try {\n numberB = sc.nextInt();\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"That's not a number!\");\n sc.nextLine();\n }\n }\n\n changeDigits(numberA, numberB);\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T12:25:02.933",
"Id": "474331",
"Score": "0",
"body": "Thankyou @chysaetos99 for giving so much effort for me. This problem was from a company mock test and I had to code it real fast because of the time constraint and apart from that question didn't specify to handle \"not number\" case. And yes the code is well written and can be used by others now all thanks to you. From now on I will post proper code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T12:32:10.187",
"Id": "474335",
"Score": "1",
"body": "Your're welcome. I'am happy that I could help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T10:04:38.497",
"Id": "241701",
"ParentId": "241440",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241701",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:28:41.063",
"Id": "241440",
"Score": "2",
"Tags": [
"java",
"algorithm",
"backtracking"
],
"Title": "Given 2 numbers a and b find the smallest number greater than b by interchanging the digits of a and if not possible print -1"
}
|
241440
|
<p>I'm currently going over Robert Sedgewick Algorithms book and I'm trying to recreate his Java implementations in Ruby. I would like to know If I'm following best practices. I try to use clean code principles, making the code readable and easy to comprehend. If there are any improvements please share. Constructive feedback is highly appreciated.</p>
<pre><code>class Merge
attr_accessor :aux
def sort_public(a)
@aux = []
sort(a,0, a.length - 1)
end
def merge(a, lo, mid, hi)
i = lo
j = mid + 1
k = lo
while k <= hi do
@aux[k] = a[k]
k += 1
end
k = lo
while k <= hi do
if i > mid
a[k] = @aux[j]
j += 1
elsif j > hi
a[k] = @aux[i]
i += 1
elsif aux[j] < aux[i]
a[k] = @aux[j]
j += 1
else
a[k] = @aux[i]
i += 1
end
k += 1
end
a
end
private
def sort(a, lo, hi)
return if hi <= lo
mid = lo + (hi - lo) / 2
sort(a,lo, mid) #sort left half
sort(a,mid + 1, hi) # sort right half
merge(a,lo, mid, hi)
end
end
merge = Merge.new
a = ["M", "E", "R", "G", "E", "S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"]
p merge.sort_public(a)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T06:13:33.453",
"Id": "474300",
"Score": "0",
"body": "This site is for code reviews of working code only. Your code fails, for example, for singleton or empty arrays: https://repl.it/repls/EntireSquareProfiler"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T06:38:07.873",
"Id": "474302",
"Score": "3",
"body": "(Note that getting a question closed is *not* the end of that question: it means *should not be answered as is*.) (While the fix for the cases mentioned looks trivial enough, you should seriously re-think *testing*.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T12:42:07.290",
"Id": "474337",
"Score": "3",
"body": "@JörgWMittag Technically the rule is it has to work to the best of OP's knowledge. I agree it was tested poorly, perhaps that makes it a low-quality question, but please see our meta: [Are questions with undiscovered bugs allowed?](https://codereview.meta.stackexchange.com/q/8570/52915) I think your tests would make a great start for an answer, but based on the current rules, it's not off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-04T12:59:42.623",
"Id": "474340",
"Score": "3",
"body": "\"I tried to use clean code\", with all those single letter variables I'm thinking our definitions for clean code are vastly different."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T16:35:19.443",
"Id": "241441",
"Score": "0",
"Tags": [
"algorithm",
"ruby"
],
"Title": "mergeSort implementation in Ruby"
}
|
241441
|
<p>I am replicating this <a href="https://ofdollarsanddata.com/why-market-timing-can-be-so-appealing/" rel="nofollow noreferrer">blog post</a> in Python.
The blog post shows that even if you know future stock market bottoms, only buying stocks when the stock market is below future stock market bottoms provides only a modest edge of 22%.</p>
<p>The code below replicates the blog post's result (approximately, I use different data).
However, in cell <code># In[8]</code>, it loops over the rows in data frame <code>df</code>.
This loop makes the logic clear (if the stock market is below the future stock market bottom, move cash to equity, else invest cash in Treasuries and maintain equity investment) but seems un-Pythonic (and like code I would have written in my high school Basic class 25 years ago).</p>
<p>In cell <code># In[8]</code>, can I avoid looping over rows?</p>
<p>Note, that I wrote this code in a Jupyter Notebook, and <code>display()</code> requires a Jupyter Notebook.</p>
<pre><code>#!/usr/bin/env python
# coding: utf-8
# In[1]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader as pdr
# In[2]:
url = 'https://query1.finance.yahoo.com/v7/finance/download/%5EGSPC?period1=-1325635200&period2=1588118400&interval=1d&events=history'
gspc = pd.read_csv(url, index_col='Date', parse_dates=True)
display(gspc)
# In[3]:
url = 'https://query1.finance.yahoo.com/v7/finance/download/VFINX?period1=315619200&period2=1588118400&interval=1d&events=history'
vfinx = pd.read_csv(url, index_col='Date', parse_dates=True)
vfinx['Return'] = vfinx['Adj Close'].pct_change()
display(vfinx)
# In[4]:
dgs3mo = pdr.get_data_fred('DGS3MO', start=vfinx.index.min())
display(dgs3mo)
# In[5]:
df = gspc[['Close']].join(vfinx[['Return']]).join(dgs3mo / 100 / 365).dropna()
df.columns = ['SP500', 'RM', 'RF']
display(df)
# In[6]:
df.sort_index(ascending=False, inplace=True)
df['SP500_Fwd_Min'] = df.SP500.cummin()
df.sort_index(inplace=True)
display(df)
# In[7]:
df['To_Equity'] = np.where(df.SP500 <= df.SP500_Fwd_Min, 1, 0)
df['Smart_Cash'] = 0.
df['Smart_Equity'] = 0.
df['Dumb'] = 0.
df['Daily'] = 1
# In[8]:
for i in range(1, df.shape[0]):
if (df.To_Equity[i - 1] == 1):
df.Smart_Equity[i] = (df.Smart_Equity[i-1] + df.Smart_Cash[i-1] + df.Daily[i-1]) * (1 + df.RM[i])
df.Smart_Cash[i] = 0
else:
df.Smart_Equity[i] = (df.Smart_Equity[i-1]) * (1 + df.RM[i])
df.Smart_Cash[i] = (df.Smart_Cash[i-1] + df.Daily[i-1]) * (1 + df.RF[i])
df.Dumb[i] = (df.Dumb[i-1] + df.Daily[i-1]) * (1 + df.RM[i])
df['Smart'] = df.Smart_Equity + df.Smart_Cash
# In[9]:
df[['Smart', 'Dumb']].plot(figsize=(12,8))
# In[10]:
np.log(df.Smart[-1]) - np.log(df.Dumb[-1])
# In[ ]:
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T18:27:51.207",
"Id": "473845",
"Score": "1",
"body": "`display` is not defined, it should be noted that a Jupyter instance is required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T19:22:15.233",
"Id": "473852",
"Score": "2",
"body": "Please modify your question title to indicate what you are doing, i.e. _Analyzing market bottom timings (?) from Yahoo (?)_ . Something to that effect."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T17:18:54.607",
"Id": "241443",
"Score": "4",
"Tags": [
"python",
"pandas",
"finance"
],
"Title": "Analyze Stock Market Bottom Timing without Looping over Data Frame Rows"
}
|
241443
|
<p>I'm writing integration for a project, but our framework doesn't provide any ability to inject dependencies, so I've written tests with a unit testing framework (GTest) and used a mock (GMock) in an odd way simply to leverage its behaviour obverving functions. I have a python script to run it, it all works, but, is there a better approach I should be taking?</p>
<pre><code>/** Class that exists simply to provide stubs for callbacks */
class Monitor
{
public:
virtual auto subscribe() -> void {}
};
/** Mocking the ClientMonitor in order to leverage the Mocking tools, i.e.
* EXPECT_CALL.Times, etc. */
class MockMonitor
{
public:
MOCK_METHOD1(subscribe, void());
};
TEST_F(Test, RECEIVE_PROXY_STATUS_EVENT_AVAILABLE)
{
using ::testing::_;
MockMonitor cm;
// Listen for when the service event changes.
auto const subscription_status = proxy_->getPayloadEvent().subscribe(
[&cm](int64_t id, std::string const& payload) {
cm.subscribe();
});
EXPECT_CALL(cm, subscribe());
std::cout << "Waiting " << response_window_.count() << " ms for event..." << std::endl;
std::this_thread::sleep_for(response_window_);
std::cout << "Done waiting\n";
return;
}
</code></pre>
<p>This is an integration test so I actually want the communication to work, and there's no way I can see when I go through the code to actually mock it "normally", <em>i.e.</em></p>
<p>if I derive <code>proxy_</code> and override <code>getProxyStatusEvent()</code>, I could return a mock (in this case it would be something complex like <code>CommonAPI::FNV::FNVEvent<PayloadEvent, CommonAPI::Deployable< int32_t, CommonAPI::FNV::IntegerDeployment >, CommonAPI::Deployable< std::string, CommonAPI::FNV::StringDeployment >></code>, but then that class has its own private signal handler, <em>etc</em>..</p>
<p>So, basically, because the lack of injection, I'd have to create some complex mocks based on internal code that could change at any time.. not a good solution even if possible.</p>
<p>Thus, the solution I wrote above seems to acheive my goals quite simply</p>
<ul>
<li>It only tests public api methods</li>
<li>It's small</li>
<li>It's flexible</li>
</ul>
<p>It does seem odd however to create a mock of a dummy class simply to get functions like <code>EXPECT_CALL</code>. Is there a better approach I could be taking?</p>
<p>Also, for context, I'm using GTest again simply for the tools it provides, i.e. test fixtures, command line parsing of test naems, the asserts, <em>etc</em>. This could easily work without GTest.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T19:42:25.233",
"Id": "241452",
"Score": "5",
"Tags": [
"c++",
"unit-testing",
"mocks",
"integration-testing"
],
"Title": "Using an extra mock simply to take advantage of the behaviour observation tooling"
}
|
241452
|
<p>Let's say we train a model with more than 1 million words. In order to find the most similar words we need to calculate the distance between the embedding of the test word and embeddings of all the 1 million words words, and then find the nearest words. It seems that Gensim calculate the results very fast. Although when I want to calculate the most similar, my function is extremely slow:</p>
<pre><code>def euclidean_most_similars (model, word, topn = 10):
distances = {}
vec1 = model[word]
for item in model.wv.vocab:
if item!= node:
vec2 = model[item]
dist = np.linalg.norm(vec1 - vec2)
distances[(node, item)] = dist
sorted_distances = sorted(distances.items(), key=operator.itemgetter(1))
</code></pre>
<p>I would like to know how Gensim manages to calculate the most nearest words so fast and what is an efficient way to calculate the most similar words.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T20:54:29.147",
"Id": "473856",
"Score": "0",
"body": "How fast or slow is it now? How fast do you need it to be? How fast does the competitor Gensim perform on the same data? Without numbers, it's all premature optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T20:57:10.560",
"Id": "473857",
"Score": "0",
"body": "I tested my function and Gensim's most_similar function. Gensim shows the results instantly, although my function takes almost 10 seconds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T20:58:06.830",
"Id": "473858",
"Score": "1",
"body": "Would you mind providing a minimal, complete example for us to run?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T20:47:15.660",
"Id": "241453",
"Score": "3",
"Tags": [
"python"
],
"Title": "An efficient way to find the most similar vectors"
}
|
241453
|
<p>I'm happy to present my first Android project, which collects market index data (three Asian indices) and fires a notificaiton every Wednesday, Thursday and Friday at 7:30 AM displaying the data.</p>
<p>I've applied to Computer Science in Lund, Sweden. I am looking to improve my Java through Android development (which I've found particularly interesting).</p>
<p>Please consider giving some feedback. I'll be happy with anything!</p>
<p><strong>MainActivity</strong>:</p>
<pre><code>public class MainActivity extends AppCompatActivity {
public static final String CHANNEL_ID = "com.example.morgonnotification.channel";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
ReminderReceiver.setNextNotification(this);
}
private void createNotificationChannel() {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Index Channel", NotificationManager.IMPORTANCE_HIGH);
NotificationManagerCompat.from(this).createNotificationChannel(channel);
}
}
</code></pre>
<p><strong>ReminderReceiver (BroadcastReceiver)</strong>:</p>
<pre><code>public class ReminderReceiver extends BroadcastReceiver {
public static void setNextNotification(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent intent = new Intent(context, ReminderReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
ZonedDateTime fireTime = ZonedDateTime.now(ZoneId.of("Europe/Stockholm")).withHour(7).withMinute(30).withSecond(0);
long nowEpochSecond = ZonedDateTime.now(ZoneId.of("Europe/Stockholm")).toEpochSecond();
long fireTimeEpochSecond = fireTime.toEpochSecond();
DayOfWeek day = fireTime.getDayOfWeek();
switch (day.name()) {
case "WEDNESDAY":
//before 7:30 on a wednesday? Set alarm to this Wednesday morning
fireTime = (nowEpochSecond < fireTimeEpochSecond) ? fireTime :
fireTime.with(TemporalAdjusters.next(DayOfWeek.THURSDAY));
break;
case "THURSDAY":
//before 7:30 on a Thursday? Set alarm to this Thursday morning
fireTime = (nowEpochSecond < fireTimeEpochSecond) ? fireTime :
fireTime.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
break;
case "FRIDAY":
//before 7:30 on a Friday? Set alarm to this Friday morning
fireTime = (nowEpochSecond < fireTimeEpochSecond) ? fireTime :
fireTime.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
break;
default:
fireTime = fireTime.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
break;
}
if (alarmManager != null)
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
fireTime.toInstant().toEpochMilli(), alarmIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()) ||
"android.intent.action.QUICKBOOT_POWERON".equals(intent.getAction()) ||
intent.getAction() == null) {
setNextNotification(context);
}
StringBuilder indicesBuilder = new StringBuilder();
Thread thread = new Thread(() -> {
try {
Document doc = Jsoup.connect("https://money.cnn.com/data/world_markets/asia//").get();
Elements nikkei = doc.select("#wsod_indexDataTableGrid > tbody > tr:nth-child(6) > td:nth-child(5) > span > span");
indicesBuilder.append("N: ").append(nikkei.text()).append(", ");
Elements shanghaiComposite = doc.select("#wsod_indexDataTableGrid > tbody > tr:nth-child(3) > td:nth-child(5) > span > span");
indicesBuilder.append(" S: ").append(shanghaiComposite.text()).append(", ");
Elements hangSeng = doc.select("#wsod_indexDataTableGrid > tbody > tr:nth-child(4) > td:nth-child(5) > span > span");
indicesBuilder.append(" H: ").append(hangSeng.text());
} catch (Exception e) {
indicesBuilder.append("Something went terribly wrong");
e.printStackTrace();
} finally {
Notification notification = new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_index)
.setContentTitle("Morning indices")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setStyle(new NotificationCompat.BigTextStyle().bigText(indicessBuilder)).build();
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.notify(1, notification);
indicesBuilder.setLength(0);
}
});
thread.start();
}
}
</code></pre>
<p><strong>XML File:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
</code></pre>
<p></p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name=".ReminderReceiver"
android:enabled="true"
android:exported="true">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to Code Review. Your code seems me well structured, I have two suggestions for you:</p>\n\n<blockquote>\n<pre><code>switch (day.name()) {\n case \"WEDNESDAY\":\n //before 7:30 on a wednesday? Set alarm to this Wednesday morning\n fireTime = (nowEpochSecond < fireTimeEpochSecond) ? fireTime :\n fireTime.with(TemporalAdjusters.next(DayOfWeek.THURSDAY));\n break;\n case \"THURSDAY\":\n //before 7:30 on a Thursday? Set alarm to this Thursday morning\n fireTime = (nowEpochSecond < fireTimeEpochSecond) ? fireTime :\n fireTime.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));\n break;\n case \"FRIDAY\":\n //before 7:30 on a Friday? Set alarm to this Friday morning\n fireTime = (nowEpochSecond < fireTimeEpochSecond) ? fireTime :\n fireTime.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));\n break;\n default:\n fireTime = fireTime.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));\n break;\n}\n</code></pre>\n</blockquote>\n\n<p>There is code repetition and you have a binary association between one day and another one, so you could create a <code>Map</code> to reduce your code lines like below:</p>\n\n<pre><code>//creation of one map for the days\nMap<String, String> map = new HashMap<String, String>();\nmap.put(\"WEDNESDAY\", \"THURSDAY\");\nmap.put(\"THURSDAY\" , \"FRIDAY\");\nmap.put(\"FRIDAY\" , \"WEDNESDAY\");\n\n//here the code instead of your switch\nDayOfWeek day = fireTime.getDayOfWeek();\nString name = day.name();\nif (map.containsKey(name)) {\n fireTime = (nowEpochSecond < fireTimeEpochSecond) ? fireTime :\n fireTime.with(TemporalAdjusters.next(DayOfWeek.valueOf(map.get(name))));\n} else {\n //default value of your switch\n fireTime = fireTime.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));\n}\n</code></pre>\n\n<p>About the following lines in your jsoup code :</p>\n\n<blockquote>\n<pre><code>StringBuilder indicesBuilder = new StringBuilder();\nindicesBuilder.append(\"N: \").append(nikkei.text()).append(\", \");\nindicesBuilder.append(\" S: \").append(shanghaiComposite.text()).append(\", \");\nindicesBuilder.append(\" H: \").append(hangSeng.text());\n</code></pre>\n</blockquote>\n\n<p>You can obtain the same result not going crazy about data format when you add or delete new indices using <code>StringJoiner</code> class:</p>\n\n<pre><code>StringJoiner sj = new StringJoiner(\", \");\nsj.add(\"N: \" + nikkei.text());\nsj.add(\"S: \" + shanghaiComposite.text());\nsj.add(\"H: \" + hangSeng.text());\n\nString bigText = sj.toString(); //<-- the string you can use later in your code.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T09:25:28.030",
"Id": "241481",
"ParentId": "241455",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241481",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:04:05.663",
"Id": "241455",
"Score": "4",
"Tags": [
"java",
"android",
"xml"
],
"Title": "Scheduled Notifications (First Android App)"
}
|
241455
|
<p>Based on <a href="https://github.com/KyleBanks/XOREncryption/blob/master/C/main.c" rel="noreferrer">this code</a> found on github and the advice given to me on stackoverflow I made this code for the xor in c.</p>
<pre><code> #include <stdio.h>
#include <string.h>
void encryptDecrypt(char *input, char *output)
{
char key[3] = {'K', 'E', 'Y'};
for (int i = 0; i < strlen(input); ++i)
output[i] = input [i] ^ key [i % sizeof(key)];
}
int main()
{
char baseStr[] = "Test";
char encrypted[strlen(baseStr) + 1];
memset(encrypted, '\0', sizeof(encrypted));
encryptDecrypt(baseStr, encrypted);
printf("Encrypted: %s\n", encrypted);
char decrypted[strlen(baseStr) + 1];
memset(decrypted, '\0', sizeof(decrypted));
encryptDecrypt(encrypted, decrypted);
printf("Decrypted: %s\n", decrypted);
return 0;
}
</code></pre>
<p>How can I improve the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T00:54:06.230",
"Id": "474005",
"Score": "0",
"body": "The first time I broke XOR encrypted text it took me two years after I broke the encryption to realize it was even using encryption. I thought it just a weird encoding."
}
] |
[
{
"body": "<p>First, about the existing code:</p>\n\n<ul>\n<li><code>key</code> can be initialized with a string literal, <code>\"KEY\"</code>, rather than an array literal - with caveats in the comments</li>\n<li><code>encryptDecrypt</code> should be <code>static</code></li>\n<li>It should accept a <code>const char *input</code> as a promise not to modify it</li>\n<li>Since your <code>baseStr</code> is a local array, you do not need to call <code>strlen</code> on it; you can use <code>sizeof</code></li>\n</ul>\n\n<p>Now, about what the code <em>could</em> be doing:</p>\n\n<ul>\n<li>Accept the input from <code>stdin</code> or a file instead of having it be hard-coded; similar for the key</li>\n<li>Learn about encryption algorithms that are stronger than this; and learn about the cryptographic weaknesses of xor encryption</li>\n<li>When you print the encrypted string to <code>stdout</code>, do not print its raw string which will be full of unprintable characters. Instead print a hex string.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T00:09:35.397",
"Id": "473869",
"Score": "4",
"body": "Note that initializing key with a string literal can be fraught with trouble. GCC for instance gives you warnings. The issue is that a string literal includes a trailing NUL. If you don't use sizeof(key), this can be cleaner. And maybe key should be static either way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T09:58:36.220",
"Id": "473911",
"Score": "4",
"body": "You can and should also hoist `strlen(input)` out of the loop! With a `char` assignment inside the loop body, the compiler will probably re-run strlen every iteration in case that store to `output[i]` affected `input[i+1]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T10:01:17.600",
"Id": "473912",
"Score": "1",
"body": "I'd also recommend taking a command-line arg as the string to encrypt with a fallback string literal if there are no args. Easier to test with than `echo foo | ./xor` if you only support `stdin`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T19:27:55.807",
"Id": "473972",
"Score": "0",
"body": "Weaknesses of xor encryption, including but not limited to the encryption function is the decryption function."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T00:03:34.543",
"Id": "241465",
"ParentId": "241456",
"Score": "7"
}
},
{
"body": "<p>Don't deal in NUL terminated strings. The problem is that there are characters that will \"encrypt\" to NUL. (In this case, notably, 'K', 'E', and 'Y'.) This means you need to pass in the length of the text. </p>\n\n<p>If you want to allow for future expansion, allow for the possibility that the output text may be longer than the input text. Dynamic allocation may be appropriate, or maybe you have an auxiliary function that says \"for a text of length x, what is the longest length of output text.\" It may also then be appropriate to pass in the output buffer length, and pass out the output used length.</p>\n\n<p>Also allow for the specifying the operation (encrypt/decrypt). This \"encryption\" doesn't need it, but most symmetric encryptions do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T10:05:32.297",
"Id": "473914",
"Score": "3",
"body": "Symmetric ciphers normally have output length = input length; I don't think doing dynamic allocation inside the enc/dec function sounds like a great idea. I'd suggest having `main` call it with output=input to encrypt and then decrypt *in place* so it doesn't need any extra allocation of C99 VLAs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T14:17:28.970",
"Id": "473940",
"Score": "0",
"body": "@PeterCordes Symmetric ciphers normally have a block size. Feeding 3 bytes in will not get you three bytes out. OP's \"encryption\" is unusual in having a block size of 1 byte. Also, it is not unusual to add a header, to validate that the decryption is using the right key. Adding a magic number header is also reasonable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T14:31:31.743",
"Id": "473943",
"Score": "0",
"body": "Sure, I left out that detail. For a block cipher the buffers should be explicit-length, so just passing the input length implies the output length is that rounded up. If the caller wants to alloc a buffer, it's not unreasonable to expect it to know whatever rule applies for rounding the length up to a multiple of the block size. Baking in allocation would make it impossible to encrypt in-place, overwriting the input with encrypted output, so I hope you're not suggesting that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T00:18:41.057",
"Id": "241467",
"ParentId": "241456",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:13:13.313",
"Id": "241456",
"Score": "6",
"Tags": [
"c",
"encryption"
],
"Title": "Xor encryption in C"
}
|
241456
|
<h2>Background</h2>
<p>I worked at a community center where everyday one of my coworkers would spend 20ish minutes trying to organize the day's schedule. The facility had three rooms: The Great Hall, The Club House, and The Sub Cellar. Each of these rooms were open at different times in the day, and when he was organizing the schedule, he didn't want too many staff in there at once. For some rooms, he allowed more staff than others. Every day, we had different people working. Each person had a different shift. Some people came at 9am, while other people came at 1pm to cover the evening shifts. How long each person's shift was for that day determined the length of the break they were given that day in order to grab lunch or dinner.</p>
<h2>Repo</h2>
<p><a href="https://github.com/barrezuetai/scheduler" rel="nofollow noreferrer">Scheduler</a></p>
<pre><code>scheduler
|_________ src
| |________ scheduler
| | |________ __init__.py
| | |________ __main__.py
| |
| |_______ _scheduler
| |________ __init__.py
| |________ work.py
| |________ timemodule.py
| |________ manager.py
|_________testing
|
|_________setup.py
</code></pre>
<p><code>manager.py</code></p>
<pre><code>""" This module contains manager classes that are responsible for
assigning staff to rooms based on the required hard conditions"""
from collections import defaultdict
from copy import deepcopy
from typing import List, Dict
from _scheduler.work import Room, Staff, RType, EType, Shift
from _scheduler.timemodule import TimePeriod
class Manager():
def __init__(self, staff: List):
self.staff = staff
def manage(self):
raise NotImplementedError()
class RoomManager(Manager):
def __init__(self, room: Room, staff: List):
super().__init__(staff)
self.room = room
def manage(self) -> (List[TimePeriod], List[List[Staff]]):
available_staff = []
staff = self._get_available_staff(self.staff)
while(True):
if self._is_enough_coverage(staff):
breakdown = self._get_breakdown(staff)
result = self._verify_breakdown(breakdown, len(staff))
if result:
return self.get_possible_shifts(breakdown)
else:
staff = self._remove_extra_staff(breakdown)
else:
return {}
def _get_available_staff(self, staff: List):
""" Given a list of staff, this checks to see which
ones are available """
avail_staff = []
for s in staff:
if s._is_coincides(self.room):
avail_staff.append(s)
return avail_staff
def _get_breakdown(self, staff: List) -> Dict[TimePeriod, List[Staff]]:
room_schedule = defaultdict(list)
avail_staff = self._get_available_staff(staff)
num_of_staff = len(avail_staff)
split_times = self.room.time_open._split(num_of_staff)
for time in split_times:
for staff in avail_staff:
if staff._is_available(time):
room_schedule[time].append(staff)
return room_schedule
def _verify_breakdown(self,
breakdown: Dict[TimePeriod, List[Staff]],
expected: int) -> bool:
valid_staff = set()
for s in breakdown.values():
valid_staff = valid_staff.union(set(s))
return len(valid_staff) == expected
def _remove_extra_staff(self, breakdown) -> List[Staff]:
valid_staff = set()
for s in breakdown.values():
valid_staff = valid_staff.union(set(s))
return list(valid_staff)
def _is_enough_coverage(self, staff: List) -> bool:
""" Given a list of staff, this checks that their combined
times cover the room's time"""
room_time = set(self.room.time_open.comp)
total_coverage = set()
for s in staff:
total_coverage = total_coverage.union(s.shift.comp)
return room_time.issubset(total_coverage)
def _find_valid_path(self, time_list: List,
curr_list: List, i: int,
valid_path: List) -> None:
if i >= len(time_list):
valid_path.append(curr_list)
return
staff_list = list(time_list.values())
staff_list = staff_list[i]
for staff in staff_list:
if staff not in curr_list:
new_list = deepcopy(curr_list)
new_list.append(staff)
self._find_valid_path(time_list, new_list, i + 1, valid_path)
else:
continue
return
def get_possible_shifts(self, time_list: List
)-> (List[TimePeriod], List[List[Staff]]):
possible_schedules = []
self._find_valid_path(time_list, [], 0, possible_schedules)
times = list(time_list.keys())
return times, possible_schedules
class BreakManager(Manager):
def __init__(self, staff: List):
super().__init__(staff)
def manage(self):
pass
</code></pre>
<p><code>work.py</code></p>
<pre><code>from enum import Enum, auto
from datetime import datetime
from typing import Dict, Any
from _scheduler.timemodule import TimePeriod
class EType(Enum):
COUNSELOR = auto()
FRONT_DESK = auto()
class RType(Enum):
GH = auto()
SC = auto()
CH = auto()
class Shift(TimePeriod):
def __init__(self, st: int, et: int):
super().__init__(st, et)
hours = self.dur.seconds // 3600
if hours > 5:
self.break_length = 1
else:
self.break_length = .5
class Staff:
def __init__(self, name: str, emp_type: EType, st: int = None,
et: int = None, shift: Shift = None,):
if shift:
self.shift = shift
else:
self.shift = Shift(st, et)
self.name = name
self.emp_type = emp_type
def __str__(self):
return f'{self.name}'
def __repr__(self):
return f'Staff("{self.name}", {self.emp_type}, Shift={self.shift})'
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.name == other.name
return False
def __hash__(self):
return hash(self.name)
def _get_possible_break_periods(self):
emp_shift = self.shift
break_length = emp_shift.break_length
shifts = []
i = emp_shift.st + break_length
while i <= emp_shift.et:
shifts.append(Shift(i-break_length, i))
i += .5
return shifts
def _is_coincides(self, shift: Any) -> bool:
""" This function determins whether the staff object's
shift happens within the same time as another TimePeriod
returns true if it does, and false if it doesn't."""
if type(shift) == Staff:
shift = shift.shift
elif type(shift) == Room:
shift = shift.time_open
coincides = self.shift._coincides(shift)
return coincides
def _is_available(self, shift: Any) -> bool:
""" This function determins whether the staff object's
shift contains the entire period. If it does, then the staff
is available"""
if type(shift) == Staff:
shift = shift.shift
elif type(shift) == Room:
shift = shift.time_open
is_available = self.shift._contains(shift)
return is_available
class Room:
def __init__(self, name: RType):
room_info = self._room_assignment(name)
self.max_cap = room_info["max_cap"]
self.name = name
self.time_open = room_info["time_open"]
def _room_assignment(self, name: RType) -> Dict[str, Any]:
room_info = {}
times = [datetime(1, 1, 1, 9, 0),
datetime(1, 1, 1, 21, 0),
datetime(1, 1, 1, 14, 30, 0)]
if name == RType.CH:
room_info["max_cap"] = 2
room_info["time_open"] = TimePeriod(times[0], times[2])
elif name == RType.GH:
room_info["max_cap"] = 3
room_info["time_open"] = TimePeriod(times[0], times[1])
elif name == RType.SC:
room_info["max_cap"] = 1
room_info["time_open"] = TimePeriod(times[0], times[2])
return room_info
</code></pre>
<p><code>timemodule.py</code></p>
<pre><code>from typing import List
from datetime import datetime, timedelta
import scheduler
class TimePeriod:
"""
This class represents a time period between two points in time.
The smallest unit of time in this representation is 30mins, and
each time period is composed of 30 minute intervals.
---------------------------------------------------------------
++++++++++++++++++++++++ ARGS +++++++++++++++++++++++++++++++++
---------------------------------------------------------------
(int) st: Start Time
(int) et: End Time
"""
num = 0
def __init__(self, st: datetime, et: datetime):
if et <= st:
raise scheduler.TimeError(
"End time needs to be later than start time.")
self.st = st # datetime
self.et = et # datetime
self.dur = et - st # timedelta in seconds
self.comp = self._get_composition(self.dur)
self._id = self.update(1)
def __eq__(self, other):
"""
Allows one to check equality with instances
>>> start = datetime(1,1,1,1,30)
>>> end = datetime(1,1,1,4,30)
>>> TimePeriod(start, end) == TimePeriod(start, end)
True
"""
if isinstance(other, self.__class__):
return str(self) == str(other)
return False
def __str__(self):
return f'{self.st.strftime("%I:%M %p")} - {self.et.strftime("%I:%M %p")}'
def __repr__(self):
return f'{self.__class__}({self.st}, {self.et})'
def __hash__(self):
return hash(self._id)
def _split(self, part: int) -> List:
""" Split uses the partition argument to split the TimePeriod into
equal parts by blocks of .5 """
if part > len(self.comp):
raise BaseException("Cannot divide time segment into that many parts")
split_time = []
part_size = len(self.comp) // part
for i in range(part):
if i == (part - 1):
split_time.append(TimePeriod(self.comp[i * part_size],
self.comp[-1]))
else:
split_time.append(TimePeriod(self.comp[i * part_size],
self.comp[(i+1) * part_size]))
return split_time
def _contains(self, other_tp):
if self.st <= other_tp.st and self.et >= other_tp.et:
return True
return False
def _coincides(self, t2):
composition1 = set(self.comp)
composition2 = set(t2.comp)
in_common = composition1 & composition2
return bool(in_common)
def _get_composition(self, duration: timedelta) -> int:
""" It splits the duration into 30 minute segments and creates/returns a list
of the 30 minute segments the TimePeriod is composed from"""
hours = duration.seconds // 3600
mins = duration.seconds - (hours * 3600)
quant = hours * 2
quant = quant + 1 if int(mins) > 0 else quant
comp = [self.st + i * timedelta(minutes=30) for i in range(quant + 1)]
return comp
@classmethod
def update(cls, value):
cls.num += value
return cls.num
</code></pre>
<p><code>driver.py</code></p>
<pre><code>import streamlit as st
from _scheduler.work import Room, Staff, EType, RType
from _scheduler.manager import RoomManager
import graphviz as graphviz
import datetime as dt
from datetime import datetime, date, timedelta
import scheduler
def get_num_of_staff():
num_of_staff = st.text_input("How many staff do you want?", "0")
num_of_staff = int(num_of_staff)
return num_of_staff
def setup_times():
base_date = date(1, 1, 1)
start_time = dt.time(9, 0)
start_time = datetime.combine(base_date, start_time)
avail_times = [start_time + (i * timedelta(minutes=30)) for i in range(25)]
return avail_times
def create_staff_list(num_of_staff, avail_times):
staff_list = []
for i in range(num_of_staff):
name = st.text_input("* Enter the Staff's name",
str(i*num_of_staff))
start_time = st.selectbox(
f"Please Choose a Starting Time for {name}",
avail_times,
index=i * num_of_staff + 1,
format_func=lambda x: str(x.strftime("%I:%M %p")))
end_time = st.selectbox(
f"Please Choose an Ending Time for {name}",
avail_times,
index=i * num_of_staff + 2,
format_func=lambda x: str(x.strftime("%I:%M %p")))
try:
staff_list.append(Staff(name,
EType.COUNSELOR,
st=start_time,
et=end_time))
except scheduler.TimeError:
st.write("Please Pick A valid TIme")
return None
return staff_list
def setup_room_and_manager(staff_list):
club_house = Room(RType.CH) # room
chmanager = RoomManager(club_house, staff_list)
return chmanager
def draw_graph(times, order):
graph = graphviz.Digraph()
colorx = .000
for current in order:
final_color = f'{colorx} .999 .400'
for i, v in enumerate(current):
if i == len(current) - 1:
continue
time = str(times[i]).replace(":", " ")
time2 = str(times[i+1]).replace(":", " ")
node1 = v.name + " " + time
node2 = current[i+1].name + " " + time2
graph.edge(node1, node2, color=final_color)
colorx += .070
st.graphviz_chart(graph)
def get_schedule():
times, order = [], []
try:
times, order = manager.manage()
except Exception:
st.write("Not A valid Schedule")
return times, order
if __name__ == '__main__':
st.title("Break Scheduler")
number_of_staff = get_num_of_staff()
if number_of_staff > 0:
time_choices = setup_times()
staff_list = create_staff_list(number_of_staff, time_choices)
manager = setup_room_and_manager(staff_list)
times, order = get_schedule()
if len(times) > 0:
draw_graph(times, order)
else:
st.write("""
Please get more coverage. Can't make schedule from current shifts
""")
else:
st.write("Please begin filling out the information above")
</code></pre>
<h2>Design</h2>
<p>I'd love it if I could get advice and feedback on my current design. I've broken down the problem and created classes for Staff, Rooms, Shifts. I have a TimePeriod class that has a start and end time and some other attributes that allow for splitting a time period into multiple components that together add up to the original TimePeriod. It's made a little easy because for this program, the smallest unit of time is 30 mins, and the front end portion only provides users to select hours in the half hour interval. 9am, 9:30am, ..., 8:30pm, 9pm.</p>
<p>I have a Manager class that's in charge of creating the schedules, and my current manager class takes a Room and a list of Staff and provides possible combinations in which those staff can cover that room only for staff that are available to work at the time the room is open.</p>
<p>My front end runs on streamline and asks how many staff and for each staff collects their shift.
It then, if possible with the given staff shifts, returns a graph with the possible combinations that they can cover the club house which is open from 9AM-2:30PM.</p>
<h2>Goals</h2>
<p>I eventually want to be able to provide a more generalized front end. I'd like to give the user the ability to create any room and as many rooms as they need. I'd like to have an algorithm that can place the staff in each of those rooms. </p>
<p>I'd also like for it to figure out when the best time for staff to take breaks. I have a function in the <code>Staff</code> class that creates a list of possible break times within that staff's shift. I have an algorithm in mind that ranks each of the times in that list with the times in the being ranked higher, so that when it looks at all staff, it gives them breaks that don't overlap but are as close to the middle of their shift as possible. All while making sure that all rooms are covered by a staff member.</p>
<p>For my specific purpose I only need three rooms, two of which have the same time, but I'd like this to be very generalized so that anyone could use it for their workplace.</p>
<h2>Questions</h2>
<p>My questions have kind of been scattered throughout the text above and so I'll consolidate them here so that it's easier to refer to.</p>
<ul>
<li><p>Is the current design good for the goals that I have in mind, if not what can I change to make my goals easier to accomplish</p></li>
<li><p>What algorithms should I use when it comes to scheduling the rooms</p></li>
<li><p>Am I overlooking anything?</p></li>
<li><p>Where else can I look for help on this? I'm only one person and can't imagine this is something I get done alone in a short amount of time.</p></li>
</ul>
|
[] |
[
{
"body": "<h2>Type hints</h2>\n\n<p>You're using them. Great! As for this one:</p>\n\n<pre><code>def __init__(self, staff: List):\n</code></pre>\n\n<p>What is <code>staff</code> a list of? If you know, specify it as <code>List[Thing]</code>. If you do not know, leave it as <code>list</code>.</p>\n\n<h2>Parens</h2>\n\n<p>We're not in Java/C++/etc., so this</p>\n\n<pre><code> while(True):\n</code></pre>\n\n<p>does not need parentheses.</p>\n\n<h2>Order of conditions</h2>\n\n<p>I find this:</p>\n\n<pre><code> if self._is_enough_coverage(staff):\n breakdown = self._get_breakdown(staff)\n result = self._verify_breakdown(breakdown, len(staff))\n if result:\n return self.get_possible_shifts(breakdown)\n else:\n staff = self._remove_extra_staff(breakdown)\n else:\n return {}\n</code></pre>\n\n<p>would be more legible as</p>\n\n<pre><code>if not self._is_enough_coverage(staff):\n return {}\n\nbreakdown = self._get_breakdown(staff)\nresult = self._verify_breakdown(breakdown, len(staff))\nif result:\n return self.get_possible_shifts(breakdown)\n\nstaff = self._remove_extra_staff(breakdown)\n</code></pre>\n\n<h2>Generators</h2>\n\n<p>Some of your functions can be simplified with <code>yield</code>:</p>\n\n<pre><code> avail_staff = []\n for s in staff:\n if s._is_coincides(self.room):\n avail_staff.append(s)\n return avail_staff\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>for s in staff:\n if s._is_coincides(self.room):\n yield s\n</code></pre>\n\n<p>though in this case, you can condense this further:</p>\n\n<pre><code>return (s for s in staff if s._is_coincides(self.room))\n</code></pre>\n\n<p>A grammar nitpick: \"is coincides\" does not make sense; use either \"coincides\" or \"does coincide\".</p>\n\n<h2>Set simplification</h2>\n\n<pre><code> valid_staff = set()\n for s in breakdown.values():\n valid_staff = valid_staff.union(set(s))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>valid_staff = set(breakdown.values())\n</code></pre>\n\n<p>This pattern appears a few times.</p>\n\n<h2>Redundant <code>return</code></h2>\n\n<p>At the end of <code>_find_valid_path</code>.</p>\n\n<h2>Do not do your own time math</h2>\n\n<p>Here.</p>\n\n<pre><code> hours = self.dur.seconds // 3600\n</code></pre>\n\n<p>The way that the Python built-in recommends:</p>\n\n<pre><code>from datetime import timedelta\n# ...\n\nhours = self.dur / timedelta(hours=1)\n</code></pre>\n\n<p><code>self.dur</code> is already a <code>timedelta</code>. <code>break_length</code> should also be.</p>\n\n<h2>No-op format</h2>\n\n<p><code>f'{self.name}'</code> should just be <code>self.name</code>.</p>\n\n<h2>Combined predicates</h2>\n\n<pre><code> if isinstance(other, self.__class__):\n return self.name == other.name\n return False\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>return isinstance(other, self.__class__) and self.name == other.name\n</code></pre>\n\n<h2>Stringy representation</h2>\n\n<p>Why does <code>_room_assignment</code> return a dict? You already have a strong class structure. You should make a class with members <code>max_cap</code> and <code>time_open</code> and return an instance of this.</p>\n\n<h2>Overlap algorithm</h2>\n\n<pre><code> composition1 = set(self.comp)\n composition2 = set(t2.comp)\n in_common = composition1 & composition2\n</code></pre>\n\n<p>is a bad idea. Re-think this in terms of the start and end times of the two objects. I will leave this as an exercise to you.</p>\n\n<h2>Stringy times</h2>\n\n<p><code>draw_graph</code>, first of all, is missing type hints - but even without them I can tell that <code>times</code> is some sequence of strings. It should not be, nor should you be doing string manipulation on formatted times. Instead, pass them as actual time objects, and format them as appropriate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T23:47:04.683",
"Id": "241462",
"ParentId": "241458",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T21:36:00.097",
"Id": "241458",
"Score": "4",
"Tags": [
"python",
"algorithm",
"object-oriented",
"design-patterns"
],
"Title": "Staff Scheduler: Design/Algorithm questions (Python)"
}
|
241458
|
<blockquote>
<h1>Robot Name</h1>
<p>Manage robot factory settings.</p>
<p>When robots come off the factory floor, they have no name.</p>
<p>The first time you boot them up, a random name is generated in the format
of two uppercase letters followed by three digits, such as RX837 or BC811.</p>
<p>Every once in a while we need to reset a robot to its factory settings,
which means that their name gets wiped. The next time you ask, it will
respond with a new random name.</p>
<p>The names must be random: they should not follow a predictable sequence.
Random names means a risk of collisions. Your solution must ensure that
every existing robot has a unique name.</p>
</blockquote>
<p>That was the instructions given to me. The only constraints is the tests. From my previous post I'm trying to improve on my naming conventions, DRY code, access modifiers, and keeping it readable. Any advice would help me a lot since I'm learning C# and teaching myself. Thank you for your help especially to those that follow my progress and help me.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
public class Robot
{
private static Random _random;
private string _name;
private static readonly HashSet<string> _nameList = new HashSet<string>();
public string Name => _name;
public Robot()
{
_random = new Random();
_name = GenerateRandomName();
}
public void Reset()
{
_nameList.Remove(_name);
_name = GenerateRandomName();
}
private static string GenerateRandomLetters() => new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 2)
.Select(s => s[_random.Next(s.Length)]).ToArray());
private static string GenerateRandomName()
{
string name;
do
{
name = $"{GenerateRandomLetters()}{_random.Next(10)}{_random.Next(10)}{_random.Next(10)}";
}
while (_nameList.Contains(name));
_nameList.Add(name);
return name;
}
}
</code></pre>
<pre><code>using System.Collections.Generic;
using Xunit;
public class RobotNameTests
{
private readonly Robot robot = new Robot();
[Fact]
public void Robot_has_a_name() => Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name);
[Fact]
public void Name_is_the_same_each_time() => Assert.Equal(robot.Name, robot.Name);
[Fact]
public void Different_robots_have_different_names() => Assert.NotEqual(new Robot().Name, robot.Name);
[Fact]
public void Can_reset_the_name()
{
var originalName = robot.Name;
robot.Reset();
Assert.NotEqual(originalName, robot.Name);
}
[Fact]
public void After_reset_the_name_is_valid()
{
robot.Reset();
Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name);
}
[Fact]
public void Robot_names_are_unique()
{
var names = new HashSet<string>();
for (int i = 0; i < 10_000; i++) {
var robot = new Robot();
Assert.True(names.Add(robot.Name));
}
}
}
</code></pre>
<p>The test are immutable. They cannot be altered at all. I did not write these test. I have to work within the test. I would be interested in learning on how to improve on them out of curiosity at best. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T07:00:44.977",
"Id": "473900",
"Score": "0",
"body": "Do not call things something like `_nameList`, call it what would call it in real life: `_names` (or rather `_possibleNames`). Case in point: your `_nameList ` isn't even a `List`, it's a `Hashset`, and thus the name does not correspond with its actual type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:01:17.460",
"Id": "473979",
"Score": "0",
"body": "@BCdotWEB what about _robotNames or _robotNamesInUse?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T05:45:16.863",
"Id": "474026",
"Score": "0",
"body": "Write a test to generate 676000 robots, it Will take incredibly long. Write a test to create 676001 robots And your program Will get stuck in an Infinite loop. Assuming alphabet with 26 letters..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T06:16:19.360",
"Id": "474030",
"Score": "0",
"body": "Bonus question, if you choose 10000 items from 676000 possibilities, what Is the probability that two chosen elements are the same? In other words, what Is the reliability of the Robot_names_are_unique test? Well, it Is less than 100% And it would be less than 100% for any number of robots smaller then all of them plus 1. So only reliable test is to check that you can create 676000 robots and creating another one must fail."
}
] |
[
{
"body": "<p>We can create 676000 robots with unique names, because we have 26 possibilities for each 'letter position' and 10 possibilities for 'number position' in our name. So calculation is 26 * 26 * 10 * 10 * 10 = 676000.</p>\n\n<p>Why am I mentioning that? Because that number is not so big and maybe it's worth to <strong>consider</strong> pregenerating all possible values, keep them in pool and get/return when necessary. That's another approach. I don't want to say that it's better. It will be more memory consuming solution, but robot 'initialization' will be faster. Also it'll be easier to apply fix for point 6. Anyway, you should always get what suits your requirements. </p>\n\n<p>End of digression - back to your code!</p>\n\n<ol>\n<li>Why I can't see namespaces both in tests and in class? You copied it that way?</li>\n<li>I understand why you set up Random as static, but it's not thread safe the way you implemented it. Reference: <a href=\"https://jonskeet.uk/csharp/miscutil/usage/staticrandom.html\" rel=\"nofollow noreferrer\">[JON SKEET ARTICLE]</a></li>\n<li>Static readonly HashSet is very dangerous, because it's instance is shared between all threads and Hashset.Remove method could cause strange problems/exceptions in multithreaded environment. Of course no one is saying that in requirements, but I think that case should never be ignored. ConcurrentDictionary should be your choice in here, because it ensures thread safety. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=netcore-3.1\" rel=\"nofollow noreferrer\">[MSDN]</a></li>\n<li>Letters in alphabet will never change, so you can keep it as a const field. Thanks to that you'll avoid allocation string for each time somebody tries to generate random letters.</li>\n<li>In case for readability I have nothing to add it's pretty clear what's happening here.</li>\n<li>Last, but most important, comment from my side. A little challenge for you :) what will happen with your code when you create 676000 robots and try to create one more? Hint: you can use code from Robot_names_are_unique() test method, but increase upper limit of iterations to 676000.</li>\n</ol>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:13:16.957",
"Id": "473980",
"Score": "0",
"body": "1. That was how it was provided. I didn't think of adding a namespace to it either. I added it to my code. 2. I set it up that way to get it to work as in I had trouble getting it to work on the final test. It would fail without it. I will use @Henrik suggestion to address that. I have yet to get into topics about thread safety so I am unaware of these issues. 3. Is it because its a HashSet, the access modifiers, or both that makes this dangerous?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T05:54:06.183",
"Id": "474027",
"Score": "0",
"body": "Oh i wrote about the limit of number of robots into comments on OP question. Now I see you already pointed this out. You were on the very bottom, Gotta bump you up :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T18:37:02.337",
"Id": "474097",
"Score": "0",
"body": "```if (_robotNamesInUse.Count > _maxRobotNamesInUse)\n throw new IndexOutOfRangeException(\"Cannot create more robot names. List is full.\");```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T18:37:36.127",
"Id": "474098",
"Score": "0",
"body": "Would this and what I posted above work for this case?\n```private const int _maxRobotNamesInUse = 676000;```\n@slepic @Karol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T19:19:07.297",
"Id": "474109",
"Score": "0",
"body": "Basically yes. That rules out the possible Infinite loop. But there Is still the problem that the more robots you create the more likely it Is that you get duplicates during name generation. Lets take the worst case that you Are creating the last possible robot. You have Chance 1:676000 that you randomly choose the last unused name. That's 676000 random names to generate before you find the unused one, on average. Your algorithm Is basically O(r!) where r Is number of existing robots."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T19:26:06.753",
"Id": "474112",
"Score": "0",
"body": "@Milliorn if you pre generate all possible names And maintain a set of free And a set of used names you should be able to make it O(n-r) where n Is maximum number of robots And r Is current number of robots. At cost of increased memory consumption and some initial load time to generate all names in advance. The more robots you create the Faster it Is to create another one (on average). In your implementation it goes the other way."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T09:09:29.103",
"Id": "241479",
"ParentId": "241460",
"Score": "4"
}
},
{
"body": "<p>Again, your code seems well written and easy to follow and understand. Except for the name <code>_nameList</code> (as mentioned in the comment by BCdotWEB) your naming seems ok.</p>\n\n<p>Below, find my comments inline (<code>// HH: ...</code>) and my refactoring attempt:</p>\n\n<pre><code>// HH: You need a mechanism to remove the name from the name list when the Robot dies (= is garbage collected). Implementing IDisposable could be the way to go.\npublic class Robot\n{\n private static Random _random;\n private string _name; // HH: Use auto property for Name { get; private set; }\n private static readonly HashSet<string> _nameList = new HashSet<string>();\n public string Name => _name; // HH: Use auto property for Name { get; private set; }\n\n public Robot()\n {\n _random = new Random(); // HH: Instantiate this once when declaring it above. It gives no meaning to recreate a static member for each new instance of the object\n _name = GenerateRandomName();\n }\n\n public void Reset()\n {\n _nameList.Remove(_name); // HH: this needs to be done after GenerateRandomName() or else you could potentially create and use the same name again.\n _name = GenerateRandomName();\n }\n\n // HH: See my suggestion for an more readable approach. If you have to break the code into more lines, then IMO block style is more appropriate\n private static string GenerateRandomLetters() => new string(Enumerable.Repeat(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", 2)\n .Select(s => s[_random.Next(s.Length)]).ToArray());\n\n private static string GenerateRandomName()\n {\n string name;\n\n do\n {\n name = $\"{GenerateRandomLetters()}{_random.Next(10)}{_random.Next(10)}{_random.Next(10)}\";\n }\n while (_nameList.Contains(name)); // HH: You could just check: _nameList.Add(name) which will return false, if the name is already present in the set\n\n _nameList.Add(name);\n return name;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>My version:</p>\n\n<pre><code> public class Robot : IDisposable\n {\n private static readonly Random _random = new Random();\n const string _nameChars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n private static readonly HashSet<string> _namesInUse = new HashSet<string>();\n public string Name { get; private set; }\n\n public Robot()\n {\n Name = GenerateRandomName();\n }\n\n public void Reset()\n {\n Name = GenerateRandomName();\n _namesInUse.Remove(Name);\n }\n\n private static string GenerateRandomLetters()\n {\n return $\"{_nameChars[_random.Next(_nameChars.Length)]}{_nameChars[_random.Next(_nameChars.Length)]}\";\n }\n\n private static string GenerateRandomName()\n {\n string name;\n\n do\n {\n name = $\"{GenerateRandomLetters()}{_random.Next(1000):000}\";\n } while (!_namesInUse.Add(name));\n\n return name;\n }\n\n public void Dispose()\n {\n if (Name != null)\n {\n _namesInUse.Remove(Name);\n Name = null;\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T14:55:34.547",
"Id": "473946",
"Score": "0",
"body": "Your code indeed fixes points 2 and 4 from my answer, but still thread safety and point 6 seems unresolved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T18:13:32.313",
"Id": "473959",
"Score": "1",
"body": "@KarolMiszczyk: I think thread safety is beyond the beginners level. I find your suggestion about generating all the names beforehand as a bad approach. And about name \"overflow\": If there was a risk of that, the name was probably designed a bit longer than it is. Anyway my answer is an answer to the question not to your answer. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:18:13.223",
"Id": "473982",
"Score": "0",
"body": "@HenrikHansen I changed ```_nameList``` to ```_robotNamesInUse```. I've gotten out of the habit of making comments. I need to get in the habit again of doing that in case people are unclear of my intent. Is there a reason why you did ```Name = GenerateRandomName();\n _namesInUse.Remove(Name);``` and not ```_robotNamesInUse.Remove(Name);\n Name = GenerateRandomName();``` Basically the order of which one is called is switched."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:21:49.527",
"Id": "473983",
"Score": "0",
"body": "```return $\"{_nameChars[_random.Next(_nameChars.Length)]}{_nameChars[_random.Next(_nameChars.Length)]}\";``` You changed that from ```new string(Enumerable.Repeat(_nameChars, 2)\n .Select(s => s[_random.Next(s.Length)]).ToArray());``` Was that done to simply remove the dependency on Linq? If not, then what was the reason. Preference? I'm asking because it seems repetitive an I am unsure of what issue you had with my approach? I went ahead and change it to that since it remove Linq from this, but still like to have an explanation of why you chose this if it was another reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:27:47.277",
"Id": "473984",
"Score": "1",
"body": "@HenrikHansen disregard what I asked about why you swapped those calls. I just realize you notated that when you said **_nameList.Remove(_name); // HH: this needs to be done after GenerateRandomName() or else you could potentially create and use the same name again.**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:29:10.307",
"Id": "473985",
"Score": "0",
"body": "@Millorn: If you remove the old name from the list of names in use - before you generate a new one, you can not guarantee that the new one is different from the old one, because the old one is no longer in the list of existing names to compare against. The spec says, that the new name should be a different random name than the old. About the generation of names: I just think my approach is easier to read and maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:32:02.167",
"Id": "473986",
"Score": "0",
"body": "@HenrikHansen yeah, I didn't post fast enough to say I overlooked that comment. The one last thing that baffles me is how this works ```name = $\"{GenerateRandomLetters()}{_random.Next(1000):000}\";``` In particular the use of : in this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T20:37:54.170",
"Id": "473987",
"Score": "0",
"body": "@Milliorn: `:000` is a [format specifier](https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=netcore-3.1), which is an art in itself. Here it specify that the random number should always be shown with three digits (maybe prefixed with one or two `0`if the random number is less than `100`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T23:18:49.500",
"Id": "474001",
"Score": "1",
"body": "@HenrikHansen it's starting to make sense now. 000-999."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T13:06:11.963",
"Id": "241493",
"ParentId": "241460",
"Score": "4"
}
},
{
"body": "<p>To me, one of the things worth considering is that a <code>Robot</code> object would be more involved than having just a name. To that end it would make sense to have a name generator(<code>RobotNameGenerator</code>) to encapsulate the fields and methods relating to generating the name.</p>\n\n<p>For the actual name generating algorithm, a readonly string for the letters and some LINQ extensions, will reduce it to one line:</p>\n\n<pre><code>String.Join(\"\", Enumerable.Range(0, 2)\n .Select(x => letters[rnd.Next(26)])\n .Concat(Enumerable.Range(0, 3)\n .Select(x => (char)(rnd.Next(10) + '0'))))\n</code></pre>\n\n<p>Such a generator when put together could look something like this:</p>\n\n<pre><code>private class RobotNameGenerator\n{\n private static readonly string letters = \"ABCDEFGHIJKLMNOPQRST\";\n private static readonly Random rnd = new Random();\n private static readonly HashSet<string> usedNames = new HashSet<string>();\n public static string GetUniqueName(string nameToReplace = \"\")\n {\n string name = \"\";\n do\n {\n name = String.Join(\"\", Enumerable.Range(0, 2)\n .Select(x => letters[rnd.Next(26)])\n .Concat(Enumerable.Range(0, 3)\n .Select(x => (char)(rnd.Next(10) + '0'))));\n } while (usedNames.Contains(name));\n usedNames.Add(name);\n if (nameToReplace != \"\")\n {\n CancelUsedName(nameToReplace);\n }\n return name;\n }\n static void CancelUsedName(string name)\n {\n usedNames.Remove(name);\n }\n}\n</code></pre>\n\n<p>After some more thought, I came upon an optimization:</p>\n\n<pre><code>name = String.Join(\"\", Enumerable.Range(0, 5)\n .Select(x => x < 2 ? letters[rnd.Next(letters.Length)] : (char)(rnd.Next(10) + '0')));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T23:28:23.990",
"Id": "474003",
"Score": "0",
"body": "That is another interesting perspective using LINQ to set **name**."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T22:12:03.987",
"Id": "241528",
"ParentId": "241460",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T22:02:58.673",
"Id": "241460",
"Score": "3",
"Tags": [
"c#",
"beginner",
"object-oriented",
"xunit"
],
"Title": "Robot Name - Exercise"
}
|
241460
|
<p>I have a dictionary that I need to iterate efficiently. I already know about the keys beforehand which I need to extract from <code>values</code> dictionary object.
What's the best way to do that? I have around 20 entries in dictionary object as of now.</p>
<p>Below is how I am doing it but wanted to see if we can optimize it by just getting values of key directly since I already know about what key I need to extract from them instead of using <code>foreach</code> loop here which is not good in terms of performance?</p>
<pre><code> // predefined keys
public const string ABC = "header-abc";
public const string PQR = "header-pqr";
public const string DEF = "header-def";
public const string HIP = "header-hip";
foreach (KeyValuePair<string, StringValues> v in values)
{
string key = v.Key;
StringValues val = v.Value;
if (val.Count > 0)
{
if (!string.IsNullOrWhiteSpace(val[0]))
{
switch (key)
{
case ABC:
HeadOne = val[0];
HeadOneId = HeadOne;
break;
case PQR:
HeadTwo = val[0];
HeadTwoId = HeadTwo;
break;
case DEF:
HeadThree = val[0];
HeadThreeId = HeadThree;
break;
case HIP:
HeadFour = val[0];
HeadFourId = HeadFour;
break;
//.. bunch of other case block here with similar stuff
}
}
}
}
</code></pre>
<p>As of now it looks redundant to iterate <code>values</code> dictionary object since I already know about all my keys that I need to extract from <code>values</code> dictionary object. What's the best way (in terms of performance) to do this considering <code>keys</code> are already known beforehand?</p>
<p>One option I can think of is instead of <code>foreach</code> loop here can we use <code>keys</code> property of iterating dictionary?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T06:21:32.870",
"Id": "473895",
"Score": "4",
"body": "While `values` is a strange name for a dictionary anyway, you don't explicitly state its type. You don't show but a couple of key values to handle; in particular, you don't show how irrelevant keys are handled/ignored. You don't indicate the ratio of keys to handle vs. keys to ignore: There is too much context missing to give a meaningful review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T06:55:19.380",
"Id": "473899",
"Score": "0",
"body": "Why do you do `HeadOne = val[0];` and then `HeadOneId = HeadOne;`? Why would you store the same value in two variables like that? What is even the point of extracting the values from the Dictionary and storing them in variables -- why not use the Dictionary directly? What's the point of having a value in your Dictionary that is of type StringValues when you only are going to use a single value from it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T19:11:32.520",
"Id": "474106",
"Score": "0",
"body": "I agree we're missing something here. Next time, please add the *real* code and take a look at the [help/on-topic]."
}
] |
[
{
"body": "<p>I'm not sure I understand completely what you're trying to achieve. [Sorry, I'm not allowed to write a comment yet, so I couldn't ask for clarification there...]</p>\n\n<p>If you know what keys you're looking for, you can just get the value in 1 step from the Dictionary.</p>\n\n<pre><code>public const string searchKey = \"key2\";\n\nDictionary<string, string> values = new Dictionary<string, string>() {\n { \"key1\", \"value1\" },\n { \"key2\", \"value2\" },\n { \"key3\", \"value3\" }\n};\n\n// A: If you are sure the key can be found in the dictionary or you want to get an Exception in case it is not\nstring v = values[searchKey]; // v will be \"value2\"\n\n// B: If you're not sure if the key is in the dictionary and you don't want an Exception\nif (values.TryGetValue(searchKey, out string val))\n{\n // Here val will be \"value2\"\n}\nelse\n{\n // This code runs when searchKey was not among the dictionary keys\n}\n\n</code></pre>\n\n<p>Of course Option A is faster, but see the comment if it fits your situation. There is no faster way to get a value from a Dictionary.</p>\n\n<p>Based on this, your code would be something like this:</p>\n\n<pre><code>// predefined keys\npublic const string ABC = \"header-abc\";\npublic const string PQR = \"header-pqr\";\npublic const string DEF = \"header-def\";\npublic const string HIP = \"header-hip\";\n\nHeadOne = values[ABC];\nHeadOneId = HeadOne;\n\nHeadTwo = values[PQR];\nHeadTwoId = HeadTwo;\n\nHeadThree = values[DEF];\nHeadThreeId = HeadThree;\n\nHeadFour = values[HIP];\nHeadFourId = HeadFour;\n\n</code></pre>\n\n<p>or with option B:</p>\n\n<pre><code>// predefined keys\npublic const string ABC = \"header-abc\";\npublic const string PQR = \"header-pqr\";\npublic const string DEF = \"header-def\";\npublic const string HIP = \"header-hip\";\n\nif (values.TryGetValue(ABC, out string val))\n{\n HeadOne = val;\n HeadOneId = HeadOne;\n}\n\nif (values.TryGetValue(PQR, out string val))\n{\n HeadTwo = val;\n HeadTwoId = HeadTwo;\n}\n\nif (values.TryGetValue(DEF, out string val))\n{\n HeadThree = val;\n HeadThreeId = HeadThree;\n}\n\nif (values.TryGetValue(HIP, out string val))\n{\n HeadFour = val;\n HeadFourId = HeadFour;\n}\n</code></pre>\n\n<p>I hope this is an answer to your question. If not, please clarify your goal or ask questions. Thanks!</p>\n\n<hr>\n\n<p>Update 1 - Answer to your comment:</p>\n\n<p>Yes, totally. If you have the relevant keys in a collection you can iterate through them and use TryGetValue in the loop. But in this case the variable names like \"HeadOne\", \"HeadTwo\" or \"HeadFourId\" need to be generalized as well. Or you need an extra switch-case inside the loop again, which leads back to square one.</p>\n\n<p>Also, consider the comments on the question, they have some good points, like using the dictionary directly where you need it rather than getting out the values separately and use them later.</p>\n\n<p>An example for the loop:</p>\n\n<pre><code>string[] keys = new string[] { \"header-abc\", \"header-pqr\", \"header-def\", \"header-hip\" }\n\nIList<string> headerValues = new List<string>();\n\nforeach (var key in keys)\n{\n if (values.TryGetValue(key, out string val))\n {\n headerValues.Add(val);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T02:09:55.930",
"Id": "473887",
"Score": "0",
"body": "thanks for your suggestion. how about using for loop here to iterate all the keys and then using `TryGetValue` on them instead of having each separate line with if check? maybe I can make separate arrays list here with all the keys and iterate that array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T11:27:34.420",
"Id": "473918",
"Score": "0",
"body": "See the update in the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T01:49:35.053",
"Id": "241469",
"ParentId": "241461",
"Score": "2"
}
},
{
"body": "<p>I believe you can do this if you put the header keys inside an array, and then you can loop over the array itself, and use <code>TryGetValue</code> for the dictionary. </p>\n\n<p>This is the simplest form for it : </p>\n\n<pre><code>public readonly string[] HeaderKeys = {\n \"header-abc\", \n \"header-pqr\", \n \"header-def\", \n \"header-hip\"\n}\n\nfor(var x = 0; x < HeaderKeys.Length; x++)\n{\n var isKeyExist = values.TryGetValue(HeaderKeys[x], var KeyValue);\n\n // if there is no key defined, just go to the next iteration.\n if(!isKeyExist) { continue; } \n\n switch (HeaderKeys[x])\n {\n case \"header-abc\":\n // inline assigning\n HeadOne = HeadOneId = KeyValue; \n break;\n case \"header-pqr\":\n HeadTwo = HeadTwoId = KeyValue;\n break;\n case \"header-def\":\n HeadThree = HeadThreeId = KeyValue;\n break;\n case \"header-hip\":\n HeadFour = HeadFourId = KeyValue;\n break;\n //.. bunch of other case block here with similar stuff\n }\n}\n</code></pre>\n\n<p>You need a <code>readonly string[]</code> this way, it can't be changed once initialized. <code>System.Array</code> is the lightest, and yet the simplest array, so using <code>for</code> loop with it would give you the fastest iteration over any other collection type. </p>\n\n<p>Next, you only want to pass each header key to the <code>TryGetValue</code> and get the value. The <code>TryGetValue</code> would return <code>true</code> if the value has been <code>out</code>, and <code>false</code> if there is none. </p>\n\n<p>Then, you have one line if condition : </p>\n\n<pre><code> // if there is no key defined, just go to the next iteration.\n if(!isKeyExist) { continue; } \n</code></pre>\n\n<p>This would skip any iteration if the result of <code>TryGetValue</code> is <code>false</code>. \nAnd I believe that <code>string.IsNullOrWhiteSpace(KeyValue)</code> is an extra unneeded work. So, I got rid of it. because even if the <code>KeyValue</code> is null or empty, the variables would be also null. So, at this stage you're just assigning variables, the other validation would be on other part of the current system where it needs to be critical to have a value. </p>\n\n<p>Now, assigning the variables like this : </p>\n\n<pre><code>HeadOne = KeyValue;\nHeadOneId = HeadOne;\n</code></pre>\n\n<p>can be simplified to this : </p>\n\n<pre><code>HeadOne = HeadOneId = KeyValue;\n</code></pre>\n\n<p>the difference is that the first one would let the compiler read the value twice. While the second would read it once, and assign it twice. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-19T02:05:53.343",
"Id": "482558",
"Score": "0",
"body": "I have another question which needs code review [here](https://codereview.stackexchange.com/questions/245670/scan-a-directory-for-files-and-load-it-in-memory-efficiently). Wanted to see if you have some time to take a look and provide some suggestions and improvements basis on my code. Any help will be appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T16:41:11.607",
"Id": "241507",
"ParentId": "241461",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241507",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T22:39:36.850",
"Id": "241461",
"Score": "0",
"Tags": [
"c#",
"performance"
],
"Title": "Iterate dictionary object efficiently in c# with pre defined keys?"
}
|
241461
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.