body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have the following method:</p>
<pre><code>private P2SAFile populateP2SAFile(File file, Message out) throws Exception {
String filename = file.getName();
FileType fileType = extractFileTypeFromFileName(filename);
String instrument = null;
Boolean calibrated = null;
String destination = null;
Date date = new Date();
switch (fileType) {
case ANCILLARY:
instrument = Constants.Instrument.LYRA.name();
calibrated = Boolean.FALSE;
destination = getDestination(fileType, instrument);
break;
case DAILY_DIFF_MOVIE:
case DAILY_MOVIE:
instrument = Constants.Instrument.SWAP.name();
calibrated = Boolean.TRUE;
date = extractDateFromFileName(filename);
destination =
getYearMonthDestination(date,
Constants.Instrument.SWAP.name().toLowerCase(),
Constants.DataType.MOVIE.name().toLowerCase());
break;
default:
throw new IllegalArgumentException("Unknown file type " + filename);
}
out.setHeader(Constants.FILE_DESTINATION_HEADER, destination);
FileExtension fileExtension = FileExtension.valueOf(getFileExtension(filename).toUpperCase());
P2SAFile p2saFile = getP2SAFile(filename, fileExtension.name(), instrument, calibrated);
p2saFile.setFilePath(destination);
p2saFile.setExtension(fileExtension.name());
p2saFile.setFileDate(date);
p2saFile.setFileSize(file.length());
p2saFile.setFileType(fileType.name());
p2saFile.setProcessingLevel(Constants.NOT_APPLICABLE);
return p2saFile;
}
</code></pre>
<p>I would like to refactor out the switch statements as new types will be added in future and it is a bit ugly. I know one solution to this is to create classes to do this using strategy or command pattern or maybe I could create a factory which returned the right type.</p>
<p>Any comments welcome
Thanks</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T08:49:08.370",
"Id": "389956",
"Score": "3",
"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... | [
{
"body": "<p>Your FileType appears to me good to encapsulate itself all the things you need.</p>\n\n<p>I used many strategies to archieve same result to illustrate how to use enum as you like. I think it works with very few changes</p>\n\n<pre><code>public enum FileType{\n\nANCILLARY(Constants.Instrument.LYRA.... | {
"AcceptedAnswerId": "202381",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T08:02:54.190",
"Id": "202375",
"Score": "-1",
"Tags": [
"java"
],
"Title": "Removing switch statments"
} | 202375 |
<p>I want to write a generic parser which takes a value, and type and returns label of given value instead.</p>
<p>Currently, this is my code:</p>
<pre><code>import a from "../constants/a"
import b from "../constants/b"
import c from "../constants/c"
const find = (value, fromArray) => fromArray.find((term) => term.value === value);
const getLabel = (of, fromArray) => {
const value = find(of, fromArray);
return (value && value.label) || 'No info';
};
export default (value, type) => {
switch (type) {
case 'paymentMethod':
return getLabel(value, paymentMethods);
case 'paymentTerm':
return getLabel(value, paymentTerms);
case 'dateType':
return getLabel(value, dateTypes);
default:
return 'No info';
}
}
</code></pre>
<p>What would be more ES6, faster and concise way to achieve this?</p>
| [] | [
{
"body": "<h1>Granularity</h1>\n\n<p>All code can be said to have a level of granularity. This is a measure of how many functions it contains. Low granularity has fewer larger functions that has benefits of faster run-times at the expense of readability, while high granularity has many smaller functions, tradi... | {
"AcceptedAnswerId": "202450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T09:21:20.953",
"Id": "202379",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Javascript / ES6 parse value from arrays of objects"
} | 202379 |
<p>I have a large HTML document where everything is inside a main div, structured like this:</p>
<pre><code><div class="main">
\\block 1
<div class="header"><span>content1a</span><span>content1b</span></div>
<p>content1c</p>
\\block 2
<div class="header"><span>content2a</span><span>content2b</span></div>
<p>content2c</p>
...
</div>
</code></pre>
<p>As you can see the contents of the header divs are related to the paragraphs, so my Python code separates these tag blocks into lists of a list so I can take out their contents later:</p>
<pre><code>main_div = soup.find("div", class_="main")
headers = main_div.find_all("div", class_="header")
all_blocks = []
current_block = []
for tag in main_div.contents:
if tag in headers:
all_blocks.append(current_block)
current_block = [tag]
else:
current_block.append(tag)
all_blocks.append(current_block) # append final block
all_blocks = all_blocks[1:] # take off first empty list
</code></pre>
<p>Problem is this seems to take forever on a ~12MB HTML file I'm feeding it (less than 1% done after 1h, while parsing the file with bs4 only took 25s).
Is there something really inefficient in my code or is this going to be slow anyway?</p>
| [] | [
{
"body": "<p>It seems like you have the following:</p>\n\n<pre><code><div class=\"main\">\n <div class=\"header\">a</div>\n <p>b</p>\n\n <div class=\"header\">c</div>\n <p>d</p>\n</div>\n</code></pre>\n\n<p>And you want to extract a list o... | {
"AcceptedAnswerId": "202391",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T10:53:47.763",
"Id": "202389",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"html",
"beautifulsoup"
],
"Title": "Python - Iterating over contents of BeautifulSoup element very slow"
} | 202389 |
<p>This class is intended to be used in situations where <a href="https://docs.python.org/3/library/queue.html" rel="noreferrer"><code>queue.Queue</code></a> does not suffice, because the following two properties are needed.</p>
<ul>
<li>Every item in the queue can have a priority assigned.</li>
<li>No item can occur more than once in the queue.</li>
</ul>
<p>So here is my current implementation. I would be happy to hear your ideas on how the code can be improved.</p>
<pre><code>"""A thread-safe priority queue keeping its elements unique
"""
import collections
import threading
import time
import unittest
from typing import DefaultDict, Deque, Set, Generic, TypeVar
T = TypeVar('T')
class OrderedSetPriorityQueue(Generic[T]):
"""A thread-safe priority queue keeping its elements unique"""
def __init__(self) -> None:
self.deques: DefaultDict[int, Deque[T]] = \
collections.defaultdict(collections.deque)
self.elem_sets: DefaultDict[int, Set[T]] = \
collections.defaultdict(set)
self.condition_var = threading.Condition(threading.RLock())
def contains(self, item: T) -> bool:
"""Check if the item is already queued."""
with self.condition_var:
for elem_set in self.elem_sets.values():
if item in elem_set:
return True
return False
def contains_with_prio(self, item: T, priority: int) -> bool:
"""Check if the item is already queued with this exact priority."""
with self.condition_var:
if priority not in self.elem_sets:
return False
return item in self.elem_sets[priority]
def remove(self, item: T) -> bool:
"""Remove an item from the queue, disregarding its stored priority."""
with self.condition_var:
if not self.contains(item):
return False
removed_count = 0
for set_prio, elem_set in self.elem_sets.items():
if item in elem_set:
self.deques[set_prio].remove(item)
elem_set.remove(item)
removed_count += 1
assert removed_count in [0, 1]
self._clean_up()
return removed_count > 0
def put(self, item: T, priority: int = 0) -> bool:
"""Returns False if item already is queued with the same priority.
If is has not been queued yet, it is added and True is returned.
If it already was queued but with a different priority,
the entry with the old priority will be removed,
and the new one is added."""
with self.condition_var:
if self.contains_with_prio(item, priority):
return False
if self.contains(item):
self.remove(item)
self.deques[priority].appendleft(item)
self.elem_sets[priority].add(item)
self.condition_var.notify()
return True
def empty(self) -> bool:
"""Return True if the queue is completely empty."""
with self.condition_var:
assert bool(self.elem_sets) == bool(self.deques)
return not self.elem_sets
def size(self) -> int:
"""Number of elements in the queue."""
with self.condition_var:
return sum(map(len, self.elem_sets.values()))
def get(self) -> T:
"""Pop the oldest item from the highest priority."""
with self.condition_var:
while not self.elem_sets:
self.condition_var.wait()
priority = sorted(self.deques.keys())[-1]
item = self.deques[priority].pop()
self.elem_sets[priority].remove(item)
self._clean_up()
return item
def _clean_up(self) -> None:
"""Internal function used to clean up unused data structures."""
with self.condition_var:
assert sorted(self.deques.keys()) == sorted(self.elem_sets.keys())
priorities = list(self.elem_sets.keys())
for priority in priorities:
if not self.deques[priority]:
del self.deques[priority]
if not self.elem_sets[priority]:
del self.elem_sets[priority]
class OrderedSetPriorityQueueTest(unittest.TestCase):
"""
Verify integrity of custom queue implementation
"""
def test_get_and_put(self) -> None:
queue: OrderedSetPriorityQueue[int] = OrderedSetPriorityQueue()
queue.put(0)
self.assertEqual(0, queue.get())
self.assertTrue(queue.empty())
def test_order(self) -> None:
queue: OrderedSetPriorityQueue[int] = OrderedSetPriorityQueue()
queue.put(0)
queue.put(2)
queue.put(1)
self.assertEqual(0, queue.get())
self.assertEqual(2, queue.get())
self.assertEqual(1, queue.get())
self.assertTrue(queue.empty())
def test_priority(self) -> None:
queue: OrderedSetPriorityQueue[int] = OrderedSetPriorityQueue()
queue.put(0, 0)
queue.put(1, 1)
self.assertEqual(1, queue.get())
self.assertEqual(0, queue.get())
self.assertTrue(queue.empty())
def test_increase_priority(self) -> None:
queue: OrderedSetPriorityQueue[int] = OrderedSetPriorityQueue()
queue.put(0, 0)
queue.put(1, 1)
queue.put(0, 2)
self.assertEqual(2, queue.size())
self.assertEqual(0, queue.get())
self.assertEqual(1, queue.get())
self.assertTrue(queue.empty())
def test_decrease_priority(self) -> None:
queue: OrderedSetPriorityQueue[int] = OrderedSetPriorityQueue()
queue.put(0, 1)
queue.put(1, 1)
queue.put(0, 0)
self.assertEqual(1, queue.get())
self.assertEqual(0, queue.get())
self.assertTrue(queue.empty())
def test_uniqueness(self) -> None:
queue: OrderedSetPriorityQueue[int] = OrderedSetPriorityQueue()
queue.put(0)
queue.put(0)
queue.put(1)
queue.put(0)
self.assertEqual(0, queue.get())
self.assertEqual(1, queue.get())
self.assertTrue(queue.empty())
def test_get_with_wait(self) -> None:
queue: OrderedSetPriorityQueue[int] = OrderedSetPriorityQueue()
def add_to_queue() -> None:
time.sleep(0.2)
queue.put(0)
thread = threading.Thread(target=add_to_queue, args=(), kwargs={})
thread.start()
self.assertEqual(0, queue.get())
thread.join()
self.assertTrue(queue.empty())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T08:39:37.953",
"Id": "390499",
"Score": "0",
"body": "You're aware of the `PriorityQueue` yes? (`from queue import PriorityQueue`) As for the constraint of no duplicate items, I guess you'll want to have a wrapper function to perfor... | [
{
"body": "<p>Let's start with the good:</p>\n\n<ul>\n<li>Ohh recent Python 3, nice!</li>\n<li>Good documentation</li>\n<li>Good use of <code>typing</code>. This is great for datastructures.</li>\n<li>Good formatting of your code. Nice spacing. Decent naming</li>\n<li>Good use of <code>defaultdict</code></li>\n... | {
"AcceptedAnswerId": "202399",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T11:46:03.753",
"Id": "202393",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"multithreading",
"thread-safety",
"queue"
],
"Title": "A thread-safe priority queue keeping its elements unique"
} | 202393 |
<p>Coming to the close of week 1 learning a programming language (Python)</p>
<p>Looking for general review, comments, and tips</p>
<p><strong>Objective of Code</strong>
<br/>
The objective here was to practice pulling information from dictionaries within lists and also adding dictionaries created from user input.</p>
<p><strong>Code</strong></p>
<pre><code>def make_album(artist, album, tracks =''):
catalog = {}
catalog['artist_name'] = artist
catalog['album_title'] = album
catalog['tracks'] = tracks
return catalog
def ask_user(message):
user_input =''
while not user_input:
user_input = input(message)
return user_input
riven = make_album('Zeppelin', 'Houses of the Holy', 8)
jax = make_album('Tool', 'Lateralus', 13)
vayne = make_album('Pink Floyd', 'Dark Side of the Moon')
differents = [riven, jax, vayne]
while True:
print("type q to quit")
band = ask_user("Enter artist: ")
if band == "q":
break
album = ask_user("Enter album: ")
if album == 'q':
break
numbers = input("Enter number of tracks: ")
if numbers == 'q':
break
fire = make_album(band.title(), album.title(), numbers)
differents.append(fire)
for i in differents:
if i['tracks']:
print('\n' + i['album_title'] + ' by ' \
+ i['artist_name'] + ' it has '\
+ str(i['tracks']) +' tracks.')
else:
print('\n' + i['album_title'] + ' by ' + i['artist_name'] \
+ '.')
</code></pre>
<p><strong>Output</strong></p>
<pre class="lang-none prettyprint-override"><code>vash@localhost:~/pcc/8$ python3 lot2learn.py
type q to quit
Enter artist: circa survive
Enter album: juturna
Enter number of tracks: 11
type q to quit
Enter artist: dance gavin dance
Enter album: happiness
Enter number of tracks:
type q to quit
Enter artist: q
Houses of the Holy by Zeppelin it has 8 tracks.
Lateralus by Tool it has 13 tracks.
Dark Side of the Moon by Pink Floyd.
Juturna by Circa Survive it has 11 tracks.
Happiness by Dance Gavin Dance .
(xenial)vash@localhost:~/pcc/8$
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T12:53:19.383",
"Id": "389999",
"Score": "0",
"body": "@Graipher when you have time!"
}
] | [
{
"body": "<ol>\n<li>You should put all code that isn't in a function in a <code>if __name__ == '__main__'</code> guard. So that it doesn't run when it shouldn't.</li>\n<li>You can simplify quitting by using exceptions. If you make a function that raises say <code>KeyboardInterupt</code> if the input is <code>'... | {
"AcceptedAnswerId": "202406",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T12:52:46.837",
"Id": "202400",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Working with user input and dictionaries inside of lists"
} | 202400 |
<p>I have some code that I'm trying to speed up. Maybe what I've got is right, but whenever I ask on StackOverflow somebody usually knows a clever little trick "Use map!", "try this lambda", or "import iteratetools" and I'm hoping somebody can help here. This is the section of code I'm concerned with:</p>
<pre><code>#slowest part from here....
for row_dict in json_data:
row_dict_clean = {}
for key, value in row_dict.items():
value_clean = get_cleantext(value)
row_dict_clean[key] = value_clean
json_data_clean.append(row_dict_clean)
total += 1
#to here...
</code></pre>
<p>The concept is pretty simple. I have a multi-million long <code>list</code> that contains dictionaries and I need to run each <code>value</code> through a little cleaner. Then I end up with a nice list of cleaned dictionaries. Any clever <code>iterate</code> tool that I'm not aware of that I should be using? Here is a more complete MVE to help play with it:</p>
<pre><code>def get_json_data_clean(json_data):
json_data_clean = []
total = 0
#slowest part from here....
for row_dict in json_data:
row_dict_clean = {}
for key, value in row_dict.items():
value_clean = get_cleantext(value)
row_dict_clean[key] = value_clean
json_data_clean.append(row_dict_clean)
total += 1
#to here...
return json_data_clean
def get_cleantext(value):
#do complex cleaning stuffs on the string, I can't change what this does
value = value.replace("bad", "good")
return value
json_data = [
{"key1":"some bad",
"key2":"bad things",
"key3":"extra bad"},
{"key1":"more bad stuff",
"key2":"wow, so much bad",
"key3":"who dis?"},
# a few million more dictionaries
{"key1":"so much bad stuff",
"key2":"the bad",
"key3":"the more bad"},
]
json_data_clean = get_json_data_clean(json_data)
print(json_data_clean)
</code></pre>
<p>Anytime I have nested for loops a little bell rings in my head, there is probably a better way to do this. Any help is appreciated!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T13:30:10.390",
"Id": "390013",
"Score": "4",
"body": "Have you done any profiling? From looking at your example, it seems like `get_cleantext` should take up 99%+ of your execution time, yet you haven't provided the code inside that... | [
{
"body": "<p>You could start putting all this in a function:</p>\n\n<pre><code>def foo(row_dict):\n row_dict_clean = {}\n for key, value in row_dict.items():\n value_clean = get_cleantext(value)\n row_dict_clean[key] = value_clean\n return row_dict_clean\n</code></pre>... | {
"AcceptedAnswerId": "202404",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T13:14:40.673",
"Id": "202402",
"Score": "-2",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Faster mapping/modifying values in a large list of Python dicts?"
} | 202402 |
<p>I need to print signed 64-bit numbers in decimal form. Program runs in freestanding environment (no C library available, libgcc may be unavailable too, or may not work correctly). So I can't use printf(3) function.</p>
<p>I'am trying to write function, which will be able to convert number from binary form (int64_t) to ascii. Simple solution is to divide number by 10, and use remainder as next digit (from left to right, iteratively).</p>
<p>Unfortunately, processor doesn't have 64 bit division, and I can't rely on libgcc in that (__udivdi3 function). So I invented other way to perform binary->decimal conversion, by using binary coded decimal (BCD) numbers. First I convert binary number to BCD form (bit by bit, need 64 iterations, and need to sum BCD numbers), then convert BCD to ASCII.</p>
<p>Source code is following:</p>
<pre><code>/*static*/ void _print_dec(intmax_t num)
{
char *p;
char buf[24 /* > log10(2^64) */];
uint_fast8_t r;
uint64_t n = num < 0 ? -num : +num;
uint_fast16_t result_h = 0, digit_h = 0;
uint64_t result = 0, digit = 1;
while (n != 0)
{
/* sum bcd numbers: r = a + b, where r should be L-value */
#define BCD_ADD(type, r, a, b) do { \
type t1 = a + (type)(0x6666666666666666 & ((type)-1 >> 4)), t2 = t1 ^ b; \
t1 += b, t2 = ~(t1 ^ t2) & (type)0x1111111111111110; r = t1 - (t2>>2 | t2>>3); \
} while (0);
/* this macro computes rh:rl = ah:al + bh:bl (sum of compound BCD number), rh:rl should be L-value */
#define BCD_ADD_COMPOUND(type_h, type, rh, rl, ah, al, bh, bl) do { \
uint_fast8_t c = 0; \
type t1 = al, t2 = bl; \
BCD_ADD(type, rl, al, bl); \
c = rl >> (sizeof(type)*CHAR_BIT-4); \
BCD_ADD(type_h, rh, ah, bh); \
if (c >= 10 || (rl < t1 && rl < t2)) { \
rl = (rl & ((type)-1 >> 4)) | ((c - 10ULL) << (sizeof(type)*CHAR_BIT-4)); \
BCD_ADD(type_h, rh, rh, 1); \
} \
} while (0)
if (n & 1)
BCD_ADD_COMPOUND(uint_fast16_t, uint64_t, result_h, result, result_h, result, digit_h, digit);
BCD_ADD_COMPOUND(uint_fast16_t, uint64_t, digit_h, digit, digit_h, digit, digit_h, digit);
n >>= 1;
}
p = &buf[sizeof(buf) - 1];
*p = 0;
do {
r = result & 0x0f;
*--p = r + '0';
result = (result >> 4) | ((uint64_t)(result_h & 0x0f) << (sizeof(uint64_t)*CHAR_BIT-4));
result_h = result_h >> 4;
} while (result_h != 0 || result != 0);
if (num < 0) *--p = '-';
print_cstr(p);
}
#define print_dec(num) DECL_FUNC(_print_dec, num)
</code></pre>
<p>I hope, that somebody suggests me some improvements...</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T13:47:40.317",
"Id": "390021",
"Score": "8",
"body": "Hello and welcome to Code Review! Does this code work correctly? Your question is a little unclear in that regard. Also, it would be nice of you to expand your code into a minima... | [
{
"body": "<blockquote>\n <p>How can I print 64-bit decimal numbers in freestanding environment?<br>\n suggests me some improvements...</p>\n</blockquote>\n\n<p><strong>Create test cases</strong></p>\n\n<p>Post lacks a good way to assess its correctness. Since the goal is to <em>print</em> rather than form a... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T13:15:51.913",
"Id": "202403",
"Score": "2",
"Tags": [
"c",
"formatting",
"integer",
"embedded",
"gcc"
],
"Title": "Printing 64-bit decimal numbers in freestanding environment"
} | 202403 |
<p>This is not really a question but I'd like to obtain some opinions about this simple class. For an old project I had the necessity to load some php template files that includes some <code>foreach()</code> and <code>for()</code> loops and other variables loaded from a database. I was start thinking how to obtain this using a templating class and this is what I wrote to achieve the objective, I've reworked a templating class that works well with html and php files that doesn't need to load data from variables. I know that I can also use simply the <code>include</code>, <code>require</code> or <code>include_once</code> and <code>require_once</code> but writing a reusable class was the solution that seemed to me more reliable. Can this class to be considered useful? Is it possible to improve it by using magic methods like <code>__set()</code> and <code>__get()</code> to output the desired data to a loop? In the usage example I will not post the <code>$data</code> variable that is an array of data loaded from database, this choiche is because I don't want to write a long post.</p>
<pre><code><?php
class Template{
private $tpl;
private $fileName;
private $templatePath;
public function __construct($templatePath){
$this->templatePath = $templatePath;
}
public function loadTemplate(string $tpl){
$this->fileName = basename($tpl.'.php');
if(file_exists($this->templatePath.'/'.$this->fileName)){
return $this->templatePath.'/'.$this->fileName;
} else {
throw new Exception('Template not found.');
}
}
}
?>
</code></pre>
<p>Usage example: </p>
<pre><code><?php
require_once 'Template.class.php';
//$data = array(); this array comes from a db
//$results = array(); this is an handmade array
$template = new Template('path/to/template/file');
include($template->loadTemplate('demo'));
?>
</code></pre>
<p>Template file that is loaded</p>
<pre><code> <div class="wrapper">
<?php for($i = 0; $i < count($data); $i++): ?>
<span><small class="text-uppercase"><?php echo $data[$i]['h']; ?></small>
<small>&nbsp;-&nbsp;</small>
<small class="text-uppercase"><?php echo $data[$i]['a']; ?></small>
<p><?php echo $results[mt_rand(1,12)]; ?></p></span>
<?php endfor;?>
</div>
</code></pre>
| [] | [
{
"body": "<p>This is not a template class at all, but sort of a wrapper for <code>file_exists()</code> function. It does nothing of the templating business but just gets you a filename.</p>\n\n<p>To make it a template class, </p>\n\n<ul>\n<li>make it accept an array with all data used in the template</li>\n<li... | {
"AcceptedAnswerId": "202413",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T15:36:31.917",
"Id": "202410",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"template"
],
"Title": "PHP simple template loader"
} | 202410 |
<p><strong>Code Summary</strong></p>
<p>The following code is a data science script I've been working on that cross-validates a fixed effect model. I'm moving from R to Python and would appreciate feedback on the code below.</p>
<p>The code does the following:</p>
<ol>
<li><p>Split data into train and test using a custom function that groups/clusters the data</p></li>
<li><p>Estimate a linear fixed effect model with train and test data</p></li>
<li><p>Calculate RMSE and tstat to verify independence of residuals</p></li>
<li><p>Prints RMSE, SE, and tstat from cross-validation exercise.</p></li>
</ol>
<p>Note: the code downloads a remote data set, so the code can be run on its own.</p>
<p><strong>Code</strong></p>
<pre><code>from urllib import request
from scipy import stats
import pandas as pd
import numpy as np
import statsmodels.api as sm
print("Defining functions......")
def main():
"""
Estimate baseline and degree day regression.
Returns:
data.frame with RMSE, SE, and tstats
"""
# Download remote from github
print("Downloading custom data set from: ")
print("https://github.com/johnwoodill/corn_yield_pred/raw/master/data/full_data.pickle")
file_url = "https://github.com/johnwoodill/corn_yield_pred/raw/master/data/full_data.pickle"
request.urlretrieve(file_url, "full_data.pickle")
cropdat = pd.read_pickle("full_data.pickle")
# Baseline WLS Regression Cross-Validation with FE and trends
print("Estimating Baseline Regression")
basedat = cropdat[['ln_corn_yield', 'trend', 'trend_sq', 'corn_acres']]
fe_group = pd.get_dummies(cropdat.fips)
regdat = pd.concat([basedat, fe_group], axis=1)
base_rmse, base_se, base_tstat = felm_cv(regdat, cropdat['trend'])
# Degree Day Regression Cross-Validation
print("Estimating Degree Day Regression")
dddat = cropdat[['ln_corn_yield', 'dday0_10C', 'dday10_30C', 'dday30C',
'prec', 'prec_sq', 'trend', 'trend_sq', 'corn_acres']]
fe_group = pd.get_dummies(cropdat.fips)
regdat = pd.concat([dddat, fe_group], axis=1)
ddreg_rmse, ddreg_se, ddreg_tstat = felm_cv(regdat, cropdat['trend'])
# Get results as data.frame
fdat = {'Regression': ['Baseline', 'Degree Day',],
'RMSE': [base_rmse, ddreg_rmse],
'se': [base_se, ddreg_se],
't-stat': [base_tstat, ddreg_tstat]}
fdat = pd.DataFrame(fdat, columns=['Regression', 'RMSE', 'se', 't-stat'])
# Calculate percentage change
fdat['change'] = (fdat['RMSE'] - fdat['RMSE'].iloc[0])/fdat['RMSE'].iloc[0]
return fdat
def felm_rmse(y_train, x_train, weights, y_test, x_test):
"""
Estimate WLS from y_train, x_train, predict using x_test, calculate RMSE,
and test whether residuals are independent.
Arguments:
y_train: Dep variable - Full or training data
x_train: Covariates - Full or training data
weights: Weights for WLS
y_test: Dep variable - test data
x_test: Covariates - test data
Returns:
Returns tuple with RMSE and tstat from ttest
"""
# Fit model and get predicted values of test data
mod = sm.WLS(y_train, x_train, weights=weights).fit()
pred = mod.predict(x_test)
#Get residuals from test data
res = (y_test[:] - pred.values)
# Calculate ttest to check residuals from test and train are independent
t_stat = stats.ttest_ind(mod.resid, res, equal_var=False)[0]
# Return RMSE and t-stat from ttest
return (np.sqrt(np.mean(res**2)), t_stat)
def gc_kfold_cv(data, group, begin, end):
"""
Custom group/cluster data split for cross-validation of panel data.
(Ensure groups are clustered and train and test residuals are independent)
Arguments:
data: data to filter with 'trend'
group: group to cluster
begin: start of cluster
end: end of cluster
Return:
Return test and train data for Group-by-Cluster Cross-validation method
"""
# Get group data
data = data.assign(group=group.values)
# Filter test and train based on begin and end
test = data[data['group'].isin(range(begin, end))]
train = data[~data['group'].isin(range(begin, end))]
# Return train and test
dfs = {}
tsets = [train, test]
# Combine train and test to return dfs
for i, val in enumerate([1, 2]):
dfs[val] = tsets[i]
return dfs
def felm_cv(regdata, group):
"""
Cross-validate WLS FE model
Arguments:
regdata: regression data
group: group fixed effect
Returns:
return mean RMSE, standard error, and mean tstat from ttest
"""
# Loop through 1-31 years with 5 groups in test set and 26 train set
#i = 1
#j = False
retrmse = []
rettstat = []
#for j, val in enumerate([1, 27]):
for j in range(1, 28):
# Get test and training data
tset = gc_kfold_cv(regdata, group, j, j + 4)
# Separate y_train, x_train, y_test, x_test, and weights
y_train = tset[1].ln_corn_yield
x_train = tset[1].drop(['ln_corn_yield', 'corn_acres'], 1)
weights = tset[1].corn_acres
y_test = tset[2].ln_corn_yield
x_test = tset[2].drop(['ln_corn_yield', 'corn_acres'], 1)
# Get RMSE and tstat from train and test data
inrmse, t_stat = felm_rmse(y_train, x_train, weights, y_test, x_test)
# Append RMSE and tstats to return
retrmse.append(inrmse)
rettstat.append(t_stat)
# If end of loop return mean RMSE, s.e., and tstat
if j == 27:
return (np.mean(retrmse), np.std(retrmse), np.mean(t_stat))
if __name__ == "__main__":
RDAT = main()
print(RDAT)
# print results
print("---Results--------------------------------------------")
print("Baseline: ", round(RDAT.iloc[0, 1], 2), "(RMSE)",
round(RDAT.iloc[0, 2], 2), "(se)",
round(RDAT.iloc[0, 1], 3), "(t-stat)")
print("Degree Day: ", round(RDAT.iloc[1, 1], 2), "(RMSE)",
round(RDAT.iloc[0, 2], 2), "(se)",
round(RDAT.iloc[1, 3], 2), "(t-stat)")
print("------------------------------------------------------")
print("% Change from Baseline: ", round(RDAT.iloc[1, 4], 4)*100, "%")
print("------------------------------------------------------")
</code></pre>
| [] | [
{
"body": "<p>In general looks great and clean the code, I saw just a couple of things that looked strange, marked with ##!##:</p>\n\n<pre><code>def gc_kfold_cv(data, group, begin, end):\n \"\"\"\n Custom group/cluster data split for cross-validation of panel data.\n (Ensure groups are clustered and tr... | {
"AcceptedAnswerId": "202743",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T15:48:41.537",
"Id": "202412",
"Score": "5",
"Tags": [
"python",
"statistics"
],
"Title": "Cross-validating Fixed-effect Model"
} | 202412 |
<p>Sometimes in advanced OOP scenarios, a class needs to hold instances of another class which needs to hold a reference to the "parent". For example when you have a dynamic <code>UserForm</code> control that needs to "call back" to the parent form that created it, or when you have a <code>ViewAdapter</code> that talks to some UI, which in turn needs to "call back" to the adapter.</p>
<p>Such relationships create <em>circular references</em>, and if nothing is done to solve this, the objects don't get cleaned up and you're looking at what's essentially a memory leak.</p>
<p>With the help of <a href="https://codereview.stackexchange.com/users/36565/comintern">Comintern</a> I've written a class that solves this problem, and called it <code>WeakReference</code> - in order to make the API as simple to use as possible, I wrapped it with an <code>IWeakReference</code> interface:</p>
<pre><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "IWeakReference"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Option Explicit
Public Property Get Object() As Object
End Property
</code></pre>
<p>Here's the <code>WeakReference</code> class:</p>
<pre><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "WeakReference"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Implements IWeakReference
#If Win64 Then
Private Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As LongPtr)
#Else
Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)
#End If
Private Type TReference
Address As Long
End Type
Private this As TReference
Public Function Create(ByVal instance As Object) As IWeakReference
With New WeakReference
.Address = ObjPtr(instance)
Set Create = .Self
End With
End Function
Public Property Get Self() As IWeakReference
Set Self = Me
End Property
Public Property Get Address() As Long
Address = this.Address
End Property
Public Property Let Address(ByVal value As Long)
this.Address = value
End Property
Private Property Get IWeakReference_Object() As Object
' Bruce McKinney's code for getting an Object from the object pointer:
Dim objT As Object
CopyMemory objT, this.Address, 4
Set IWeakReference_Object = objT
CopyMemory objT, 0&, 4
End Property
</code></pre>
<p>Can this class be improved? Is the interface & factory method overkill?</p>
<hr>
<p>Here's a simple example usage scenario:</p>
<p>Class: <code>TheParent</code></p>
<pre><code>Option Explicit
Private child As TheChild
Private Sub Class_Initialize()
Set child = New TheChild
Set child.Parent = Me
End Sub
Private Sub Class_Terminate()
Set child = Nothing
End Sub
</code></pre>
<p>And the <code>TheChild</code> class:</p>
<pre><code>Option Explicit
Private ref As IWeakReference
Public Property Get Parent() As TheParent
Set Parent = ref.Object
End Property
Public Property Set Parent(ByVal value As TheParent)
Set ref = WeakReference.Create(value)
End Property
Private Sub Class_Terminate()
Stop ' expected break here when TheParent is terminated
Set ref = Nothing
End Sub
</code></pre>
<p>And a little procedure to test everything:</p>
<pre><code>Public Sub Test()
Dim p As TheParent
Set p = New TheParent
Debug.Print ObjPtr(p)
Set p = Nothing
End Sub
</code></pre>
<p>As expected, the <code>Stop</code> statement is hit in <code>TheChild</code>, and if you put a breakpoint in <code>TheParent</code>'s <code>Class_Terminate</code> handler, it's also hit - whereas if you replace the <code>IWeakReference</code> with <code>TheParent</code> in <code>TheChild</code>, none of the two <code>Class_Terminate</code> handlers run.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T16:19:00.780",
"Id": "390054",
"Score": "0",
"body": "VBA doesn't have proper garbage collection?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T16:19:38.033",
"Id": "390056",
"Score": "1",
... | [
{
"body": "<p>Thank you, thank you, thank you!! I have been tortured by this very problem and never could figure out why.</p>\n\n<p>I would simplify the factory by storing the Object pointer and making the <strong>IWeakReference_Object</strong> the default member of the class. </p>\n\n<p>Returning a self refe... | {
"AcceptedAnswerId": "239725",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T16:06:35.173",
"Id": "202414",
"Score": "12",
"Tags": [
"object-oriented",
"vba",
"weak-references"
],
"Title": "Solution for Parent/Child circular references: WeakReference class"
} | 202414 |
<p>I have a VBA code which copies same data from Multiple sheet and then paste it in "Main" Sheet. It then auto fills the blank cells for values from above and then it delete all the rows Where H:H is blank. However being novice in VBA, i feel my code has too many loops, which makes it run slower. Moreover if have the "Main" Sheet have a table formatted, the code does not delete any row <em>H</em> is blank. However it works if "Main" is blank and not formatted.</p>
<p>Another thing I found out that after the code is executed, the excel sheet becomes less responsive. I cannot select cells quickly, change between sheets. </p>
<p>Please advise if anything can be improved to make it run more efficiently.</p>
<pre><code>Private Sub CopyRangeFromMultiWorksheets1()
'Fill in the range that you want to copy
'Set CopyRng = sh.Range("A1:G1")
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim rng As Range
Dim Last As Long
Dim CopyRng1 As Range
Dim CopyRng2 As Range
Dim CopyRng3 As Range
Dim CopyRng4 As Range
Dim CopyRng5 As Range
Dim CopyRng6 As Range
Dim CopyRng7 As Range
Dim cell As Range
Dim Row As Range
Dim LastrowDelete As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Delete the sheet "RDBMergeSheet" if it exist
'Application.DisplayAlerts = False
On Error Resume Next
'ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
On Error GoTo 0
'Application.DisplayAlerts = True
'Add a worksheet with the name "RDBMergeSheet"
Set DestSh = Sheets("Main")
'Set DestSh = ActiveWorkbook.Worksheets.Add
' DestSh.Name = "RDBMergeSheet"
'loop through all worksheets and copy the data to the DestSh
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name And sh.Name <> "PAYPERIOD" And sh.Name <>
"TECHTeamList" Then
'Find the last row with data on the DestSh
Last = LastRow(DestSh)
'Fill in the range that you want to copy
Set CopyRng1 = sh.Range("B3")
Set CopyRng2 = sh.Range("C3")
Set CopyRng3 = sh.Range("D3")
Set CopyRng4 = sh.Range("G3")
Set CopyRng5 = sh.Range("C5")
Set CopyRng6 = sh.Range("A8:j25")
Set CopyRng7 = sh.Range("A28:j45")
'Test if there enough rows in the DestSh to copy all the data
If Last + CopyRng1.Rows.Count > DestSh.Rows.Count Then
MsgBox "There are not enough rows in the Destsh"
GoTo ExitTheSub
End If
'This example copies values/formats, if you only want to copy the
'values or want to copy everything look at the example below this
macro
CopyRng1.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
'Application.CutCopyMode = False
End With
CopyRng2.Copy
With DestSh.Cells(Last + 1, "B")
.PasteSpecial xlPasteValues
'Application.CutCopyMode = False
End With
CopyRng3.Copy
With DestSh.Cells(Last + 1, "C")
.PasteSpecial xlPasteValues
'Application.CutCopyMode = False
End With
CopyRng4.Copy
With DestSh.Cells(Last + 1, "D")
.PasteSpecial xlPasteValues
'Application.CutCopyMode = False
End With
CopyRng5.Copy
With DestSh.Cells(Last + 1, "E")
.PasteSpecial xlPasteValues
'Application.CutCopyMode = False
End With
CopyRng6.Copy
With DestSh.Cells(Last + 1, "F")
.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
'Application.CutCopyMode = False
End With
'Refresh the Lastrow used so that the values start from
'underneath copyrng6
Last = LastRow(DestSh)
CopyRng7.Copy
With DestSh.Cells(Last + 1, "F")
.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
'Application.CutCopyMode = False
End With
Application.CutCopyMode = False
End If
Next
ExitTheSub:
Application.Goto DestSh.Cells(1)
'AutoFit the column width in the DestSh sheet
DestSh.Columns.AutoFit
'Autofill the rang A2:E for values from above looking at the last row of F
With Range("A2:E" & Range("F" & Rows.Count).End(xlUp).Row)
.SpecialCells(xlBlanks).FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With
'Delete Entire rows where H is Blank
Application.ScreenUpdating = False
Columns("H:H").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Application.ScreenUpdating = True
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
</code></pre>
| [] | [
{
"body": "<p>try replacing your copies with this. Does this improve performance? </p>\n\n<pre><code> DestSh.Cells(Last + 1, \"A\").Resize(CopyRng1.Rows.Count, CopyRng1.Columns.Count).Value = CopyRng1.Value\n DestSh.Cells(Last + 1, \"B\").Resize(CopyRng2.Rows.Count, CopyRng2.Columns.Count).Value = CopyRng... | {
"AcceptedAnswerId": "202417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T16:13:18.050",
"Id": "202415",
"Score": "0",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Copying ranges from multiple Excel sheets into a main sheet"
} | 202415 |
<p>I have a function which plots <code>n</code> randomly generated non-colliding circles. The circle is a <code>Circle</code> object, part of <code>matplotlib.patches</code>. We will generate each random circle by its <code>center</code> and <code>r</code>, for example : <code>r = random.uniform(min_r, max_r)</code>.</p>
<p>To make circles with no collision, no two circles (with <code>c1, r1</code> and <code>c2, r2</code> as the center and radius) can have :
<code>distance(c1, c2) < r1 + r2</code>.</p>
<p>Here is the imports:</p>
<pre><code>import random
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import numpy
</code></pre>
<p>The implementation is done by the function below, how to make the script more compact and the implementation more efficient (faster)? Thanks.</p>
<p>The main function:</p>
<pre><code>def nocollide_random_unif_circles():
def add_circle(ax, center=(0,0), r=1, face_color=(0,0,1,1), edge_color=(0,0,1,1), line_width = None):
C = Circle(center, radius = r, facecolor = face_color, edgecolor = edge_color, linewidth = line_width)
ax.add_patch(C)
def dist2d(p, q):
distance = numpy.sqrt( (p[0]-q[0])**2 + (p[1]-q[1])**2 )
return distance
def collide(center, rad, centers, rads):
for c, r in zip(centers, rads):
if dist2d(c, center) < r + rad:
return True
return False
ncircle = 1000
min_r = 1
max_r = 200
color = 'blue'
sizex = [0, 1000]; sizey = [0, 1000]
fig, ax = plt.subplots(1, 1)
centers = [(random.uniform(sizex[0], sizex[1]), \
random.uniform(sizey[0], sizey[1]))]
rads = [random.uniform(min_r, max_r)]
add_circle(ax, center = centers[0], r = rads[0],\
face_color = color, edge_color = (0, 0, 0, 0))
for n in range(ncircle-1):
center = (random.uniform(sizex[0], sizex[1]), \
random.uniform(sizey[0], sizey[1]))
rad = random.uniform(min_r, max_r)
while collide(center, rad, centers, rads):
center = (random.uniform(sizex[0], sizex[1]), \
random.uniform(sizey[0], sizey[1]))
rad = random.uniform(min_r, max_r)
centers.append(center); rads.append(rad)
add_circle(ax, center = centers[-1], r = rads[-1],\
face_color = color, edge_color = (0, 0, 0, 0))
print(n)
ax.axis('equal')
ax.set_xlim(sizex); ax.set_ylim(sizey)
ax.tick_params(colors = (0,0,0,0))
ax.set_title('min radius = {}, max radius = {}, n = {} circles'.format(min_r, max_r, ncircle))
fig.tight_layout()
fig.show()
</code></pre>
<p>Example result with <code>n=4000</code> (took quite some time): </p>
<p><a href="https://i.stack.imgur.com/FOWkM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FOWkM.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<p>I would pull out the generation of the next circle and the generation of all circles into their own functions. This allows you to test those parts without having to plot the result, allowing some speed comparisons:</p>\n\n<pre><code>def place_circle(centers, rads, size_x, size_y, size_r):\n cen... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T16:28:18.697",
"Id": "202416",
"Score": "4",
"Tags": [
"python",
"performance",
"data-visualization",
"matplotlib"
],
"Title": "Plot random generated 'n' non-colliding circles using Matplotlib"
} | 202416 |
<p>I'm curious if there's any way I can substantially improve its speed (it runs through >200k rows). I think I'll most likely need this once, so please bear with me since it <em>probably</em> looks terrible.</p>
<p>Thanks for reading!</p>
<p>Code I would like reviewed:</p>
<pre><code>Option Explicit
Public Sub RemoveDuplicates()
Dim r As Range
Dim rBefore As Range
Dim wsSource As Worksheet
Dim ws As Worksheet
Dim c As Range
Dim c_ As Range
Dim v As Variant
Dim v_ As Variant
Dim dupCount As Long
Dim xlApp As Application
Dim i As Long
Dim size As Long
Set xlApp = Excel.Application
With xlApp
.ScreenUpdating = False
.DisplayStatusBar = True
.StatusBar = "Running Script..."
End With
Set wsSource = xlApp.ThisWorkbook.Worksheets("source")
Set rBefore = wsSource.Range(wsSource.Cells(2, 1), wsSource.Cells(wsSource.UsedRange.Rows.Count, 1))
Set ws = xlApp.ThisWorkbook.Worksheets("testSheet")
Set r = ws.Range(ws.Cells(2, 1), ws.Cells(ws.UsedRange.Rows.Count, 1))
size = r.Count
i = 1
For Each v In r
Set c = v
DoEvents
dupCount = 0
For Each v_ In r
Set c_ = v_
DoEvents
If CStr(c.Value) = CStr(c_.Value) Then
dupCount = dupCount + 1
If dupCount > 1 Then
c_.Rows(c_.Row).EntireRow.Delete
End If
End If
Next
xlApp.StatusBar = Format(i & " out of " & size) & " Rows Complete"
i = i + 1
Next
With xlApp
.ScreenUpdating = True
.DisplayStatusBar = False
.DisplayAlerts = False
.ThisWorkbook.Save
.DisplayAlerts = True
.ThisWorkbook.Close
End With
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T17:48:33.067",
"Id": "390076",
"Score": "2",
"body": "Any reason why [Range.RemoveDuplicates](https://docs.microsoft.com/en-us/office/vba/api/Excel.Range.RemoveDuplicates) can't be used here?"
},
{
"ContentLicense": "CC BY-S... | [
{
"body": "<p>Seems <a href=\"https://docs.microsoft.com/en-us/office/vba/api/Excel.Range.RemoveDuplicates\" rel=\"nofollow noreferrer\"><code>Range.RemoveDuplicates</code></a> could turn it all into a much more efficient one-liner.</p>\n\n<p>Stylistically though, the code could use some help anyway.</p>\n\n<p>... | {
"AcceptedAnswerId": "202438",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T17:22:47.623",
"Id": "202421",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "VBA Script to Remove Duplicates"
} | 202421 |
<p>I have written a Python program to loop through a list of X files, open each one, read line by line, and write (append) to an output file. Being that these files are several GB each, it is taking very long.</p>
<p>I am looking for suggestions to improve the performance of this program. I have no formal CS training so it's likely I am missing the "obvious solution" to this problem; I have done some research but again, my limited knowledge (and other higher priority tasks) limits my ability to implement such.</p>
<pre><code>for name in PR_files:
with open(PR_path + name, 'r') as f:
line = f.readline()
while line:
with open(PR_out_path, 'a') as g:
g.write(line + '\n')
line = f.readline()
f.close()
</code></pre>
<p>The program will work but will have a blank line between each line in the output text file; this is because the first line of the next file began on the last line of the previous file (my solution to this problem was to add <code>'\n'</code> to each line being written to the output file. For that reason I wrote another block to remove all blank lines in the output file (yes I know, very inefficient).</p>
<pre><code># this removes all blank lines from out put file
with open(PR_out_path) as this, open(PR_out_path_fix, 'w') as that:
for line in this:
if not line.strip():
continue
that.write(line)
</code></pre>
<p>PLEASE NOTE: I attempted to do this, as oppose to reading line by line but I received a MemoryError.</p>
<pre><code>with open(PR_out_path, 'a') as g:
for name in PR_files:
with open(PR_path + name, 'r') as f:
g.write(f.read())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T17:40:54.343",
"Id": "390073",
"Score": "1",
"body": "Welcome to Code Review! 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 t... | [
{
"body": "<p>Your original code:</p>\n\n<pre><code>with open(PR_out_path, 'a') as g:\n for name in PR_files:\n with open(PR_path + name, 'r') as f:\n g.write(f.read())\n</code></pre>\n\n<p>works but, as you found, has problems if the entire file can't be read into memory. The solution to ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T17:24:27.070",
"Id": "202423",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"io"
],
"Title": "Text processing program"
} | 202423 |
<p>Learned alot in this first week, following PCC, but biggest leaps came from the community and others giving their time to help, thank you!</p>
<p>All input appreciated!</p>
<p><strong>Objective</strong><br/>Goals were to fill a class with user inputs from multiple users and then be able to call methods to each user input created class. (... did I say that right O.o)</p>
<p><strong>Code</strong></p>
<pre><code>class User():
def __init__(a, first_name, last_name, city, age):
a.first_name = first_name.title()
a.last_name = last_name.title()
a.city = city.title()
a.age = age
def describe_user(a):
print("-----")
print("First Name" + " : " + a.first_name)
print("Last Name" + " : " + a.last_name)
print("City" + " : " + a.city)
print("Age" + " : " + a.age)
def ask_user(message=''):
user_input = ''
while not user_input:
user_input = input(message)
return user_input
def form_complete(values, placement, length):
placement = []
while len(placement) < length:
first_name = ask_user("Enter First Name: ")
last_name = ask_user("Enter Last Name: ")
city = ask_user("Enter City: ")
age = ask_user("Enter Age: ")
values = User(first_name, last_name, city, age)
placement.append(values)
return placement
if __name__ == '__main__':
users = form_complete('user', 'users', 3)
for a in range(len(users)):
users[a].describe_user()
</code></pre>
<p><strong>Output</strong></p>
<pre><code>xenial)vash@localhost:~/pcc/9$ python3 3.py
Enter First Name: vash
Enter Last Name: the stampede
Enter City: gunsmoke
Enter Age: 131
Enter First Name: spike
Enter Last Name: spiegel
Enter City: mars
Enter Age: 27
Enter First Name: holden
Enter Last Name: caulfield
Enter City: new york city
Enter Age: 16
-----
First Name : Vash
Last Name : The Stampede
City : Gunsmoke
Age : 131
Greetings Vash!
-----
First Name : Spike
Last Name : Spiegel
City : Mars
Age : 27
Greetings Spike!
-----
First Name : Holden
Last Name : Caulfield
City : New York City
Age : 16
Greetings Holden!
(xenial)vash@localhost:~/pcc/9$
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T19:41:58.807",
"Id": "390093",
"Score": "0",
"body": "@peilonrayz learned about classes today, tried applying somethings we discussed, I feel I was able to capture some things you taught me, thank you!"
}
] | [
{
"body": "<p>Python has something called magic methods (sometimes also called dunder methods, but the other name is way cooler).</p>\n\n<p>These methods have special names and enable custom classes to use built-in functionality. If, for example you write a custom numeric class, you would want to be able to do ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T19:37:59.987",
"Id": "202427",
"Score": "1",
"Tags": [
"python",
"beginner",
"object-oriented",
"python-3.x"
],
"Title": "Buidling classes with user input and calling methods"
} | 202427 |
<pre><code>function ExecuteWindowsTaskScheduler {
param(
[Parameter(Mandatory = $true)]
[String]$TaskName, #e.g. "Open Notepad task"
[Parameter(Mandatory = $true)]
[String]$TimeToExecute, #e.g. "3:45pm/am"
[Parameter(Mandatory = $true)]
[ValidateSet('Once','Daily','Weekly, Monthly')]
[string]$FrequencyToExecute,
[Parameter(Mandatory = $true)]
[String]$DomainAndUser, #e.g. "yourdomain\yourusername"
[Parameter(Mandatory = $true)]
[String]$ProgramWithPath, #e.g. "C:\PowerShell\yourFile.ps1"
[Parameter(Mandatory = $false)]
[bool]${DebugMode}
)
$TriggerParams = @{
At = $TimeToExecute
}
# Add the appropriate frequency value to the splatting table
if ($FrequencyToExecute -eq 'Monthly') {
$TriggerParams.Add('Weekly',$true)
}
else {
$TriggerParams.Add($FrequencyToExecute,$true)
}
# Specify the trigger settings
if ($FrequencyToExecute -eq "Weekly") {
$Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 1 -DaysOfWeek Monday
}
elseIf ($FrequencyToExecute -eq "Monthly") {
$Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 4 -DaysOfWeek Monday
}
else {
$Trigger = New-ScheduledTaskTrigger @TriggerParams
}
# Specify what script to run and with its parameters
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $ProgramWithPath
$TaskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $TaskName }
if($TaskExists) {
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}
</code></pre>
<p>I'm definitely not happy with this part of the code:</p>
<pre><code># Add the appropriate frequency value to the splatting table
if ($FrequencyToExecute -eq 'Monthly') {
$TriggerParams.Add('Weekly',$true)
}
else {
$TriggerParams.Add($FrequencyToExecute,$true)
}
# Specify the trigger settings
if ($FrequencyToExecute -eq "Weekly") {
$Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 1 -DaysOfWeek Monday
}
elseIf ($FrequencyToExecute -eq "Monthly") {
$Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 4 -DaysOfWeek Monday
}
else {
$Trigger = New-ScheduledTaskTrigger @TriggerParams
}
</code></pre>
<p>Is there a way to improve this part? I mean, I had to create a small hack because there is no Monthly parameter for <code>New-ScheduledTaskTrigger</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-06T19:24:27.453",
"Id": "391748",
"Score": "0",
"body": "You could probably change `[bool]$DebugMode` to `[switch]$DebugMode`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-07T01:15:32.077",
"Id": "391... | [
{
"body": "<p>Your instincts are good to dislike that bit of code. </p>\n\n<p>Whenever you can, you should put code in data structures rather than in control statements. It makes the code clearer and easier to maintain.</p>\n\n<p>So for instance you could put your settings in a hash table like this:</p>\n\n<pre... | {
"AcceptedAnswerId": "202628",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T19:55:32.930",
"Id": "202429",
"Score": "1",
"Tags": [
"powershell",
"scheduled-tasks"
],
"Title": "PowerShell - Execute Windows Task Scheduler"
} | 202429 |
<p>We assume we have unlimited number of coins and bills. My code works fine but the method <code>optimalChange()</code> has a Cyclomatic Complexity of 8.</p>
<pre><code>import java.util.*;
import java.math.*;
class Change {
long coin2 = 0;
long bill5 = 0;
long bill10 = 0;
}
class Solution {
static Change optimalChange(long s) {
long change = s;
Change c = new Change();
if (change >=10) {
if (change % 2 != 0 && change % 5 !=0) {
return dealWithChangeLike31Euros(change);
}
else {
c.bill10 = (long) change / 10;
change = change % c.bill10;
}
}
if (change <10 && change >=5) {
if (change % 2 == 0) {
c.bill5 = 0;
c.coin2 = change/2;
}
else {
change = change - 5;
c.bill5 = 1;
}
}
else if (change %2 ==0) {
c.bill5 = 0;
c.coin2 = change/2;
} else {
return null;
}
return c;
}
static Change dealWithChangeLike31Euros(long s) {
Change c = new Change();
c.bill10 = ((long) s / 10) - 1;
long change = (long) s % (c.bill10 * 10);
if (change > 5) {
change = change - 5;
c.bill5 = 1;
}
if (change % 2 == 0) {
c.coin2 = change / 2;
}
else {
return null;
}
return c;
}
}
</code></pre>
<p>Can the implementation of the <code>dealWithChangeLike31Euros()</code> method be merged into the other method?</p>
| [] | [
{
"body": "<p>The only way of making an odd total is with a five euro bill. There is no point ever having more than 1 five euro bill, as you could replace pairs with a ten euro bill. So, you should start off checking for the odd total.</p>\n\n<pre><code>if (change >= 5 && change % 2 == 1) {\n ... | {
"AcceptedAnswerId": "202431",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T20:18:01.450",
"Id": "202430",
"Score": "2",
"Tags": [
"java",
"change-making-problem"
],
"Title": "Optimal change with only with two euros coins and five and ten euros bills"
} | 202430 |
<p>I'm wondering how I could condense the following (redundant on many levels) code:</p>
<pre><code>import java.util.*;
public class Randomstems {
private static final STEM[] allStemsW1 = new STEM[25], allStemsW2 = new STEM[25], allStemsW3 = new STEM[25];
public static void main(String[] args) {
Scanner getAnswer = new Scanner(System.in);
Random getRandomSTEM = new Random();
allStemsW1[0] = new STEM("ante", "before", 1);
allStemsW1[1] = new STEM("anti", "against", 2);
allStemsW1[2] = new STEM("bi", "two", 3);
allStemsW1[3] = new STEM("circum", "around", 4);
allStemsW1[4] = new STEM("com", "together", 5);
allStemsW1[5] = new STEM("con", "together", 6);
allStemsW1[6] = new STEM("de", "down", 7);
allStemsW1[7] = new STEM("dis", "away", 8);
allStemsW1[8] = new STEM("equi", "equal", 9);
allStemsW1[9] = new STEM("extra", "beyond", 10);
allStemsW1[10] = new STEM("inter", "between", 11);
allStemsW1[11] = new STEM("intra", "within", 12);
allStemsW1[12] = new STEM("intro", "into", 13);
allStemsW1[13] = new STEM("mal", "bad", 14);
allStemsW1[14] = new STEM("mis", "bad", 15);
allStemsW1[15] = new STEM("non", "not", 16);
allStemsW1[16] = new STEM("post", "after", 17);
allStemsW1[17] = new STEM("pre", "before", 18);
allStemsW1[18] = new STEM("semi", "half", 19);
allStemsW1[19] = new STEM("sub", "under", 20);
allStemsW1[20] = new STEM("super", "over", 21);
allStemsW1[21] = new STEM("syn", "together", 22);
allStemsW1[22] = new STEM("sym", "together", 23);
allStemsW1[23] = new STEM("tri", "three", 24);
allStemsW1[24] = new STEM("un", "not", 25);
// week 2
allStemsW2[0] = new STEM("ad", "to", 1);
allStemsW2[1] = new STEM("antropo", "man", 2);
allStemsW2[2] = new STEM("archy", "government", 3);
allStemsW2[3] = new STEM("ard", "always", 4);
allStemsW2[4] = new STEM("aqua", "water", 5);
allStemsW2[5] = new STEM("auto", "self", 6);
allStemsW2[6] = new STEM("audi", "hear", 7);
allStemsW2[7] = new STEM("bell", "war", 8);
allStemsW2[8] = new STEM("biblio", "book", 9);
allStemsW2[9] = new STEM("bio", "life", 10);
allStemsW2[10] = new STEM("cap", "take", 11);
allStemsW2[11] = new STEM("cede", "go", 12);
allStemsW2[12] = new STEM("cent", "one hundred", 13);
allStemsW2[13] = new STEM("centri", "center", 14);
allStemsW2[14] = new STEM("cide", "kill", 15);
allStemsW2[15] = new STEM("cise", "cut", 16);
allStemsW2[16] = new STEM("cred", "believe", 17);
allStemsW2[17] = new STEM("dict", "say", 18);
allStemsW2[18] = new STEM("ician", "specialist", 19);
allStemsW2[19] = new STEM("itis", "inflammation", 20);
allStemsW2[20] = new STEM("logy", "science", 21);
allStemsW2[21] = new STEM("miss", "send", 22);
allStemsW2[22] = new STEM("neo", "new", 23);
allStemsW2[23] = new STEM("port", "carry", 24);
allStemsW2[24] = new STEM("scrib", "writer", 25);
// week 3
allStemsW1[0] = new STEM("duct", "lead", 1);
allStemsW1[1] = new STEM("ex", "out", 2);
allStemsW1[2] = new STEM("fer", "carry", 3);
allStemsW1[3] = new STEM("hema", "blood", 4);
allStemsW1[4] = new STEM("homo", "same", 5);
allStemsW1[5] = new STEM("hydro", "water", 6);
allStemsW1[6] = new STEM("hypo", "under", 7);
allStemsW1[7] = new STEM("micro", "small", 8);
allStemsW1[8] = new STEM("mono", "one", 9);
allStemsW1[9] = new STEM("neuro", "nerve", 10);
allStemsW1[10] = new STEM("omni", "all", 11);
allStemsW1[11] = new STEM("pan", "all", 12);
allStemsW1[12] = new STEM("pend", "hang", 13);
allStemsW1[13] = new STEM("penta", "five", 14);
allStemsW1[14] = new STEM("phon", "sound", 15);
allStemsW1[15] = new STEM("photo", "light", 16);
allStemsW1[16] = new STEM("poly", "many", 17);
allStemsW1[17] = new STEM("proto", "first", 18);
allStemsW1[18] = new STEM("pseudo", "false", 19);
allStemsW1[19] = new STEM("re", "again", 20);
allStemsW1[20] = new STEM("spec", "look", 21);
allStemsW1[21] = new STEM("tele", "far", 22);
allStemsW1[22] = new STEM("tomy", "cut", 23);
allStemsW1[23] = new STEM("vid", "look", 24);
allStemsW1[24] = new STEM("viv", "life", 25);
// starting the 'test'
// total stuff
int totalCorrect = 0;
// 1st group of 25
int allCorrect1 = 0;
int didBefore1 = 0;
boolean stop1 = false;
while(!stop1) {
int amCorrect1 = 0;
didBefore1++;
if(didBefore1>1) {
for(int i=0; i<25; i++) { // reset
allStemsW1[i].reset();
}
}
int[] incorrectAnswers = new int[25];
for(int i=0; i<25; i++) {
int randoStem = getRandomSTEM.nextInt(allStemsW1.length);
if(i!=0) {
boolean needTo = true;
while(needTo) {
if(allStemsW1[randoStem].hasDoneThis) {
randoStem = getRandomSTEM.nextInt(allStemsW1.length);
}
for(int n=0; n<25; n++) {
if(allStemsW1[randoStem].hasDoneThis) {
randoStem = getRandomSTEM.nextInt(allStemsW1.length);
n = 25;
} else {
needTo = false;
}
}
}
}
STEM randomStem = allStemsW1[randoStem];
randomStem.didThis();
System.out.println("Please type the meaning of the STEM \"" + randomStem.getName() + "\" below:");
String answer = getAnswer.nextLine();
randomStem.answerQ(answer, (25-1-i));
if(randomStem.isCorrect) {
randomStem.isCorrect = false;
amCorrect1++;
} else {
randomStem.isCorrect = false;
incorrectAnswers[i] = i+1;
}
}
int points = amCorrect1*4;
System.out.println("-----------------------");
System.out.println("Results:");
System.out.println("You got " + amCorrect1 + "/25 right! You got " + points + " points!");
allCorrect1 += amCorrect1;
if(points != 100) {
for(int i=0; i<incorrectAnswers.length; i++) {
if(incorrectAnswers[i] != 0) { // ACTUALLY got WRONG
System.out.print("you got " + allStemsW1[i].getName() + " wrong, ");
} else if(i==(incorrectAnswers.length-1)) {
System.out.println(""); // end the ^^^^ print
}
}
}
if(points == 100 && didBefore1>1) {
stop1 = true;
} else if(points != 100 && didBefore1>1) {
System.out.println("Do you wish to try to get 100 again? (true/false)");
boolean yN = getAnswer.nextBoolean();
if(!yN && didBefore1!=0) {
stop1 = true;
}
}
}
System.out.println("-------------------------------------");
System.out.println("Results:");
System.out.println("You got " + allCorrect1 + "/" + (didBefore1*25) + " correct!");
totalCorrect+=allCorrect1;
// 2nd group of 25
int allCorrect2 = 0;
int didBefore2 = 0;
boolean stop2 = false;
while(!stop2) {
int amCorrect2 = 0;
didBefore2++;
if(didBefore2>1) {
for(int i=0; i<25; i++) { // reset
allStemsW2[i].reset();
}
}
int[] incorrectAnswers = new int[25];
for(int i=0; i<25; i++) {
int randoStem = getRandomSTEM.nextInt(allStemsW2.length);
if(i!=0) {
boolean needTo = true;
while(needTo) {
if(allStemsW2[randoStem].hasDoneThis) {
randoStem = getRandomSTEM.nextInt(allStemsW2.length);
}
for(int n=0; n<25; n++) {
if(allStemsW2[randoStem].hasDoneThis) {
randoStem = getRandomSTEM.nextInt(allStemsW2.length);
n = 25;
} else {
needTo = false;
}
}
}
}
STEM randomStem = allStemsW2[randoStem];
randomStem.didThis();
System.out.println("Please type the meaning of the STEM \"" + randomStem.getName() + "\" below:");
String answer = getAnswer.nextLine();
randomStem.answerQ(answer, (25-1-i));
if(randomStem.isCorrect) {
randomStem.isCorrect = false;
amCorrect2++;
} else {
randomStem.isCorrect = false;
incorrectAnswers[i] = i+1;
}
}
int points = amCorrect2*2;
System.out.println("-----------------------");
System.out.println("Results:");
System.out.println("You got " + amCorrect2 + "/25 right! You got " + points + " points!");
allCorrect2 += amCorrect2;
if(points != 100) {
for(int i=0; i<incorrectAnswers.length; i++) {
if(incorrectAnswers[i] != 0) { // ACTUALLY got WRONG
System.out.print("you got " + allStemsW2[i].getName() + " wrong, ");
} else if(i==(incorrectAnswers.length-1)) {
System.out.println(""); // end the ^^^^ print
}
}
}
if(points == 100 && didBefore2>1) {
stop2 = true;
} else if(points != 100 && didBefore2>1) {
System.out.println("Do you wish to try to get 100 again? (true/false)");
boolean yN = getAnswer.nextBoolean();
if(!yN && didBefore2!=0) {
stop2 = true;
}
}
}
System.out.println("-------------------------------------");
System.out.println("Results:");
System.out.println("You got " + allCorrect2 + "/" + (didBefore2*25) + " correct!");
totalCorrect+=allCorrect2;
// 3rd group of 25
int allCorrect3 = 0;
int didBefore3 = 0;
boolean stop3 = false;
while(!stop3) {
int amCorrect3 = 0;
didBefore3++;
if(didBefore3>1) {
for(int i=0; i<25; i++) { // reset
allStemsW3[i].reset();
}
}
int[] incorrectAnswers = new int[25];
for(int i=0; i<25; i++) {
int randoStem = getRandomSTEM.nextInt(allStemsW3.length);
if(i!=0) {
boolean needTo = true;
while(needTo) {
if(allStemsW3[randoStem].hasDoneThis) {
randoStem = getRandomSTEM.nextInt(allStemsW3.length);
}
for(int n=0; n<25; n++) {
if(allStemsW3[randoStem].hasDoneThis) {
randoStem = getRandomSTEM.nextInt(allStemsW3.length);
n = 25;
} else {
needTo = false;
}
}
}
}
STEM randomStem = allStemsW3[randoStem];
randomStem.didThis();
System.out.println("Please type the meaning of the STEM \"" + randomStem.getName() + "\" below:");
String answer = getAnswer.nextLine();
randomStem.answerQ(answer, (25-1-i));
if(randomStem.isCorrect) {
randomStem.isCorrect = false;
amCorrect3++;
} else {
randomStem.isCorrect = false;
incorrectAnswers[i] = i+1;
}
}
int points = amCorrect3*2;
System.out.println("-----------------------");
System.out.println("Results:");
System.out.println("You got " + amCorrect3 + "/25 right! You got " + points + " points!");
allCorrect3 += amCorrect3;
if(points != 100) {
for(int i=0; i<incorrectAnswers.length; i++) {
if(incorrectAnswers[i] != 0) { // ACTUALLY got WRONG
System.out.print("you got " + allStemsW3[i].getName() + " wrong, ");
} else if(i==(incorrectAnswers.length-1)) {
System.out.println(""); // end the ^^^^ print
}
}
}
if(points == 100 && didBefore3>1) {
stop3 = true;
} else if(points != 100 && didBefore3>1) {
System.out.println("Do you wish to try to get 100 again? (true/false)");
boolean yN = getAnswer.nextBoolean();
if(!yN && didBefore3!=0) {
stop3 = true;
}
}
}
System.out.println("-------------------------------------");
System.out.println("Results:");
System.out.println("You got " + allCorrect3 + "/" + (didBefore3*25) + " correct!");
totalCorrect+=allCorrect3;
// total stuff
System.out.println("-------------------------------------");
System.out.println("Total results:");
System.out.println("You got " + totalCorrect + "/100" + " correct!");
getAnswer.close();
}
}
</code></pre>
<p>I know that it's a lot of code, but it's basically the same thing 3 times over. I originally tried a condenser way, but it threw many errors. That was also before I had 3 different STEMs lists. </p>
<p><strong>EDIT:</strong><br>
Here's what I get in the console (it works...shortened version):</p>
<pre><code>// each one is done at least 50 times
Please type the meaning of the STEM "(random STEM from week 1)" below:
Please type the meaning of the STEM "(random STEM from week 2)" below:
Please type the meaning of the STEM "(random STEM from week 3)" below:
</code></pre>
<p>If you get it correct, it says correct. It keeps track of how many you got correct and, at the end of each week and at the end of it all, it says what your total grade was.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T14:20:47.950",
"Id": "390264",
"Score": "0",
"body": "Can you include the STEM class? It would make it easier to see what it is needed for."
}
] | [
{
"body": "<ol>\n<li><p>Instead of having three different lists, have a list of lists, one per \nweek with the quiz questions. This would get rid of redundant code and\nmake it trivial to add a week.</p></li>\n<li><p>keep your data in some kind of file, then load it into a list. This will get rid of all of thos... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T20:54:28.660",
"Id": "202434",
"Score": "1",
"Tags": [
"java",
"quiz"
],
"Title": "Quiz for studying word stems"
} | 202434 |
<p>Is there a more efficient way to write the following PLSQL statement? It seems inefficient to me to have the SQL statement nested inside the where clause.</p>
<pre><code>SELECT REQ_ID
FROM REQUESTS R
WHERE P_REQ_ID IS NULL AND
EXISTS (
SELECT *
FROM REQUESTS
WHERE P_REQ_ID = R.REQ_ID
)
</code></pre>
| [] | [
{
"body": "<p>You can do an INNER JOIN but not sure if it will change your performance significantly: </p>\n\n<pre><code>SELECT R.REQ_ID\nFROM REQUESTS R\nINNER JOIN (SELECT distinct P_REQ_ID \n FROM REQUESTS) R2\nON R.P_REQ_ID IS NULL AND \n R2.P_REQ_ID = R.REQ_ID\n</code></pre>\n",
"comments... | {
"AcceptedAnswerId": "202477",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T21:16:47.567",
"Id": "202437",
"Score": "0",
"Tags": [
"sql",
"oracle",
"plsql"
],
"Title": "SQL Statement with a Select Statement Inside a Where Clause"
} | 202437 |
<blockquote>
<p><strong>Issue</strong>: Code base has lots of data structures which are accessed between threads with >= 1 writer. Application logic becomes obfuscated due to lots of mutex locks.</p>
<p><strong>Solution</strong>: Create a template class which provides synchronized access through member functions.</p>
</blockquote>
<p>This seems very hacky -- Is this a futile effort / antipattern?</p>
<pre><code>#ifndef SYNCHRONIZED_HPP_
#define SYNCHRONIZED_HPP_
#include <functional>
#include <mutex>
#include <shared_mutex>
#include <type_traits>
#include <utility>
#undef DISALLOW_EVIL_CONSTRUCTORS
#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T>
class synchronized;
template <typename T> auto
make_synchronized(T&& value) {
return synchronized<T>{ std::forward<T>(value) };
}
template <typename T>
class synchronized final {
public:
using value_t = std::remove_reference_t<T>;
template <typename... Args>
explicit synchronized(Args&&... args)
: value_(std::forward<Args>(args)...)
{}
value_t get() const {
read_lock l(mutex_);
return value_;
}
template <typename U> void
set(U&& new_value) {
write_lock l(mutex_);
value_ = std::forward<U>(new_value);
}
template <typename Accessor>
void use(Accessor&& access) const {
read_lock l(mutex_);
std::forward<Accessor>(access)(value_);
}
template <typename Mutator>
void alter(Mutator&& func) {
write_lock l(mutex_);
std::forward<Mutator>(func)(value_);
}
private:
value_t value_;
using mutex_t = std::shared_timed_mutex;
using read_lock = std::shared_lock<mutex_t>;
using write_lock = std::unique_lock<mutex_t>;
mutable mutex_t mutex_{};
DISALLOW_EVIL_CONSTRUCTORS(synchronized);
};
#endif // SYNCHRONIZED_HPP_
</code></pre>
<p><strong>With doxy comments (same code)</strong>:</p>
<pre><code>#ifndef SYNCHRONIZED_HPP_
#define SYNCHRONIZED_HPP_
#include <functional>
#include <mutex>
#include <shared_mutex>
#include <type_traits>
#include <utility>
#undef DISALLOW_EVIL_CONSTRUCTORS
#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T>
class synchronized;
/**
* @brief
* Make a synchronized<T> using template deduction.
*
* @sa synchronized
*/
template <typename T> auto
make_synchronized(T&& value) {
return synchronized<T>{ std::forward<T>(value) };
}
/**
* @brief
* Provides straightforward thread-synchronized access to template type.
*
* @note
* While access to the immediate type is synchronized, this class does not
* prevent non-synchronized access of pointer or reference members of the
* template type.
*
* @note
* For applicable types, prefer std::atomic<T>.
*/
template <typename T>
class synchronized final {
public:
using value_t = std::remove_reference_t<T>;
template <typename... Args>
explicit synchronized(Args&&... args)
: value_(std::forward<Args>(args)...)
{}
/**
* @brief
* Thread-sychronized get.
*/
value_t get() const {
read_lock l(mutex_);
return value_;
}
/**
* @brief
* Thread-sychronized set.
*/
template <typename U> void
set(U&& new_value) {
write_lock l(mutex_);
value_ = std::forward<U>(new_value);
}
/**
* @brief
* Use the underlying value where get() would be less-trivial or
* otherwise unsuitable.
*
* @note
* Prefer get(), especially if this access takes a long time, as to not
* starve a writer thread or other reader threads.
*/
template <typename Accessor>
void use(Accessor&& access) const {
read_lock l(mutex_);
std::forward<Accessor>(access)(value_);
}
/**
* @brief
* Alter (mutate) the underlying value where get() and set() would be
* less-trivial or otherwise unsuitable.
*
* @note
* Prefer the combination of get() then set(), especially if this access
* takes a long time, as to not starve other writer or reader threads.
*/
template <typename Mutator>
void alter(Mutator&& func) {
write_lock l(mutex_);
std::forward<Mutator>(func)(value_);
}
private:
value_t value_;
using mutex_t = std::shared_timed_mutex;
using read_lock = std::shared_lock<mutex_t>;
using write_lock = std::unique_lock<mutex_t>;
mutable mutex_t mutex_{};
DISALLOW_EVIL_CONSTRUCTORS(synchronized);
};
#endif // SYNCHRONIZED_HPP_
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T10:05:09.823",
"Id": "390233",
"Score": "0",
"body": "Welcome to Code Review! 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. Thi... | [
{
"body": "<p>Seems like a decent implementation. You should be aware that <em>nothing</em> in this area is foolproof. Two ways to \"break\" your code are:</p>\n\n<pre><code>auto si = make_synchronized(42);\n// ...\nint *one;\nsi.alter([&](int& val) {\n one = &val;\n});\n*one = 42; // use outsid... | {
"AcceptedAnswerId": "202444",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T22:16:11.847",
"Id": "202440",
"Score": "2",
"Tags": [
"c++",
"thread-safety",
"template"
],
"Title": "Synchronized template wrapper class"
} | 202440 |
<p>I am trying to learn some Common Lisp, except basically all of my computing background is the C family of languages. So, I'm starting small. I have made a Tic-Tac-Toe game, and I am looking for some constructive criticism.</p>
<p>In particular, is this idiomatic Lisp? Is it styled normally? What would an experienced lisper improve about this? </p>
<p>Some concerns I have about this code are:</p>
<ul>
<li>The win checking seems repetitive.
Can it be simplified?</li>
<li>The get-player-move is very long. Should it be broken up?</li>
</ul>
<p></p>
<pre><code>;;;; A simple tic-tac-toe game
(defvar p1 88) ; char code for 'X'
(defvar p2 79) ; char code for 'O'
(defvar tie 49) ; arbitrary constant to represent ties
(defun is-move-free (move board)
(let ((player (elt board move)))
(not (or (= player p1) (= player p2)))))
(defun is-same (a b c)
(and (= a b) (= b c)))
(defun win-on-rows (board)
(defun check-a-row (offset)
(or (is-same (elt board offset) (elt board (+ offset 1)) (elt board (+ offset 2)))))
(or (check-a-row 0) (check-a-row 3) (check-a-row 6)))
(defun win-on-columns (board)
(defun check-a-column (offset)
(or (is-same (elt board offset) (elt board (+ offset 3)) (elt board (+ offset 6)))))
(or (check-a-column 0) (check-a-column 1) (check-a-column 2)))
(defun win-on-diagonals (board)
(or (is-same (elt board 0) (elt board 4) (elt board 8)) (is-same (elt board 2) (elt board 4) (elt board 6))))
;;; This function gets the players move, plays it if possible
;;; then gets the next move. The game will play out in it's
;;; entirety through recursively calling this function.
(defun get-player-move (player board move-num)
(apply #'format t " ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C~%" (map 'list #'code-char board)) ; Print the board
(if (>= move-num 9) ; if all the moves have been played, and there is no winner
tie ; return the tie constant
(let ((move (- (parse-integer (read-line)) 1))) ; get the move from input, and convert it to list location
(if (is-move-free move board)
(let ((board (substitute player (elt board move) board))) ; apply the move, and get the new board
(if (or (win-on-columns board) (win-on-rows board) (win-on-diagonals board)) ; check if this was the winning move
(elt board move) ; return the winner
(get-player-move (if (= player p1) p2 p1) board (+ move-num 1)))) ; continue the game
(get-player-move player board move-num))))) ; move again, if the move was taken
(let ((result (get-player-move p1 '(49 50 51 52 53 54 55 56 57) 0)))
(if (= result tie)
(format t "It's a tie!")
(format t "The winner is ~C" (code-char result))))
</code></pre>
| [] | [
{
"body": "<p>Here are a few considerations.</p>\n\n<p><strong>DEFPARAMETER vs. DEFVAR</strong></p>\n\n<p>The first three definitions should be given with <code>defparameter</code> instead of <code>defvar</code>. The first operator is used for values that do not change, unless they are modified in the source fi... | {
"AcceptedAnswerId": "202457",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T03:15:18.173",
"Id": "202449",
"Score": "3",
"Tags": [
"beginner",
"tic-tac-toe",
"lisp",
"common-lisp"
],
"Title": "A simple Tic Tac Toe game"
} | 202449 |
<p>I have a basic method to export files, however I have several arrays to export and I need the files to have these names, I'm trying to make it by the enum list, however when I do it, the file isn't created and I'm wondering is there a way to combine the directory+name of array+.txt? Here's method that doesn't export nothing at all. Thank you for looking at the code.</p>
<pre><code>enum exportByName { Client, Appointment, Address,Location,Historic }
static string askPath()
{
var dir = "";
do
{
Console.Clear();
Console.Write("Insert path to export the txt file: ");
dir = Console.ReadLine();
} while (String.IsNullOrEmpty(dir));
var userPath = Path.Combine(dir,Enum.GetName(typeof(exportByName),0),".txt");
return userPath;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T13:53:24.323",
"Id": "390146",
"Score": "0",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask... | [
{
"body": "<p>I don't have much reputations to comment so trying to help for what I know and modified your code according to the need -</p>\n\n<p>There are two issues I observed -</p>\n\n<ol>\n<li>The below line in your code -</li>\n</ol>\n\n<blockquote>\n <p>var userPath = Path.Combine(dir,Enum.GetName(typeof... | {
"AcceptedAnswerId": "202465",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T08:53:22.440",
"Id": "202458",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Same method to export different txt files C#"
} | 202458 |
<p>I am trying to learn trie and this is my first implementation. I started off with the idea of being able to handle different data types for key and value; however, I found the data structure a bit complicated and switched to just <code>string</code> for keys and <code>int</code> for values. So, parts of my code are specific to some data types while other parts are generic. My code is based on this <a href="https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014" rel="nofollow noreferrer">link</a>. Here is my current code:</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <cstddef>
#include <stack>
// Class Node
template<typename T, std::size_t N>
class Node
{
T val;
std::vector<Node<T, N>*> paths{N, nullptr};
public:
//ctor
Node() : val{T{}}
{
}
// Set the value of node
void set_val(T value)
{
val = value;
}
// Return the value of node
T get_val() const
{
return val;
}
// Set a particular child node based on index
void set_path(Node<T, N>* new_node, std::size_t index)
{
this -> paths[index] = new_node;
}
// Return a particular child node based on index
Node* get_path(std::size_t index) const
{
return this -> paths[index];
}
};
// Class Trie
template<typename U, typename T, std::size_t N>
class Trie
{
Node<T, N>* root = new Node<T, N>{};
public:
Trie();
Trie(const std::list<U>, const T);
~Trie();
void delete_all(Node<T, N>*);
void insert(U, T);
bool search(U, T&) const;
void deletion(U);
};
// Ctor to initialize trie with a list
template<typename U, typename T, std::size_t N>
Trie<U, T, N>::Trie(const std::list<U> init_ls, const T val)
{
for(auto it = init_ls.cbegin(); it != init_ls.cend(); it++)
{
this -> insert(*it, val);
}
}
// Dtor for trie
template<typename U, typename T, std::size_t N>
Trie<U, T, N>::~Trie()
{
Node<T, N>* node = root;
this -> delete_all(node);
}
// Helper function for dtor
template<typename U, typename T, std::size_t N>
void Trie<U, T, N>::delete_all(Node<T, N>* node)
{
if(node == nullptr)
{
return;
}
for(std::size_t i = 0; i < N; i++)
{
delete_all(node -> get_path(i));
}
delete node;
}
// Insert key - value pair in trie
template<typename U, typename T, std::size_t N>
void Trie<U, T, N>::insert(U key, T value)
{
Node<T, N>* node = root;
for(std::size_t i = 0; i < key.size(); i++)
{
std::size_t index = int(key[i]) - 97;
if(node -> get_path(index) != nullptr)
{
node = node -> get_path(index);
}
else
{
Node<T, N>* new_node = new Node<T, N>{};
node -> set_path(new_node, index);
node = node -> get_path(index);
}
if(i == key.size() - 1)
{
node -> set_val(value);
}
}
}
// Search key - value pair in trie
template<typename U, typename T, std::size_t N>
bool Trie<U, T, N>::search(U key, T& ret_val) const
{
Node<T, N>* node = root;
for(std::size_t i = 0; i < key.size(); i++)
{
int index = int(key[i]) - 97;
if(node -> get_path(index) == nullptr)
{
ret_val = T{};
return false;
}
else
{
node = node -> get_path(index);
}
if(i == key.size() - 1)
{
if(node -> get_val() != T{})
{
ret_val = node -> get_val();
return true;
}
else
{
ret_val = T{};
return false;
}
}
}
return false;
}
// Delete key - value pair from trie
template<typename U, typename T, std::size_t N>
void Trie<U, T, N>::deletion(U key)
{
Node<T, N>* node = root;
std::stack<Node<T, N>*> node_stack;
for(std::size_t i = 0; i < key.size(); i++)
{
int index = int(key[i]) - 97;
if(node -> get_path(index) != nullptr)
{
node = node -> get_path(index);
node_stack.push(node);
}
else
{
std::cout << "Key does not exist\n";
return;
}
if(i == key.size() - 1)
{
if(node -> get_val() != T{})
{
node -> set_val(T{});
}
}
}
while(!node_stack.empty())
{
Node<T, N>* curr_node = node_stack.top();
node_stack.pop();
for(std::size_t i = 0; i < N; i++)
{
if(curr_node -> get_val() != T{} || curr_node -> get_path(i) != nullptr)
{
return;
}
}
delete curr_node;
}
}
// Main
int main()
{
Trie<std::string, int, 26> t1{{"apple", "ball", "cat", "banana", "beach", "ballet", "dog"}, 1};
int ret_val;
bool success = t1.search("ballet", ret_val);
std::cout << "Search result: " << success << "\t" << "Return Value: " << ret_val << "\n";
t1.insert("elephant", 1);
t1.insert("cats", 1);
success = t1.search("cats", ret_val);
std::cout << "Search result: " << success << "\t" << "Return Value: " << ret_val << "\n";
success = t1.search("cat", ret_val);
std::cout << "Search result: " << success << "\t" << "Return Value: " << ret_val << "\n";
t1.deletion("cat");
//t1.deletion("cats");
success = t1.search("cats", ret_val);
std::cout << "Search result: " << success << "\t" << "Return Value: " << ret_val << "\n";
success = t1.search("cat", ret_val);
std::cout << "Search result: " << success << "\t" << "Return Value: " << ret_val << "\n";
success = t1.search("bald", ret_val);
std::cout << "Search result: " << success << "\t" << "Return Value: " << ret_val << "\n";
return 0;
}
</code></pre>
<p>The things I would like to know:</p>
<p>1) Is the approach and operations included correct, especially for the deletion of key?</p>
<p>2) When I think about it, <code>template specialization</code> seem to be one way to make it handle multiple data types. Are there any better suggestions?</p>
<p>3) Is the memory management part good?</p>
<p>4) Is there a check list I should follow while coding data structures?</p>
<p>5) General review and suggestion please.</p>
<p><strong>Note:</strong> I would like to thank everyone who has helped me with my previous questions. I understand that I haven't been able to put into practice all the previous advice that I received. I am trying to get there in steps, through practice. Thank You!</p>
| [] | [
{
"body": "<h2>Node</h2>\n\n<ul>\n<li>Each node in a trie owns its child nodes, and nodes elsewhere in the trie don't ever point to nodes in a completely different branch. As such, a node can store its children by value in a container. There's no need to use pointers here which means we don't have to worry abou... | {
"AcceptedAnswerId": "202572",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T10:35:22.343",
"Id": "202464",
"Score": "2",
"Tags": [
"c++",
"memory-management",
"template",
"trie"
],
"Title": "C++ - Trie Implementation"
} | 202464 |
<p>I'm trying to learn Python, so I made this project. I think there are problems with the code, but I don't know how to improve it.</p>
<pre><code>import os
import random
clear = lambda: os.system('cls')
def game():
def printOutCorrectGuess():
print('Correct! There is/are ', lettersInWord, 'of this letter in this word.')
def printOutStars():
print('Currently revealed of the word: ', ''.join(stars))
def printOutVictory():
print('You won!')
print('The word was ', theWord)
print('Press enter to quit...')
def printOutWords():
print('You guessed these letters : ', words)
def printOutLifes():
print('You have ', lives, ' more lives.')
print("Let's start guessing!")
correctLetters = 0
lives = 10
words = []
stars = list('*' * len(theWord))
while True:
guess = str(input('Please give me a letter: '))
if len(guess) > 1 or len(guess) < 1:
clear()
print('I need 1 and letter, thanks.')
printOutStars()
elif guess in words:
clear()
print('You already wrote this letter.')
printOutStars()
elif guess in theWord:
theStart = 0
theEnd = 1
lettersInWord = 0
letterPosition = []
for i in range(len(theWord)):
tempWords = theWord.find(guess, theStart, theEnd)
theStart = theStart + 1
theEnd = theEnd + 1
if tempWords >= 0:
lettersInWord = lettersInWord + 1
letterPosition.append(i + 1)
stars[i] = guess
correctLetters = correctLetters + lettersInWord
if correctLetters == len(theWord):
clear()
printOutVictory()
if input() == '':
break
else:
break
clear()
printOutCorrectGuess()
printOutStars()
else:
lives = lives - 1
if lives == 0:
clear()
print('You lost.')
print('The word was: ', theWord)
print('Press enter to quit the game')
if input() == '':
break
else:
break
clear()
printOutLifes()
printOutStars()
if guess not in words and len(guess) == 1:
words.append(guess)
printOutWords()
def welcome():
print('Now we will play the classic Hangman game, but for this time without drawing it.')
print('1 or 2 player game mode? Write 1 or 2 please.')
welcome()
while True:
try:
gameMode = int(input('INPUT: '))
except ValueError:
print('Write 1 or 2 please.')
continue
if gameMode == 1:
words = ['letters', 'sloppy', 'bedroom', 'jazzy', 'discovery', 'wistful', 'unadvised', 'help', 'line', 'shake', 'mend', 'time', 'attempt', 'dare', 'straw', 'destroy', 'health', 'shiny']
theWord = random.choice(words)
clear()
game()
break
elif gameMode == 2:
theWord = str(input('Please write here the word: '))
clear()
game()
break
elif gameMode < 1 or gameMode > 2:
print('Write 1 or 2 please.')
</code></pre>
| [] | [
{
"body": "<p>Brand new to programming myself, but here's what I've got for you.</p>\n\n<p>This is just different formatting to not call print so many times:</p>\n\n<pre><code>def printOutVictory():\n print('You won!')\n print('The word was ', theWord)\n print('Press enter to quit...')\n</code></pre>\n... | {
"AcceptedAnswerId": "202469",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T13:03:43.400",
"Id": "202466",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"hangman"
],
"Title": "Very basic Hangman game in Python"
} | 202466 |
<p>Given a fraction p/q, I want to count the number of unit fraction solutions</p>
<p>$$\frac{p}{q} = \frac{1}{u} + \frac{1}{v}$$</p>
<p>with some contraints</p>
<p>$$lower \le u \le upper$$</p>
<p>By manipulating the first equation and completing a square you arrive at a formula</p>
<p>$$(pu - q)(pv - q) = q^2$$</p>
<p>So the number of solutions is related to the divisors of q squared. If we only look at the smaller of two divisors (which we will call <em>a</em>), it is a solution if it produces a valid unit fraction (1 / <em>u</em>).</p>
<p>$$a = pu - q \implies u = \frac{a + q}{p}$$</p>
<p>We are interested in a divisor <em>a</em> iff</p>
<p>$$p*lower - q \le a \le p * upper - q, \space a \equiv -q \mod p$$</p>
<hr>
<p>To compute the answer I first get the prime factorisation of q, then I double each power to get the prime factorisation of q squared. Using this I enumerate over all the possible divisors, computing each one by trying all possible combination of powers. When I generate one I check if it matches the above requirements.</p>
<pre><code>def factor_m(p, q, lower, upper):
num = q
factors = dict()
count = 0
while num % 2 == 0:
num //= 2
count += 1
if count:
factors[2] = count
current = 3
while num > 1:
count = 0
while num % current == 0:
num //= current
count += 1
if count:
factors[current] = count
current += 2
start, end = p * lower - q, p * upper - q
mod = -q % p
total = 0
for powers in product(*(range((2 * v) + 1) for v in factors.values())):
number = 1
for b, _power in zip(factors, powers):
number *= b ** _power
if start <= number <= end and number % p == mod:
total += 1
return total
</code></pre>
<p>I'm calling this function <strong>a lot</strong> with reasonably big values of q (around 10**14 currently) so anything that saves time here is a massive boost. </p>
<p>Examples:</p>
<pre><code>>>> factor_m(2, 7, 0, 50) # 3
>>> factor_m(5, 1775025265104, 355005053021, 710010106041) # 4101
>>> factor_m(737, 1046035200, 1926400, 2838630) # 1
>>> factor_m(105467, 1231689911361, 11678439, 23356877) # 0
</code></pre>
<hr>
<p><strong>EDIT</strong> To guarantee all solutions are distinct I only call the function with values that satisfy the constraint</p>
<p>$$lower \lt upper \le q$$</p>
<hr>
<p><strong>EDIT2</strong> I ran the full program through cProfile along with the program with modifications suggested by Josay. Unfortunately it is slower, I suspect because it almost doubles the number of function calls.</p>
<p>current_code - top 3 functions by time </p>
<pre><code>672574 function calls (614969 primitive calls) in 19.526 seconds
ncalls tottime percall cumtime percall filename:lineno(function)
53273 18.818 0.000 18.893 0.000 fast.py:40(factor_m)
2957 0.295 0.000 0.298 0.000 fast.py:8(factor_p1)
57606/1 0.149 0.000 19.525 19.525 fast.py:75(f)
</code></pre>
<p>With Josay's changes - top 3 functions by time </p>
<pre><code>1163833 function calls (1106228 primitive calls) in 19.835 seconds
ncalls tottime percall cumtime percall filename:lineno(function)
53273 18.427 0.000 19.160 0.000 fast.py:61(factor_m)
53273 0.500 0.000 0.650 0.000 fast.py:42(get_factors)
2957 0.297 0.000 0.301 0.000 fast.py:8(factor_v2)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T13:22:21.890",
"Id": "390256",
"Score": "0",
"body": "Is `u` <= `v`? If not, it will \"double-count\" each not-repeating (commutative) pair of unit fractions, e.g. $$\\frac{2}{7} = \\frac{1}{4} + \\frac{1}{28} = \\frac{1}{28} + \\fr... | [
{
"body": "<p><strong>Code organisation</strong></p>\n\n<p>In order to improve the code performances, if could be a good idea to make the easier to understand and easier to change.</p>\n\n<p>You could:</p>\n\n<ul>\n<li>split your code into smaller functions</li>\n<li>add documentation</li>\n<li>add tests</li>\n... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T15:35:23.750",
"Id": "202470",
"Score": "3",
"Tags": [
"python",
"performance",
"mathematics"
],
"Title": "Counting Divisors of a number with restrictions on the divisors"
} | 202470 |
<p><a href="https://codereview.stackexchange.com/questions/201902/add-two-numbers-given-in-reverse-order-from-a-linked-list">Original Question</a></p>
<p><strong>Problem Description</strong></p>
<blockquote>
<p>You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their
nodes contain a single digit. Add the two numbers and return it as a
linked list.</p>
<p>You may assume the two numbers do not contain any leading zero, except
the number 0 itself.</p>
</blockquote>
<p><a href="https://leetcode.com/problems/add-two-numbers/description/" rel="nofollow noreferrer">Link to LeetCode</a>. Only code submitted to LeetCode is in <code>AddTwoNumbersHelper</code> and <code>AddTwoNumbers</code>.</p>
<p>I've written this so that anyone can compile and run this program on their machines with:</p>
<pre><code>g++ -std=c++11 -Wall -Wextra -Werror Main.cpp -o main ; ./main
</code></pre>
<p>I'm looking for feedback on this <a href="https://leetcode.com/problems/add-two-numbers/description/" rel="nofollow noreferrer">LeetCode</a> question after modifying the code from feedback in my <a href="https://codereview.stackexchange.com/questions/201902/add-two-numbers-given-in-reverse-order-from-a-linked-list">Original Question</a>. Here is what <strong>has changed</strong>:</p>
<ul>
<li><p>The solution now uses recursion</p></li>
<li><p>The main logic is not spaghetti code anymore</p></li>
<li><p>Dealt with dangling pointers</p></li>
</ul>
<p><strong>What I'd like some feedback on</strong></p>
<p>I'm still a bit unclear on the best practice for how to handle the <code>namespace</code> and <code>using</code>s, as well as how to find the <em>time</em> and <em>space complexity</em> for this.</p>
<pre><code>#include <cstddef>
#include <iostream>
#include <ostream>
#include <stddef.h>
#include <stdlib.h>
using std::cout;
using std::endl;
using std::ostream;
using std::string;
struct Node
{
int val;
Node *next;
Node(int val) : val(val), next(NULL) {}
void PrintAllNodes()
{
Node *current = new Node(0);
current = this;
std::string nodeString = "LinkedList: ";
int val = 0;
while(current != NULL)
{
val = current->val;
nodeString = nodeString + " -> ( " + std::to_string(val) + " ) ";
current = current->next;
}
std::cout << nodeString << '\n';
}
void Append(int i)
{
if (this->next == NULL)
{
Node *n = new Node(i);
this->next = n;
}
else { this->next->Append(i); }
}
};
class Solution
{
public:
Node *AddTwoNumbers(Node *l1, Node *l2);
private:
Node *AddTwoNumbersHelper(Node *l1, Node *l2, int sum, int carry, Node *current, Node *head);
};
Node *Solution::AddTwoNumbers(Node *l1, Node *l2)
{
Node *head = new Node(0);
Node *current = head;
int sum = 0;
int carry = 0;
return AddTwoNumbersHelper(l1, l2, sum, carry, current, head);
}
Node *Solution::AddTwoNumbersHelper(Node *l1, Node *l2, int sum, int carry, Node *current, Node *head)
{
if (l1 == NULL && l2 == NULL)
{
head = head->next;
return head;
}
sum = 0;
if (l1 == NULL) { sum = l2->val + carry; }
else if (l2 == NULL) { sum = l1->val + carry; }
else if (l1 != NULL && l2 != NULL) { sum = l1->val + l2->val + carry; }
if (sum >= 10)
{
carry = sum / 10;
sum -= 10;
}
else { carry = 0; }
Node *next = new Node(sum);
current->next = next;
if (l1 == NULL) { return AddTwoNumbersHelper(l1, l2->next, sum, carry, current->next, head); }
else if (l2 == NULL) { return AddTwoNumbersHelper(l1->next, l2, sum, carry, current->next, head); }
else if (l1 != NULL && l2 != NULL) { return AddTwoNumbersHelper(l1->next, l2->next, sum, carry, current->next, head); }
return head;
}
/**
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
* Explanation: 342 + 465 = 807.
*/
void ProveBasicCase()
{
cout << "\n\nBasic case\n";
Solution s;
Node *l1 = new Node(2);
l1->Append(4);
l1->Append(3);
Node *l2 = new Node(5);
l2->Append(6);
l2->Append(4);
Node *n = new Node(0);
n = s.AddTwoNumbers(l1, l2);
n->PrintAllNodes();
}
/**
* Input: (2 -> 4 -> 3) + (5 -> 6)
* Output: 7 -> 0 -> 4
* Explanation: 342 + 65 = 407.
*/
void ProveUnEqualListSize()
{
cout << "\n\nUneven List sizes\n";
Solution s;
Node *l1 = new Node(2);
l1->Append(4);
l1->Append(3);
Node *l2 = new Node(5);
l2->Append(6);
Node *n = new Node(0);
n = s.AddTwoNumbers(l1, l2);
n->PrintAllNodes();
}
/**
* Input: (9) + (1 -> 9 -> 9 -> 9 -> 8 -> 9 -> 9)
* Output: 0 -> 0 -> 0 -> 0 -> 9 -> 9 -> 9
* Explanation: 9 + 9989991 = 9990000
*/
void ProveDoubleCarry()
{
cout << "\n\nDouble Carry\n";
Solution s;
Node *l1 = new Node(9);
Node *l2 = new Node(1);
l2->Append(9);
l2->Append(9);
l2->Append(9);
l2->Append(8);
l2->Append(9);
l2->Append(9);
Node *n = new Node(0);
n = s.AddTwoNumbers(l1, l2);
n->PrintAllNodes();
}
int main()
{
cout << "mr.robot prgm running...\n";
ProveBasicCase();
ProveUnEqualListSize();
ProveDoubleCarry();
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T16:54:49.210",
"Id": "390167",
"Score": "1",
"body": "When you compile your program, why do you pipe the output of `g++` into `./main`? Did you mean to use a semicolon, or a logical operator of some sort?"
},
{
"ContentLicen... | [
{
"body": "<pre><code>#include <cstddef>\n#include <iostream>\n#include <ostream>\n#include <stddef.h>\n#include <stdlib.h>\n</code></pre>\n\n<p>You've got some unnecessary includes here. <code><cstddef></code> and <code><stddef.h></code> are the C++ and C versions of ... | {
"AcceptedAnswerId": "202568",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T16:50:32.853",
"Id": "202472",
"Score": "5",
"Tags": [
"c++",
"programming-challenge",
"linked-list"
],
"Title": "“Add two numbers given in reverse order from a linked list”"
} | 202472 |
<p>This is a nice workqueue class template to keep the gui fluid, while data is being written into a database or into some file/network...</p>
<pre><code>#include <cassert>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <functional>
template <template <typename> class Function = std::function>
class workqueue
{
using f_t = Function<void()>;
std::vector<f_t> queue_;
std::mutex mutex_;
std::condition_variable cv_;
std::atomic_bool quit_flag_{false};
std::thread thread_;
public:
explicit workqueue() :
thread_([this]()
{
bool qf{};
while (!qf)
{
std::unique_lock<decltype(mutex_)> l(mutex_);
while (!(qf = quit_flag_.load(std::memory_order_relaxed)) &&
queue_.empty())
{
cv_.wait(l);
}
decltype(queue_) q(std::move(queue_));
l.unlock();
for (auto& f: q)
{
f();
}
}
}
)
{
}
~workqueue()
{
assert(!quit_flag_.load(std::memory_order_relaxed));
quit_flag_.store(true, std::memory_order_relaxed);
cv_.notify_one();
assert(thread_.joinable());
thread_.join();
}
template <typename F>
void exec(F&& f)
{
{
std::lock_guard<decltype(mutex_)> l(mutex_);
queue_.emplace_back(std::forward<F>(f));
}
cv_.notify_one();
}
};
</code></pre>
| [] | [
{
"body": "<pre><code> template <typename F>\n void exec(F&& f)\n {\n {\n std::lock_guard<decltype(mutex_)> l(mutex_);\n\n queue_.emplace_back(std::forward<F>(f));\n }\n\n cv_.notify_one();\n }\n</code></pre>\n\n<p>This is a bit weird. <code>emplace_back</code> a... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T19:29:19.220",
"Id": "202476",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"c++14",
"queue"
],
"Title": "C++ workqueue class"
} | 202476 |
<p>I am writing Python program which calculates area and perimeter of various 2d shapes. I am trying to learn about OOP and this is the first project which I wrote from scratch.</p>
<p>I'm wondering how to let user now what attributes he should use in order to get the correct result from particular class?
For ex: </p>
<blockquote>
<p>C = Circle(radi=2)</p>
</blockquote>
<p>gives me an atttribute error because the correct name should be radius not radi. I would like to handle this error and print the correct attribute name.</p>
<pre><code>from math import pi
"""
Exercise (Shape Area and Perimeter Classes):
Create an abstract class called Shape and then inherit from it other shapes like
diamond, rectangle, cirlce, etc. Then have each class override the area and
perimeter functionality to handle each shape type.
I wrote 20 classes to handle various shapes
Geometry figures taken from: http://www.aplustopper.com/mensuration-rs-aggarwal-class-7-maths-solutions-exercise-20c/
"""
"""
init method takes all arguments in key=value format
str method returns all given attributes in column
"""
class Shape:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __str__(self):
all_info_str = ""
for attribute, value in self.__dict__.items():
if value > 0:
all_info_str += attribute + ": " + "%.2f" %(value) + "\n"
return self.__class__.__name__ + "\n" + all_info_str
"""
Rectangle class attributes must be:
lenght=x, width=x
"""
class Rectangle(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = self.lenght * self.width
def count_perimeter(self):
self.perimeter = 2 * (self.lenght + self.width)
"""
Square class attributes must be:
lenght=x
"""
class Square(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = self.lenght ** 2
def count_perimeter(self):
self.perimeter = 4 * self.lenght
"""
Triangle class attributes must be:
base=x, height=x, leg_a=x, leg_b=x
"""
class Triangle(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = 1/2 * self.base * self.height
def count_perimeter(self):
self.perimeter = self.leg_a + self.base + self.leg_b
"""
RightTriangle class attributes must be:
base=x, height=x, hypotenuse=x
"""
class RightTriangle(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = self.base + self.height + self.hypotenuse
def count_perimeter(self):
self.perimeter = 1/2 * self.base * self.height
"""
EquilateralTriangle class attributes must be:
leg_a=x
"""
class EquilateralTriangle(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = math.sqrt(3) / 4 * self.leg_a ** 2
def count_perimeter(self):
self.perimeter = 3 * self.leg_a
"""
IsoscelecRightTriangle class attributes must be:
leg_a=x, hypotenuse=x
"""
class IsoscelecRightTriangle(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = 1/2 * self.leg_a ** 2
def count_perimeter(self):
self.perimeter = 2 * self.leg_a + self.hypotenuse
"""
Parallelogram class attributes must be:
lenght=x, height=x, width=x
"""
class Parallelogram(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = self.lenght * self.height
def count_perimeter(self):
self.perimeter = 2 * (self.lenght + self.width)
"""
Rhombus class attributes must be:
hypotenuse_1=x, hypotenuse_2=x, lenght=x
"""
class Rhombus(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = 1/2 * self.hypotenuse_1 * self.hypotenuse_2
def count_perimeter(self):
self.perimeter = 4 * self.lenght
"""
Trapezium class attributes must be:
height=x, top=x, base=x, leg_a=x, leg_b=x
"""
class Trapezium(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = 1/2 * self.height * (self.top + self.base)
def count_perimeter(self):
self.perimeter = self.leg_a + self.leg_b + self.top + self.base
"""
Circle class attributes must be:
radius=x
"""
class Circle(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = pi * self.radius ** 2
def count_perimeter(self):
self.perimeter = (pi * self.radius) + (2 * self.radius)
"""
Ring class attributes must be:
radius_1=x, radius_2=x
"""
class Ring(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = pi * (self.radius1 - self.radius2)
def count_perimeter(self):
self.perimeter = (pi * 2 * self.radius1) - (pi * 2 * self.radius2)
"""
CircleSector attributes must be:
angle=x, radius=x
"""
class CircleSector(Shape):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def count_area(self):
self.area = self.angle / 360 * pi * self.radius ** 2
def count_perimeter(self):
self.perimeter = (self.angle / 360 * 2 * pi * self.radius) +\
2 * self.radius
if __name__ == '__main__':
R = Rectangle(lenght=2, width=5)
R.count_area()
R.count_perimeter()
print(R)
C = Circle(radius=23)
C.count_area()
C.count_perimeter()
print(C)
</code></pre>
| [] | [
{
"body": "<p>A few basic things -</p>\n\n<ol>\n<li>Length is misspelled \"lenght\"</li>\n<li>Right triangle's area and perimeter are switched</li>\n<li>I'm not sure the perimeter of the circle is the correct formula, but I'm no mathematician </li>\n<li>All of these are named as <strong>count</strong> - wouldn'... | {
"AcceptedAnswerId": "202500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T19:50:31.010",
"Id": "202478",
"Score": "3",
"Tags": [
"python",
"object-oriented"
],
"Title": "Calculate various shapes Area and Perimeter"
} | 202478 |
<p><strong>Question-</strong></p>
<p>Generate all prime numbers between two given numbers.</p>
<p><a href="https://www.spoj.com/problems/PRIME1/" rel="nofollow noreferrer">https://www.spoj.com/problems/PRIME1/</a></p>
<p><strong>My attempt-</strong></p>
<p>I used segmented sieve method.</p>
<pre><code>t=int(input())
import math
def segsieve(x):
if x==1:
return False
for i in range(2,int(math.sqrt(x))+1):
if x%i==0:
return False
return True
while t>0:
f,l=map(int,input().split())
for j in range(f,l):
a=segsieve(j)
if a==True:
print(j)
t-=1
</code></pre>
<p><strong>Issue-</strong></p>
<p>I am getting time limit exceeded. How can I make it faster?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T06:44:10.033",
"Id": "390221",
"Score": "0",
"body": "You never decrement `t`, so your code runs an infinite loop, exceeding any time limit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-31T17:32:56.15... | [
{
"body": "<h1>Algorithm</h1>\n\n<h2>Hint</h2>\n\n<p>You don't need to check all integers between <code>2</code> and <code>int(math.sqrt(x))+1</code>. You only need to check primes between <code>2</code> and <code>int(math.sqrt(x))+1</code>.</p>\n\n<h1>Stylistic</h1>\n\n<h2><code>__main__</code></h2>\n\n<p>I wo... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T20:02:00.157",
"Id": "202480",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "Spoj-Prime Generator"
} | 202480 |
<p><strong>Yes, I made it up.</strong></p>
<p>This program checks if an entered <code>string</code> is a palindrome or not by assigning a <code>char</code> variable the characters in the inserted word in reverse order. The program then takes the variable and appends it to a <code>StringBuilder</code> to be able to compare the original word and the finalized reversed version.</p>
<pre><code>package Palindrome;
import java.util.Scanner;
public class palindrome {
static String word;
StringBuilder reversedWord = new StringBuilder();
public palindrome() {
char reversedChar;
for (int i = 1; i < word.length() + 1; i++) {
reversedChar = word.charAt(word.length() - i);
reversedWord.append(reversedChar);
}
}
public void checkPalindrome() {
if(word.equalsIgnoreCase(reversedWord.toString())) {
System.out.println("You got a Palindrome!");
}else{
System.out.println("That's not a Palindrome...");
}
}
public static void main(String[] args) {
System.out.print("Enter a word to check Palindromness: ");
Scanner scan = new Scanner(System.in);
word = scan.next();
scan.close();
new palindrome();
new palindrome().checkPalindrome();
}
}
</code></pre>
| [] | [
{
"body": "<h3>notes:</h3>\n\n<ol>\n<li><p>Your coding style seems good. There is some inconsistent indentation,\nbut i am guessing that is a question formatting problem.</p></li>\n<li><p>Having a static variable <code>word</code> means that <code>palindrome</code> is not \nthreadsafe, and is confusing to call.... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T20:51:53.840",
"Id": "202481",
"Score": "1",
"Tags": [
"java",
"beginner",
"palindrome"
],
"Title": "A program that checks for Palindromness"
} | 202481 |
<p>I recently finished a simple Blackjack game that I made to get better at C#. I am wondering how I can better organize or simplify my code. There are 4 files:</p>
<h3>Program.cs</h3>
<pre><code>/* Blackjack Game Copyright (C) 2018
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see<https://www.gnu.org/licenses/>. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Blackjack;
namespace Blackjack
{
public class Program
{
private static Deck deck = new Deck();
private static Player player = new Player();
private enum RoundResult
{
PUSH,
PLAYER_WIN,
PLAYER_BUST,
PLAYER_BLACKJACK,
DEALER_WIN,
SURRENDER,
INVALID_BET
}
/// <summary>
/// Initialize Deck, deal the player and dealer hands, and display them.
/// </summary>
static void InitializeHands()
{
deck.Initialize();
player.Hand = deck.DealHand();
Dealer.HiddenCards = deck.DealHand();
Dealer.RevealedCards = new List<Card>();
// If hand contains two aces, make one Hard.
if (player.Hand[0].Face == Face.Ace && player.Hand[1].Face == Face.Ace)
{
player.Hand[1].Value = 1;
}
if (Dealer.HiddenCards[0].Face == Face.Ace && Dealer.HiddenCards[1].Face == Face.Ace)
{
Dealer.HiddenCards[1].Value = 1;
}
Dealer.RevealCard();
player.WriteHand();
Dealer.WriteHand();
}
/// <summary>
/// Handles everything for the round.
/// </summary>
static void StartRound()
{
Console.Clear();
if (!TakeBet())
{
EndRound(RoundResult.INVALID_BET);
return;
}
Console.Clear();
InitializeHands();
TakeActions();
Dealer.RevealCard();
Console.Clear();
player.WriteHand();
Dealer.WriteHand();
player.HandsCompleted++;
if (player.Hand.Count == 0)
{
EndRound(RoundResult.SURRENDER);
return;
}
else if (player.GetHandValue() > 21)
{
EndRound(RoundResult.PLAYER_BUST);
return;
}
while (Dealer.GetHandValue() <= 16)
{
Thread.Sleep(1000);
Dealer.RevealedCards.Add(deck.DrawCard());
Console.Clear();
player.WriteHand();
Dealer.WriteHand();
}
if (player.GetHandValue() > Dealer.GetHandValue())
{
player.Wins++;
if (Casino.IsHandBlackjack(player.Hand))
{
EndRound(RoundResult.PLAYER_BLACKJACK);
}
else
{
EndRound(RoundResult.PLAYER_WIN);
}
}
else if (Dealer.GetHandValue() > 21)
{
player.Wins++;
EndRound(RoundResult.PLAYER_WIN);
}
else if (Dealer.GetHandValue() > player.GetHandValue())
{
EndRound(RoundResult.DEALER_WIN);
}
else
{
EndRound(RoundResult.PUSH);
}
}
/// <summary>
/// Ask user for action and perform that action until they stand, double, or bust.
/// </summary>
static void TakeActions()
{
string action;
do
{
Console.Clear();
player.WriteHand();
Dealer.WriteHand();
Console.Write("Enter Action (? for help): ");
Console.ForegroundColor = ConsoleColor.Cyan;
action = Console.ReadLine();
Casino.ResetColor();
switch (action.ToUpper())
{
case "HIT":
player.Hand.Add(deck.DrawCard());
break;
case "STAND":
break;
case "SURRENDER":
player.Hand.Clear();
break;
case "DOUBLE":
if (player.Chips <= player.Bet)
{
player.AddBet(player.Chips);
}
else
{
player.AddBet(player.Bet);
}
player.Hand.Add(deck.DrawCard());
break;
default:
Console.WriteLine("Valid Moves:");
Console.WriteLine("Hit, Stand, Surrender, Double");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
break;
}
if (player.GetHandValue() > 21)
{
foreach (Card card in player.Hand)
{
if (card.Value == 11) // Only a soft ace can have a value of 11
{
card.Value = 1;
break;
}
}
}
} while (!action.ToUpper().Equals("STAND") && !action.ToUpper().Equals("DOUBLE")
&& !action.ToUpper().Equals("SURRENDER") && player.GetHandValue() <= 21);
}
/// <summary>
/// Take player's bet
/// </summary>
/// <returns>Was the bet valid</returns>
static bool TakeBet()
{
Console.Write("Current Chip Count: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(player.Chips);
Casino.ResetColor();
Console.Write("Minimum Bet: ");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(Casino.MinimumBet);
Casino.ResetColor();
Console.Write("Enter bet to begin hand " + player.HandsCompleted + ": ");
Console.ForegroundColor = ConsoleColor.Magenta;
string s = Console.ReadLine();
Casino.ResetColor();
if (Int32.TryParse(s, out int bet) && bet >= Casino.MinimumBet && player.Chips >= bet)
{
player.AddBet(bet);
return true;
}
return false;
}
/// <summary>
/// Perform action based on result of round and start next round.
/// </summary>
/// <param name="result">The result of the round</param>
static void EndRound(RoundResult result)
{
switch (result)
{
case RoundResult.PUSH:
player.ReturnBet();
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Player and Dealer Push.");
break;
case RoundResult.PLAYER_WIN:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Player Wins " + player.WinBet(false) + " chips");
break;
case RoundResult.PLAYER_BUST:
player.ClearBet();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Player Busts");
break;
case RoundResult.PLAYER_BLACKJACK:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Player Wins " + player.WinBet(true) + " chips with Blackjack.");
break;
case RoundResult.DEALER_WIN:
player.ClearBet();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Dealer Wins.");
break;
case RoundResult.SURRENDER:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Player Surrenders " + (player.Bet / 2) + " chips");
player.Chips += player.Bet / 2;
player.ClearBet();
break;
case RoundResult.INVALID_BET:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid Bet.");
break;
}
if (player.Chips <= 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine("You ran out of Chips after " + (player.HandsCompleted - 1) + " rounds.");
Console.WriteLine("500 Chips will be added and your statistics have been reset.");
player = new Player();
}
Casino.ResetColor();
Console.WriteLine("Press any key to continue");
Console.ReadKey();
StartRound();
}
static void Main(string[] args)
{
// Console cannot render unicode characters without this line
Console.OutputEncoding = Encoding.UTF8;
Casino.ResetColor();
Console.Title = "♠♥♣♦ Blackjack";
Console.WriteLine("♠♥♣♦ Welcome to Blackjack v" + Casino.GetVersionCode());
Console.WriteLine("Press any key to play.");
Console.ReadKey();
StartRound();
}
}
}
</code></pre>
<h3>Casino.cs</h3>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
public class Casino
{
private static string versionCode = "1.0";
public static int MinimumBet { get; } = 10;
public static string GetVersionCode() { return versionCode; }
/// <param name="hand">The hand to check</param>
/// <returns>Returns true if the hand is blackjack</returns>
public static bool IsHandBlackjack(List<Card> hand)
{
if (hand.Count == 2)
{
if (hand[0].Face == Face.Ace && hand[1].Value == 10) return true;
else if (hand[1].Face == Face.Ace && hand[0].Value == 10) return true;
}
return false;
}
/// <summary>
/// Reset Console Colors to DarkGray on Black
/// </summary>
public static void ResetColor()
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.BackgroundColor = ConsoleColor.Black;
}
}
public class Player
{
public int Chips { get; set; } = 500;
public int Bet { get; set; }
public int Wins { get; set; }
public int HandsCompleted { get; set; } = 1;
public List<Card> Hand { get; set; }
/// <summary>
/// Add Player's chips to their bet.
/// </summary>
/// <param name="bet">The number of Chips to bet</param>
public void AddBet(int bet)
{
Bet += bet;
Chips -= bet;
}
/// <summary>
/// Set Bet to 0
/// </summary>
public void ClearBet()
{
Bet = 0;
}
/// <summary>
/// Cancel player's bet. They will neither lose nor gain any chips.
/// </summary>
public void ReturnBet()
{
Chips += Bet;
ClearBet();
}
/// <summary>
/// Give player chips that they won from their bet.
/// </summary>
/// <param name="blackjack">If player won with blackjack, player wins 1.5 times their bet</param>
public int WinBet(bool blackjack)
{
int chipsWon;
if (blackjack)
{
chipsWon = (int) Math.Floor(Bet * 1.5);
}
else
{
chipsWon = Bet * 2;
}
Chips += chipsWon;
ClearBet();
return chipsWon;
}
/// <returns>
/// Value of all cards in Hand
/// </returns>
public int GetHandValue()
{
int value = 0;
foreach(Card card in Hand)
{
value += card.Value;
}
return value;
}
/// <summary>
/// Write player's hand to console.
/// </summary>
public void WriteHand()
{
// Write Bet, Chip, Win, Amount with color, and write Round #
Console.Write("Bet: ");
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write(Bet + " ");
Casino.ResetColor();
Console.Write("Chips: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(Chips + " ");
Casino.ResetColor();
Console.Write("Wins: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(Wins);
Casino.ResetColor();
Console.WriteLine("Round #" + HandsCompleted);
Console.WriteLine();
Console.WriteLine("Your Hand (" + GetHandValue() + "):");
foreach (Card card in Hand) {
card.WriteDescription();
}
Console.WriteLine();
}
}
public class Dealer
{
public static List<Card> HiddenCards { get; set; } = new List<Card>();
public static List<Card> RevealedCards { get; set; } = new List<Card>();
/// <summary>
/// Take the top card from HiddenCards, remove it, and add it to RevealedCards.
/// </summary>
public static void RevealCard()
{
RevealedCards.Add(HiddenCards[0]);
HiddenCards.RemoveAt(0);
}
/// <returns>
/// Value of all cards in RevealedCards
/// </returns>
public static int GetHandValue()
{
int value = 0;
foreach (Card card in RevealedCards)
{
value += card.Value;
}
return value;
}
/// <summary>
/// Write Dealer's RevealedCards to Console.
/// </summary>
public static void WriteHand()
{
Console.WriteLine("Dealer's Hand (" + GetHandValue() + "):");
foreach (Card card in RevealedCards)
{
card.WriteDescription();
}
for (int i = 0; i < HiddenCards.Count; i++)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("<hidden>");
Casino.ResetColor();
}
Console.WriteLine();
}
}
}
</code></pre>
<h3>Deck.cs</h3>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
public class Deck
{
private List<Card> cards;
/// <summary>
/// Initilize on creation of Deck.
/// </summary>
public Deck()
{
Initialize();
}
/// <returns>
/// Returns a Cold Deck-- a deck organized by Suit and Face.
/// </returns>
public List<Card> GetColdDeck()
{
List<Card> coldDeck = new List<Card>();
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 4; j++)
{
coldDeck.Add(new Card((Suit)j, (Face)i));
}
}
return coldDeck;
}
/// <summary>
/// Remove top 2 cards of Deck and turn it into a list.
/// </summary>
/// <returns>List of 2 Cards</returns>
public List<Card> DealHand()
{
// Create a temporary list of cards and give it the top two cards of the deck.
List<Card> hand = new List<Card>();
hand.Add(cards[0]);
hand.Add(cards[1]);
// Remove the cards added to the hand.
cards.RemoveRange(0, 2);
return hand;
}
/// <summary>
/// Pick top card and remove it from the deck
/// </summary>
/// <returns>The top card of the deck</returns>
public Card DrawCard()
{
Card card = cards[0];
cards.Remove(card);
return card;
}
/// <summary>
/// Randomize the order of the cards in the Deck.
/// </summary>
public void Shuffle()
{
Random rng = new Random();
int n = cards.Count;
while(n > 1)
{
n--;
int k = rng.Next(n + 1);
Card card = cards[k];
cards[k] = cards[n];
cards[n] = card;
}
}
/// <summary>
/// Replace the deck with a Cold Deck and then Shuffle it.
/// </summary>
public void Initialize()
{
cards = GetColdDeck();
Shuffle();
}
}
}
</code></pre>
<h3>Card.cs</h3>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Blackjack.Suit;
using static Blackjack.Face;
namespace Blackjack
{
public enum Suit
{
Clubs,
Spades,
Diamonds,
Hearts
}
public enum Face
{
Ace,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King
}
public class Card
{
public Suit Suit { get; }
public Face Face { get; }
public int Value { get; set; }
public char Symbol { get; }
/// <summary>
/// Initilize Value and Suit Symbol
/// </summary>
public Card(Suit suit, Face face)
{
Suit = suit;
Face = face;
switch (Suit)
{
case Clubs:
Symbol = '♣';
break;
case Spades:
Symbol = '♠';
break;
case Diamonds:
Symbol = '♦';
break;
case Hearts:
Symbol = '♥';
break;
}
switch (Face)
{
case Ten:
case Jack:
case Queen:
case King:
Value = 10;
break;
case Ace:
Value = 11;
break;
default:
Value = (int)Face + 1;
break;
}
}
/// <summary>
/// Print out the description of the card, marking Aces as Soft or Hard.
/// </summary>
public void WriteDescription()
{
if (Suit == Suit.Diamonds || Suit == Suit.Hearts)
{
Console.ForegroundColor = ConsoleColor.Red;
}
else
{
Console.ForegroundColor = ConsoleColor.White;
}
if (Face == Ace)
{
if (Value == 11)
{
Console.WriteLine(Symbol + " Soft " + Face + " of " + Suit);
}
else
{
Console.WriteLine(Symbol + " Hard " + Face + " of " + Suit);
}
}
else
{
Console.WriteLine(Symbol + " " + Face + " of " + Suit);
}
Casino.ResetColor();
}
}
}
</code></pre>
<blockquote>
<p><strong>Program.cs:</strong> This file controls the game by printing most text and taking > player input.</p>
<p><strong>Casino.cs:</strong> This file contains "the rules of the house" as well as Player and > Dealer classes.</p>
<p><strong>Deck.cs:</strong> This file contains the code for the Deck--drawing cards and
shuffling.</p>
<p><strong>Card.cs:</strong> This file contains the code for the Card class.</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T15:21:52.497",
"Id": "390270",
"Score": "0",
"body": "You should create rng only once."
}
] | [
{
"body": "<p>A few things I noticed:</p>\n\n<p>Instead of adding one to the <code>Face</code> enum value, it would make sense to me to make <code>Ace = 1,</code>. This will automatically set all the rest to where you need them.</p>\n\n<p>A <code>Hand</code> class would make sense. This could handle the sum o... | {
"AcceptedAnswerId": "202497",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T21:06:58.050",
"Id": "202483",
"Score": "7",
"Tags": [
"c#",
"playing-cards"
],
"Title": "C# Singleplayer Blackjack Game"
} | 202483 |
<p>Feedback from previous posts of mine suggested that my approach to states was haphazard, which is not surprising since I hadn't really thought of games in terms of states before. I have since gone off and done some studying and implemented a version of "the 21 Game" using the finite state machine pattern. My code is procedural intentionally. I will try to use an OOP version of this pattern for my next project. </p>
<p>I would appreciate some feedback on how well I did with a first attempt using this pattern.</p>
<p>For example, did I identify all the states correctly? Is my implementation "clean"? How could it be improved?</p>
<pre><code>"""
Count to 21 game (aka Nim)
Uses basic implementation of a finite state machine pattern for
game control
A variable named 'state' controls the game in the loop at the end
of the program
"""
import random
import sys
import os
settings = {
"max_add": 3, # Must be int >= 1
"text": {
"header": """ ___ __ _______ ___ .___ ___. _______
|__ \ /_ | / _____| / \ | \/ | | ____|
) | | | | | __ / ^ \ | \ / | | |__
/ / | | | | |_ | / /_\ \ | |\/| | | __|
/ /_ | | | |__| | / _____ \ | | | | | |____
|____| |_| \______| /__/ \__\ |__| |__| |_______|
""",
"number_prompt": "Enter a number between 1 and #: ",
"invalid": "Invalid input",
"welcome": "Welcome to 21",
"instructions": """You must add to the total to make 21 without going over.
The computer will try and beat you.""",
"ready?": "Are you ready? ",
"won": "Congratulations. You won",
"lost": "You lost.",
"again?": "Play again? ",
"goodbye": "Thank you for playing.",
"current_total": "The current total is #.",
"player_turn": "Player turn",
"computer_turn": "Computer turn"
}
}
def print_header():
os.system('clear') # Windows version. Use "cls" on Linux/Mac
print(settings["text"]["header"])
def get_integer():
number = None
while number is None:
prompt = settings["text"]["number_prompt"]
value = input(prompt.replace("#", str(settings["max_add"])))
if value.isdigit() and int(value) <= settings["max_add"]:
number = int(value)
else:
print(settings["text"]["invalid"])
return number
def yes_no(txt):
result = None
while result is None:
choice = input(txt)
if choice in ["y", "Y"]:
result = True
elif choice in ["n", "N"]:
result = False
else:
print(settings["text"]["invalid"])
return result
def player_turn():
global state
global current_total
print("")
print(settings["text"]["player_turn"])
print(settings["text"]["current_total"].replace("#", str(current_total)))
to_add = get_integer()
if to_add in range(1, settings["max_add"] + 1):
current_total += to_add
if current_total == 21:
state = "PLAYER_WINS"
return
elif current_total > 21:
state = "PLAYER_LOSES"
return
state = "COMPUTER_TURN"
return
def computer_turn():
print("")
print(settings["text"]["computer_turn"])
global state
global current_total
computer_choice = random.randrange(1, settings["max_add"] + 1)
print("Computer adds {}".format(computer_choice))
current_total += computer_choice
print(settings["text"]["current_total"].replace("#", str(current_total)))
if current_total == 21:
state = "PLAYER_LOSES"
return
elif current_total > 21:
state = "PLAYER_WINS"
return
state = "PLAYER_TURN"
return
def start():
print_header()
global current_total
global state
current_total = 0
print(settings["text"]["welcome"])
print(settings["text"]["instructions"])
result = yes_no(settings["text"]["ready?"])
if result:
state = "PLAYER_TURN" if random.randrange(2) == 0 else "COMPUTER_TURN"
else:
state = "STOP"
return
def player_wins():
global state
print(settings["text"]["won"])
state = "END"
return
def player_loses():
global state
print(settings["text"]["lost"])
state = "END"
return
def end():
global state
print("")
again = yes_no(settings["text"]["again?"])
if again:
state = "START"
else:
state = "STOP"
return
def stop():
print(settings["text"]["goodbye"])
sys.exit()
# Main game loop
state = "START"
while True:
if state == "START":
start()
elif state == "PLAYER_TURN":
player_turn()
elif state == "COMPUTER_TURN":
computer_turn()
elif state == "PLAYER_WINS": # Synonymous with "COMPUTER_LOSES"
player_wins()
elif state == "PLAYER_LOSES": # Synonymous with "COMPUTER_WINS"
player_loses()
elif state == "END":
end()
elif state == "STOP":
stop()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T21:10:50.847",
"Id": "202484",
"Score": "1",
"Tags": [
"python",
"game",
"state-machine"
],
"Title": "21 Game (Nim) as Finite State Machine in Python"
} | 202484 |
<p>Given a binary tree, return all root-to-leaf paths.</p>
<p>Example: </p>
<pre><code>-- 1
/ \
2 3
\
5
</code></pre>
<p>Output should be: ["1->2->5", "1->3"]</p>
<p>My approach: I walk the branches from left to right, finding the first leaf on the leftward tangent collecting the segments until the last node. I collect the vectors of the tree into a passing stack. On exhausting every leftward vector I stop collecting the segments. I look to the right vector and see if a pathway exists. I turn on segment collection and reorient on a parallel trajectory adjacent to the right vector.</p>
<p>On reaching the last node I push a copy of the current state of the passing stack to the list of paths. I traverse back up the frames removing the collected paths by <code>popping()</code> them from the passing stack, and my current position.</p>
<p>As I slingshot back up the frames, to the beginning. I exploring the right vectors and I stack the frames and branch down the path on every opening. I collect the nodes values into the passed stack on entering and push a copy of the current state of the passed stack on reaching every leaf. On exiting the branching frames, I removing from the passed stack every value as I travel back to the beginning, branching on every fork along the frames.</p>
<p>Time complexity is \$O(n^2)\$ where \$n\$ is the number of nodes. I touch both the right and left vectors of the recursion. The left on entering and right on exiting.</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 binaryTreePaths(root) {
const paths = [];
let moveLeft = true;
function pathsInternal(node, stack = []) {
if (moveLeft) stack.push(node.val)
if (node.left) pathsInternal(node.left, stack)
else moveLeft = false;
if (node.right) {
moveLeft = true
pathsInternal(node.right, stack)
} else {
if (node.left === null) paths.push(stack.slice())
}
stack.pop()
return paths
}
return pathsInternal(root).map(x => x.join("->"))
}
const leaves1 = {
"val": 1,
"right": {
"val": 3,
"right": null,
"left": null
},
"left": {
"val": 2,
"right": {
"val": 5,
"right": null,
"left": null
},
"left": null
}
}
leaves2 = {
val: 1,
left: {
val: 2,
left: {
val: 3,
left: {
val: 4,
left: {
val: 5,
left: null,
right: null
},
right: null
},
right: {
val: 6,
left: null,
right: null
}
},
right: {
val: 7,
left: {
val: 8,
left: {
val: 9,
left: null,
right: null
},
right: null
},
right: {
val: 10,
left: {
val: 11,
left: {
val: 12,
left: {
val: 13,
left: null,
right: null
},
right: null
},
right: {
val: 14,
left: null,
right: null
}
},
right: {
val: 15,
left: {
val: 16,
left: null,
right: {
val: 17,
left: {
val: 18,
left: null,
right: null
},
right: null
}
},
right: null
}
}
}
},
right: {
val: 19,
left: null,
right: {
val: 20,
left: null,
right: {
val: 21,
left: {
val: 22,
left: {
val: 23,
left: null,
right: null
},
right: null
},
right: {
val: 24,
left: {
val: 25,
left: {
val: 26,
left: {
val: 27,
left: null,
right: null
},
right: null
},
right: {
val: 28,
left: null,
right: null
}
},
right: null
}
}
}
}
};
console.log(binaryTreePaths(leaves1))
console.log(binaryTreePaths(leaves2))</code></pre>
</div>
</div>
</p>
<p>Second approach: In my second approach I only touch every element once. I believe this makes it linear but I am not positive?</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 branchPaths(tree) {
const paths = [],
rightIndexes = new WeakMap(),
map = new Map();
function leaves(root, cpaths = []) {
let stack = [];
while (root) {
let index = cpaths.push(root.val)
if (root.right) {
stack.push(root.right)
rightIndexes.set(root.right, index - 1)
}
map.set(root.val, root)
root = root.left
}
let pier = map.get(cpaths[cpaths.length - 1])
if (!pier.right && !pier.left) paths.push(cpaths)
while (stack.length) {
let right = stack.pop(),
origin = rightIndexes.get(right),
slice = cpaths.slice(0, origin + 1);
leaves(right, slice)
}
return paths.map(x => x.join('->'))
}
return leaves(tree)
}
const tree1 = {
"val": 1,
"right": {
"val": 3,
"right": {
"val": 4,
"right": null,
"left": null
},
"left": null
},
"left": {
"val": 2,
"right": {
"val": 5,
"right": null,
"left": null
},
"left": null
}
}
const tree2 = {
val: 1,
left: {
val: 2,
left: {
val: 3,
left: {
val: 4,
left: {
val: 5,
left: null,
right: null
},
right: null
},
right: {
val: 6,
left: null,
right: null
}
},
right: {
val: 7,
left: {
val: 8,
left: {
val: 9,
left: null,
right: null
},
right: null
},
right: {
val: 10,
left: {
val: 11,
left: {
val: 12,
left: {
val: 13,
left: null,
right: null
},
right: null
},
right: {
val: 14,
left: null,
right: null
}
},
right: {
val: 15,
left: {
val: 16,
left: null,
right: {
val: 17,
left: {
val: 18,
left: null,
right: null
},
right: null
}
},
right: null
}
}
}
},
right: {
val: 19,
left: null,
right: {
val: 20,
left: null,
right: {
val: 21,
left: {
val: 22,
left: {
val: 23,
left: null,
right: null
},
right: null
},
right: {
val: 24,
left: {
val: 25,
left: {
val: 26,
left: {
val: 27,
left: null,
right: null
},
right: null
},
right: {
val: 28,
left: null,
right: null
}
},
right: null
}
}
}
}
};
console.log(branchPaths(tree1))
console.log(branchPaths(tree2))</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T17:52:28.490",
"Id": "390408",
"Score": "0",
"body": "I could've sworn there was an answer on this question..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T17:52:56.673",
"Id": "390409",
"S... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T22:38:08.573",
"Id": "202487",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"recursion",
"tree",
"stack"
],
"Title": "All the paths from the root to the leaves"
} | 202487 |
<p>I'm working on part of a service for data processing. The main idea of the service is to get the input data, process it and return the processed data to another service. Input and output data format are flat JSON documents (documents without nested objects and lists, only first level objects).
The core entity of this service is <code>Filter</code>. <code>Filter</code> accepts parsed JSON data, processes it and returns processed data in its internal format (in my case this is <code>Map<String, BaseValue</code>). <code>Filter</code> has a context (current state of data) and a list of operations.
Here is the code of the <code>Filter</code> class:</p>
<pre><code>package com.rk.filter;
import com.rk.filter.context.FilterContext;
import com.rk.operations.Operation;
import com.rk.types.BaseValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class Filter {
private List<Operation> ops = new ArrayList<>();
public Map<String, BaseValue> apply(Map<String, BaseValue> inputs) {
return apply(inputs, null);
}
public Map<String, BaseValue> apply(Map<String, BaseValue> inputs, Consumer<String> traceConsumer) {
FilterContext context = new FilterContext(inputs);
for (Operation block: ops) {
block.apply(context);
if (traceConsumer != null) {
traceConsumer.accept(context.trace());
}
}
return context.getData();
}
public void addOperation(Operation operation) {
ops.add(operation);
}
}
</code></pre>
<p>Code of FilterContext class:</p>
<pre><code>package com.rk.filter.context;
import com.rk.filter.MissingValuesException;
import com.rk.types.BaseValue;
import com.rk.types.NullValue;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public class FilterContext {
private final Map<String, BaseValue> data;
private final Map<String, BaseValue> variables;
public Map<String, BaseValue> getData() {
return data;
}
public FilterContext(Map<String, BaseValue> inputData) {
this.data = new HashMap<>(inputData);
this.variables = new HashMap<>();
}
public BaseValue getFromData(String key) {
BaseValue value = data.get(key);
assertReadValueIsNotNull(value, "data", key);
return value;
}
public void setToData(String key, BaseValue value) {
value = Objects.requireNonNull(value);
data.put(key, value);
}
public BaseValue getFromVariables(String key) {
BaseValue value = variables.get(key);
assertReadValueIsNotNull(value, "variables", key);
return value;
}
public void setToVariables(String key, BaseValue value) {
value = Objects.requireNonNull(value);
variables.put(key, value);
}
public String trace() {
return "data: " + formatData(data) + "\nvariables: " + formatData(variables);
}
private static String formatData(Map<String, BaseValue> data) {
return data.entrySet().stream()
.map((Map.Entry e) -> e.getKey() + " = " + e.getValue())
.collect(Collectors.joining(", "));
}
private static void assertReadValueIsNotNull(Object value, String storageName, String key) {
if (value == null) {
throw new MissingValuesException(storageName, key);
}
}
}
</code></pre>
<p><code>Operation</code> is an entity that accepts data from given sources and writes the result to the given targets. Each <code>Operation</code> class defines its sources and targets, for example the string concatenation operation (<code>A + B</code>) takes 2 sources (<code>A</code> and <code>B</code>) and writes the result to the <code>OUT</code> target. My current implementation of operations knows about <code>FilterContext</code>:</p>
<pre><code>package com.rk.operations;
import com.rk.filter.context.FilterContext;
public interface Operation {
void apply(FilterContext context);
}
</code></pre>
<p>Example of operation implementation:</p>
<pre><code>package com.rk.operations;
import com.rk.filter.context.FilterContext;
import com.rk.filter.context.Getter;
import com.rk.filter.context.Setter;
import com.rk.types.NumberValue;
import java.math.BigDecimal;
public class NumberAddOperation implements Operation {
private final Getter a;
private final Getter b;
private final Setter out;
public NumberAddOperation(Getter a, Getter b, Setter out) {
this.a = a;
this.b = b;
this.out = out;
}
@Override
public void apply(FilterContext context) {
NumberValue aValue = a.getValue(context).toNumberValue();
NumberValue bValue = b.getValue(context).toNumberValue();
BigDecimal result = aValue.getValue().add(bValue.getValue());
out.setValue(new NumberValue(result), context);
}
}
</code></pre>
<p>As you can see, <code>Operation</code> has two getters and one setter. The <code>Getter</code> interface implementations says what kind of data we should read from <code>FilterContext</code> (the data source). The <code>Setter</code> interface implementations says where we should put our data (the data target).</p>
<p>Code of <code>Getter</code> interface:</p>
<pre><code>package com.rk.filter.context;
import com.rk.types.BaseValue;
public interface Getter {
BaseValue getValue(FilterContext context);
}
</code></pre>
<p>Code of <code>Setter</code> interface:</p>
<pre><code>package com.rk.filter.context;
import com.rk.types.BaseValue;
public interface Setter {
void setValue(BaseValue value, FilterContext context);
}
</code></pre>
<p>Now I have three implementations of these interfaces:</p>
<ul>
<li>class <code>DataAccess</code> - both read and write to context <code>data</code> field;</li>
<li>class <code>VariablesAccess</code> - both read and write to context <code>variables</code> field;</li>
<li>class <code>ConstGetter</code> - special getter that provides <code>const</code> value and actually doesn't read or write context.</li>
</ul>
<p>Here is some runnable code:</p>
<pre><code>package com.rk;
import com.rk.filter.Filter;
import com.rk.filter.context.ConstGetter;
import com.rk.filter.context.DataAccess;
import com.rk.filter.context.VariablesAccess;
import com.rk.operations.AssignOperation;
import com.rk.operations.NumberAddOperation;
import com.rk.operations.Operation;
import com.rk.operations.StringTrimOperation;
import com.rk.types.BaseValue;
import com.rk.types.NumberValue;
import com.rk.types.StringValue;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
/* Setup test data */
Map<String, BaseValue> data = new HashMap<>();
data.put("foo", new StringValue(" hello "));
data.put("bar", new StringValue("500"));
BigDecimal number = new BigDecimal(155);
/* Setup operations */
Operation op1 = new StringTrimOperation(new DataAccess("foo"), new DataAccess("foo"));
Operation op2 = new AssignOperation(new DataAccess("bar"), new VariablesAccess("var_bar"));
Operation op3 = new NumberAddOperation(
new VariablesAccess("var_bar"),
new ConstGetter(new NumberValue(number)),
new DataAccess("bar"));
/* Setup filters */
Filter filter = new Filter();
filter.addOperation(op1);
filter.addOperation(op2);
filter.addOperation(op3);
/* Execute */
Map<String, BaseValue> result = filter.apply(data, (trace -> {
System.out.println(trace);
System.out.println();
}));
System.out.println(result.get("foo").toStringValue().getValue()); // "hello"
System.out.println(result.get("bar").toNumberValue().getValue()); // 655
}
}
</code></pre>
<p>In reality, the service configurations of <code>Filter</code>, operations, getter and setter will all be taken from a database.</p>
<p>Note about <code>BaseValue</code> class: base value is a set of 4 basic types (null, string, number and boolean) that can be converted to each other:</p>
<pre><code>package com.rk.types;
abstract public class BaseValue {
abstract public StringValue toStringValue();
abstract public BooleanValue toBooleanValue();
abstract public NumberValue toNumberValue();
public final NullValue toNullValue() {
return NullValue.NULL;
}
}
</code></pre>
<p>Example of implementation of <code>NumberValue</code>:</p>
<pre><code>package com.rk.types;
import java.math.BigDecimal;
import java.util.Objects;
public class NumberValue extends BaseValue implements TypeAdapter<BigDecimal> {
private static final BigDecimal DEFAULT_VALUE = BigDecimal.ZERO;
private BigDecimal value;
public NumberValue() {
this.value = DEFAULT_VALUE;
}
public NumberValue(BigDecimal value) {
this.value = Objects.requireNonNull(value);
}
@Override
public BigDecimal getValue() {
return this.value;
}
@Override
public void setValue(BigDecimal value) {
this.value = Objects.requireNonNull(value);
}
@Override
public BooleanValue toBooleanValue() {
return new BooleanValue(!isZero());
}
@Override
public NumberValue toNumberValue() {
return this;
}
@Override
public StringValue toStringValue() {
return new StringValue(value.toPlainString());
}
private boolean isZero() {
return value.equals(BigDecimal.ZERO);
}
@Override
public String toString() {
return value.toString();
}
}
</code></pre>
<p>Is it possible to make this code better? It seems that my mechanism of <code>Getter</code> and <code>Setter</code> is not too good, because the operations classes know about the <code>Filter</code> context, even though they don't work with the context interface directly.</p>
<p>Implementation note: I assume that my code should be null-safe. It means that my data storage can't have keys with <code>null</code> values. For null-like values, an instance of class <code>NullValue</code> should be used.</p>
<p>The whole code is published on <a href="https://github.com/iRomul/DataProcessMini" rel="nofollow noreferrer" title="GitHub">GitHub</a>.</p>
<p>Class diagram.
<a href="https://i.stack.imgur.com/fmAsF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fmAsF.png" alt="Class diagram"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T07:50:27.127",
"Id": "406073",
"Score": "1",
"body": "If you want to remove boiler plate code like getter setter then use lombok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T07:51:12.633",
"Id... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T23:30:01.740",
"Id": "202488",
"Score": "4",
"Tags": [
"java",
"object-oriented"
],
"Title": "Data processing program"
} | 202488 |
<p>I wanted to make a function that will dynamically retrieve a line from a stream to a buffer. This function just needs to take in the <code>char*</code> and the stream to read from. It'll keep allocating a bigger buffer until it can read all the data into the <code>rtr</code> variable (terminated on new line). Any ways I can improve this would be amazing.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* dynamic_fgets(char** rtr, FILE* stream) {
int bufsize = 1024; //Start at 1024 bytes
char* buf = (char*) malloc(bufsize*sizeof(char));
if(buf == NULL) {
perror("Couldn't allocate memory for buf in dynamic_fgets\n");
}
do {
fgets(buf, bufsize, stream);
*rtr = realloc(*rtr, strlen(buf)+strlen(*rtr));
if(*rtr == NULL) {
perror("Couldn't allocate memory for *rtr in dynamic_fgets\n");
}
*rtr = strncat(*rtr, buf, bufsize);
bufsize *= 2;
} while(buf[strlen(buf)-1] != '\n');
return *rtr;
}
int main(int argc, char** argv) {
char* buf = (char*) malloc(sizeof(1));
strncpy(buf, "\0", 1);
printf("Input: ");
dynamic_fgets(&buf, stdin);
printf("Output: %s", buf);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T22:57:55.500",
"Id": "390300",
"Score": "1",
"body": "Perhaps you want [getline(3)](http://man7.org/linux/man-pages/man3/getline.3.html) ?"
}
] | [
{
"body": "<ul>\n<li><p>Make up your mind. <code>dynamic_fgets</code> returns the same information via return value (<code>return *rtr</code>) and the in-out parameter (<code>char ** rtr</code>). Chose one.</p></li>\n<li><p>Do not cast <code>malloc</code> return value. In C it is redundant, and may cause hard-t... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T01:09:14.360",
"Id": "202490",
"Score": "6",
"Tags": [
"c",
"reinventing-the-wheel",
"io"
],
"Title": "Dynamic fgets in C"
} | 202490 |
<h2>Motivation</h2>
<p>As an exercise, I wanted to try implementing function overloading in Python 3, i.e. to implement a way of defining multiple functions with the same name and then calling the appropriate function based on the given arguments in a function call. I know that this isn't necessary with Python and my understanding is that the Pythonic way to realize this kind of functionality is to define a single function and then inspect the arguments in order to determine the desired course of action, but I wanted to try this anyway and see how it went.</p>
<h2>Features</h2>
<p>There were a few basic features that I wanted to include:</p>
<ul>
<li><p>Collect functions by name, e.g. <code>def f(x): pass</code> and <code>def f(y): pass</code> should be considered as two versions of the same polymorphic function <code>f</code> (this is basically just the definition of function overloading, right?).</p></li>
<li><p>Handle both stand-alone (unbound) functions and instance methods (bound functions).</p></li>
<li><p>If there is a way to resolve a given function call, then do so (i.e. don't fail unless there is no function that can handle the given arguments).</p></li>
</ul>
<h2>Implementation</h2>
<p>My idea was to use a controller class to store the different function definitions and use a decorator to register the functions with the controller. I wrote a module called <code>overload.py</code> with two classes: an <code>OverloadedFunction</code> class which stores a list of functions corresponding to the different overloaded versions of a given polymorphic function and an <code>Overloader</code> class which associates function names with <code>OverloadedFunction</code> objects.</p>
<p>The <code>OverloadFunction</code> objects have a <code>lookup</code> method which looks through the list of registered functions and returns the first one that matches the given set of arguments. The <code>OverloadFunction</code> objects are also callable and use their <code>__call__</code> method to call the function obtained via the <code>lookup</code> method.</p>
<p>The <code>Overload</code> class defines an <code>overload</code> decorator which defines two wrapper functions: <code>function_wrapper</code> and <code>method_wrapper</code>. This handles both the cases of stand-alone (unbound) functions and instance methods (bound functions).</p>
<p>Here is the script:</p>
<pre><code>#!/usr/bin/env python3
# coding: ascii
"""overload.py
Allow for multiple functions with different signatures
to have the same name (i.e. function overloading)."""
import inspect
from inspect import (
getfullargspec,
getmro,
isfunction,
ismethod,
)
from functools import (
wraps,
)
class OverloadedFunctionError(Exception):
"""Exception class for errors related to the OverloadedFunction class."""
pass
class OverloadedFunction(object):
"""An overloaded function.
This is a proxy object which stores a list of functions. When called,
it calls the first of its functions which matches the given arguments."""
def __init__(self):
"""Initialize a new overloaded function."""
self.registry = list()
def lookup(self, args, kwargs):
"""Return the first registered function
that matches the given call-parameters."""
for function in self.registry:
fullargspec = getfullargspec(function)
# Make sure that the function can handle
# the given number of positional arguments
if(
len(args) <= len(fullargspec.args) or
bool(fullargspec.varargs)
):
# Make sure that the function can handle
# the remaining keyword arguments
remaining_args = fullargspec.args[len(args):]
if(
frozenset(kwargs.keys()).issubset(remaining_args) or
bool(fullargspec.varkw)
):
return function
def register(self, function):
"""Add a new function to the registry."""
self.registry.append(function)
def __call__(self, *args, **kwargs):
"""Call the first matching registered
function with the given call parameters."""
# Get the first function which can handle the given arguments
function = self.lookup(args=args, kwargs=kwargs)
# If no function can be found, raise an exception
if not function:
raise OverloadedFunctionError(
"Failed to find matching function for given arguments: "
"args={}, kwargs={}".format(args, kwargs)
)
# Evaluate the function and return the result
return function(*args, **kwargs)
class Overloader(object):
"""A controller object which organizes OverloadedFunction by name."""
def __init__(self):
"""Initialize a new OverloadedFunction controller."""
self.registry = dict()
def register(self, function):
"""Add a new function to the controller."""
# Create a new OverloadedFunction for this
# function name if one does not # already exists
if function.__qualname__ not in self.registry.keys():
self.registry[function.__qualname__] = OverloadedFunction()
self.registry[function.__qualname__].register(function)
def overload(self, function):
"""Decorator for registering a new function with
the Overloader overloaded function controller."""
# Register the new function with the controller
self.register(function)
# Handle the case of unbound functions
if isfunction(function):
def function_wrapper(*args, **kwargs):
_function = self.registry[function.__qualname__]
return _function(*args, **kwargs)
return function_wrapper
# Handle the case of bound functions
if ismethod(function):
def method_wrapper(_self, *args, **kwargs):
_function = self.registry[function.__qualname__]
return _function(self=_self, *args, **kwargs)
return method_wrapper
</code></pre>
<h2>Example</h2>
<p>I wrote a short example script to test out the module. Here is the script:</p>
<pre><code>#!/usr/bin/env python3
# coding: ascii
"""test_overload.py
Simple tests of the overload.py module.
"""
from overload import Overloader
# Instantiate a controller object
p = Overloader()
# Define several function with the same name "f"
@p.overload
def f():
return "called: def f()"
@p.overload
def f(x):
return "called: def f(x) with x={}".format(x)
@p.overload
def f(y):
return "called: def f(y) with y={}".format(y)
@p.overload
def f(*args, **kwargs):
return "called: def f(*args, **kwargs) with args={}, kwargs={}".format(args, kwargs)
# Call the overloaded function "f" and print the results
print(f())
print(f(1))
print(f(x=2))
print(f(y=3))
print(f(1, 2, 3, x=4, y=5, z=6))
# Define a class with overloaded methods
class MyClass(object):
@p.overload
def g(self, x=1):
return "called: def MyClass.g(x) with x={}".format(x)
@p.overload
def g(self, x=1, y=2):
return "called: def MyClass.g(x, y) with x={}, y={}".format(x, y)
# Instantiate an object
myobject = MyClass()
# Call the overloaded method
print(myobject.g())
print(myobject.g(1, 2))
</code></pre>
<p>When I run the <code>test_overload.py</code> script I get the following output:</p>
<pre class="lang-none prettyprint-override"><code>called: def f()
called: def f(x) with x=1
called: def f(x) with x=2
called: def f(y) with y=3
called: def f(*args, **kwargs) with args=(1, 2, 3), kwargs={'x': 4, 'y': 5, 'z': 6}
called: def MyClass.g(x) with x=1
called: def MyClass.g(x, y) with x=1, y=2
</code></pre>
<h2>Comments and Questions</h2>
<p>Am I overlooking anything important? Are there any counterintuitive behaviors or unexpected errors that this implementation might lead to? Are there any easily implementable features that I could add? I thought about trying to check for function collision when registering a function, i.e. checking to see if there are multiple functions that could be called for the same arguments. Right now I'm resolving this issue my just relying on the order in which the functions are registered, but maybe there's a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T06:25:17.640",
"Id": "390218",
"Score": "7",
"body": "Are you aware that this is already in the standard library since Python 3.4? It is called [`functools.singledispatch`](https://docs.python.org/3/library/functools.html#functools.... | [
{
"body": "<h3>funtools.singledispatch()</h3>\n<p>Take a look at the code for <code>functools.singledispatch()</code>. It's different in that it dispatches based on the type of the first argument. Look at how it wraps the first function with an object, so a separate controller object isn't needed. It also has... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T01:49:54.210",
"Id": "202491",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"meta-programming",
"polymorphism",
"overloading"
],
"Title": "Function overloading in Python"
} | 202491 |
<p>I'm doing some exercises in OOP and I just created a program that calculates amounts of denominations in a change at the shop. So, let's say something costs 10, I give 25.30 (for some reason), so I should get as a change: one 10, one 5, one 0.20, one 0.10.</p>
<p>When I started to create the program, I thought it would be nice if client of the ChangeCalculator had an option to specify his way of calculating the amounts - for example to use his own currency. That's why I created interfaces.</p>
<p>My program consists of:</p>
<ul>
<li>IChangeCalculator - represents change calculator</li>
<li>ChangeCalculatorPLN - implementation that returns MoneyAmountPLN (money denominations amounts in PLN currency)</li>
<li>IMoneyAmount - represents data about amounts of denominations</li>
<li>MoneyAmountPLN - represents money denominations amounts in PLN</li>
<li>IMoneyToCoinsConverter - represents converter that converts given money to something that implements IMoneyAmount</li>
<li>MoneyToCoinsConverterPLN - converts given amount of money to MoneyAmountPLN</li>
</ul>
<p>Here is the source code:</p>
<pre><code>public interface IChangeCalculator<T> where T : IMoneyAmount
{
T Calculate(decimal price, decimal payedAmount);
}
public class ChangeCalculatorPLN : IChangeCalculator<MoneyAmountPLN>
{
IMoneyToCoinsConverter<MoneyAmountPLN> _moneyToCoinsConverter;
public ChangeCalculatorPLN( IMoneyToCoinsConverter<MoneyAmountPLN> moneyToCoinsConverter )
{
_moneyToCoinsConverter = moneyToCoinsConverter;
}
public MoneyAmountPLN Calculate(decimal price, decimal payedAmount)
{
var change = payedAmount - price;
if (change < 0)
throw new Exception("The given amount of money is not enough!");
if (change == 0)
return MoneyAmountPLN.Empty;
var amount = GetAmount(change);
return amount;
}
private MoneyAmountPLN GetAmount(decimal change)
{
return _moneyToCoinsConverter.Convert(change);
}
}
public interface IMoneyAmount
{
IEnumerable<int> GetAmounts( );
}
//MoneyAmountPLN is quite long, because it contains fields for each denomination: 500, 200, 100, 50, 20, 10, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01. I'll not put it here.
public interface IMoneyToCoinsConverter<T> where T : IMoneyAmount
{
T Convert(decimal money);
}
public class MoneyToCoinsConverterPLN : IMoneyToCoinsConverter<MoneyAmountPLN>
{
public MoneyAmountPLN Convert(decimal money)
{
//logic doesn't really matter here. It returns MoneyAmountPLN with corrects amounts of denominations.
}
}
</code></pre>
<p>The program works, I did some unit tests. My real issue is that I'm not sure if this implementation is a good one. Did I do some mistakes? Could some parts be done better? Personally I think that maybe the structure is a little too complicated? If I saw a program like this for the first time, I would probably feel lost, but I'm not a very good programmer, so I can't say if my feeling is right.
Adding new currency requires creation of new classes that implement: IChangeCalculator, IMoneyAmount, IMoneyToCoinsConverter.
I think that this is too much. I think that ChangeCalculator shouldn't need to be reimplemented for each new currency, but I didn't know how to do that, since each currency requires different IMoneyAmount implementation. Calculate method of ChangeCalculator needs to know what type of IMoneyAmount it returns.</p>
<p>Please provide constructive feedback, it would be great to hear any of your advices.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T17:29:15.750",
"Id": "390279",
"Score": "0",
"body": "Confusing to me. I am not seeing where is actually makes change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T12:06:28.003",
"Id": "390353... | [
{
"body": "<p>The main problem with your code is that you've been encoding currency denomination data in C#'s type system: one type for each currency. That somehow led to a complicated interface/generics design, all without providing any real benefits. In fact, this design has several drawbacks:</p>\n\n<ul>\n<l... | {
"AcceptedAnswerId": "202615",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T08:45:51.733",
"Id": "202502",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
".net",
"interface"
],
"Title": "ChangeCalculator for calculating money denominations in change"
} | 202502 |
<p>I wrote some code to do regularised linear regression and it works, but I don't like the fact that I've had to double call the functions when plotting, nor the fact that I've sliced those calls to get the parts that I want.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def fit(phi_fn, xx, yy):
w_fit = np.linalg.lstsq(phi_fn(xx), yy, rcond=None)[0]
grid_size = 0.01
x_grid = np.arange(0,9,grid_size)[:,None]
f_grid = np.matmul(phi_fn(x_grid),w_fit)
return(x_grid, f_grid)
def fitreg(phi_fn, xx, yy,lamb):
yy = np.pad(yy,(0,8),'constant',constant_values=0)
zz = np.concatenate((phi_fn(xx),lamb*np.identity(8)),axis=0)
w_fit = np.linalg.lstsq(zz, yy, rcond=None)[0]
grid_size = 0.01
x_grid = np.arange(0,9,grid_size)[:,None]
f_grid = np.matmul(phi_fn(x_grid),w_fit)
return(x_grid, f_grid)
def phi_poly(xx):
return np.concatenate([np.ones((xx.shape[0],1)), xx,xx**2,xx**3,xx**4,xx**5,xx**6,xx**7], axis=1)
D = 1
N = 10
mu = np.array([0,1,2,3,4,5,6,7,8,9])
xx = np.tile(mu[:,None], (1, D)) + 0.01*np.random.randn(N, D)
yy = 2*xx + 2*np.random.randn(N,D)
plt.clf()
plt.plot(xx,yy,'kx')
plt.plot(fit(phi_poly, xx, yy)[0], fit(phi_poly, xx, yy)[1], 'b-')
plt.plot(fitreg(phi_poly, xx, yy,1)[0], fitreg(phi_poly, xx, yy,1)[1][:,0], 'r-')
plt.plot(fitreg(phi_poly, xx, yy,10)[0], fitreg(phi_poly, xx, yy,10)[1][:,0], 'g-')
plt.plot(fitreg(phi_poly, xx, yy,0.1)[0], fitreg(phi_poly, xx, yy,0.1)[1][:,0], 'y-')
plt.show()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T11:39:04.647",
"Id": "390247",
"Score": "0",
"body": "Did you test the code with the values you posted? When trying to run it, I currently get a `TypeError: must be real number, not NoneType` in the call to `np.linalg.lstsq`."
},
... | [
{
"body": "<p>You can get rid of some of the repetition using a <code>for</code> loop looping over the lambdas and colors and using tuple assignment to at least get rid of one level of having to use indexing as well as the necessity of having to call <code>fitreg</code> twice for each plot:</p>\n\n<pre><code>if... | {
"AcceptedAnswerId": "202510",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T10:43:55.657",
"Id": "202507",
"Score": "2",
"Tags": [
"python",
"numpy",
"statistics",
"matplotlib"
],
"Title": "Regularised regression code"
} | 202507 |
<p>This AjaxCompound is invoked every time when the user types a key for search or click to sort. It contains 1million data 10 distinct rows by compound name. It takes 1.1 minutes and return only 1-5 KB data to search (general and column specific) or sort or pagination. Any way to reduce the execution time? Any wrong practice that I should correct in following code?</p>
<pre><code>[OutputCache(Duration = 10, VaryByParam = "none")]
public ActionResult AjaxCompound(JQueryDataTableParamModel param)
{
IQueryable<Compound> allCompounds = _context.Compounds.GroupBy(x => x.CompoundName).Select(x => x.FirstOrDefault());
IEnumerable<Compound> filteredCompounds;
if (!string.IsNullOrEmpty(param.sSearch))
{
filteredCompounds = allCompounds
.Where(c => c.CompoundName.Contains(param.sSearch)
||
c.RI.Contains(param.sSearch)
||
c.MolecularWeight.Contains(param.sSearch)
||
c.MolecularFormula.Contains(param.sSearch)
);
}
else
{
filteredCompounds = allCompounds;
}
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
Func<Compound, string> orderingFunction = (c => sortColumnIndex == 1 ? c.CompoundName :
sortColumnIndex == 2 ? c.RI :
sortColumnIndex == 3 ? c.MolecularFormula :
c.MolecularWeight);
var name = Convert.ToString(Request["sSearch_1"]);
var rI = Convert.ToString(Request["sSearch_2"]);
var mW = Convert.ToString(Request["sSearch_4"]);
var mF = Convert.ToString(Request["sSearch_3"]);
//var areaPercent = Convert.ToString(Request["sSearch_6"]);
if (!string.IsNullOrEmpty(name))
{
filteredCompounds = filteredCompounds.Where(c => c.CompoundName.Contains(name));
}
if (!string.IsNullOrEmpty(rI))
{
filteredCompounds = filteredCompounds.Where(c => c.RI.Contains(rI));
}
if (!string.IsNullOrEmpty(mF))
{
filteredCompounds = filteredCompounds.Where(c => c.MolecularFormula.Contains(mF));
}
if (!string.IsNullOrEmpty(mW))
{
filteredCompounds = filteredCompounds.Where(c => c.MolecularWeight.Contains(mW));
}
//if (!string.IsNullOrEmpty(areaPercent))
//{
// filteredCompounds = filteredCompounds.Where(c => c.AreaPercent.Contains(areaPercent));
//}
var sortDirection = Request["sSortDir_0"];
if (sortDirection == "asc")
filteredCompounds = filteredCompounds.OrderBy(orderingFunction);
else
filteredCompounds = filteredCompounds.OrderByDescending(orderingFunction);
var displayedCompounds = filteredCompounds
.Skip(param.iDisplayStart)
.Take(param.iDisplayLength).ToList();
var result = from c in displayedCompounds
select new[] { c.PaperId, c.CompoundName, c.RI, c.MolecularWeight, c.MolecularFormula };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allCompounds.Count(),
iTotalDisplayRecords = filteredCompounds.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T20:04:21.060",
"Id": "390284",
"Score": "0",
"body": "The performance bottleneck is likely in the backend database rather than in the C# code. Have you measured the time it takes to perform just the database query?"
},
{
"Co... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T10:54:29.137",
"Id": "202508",
"Score": "2",
"Tags": [
"c#",
"performance",
"linq",
"asp.net-mvc-5",
"jquery-datatables"
],
"Title": "Handler for jQuery DataTable search with filters and pagination"
} | 202508 |
<p>I have this piece of code placed in ESI class. There is <code>switch</code> statement nested in a <code>try-catch</code> block and it feels simply wrong for me (I have a suspicion that I'm close to exception driven development). I'm looking forward to read your suggestions on how could I potentially improve this code.</p>
<pre><code>@PostConstruct
public void initialize() {
this.webTarget = this.client.target("http://demo1173642.mockable.io/");
}
public Message getMockMessage() {
Response response = null;
try {
response = this.webTarget.request().get();
switch (response.getStatusInfo().getFamily()) {
case SUCCESSFUL:
return response.readEntity(Message.class);
case SERVER_ERROR:
throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
Response.Status.BAD_GATEWAY);
default:
throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
}
} catch (Exception ex) {
logger.log(Level.WARNING, ErrorCode.UNEXPECTED_EXECPTION.getMessage(), ex);
if (response != null) {
response.close();
}
throw new InternalServerErrorException();
}
}
</code></pre>
| [] | [
{
"body": "<p>In fact, your error handling is quite messed up: in the cases for server error and default you throw an exception, which you immediately replace with a different exception in your own catch block. I don't think that's what you meant to do. Furthermore, you only close() the response object in the e... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T10:55:49.960",
"Id": "202509",
"Score": "0",
"Tags": [
"java"
],
"Title": "Handling response from another microservice"
} | 202509 |
<p>i am currently developing an application to use with Measurement or Generation Instruments like Power Meters, Functiongenerators and so on. As this is my very first Programming Project in General, I would like your help not running into OO Programming mishaps right in the beginning.</p>
<p>I have 3 Classes: Instrument -> PowerMeter -> Chroma66205, each containing a nested Class for either their Measurement or Generation Parameters (Like Voltage, Current and so on). Find the important bits of Code below.</p>
<pre><code>/// <summary>
/// General Class for all Instruments
/// </summary>
public abstract class Instrument : IDisposable
{
...
...
/// <summary>
/// Measurement Parameters for ALL Instruments
/// </summary>
public abstract class MeasurementParameter
{
public new string ToString { get; protected set; }
public string Description { get; protected set; }
protected MeasurementParameter(string toString, string description)
{
ToString = toString;
Description = description;
}
}
public abstract class GenerationParameter
{
public new string ToString { get; protected set; }
public string Description { get; protected set; }
protected GenerationParameter(string toString, string description)
{
ToString = toString;
Description = description;
}
}
}
public abstract class PowerMeter : Instrument
{
...
...
public abstract Dictionary<string, double> Measure(params Instrument.MeasurementParameter[] measurementParameters);
/// <summary>
/// Measurement Parameters unique to Power Meters
/// </summary>
public new class MeasurementParameter : Instrument.MeasurementParameter
{
/// <summary>
/// RMS Voltage
/// </summary>
public static readonly MeasurementParameter V = new MeasurementParameter("V", "RMS Voltage");
/// <summary>
/// RMS Current
/// </summary>
public static readonly MeasurementParameter I = new MeasurementParameter("I", "RMS Current");
/// <summary>
/// Active Power
/// </summary>
public static readonly MeasurementParameter W = new MeasurementParameter("W", "Active Power");
protected MeasurementParameter(string toString, string description):base(toString,description){}
}
}
/// <summary>
/// Specific Implementation of the Chroma66205 Power Meter
/// </summary>
public sealed class Chroma66205 : PowerMeter
{
...
...
public Dictionary<string, double> Measure(params Instrument.MeasurementParameter[] measurementParameters)
{
throw new NotImplementedException();
}
/// <summary>
/// Measurement Parameters Unique to the Chroma 66205
/// </summary>
public new class MeasurementParameter : PowerMeter.MeasurementParameter
{
/// <summary>
/// Positive Voltage Peak
/// </summary>
public static readonly MeasurementParameter VPKp = new MeasurementParameter("VPK+", "Positive Voltage Peak");
/// <summary>
/// Negative Voltage Peak
/// </summary>
public static readonly MeasurementParameter VPKn = new MeasurementParameter("VPK-", "Negative Voltage Peak");
/// <summary>
/// Total Harmonic Distortion of Voltage
/// </summary>
public static readonly MeasurementParameter THDV = new MeasurementParameter("THDV", "Total Harmonic Distortion of Voltage");
/// <summary>
/// Positive Current Peak
/// </summary>
public static readonly MeasurementParameter IPKp = new MeasurementParameter("IPK+", "Positive Current Peak");
/// <summary>
/// Negative Current Peak
/// </summary>
public static readonly MeasurementParameter IPKn = new MeasurementParameter("IPK-", "Negative Current Peak");
/// <summary>
/// IS?
/// </summary>
public static readonly MeasurementParameter IS = new MeasurementParameter("IS", "");
/// <summary>
/// Crest Factor Current
/// </summary>
public static readonly MeasurementParameter CFI = new MeasurementParameter("CFI", "Crest Factor Current");
/// <summary>
/// Total Harmonic Distortion of Current
/// </summary>
public static readonly MeasurementParameter THDI = new MeasurementParameter("THDI", "Total Harmonic Distortion of Current");
/// <summary>
/// Power Factor
/// </summary>
public static readonly MeasurementParameter PF = new MeasurementParameter("PF", "Power Factor");
/// <summary>
/// Apparent Power
/// </summary>
public static readonly MeasurementParameter VA = new MeasurementParameter("VA", "Apparent Power");
/// <summary>
/// Reactive Power
/// </summary>
public static readonly MeasurementParameter VAR = new MeasurementParameter("VAR", "Reactive Power");
/// <summary>
/// Watt-hour
/// </summary>
public static readonly MeasurementParameter WH = new MeasurementParameter("WH", "Watt-hour");
/// <summary>
/// Zero Crossing Frequency
/// </summary>
public static readonly MeasurementParameter FREQ = new MeasurementParameter("FREQ", "Frequency");
/// <summary>
/// Voltage DC Value
/// </summary>
public static readonly MeasurementParameter VDC = new MeasurementParameter("VDC", "Voltage DC Value");
/// <summary>
/// Current DC Value
/// </summary>
public static readonly MeasurementParameter IDC = new MeasurementParameter("IDC", "Current DC Value");
/// <summary>
/// Wattage DC Value
/// </summary>
public static readonly MeasurementParameter WDC = new MeasurementParameter("WDC", "Wattage DC Value");
/// <summary>
/// Mean Voltage
/// </summary>
public static readonly MeasurementParameter VMEAN = new MeasurementParameter("VMEAN", "Mean Voltage");
/// <summary>
/// Phase difference in degree
/// </summary>
public static readonly MeasurementParameter DEG = new MeasurementParameter("DEG", "Phase difference in degree");
/// <summary>
/// Crest Factor Voltage
/// </summary>
public static readonly MeasurementParameter CFV = new MeasurementParameter("CFV", "Crest Factor Voltage");
/// <summary>
/// Voltage Frequency
/// </summary>
public static readonly MeasurementParameter VHZ = new MeasurementParameter("VHZ", "Voltage Frequency");
/// <summary>
/// Current Frequency
/// </summary>
public static readonly MeasurementParameter IHZ = new MeasurementParameter("IHZ", "Current Frequency");
/// <summary>
/// Ampere Hours
/// </summary>
public static readonly MeasurementParameter AH = new MeasurementParameter("AH", "Ampere Hours");
MeasurementParameter(string toString, string description) : base(toString, description) { }
}
}
</code></pre>
<p>In my main Program Code a call to the Measure Method of the Chroma 66205 then Looks like this:</p>
<pre><code>using (Chroma66205 chroma66205 = new Chroma66205("TCPIP0::192.168.1.7::inst0::INSTR"))
{
chroma66205.Measure(
Chroma66205.MeasurementParameter.W,
Chroma66205.MeasurementParameter.V,
Chroma66205.MeasurementParameter.I,
Chroma66205.MeasurementParameter.THDV);
}
</code></pre>
<p>Where Voltage, Power and Current could also be called with PowerMeter.MeasurementParameter.*, but THDV is a Parameter Unique to the Chroma.</p>
<p>Is this considered bad practice and could it potentially fall on my feet in the future? If so, what would be the appropriate way to accomplish the way of Calling the Method like in my Main Program.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T08:04:45.680",
"Id": "390337",
"Score": "0",
"body": "Do you ever need to handle different instruments in a general fashion (`Instrument instrument = GetSomeKindOfInstrument(); instrument.Measure(...);`), or do you always use specif... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T11:34:39.287",
"Id": "202511",
"Score": "1",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Nested class hierarchy for scientific instruments"
} | 202511 |
<p>Is there more efficient, proper way, to write a function like this? The effect I want to achieve is to remove CSS classes in three steps, one after another.</p>
<pre><code>function loadColors(){
setTimeout(()=>{
document.querySelector('.class-1').classList.remove('class-x')
}, 0);
setTimeout(()=>{
document.querySelector('.class-2').classList.remove('class-z')
}, 100);
setTimeout(()=>{
document.querySelector('.class-3').classList.remove('class-y')
}, 200);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T14:01:27.907",
"Id": "390262",
"Score": "0",
"body": "Write a small library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T19:54:20.433",
"Id": "390281",
"Score": "2",
"body": "Welcome t... | [
{
"body": "<p>You can save the info in an array,then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\">Array.forEach()</a> to execute.</p>\n\n<pre><code>const timeoutPieces = [\n [\".class-1\", \"class-x\", 0],\n [\".... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T12:11:05.653",
"Id": "202513",
"Score": "-1",
"Tags": [
"javascript",
"dom"
],
"Title": "Chaining setTimeouts"
} | 202513 |
<p>The script will work through each number from 0 - 10.</p>
<pre><code>aList=[3,5,... over 10k numbers ...,2,2,6]
</code></pre>
<p>Let’s say, for example: <code>findSquence01=[3,5]</code> or <code>findSquence02=[3,5,3]</code></p>
<pre><code>count = 0
for i in range(len(data)-len(pattern)+1):
tmp = [data[i], data [i+1]]
try:
for j in range(len(data)-i):
print(i, i+j)
if tmp[-1] != data[i+j+1]:
tmp.append(data[i+j+1])
if len(tmp) == len(pattern):
print(tmp)
break
except:
pass
if tmp == pattern:
count +=1
</code></pre>
<blockquote>
<p>i- represents times of [3,5]</p>
<p>j- represents times of [3,5,3]</p>
</blockquote>
<pre><code>print("There is",i,"times",findSquence01)
print("There is",j,"times",findSquence02)
</code></pre>
<p>The output should look like:</p>
<blockquote>
<p>There is 73 times [3,5]</p>
<p>There is 12 times [3,5,3]</p>
</blockquote>
<p>How can I walk through the list and count those given sequences?</p>
| [] | [
{
"body": "<p>Try to keep your solution as general as possible. If I'm reading your code snippet right, you're trying to solve the problem for two patterns simultaneously. Instead, write a simple function that takes a list and a pattern, and just loops through the list counting occurrences of the pattern. This ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T14:12:51.793",
"Id": "202518",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"homework"
],
"Title": "Count occurrences of a specific sequence in a list of many numbers"
} | 202518 |
<p>I have written a game in which the user has to guess six numbers between 1 and 49. I want that my program gets checked in the following criteria:</p>
<ol>
<li><p>Does this program meet the requirements of object-oriented thinking and programming?</p></li>
<li><p>Did I have used the library of the Java language wisely or were parts of the program implemented more cumbersome than they must be?</p></li>
<li><p>Are I / O instructions in the right place?</p></li>
<li><p>Are there other things that are not mentioned here but can be improved?</p></li>
</ol>
<p><a href="https://repl.it/@Dexter1997/FullEducatedToolbox" rel="nofollow noreferrer">The program can be tested here.</a></p>
<p>Main.java</p>
<pre><code>public class Main {
public static void main(String[] args) {
Game game = new Game();
game.play();
}
}
</code></pre>
<p>Game.java</p>
<pre><code>import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class Game {
private Lottery lottery;
private List<Integer> guess;
private Integer guessedNumber;
private boolean inputAccepted;
private int rightNumbers;
private static Scanner scanner = new Scanner(System.in);
public Game() {
lottery = new Lottery();
guess = new ArrayList<Integer>();
guessedNumber = 0;
inputAccepted = false;
rightNumbers = 0;
}
public void play() {
System.out.println("You have to guess six numbers.\n");
guessNumbers();
compareGuess();
printScore();
}
private void guessNumbers() {
while (guess.size() < 6) {
System.out.print("Number nr." + (guess.size() + 1) + ": ");
String input = scanner.nextLine();
guessedNumber = Integer.valueOf(input);
checkInput();
if (inputAccepted) {
guess.add(guessedNumber);
}
}
System.out.println();
Collections.sort(guess);
}
// checks if input is valid
private void checkInput() {
inputAccepted = true;
// check if number is out of range
if (guessedNumber > 49 || guessedNumber < 1) {
System.out.println("You have to guess a number between 1 and 49.");
inputAccepted = false;
}
// check if number allready exists in list
for (int i = 0; i < guess.size(); i++) {
if (guess.get(i).equals(guessedNumber)) {
System.out.println("You allready have guessed this number");
inputAccepted = false;
break;
}
}
}
private void compareGuess() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (lottery.getDraw().get(i).equals(guess.get(j))) {
rightNumbers++;
}
}
}
}
private void printScore() {
System.out.println("Draw: " + lottery.getDraw());
System.out.println("Your guess: " + guess);
if (rightNumbers == 0) {
System.out.println("You have no right numbers.");
} else if (rightNumbers == 1) {
System.out.println("You have one right numbers.");
} else if (rightNumbers > 1) {
System.out.println("You have " + rightNumbers + " right numbers.");
}
}
}
</code></pre>
<p>Lottery.java</p>
<pre><code>import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class Lottery {
private static Random random = new Random();
private List<Integer> draw;
public Lottery() {
renewDraw();
}
public List<Integer> getDraw() {
return draw;
}
public void renewDraw() {
draw = new ArrayList<Integer>();
while (draw.size() < 6) {
Integer number = new Integer(random.nextInt(49) + 1);
boolean drawHasNumber = false;
for (int i = 0; i < draw.size(); i++) {
if (draw.get(i).equals(number)) {
drawHasNumber = true;
break;
}
}
if (!drawHasNumber) {
draw.add(number);
}
}
Collections.sort(draw);
}
public int compare(List<Integer> guess) {
int rightNumbers = 0;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (draw.get(i).equals(guess.get(j))) {
rightNumbers++;
}
}
}
return rightNumbers;
}
}
</code></pre>
| [] | [
{
"body": "<p>One quick suggestion would be to create an interface for the methods in Lottery and Game and implement those methods separately in each of the classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T20:27:11.260",
"Id": "3902... | {
"AcceptedAnswerId": "202528",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T17:04:14.250",
"Id": "202521",
"Score": "1",
"Tags": [
"java",
"game",
"random"
],
"Title": "Lottery in the command line"
} | 202521 |
<p>I need to count the number of substrings of <code>s</code> which contains both the strings <code>a</code> and <code>b</code>.</p>
<p>This is what I did till now:</p>
<pre><code>a = input().rstrip()
b = input().rstrip()
s = input().rstrip()
min_length = max(len(a), len(b))
n = len(s)
count = 0
for i in range(min_length, n+1):
for j in range(n+1-i):
temp = s[j:j+i]
if (a in temp) and (b in temp):
count += 1
print(count)
</code></pre>
<p>The above code works fine, but is slow. How can I optimise it?</p>
<p><strong>For example:</strong> </p>
<p><strong>Input:</strong></p>
<pre><code>ab
c
cabc
</code></pre>
<p><strong>Output</strong></p>
<pre><code>3
</code></pre>
<p>Substrings of <code>s</code>, which contains both <code>a</code> and <code>b</code> as substring are <code>cab</code> , <code>abc</code> and <code>cabc</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T19:55:37.337",
"Id": "390282",
"Score": "1",
"body": "You can improve your `min_length` by looking at the non-overlapping length of `a` and `b`, e.g. `len(a) + len(b) - overlap(a, b)` vs just the `max`."
},
{
"ContentLicense... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T19:38:44.743",
"Id": "202525",
"Score": "3",
"Tags": [
"python",
"strings"
],
"Title": "Count number of substrings which contains particular strings"
} | 202525 |
<p>I am finishing up an actor system (like those used in 90s games, like <em>Doom</em>, <em>Unreal</em>, etc.), which currently deals with damage and event handling.</p>
<p><strong>actor.cpp</strong></p>
<pre><code>/*
* Actor System
* (with Event System included)
*
* Author: Gustavo Ramos "Gustavo6046" Rehermann.
* (c)2018. The MIT License.
*
* This system basically allows the creation of
* Actors (entities), in a game world. This does
* not handle 3D coordinates nor collision. I
* have neither ideas nor time to implement those,
* so I hope someone will implement those on top
* of this code, either extending it or modifying it.
*
* For the sake of extensibility, actors aren't removed
* when they die. That task is here delegated to the
* upper levels.
*
* For an example of a possible extension:
*
* struct Vec3
* {
* int XYZ[3];
* }
*
* struct G_PhysicalActor
* {
* G_Actor* baseActor;
* Vec3 pos;
* int colCylinderRadius;
* int colCylinderHeight;
* // ...
* }
*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include "actor.h" // > structs
E_ActorEvent* E_BaseEvent = NULL; // > Master actor event linked list.
G_Actor* G_Actors = NULL; // > Master actor linked list.
unsigned int G_NumActors = 0;
// > This function shall append actor events
// to the master event linked list (I call
// this event notification).
void G_NotifyActorEvent(E_ActorEvent* evt)
{
evt->nextEvent = NULL;
if ( E_BaseEvent == NULL )
E_BaseEvent = evt;
else
{
E_ActorEvent* e = NULL;
for ( e = E_BaseEvent; e->nextEvent != NULL; e = e->nextEvent ); // > quick way to get
// the last event on
// the linked list :)
e->nextEvent = evt;
}
}
// > Returns the next actor event.
//
E_ActorEvent* G_PollActorEvent()
{
// > For the sake of while loop polling, we want
// to return NULL (0) when there is no event.
if ( !E_BaseEvent ) return NULL;
// > Since our linked list is like a queue, we want
// to take only the 1st event (FIFO), and the 2nd
// will become the 1st. Fortunately, this is very
// easy to do.
E_ActorEvent* res = E_BaseEvent;
E_BaseEvent = res->nextEvent;
return res;
}
// > Handle actor death (health being
// smaller than or equal to 0).
void G_Die(G_Actor* actor)
{
// > At the moment, all it does is notify an event.
// This may change.
E_ActorEvent* evt = new E_ActorEvent;
evt->eventType = AEV_DEATH;
evt->actor = actor;
G_NotifyActorEvent(evt);
}
// > Create an actor and append it to
// the master Actor linked list.
G_Actor* G_CreateActor(int health)
{
// > Initializes the actor.
G_Actor* a = new G_Actor;
_G_DamageTrack* dmg = new _G_DamageTrack;
dmg->health = health;
dmg->totalDamage = 0;
dmg->totalHeal = 0;
a->damage = *dmg;
a->index = G_NumActors;
char* estr = new char[1]; // allocate an empty string.
*estr = 0; // strings terminate with a null byte.
std::fill_n(a->damageFactor_K, 256, estr);
std::fill_n(a->damageFactor_V, 256, 1000);
// > Adds the actor to the list.
if ( G_Actors == NULL )
G_Actors = a;
else
{
// > Find last element on actor list, then append
// to it.
G_Actor* prev;
for ( prev = G_Actors; prev->nextActor != NULL; prev = prev->nextActor );
prev->nextActor = a;
}
// > Notify the actor's creation.
G_NumActors++;
E_ActorEvent* evt = new E_ActorEvent;
evt->eventType = AEV_CREATED;
evt->actor = a;
G_NotifyActorEvent(evt);
a->nextActor = NULL;
return a;
}
// > Removes this actor from the list, by address.
bool G_RemoveActor(G_Actor* actor)
{
G_Actor* a = NULL;
if ( G_Actors == actor )
{
G_Actors = NULL;
return true;
}
if ( G_Actors == NULL )
return false;
for ( a = G_Actors; a->nextActor != NULL && a->nextActor != actor; a = a->nextActor )
if ( a == NULL || a->nextActor == NULL )
return false;
if ( a->nextActor != NULL )
{
a->nextActor = a->nextActor->nextActor;
if ( a->nextActor != NULL )
for ( G_Actor* cur = a->nextActor; cur != NULL; cur = cur->nextActor )
cur->index--;
}
else
a->nextActor = NULL;
E_ActorEvent* evt = new E_ActorEvent;
evt->eventType = AEV_REMOVED;
evt->actor = actor;
G_NotifyActorEvent(evt); // > Notify the actor's removal.
return true;
}
// > Perform damage checks on the actor pointed. If
// the actor's health is smaller than 1 (it's not
// a floating point number, so we can safely assume
// that i < 1 is the same as i <= 0), we call the die
// routine on it.
//
// > For the sake of modifiability, this function exists;
// however, it is only an if statement with a call to
// G_Die.
void G_DamageCheck(G_Actor* actor)
{
if ( actor->damage.health < 1 )
G_Die(actor);
}
// > Deal damage to an actor, and handle damage factors
// (unless specified otherwise). Automatically calls
// the damage check function (kills actor if health is
// null or negative).
void G_TakeDamage(G_Actor* actor, char* damageType, int damage, bool checkFactors)
{
// > Apply damage factors.
if ( checkFactors && actor->damageFactor_K != NULL && actor->damageFactor_V != NULL )
for ( unsigned int i = 0; i < 256 && actor->damageFactor_K[i] != ""; i++ )
if ( std::strcmp(actor->damageFactor_K[i], damageType) == 0 )
damage = damage * actor->damageFactor_V[i] / 1000;
actor->damage.health -= damage;
// > Damage shall be tracked by other _G_DamageTrack
// members as well!
if ( damage < 0 )
actor->damage.totalHeal -= damage;
else
actor->damage.totalDamage += damage;
if ( damage > 0 )
{
E_ActorEvent* evt1 = new E_ActorEvent;
evt1->eventType = AEV_DAMAGE;
evt1->eventData = damage;
evt1->actor = actor;
G_NotifyActorEvent(evt1); // > Notify the actor's damage.
}
else
{
E_ActorEvent* evt1 = new E_ActorEvent;
evt1->eventType = AEV_HEAL;
evt1->eventData = -damage;
evt1->actor = actor;
G_NotifyActorEvent(evt1); // > Notify the actor's heal.
}
E_ActorEvent* evt1 = new E_ActorEvent;
evt1->eventType = AEV_MODHEALTH;
evt1->eventData = -damage;
evt1->actor = actor;
G_NotifyActorEvent(evt1); // > Notify any modification to the
// actor's physical integrity.
G_DamageCheck(actor);
}
</code></pre>
<p><strong>actor.h</strong></p>
<pre><code>#ifndef GUSTAVO_ACTORSYS_HEADER
#define GUSTAVO_ACTORSYS_HEADER
/*
* Actor System (header)
* (with Event System included)
*
* Author: Gustavo Ramos "Gustavo6046" Rehermann.
* (c)2018. The MIT License.
*
* This system basically allows the creation of
* Actors (entities), in a game world. This does
* not handle 3D coordinates nor collision. I
* have neither ideas nor time to implement those,
* so I hope someone will implement those on top
* of this code, either extending it or modifying it.
*
* For the sake of extensibility, actors aren't removed
* when they die. That task is here delegated to the
* upper levels.
*
* For an example of a possible extension:
*
* struct Vec3
* {
* int XYZ[3];
* }
*
* struct G_PhysicalActor
* {
* G_Actor* baseActor;
* Vec3 pos;
* int colCylinderRadius;
* int colCylinderHeight;
* // ...
* }
*/
#define AEV_DEATH 0 // > Surprise! This actor died!
#define AEV_DAMAGE 1 // > This actor took positive damage.
#define AEV_HEAL 2 // > This actor took negative damage (heal).
#define AEV_MODHEALTH 3 // > This actor's health was modified (by
// the G_TakeDamage function, most
// likely).
#define AEV_CREATED 4 // > This actor was newly created.
#define AEV_REMOVED 5 // > This actor was removed from the master linked list..
// > This structure will track the physical integrity
// of an actor. It is supported by standard functions,
// like G_TakeDamage.
struct _G_DamageTrack
{
int health; // > tracked actor's health
unsigned int totalDamage; // > tracked actor's total damage (scaled
// by damage factors)
unsigned int totalHeal; // > tracked actor's total heal (negative damage)
};
struct G_Actor
{
// char* name; // > actor's human name
// char* id; // > actor's unique identifier
unsigned int index; // > actor's G_Actors index + 1.
// If this is equal to 0, this actor
// should be assumed not to be in
// G_Actors.
_G_DamageTrack damage; // > keeps track of 'health' (physical
// integrity) and damage
char* damageFactor_K[256]; // > this actor's damage factor map's keys
int damageFactor_V[256]; // > this actor's damage factor map's values
G_Actor* nextActor; // > actors follow a linked list.
};
struct E_ActorEvent
{
unsigned char eventType; // > event's type (as defined in AEV_* constants)
int eventData; // > extra information about the event
G_Actor* actor; // > pointer to event's reference actor
E_ActorEvent* nextEvent; // > events, like actors, follow a linked list.
};
extern E_ActorEvent* E_BaseEvent; // > Master actor event linked list.
extern G_Actor* G_Actors; // > Master actor linked list.
extern unsigned int G_NumActors;
// > This function shall append actor events
// to the master event linked list (I call
// this event notification).
extern void G_NotifyActorEvent(E_ActorEvent* evt);
// > Returns the next actor event.
//
extern E_ActorEvent* G_PollActorEvent();
// > Handle actor death (health being
// smaller than or equal to 0).
extern void G_Die(G_Actor* actor);
// > Create an actor and append it to
// the master Actor linked list.
extern G_Actor* G_CreateActor(int health);
// > Perform damage checks on the actor pointed. If
// the actor's health is smaller than 1 (it's not
// a floating point number, so we can safely assume
// that i < 1 is the same as i <= 0), we call the die
// routine on it.
extern void G_DamageCheck(G_Actor* actor);
// > Deal damage to an actor, and handle damage factors
// (unless specified otherwise). Automatically calls
// the damage check function (kills actor if health is
// null or negative).
extern void G_TakeDamage(G_Actor* actor, char* damageType, int damage, bool checkFactors = true);
// > Removes this actor from the list, by address.
extern bool G_RemoveActor(G_Actor* actor);
#endif /* GUSTAVO_ACTORSYS_HEADER */
</code></pre>
<p>Below is a usage example/demo:</p>
<p><strong>actormain.cpp</strong></p>
<pre><code>/*
* Actor system usage example.
*
* Author: Gustavo Ramos "Gustavo6046" Rehermann.
* (c)2018. The MIT License.
*/
#include <iostream>
#include "actor.h"
int main()
{
G_Actor* myActor = G_CreateActor(80);
G_Actor* myActor2 = G_CreateActor(200);
myActor2->damageFactor_K[0] = "fire"; // Let's just say it's a dragon!
myActor2->damageFactor_V[0] = 100;
myActor2->damageFactor_K[1] = "default"; // And it has hard scales.
myActor2->damageFactor_V[1] = 575;
myActor2->damageFactor_K[2] = "water"; // But it hates water!
myActor2->damageFactor_V[2] = 2420;
std::cout << "Actor 0 address: " << myActor << "\n";
std::cout << "Actor 1 address: " << myActor2 << "\n";
std::cout << "Actor 0's initial health: " << myActor->damage.health << "\n";
std::cout << "Actor 1's initial health: " << myActor2->damage.health << "\n";
G_TakeDamage(myActor, "default", 30);
G_TakeDamage(myActor, "default", 40);
G_TakeDamage(myActor, "default", -30);
G_TakeDamage(myActor, "default", 100);
G_TakeDamage(myActor2, "fire", 314);
G_TakeDamage(myActor2, "default", 120);
G_TakeDamage(myActor2, "water", 90);
std::cout << "Actor 0's final health: " << myActor->damage.health << "\n";
std::cout << "Actor 1's final health: " << myActor2->damage.health << "\n";
G_RemoveActor(myActor);
std::cout << "Actor removed.\n";
E_ActorEvent* evt;
std::cout << "\n== EVENT LOG ==\n\n";
// Print every damage/death event notified in the meanwhile.
while ( evt = G_PollActorEvent() )
{
if ( evt->eventType == AEV_CREATED )
std::cout << "Actor " << evt->actor->index << " was created!\n";
if ( evt->eventType == AEV_DAMAGE )
std::cout << "Actor " << evt->actor->index << " took " << evt->eventData << "hp damage!\n";
else if ( evt->eventType == AEV_DEATH )
std::cout << "Actor " << evt->actor->index << " has died!\n";
else if ( evt->eventType == AEV_HEAL )
std::cout << "Actor " << evt->actor->index << " healed " << evt->eventData << "hp!\n";
else if ( evt->eventType == AEV_REMOVED )
std::cout << "Actor " << evt->actor->index << " was removed from the actor list.\n";
}
return 0;
}
</code></pre>
<p><strong>NOTE:</strong> This works when compiled with Open Watcom C++. Tell me if it doesn't work with your compiler!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T22:52:02.827",
"Id": "390299",
"Score": "0",
"body": "Any reason for _not_ using `std::list`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T03:57:29.033",
"Id": "390310",
"Score": "0",
"... | [
{
"body": "<p>Defining constants with #define is only ok in c. In C++ there are better alternatives. Consider using instead <code>const int</code> or an <code>enum</code> for the states instead of <code>#define</code> in C++98. </p>\n\n<p>If C++11 would be available you could even change the <code>#define</cod... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T20:46:49.043",
"Id": "202529",
"Score": "4",
"Tags": [
"c++",
"event-handling",
"actor",
"c++98"
],
"Title": "Simple C++98 actor system (with event system) - think Doom or Unreal"
} | 202529 |
<p>I am making a poker application in JavaFX. When I try to display the cards on the screen it is working perfectly fine. Yet I have a method with a lot of duplicated code in it. </p>
<p>I have tried to compress the code into 1 function with a for loop but I couldn't get it to work. Anyone has an idea how to get rid of the duplication?</p>
<pre><code>public class GameController implements Initializable {
@FXML
private Canvas canvasBoard;
@FXML
private Canvas canvasPlayer1;
@FXML
private Canvas canvasPlayer2;
@FXML
private Canvas canvasPlayer3;
@FXML
private Canvas canvasPlayer4;
private int playerCardsWidth1 = 0;
private int playerCardsWidth2 = 0;
private int playerCardsWidth3 = 0;
private int playerCardsWidth4 = 0;
private int dealerCardsWidth = 0;
private TexasHoldem game;
private IPlayer board;
public GameController() {
try {
game = new TexasHoldem();
} catch (Exception e) {
e.printStackTrace();
}
}
private void showCardsBoard() {
board = game.getBoard();
dealerCardsWidth += 50;
for (ICard c : board.getCards()) {
String foto = c.getFilename();
Image image = new Image(foto);
GraphicsContext gcBoard = canvasBoard.getGraphicsContext2D();
int dealerCardsHeight = 0;
gcBoard.drawImage(image,dealerCardsWidth, dealerCardsHeight,60,80);
dealerCardsWidth += 75;
}
}
private void showCardsPlayers() {
List<IPlayer> spelers = game.getPlayers();
for (int i = 0; i < spelers.size(); i++) {
if (i == 0) {
IPlayer player1 = spelers.get(i);
for (ICard c : player1.getCards()) {
Image image = new Image(c.getFilename());
GraphicsContext gc1 = canvasPlayer1.getGraphicsContext2D();
int playerCardsHeight1 = 0;
gc1.drawImage(image, playerCardsWidth1, playerCardsHeight1, 60, 80);
playerCardsWidth1 += 75;
}
}
if (i == 1) {
IPlayer player2 = spelers.get(i);
for (ICard c : player2.getCards()) {
Image image = new Image(c.getFilename());
GraphicsContext gc2 = canvasPlayer2.getGraphicsContext2D();
int playerCardsHeight2 = 0;
gc2.drawImage(image, playerCardsWidth2, playerCardsHeight2, 60, 80);
playerCardsWidth2 += 75;
}
}
if (i == 2) {
IPlayer player3 = spelers.get(i);
for (ICard c : player3.getCards()) {
Image image = new Image(c.getFilename());
GraphicsContext gc3 = canvasPlayer3.getGraphicsContext2D();
int playerCardsHeight3 = 0;
gc3.drawImage(image, playerCardsWidth3, playerCardsHeight3, 60, 80);
playerCardsWidth3 += 75;
}
}
if (i == 3) {
IPlayer player4 = spelers.get(i);
for (ICard c : player4.getCards()) {
Image image = new Image(c.getFilename());
GraphicsContext gc4 = canvasPlayer4.getGraphicsContext2D();
int playerCardsHeight4 = 0;
gc4.drawImage(image, playerCardsWidth4, playerCardsHeight4, 60, 80);
playerCardsWidth4 += 75;
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p><strong>Logic</strong>: </p>\n\n<p>If statements differs only in 2 variables: <strong>canvasPlayerX</strong> and <strong>playerCardsWidthX</strong>. </p>\n\n<p><strong>playerCardsWidthX</strong>: looks like this var can be converted to local, just like playerCardsHeightX;</p>\n\n<p><strong>canvasP... | {
"AcceptedAnswerId": "202601",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T21:18:15.903",
"Id": "202531",
"Score": "1",
"Tags": [
"java",
"playing-cards",
"controller",
"javafx"
],
"Title": "JavaFX controller for a poker game"
} | 202531 |
<p>I am trying to make a multi choice quiz with a score to count. This is the first time I've used Python and I'm finding it difficult to make the code work properly. How can I make the code shorter and work better? It tells me my code has an infinite loop, how is that so?</p>
<pre><code>#Convert the 0 into a number so we can add scores
score = 0
score = int(score)
#Ask user for their name
name = input("What is your name?")
name = name.title()
print("""Hello {}, welcome to Quiz night!
You will be presented with 5 questions.
Enter the appropriate number to answer the question
Good luck!""".format(name))
#Question1
print("""What is the term for ‘Maori’ language?
1. Te Rex
2. Hangi
3. Hongu
4. Te Reo""")
answer1 = "4"
response1 = input("Your answer is:")
if (response1 != answer1):
print("Sorry, that is incorrect!")
else:
print("Well done! " + response1 + " is correct!")
score = score + 1
print("Your current score is " + str(score) + " out of 5")
#Question2
print("""What is the Maori term for ‘tribe’ or ‘mob’?
1. Mihi
2. Iwi
3. Awi
4. Hapu""")
answer2 = "2"
response2 = input("Your answer is:")
if (response2 != answer2):
print("Sorry, that is incorrect!")
else:
print("Well done! " + response2 + " is correct!")
score = score + 1
print("Your current score is " + str(score) + " out of 5")
#Question3
print("""What is the term for the formal welcome, where two individuals press their nose together?
1. Hongi
2. Haka
3. Hangi
4. Huka""")
answer3 = "1"
response3 = input("Your answer is:")
if (response3 != answer3):
print("Sorry, that is incorrect!")
else:
print("Well done! " + response3 + " is correct!")
score = score + 1
print("Your current score is " + str(score) + " out of 5")
#Question4
print("""Who is the ‘demi-god’ or the ‘great creator’ who fished NZ out from the sea?
1. Zeus
2. Hercules
3. Maui
4. Maori""")
answer4 = "3"
response4 = input("Your answer is:")
if (response4 != answer4):
print("Sorry, that is incorrect!")
else:
print("Well done! " + response4 + " is correct!")
score = score + 1
print("Your current score is " + str(score) + " out of 5")
#Question5
print("""What is the name for the traditional Maori method of cooking?
1. Roast
2. Hangi
3. Hongi
4. Bake""")
answer5 = "2"
response5 = input("Your answer is:")
if (response5 != answer5):
print("Sorry, that is incorrect!")
else:
print("Well done! " + response5 + " is correct!")
score = score + 1
print("Your total score is " + str(score) + " out of 5")
print("Thank you for playing {}, goodbye!".format(name))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T22:21:17.337",
"Id": "390297",
"Score": "1",
"body": "Who is telling to that you have an infinite loop? You haven't even written any loop."
}
] | [
{
"body": "<p>The biggest gain in readability here is to get rid of the duplication. Currently all your strings are hardcoded and you print each of them separately.</p>\n\n<p>We can make life easier by putting the questions, answers and correct answers into some datastructure we can iterate over. In addition, w... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T21:27:42.433",
"Id": "202532",
"Score": "1",
"Tags": [
"python",
"beginner",
"quiz"
],
"Title": "Python Multi Choice Quiz with a score to count"
} | 202532 |
<p>I created an algorithm that match roots of two texts, a question and a paragraph made of sentences. I aim at predicting in which sentence it exists the answer of a question. Yet It seems that I really complicated it. Do you know if I can improve it ? It is important as far as I apply it to a big file then.</p>
<pre><code>import numpy as np, pandas as pd
# Break the paragraph/context into multiple sentences.
import spacy
en_nlp = spacy.load('en')
# synonyms
from itertools import chain
from nltk.corpus import wordnet
# stemmer/ root maker
from nltk.stem.lancaster import LancasterStemmer
st = LancasterStemmer()
# to evaluate literal expressions (sorry, I know it might not mean anything ...)
import ast
def match_roots(x):
# we flatten the question
question = x["question"].lower()
# We get the sentences of the question in seperated words
sentences = en_nlp(x["context"].lower()).sents
# taking anything that look like a root in the question, not just the dominating one
question_roots = [chunk.root.head.text.lower() for chunk in en_nlp(question).noun_chunks]
# Attempt of using synonyms
synonyms = []
for word in set(question_roots):
words = []
words = wordnet.synsets(word)
for synset in words:
name = synset.lemmas()[0].name()
synonyms.append(st.stem(name))
question_roots.extend(synonym for synonym in set(synonyms))
# end of attempt
li = []
# Here we prepare the ranking list
ranking_list = []
# for each sentence of a bunch of sentences
for i,sent in enumerate(sentences):
# we store the roots of a sentence
roots = [st.stem(chunk.root.head.text.lower()) for chunk in sent.noun_chunks]
common_roots = []
if sum(1 for root in roots if root in question_roots)>0:
# Here we score
common_roots = [root for root in roots if root in question_roots]
for k,item in enumerate(ast.literal_eval(x["sentences"])):
if str(sent) in item.lower():
li.append(k)
ranking_list.append((len(common_roots),i))
return [max(ranking_list,key=lambda item:item[0])[1]]
</code></pre>
<p>The input can be :</p>
<pre class="lang-none prettyprint-override"><code>>>>predicted["question"][0]
What role did Beyoncé have in Destiny's Child?
>>>predicted["context"][0]
'Beyoncé Giselle Knowles-Carter (/biːˈjɒnseɪ/ bee-YON-say) (born September 4, 1981) is an American singer, songwriter, record producer and actress. Born and raised in Houston, Texas, she performed in various singing and dancing competitions as a child, and rose to fame in the late 1990s as lead singer of R&B girl-group Destiny\'s Child. Managed by her father, Mathew Knowles, the group became one of the world\'s best-selling girl groups of all time. Their hiatus saw the release of Beyoncé\'s debut album, Dangerously in Love (2003), which established her as a solo artist worldwide, earned five Grammy Awards and featured the Billboard Hot 100 number-one singles "Crazy in Love" and "Baby Boy".'
</code></pre>
<p>The output would be 1. The sentence at rank 1 (the second sentence would be elected as the one containing the answer).</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T22:18:31.707",
"Id": "390296",
"Score": "0",
"body": "Please provide some context for your code. Are there some missing function definitions or `import` statements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate":... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T21:54:05.663",
"Id": "202533",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"natural-language-processing"
],
"Title": "Function for root matching between two paragraphs"
} | 202533 |
<p>I have a data object like that:</p>
<pre><code>const data = {
"id": ["1", "2", "3"],
"name": ["foo", "bar", "baz"],
"age": [20, 30, 40 ],
"location": ["pluto", "mars", "jupiter"],
};
</code></pre>
<p>Those properties are matched in the array order. I need to create an array which holds all the items like:</p>
<pre><code>[
{ id: '1', name: 'foo', age: 20, location: 'pluto' },
{ id: '2', name: 'bar', age: 30, location: 'mars' },
{ id: '3', name: 'baz', age: 40, location: 'jupiter' }
]
</code></pre>
<p>I tried many things including <code>reduce</code> but can't get a decent way of doing this. Here is how I'm creating this result:</p>
<pre><code>let item = {};
let items = [];
const length = Object.values( data)[0].length;
for( i = 0; i < length; i++) {
Object.entries( data ).forEach( ( [key,value] ) =>
item = { ...item, [key]: value[i] }
);
items = [ ...items, item ];
}
</code></pre>
<p>But, the way that I am getting the length, using a <code>for</code> loop really bothers me.</p>
| [] | [
{
"body": "<p>Try this code:</p>\n\n<pre><code>function transformObject(data) {\n const values = Object.values(data);\n const keys = Object.keys(data);\n const transposed = values[0].map((col, i) => values.map(row => row[i]));\n return transposed.map(itemArr => keys.reduce((acc, key, i) => ({...... | {
"AcceptedAnswerId": "202542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T22:57:28.677",
"Id": "202538",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Extracting matched items from an object which has properties of arrays"
} | 202538 |
<p>I am reading a text, that from a higher level explained adjacency list implementation of a graph.</p>
<p>I have now tried to implement this as simply as I could. I did not see any reason to have an actual vertex or node class.</p>
<p>Based on my implementation, does it look like I understood properly how an adjacency list graph works?</p>
<pre><code>import java.util.*;
public class Graph {
private HashMap<String, HashSet<String>> nodes;
public Graph ()
{
nodes = new HashMap<String, HashSet<String>>();
}
public void addNode(String name)
{
if (!nodes.containsKey(name))
nodes.put(name , new HashSet<String>());
}
public void addEdge(String src , String dest)
{
HashSet<String> adjList = nodes.get(src);
if (adjList == null)
throw new RuntimeException("addEdge - src node does not exist");
adjList.add(dest);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T07:39:59.640",
"Id": "390332",
"Score": "1",
"body": "Can you include a `main()` that exercises this code? It's not obvious how you can use the generated graph."
}
] | [
{
"body": "<p>I think the code is incomplete. It's possible to build a <code>Graph</code> but there is no way to process it as there are no methods returning the state of a <code>Graph</code>.</p>\n\n<p>To be able to evaluate the shown code I'm going to extend it by two methods:</p>\n\n<pre><code>/**\n * Return... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T23:50:16.987",
"Id": "202540",
"Score": "2",
"Tags": [
"java",
"graph"
],
"Title": "Adjacency list graph in Java"
} | 202540 |
<p>This program estimates the likelihood for a string to belong to a certain natural language by computing the cosine similarity between an input string's and several natural languages' letter frequency, and it allows the storage of a prediction as a list in a .txt file.
I would like to know whether improvements (both formal and functional) are possible. My experience with programming is pretty limited, even though I've been programming intermittently for a couple of years now.</p>
<p>Here's the code:</p>
<pre><code>import time
import string
import os
from scipy import spatial
baseDict = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0, "i":0, "j":0, "k":0, "l":0, "m":0, "n":0, "o":0, "p":0, "q":0, "r":0, "s":0, "t":0, "u":0, "v":0, "w":0, "x":0, "y":0, "z":0}
baseChars = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "à", "â", "á", "å", "ä", "ã", "ą", "æ", "œ", "ç", "ĉ", "ć", "č", "ď", "ð", "è", "é", "ê", "ë", "ę", "ě", "ĝ", "ğ", "ĥ", "î", "ì", "í", "ï", "ı", "ĵ", "ł", "ñ", "ń", "ň", "ò", "ö", "ô", "ó", "õ", "ø", "ř", "ŝ", "ş", "ś", "š", "ß", "ť", "þ", "ù", "ú", "û", "ŭ", "ü", "ů", "ý", "ź", "ż", "ž"]
dictEN = {"a":8.167, "b":1.492, "c":2.782, "d":4.253, "e":12.702, "f":2.228, "g":2.015, "h":6.094, "i":6.966, "j":0.153, "k":0.772, "l":4.025, "m":2.406, "n":6.749, "o":7.507, "p":1.929, "q":0.095, "r":5.987, "s":6.327, "t":9.056, "u":2.758, "v":0.978, "w":2.36, "x":0.15, "y":1.974, "z":0.074, "à":0, "â":0, "á":0, "å":0, "ä":0, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0, "ô":0, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictFR = {"a":7.636, "b":0.901, "c":3.26, "d":3.669, "e":14.715, "f":1.066, "g":0.866, "h":0.737, "i":7.529, "j":0.613, "k":0.049, "l":5.456, "m":2.968, "n":7.095, "o":5.796, "p":2.521, "q":1.362, "r":6.693, "s":7.948, "t":7.244, "u":6.311, "v":1.838, "w":0.074, "x":0.427, "y":0.128, "z":0.326, "à":0.486, "â":0.051, "á":0, "å":0, "ä":0, "ã":0, "ą":0, "æ":0, "œ":0.018, "ç":0.085, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0.271, "é":1.504, "ê":0.218, "ë":0.008, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0.045, "ì":0, "í":0, "ï":0.005, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0, "ô":0.023, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0.058, "ú":0, "û":0.06, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictDE = {"a":6.516, "b":1.886, "c":2.732, "d":5.076, "e":16.396, "f":1.656, "g":3.009, "h":4.577, "i":6.55, "j":0.268, "k":1.417, "l":3.437, "m":2.534, "n":9.776, "o":2.594, "p":0.67, "q":0.018, "r":7.003, "s":7.27, "t":6.154, "u":4.166, "v":0.846, "w":1.921, "x":0.034, "y":0.039, "z":1.134, "à":0, "â":0, "á":0, "å":0, "ä":0.578, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0.443, "ô":0, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0.307, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":0.995, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictES = {"a":11.525, "b":2.215, "c":4.019, "d":5.01, "e":12.181, "f":0.692, "g":1.768, "h":0.703, "i":6.247, "j":0.493, "k":0.011, "l":4.967, "m":3.157, "n":6.712, "o":8.683, "p":2.51, "q":0.877, "r":6.871, "s":7.977, "t":4.632, "u":2.927, "v":1.138, "w":0.017, "x":0.215, "y":1.008, "z":0.467, "à":0, "â":0, "á":0.502, "å":0, "ä":0, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0.433, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0.725, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0.311, "ń":0, "ň":0, "ò":0, "ö":0, "ô":0, "ó":0.827, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0.168, "û":0, "ŭ":0, "ü":0.012, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictPT = {"a":14.634, "b":1.043, "c":3.882, "d":4.992, "e":12.57, "f":1.023, "g":1.303, "h":0.781, "i":6.186, "j":0.397, "k":0.015, "l":2.779, "m":4.738, "n":4.446, "o":9.735, "p":2.523, "q":1.204, "r":6.53, "s":6.805, "t":4.336, "u":3.639, "v":1.575, "w":0.037, "x":0.253, "y":0.006, "z":0.47, "à":0.072, "â":0.562, "á":0.118, "å":0, "ä":0, "ã":0.733, "ą":0, "æ":0, "œ":0, "ç":0.53, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0.337, "ê":0.45, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0.132, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0, "ô":0.635, "ó":0.296, "õ":0.04, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0.207, "û":0, "ŭ":0, "ü":0.026, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictIT = {"a":11.745, "b":0.927, "c":4.501, "d":3.736, "e":11.792, "f":1.163, "g":1.644, "h":0.636, "i":10.143, "j":0.011, "k":0.009, "l":6.51, "m":2.512, "n":6.883, "o":9.832, "p":3.056, "q":0.505, "r":6.367, "s":4.981, "t":5.623, "u":3.011, "v":2.097, "w":0.033, "x":0.003, "y":0.02, "z":1.181, "à":0.635, "â":0, "á":0, "å":0, "ä":0, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0.263, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0.03, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0.002, "ö":0, "ô":0, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0.166, "ú":0, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictTK = {"a":12.92, "b":2.844, "c":1.463, "d":5.206, "e":9.912, "f":0.461, "g":1.253, "h":1.212, "i":9.6, "j":0.034, "k":5.683, "l":5.922, "m":3.752, "n":7.987, "o":2.976, "p":0.886, "q":0, "r":7.722, "s":3.014, "t":3.314, "u":3.235, "v":0.959, "w":0, "x":0, "y":3.336, "z":1.5, "à":0, "â":0, "á":0, "å":0, "ä":0, "ã":0, "ą":0, "æ":0, "œ":0, "ç":1.156, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":1.125, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":5.114, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0.777, "ô":0, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":1.78, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":1.854, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictSW = {"a":9.383, "b":1.535, "c":1.486, "d":4.702, "e":10.149, "f":2.027, "g":2.862, "h":2.09, "i":5.817, "j":0.614, "k":3.14, "l":5.275, "m":3.471, "n":8.542, "o":4.482, "p":1.839, "q":0.02, "r":8.431, "s":6.59, "t":7.691, "u":1.919, "v":2.415, "w":0.142, "x":0.159, "y":0.708, "z":0.07, "à":0, "â":0, "á":0, "å":1.338, "ä":1.797, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":1.305, "ô":0, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictPL = {"a":10.503, "b":1.74, "c":3.895, "d":3.725, "e":7.352, "f":0.143, "g":1.731, "h":1.015, "i":8.328, "j":1.836, "k":2.753, "l":2.564, "m":2.515, "n":6.237, "o":6.667, "p":2.445, "q":0, "r":5.243, "s":5.224, "t":2.475, "u":2.062, "v":0.012, "w":5.813, "x":0.004, "y":3.206, "z":4.852, "à":0, "â":0, "á":0, "å":0, "ä":0, "ã":0, "ą":0.699, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0.743, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":1.035, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":2.109, "ñ":0, "ń":0.362, "ň":0, "ò":0, "ö":0, "ô":0, "ó":1.141, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0.814, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0.078, "ż":0.706, "ž":0}
dictNL = {"a":7.486, "b":1.584, "c":1.242, "d":5.933, "e":18.91, "f":0.805, "g":3.403, "h":2.38, "i":6.499, "j":1.46, "k":2.248, "l":3.568, "m":2.213, "n":10.032, "o":6.063, "p":1.57, "q":0.009, "r":6.411, "s":3.73, "t":6.79, "u":1.99, "v":2.85, "w":1.52, "x":0.036, "y":0.035, "z":1.39, "à":0, "â":0, "á":0, "å":0, "ä":0, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0, "ô":0, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictDK = {"a":6.025, "b":2, "c":0.565, "d":5.858, "e":15.453, "f":2.406, "g":4.077, "h":1.621, "i":6, "j":0.73, "k":3.395, "l":5.229, "m":3.237, "n":7.24, "o":4.636, "p":1.756, "q":0.007, "r":8.956, "s":5.805, "t":6.862, "u":1.979, "v":2.332, "w":0.069, "x":0.028, "y":0.698, "z":0.034, "à":0, "â":0, "á":0, "å":1.19, "ä":0, "ã":0, "ą":0, "æ":0.872, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0, "ô":0, "ó":0, "õ":0, "ø":0.939, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictIS = {"a":10.11, "b":1.043, "c":0, "d":1.575, "e":6.418, "f":3.013, "g":4.241, "h":1.871, "i":7.578, "j":1.144, "k":3.314, "l":4.532, "m":4.041, "n":7.711, "o":2.166, "p":0.789, "q":0, "r":8.581, "s":5.63, "t":4.953, "u":4.562, "v":2.437, "w":0, "x":0.046, "y":0.9, "z":0, "à":0, "â":0, "á":1.799, "å":0, "ä":0, "ã":0, "ą":0, "æ":0.867, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":4.393, "è":0, "é":0.647, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":1.57, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0.777, "ô":0, "ó":0.994, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":1.455, "ù":0, "ú":0.613, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0.228, "ź":0, "ż":0, "ž":0}
dictFI = {"a":12.217, "b":0.281, "c":0.281, "d":1.043, "e":7.968, "f":0.194, "g":0.392, "h":1.851, "i":10.817, "j":2.042, "k":4.973, "l":5.761, "m":3.202, "n":8.826, "o":5.614, "p":1.842, "q":0.013, "r":2.872, "s":7.862, "t":8.75, "u":5.008, "v":2.25, "w":0.094, "x":0.031, "y":1.745, "z":0.051, "à":0, "â":0, "á":0, "å":0.003, "ä":3.577, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0, "ď":0, "ð":0, "è":0, "é":0, "ê":0, "ë":0, "ę":0, "ě":0, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":0, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0, "ò":0, "ö":0.444, "ô":0, "ó":0, "õ":0, "ø":0, "ř":0, "ŝ":0, "ş":0, "ś":0, "š":0, "ß":0, "ť":0, "þ":0, "ù":0, "ú":0, "û":0, "ŭ":0, "ü":0, "ů":0, "ý":0, "ź":0, "ż":0, "ž":0}
dictCZ = {"a":8.421, "b":0.822, "c":0.74, "d":3.475, "e":7.562, "f":0.084, "g":0.092, "h":1.356, "i":6.073, "j":1.433, "k":2.894, "l":3.802, "m":2.446, "n":6.468, "o":6.695, "p":1.906, "q":0.001, "r":4.799, "s":5.212, "t":5.727, "u":2.16, "v":5.344, "w":0.016, "x":0.027, "y":1.043, "z":1.503, "à":0, "â":0, "á":0.867, "å":0, "ä":0, "ã":0, "ą":0, "æ":0, "œ":0, "ç":0, "ĉ":0, "ć":0, "č":0.462, "ď":0.015, "ð":0, "è":0, "é":0.633, "ê":0, "ë":0, "ę":0, "ě":1.222, "ĝ":0, "ğ":0, "ĥ":0, "î":0, "ì":0, "í":1.643, "ï":0, "ı":0, "ĵ":0, "ł":0, "ñ":0, "ń":0, "ň":0.007, "ò":0, "ö":0, "ô":0, "ó":0.024, "õ":0, "ø":0, "ř":0.38, "ŝ":0, "ş":0, "ś":0, "š":0.688, "ß":0, "ť":0.006, "þ":0, "ù":0, "ú":0.045, "û":0, "ŭ":0, "ü":0, "ů":0.204, "ý":0.995, "ź":0, "ż":0, "ž":0.721}
freqEN = list(dictEN.values())
freqFR = list(dictFR.values())
freqDE = list(dictDE.values())
freqES = list(dictES.values())
freqPT = list(dictPT.values())
freqIT = list(dictIT.values())
freqTK = list(dictTK.values())
freqSW = list(dictSW.values())
freqPL = list(dictPL.values())
freqNL = list(dictNL.values())
freqDK = list(dictDK.values())
freqIS = list(dictIS.values())
freqFI = list(dictFI.values())
freqCZ = list(dictCZ.values())
freqList = [freqEN, freqFR, freqDE, freqES, freqPT, freqIT, freqTK, freqSW, freqPL, freqNL, freqDK, freqIS, freqFI, freqCZ]
langDict = {"EN: ":0,"FR: ":0, "DE: ":0, "ES: ":0, "PT: ":0, "IT: ":0, "TK: ":0, "SW: ":0, "PL: ":0, "NL: ":0, "DK: ":0, "IS: ":0, "FI: ":0, "CZ: ":0}
langNames = list(langDict.keys())
def detectLang(s):
freqText = []
cosines = []
#String preprocessing: removing punctuation, whitespace, and digits
s = s.lower()
s = ''.join([i for i in s if i not in string.punctuation and i not in string.whitespace and i not in string.digits])
#Count every instance of a letter in the input string, then estimate frequency
for i in baseChars:
j = s.count(i)
freqText.append((j*100)/len(s))
#Calculate cosine similarity between input string's and each language's letter frequency
for i in range(len(freqList)):
langDict[langNames[i]] = 1-spatial.distance.cosine(freqList[i], freqText)
newLangDict = sorted(langDict.values(), reverse = True)
newLangNames = sorted(langDict, key=langDict.get, reverse = True)
print("Cosine similarity (descending order):")
for i in range(len(freqList)):
print(newLangNames[i], newLangDict[i])
print()
time.sleep(5)
finalDict = dict(zip(newLangNames, newLangDict))
finalDict = str(finalDict)
return(finalDict)
def main():
flag = True
print("**************")
print("*ClassifyLang*")
print("**(ver. 1.0)**")
print("**************")
time.sleep(2)
os.system('cls')
print("Can recognize the following languages: English (EN), French (FR), German (DE), Spanish (ES), Portuguese (PT), Italian (IT), Turkish (TK), Swedish (SW), Polish (PL), Dutch (NL), Danish (DK), Icelandic (IS), Finnish (FI), Czech (CZ)")
time.sleep(5)
while flag:
os.system('cls')
print("*MENU*")
print("Detect string's language [1]")
print("Detect .txt file's language [2]")
print("Exit [0]\n")
try:
ans = int(input(""))
print()
if(ans == 1):
s = input("Enter string: ")
print()
if(len(s) <= 50):
print("[For more reliable results, the string should be longer]")
time.sleep(2)
print()
print("Save detection to file? [Y][N]\n")
save = input()
save = save.upper()
if(save == "Y"):
filename = input("File name?\n")
with open(filename, 'w') as file:
file.write(detectLang(s))
file.close()
print()
else:
if(s == "0"):
flag = False
else:
detectLang(s)
elif(ans == 2):
filename = input("Enter the file's name: ")
if(not os.path.exists(filename)):
print("File", filename, "does not exist in working directory!\n")
time.sleep(2)
else:
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(__location__, filename)) as file:
text = file.read()
print("Save detection to file? [Y][N]\n")
save = input()
save = save.upper()
if(save == "Y"):
filename = input("File name?\n")
file = open(filename, 'w')
file.write(detectLang(text))
file.close()
print()
else:
detectLang(text)
else:
flag = False
except(SyntaxError, TypeError, ValueError, NameError, ZeroDivisionError):
print("Invalid input! Try again...")
main()
</code></pre>
| [] | [
{
"body": "<p>Welcome to Code Review!</p>\n\n<p>This is an interesting program; thanks for sharing!</p>\n\n<p>To help you maintain it ...</p>\n\n<p><code>baseDict</code> appears to be unused, and can be removed. Ditto for <code>cosines</code></p>\n\n<p><code>baseChars</code> is a list of characters, which appe... | {
"AcceptedAnswerId": "202556",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-26T23:54:01.510",
"Id": "202541",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"clustering",
"natural-language-processing",
"scipy"
],
"Title": "Simple natural language classifier"
} | 202541 |
<p>I'm making an ASCII roguelike game and while writing the code for processing the player's move I can't decide between these two options. I have defined a class named <code>point</code> to handle positions in the game, like this. I would also like to know if this is a good idea or if I should use a structure instead.</p>
<p>Should I pass an object as a parameter to a function or create it inside?</p>
<pre><code>class point {
public:
point();
point(int x, int y);
int getX() const;
int getY() const;;
void setX(int x);
void setY(int y);
private:
int x;
int y;
};
</code></pre>
<p><strong>OPTION 1</strong></p>
<p>I define the target point object before calling the function.</p>
<pre><code>point playerPos = player.get_position();
point moveTilePos;
switch (input) {
case MOVE_UP:
moveTilePos.setX(playerPos.getX());
moveTilePos.setY(playerPos.getY()-1);
processPlayerMove(player, moveTilePos);
</code></pre>
<p>which is defined as follows:</p>
<pre><code>void Level::processPlayerMove(Player &player, point target) {
char moveTileSymbol;
moveTileSymbol = getTile(target);
switch(moveTileSymbol){
case WALL_SYMBOL:
break;
case GROUND_SYMBOL:
setTile(player.get_position(), GROUND_SYMBOL);
player.set_position(target);
setTile(target, PLAYER_SYMBOL);
break;
}
}
</code></pre>
<p>I think this is more readable overall but requires a setup that maybe should be part of the function. </p>
<p><strong>Option 2</strong></p>
<p>Everything is handled by the function:</p>
<pre><code>point playerPos = player.get_position();
switch (input) {
case MOVE_UP:
processPlayerMove2(player, playerPos.getX(), playerPos.getY() -1)
</code></pre>
<p>Which is defined like this:</p>
<pre><code>void Level::processPlayerMove2(Player &player, int targetX, int targetY) {
char moveTileSymbol;
point target;
target.setX(targetX);
target.setY(targetY);
moveTileSymbol = getTile(target);
switch(moveTileSymbol){
case WALL_SYMBOL:
break;
case GROUND_SYMBOL:
setTile(player.get_position(), GROUND_SYMBOL);
player.set_position(target);
setTile(target, PLAYER_SYMBOL);
break;
}
}
</code></pre>
<p>This case is more succinct, as the function handles everything. </p>
| [] | [
{
"body": "<pre><code>point playerPos = player.get_position();\npoint moveTilePos;\n\nmoveTilePos.setX(playerPos.getX());\nmoveTilePos.setY(playerPos.getY()-1);\nprocessPlayerMove(player, moveTilePos);\n</code></pre>\n\n<p>Well, of course you shouldn't do <em>that</em>. Declaring an \"uninitialized\" variable t... | {
"AcceptedAnswerId": "202548",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T00:45:02.453",
"Id": "202544",
"Score": "8",
"Tags": [
"c++",
"object-oriented",
"game",
"comparative-review"
],
"Title": "Processing player's move in an ASCII rogue-like game"
} | 202544 |
<p>I'm looking for any suggestions on how to improve my T-SQL for this procedure. It works okay, but I'd like to get advice to improve it from more experienced SQL developers. This procedure adds 4 columns to a table for row level auditing: <code>CreatedId</code>, <code>CreatedDate</code>, <code>ModifiedId</code> and <code>ModifiedDate</code>. It also creates a trigger for updating the modified columns as well as default constraints for setting the initial values. Also, should I create a database to house these administrative stored procedures e.g. <code>[AdminTasks].[dbo].[RowLevelAuditAdd]</code>?</p>
<p>For reference, this is using version Microsoft SQL Server 2016.</p>
<h3>Here is the stored procedure create statement for review:</h3>
<pre><code>CREATE PROCEDURE [dbo].[RowLevelAuditAdd]
@SchemaName NVARCHAR(50) = NULL
, @TableName NVARCHAR(50) = NULL
AS
BEGIN
/*
'--------------------------------------------------------------------------------------------------------------------
' Purpose: Adds row level auditing columns to a table
' Example: EXEC dbo.RowLevelAuditAdd 'dbo', 'ORGN';
' Note: The table must have a primary key to create the update trigger
'--------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------
-->>>>>>>>>>>>>>>>> FOR DEBUGGING <<<<<<<<<<<<<<<<<<<
-----------------------------------------------------
BEGIN
DECLARE @SchemaName NVARCHAR(50)
DECLARE @TableName NVARCHAR(50)
SET @SchemaName = 'dbo'
SET @TableName = 'ORGN'
-----------------------------------------------------
-----------------------------------------------------
*/
SET XACT_ABORT ON
BEGIN TRANSACTION;
SET NOCOUNT ON
DECLARE @SqlCommand NVARCHAR(1000)
DECLARE @TableKey NVARCHAR(1000)
DECLARE @UserName NVARCHAR(50)
DECLARE @CreatedId NVARCHAR(50)
DECLARE @CreatedDate NVARCHAR(50)
DECLARE @ModifiedId NVARCHAR(50)
DECLARE @ModifiedDate NVARCHAR(50)
DECLARE @TodayDate NVARCHAR(50)
SET @CreatedId = 'CreatedId'
SET @CreatedDate = 'CreatedDate'
SET @ModifiedId = 'ModifiedId'
SET @ModifiedDate = 'ModifiedDate'
SET @UserName = LOWER(LEFT(RIGHT(SYSTEM_USER,(LEN(SYSTEM_USER)-CHARINDEX('\',SYSTEM_USER))), 50))
SET @TodayDate = FORMAT(GETDATE(), 'dd-MMM-yyyy HH:mm:ss', 'en-US' )
PRINT '=====================================================================';
PRINT 'START - ALTER [' + @SchemaName + '].[' + @TableName + ']... ';
IF COL_LENGTH(@SchemaName + '.' + @TableName, @CreatedId) IS NULL
BEGIN
PRINT '=====================================================================';
PRINT 'START - ADD COLUMN [' + @CreatedId + ']... ';
PRINT '1. alter table add ' + @CreatedId + ' column... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD [' + @CreatedId + '] [NVARCHAR](50) NULL'
EXEC (@SqlCommand)
PRINT '2. update new column to a value... ' + @UserName;
SET @SqlCommand = 'UPDATE [' + @SchemaName + '].[' + @TableName + '] SET [' + @CreatedId + '] =''' + @UserName + ''' WHERE [' + @CreatedId + '] IS NULL'
EXEC (@SqlCommand)
PRINT '3. alter table alter new column add constraints... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ALTER COLUMN [' + @CreatedId + '] [NVARCHAR](50) NOT NULL'
EXEC (@SqlCommand)
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD CONSTRAINT [DF_' + @TableName + '_' + @CreatedId + '] DEFAULT (LOWER(LEFT(RIGHT(SYSTEM_USER,(LEN(SYSTEM_USER)-CHARINDEX(''\'',SYSTEM_USER))), 50))) FOR [' + @CreatedId + ']'
EXEC (@SqlCommand)
PRINT '4. add column description... ';
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Who created the record' , @level0type=N'SCHEMA',@level0name=@SchemaName, @level1type=N'TABLE',@level1name=@TableName, @level2type=N'COLUMN',@level2name=@CreatedId;
PRINT 'END - ADD COLUMN [' + @CreatedId + ']... ';
PRINT '=====================================================================';
END
IF COL_LENGTH(@SchemaName + '.' + @TableName, @CreatedDate) IS NULL
BEGIN
PRINT '=====================================================================';
PRINT 'START - ADD COLUMN [' + @CreatedDate + ']... ';
PRINT '1. alter table add ' + @CreatedDate + ' column... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD [' + @CreatedDate + '] [DATETIME] NULL'
EXEC (@SqlCommand)
PRINT '2. update new column to a value... ' + @TodayDate;
SET @SqlCommand = 'UPDATE [' + @SchemaName + '].[' + @TableName + '] SET [' + @CreatedDate + '] = ''' + @TodayDate+ ''' WHERE [' + @CreatedDate + '] IS NULL'
EXEC (@SqlCommand)
PRINT '3. alter table alter new column add constraints... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ALTER COLUMN [' + @CreatedDate + '] [DATETIME] NOT NULL'
EXEC (@SqlCommand)
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD CONSTRAINT [DF_' + @TableName + '_' + @CreatedDate + '] DEFAULT (GETDATE()) FOR [' + @CreatedDate + ']'
EXEC (@SqlCommand)
PRINT '4. add column description... ';
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The date and time the record was created' , @level0type=N'SCHEMA',@level0name=@SchemaName, @level1type=N'TABLE',@level1name=@TableName, @level2type=N'COLUMN',@level2name=@CreatedDate;
PRINT 'END - ADD COLUMN [' + @CreatedDate + ']... ';
PRINT '=====================================================================';
END
IF COL_LENGTH(@SchemaName + '.' + @TableName, @ModifiedId) IS NULL
BEGIN
PRINT '=====================================================================';
PRINT 'START - ADD COLUMN [' + @ModifiedId + ']... ';
PRINT '1. alter table add ' + @ModifiedId + ' column... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD [' + @ModifiedId + '] [NVARCHAR](50) NULL'
EXEC (@SqlCommand)
PRINT '2. update new column to a value... ' + @UserName;
SET @SqlCommand = 'UPDATE [' + @SchemaName + '].[' + @TableName + '] SET [' + @ModifiedId + '] =''' + @UserName + ''' WHERE [' + @ModifiedId + '] IS NULL'
EXEC (@SqlCommand)
PRINT '3. alter table alter new column add constraints... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ALTER COLUMN [' + @ModifiedId + '] [NVARCHAR](50) NOT NULL'
EXEC (@SqlCommand)
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD CONSTRAINT [DF_' + @TableName + '_' + @ModifiedId + '] DEFAULT (LOWER(LEFT(RIGHT(SYSTEM_USER,(LEN(SYSTEM_USER)-CHARINDEX(''\'',SYSTEM_USER))), 50))) FOR [' + @ModifiedId + ']'
EXEC (@SqlCommand)
PRINT '4. add column description... ';
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Who modified the record' , @level0type=N'SCHEMA',@level0name=@SchemaName, @level1type=N'TABLE',@level1name=@TableName, @level2type=N'COLUMN',@level2name=@ModifiedId;
PRINT 'END - ADD COLUMN [' + @ModifiedId + ']... ';
PRINT '=====================================================================';
END
IF COL_LENGTH(@SchemaName + '.' + @TableName, @ModifiedDate) IS NULL
BEGIN
PRINT '=====================================================================';
PRINT 'START - ADD COLUMN [' + @ModifiedDate + ']... ';
PRINT '1. alter table add ' + @ModifiedDate + ' column... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD [' + @ModifiedDate + '] [DATETIME] NULL'
EXEC (@SqlCommand)
PRINT '2. update new column to a value... ' + @TodayDate;
SET @SqlCommand = 'UPDATE [' + @SchemaName + '].[' + @TableName + '] SET [' + @ModifiedDate + '] = ''' + @TodayDate+ ''' WHERE [' + @ModifiedDate + '] IS NULL'
EXEC (@SqlCommand)
PRINT '3. alter table alter new column add constraints... ';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ALTER COLUMN [' + @ModifiedDate + '] [DATETIME] NOT NULL'
EXEC (@SqlCommand)
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ADD CONSTRAINT [DF_' + @TableName + '_' + @ModifiedDate + '] DEFAULT (GETDATE()) FOR [' + @ModifiedDate + ']'
EXEC (@SqlCommand)
PRINT '4. add column description... ';
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The date and time the record was modified' , @level0type=N'SCHEMA',@level0name=@SchemaName, @level1type=N'TABLE',@level1name=@TableName, @level2type=N'COLUMN',@level2name=@ModifiedDate;
PRINT 'END - ADD COLUMN [' + @ModifiedDate + ']... ';
PRINT '=====================================================================';
END
IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[' + @SchemaName + '].[TR_' + @TableName + '_LAST_UPDATED]'))
BEGIN
PRINT '=====================================================================';
PRINT 'START - ADD TRIGGER [TR_' + @TableName + '_LAST_UPDATED]... ';
PRINT '1. get primary key from information schema';
SELECT
@TableKey = COALESCE(@TableKey, '') + CASE WHEN ORDINAL_POSITION = 1 THEN 'ON' ELSE 'AND' END + ' t.' + COLUMN_NAME + ' = i.' + COLUMN_NAME + ' '
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
1=1
AND OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = @TableName AND TABLE_SCHEMA = @SchemaName
ORDER BY
ORDINAL_POSITION
PRINT '2. build trigger dynamically';
SET @SqlCommand = 'CREATE TRIGGER [' + @SchemaName + '].[TR_' + @TableName + '_LAST_UPDATED]' + CHAR(13);
SET @SqlCommand += 'ON [' + @SchemaName + '].[' + @TableName + ']' + CHAR(13);
SET @SqlCommand += 'AFTER UPDATE' + CHAR(13);
SET @SqlCommand += 'AS' + CHAR(13);
SET @SqlCommand += 'BEGIN' + CHAR(13);
SET @SqlCommand += CHAR(9) + 'IF NOT UPDATE(' + @ModifiedDate + ')' + CHAR(13);
SET @SqlCommand += CHAR(9) + 'BEGIN' + CHAR(13);
SET @SqlCommand += CHAR(9) + CHAR(9) + 'UPDATE t' + CHAR(13);
SET @SqlCommand += CHAR(9) + CHAR(9) + 'SET' + CHAR(13);
SET @SqlCommand += CHAR(9) + CHAR(9) + ' t.' + @ModifiedDate + ' = CURRENT_TIMESTAMP' + CHAR(13);
SET @SqlCommand += CHAR(9) + CHAR(9) + ', t.' + @ModifiedId + ' = LOWER(LEFT(RIGHT(SYSTEM_USER,(LEN(SYSTEM_USER)-CHARINDEX(''\'',SYSTEM_USER))), 50))' + CHAR(13);
SET @SqlCommand += CHAR(9) + CHAR(9) + 'FROM [' + @SchemaName + '].[' + @TableName + '] AS t' + CHAR(13);
SET @SqlCommand += CHAR(9) + CHAR(9) + 'INNER JOIN inserted AS i' + CHAR(13);
SET @SqlCommand += CHAR(9) + CHAR(9) + @TableKey + ';' + CHAR(13);
SET @SqlCommand += CHAR(9) + 'END' + CHAR(13);
SET @SqlCommand += 'END;' + CHAR(13);
EXEC (@SqlCommand)
PRINT '3. enable trigger';
SET @SqlCommand = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ENABLE TRIGGER [TR_' + @TableName + '_LAST_UPDATED]';
EXEC (@SqlCommand)
PRINT 'END - ADD TRIGGER [' + @ModifiedDate + ']... ';
PRINT '=====================================================================';
END
PRINT 'END - ALTER [' + @SchemaName + '].[' + @TableName + ']... ';
PRINT '=====================================================================';
--PRINT '******* ROLLBACK TRANSACTION ******* ';
--ROLLBACK TRANSACTION;
PRINT '******* COMMIT TRANSACTION ******* ';
COMMIT TRANSACTION;
END
GO
</code></pre>
<h3>Example of table script before the stored procedure is run:</h3>
<pre><code>--create the table
CREATE TABLE [dbo].[ORGN] (
[ORGN_ID] INT IDENTITY (1, 1) NOT NULL,
[ORGN_ABBR] VARCHAR (5) NOT NULL,
[ORGN_NAME] VARCHAR (100) NULL
);
--Add the keys
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [PK_ORGN] PRIMARY KEY NONCLUSTERED ([ORGN_ID] ASC);
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [UK_ORGN] UNIQUE NONCLUSTERED ([ORGN_ABBR] ASC);
--Add some test records
INSERT INTO dbo.ORGN (ORGN_ABBR, ORGN_NAME) VALUES('AABA', 'Altaba Inc');
INSERT INTO dbo.ORGN (ORGN_ABBR, ORGN_NAME) VALUES('AAPL', 'Apple Inc');
INSERT INTO dbo.ORGN (ORGN_ABBR, ORGN_NAME) VALUES('GOOG', 'Alphabet Inc');
INSERT INTO dbo.ORGN (ORGN_ABBR, ORGN_NAME) VALUES('MSFT', 'Microsoft Corporation');
INSERT INTO dbo.ORGN (ORGN_ABBR, ORGN_NAME) VALUES('TSLA', 'Tesla Inc');
</code></pre>
<h3>Example of the Results</h3>
<p><a href="https://i.stack.imgur.com/dGttZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dGttZ.png" alt="results"></a></p>
<h3>Example of the procedure with parameters:</h3>
<pre><code>EXEC dbo.RowLevelAuditAdd 'dbo', 'ORGN';
</code></pre>
<h3>Example of table after the stored procedure has been run:</h3>
<pre><code>CREATE TABLE [dbo].[ORGN] (
[ORGN_ID] INT IDENTITY (1, 1) NOT NULL,
[ORGN_ABBR] VARCHAR (5) NOT NULL,
[ORGN_NAME] VARCHAR (100) NULL,
[CreatedId] NVARCHAR (50) NOT NULL,
[CreatedDate] DATETIME NOT NULL,
[ModifiedId] NVARCHAR (50) NOT NULL,
[ModifiedDate] DATETIME NOT NULL
);
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [PK_ORGN] PRIMARY KEY NONCLUSTERED ([ORGN_ID] ASC);
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [UK_ORGN] UNIQUE NONCLUSTERED ([ORGN_ABBR] ASC);
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [DF_ORGN_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate];
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [DF_ORGN_CreatedId] DEFAULT (lower(left(right(suser_sname(),len(suser_sname())-charindex('\',suser_sname())),(50)))) FOR [CreatedId];
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [DF_ORGN_ModifiedDate] DEFAULT (getdate()) FOR [ModifiedDate];
ALTER TABLE [dbo].[ORGN]
ADD CONSTRAINT [DF_ORGN_ModifiedId] DEFAULT (lower(left(right(suser_sname(),len(suser_sname())-charindex('\',suser_sname())),(50)))) FOR [ModifiedId];
CREATE TRIGGER [dbo].[TR_ORGN_LAST_UPDATED]
ON [dbo].[ORGN]
AFTER UPDATE
AS
BEGIN
IF NOT UPDATE(ModifiedDate)
BEGIN
UPDATE t
SET
t.ModifiedDate = CURRENT_TIMESTAMP
, t.ModifiedId = LOWER(LEFT(RIGHT(SYSTEM_USER,(LEN(SYSTEM_USER)-CHARINDEX('\',SYSTEM_USER))), 50))
FROM [dbo].[ORGN] AS t
INNER JOIN inserted AS i
ON t.ORGN_ID = i.ORGN_ID ;
END
END;
</code></pre>
<h3>Results</h3>
<p><a href="https://i.stack.imgur.com/06AQ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/06AQ4.png" alt="results"></a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T01:02:51.027",
"Id": "202545",
"Score": "1",
"Tags": [
"sql",
"sql-server",
"logging",
"t-sql",
"stored-procedure"
],
"Title": "Stored procedure that adds row-level auditing to a table"
} | 202545 |
<p>This is the problem: </p>
<blockquote>
<p>You are given queries. Each query is of the form two integers
described below:
- 1: Insert x in your data structure.
- 2: Delete one occurrence of y from your data structure, if present.
- 3: Check if any integer is present whose frequency is exactly. If yes, print 1 else 0.</p>
<p>The queries are given in the form of a 2-D array query of size q where
queries[i][0] contains the operation, and queries<a href="https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps" rel="nofollow noreferrer">i</a> contains the
data element contains the operation and contains the data element. For
example, you are given array.
[[1,1],[2,2],[3,2],[1,1],[1,1],[2,1],[3,2]] The output=[0,1]</p>
</blockquote>
<p>The question can be found here;
<a href="https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps</a></p>
<p>My code does not work some of the cases on hackerrank for some reason but I can't figure out why. It is not caused by timeout or compiler error. It gives a 'wrong answer' in the compiler but when I try to test my code with the same input on VSCode, it actually works. It's the first time I am encountering something like this. If I would be more specific, I tested my code manually against this input </p>
<blockquote>
<p>[1, 3], [1, 38], [2, 1], [1, 16], [2, 1], [2, 2], [1, 64],
[1, 84], [3, 1], [1, 100], [1, 10], [2, 2], [2, 1], [1,
67], [2, 2], [3, 1], [1, 99], [1, 32], [1, 58], [3, 2]</p>
</blockquote>
<p><strong>and it returns [1,1,0] on vs code when I try it. However, on hackerrank it says the wrong answer even though it expects the same result. Any idea what's going on?</strong></p>
<p>Here is my code in javascript;</p>
<pre><code>function freqQuery(queries) {
let store = [];
let output = [];
let obj = {};
let checkFreq = false;
for (let i = 0; i < queries.length; i++) {
let query = queries[i];
if (query[0] === 1) {
store.push(query[1]);
} else if (query[0] === 2) {
let index = store.indexOf(query[1]);
if (index > -1) {
store.splice(index, 1);
}
} else {
let freq = query[1];
if (store.length === 0) {
output.push(0);
} else {
obj = charToObj(store);
for (let number in obj) {
if (obj[number] === freq) {
checkFreq = true;
break;
} else {
checkFreq = false;
}
}
if (checkFreq) {
output.push(1);
} else {
output.push(0);
}
}
}
}
return output;
}
function charToObj(arr) {
let obj = {};
for (let i = 0; i < arr.length; i++) {
if (obj[arr[i]]) {
obj[arr[i]] += 1;
} else {
obj[arr[i]] = 1;
}
}
return obj;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T08:29:30.363",
"Id": "390339",
"Score": "0",
"body": "Are you sure that this test case is failing? Seems ok to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T15:52:44.320",
"Id": "390384",
... | [
{
"body": "<h1>Optimizations</h1>\n\n<p>You should think of your algorithm as a black box. As long as input and output match, internally the function has not to reproduce the textual representation of the problem.</p>\n\n<p>With this in mind you can simplify your code. You also have an approach already in the <... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T01:41:03.073",
"Id": "202546",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"hash-map"
],
"Title": "Frequency Queries hackerrank"
} | 202546 |
<p>I am a 46 year young newbie trying to learn programming for fun and adventure. I do this in my free time. Some very nice gentlemen on stackoverflow have sent me here. I wish that someone could review my code and find faults with my style and weak areas, so that I might work upon it.</p>
<pre><code>prime_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 ]
list_of_factors = []
list_of_Prime_factors = []
def look4factors(number):
global list_of_factors
for index in range (2, 1 + number/2):
if number % index == 0:
list_of_factors.append (index)
#-------------------------------------------------------------------
def find_prime_factors(number):
global list_of_factors
global prime_numbers
global list_of_Prime_factors
quotient = number
while (quotient > 1):
for index in range(0,len(prime_numbers)):
if (quotient % prime_numbers[index] == 0 ):
list_of_Prime_factors.append(prime_numbers[index])
quotient = quotient / prime_numbers[index]
#------------------------------------------------------------------
def print_all_factors(number):
global list_of_factors
print "\n\nThe Factors for {} are,".format(number),
for index in range (0, len(list_of_factors)):
print "{}".format(list_of_factors[index]),
print "",
#-------------------------------------------------------------------
def print_all_prime_factors(number):
global list_of_Prime_factors
find_prime_factors(number)
list_of_Prime_factors.sort()
print "\n\nThe Prime Factorization for {} would be = ".format(number),
for index in range (0, len(list_of_Prime_factors)):
print "{}".format(list_of_Prime_factors[index]),
if (index + 1 == len(list_of_Prime_factors)):
pass
else:
print "X",
#-------------------------------------------------------------------
def main():
str_product = raw_input("Please enter a number to get its factors ")
int_product = int(str_product)
look4factors(int_product)
if len(list_of_factors)== 0:
print "It's a Prime Number."
else:
print_all_factors(int_product)
print_all_prime_factors(int_product)
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T10:02:02.753",
"Id": "390348",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>Welcome to programming! I'm new to code reviews (your StackOverflow post brought me here), but hopefully I have enough other experiences that something that follows will be of value to you.</p>\n\n<p>As to your OOP question, since you're already learning it I would <strong>stick to Python</strong>... | {
"AcceptedAnswerId": "202559",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T04:54:04.217",
"Id": "202552",
"Score": "7",
"Tags": [
"python",
"beginner",
"primes",
"python-2.x"
],
"Title": "Printing factors and prime factors of a number"
} | 202552 |
<p>I have been studying C# for 2 weeks already, I wrote a simple math game but not quite sure how bad it is. I'm just teaching myself to code through internet references. If you could review my work, I would appreciate it.</p>
<ol>
<li>It is a simple math quiz game</li>
<li>player gets 1 point in every correct answer</li>
<li>the game will be over when the player gives the incorrect answer</li>
<li>it displays total score the player earned, then the score resets.</li>
<li>Is my program reasonable or is there anything i need to improve?</li>
</ol>
<pre><code> static void Main(string[] args)
{
Console.Write("Please enter your Name: ");
string userName = (Console.ReadLine());
Console.WriteLine("Hello " + userName + ", Press ENTER to start the Math Quiz");
Console.WriteLine();
Console.ReadKey();
Start:
Random numberGenerator = new Random();
int score = 0;
while (true)
{
int num01 = numberGenerator.Next(1, 11);
int num02 = numberGenerator.Next(1, 11);
Console.WriteLine("What is " + num01 + " times " + num02 + " equal to?");
int Answer = Convert.ToInt32(Console.ReadLine());
int correctAnswer = num01 * num02;
if (Answer == num01 * num02)
{
Console.ForegroundColor = ConsoleColor.Green;
++score;
int responseIndex = numberGenerator.Next(1, 5);
switch (responseIndex)
{
case 1:
Console.WriteLine("Great!");
Console.WriteLine("Your score: " + score);
break;
case 2:
Console.WriteLine("You nailed it!");
Console.WriteLine("Your score: " + score);
break;
case 3:
Console.WriteLine("You're correct!");
Console.WriteLine("Your score: " + score);
break;
default:
Console.WriteLine("Good Job " + userName + ", Keep it up!");
Console.WriteLine("Your score: " + score);
break;
}
Console.ResetColor();
Console.ReadLine();
Console.WriteLine();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
int responseIndex2 = numberGenerator.Next(1, 5);
switch (responseIndex2)
{
case 1:
Console.WriteLine("Are you even trying? The correct answer is " + correctAnswer);
break;
case 2:
Console.WriteLine("Ooops!!! The correct answer is " + correctAnswer);
break;
case 3:
Console.WriteLine("Oh, come on " + userName + " I know you can do better than that! The correct answer is " + correctAnswer);
break;
default:
Console.WriteLine("Sorry " + userName + ", that's incorrect, the correct answer is " + correctAnswer);
break;
}
Console.WriteLine(Environment.NewLine + "Game Over, Your score: " + score);
Console.ResetColor();
Console.WriteLine();
Console.ReadLine();
goto Start;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T20:03:16.083",
"Id": "390440",
"Score": "0",
"body": "Just out of curiosity, Which references are you reading that suggest to use `goto`? In C#, (possibly) the only sensible use for the `goto` statement is to imitate the *fallthroug... | [
{
"body": "<p>Even though this is a fairly short program, resist the temptation to do everything in the <code>Program</code> class of your console app. Whenever I start a new console app, the first thing I do is create a <code>Runner</code> class with an <code>Execute()</code> method and call that from the <cod... | {
"AcceptedAnswerId": "202574",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T05:11:21.863",
"Id": "202555",
"Score": "7",
"Tags": [
"c#",
"beginner",
"quiz"
],
"Title": "Simple Math Quiz Game"
} | 202555 |
<p><strong>I have addressed the critique for this post and resubmitted it for iterative review;</strong> <em><a href="https://codereview.stackexchange.com/questions/203435">C++ multithread pool class</a>.</em></p>
<p>Class for creating thread pools with the latest C++ standard. Currently C++17 and C++2a.</p>
<ul>
<li>It currently only accepts and executes parameterless routines.</li>
<li>Multiple functions may be enqueued via variadic template or stl
vector.</li>
<li>The number of threads created in the pool is relative to the
hardware concurrency by means of a user multiplier. If the hardware
concurrency cannot be determined it will default to four and the
number of threads created will be two, four, or eight depending on
the multiplier used.</li>
</ul>
<p>Please review code correctness, best practices, design and implementation.</p>
<p>Please assume the namespace Mercer is to be used as a cross-platform library.</p>
<p>This code <strong>was</strong> also available on <a href="https://github.com/sixequalszero/C-" rel="nofollow noreferrer">GitHub</a>, but now contains current iteration.</p>
<p><strong>mercer.h</strong></p>
<pre><code>//File mercer.h
//Author Michael Mercer
//Copyleft CC BY-SA
//Description Header for universal declarations used in namespace Mercer
#ifndef MERCER_H_0000
#define MERCER_H_0000
/*#####################----- Mercer -----###################*/
/* universal declarations */
namespace Mercer
{
enum struct execution: bool {failure, success};
}
/* */
/*#####################----- Mercer -----###################*/
#endif //MERCER_H_0000
</code></pre>
<p><strong>multithread.h</strong></p>
<pre><code>//File multithread.h
//Author Michael Mercer
//Copyleft CC BY-SA
//Description Header for multithread class
#ifndef MULTITHREAD_H_0000
#define MULTITHREAD_H_0000
/*#####################----- multithread -----###################*/
/* class for multithread interface */
/* GCC Bug 84330 - [6/7 Regression] [concepts] ICE with broken constraint
#ifndef __cpp_concepts
static_assert(false, "Concepts TS NOT found");
#endif
#include <type_traits>
template<typename dataType>
concept bool Function()
{
return std::is_function<dataType>::value;
}
*/
#include <deque>
#include <queue>
#include <mutex>
#include <vector>
#include <memory>
#include <thread>
#include <functional>
#include <condition_variable>
#include "mercer.h"
namespace Mercer
{
//Multithread class
//if !joinable no new routines may be enqueued
class multithread
{
class implementation;
std::unique_ptr<implementation> data;
public:
enum struct concurrency: int {half, full, twofold};
multithread(concurrency quantity);
multithread(); //concurrency::full
~multithread();
execution enqueue(const std::vector<std::function<void()>>&&);
//consumes std::vector iff execution::success
execution enqueue(const std::function<void()>&&);
template<typename ... dataType>
execution enqueue(const std::function<void()>&& proximate ,
const std::function<void()>&& penproximate,
dataType ... parameters )
{
if(execution::success==
enqueue(std::forward<const std::function<void()>>(proximate ) ))
enqueue(std::forward<const std::function<void()>>(penproximate) ,
std::forward<dataType >(parameters )...);
else
return execution::failure;
return execution::success;
}
execution join();
execution detach();
bool thrown() const noexcept;
std::exception_ptr getNextException() const;
//If thrown()==true, will never throw
//If get final exception, thrown() will reset to false
};
}//namespace Mercer
/* */
/*#####################----- multithread -----###################*/
#endif //MULTITHREAD_H_0000
</code></pre>
<p><strong>multithread.cpp</strong></p>
<pre><code>//File multithread.cpp
//Author Michael Mercer
//Copyleft CC BY-SA
//Description Source for multithread class
/*#####################----- multithread -----###################*/
/* class for multithread interface */
#include "multithread.h"
using Mercer::multithread;
using Mercer::execution;
using function = std::function<void()>;
struct multithread::implementation
{
enum struct close: bool {detach, join};
std::queue<std::exception_ptr> exceptions;
bool open ;
std::deque <function> line ;
std::mutex door ;
std::condition_variable guard;
std::vector<std::thread> pool ;
implementation(concurrency quantity) :
open(true),
line(),
door(),
guard(),
pool(std::invoke( [&]
{
std::vector<std::thread> temp;
unsigned threads = std::thread::hardware_concurrency();
if(threads==0)
threads=4;
switch(quantity)
{
case concurrency::half : threads /= 2; break;
case concurrency::full : break;
case concurrency::twofold: threads *= 2; break;
}
temp.reserve(threads);
for(auto i=threads; i>0; i--)
temp.emplace_back( [&]
{
function next;
bool perpetual = true;
while(perpetual)
{
std::unique_lock lock(door);
guard.wait(lock, [&]
{
return !line.empty() || !open;
} );
if(!line.empty())
{
next = std::forward<function>(line.front());
line.pop_front();
if(!open && line.empty())
perpetual = false;
lock.unlock();
guard.notify_one();
try
{
next();
}
catch(...)
{
exceptions.emplace(
std::current_exception() );
}
}
else if(!open)
perpetual = false;
}
}
);
return temp;
}) )
{}
template<close closeType>
execution close()
{
auto result = execution::success;
if (open==true)
{
open = false;
guard.notify_all();
for (auto&& thread : pool)
if (thread.joinable())
switch(closeType)
{
case close::join : thread.join() ; break;
case close::detach: thread.detach(); break;
}
pool.clear();
pool.shrink_to_fit();
}
else
result = execution::failure;
return result;
}
};
multithread::multithread(concurrency quantity):
data(std::make_unique<implementation>(quantity))
{}
multithread::multithread():
data(std::make_unique<implementation>(concurrency::full))
{}
execution multithread::join()
{
return data->close<implementation::close::join>();
}
execution multithread::detach()
{
return data->close<implementation::close::detach>();
}
multithread::~multithread()
{
join();
}
execution multithread::enqueue(const function&& item)
{
auto result = execution::success;
if (data->open==true)
{
std::scoped_lock(data->door);
data->line.emplace_back(std::forward<const function>(item));
data->guard.notify_all();
}
else
result = execution::failure;
return result;
}
execution multithread::enqueue(const std::vector<function>&& adjunct)
{
auto result = execution::success;
if (data->open==true)
{
std::scoped_lock(data->door);
data->line.insert(data->line.end(),
make_move_iterator(adjunct.begin()) ,
make_move_iterator(adjunct.end() ));
data->guard.notify_all();
}
else
result = execution::failure;
return result;
}
bool multithread::thrown() const noexcept
{
return data->exceptions.empty() ? false : true;
}
std::exception_ptr multithread::getNextException() const
{
if(thrown())
{
auto temp = std::forward<std::exception_ptr>(data->exceptions.front());
data->exceptions.pop();
return temp;
}
else
throw std::out_of_range("Thrown() is false, no exception to get");
}
/* */
/*#####################----- multithread -----###################*/
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T06:14:52.523",
"Id": "390471",
"Score": "2",
"body": "I hate us-less comments: `//Description Header for universal declarations used in namespace Mercer`. If you are going to have comments (a code smell for now writing readable cod... | [
{
"body": "<h1><code>multithread::enqueue</code> parameter type issues</h1>\n\n<blockquote>\n <p>This section is trying to address all overloads of this member function, as these issues affect all of them.</p>\n</blockquote>\n\n<p>Why take parameters of the form <code>const X&&</code> (where <code>X</c... | {
"AcceptedAnswerId": "202569",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T05:42:01.957",
"Id": "202557",
"Score": "5",
"Tags": [
"c++",
"multithreading",
"c++17"
],
"Title": "C++ thread pool class"
} | 202557 |
<p>I am working with a Star Wars API from <a href="http://swapi.co/api/" rel="nofollow noreferrer">http://swapi.co/api/</a>. Here's the problem that I was working on for the <em>Star Wars API problem</em>. And the code works and prints out the exact output that I desired. I would like to get some code review.</p>
<blockquote>
<pre><code>>
# You are a Coordinator for the Star Wars rebel forces and are responsible for planning troop deployments.
# You need a tool to help find starships with enough passenger capacity and pilots to fly them.
# Build a CLI tool that takes as its single argument the number of people that
# need to be transported and outputs a list of candidate pilot and starship names
# that are each a valid possibility.
# Assume that any pilot can be a candidate regardless of allegiance.
# Assume the entire group of passengers must fit in a single starship.
# You may skip starships with no pilots or with unknown passenger capacity.
# Your tool must use the Star Wars API (http://swapi.co) to obtain the necessary data.
# You may not use any of the official Star Wars API helper libraries but can use any other libraries you want
# (http client, rest client, json).
</code></pre>
<h1>Example:</h1>
</blockquote>
<pre><code>> # print-pilots-and-ships with minimum of 20 passengers
>
> # Luke Skywalker, Imperial shuttle
>
> # Chewbacca, Imperial shuttle
>
> # Han Solo, Imperial shuttle
>
> # Obi-Wan Kenobi, Trade Federation cruiser
>
> # Anakin Skywalker, Trade Federation cruiser
</code></pre>
<p><a href="https://repl.it/@Jeffchiucp/twolargestklargest-3" rel="nofollow noreferrer">Python 3 solution</a>:</p>
<pre><code>import sys
import requests
import json
import urllib.parse
#number of pages in JSON feed
def print_page(page_num, num_passenger):
endpoint = "https://swapi.co/api/starships/?"
type = 'json'
#specifies api parameters
url = endpoint + urllib.parse.urlencode({"format": type, "page": page_num})
#gets info
json_data = requests.get(url).json()
# number_of_ship = json_data['count']
if 'results' in json_data:
for ship in json_data['results']:
if has_pilot(ship) and has_enough_passenger(ship, num_passenger):
print_pilots_on(ship)
def get_pilot_name(pilot):
type = 'json'
#specifies api parameters
url = pilot
#gets info
json_data = requests.get(url).json()
return json_data["name"]
def print_pilots_on(ship):
for pilot in ship['pilots']:
print(get_pilot_name(pilot), ship['name'])
def has_pilot(ship):
if ship['pilots']:
return True
return False
def has_enough_passenger(ship, num):
if ship['passengers'] != "unknown" and int(ship['passengers']) >= num:
return True
return False
def print_pilots_and_ships(num_passenger):
page_list = [1,2,3,4,5,6,7,8,9]
# list to store names
for page in page_list:
print_page(page, num_passenger)
if __name__ == '__main__':
num_passenger = int(20)
print_pilots_and_ships(num_passenger)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T09:51:14.287",
"Id": "390346",
"Score": "4",
"body": "So, where is the problem itself from? And are there more like this there?"
}
] | [
{
"body": "<p>This is pretty good. I only have a few small nitpicks</p>\n\n<ul>\n<li><p>Return directly</p>\n\n<p>You do this a few times:</p>\n\n<blockquote>\n<pre><code> if ship['passengers'] != \"unknown\" and int(ship['passengers']) >= num:\n return True\nreturn False\n</code></pre>\n</blockquote>\n\n... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T07:00:59.793",
"Id": "202561",
"Score": "6",
"Tags": [
"python",
"rest"
],
"Title": "Star Wars API GET request in Python"
} | 202561 |
<p>I think the general functionality is there, but sometimes it looks a little slow/clunky when I try to run my app. Highlighting cells can be slow as it skips over some of the cells I hover over if my mouse is moving somewhat fast. Also the speed the grid evolves doesn't always consistent.</p>
<p>I suspect that calling setState() so often is a bit heavy? I was also wondering if there are "better" ways to do the styling of the grid.</p>
<p><a href="https://jsfiddle.net/bonbonlemon/49jzdo1n/" rel="nofollow noreferrer">https://jsfiddle.net/bonbonlemon/49jzdo1n/</a></p>
<p>JSX:</p>
<pre><code>class GameOfLife extends React.Component {
constructor(props) {
super(props);
const grid = this.createNewGrid();
this.state = {
grid: grid,
isPointerDown: false,
pointerStatus: false,
isStarted: false,
intervalId: 0,
ticksPerSecond: 10
};
this.updateCell = this.updateCell.bind(this);
this.handlePointerDown = this.handlePointerDown.bind(this);
this.handlePointerOver = this.handlePointerOver.bind(this);
this.handlePointerUp = this.handlePointerUp.bind(this);
this.evolve = this.evolve.bind(this);
this.clearGrid = this.clearGrid.bind(this);
this.updateTicksPerSecond = this.updateTicksPerSecond.bind(this);
this.toggleStart = this.toggleStart.bind(this);
}
createNewGrid() {
let grid = [];
for (let row = 0; row < 40; row++) {
grid.push([]);
for (let col = 0; col < 40; col++) {
grid[row].push(false);
}
}
return grid;
}
updateCell(e, updatePointerDown) {
let coordinates = e.currentTarget.getAttribute('coordinates');
coordinates = coordinates.split(",");
coordinates = coordinates.map(coordinate => parseInt(coordinate));
const [row, col] = coordinates;
let grid = this.state.grid;
let cell = grid[row][col];
let { isPointerDown, pointerStatus } = this.state;
if (updatePointerDown) {
isPointerDown = true;
pointerStatus = !cell;
}
grid[row][col] = pointerStatus;
this.setState({
grid: grid,
isPointerDown: isPointerDown,
pointerStatus: pointerStatus
});
}
handlePointerDown(e) {
e.preventDefault();
this.updateCell(e, true);
}
handlePointerOver(e) {
e.preventDefault();
if (this.state.isPointerDown) {
this.updateCell(e);
}
}
handlePointerUp(e) {
e.preventDefault();
this.setState({isPointerDown: false});
}
evolve(e) {
if (e) { e.preventDefault(); }
let currentGen = this.state.grid;
let nextGen = [];
currentGen.forEach((row, rowIdx) => {
nextGen.push([]);
row.forEach((cell, colIdx) => {
const numNeighbors = this.countNeighbors(rowIdx, colIdx);
if (currentGen[rowIdx][colIdx]) {
if (numNeighbors >= 2 && numNeighbors <= 3) {
nextGen[rowIdx].push(true);
} else {
nextGen[rowIdx].push(false);
}
} else {
if (numNeighbors == 3) {
nextGen[rowIdx].push(true);
} else {
nextGen[rowIdx].push(false);
}
}
});
});
this.setState({grid: nextGen});
}
countNeighbors(rowIdx, colIdx) {
const { grid } = this.state;
let numNeighbors = 0;
for (let dy = -1; dy <= 1; dy++) {
if (grid[rowIdx + dy] ) {
for (let dx = -1; dx <= 1; dx++) {
if (grid[rowIdx + dy][colIdx + dx] && (dy != 0 || dx != 0)) {
numNeighbors++;
}
}
}
}
return numNeighbors;
}
clearGrid(e) {
e.preventDefault();
const grid = this.createNewGrid();
this.setState({grid: grid});
}
toggleStart(e) {
let { isStarted, ticksPerSecond, intervalId } = this.state;
if (!isStarted) {
intervalId = setInterval(this.evolve, 1000 / ticksPerSecond);
} else {
clearInterval(intervalId);
}
this.setState({
isStarted: !isStarted,
intervalId: intervalId
});
}
updateTicksPerSecond(e) {
this.setState({ticksPerSecond: e.currentTarget.value});
}
render() {
const { grid, ticksPerSecond, isStarted } = this.state;
return (
<div>
<div id="grid" onPointerUp={this.handlePointerUp}>
{
grid.map((row, rowIdx) => (
<div className="row" key={rowIdx.toString()}>
{row.map((cell, colIdx) => (
<div className={"cell " + (cell ? "alive": "dead")} onPointerDown={this.handlePointerDown} onPointerOver={this.handlePointerOver} coordinates={[rowIdx, colIdx]} key={[rowIdx, colIdx]} />
))}
</div>
))
}
</div>
<button onClick={this.clearGrid}>Clear</button>
<button onClick={this.evolve}>Next</button>
<button onClick={this.toggleStart}>{ isStarted ? "Pause" : "Start" }</button>
<input
type="text"
value={ticksPerSecond}
onChange={this.updateTicksPerSecond}
/>
</div>
)
}
}
ReactDOM.render(<GameOfLife />, document.querySelector("#app"))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T07:38:43.400",
"Id": "390331",
"Score": "2",
"body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what y... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T07:30:02.737",
"Id": "202563",
"Score": "3",
"Tags": [
"performance",
"html",
"react.js",
"game-of-life",
"jsx"
],
"Title": "Game of Life as a React app"
} | 202563 |
<p>I need to make multiple http requests very fast. I've currently use this method.</p>
<pre><code>import queue as Queue
import threading
from threading import Thread
import os
import requests
Lock = threading.Lock()
Queue = Queue.Queue(maxsize=0)
for i in range(1000):
Queue.put((i,i+1)) # These Are Examples
Task_Done = 0
Task_Total = 1000
os.system("title Task Done : {}".format(Task_Done))
class MultiThreading(threading.Thread):
def __init__(self,Queue):
threading.Thread.__init__(self)
self.Queue = Queue
def run(self):
global Lock
global Task_Done
TaskLeft = self.Queue.get()
Part1,Part2 = TaskLeft
try:
A = requests.get("https://twitter.com/{}{}".format(Part1,Part2))
B = A.text
Task_Done += 1
with Lock:
os.system("title Task Done : {}".format(Task_Done))
except:
self.Queue.put((Part1,Part2))
self.Queue.task_done()
while not (Task_Total == Task_Done):
for i in range(100):
try:
t = MultiThreading(Queue)
t.setDaemon(True)
t.start()
except:
time.sleep(5)
</code></pre>
<p>I'm currently new to this so excuse my messy code. I want to know what's the most efficient, best, and fastest way of sending HTTP requests.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T13:07:08.590",
"Id": "390361",
"Score": "1",
"body": "You're importing threads and queues, but still hand-maintained global locks? Why did you write it this way? Were you specifically working around a specific bug or problem?"
},
... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T11:35:28.547",
"Id": "202577",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"multithreading",
"http",
"twitter"
],
"Title": "Making multiple HTTP requests to Twitter"
} | 202577 |
<p>I have used d3 to draw a sine wave going around a circle. This is the very first time I've used d3 or drawn a SVG and I'm fairly new to JS as well, so I don't know if I've overcomplicated it/if there is a simpler way to achieve this. I'd appreciate some feedback - especially if there's any way to make my code more concise.</p>
<p>See my <a href="https://codepen.io/vipin-ajayakumar/pen/mGPXoL" rel="noreferrer">codepen</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const svg = d3.select('svg');
const margin = { top: 50, right: 50, bottom: 50, left: 50 };
const width = +svg.attr('width') - margin.left - margin.right;
const height = +svg.attr('height') - margin.top - margin.bottom;
// content area of your visualization
const vis = svg
.append('g')
.attr('transform', `translate(${margin.left+width/2},${margin.top+height/2})`);
// show area inside of margins
const rect = vis
.append('rect')
.attr('class', 'content')
.attr('width', width)
.attr('height', height)
.attr('transform', `translate(${-width/2},${-height/2})`);
// show scales
const xScale = d3
.scaleLinear()
.domain([-100, 100])
.range([-width/2, width/2]);
const yScale = d3
.scaleLinear()
.domain([100, -100])
.range([-height/2, height/2]);
vis.append('g').call(d3.axisTop(xScale));
vis.append('g').call(d3.axisLeft(yScale));
// draw circle
const pi = Math.PI
const radius = 63.66
const circle = vis
.append('circle')
.style('stroke-dasharray', '3, 3')
.style('stroke', 'black')
.style("fill", "transparent")
.attr("r", xScale(radius))
.attr("cx", 0)
.attr("cy", 0)
// get coordinates for a sine wave
const getSineWave = ({
numWaves,
wavelength,
amplitude,
phase,
numPointsPerWave,
}) => {
return (
d3.range(numWaves*numPointsPerWave+1).map(function(k) {
const x = k * wavelength/numPointsPerWave
return [x, amplitude * Math.sin(phase + 2 * pi * x/wavelength)];
})
)
}
// tranform a coordinate from linear space to circular space
const rotate = (cx, cy, x, y, radius) => {
const theta = x/radius,
sin = Math.sin(theta),
cos = Math.cos(theta),
nx = cx + (radius + y) * sin,
ny = cy + (radius + y) * cos
return [nx, ny];
}
// generate sine wave
const numWaves = 4
const amplitude = 10
const phase = pi/2
const circumference = 2 * pi * radius
const wavelength = circumference / numWaves
const numPointsPerWave = 4
const sineWave = getSineWave({
numWaves,
numPointsPerWave,
wavelength,
amplitude,
phase,
wavelength
})
var rotatedSine = sineWave.map( d => {
const rotatedCoords = rotate(0, 0, d[0], d[1], radius)
return rotatedCoords
})
// remove the last point as it would overlap the first point of the circle
rotatedSine.pop()
// get Path commands for given coordinates
const getPath = d3.line()
.x(d => xScale(d[0]))
.y(d => yScale(d[1]))
.curve(d3.curveCardinalClosed)
// draw sine wave going around a circle
const wave = vis
.append('path')
.attr('d', getPath(rotatedSine))
.attr('fill', 'none')
.attr('stroke', 'black')
.attr('stroke-width', '1px')</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
background-color: steelblue;
}
.content {
fill: lightsteelblue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script>
<svg width="1000" height="1000" </ svg></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T13:41:36.487",
"Id": "390368",
"Score": "0",
"body": "Could you, perhaps, embed the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T13:46:59.233",
"Id": "390369",
"Score": "0",
"body... | [
{
"body": "<p>Overall you have a good D3 code here, congrats (I'm fairly impressed with the questions I've seen here at CR lately, from people claiming <em>"This is the very first time I've used d3 or drawn a SVG"</em>).</p>\n<p>However, before sharing my proposed alternative, I'd like to tell you tha... | {
"AcceptedAnswerId": "202638",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T12:34:20.483",
"Id": "202579",
"Score": "11",
"Tags": [
"javascript",
"mathematics",
"ecmascript-6",
"d3.js",
"svg"
],
"Title": "Draw sine wave going around a circle"
} | 202579 |
<p>We have specific Email2Case emails that come in that we just want to delete. Below is a simple APEX trigger that I think will do the trick. </p>
<pre><code>trigger CaseDeleteDatabaseCompaction on Case (after insert) {
List<Id> casesToDelete = new List<Id>();
for (Case a: Trigger.New) {
System.debug('Subject: ' + a.Subject);
if (a.Subject == 'Error: Database compaction')
{
casesToDelete.add(a.Id);
System.debug('Adding ID: ' + a.Id);
}
if(casesToDelete.size()>0)
{
System.debug('casesToDelete: ' + casesToDelete.size());
Database.delete(casesToDelete);
}
} }
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T14:58:48.327",
"Id": "390377",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>The second <code>if</code> should be placed outside of the loop, otherwise the <code>List<Id></code> wouldn't make any sense.</p>\n\n<p>Your code would be more readable and it would be easier to grasp at first glance if you use better names to name your things with. </p>\n\n<p>Let your vari... | {
"AcceptedAnswerId": "202585",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T14:19:36.763",
"Id": "202583",
"Score": "-2",
"Tags": [
"salesforce-apex"
],
"Title": "Salesforce Delete Case based on Subject"
} | 202583 |
<p>I've solved an assignment a week ago, which is my first assignment using Lisp.</p>
<hr>
<h2>Tasks:</h2>
<p>Task 1:</p>
<blockquote>
<p>a. Given a tree as recursive lists, print the tree in breadth first order.</p>
<p>b. Given a tree like in task 1a, print it in child-successor order. </p>
<p>Input for Tasks 1a and 1b:
<code>(A (B (C (D))(E (F) (G (H)))) (J (K (L (M) (N (P))))))</code></p>
<p>Output for Task 1a:</p>
<pre><code>A
B J
C E K
D F G L
H M N
P
</code></pre>
<p>Output for Task 1b:</p>
<pre><code>A, B J
B, C E
J, K
C, D
E, F G
K, L
D,
F,
G, H
L, M N
H,
M,
N, P
P,
</code></pre>
</blockquote>
<hr>
<p>Task 2:</p>
<blockquote>
<p>Tasks 2a and 2b are the same as in task 1, but now the nodes of the tree have costs. The cost represents the cost from the node parent to this node. When printing, cost should be accumulated starting from the root (2a, 2b are using styles defined by 1a, 1b accordingly).</p>
<p>Input for Task 2:
<code>((A 0) ((B 5) ((C 3) ((D 4))) ((E 2) ((F 1)) ((G 7) ((H 9))))) ((J 1) ((K 3) ((L 1) ((M 7)) ((N 1) ((P 2)))))))</code></p>
<p>Output for Task 2a:</p>
<pre><code>B,5 J,1
C,8 E,7 K,4
D,12 F,8 G,14 L,5
H,23 M,12 N,6
P,8
</code></pre>
<p>Output for Task 2b:</p>
<pre><code>A,0; B,5 J,1
B,5; C,3 E,2
J,1; K,3
C,8; D,4
E,7; F,1 G,7
K,4; L,1
D,12;
F,8;
G,14 H,9
L,5; M,7 N,1
H,23;
M,12;
N,6; P,2
P,8;
</code></pre>
</blockquote>
<hr>
<h2>Solution</h2>
<p>I implemented my solution using an iterative approach - taking and printing cdr's of each childs (tasks are marked using comments):</p>
<pre><code> ;; Task 1a
;; This function takes a list of lists and
;; prints (car) for every sublist then repeats
;; for accumulated (cdr)'s of those sublists if not empty
(defun breadth-print (node)
(loop while (not (eq nil node))
do
(setq temp nil)
(loop for i in node do (progn (format t "~a " (car i))
(mapcar #'(lambda (j) (if (null temp)
(setq temp (list j))
(setq temp (append temp (list j))))) (cdr i))))
(setq node temp)
(format t "~%")))
;; Task 1b
;; This function utilizes the same principle
;; as breadth-print, however each node is printed
;; on a new line with its children
(defun breadth-print-childs (node)
(loop while (not (eq nil node))
do
(setq temp nil)
(loop for i in node do (progn (format t "~a, " (car i))
(loop for beta in (cdr i) do (format t "~d " (car beta)))
(format t "~%")
(mapcar #'(lambda (j) (if (null temp)
(setq temp (list j))
(setq temp (append temp (list j))))) (cdr i))))
(setq node temp)))
;; Task 2a
;; This function is based on breadth-print and
;; the only difference is that the costs are
;; updated for every element in (cdr) of sublists,
;; and formatting is a bit different
(defun breadth-print-costs (node)
(loop while (not (eq nil node))
do
(setq temp nil)
(loop for i in node do (progn (format t "~{~a,~a~} " (car i))
(mapcar #'(lambda (j) (progn (setf (nth 1 (car j)) (+ (nth 1 (car j)) (nth 1 (car i))))
(if (null temp)
(setq temp (list j))
(setq temp (append temp (list j)))))) (cdr i))))
(setq node temp)
(format t "~%")))
;; Task 2b
;; This function utilizes the same principle
;; as breadth-print-childs, with only addition
;; is the calclulations of cost (similar fasion is used in breadth-print-costs),
;; which is modified according to the already passed path
(defun breadth-print-childs-costs (node)
(loop while (not (eq nil node))
do
(setq temp nil)
(loop for i in node do (progn (format t "~{~a,~a~}; " (car i))
(loop for beta in (cdr i) do (format t "~{~a,~a~} " (car beta)))
(format t "~%")
(mapcar #'(lambda (j) (progn (setf (nth 1 (car j)) (+ (nth 1 (car j)) (nth 1 (car i))))
(if (null temp)
(setq temp (list j))
(setq temp (append temp (list j)))))) (cdr i))))
(setq node temp)))
(format t "Task 1a provide input: ")
(defparameter *inpa* (list (read)))
(format t "~%Input 1a is ~a~%Part 1a:~%" *inpa*)
(breadth-print *inpa*)
(format t "Task 1b provide input: ")
(defparameter *inpb* (list (read)))
(format t "~%Input 1b is ~a~%Part 1b:~%" *inpb*)
(breadth-print-childs *inpb*)
(format t "Task 2a provide input: ")
(defparameter *inpc* (list (read)))
(format t "~%Input 2a is ~a~%Part 2a:~%" *inpc*)
(breadth-print-costs *inpc*)
(format t "Task 2b provide input: ")
(defparameter *inpd* (list (read)))
(format t "Input 2b is ~a~%Part 2b:~%" *inpd*)
(breadth-print-childs-costs *inpd*)
</code></pre>
<hr>
<h2>Concerns</h2>
<p>What I would like to improve:</p>
<ul>
<li>Does it fit the Lisp coding style? </li>
<li>Performance (is my iterative approach viable?)</li>
<li>Function choice and general structure of the code (I'm sure that
there should be a better way to do the <strong>temp</strong> checks or
completely avoid them)</li>
</ul>
| [] | [
{
"body": "<p>A few considerations about the style of the code.</p>\n\n<p><strong>Generalized booleans</strong></p>\n\n<p>In Common Lisp the only value “false” is <code>NIL</code>, every other value is considered “true”. So, if you want to check if <code>node</code> is different from <code>NIL</code>, you can s... | {
"AcceptedAnswerId": "202608",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T14:37:14.263",
"Id": "202586",
"Score": "4",
"Tags": [
"beginner",
"algorithm",
"tree",
"lisp",
"common-lisp"
],
"Title": "Implementing a tree parsing function"
} | 202586 |
<p>The purpose of the application is very simple.
<code>PlantList</code> is a object containing a list of <code>PlantConfiguration</code>.</p>
<p>Each <code>PlantConfiguration</code> has two schedules: <code>HourlySchedule</code> and <code>DailySchedule</code>, as well as a TimeZone.</p>
<p>The program reads a <code>PlantList</code> object, stored as a JSON file in the settings, and returns an enumerable of <code>Schedule</code>, containing all the <code>HourlySchedule</code>s, and the <code>DailySchedule</code> if it is midnight in a plant's timezone.</p>
<p>In addition to general comments about the code, I am looking for a way to improve the loop. Indeed, using the <code>Concat</code> feature to smash together all schedules as they come feels sub-optimal, and I figure this is a good occasion to learn about a new pattern.</p>
<pre><code>public class Program
{
private readonly static log4net.ILog log = LogHelper.GetLogger();
public static void Main()
{
var container = new UnityContainer();
container.RegisterType<IPlantRepository, JsonPlantRepository>();
IPlantRepository serverRepository = container.Resolve<IPlantRepository>();
var plantList = serverRepository.GetPlants(MySettings.Default.Servers);
if (MySettings.Default.Disabled == true)
{
log.Fatal("Script disabled");
return;
}
UpdateValues(plantList);
}
private static void UpdateValues(PlantList plantList)
{
DateTime utcTopHourDate = GetUtcTopHourDate();
IEnumerable<KpiSchedule> schedulesToUpdate = new List<KpiSchedule>();
foreach(PlantConfiguration plant in plantList.Plants)
{
schedulesToUpdate = schedulesToUpdate.Concat(GetScheduleList(utcTopHourDate,plant));
}
//... Do stuff with the schedule list
}
private static IEnumerable<KpiSchedule> GetScheduleList(DateTime utcTime, PlantConfiguration plant)
{
var localDate = TimeZoneInfo.ConvertTimeFromUtc(utcTime, server.TimeZone);
List<KpiSchedule> returnList = new List<KpiSchedule>
{
plant.HourlySchedule
};
if (localDate.Hour == 0)
{
returnList.Add(plant.DailySchedule);
}
return returnList;
}
private static DateTime GetUtcTopHourDate(int ForceHour = -1)
{
return new DateTime(
DateTime.UtcNow.Year,
DateTime.UtcNow.Month,
DateTime.UtcNow.Day,
DateTime.UtcNow.Hour,
0,
0,
DateTimeKind.Utc
);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>There are some things I would do differently. I think <code>GetScheduleList</code> should be a public method in your <code>PlantConfiguration</code> class.</p>\n\n<p>The primary method you are concerned about, <code>UpdateValues</code> is private. You declare <code>schedulesToUpdate</code> as an... | {
"AcceptedAnswerId": "202653",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T14:42:16.187",
"Id": "202587",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Creating an enumerable by calling a function returning enumerables"
} | 202587 |
<p>The following small function receives a range and returns it with only the cells that contain constants or <code>Nothing</code> if there's none.</p>
<pre><code>Private Function GetConstants(ByVal Cells As Range) As Range
On Error GoTo ErrHandler
Set GetConstants = Intersect(Arg1:=Cells.SpecialCells(Type:=xlCellTypeConstants), Arg2:=Cells)
Exit Function
ErrHandler: If Err.Number <> 1004 Then Err.Raise Number:=Err.Number, Source:=Err.Source, Description:=Err.Description, HelpFile:=Err.HelpFile, HelpContext:=Err.HelpContext
End Function
</code></pre>
<p>If there's no constants in the range <code>Cells</code>, the <code>Range.SpecialCells</code> method throws the error:</p>
<blockquote>
<p>Run-time error '1004':</p>
<p>Application-defined or object-defined error</p>
</blockquote>
<p>The error handler ignores it and returns the default value <code>Nothing</code>.</p>
<p>The use of the <code>Intersect</code> method fixes the issue that occurs when the range is only one cell. It otherwise treats it as the whole sheet.</p>
<hr />
<p>Question:</p>
<p>Is there any edge case not being handled or not in the best overall way?</p>
<p>Did I miss something, are the names ideal, should I check <code>If Not TypeOf Cells Is Range Then Exit Function</code>, or maybe use another way instead of <code>Intersect</code> and checking <code>Err.Number <> 1004</code>?</p>
| [] | [
{
"body": "<p>I like the use of <strong>Intersect</strong> to handle single cell ranges. </p>\n\n<p>You should avoid using <strong>Cells</strong> as variable name because it could easily be confused with the built in <strong>Cells</strong> collection. By contrast <strong>Range As Range</strong> could be used ... | {
"AcceptedAnswerId": "202594",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T15:43:37.287",
"Id": "202590",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Function to get constants of range"
} | 202590 |
<p>A school student here. Hope you are having a nice day.</p>
<p>So, I implemented a Singly Linked List in Python and of course also a Node. I tried to make it have the best Big O time complexity I could. Here it is, please tell me what do you think can be improved, changed, etc.</p>
<pre><code>class LinkedList():
"""
A basic class implementing a Singly Linked List.
LinkedList() - new empty linked list
LinkedList(iterable) - new linked list with items of iterable:
head - iterable[0] tail - iterable[-1]
"""
class Node():
"""A class for a singly linked list node."""
def __init__(self, value):
"""Initialize default values."""
self.value = value
self.link = None # by default a node is linked to nothing
def __init__(self, seq=()):
"""Initialize default values."""
self.size = 0
# While instantiated there are no elements in list
# but None, to which will be linked the first element
self.head = None
node = self.head
for i in seq: # iterate through and copy contents
new_node = self.Node(i)
if node:
node.link = new_node
node = node.link
else:
# runs only once, at the first item,
# when the list is empty(head is None)
self.head = new_node
node = self.head
self.size += 1
def __len__(self):
"""Implement len(self). Return the number of items in list."""
return self.size
def __iter__(self):
"""Implement iter(self)."""
node = self.head
while node:
yield node.value
node = node.link
def __repr__(self):
"""Return repr(self)."""
return self.__str__()
def __str__(self):
"""Define string casting for the list."""
node = self.head
s = ''
while node:
s += str(node.value) + ' => '
node = node.link
return s + 'None'
def __getitem__(self, index):
"""Implement indexing access: a[b]."""
# change index if negative
index = self.size + index if index < 0 else index
if 0 <= index < self.size:
i = 0
node = self.head
while i < index:
node = node.link
i += 1
return node.value
else:
raise IndexError('list index out of range')
def __setitem__(self, index, item):
"""Implement indexed assignment."""
# change index if negative
index = self.size + index if index < 0 else index
if 0 <= index < self.size:
i = 0
node = self.head
while i < index:
node = node.link
i += 1
node.value = item
else:
raise IndexError('list assignment index out of range')
def __delitem__(self, index):
"""Implement indexed deletion."""
# change index if negative
index = self.size + index if index < 0 else index
# check .remove() method for explanation
if 0 < index < self.size:
i = 0
node = self.head
while i < index - 1:
node = node.link
i += 1
node.link = node.link.link
self.size -= 1
elif index == 0:
self.head = self.head.link
self.size -= 1
else:
raise IndexError('list deletion index out of range')
def __contains__(self, item):
"""Implement 'in' access: if item in..."""
i = 0
node = self.head
while i < self.size:
if node.value == item:
return True
node = node.link
i += 1
return False
def insertStart(self, item):
"""Insert an item to the head of the link."""
self.size += 1
new_node = self.Node(item)
if not self.head: # check in the list has a head
self.head = new_node
else:
new_node.link = self.head # link the node to the head
self.head = new_node # make it the head
def insertEnd(self, item):
"""Insert an item at the tail."""
new_node = self.Node(item)
if self.head: # check if list is empty
node = self.head
while node.link: # iterate through the list to get to the tail
node = node.link
node.link = new_node
else:
self.head = new_node # create a head
self.size += 1
def insert(self, index, item):
"""Insert given item before specified index."""
t = type(index)
if t is not int:
raise TypeError('{} cannot be interpreted as an integer'.format(t))
else:
# change index if negative
index = self.size + index if index < 0 else index
if index > self.size - 1: # check for special cases
self.insertEnd(item)
elif index <= 0:
self.insertStart(item)
else: # iterate through and insert item
i = 0
node = self.head
while i < index - 1:
node = node.link
i += 1
new_node = self.Node(item)
new_node.link = node.link
node.link = new_node
self.size += 1
def remove(self, value=None):
"""
Remove the first occurence of the value(default head).
Raises a ValueError if the is not present.
Raises an IndexError if the list is empty.
"""
if not self.head:
raise IndexError("remove from an empty list")
else:
if value: # check if value is provided
if self.head.value == value:
self.head = self.head.link
else:
node = self.head
try:
# iterate through the list while checking for
# given value and being one step behind to be
# able to efficiently remove it
while node.link.value != value:
node = node.link
node.link = node.link.link
except AttributeError: # mute the original error
raise ValueError('value not present in list') from None
else:
self.head = self.head.link # value not present. remove head
self.size -= 1
def index(self, item):
"""Return index of first occurence of specified item. -1 if absent."""
i = 0
node = self.head
while i < self.size:
if node.value == item:
return i
node = node.link
i += 1
return -1
def reverse(self):
"""Reverse list in place."""
current_node = self.head
prev_node = None
next_node = None
while current_node:
next_node = current_node.link
current_node.link = prev_node
prev_node, current_node = current_node, next_node
self.head = prev_node
</code></pre>
| [] | [
{
"body": "<p>Your code is good because you implemented many <code>__methods__</code> that allow natural use of the class with <code>for</code> and <code>print</code> built-ins.</p>\n\n<p>A great way to make it easier to improve the code is to add automatic tests, for example with <code>doctest</code>.</p>\n\n<... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T16:12:08.780",
"Id": "202592",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"linked-list"
],
"Title": "Singly Linked List in Python"
} | 202592 |
<p>This code finds duplicate files in Linux.
I assume that MD5 hash will return unique hash number.
What can I improve in this code? </p>
<pre><code>#!/usr/bin/python;
import sys
import subprocess
import os
import hashlib
FIND_CMD = "find . -name \*.* -print"
BUFFER = 65536
#Get path from the user
root_path = sys.argv[1]
#Checks that the user sent path
if not root_path:
print("Error: No file specified.Please try again ")
sys.exit(1)
#Chage working path
os.chdir(root_path)
#Get all the possible paths under the given directory
dirty_out = subprocess.run(FIND_CMD.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
file_list = dirty_out.stdout.decode("utf-8").splitlines()
#Find files with the same size and add to dic
same_size = dict()
for file in file_list:
path = root_path + file[1:]
if os.path.isdir(path):
continue
if os.path.exists(path):
file_size = os.path.getsize(path)
#Add the path to dictionary by size
if file_size not in same_size:
same_size[file_size] = list([path])
else:
same_size[file_size].append(path)
#Find files with the same size and hash code
file_signatures = dict()
for size in same_size:
if len (same_size[size]) > 1:
i = 0
while i < len (same_size[size]):
# Hash file content with read buffer
md5 = hashlib.md5()
path = same_size[size][i]
md5 = hashlib.md5()
with open(path, 'rb') as f:
while True:
data = f.read(BUFFER)
if not data:
break
md5.update(data)
md5_sig = md5.hexdigest()
# Add to dictionary only files with the same size and hash
if md5_sig not in file_signatures:
file_signatures[md5_sig] = list([path])
else:
file_signatures[md5_sig].append(path)
i=i+1
#Prints the path of all the duplicate files separated with ,
for sig in file_signatures:
if len(file_signatures[sig]) > 1:
print("{0}\n".format(",".join(file_signatures[sig])))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T13:26:19.220",
"Id": "390536",
"Score": "1",
"body": "If you're not writing this for coding practice, you ought to be aware of the `rdfind` program, which does the same thing (and more)."
}
] | [
{
"body": "<p>Please be careful with the indentation because it looks like there are different number of spaces for different indentation depths and it looks very weird.</p>\n\n<p>Minor improvements:</p>\n\n<h3>Repetition</h3>\n\n<pre><code> md5 = hashlib.md5()\n path = same_size[size][i]\n md5 = hashlib.md5()\... | {
"AcceptedAnswerId": "202604",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T16:27:32.410",
"Id": "202593",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"file-system",
"linux",
"hashcode"
],
"Title": "Find duplicate files in Linux"
} | 202593 |
<p>I have a matrix <code>A</code> containing numeric values and a matrix <code>B</code> containing 0/1s:</p>
<pre><code>A <- matrix(1:25, 5, 5)
B <- matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0), 5, 5)
A B
1 6 11 16 21 0 0 1 0 0
2 7 12 17 22 0 0 0 0 1
3 8 13 18 23 0 0 0 0 1
4 9 14 19 24 0 0 1 0 0
5 10 15 20 25 0 0 1 0 0
</code></pre>
<p>I want to extract the elements of <code>A</code> where <code>B==1</code> in row order. The desired result is:</p>
<pre><code>11 22 23 14 15
</code></pre>
<p>I've come up with two possible ways to do this:</p>
<pre><code>#1
rowSums(A*B)
#2
t(A)[as.logical(t(B))]
</code></pre>
<p>It seems like there should be a better (more elegant or faster) way to do this...</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T16:45:42.793",
"Id": "390392",
"Score": "0",
"body": "Did you profile both?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T16:49:01.160",
"Id": "390394",
"Score": "0",
"body": "@Mast -- N... | [
{
"body": "<p>While <code>rowSums(A*B)</code> looks pretty nice for me, you can also try</p>\n\n<pre><code>A[which(t(B) == 1, arr.ind = T)[,2:1]]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T13:46:4... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T16:37:39.863",
"Id": "202598",
"Score": "2",
"Tags": [
"matrix",
"r"
],
"Title": "Extract numerics from matrix A with logical matrix B"
} | 202598 |
<p>I'm new to python and programming in general and I found Project Euler problems a good way to practice python. But my code is pretty slow. It seems to work, didn't wait long enough for the code to print the answer though. Any tips on how to make it faster ? I assume that you don't have to check <strong>every single number</strong> but that's just a guess any help appreciated.</p>
<pre><code>tri_nums = [1]
divisors = []
temp_divisors =[]
while len(divisors) <= 500:
for x in range(1, tri_nums[-1] + 1):
if tri_nums[-1] % x == 0:
temp_divisors.append(x)
if len(temp_divisors) > len(divisors):
divisors = temp_divisors[:]
temp_divisors.clear()
print("Number: " + str(tri_nums[-1]))
print("Number of divisors: " + str(len(divisors)))
print("List of divisors: " + str(divisors))
tri_nums.append(len(tri_nums) + 1 + tri_nums[-1])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T18:11:56.703",
"Id": "390415",
"Score": "1",
"body": "You only need to check for divisors up to the square root of the number"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T18:18:19.523",
"Id": "... | [
{
"body": "<p>To avoid spoiling the problem for you, I'll offer some hints.</p>\n\n<p>Hint 1:</p>\n\n<blockquote class=\"spoiler\">\n <p> Have you read the Wikipedia article about the <a href=\"https://en.wikipedia.org/wiki/Triangular_number\" rel=\"noreferrer\">triangular numbers</a>? It's always worth doing ... | {
"AcceptedAnswerId": "202855",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T18:07:26.800",
"Id": "202602",
"Score": "0",
"Tags": [
"python",
"performance",
"beginner",
"mathematics"
],
"Title": "Project Euler problem 12 Python"
} | 202602 |
<p>I have this xml file and i am parsing it with php simplexml.</p>
<p>My XML file looks like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<noticias>
<noticia url="noticia-1">
<titulo>título da notícia 1</titulo>
<desc>plain text.</desc>
<texto>plain text.</texto>
<img></img>
<in>Publico</in>
</noticia>
...
</noticias>
</code></pre>
<p>In my php page i parse it like this:</p>
<pre><code>$file = 'xml/noticias.xml';
if(file_exists($file)) {
$xml = simplexml_load_file($file);
foreach($items as $item) {
$titulo = htmlentities($item->titulo, ENT_QUOTES, 'utf-8');
$desc = htmlentities($item->desc, ENT_QUOTES, 'utf-8');
$url = htmlentities($item['url'], ENT_QUOTES, 'utf-8');
if(strlen($titulo) < 3) {$titulo = 'T&iacute;tulo em falta';} else {$titulo = $titulo;}
if(strlen($desc) < 3) {$desc = 'Descri&ccedil;&atilde;o em falta';} else {$desc = $desc;}
if(strlen($url) < 3) {$h3 = '<h3>'.$titulo.'</h3>';} else {$h3 = '<a href="noticia/'.$url.'"><h3>'.$titulo.'</h3></a>';}
?>
<div class="col-lg-3 col-md-6">
<div class="item">
<div class="content">
<?php echo $h3; ?>
<p><?php echo $desc; ?></p>
</div>
</div>
</div>
<?php
}
}
else {
// do something... throw error message
}
</code></pre>
<p>Is this ok? i mean, i escape values when i get from xml. Is it ok to do it like this or should i escape values on echo? is there any danger to leave as i have?</p>
<p>other thing... i have the xml files protected with htaccess. right now, they can only be edited directly. no scripts to edit them.</p>
| [] | [
{
"body": "<p>My preference is to leave the html escaping until the last minute.</p>\n\n<p>Here are some changes you could make to simplify your code.</p>\n\n<p>Code should work but there is no link between $xml and $items, so unable to test.</p>\n\n<pre><code><?php\n\n$file = 'xml/noticias.xml';\n\n// guard... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T19:32:27.397",
"Id": "202606",
"Score": "4",
"Tags": [
"php",
"xml",
"escaping"
],
"Title": "Displaying text extracted from XML using PHP simplexml"
} | 202606 |
<p>I have written a simple snippet of code that implements a function that returns a list of primes up to a certain integer <code>n</code>. Assuming that this function could be called several times in the script for different values of <code>n</code>, I wanted to make it as "lazy" as possible—that is, able to reuse previously-calculated variables.</p>
<p>Here is the code (assume <code>isPrime(n)</code> returns <code>True</code> if <code>n</code> is prime and <code>False</code> otherwise):</p>
<pre><code>primes = []
def pi(n):
global primes
if len(primes) == 0:
# Full
for i in range(2, n + 1):
if isPrime(i):
primes.append(i)
return primes
elif n <= primes[-1]:
# Lazy
return list(filter(lambda m: m <= n, primes))
else:
# Semi-lazy
for i in range(primes[-1] + 1, n + 1):
if isPrime(i):
primes.append(i)
return primes
</code></pre>
<p>The problem is, as you may have spotted, that I'm using a global variable (<code>primes</code>) to store the list of primes, and later modifying it inside the <code>pi</code> function. I've heard that relying on mutable global variables is a bad design choice. What are better ways to implement this?</p>
<hr>
<p>This question should actually be generalized to the following: what's the best design pattern to implement a 'lazy' function (i.e. a function that reuses previously calculated values)?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T03:34:33.233",
"Id": "390465",
"Score": "2",
"body": "Unrelated to your original question, but even numbers can never be prime (2 notwithstanding) so the For i in range... isprime(i) can be put into a statement to check if i is e... | [
{
"body": "<p>The technique you're looking for is called <strong>memoization</strong> (or in other contexts it might have names like <strong>caching</strong>). Lazy evaluation is something else entirely.</p>\n\n<p>Memoization is the canonical example for how decorators work in Python, but you don't need to lear... | {
"AcceptedAnswerId": "202627",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T21:52:54.577",
"Id": "202616",
"Score": "1",
"Tags": [
"python",
"beginner",
"design-patterns",
"lazy"
],
"Title": "Lazy prime counting function"
} | 202616 |
<p>I wrote an Othello version with limited UI to try to learn python(3.7) and OOP.<br>
The game has 8 classes.<br>
Start creates a controller object which is responsible for the logical flow of the game. Controller creates AI objects that chooses moves based on difficulty settings.<br>
Start also creates a GameFrame object which controls the UI (GameFrame is passed two function from Controller so that Controller can respond to player actions). GameFrame has the Tk(), and adds ScoreFrame(score and status), GameButtons(main game frame) and playerselectUI(frame). the GameButtons class populates the board with GameButton which at the moment functions like a regular tkinter.Button</p>
<p>I would really like some feedback regarding my OOP choices. I've never done peer review before and I'm curious if my structure makes sense to anyone else, and if my code is readable.</p>
<p>Thank you for your time.</p>
<p><strong>Start.py</strong></p>
<pre><code>from Controller import Controller
from GameFrame import GameFrame
# Set up a controller object, and give it access to the graphical representation of the board
# Board is passed the click and startnewgame functions from the controller so that controller
# can decide what happens when buttons are clicked
if __name__ == '__main__':
controller = Controller()
game = GameFrame("title" ,controller.click, controller.start_new_game)
controller.game = game
game.start()
pass
</code></pre>
<p><strong>Controller.py</strong></p>
<pre><code>from Ai import Ai
class Controller(object):
# Set up a 8x8 board of zeroes (empty spots) ones(black bricks) and twos (white bricks)
# AIs set to None (Human controllers) at start
def __init__(self):
self.empty = 0
self.player = 1
self.opponent = 2
self.ais = [None, None]
self.buttons = [[0 for _ in range(8)]for _ in range(8)]
self.reset_board()
def reset_board(self):
for x in range(8):
for y in range(8):
self.buttons[x][y] = 0
self.buttons[3][3] = 2
self.buttons[4][4] = 2
self.buttons[3][4] = 1
self.buttons[4][3] = 1
self.whiteCount = 2
self.blackCount = 2
self.emptyCount = 60
self.player = 1
self.opponent = 2
# Reset the board to starting positions.
#Set AIs as selected by the player in playerSelectUI. Start the first move
# p1 and p2 are ints
def start_new_game(self, p1, p2):
self.reset_board()
self.game.reset_board()
self.ais= [self.get_AI_level_or_human(p1), self.get_AI_level_or_human(p2)]
self.next_move()
# 0 returns easiest AI, 1 normal AI, 2 hard AI.
# 3 returns None which sets player as human
# x is an int
def get_AI_level_or_human(self, x):
if x == 3:
return None
else:
return Ai(x)
# Check if player has a move to perform, if not switch player.
# If that player doesn't have any legal moves either -> end game
# If one of the players has a move to perform,
# do the AIs move, or wait for player to click a move
def next_move(self):
if len(self.find_all_legal_moves()) == 0:
self.update_status(self.get_player_color() + " has no legal moves, switching player")
self.switch_player()
if len(self.find_all_legal_moves()) == 0:
self.update_status("No more legal moves, ending game. " + self.get_winner())
return None
if self.emptyCount == 0:
self.update_status("No more empty squares, ending game. " + self.get_winner())
else:
if self.ais[self.player-1] != None:
self.game.root.after(100,self.ai_move)
# Get all legal moves and have the AI determine which move to make
# Flip those bricks
def ai_move(self):
toFlip = self.ais[self.player-1].make_move(self.find_all_legal_moves())
self.perform_move(toFlip)
# Check every square on the board to see if a brick can be placed there.
# Return a list of squares which are legal
# and which bricks will be turned if you place brick there
def find_all_legal_moves(self):
legal = []
lega = []
for x in range(8):
for y in range(8):
lega = self.check_if_legal(x, y)
if len(lega) > 0:
legal.append(lega)
return legal
# Called from the GameButtons when a player clicks.
# Check if player can place brick at that square, and perform the turn
# x and y are ints
def click(self, x, y):
toTurn = self.check_if_legal(x,y)
if len(toTurn) > 0:
self.perform_move(toTurn)
else: self.update_status(
"That's not a legal move, try again. Current player: " + self.get_player_color())
# check if current player is white or black
def get_player_color(self):
if self.player == 2:
return "white"
else: return "black"
# If current player is black, change to white. Else change to black.
def switch_player(self):
self.opponent = self.player
if self.player == 1:
self.player = 2
else: self.player = 1
self.update_status("Current player: " + self.get_player_color())
# Update scoreboard. If the move placed 5 white bricks on the board
# then black must have lost 4 and "empty" lost one.
# x is int and represents how many bricks were altered
def update_count(self, x):
if self.player == 2:
self.whiteCount += x
self.blackCount -= x-1
else:
self.whiteCount -= x-1
self.blackCount += x
self.emptyCount -= 1
self.game.update_texts(self.whiteCount, self.blackCount, self.emptyCount)
# After move has been selected update gameboard and graphics to reflect changes.
# Swap current player and opponent
# Prepare for next move.
# toTurn is a list of squares to turn
def perform_move(self, toTurn):
self.flip_buttons(toTurn)
self.update_count(len(toTurn))
self.switch_player()
self.next_move()
# Look at one particular square and see if current player can place a brick there.
# If yes, return a list of squares that now will get players color
def check_if_legal(self,x,y):
toTurn = []
if self.buttons[x][y] == self.empty:
for i in range(9):
if i == 4:
continue
toTurnDir = self.check_direction(x,y,self.get_Y_direction(i), self.get_X_direction(i))
if toTurnDir != None:
toTurn += toTurnDir
if len(toTurn) > 0:
toTurn.append([x, y])
return toTurn
# Change values in the gameboard and change the graphics for those squares
def flip_buttons(self, toTurn):
for brick in toTurn:
self.buttons[brick[0]][brick[1]] = self.player
self.game.change_color(brick[0], brick[1],self.get_player_color())
# Get direction to move along the Y axis(rows), -1:up, 0:no movement, 1:up
def get_Y_direction(self,y):
dirX = y % 3 - 1
return dirX
# Get direction to move along X axis (column), -1:left, 0:no movement, 1:right
def get_X_direction(self, x):
dirY = x // 3 - 1
return dirY
# Check that square being clicked is next to an opponent.
# Keep checking that direction as long as there's an opponent
# If you run outside the board or hit an empty square:
# return None indicating no bricks will be turned in that direction
# If you find a brick of your own color after finding an opponent then direction is legal.
# Return list of squares that will be turned
def check_direction(self, x, y, dirX, dirY):
toTurn = []
if x+dirX > 7 or x + dirX < 0 or y + dirY < 0 or y + dirY > 7:
return None
if self.buttons[x+dirX][y+dirY] == self.opponent:
toTurn.append([x+dirX, y+dirY])
for i in range(2,8):
if x + dirX * i > 7 or x + dirX*i < 0 or y + dirY*i < 0 or y + dirY*i > 7:
return None
if self.buttons[x+dirX*i][y+dirY*i] == self.opponent:
toTurn.append([x+dirX*i, y+dirY*i])
if self.buttons[x+dirX*i][y+dirY*i] == self.empty:
return None
if self.buttons[x+dirX*i][y+dirY*i] == self.player:
return toTurn
def update_status(self, text):
self.game.scoreFrame.update_status(text)
def get_winner(self):
if self.whiteCount > self.blackCount:
return "White wins the game"
if self.blackCount > self.whiteCount:
return "Black wins the game"
return "The game ends in a tie"
</code></pre>
<p><strong>Ai.py</strong></p>
<pre><code>import random as ran
class Ai(object):
def __init__(self, difficulty):
'''
Constructor
'''
self.difficulty = difficulty
# Select a move from the list of legal moves, based on what difficulty AI is in use.
def make_move(self, possibleMoves):
if self.difficulty == 0:
return self.random_move(possibleMoves)
if self.difficulty == 1:
return self.greedy(possibleMoves)
if self.difficulty == 2:
return self.hard(possibleMoves)
# Select a random move out of the legal ones.
# Known as "easy" difficulty
def random_move(self, possibleMoves):
select = ran.randrange(len(possibleMoves))
return possibleMoves[select]
# Check the list of legal moves and select the one that will turn the most bricks.
# If several moves turns the same amount of bricks, return a random one of them
# Known as "normal" difficulty
def greedy(self, possibleMoves):
biggest = 0
greediestMoves = []
for x in range(len(possibleMoves)):
if len(possibleMoves[x]) == biggest:
greediestMoves.append(possibleMoves[x])
if len(possibleMoves[x]) > biggest:
biggest = len(possibleMoves[x])
greediestMoves = []
greediestMoves.append(possibleMoves[x])
select = ran.randrange(len(greediestMoves))
return greediestMoves[select]
# Values indicating how "good" a square is to have, used only by the hardest AI
square_values = [
[99, -8, 8, 6, 6, 8, -8, 99],
[-8, -24, -4, -3, -3, -4, -24, -8],
[8, -4, 7, 4, 4, 7, -4, 8],
[6, -3, 4, 0, 0, 4, -3, 6],
[6, -3, 4, 0, 0, 4, -3, 6],
[8, -4, 7, 4, 4, 7, -4, 8],
[-8, -24, -4, -3, -3, -4, -24, -8],
[99, -8, 8, 6, 6, 8, -8, 99]
]
# Go trough the list of legal moves to find the move that adds the most "value" based on the valuegrid.
# If several moves add the same "value", randomly return one of them
# Known as "hard" difficulty
def hard(self, possibleMoves):
best = -99
bestMoves = []
for x in range(len(possibleMoves)):
value = self.square_values[possibleMoves[x][-1][0]][possibleMoves[x][-1][1]]
if value == best:
bestMoves.append(possibleMoves[x])
best = value
if value > best:
bestMoves = [possibleMoves[x]]
best = value
return bestMoves[ran.randrange(len(bestMoves))]
</code></pre>
<p><strong>GameFrame.py</strong></p>
<pre><code>from GameButtons import GameButtons
from tkinter import Tk, Frame, BOTH, X
from ScoreFrame import ScoreFrame
from playerSelectUI import PlayerSelectUi
class GameFrame(Frame):
# Main UI frame. Starts a Tk() and adds other frames to it.
def __init__(self, params, click, start_new_game):
self.root = Tk()
self.root.geometry("500x600")
self.scoreFrame = ScoreFrame(self.root)
self.scoreFrame.update_texts(2, 2, 60)
self.scoreFrame.pack(fill = X)
self.buttons = GameButtons(click)
self.buttons.pack(fill=BOTH, expand=1)
self.playerSelect = PlayerSelectUi(start_new_game)
self.playerSelect.pack(fill = BOTH)
def change_color(self, x, y, color):
self.buttons.change_color(x, y, color)
def update_texts(self, white, black, empty):
self.scoreFrame.update_texts(white, black, empty)
def start(self):
self.root.mainloop()
def reset_board(self):
self.buttons.reset_board()
</code></pre>
<p><strong>ScoreFrame.py</strong></p>
<pre><code>from tkinter import Frame, StringVar, E,W, Label
class ScoreFrame(Frame):
'''
Set up a frame where scores are displayed. (Current amount of black/white and empty bricks)
Class used by and added to GameFrame
'''
def __init__(self, params):
'''
Constructor
Set up StringVars and add them to the labels
'''
super().__init__()
self.whiteTextVar = StringVar()
self.blackTextVar = StringVar()
self.emptyTextVar = StringVar()
self.columnconfigure(0, weight = 1)
self.columnconfigure(1, weight = 1)
self.columnconfigure(2, weight = 1)
self.whiteTextVar.set("White discs: ")
self.blackTextVar.set("Black discs: ")
self.emptyTextVar.set("Empty discs: ")
self.whiteCount = Label(self, textvariable = self.whiteTextVar, bg = "white")
self.whiteCount.grid(row = 0, column = 0, sticky=(E, W))
self.blackCount = Label(self, textvariable = self.blackTextVar, bg = "red")
self.blackCount.grid(row = 0, column = 1, sticky=(E, W))
self.emptyCount = Label(self, textvariable = self.emptyTextVar, bg = "yellow")
self.emptyCount.grid(row = 0, column = 2, sticky=(E, W))
self.status_text = StringVar()
self.status_text.set("")
self.status_bar = Label(self, textvariable = self.status_text)
self.status_bar.grid(row = 1, column = 0, columnspan = 3, sticky=(E,W))
# Change the textVariables to update the text.
def update_texts(self, white, black, empty):
self.whiteTextVar.set("White discs: %s" %white)
self.blackTextVar.set("Black discs: %s" %black)
self.emptyTextVar.set("Empty discs: %s" %empty)
def update_status(self, text):
self.status_text.set(text)
</code></pre>
<p><strong>GameButtons.py</strong></p>
<pre><code>from tkinter import E, W, N, S, Frame, PhotoImage
from GameButton import GameButton
class GameButtons(Frame):
# Create a frame with the buttons for the game, is used by GameFrame
def __init__(self, click):
super().__init__()
self.buttons = [[0 for _ in range(8)]for _ in range(8)]
for x in range(8):
for y in range(8):
b = GameButton(self, 0)
b.grid(row = x, column = y,sticky=(N, S, E, W))
b.configure(text = "%s%s"%(x,y), command = lambda row = x, col = y: click(row, col))
self.buttons[x][y] = b
self.columnconfigure(y, weight = 1)
self.rowconfigure(x, weight = 1)
self.reset_board()
def change_color(self, x, y, color):
self.buttons[x][y].configure(bg = color)
def get_brick(self, x, y):
return self.buttons[x][y].get_brick()
def reset_board(self):
for x in range(8):
for y in range(8):
self.buttons[x][y].configure(bg = "green")
self.buttons[3][3].configure(bg = "white")
self.buttons[4][4].configure(bg = "white")
self.buttons[4][3].configure(bg = "black")
self.buttons[3][4].configure(bg = "black")
</code></pre>
<p><strong>playerSelectUI.py</strong></p>
<pre><code>from tkinter import Frame, Label, Button, SUNKEN, RAISED, N, S, E, W
class PlayerSelectUi(Frame):
'''
Set up a frame where the user can select AI / Human controller for each of the players
Class used by and added to GameFrame
'''
# Set up the UI that allows player to select difficulty of opponent
# start_new_game is a function passed from Controller
def __init__(self, start_new_game):
'''
Constructor
'''
super().__init__()
self.selection1 = [None] * 4
self.selection2 = [None] * 4
self.selectedP1 = 3 #default to human controller
self.selectedP2 = 3
self.p1label = Label(self, text = "Player 1")
self.p1label.grid(row = 0, column = 0)
self.selection1[0] = self.player1SelectButton1 = Button(self, text = "Easy")
self.player1SelectButton1.grid(row = 0, column = 1,sticky=(N, S, E, W))
self.player1SelectButton1.configure(command = lambda: self.clickP1(0))
self.selection1[1] = self.player1SelectButton2 = Button(self, text = "Normal")
self.player1SelectButton2.grid(row = 0, column = 2, sticky = (N, S, E, W))
self.player1SelectButton2.configure(command = lambda: self.clickP1(1))
self.selection1[2] = self.player1SelectButton3 = Button(self, text = "Hard")
self.player1SelectButton3.grid(row = 0, column = 3,sticky=(N, S, E, W))
self.player1SelectButton3.configure(command = lambda: self.clickP1(2))
self.selection1[3] = self.player1SelectButton4 = Button(self, text = "Human")
self.player1SelectButton4.grid(row = 0, column = 4,sticky=(N, S, E, W))
self.player1SelectButton4.configure(
relief = SUNKEN, command = lambda: self.clickP1(3))
self.p2label = Label(self, text = "Player 2")
self.p2label.grid(row = 1, column = 0)
self.selection2[0] = self.player2SelectButton1 = Button(self, text = "Easy")
self.player2SelectButton1.grid(row = 1, column = 1,sticky=(N, S, E, W))
self.player2SelectButton1.configure(command = lambda: self.clickP2(0))
self.selection2[1] = self.player2SelectButton2 = Button(self, text = "Normal")
self.player2SelectButton2.grid(row = 1, column = 2, sticky = (N, S, E, W))
self.player2SelectButton2.configure(command = lambda: self.clickP2(1))
self.selection2[2] = self.player2SelectButton3 = Button(self, text = "Hard")
self.player2SelectButton3.grid(row = 1, column = 3,sticky=(N, S, E, W))
self.player2SelectButton3.configure(command = lambda: self.clickP2(2))
self.selection2[3] = self.player2SelectButton4 = Button(self, text = "Human")
self.player2SelectButton4.grid(row = 1, column = 4,sticky=(N, S, E, W))
self.player2SelectButton4.configure(
relief = SUNKEN, command = lambda: self.clickP2(3))
self.startGameButton = Button(self, text = "Start Game")
self.startGameButton.grid(row = 2, column = 0)
self.startGameButton.configure(
command = lambda: start_new_game(self.selectedP1, self.selectedP2))
# Select difficulty of player1. Can set as AI or human player.
# x 0 = easy, 1 = normal, 2 = hard, 3 = human
def clickP1(self, x):
self.selectedP1 = x
for b in range(len(self.selection1)):
if b == x:
self.selection1[b].configure(relief =SUNKEN)
else:
self.selection1[b].configure(relief=RAISED)
# Select difficulty of player2. Can set as AI or human player
def clickP2(self, x):
self.selectedP2 = x
for b in range(len(self.selection2)):
if b == x:
self.selection2[b].configure(relief =SUNKEN)
else:
self.selection2[b].configure(relief=RAISED)
</code></pre>
<p><strong>GameButton.py</strong></p>
<pre><code>from tkinter import Button
class GameButton(Button):
'''
classdocs
extends tkinter.Button to be able to store a value.
Class currently adds no value and could be replaced with tkinter.Button.
'''
def __init__(self, master, brick):
Button.__init__(self, master)
self.brick = brick
# Currently not used
def get_brick(self):
return self.brick
#def animate_flip():
#def change_icon():
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T03:27:09.650",
"Id": "390464",
"Score": "0",
"body": "The indentation for some of your code is formatted incorrectly."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T22:38:33.477",
"Id": "202618",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"game",
"tkinter"
],
"Title": "OOP Othello in Python with tkinter UI and basic AI"
} | 202618 |
<h2>Intro</h2>
<p>I wrote this code to solve <a href="https://www.websudoku.com" rel="nofollow noreferrer">sudoku</a> as part of an assignment (closed now) for an <a href="https://courses.edx.org/courses/course-v1:ColumbiaX+CSMM.101x+2T2018/course/" rel="nofollow noreferrer">AI course</a>. The program works correctly and I am quite happy with the code. Please let me know if I am rightfully pleased or if the implementation could be so much better. </p>
<p>This is a pure code review question so don't hold back on anything.</p>
<h2>The problem</h2>
Input
<p>The input is an 81 character string representing the sudoku board with digits listed row-wise. Empty spaces are represented by zeros.<br>
<code>000000000302540000050301070000000004409006005023054790000000050700810000080060009</code></p>
Output
<p>The program must output the solved sudoku board to a text file <code>output.txt</code> in the same string representation as the input.<br>
<code>148697523372548961956321478567983214419276385823154796691432857735819642284765139</code></p>
Algorithm
<p>The algorithm is based on <a href="https://en.wikipedia.org/wiki/Sudoku_solving_algorithms#Backtracking" rel="nofollow noreferrer">backtracking search</a> (glorified DFS) but will also include a heuristic that treats the sudoku as a CSP (constraint satisfaction problem) to improves results. The heuristic <a href="http://cs188ai.wikia.com/wiki/Minimum_Remaining_Values" rel="nofollow noreferrer">Minimal Remaining Values</a> favours making assignments to those variables first that have the least number of available options. (Intuitively it is like attempting to solve the harder ones first so we can backtrack sooner if things don't pan out.)</p>
<p>The algorithm (from <a href="http://aima.cs.berkeley.edu/2nd-ed/" rel="nofollow noreferrer">AIMA</a>) :-</p>
<pre><code>function RECURSIVE-BACKTRACKING(assignment, csp) returns a solution, or failure
if assignment is complete then return assignment
var ← SELECT-UNASSIGNED-VARIABLE(VARIABLES[csp], assignment, csp)
for each value in ORDER-DOMAIN-VALUES(var , assignment, csp) do
if value is consistent with assignment according to CONSTRAINTS[csp] then
add {var = value} to assignment
result ← RECURSIVE-BACKTRACKING(assignment, csp)
if result != failure then return result
remove {var = value} from assignment
return failure
</code></pre>
<h2>Code</h2>
<p>Here is the code up for review:-</p>
<pre><code>import sys
import numpy as np
from functools import reduce
# Instructions:
# Linux>> python3 driver_3.py <soduku_str>
# Windows py3\> python driver_3.py <soduku_str>
# Inputs
print("input was:", sys.argv)
soduku_str=sys.argv[1]
def str2arr(soduku_str):
"Converts soduku_str to 2d array"
return np.array([int(s) for s in list(soduku_str)]).reshape((9,9))
soduku = str2arr(soduku_str)
slices = [slice(0,3), slice(3,6), slice(6,9)]
s1,s2,s3 = slices
allgrids=[(si,sj) for si in [s1,s2,s3] for sj in [s1,s2,s3]] # Makes 2d slices for grids
def var2grid(var):
"Returns the grid slice (3x3) to which the variable's coordinates belong "
row,col = var
grid = ( slices[int(row/3)], slices[int(col/3)] )
return grid
FULLDOMAIN = np.array(range(1,10)) #All possible values (1-9)
# Constraints
def unique_rows(soduku):
for row in soduku:
if not np.array_equal(np.unique(row),np.array(range(1,10))) :
return False
return True
def unique_columns(soduku):
for row in soduku.T: #transpose soduku to get columns
if not np.array_equal(np.unique(row),np.array(range(1,10))) :
return False
return True
def unique_grids(soduku):
for grid in allgrids:
if not np.array_equal(np.unique(soduku[grid]),np.array(range(1,10))) :
return False
return True
def isComplete(soduku):
if 0 in soduku:
return False
else:
return True
def checkCorrect(soduku):
if unique_columns(soduku):
if unique_rows(soduku):
if unique_grids(soduku):
return True
return False
# Search
def getDomain(var, soduku):
"Gets the remaining legal values (available domain) for an unfilled box `var` in `soduku`"
row,col = var
#ravail = np.setdiff1d(FULLDOMAIN, soduku[row,:])
#cavail = np.setdiff1d(FULLDOMAIN, soduku[:,col])
#gavail = np.setdiff1d(FULLDOMAIN, soduku[var2grid(var)])
#avail_d = reduce(np.intersect1d, (ravail,cavail,gavail))
used_d = reduce(np.union1d, (soduku[row,:], soduku[:,col], soduku[var2grid(var)]))
avail_d = np.setdiff1d(FULLDOMAIN, used_d)
#print(var, avail_d)
return avail_d
def selectMRVvar(vars, soduku):
"""
Returns the unfilled box `var` with minimum remaining [legal] values (MRV)
and the corresponding values (available domain)
"""
#Could this be improved?
avail_domains = [getDomain(var,soduku) for var in vars]
avail_sizes = [len(avail_d) for avail_d in avail_domains]
index = np.argmin(avail_sizes)
return vars[index], avail_domains[index]
def BT(soduku):
"Backtracking search to solve soduku"
# If soduku is complete return it.
if isComplete(soduku):
return soduku
# Select the MRV variable to fill
vars = [tuple(e) for e in np.transpose(np.where(soduku==0))]
var, avail_d = selectMRVvar(vars, soduku)
# Fill in a value and solve further (recursively),
# backtracking an assignment when stuck
for value in avail_d:
soduku[var] = value
result = BT(soduku)
if np.any(result):
return result
else:
soduku[var] = 0
return False
# Solve
print("solved:\n", BT(soduku))
print("correct:", checkCorrect(soduku))
# Output
with open('output.txt','w') as f:
output_str = np.array2string(soduku.ravel(), max_line_width=90, separator='').strip('[]') + ' Solved with BTS'
f.write(output_str)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T05:06:27.883",
"Id": "390469",
"Score": "1",
"body": "In def checkCorrect, you don’t need to nest he if statements, in fact it makes it look worse if you do. Instead you can have each be if not unique_columns return false, and simil... | [
{
"body": "<p>Your algo is good, I have a few styling nitpicks.</p>\n\n<ol>\n<li><p>Use a <code>if__name__ == '__main__'</code></p>\n\n<p>This will make sure that when you import this script the root lines will not be executed.</p></li>\n<li><p>Read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"no... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T22:55:28.367",
"Id": "202619",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Solving sudoku using Backtracking-Search (BTS) with Minimum Remaining Values (MRV) heuristic"
} | 202619 |
<p>My first delve into vimscript was writing a plugin for folding markdown lists.</p>
<p>I reckon there are a few idioms I'm missing here, so I would greatly appreciate any comments to improve the plugin.</p>
<p>I've noticed something akin to "header guards" in C family languages among popular plugins:</p>
<pre><code>if exists('g:touchdown__loaded')
finish
endif
" ... plugin body goes here ..."
let g:touchdown__loaded=1
</code></pre>
<hr>
<p>Logic for folding markdown lists is handled in the next chunk:</p>
<pre><code>function! IndentLevel(lnum)
return indent(a:lnum) / &shiftwidth
endfunction
function! NextNonBlankLine(lnum)
let numlines = line('$')
let current = a:lnum + 1
while current <= numlines
if getline(current) =~? '\v\S'
return current
endif
let current += 1
endwhile
return -2
endfunction
function! GetListFold(lnum)
if getline(a:lnum) =~? '\v^\s*$'
return '-1'
endif
let this_indent = IndentLevel(a:lnum)
let next_indent = IndentLevel(NextNonBlankLine(a:lnum))
if next_indent == this_indent
return this_indent
elseif next_indent < this_indent
return this_indent
elseif next_indent > this_indent
return '>' . next_indent
endif
endfunction
</code></pre>
<p>I've also set up a custom text for the lists, but I want to make sure my logic doesn't apply to folds that aren't markdown lists. Calling <code>foldtext</code> when the regex doesn't match is the closest thing I know to do:</p>
<pre><code>function! GetFoldText()
if (match(getline(v:foldstart), "[\s\t]*[-\*][\s\t]*.*") != -1)
let nl = v:foldend - v:foldstart
let linetext = substitute(getline(v:foldstart),"-","+",1)
let txt = linetext . "\t (" . nl . ' lines hidden)'
else
let txt = foldtext()
endif
return txt
endfunction
</code></pre>
<p>Finally I apply the fold strategy here. One thing to note is I want this to only apply to markdown files, but I'm not sure how to accomplish that idiomatically:</p>
<pre><code> setlocal foldtext=GetFoldText()
setlocal foldmethod=expr
setlocal foldexpr=GetListFold(v:lnum)
setlocal fillchars=fold:\
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T22:57:18.710",
"Id": "202620",
"Score": "2",
"Tags": [
"beginner",
"markdown",
"vimscript"
],
"Title": "Vim plugin for folding markdown lists"
} | 202620 |
<p>I'm attempting to minimise the "duplicate" functions I have defined which do <em>almost</em> the exact same thing, but I'm unsure of the best way to do it, I thought of passing in the type I'm looking for (e.g. 1 for GreyLeader, 2 for HeadMarshal etc.) but that ended up looking too messy for my liking.</p>
<p>Could you guys perhaps suggest a way to combine the three functions into one to return the same result? </p>
<p>Some notes:
- marshal is a list of a Marshal class which has Name, HeadMarshal, Marshal, GreyLeader boolean flags as properties
- usedMarshals is a list of Marshals
- each marshal can only be used twice, so the usedMarshals.count(marshal) = 2 is used for that</p>
<p>Code:</p>
<pre><code>def get_marshal():
marshal = random.choice(marshals)
if marshal.Marshal:
if not marshal in usedMarshals:
return marshal
elif marshal in usedMarshals:
if usedMarshals.count(marshal) < 2:
return marshal
elif usedMarshals.count(marshal) >= 2:
return get_marshal()
elif not marshal.Marshal:
return get_marshal()
def get_head_marshal():
marshal = random.choice(marshals)
if marshal.HeadMarshal:
if not marshal in usedMarshals:
return marshal
elif marshal in usedMarshals:
if usedMarshals.count(marshal) < 2:
return marshal
elif usedMarshals.count(marshal) >= 2:
return get_head_marshal()
elif not marshal.HeadMarshal:
return get_head_marshal()
def get_grey_leader():
marshal = random.choice(marshals)
if marshal.GreyLeader:
if not marshal in usedMarshals:
return marshal
elif marshal in usedMarshals:
if usedMarshals.count(marshal) < 2:
return marshal
elif usedMarshals.count(marshal) >= 2:
return get_grey_leader()
elif not marshal.GreyLeader:
return get_grey_leader()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T11:07:32.910",
"Id": "390517",
"Score": "1",
"body": "Maybe `get_leader(kind): leader = random.choice( (m for m in marshals if isinstance(m, kind) ) )` I cannot test it without the marshal classes. Where kind is `marshal.Marshal` or... | [
{
"body": "<ol>\n<li><p>Iterative instead of recursive</p>\n\n<p>Python doesn't really suit itself for recursion </p>\n\n<ul>\n<li>No tail recursion</li>\n<li>Generally slower</li>\n<li>Limited max depth</li>\n</ul></li>\n<li><p>Use <code>ALL_CAPS</code> for <em>constant</em> variables</p>\n\n<p><code>marshels<... | {
"AcceptedAnswerId": "202660",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T23:21:35.650",
"Id": "202622",
"Score": "1",
"Tags": [
"python",
"random"
],
"Title": "Three functions to select a random character, each of which can be used at most twice"
} | 202622 |
<p>I have made a password reveal feature, however the code is duplicated. Essentially all I want to be able to improve the code, however I'm not exactly sure how I could do this, all I know is it would consist of some form of loop.</p>
<p>I would go straight to jQuery but there is no need in 2018.</p>
<p>This is my functionality markup for my HTML (it’s the same for the login page and modal):</p>
<pre class="lang-html prettyprint-override"><code><form action="/login" method="post">
<div class="input-group">
<label style="display: none" for="username">Username :</label>
<input class="input-field width-100" type="text" autocomplete="username" name="username" placeholder="Enter Your Username">
</div>
<div class="input-group">
<label style="display: none" for="password">Password :</label>
<input class="input-field width-100 password" data-js="viewShowPassword" type="password" autocomplete="current-password" name="password" placeholder="Enter Your Password">
</div>
<div class="input-group--flex">
<div class="remember-me">
<input type="checkbox"/> Remember Me
</div>
<div class="show-password">
<a class="text-dark-green--dark" data-js="viewPasswordReveal">Show Password</a>
</div>
</div>
<div class="input-group">
<button class="submit width-100 input-field text-white background-red--light" style="padding: 5px">Login</button>
</div>
</form>
</code></pre>
<p>And this is my JavaScript, which shows both the login page and login modal code to demonstrate what I have so far:</p>
<pre class="lang-js prettyprint-override"><code>document.addEventListener("DOMContentLoaded", function(event) {
var modalShowPassword = document.querySelector("[data-js=modalPasswordReveal]");
var modalPassword = document.querySelector("[data-js=modalPassword]");
if(modalShowPassword || modalPassword) {
modalShowPassword.addEventListener("click", function (){
if (modalPassword.type === "password") {
modalPassword.type = "text";
} else {
modalPassword.type = "password";
}
});
}
var viewShowPassowrd = document.querySelector("[data-js=viewPasswordReveal]");
var viewPassword = document.querySelector("[data-js=viewShowPassword]");
if( viewShowPassowrd || viewPassword) {
viewShowPassowrd.addEventListener("click", function (){
if (viewPassword.type === "password") {
viewPassword.type = "text";
} else {
viewPassword.type = "password";
}
});
}
});
</code></pre>
<p>FYI I'm fairly new to the world of JavaScript so I'm not very good.</p>
| [] | [
{
"body": "<p>Before I comment on your implementation. Your code has a bug in it.</p>\n\n<p>The code inside this <code>if</code> block:</p>\n\n<pre><code>if(modalShowPassword || modalPassword) {\n</code></pre>\n\n<p>will execute if either <code>modalShowPassword</code> or <code>modalPassword</code> is set but y... | {
"AcceptedAnswerId": "202632",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T00:46:43.937",
"Id": "202623",
"Score": "2",
"Tags": [
"javascript",
"html",
"html5",
"form"
],
"Title": "Password reveal functionality"
} | 202623 |
<p>I have an implementation of the flood fill algorithm. Assume that an <code>image</code> is provided as a <code>vector</code> of <code>vector</code>s. It takes in parameters of a square to segment the image into two regions. It also takes in a point where mouse click is detected. Based on the point, a particular segment in the image will be filled by a custom <code>fill_value</code>. In order to perform this operation a queue is used to keep track of all the points in the image that are to be filled. The visited points are noted down by an <code>unordered_map</code> which uses a user-defined class <code>Point</code> as key and a <code>bool</code> as value. Here is the complete code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <cstddef>
#include <stdexcept>
// Class representing a point(x, y)
class Point
{
int x_cord = {0};
int y_cord = {0};
public:
Point()
{
}
Point(int x, int y):x_cord{x}, y_cord{y}
{
}
int x() const
{
return x_cord;
}
int y() const
{
return y_cord;
}
// Comparison function for collision resolution in unordered_map
bool operator==(const Point& pt) const
{
return (x_cord == pt.x() && y_cord == pt.y());
}
};
// Template specialization of std::hash for using Point as Key
namespace std
{
template<>
class hash<Point>
{
public:
size_t operator()(const Point& pt) const
{
return (std::hash<int>{}(pt.x()) ^ std::hash<int>{}(pt.y()));
}
};
}
// Check if a particular point is within given dimensions of the image
bool check_point(Point pt, int x_dim, int y_dim)
{
if(pt.x() >= 0 && pt.x() < x_dim && pt.y() >= 0 && pt.y() < y_dim)
{
return true;
}
return false;
}
// Collect all the valid neighbors of a point and push it to the queue for fill candidates
void get_neighbors(Point& curr_point, std::queue<Point>& q, std::vector<std::vector<int>>& image, int old_val, std::unordered_map<Point, bool>& visited)
{
std::vector<Point> neighbors;
int x_dim = image.size();
int y_dim = 0;
if(x_dim > 0)
{
y_dim = image[0].size();
}
Point pt_n{curr_point.x(), curr_point.y() - 1};
Point pt_s{curr_point.x(), curr_point.y() + 1};
Point pt_e{curr_point.x() + 1, curr_point.y()};
Point pt_w{curr_point.x() - 1, curr_point.y()};
if(check_point(pt_n, x_dim, y_dim) && image[curr_point.x()][curr_point.y() - 1] == old_val && visited[pt_n] == false)
{
q.push(pt_n);
visited[pt_n] = true;
}
if(check_point(pt_s, x_dim, y_dim) && image[curr_point.x()][curr_point.y() + 1] == old_val && visited[pt_s] == false)
{
q.push(pt_s);
visited[pt_s] = true;
}
if(check_point(pt_e, x_dim, y_dim) && image[curr_point.x() + 1][curr_point.y()] == old_val && visited[pt_e] == false)
{
q.push(pt_e);
visited[pt_e] = true;
}
if(check_point(pt_w, x_dim, y_dim) && image[curr_point.x() - 1][curr_point.y()] == old_val && visited[pt_w] == false)
{
q.push(pt_w);
visited[pt_w] = true;
}
}
// Visit elements in the queue and perform fill (change pixel value) on them
void flood_fill(std::vector<std::vector<int>>& image, Point clicked, int new_val, int x_dim, int y_dim)
{
int old_val = image[clicked.x()][clicked.y()];
std::unordered_map<Point, bool> visited;
std::queue<Point> q;
q.push(clicked);
visited[clicked] = true;
while(!q.empty())
{
Point curr_point = q.front();
get_neighbors(curr_point, q, image, old_val, visited);
image[curr_point.x()][curr_point.y()] = new_val;
q.pop();
}
}
// Draw a square to segment image to two regions
void draw_square(std::vector<std::vector<int>>& image, Point top_left_corner, int length)
{
int x_0 = top_left_corner.x();
int y_0 = top_left_corner.y();
int x;
int y;
for(x = x_0; x < x_0 + length; x++)
{
image[x][y_0] = 1;
image[x][y_0 + length - 1] = 1;
}
for(y = y_0; y < y_0 + length; y++)
{
image[x_0][y] = 1;
image[x_0 + length - 1][y] = 1;
}
}
void print_image(std::vector<std::vector<int>>& image, int x_dim, int y_dim)
{
for(int i = 0; i < x_dim; i++)
{
for(int j = 0; j < y_dim; j++)
{
std::cout << image[i][j] << "\t";
}
std::cout << "\n";
}
std::cout << "\n";
}
int main()
{
try
{
int x_dim = 0;
int y_dim = 0;
int x = 0;
int y = 0;
int c_x = 0;
int c_y = 0;
int length;
int fill_value = 0;
// Obtain image dimensions
std::cout << "Enter the dimensions of the image: \n";
std::cin >> x_dim >> y_dim;
std::vector<std::vector<int>> image(x_dim, std::vector<int>(y_dim, 0));
// Obtain parameters to draw the square
std::cout << "Enter the top left point coordinates and length for the square: \n";
std::cin >> x >> y >> length;
Point top_left_corner{x, y};
// Check if parameters are valid
if(!check_point(top_left_corner, x_dim, y_dim) || !check_point(Point{top_left_corner.x() + length - 1, top_left_corner.y() + length - 1}, x_dim, y_dim))
{
throw std::out_of_range{"Invalid Access"};
}
draw_square(image, top_left_corner, length);
// Print the image before Flood Fill
std::cout << "Before Flood Fill: \n";
print_image(image, x_dim, y_dim);
// Obtain the clicked point
std::cout << "Enter point to be clicked: \n";
std::cin >> c_x >> c_y;
Point clicked{c_x, c_y};
// Check if the clicked point is valid
if(!check_point(clicked, x_dim, y_dim))
{
throw std::out_of_range{"Invalid Access"};
}
// Obtain fill_value
std::cout << "Enter value to be filled: \n";
std::cin >> fill_value;
// Flood Fill
flood_fill(image, clicked, fill_value, x_dim, y_dim);
// Print image after Flood Fill
std::cout << "After Flood Fill: \n";
print_image(image, x_dim, y_dim);
}
catch(std::out_of_range& e)
{
std::cerr << e.what() << "\n";
}
return 0;
}
</code></pre>
<ol>
<li><p>I have used a <code>template specialization</code> of <code>std::hash</code> and an <code>operator==</code> function inside <code>Point</code> to enable the use of <code>Point</code> as a key in <code>unordered_map</code>. Is this enough to resolve collision? Please see <a href="https://stackoverflow.com/questions/52048713/c-hash-table-how-is-collision-for-unordered-map-with-custom-data-type-as-key">this</a> link for the detailed question.</p></li>
<li><p>How can I improve the efficiency?</p></li>
<li><p>Have I picked optimal data structures, except for image?</p></li>
</ol>
| [] | [
{
"body": "<p>I'll ignore questions 1 and 5 regarding hashing, because you don't need a hash function at all.</p>\n\n<h1>Storing image data</h1>\n\n<p>A <code>std::vector<std::vector<int>></code> is, in general, not a good way to store an image. For every pixel lookup this requires finding the colum... | {
"AcceptedAnswerId": "202972",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T01:29:54.603",
"Id": "202624",
"Score": "3",
"Tags": [
"c++",
"image",
"hash-map",
"breadth-first-search",
"collision"
],
"Title": "Flood Fill using unordered_map which has user-defined type as key"
} | 202624 |
<p>I have implemented function templates that take a begin and end iterator as well as an optional comparator for user-defined types. It was my intention to mimic the usage of <code>std::sort</code>. The three sorting algorithms I used were bubble sort, selection sort and merge sort. I perform merge sort in place.</p>
<pre><code>#ifndef BRUGLESCO_DATASORTER_SORTING_FUNCTIONS_H
#define BRUGLESCO_DATASORTER_SORTING_FUNCTIONS_H
#include <cstddef>
#include <functional>
#include <iterator>
#include <utility>
namespace bruglesco {
template <typename RandIterator,
typename Comparator = std::less<typename std::iterator_traits<RandIterator>::value_type>>
inline void bubble_sort(RandIterator begin,
RandIterator end,
Comparator cmp = Comparator())
{
while (begin != end)
{
for (auto temp_lhs = begin; temp_lhs != end; ++temp_lhs)
{
auto temp_rhs = temp_lhs;
++temp_rhs;
if (temp_rhs != end && !cmp(*temp_lhs, *temp_rhs))
{
std::swap(*temp_lhs, *temp_rhs);
}
}
--end;
}
}
template <typename RandIterator,
typename Comparator = std::less<typename std::iterator_traits<RandIterator>::value_type>>
inline void selection_sort(RandIterator begin,
RandIterator end,
Comparator cmp = Comparator())
{
while (begin != end)
{
auto smallest = begin;
for (auto temp = begin; temp != end; ++temp)
{
if (cmp(*temp, *smallest))
{
smallest = temp;
}
}
if (smallest != begin)
{
std::swap(*smallest, *begin);
}
++begin;
}
}
template <typename RandIterator,
typename Comparator = std::less<typename std::iterator_traits<RandIterator>::value_type>>
inline void merge_sort(RandIterator begin,
RandIterator end,
Comparator cmp = Comparator())
{
bool unsorted{ true };
std::size_t size = 0;
std::size_t sub_size = 1;
while (unsorted)
{
auto lhs = begin;
auto rhs = begin;
for (std::size_t i = 0; i < sub_size; ++i)
{
++rhs;
if (sub_size == 1) { ++size; }
}
while (rhs != end)
{
std::size_t left_count = sub_size;
std::size_t right_count = sub_size;
while (left_count > 0 && right_count > 0)
{
if (rhs == end) { break; }
if (cmp(*rhs, *lhs))
{
auto temp_lhs = rhs;
auto temp_rhs = rhs;
--temp_lhs;
while (temp_rhs != lhs)
{
std::swap(*temp_lhs, *temp_rhs);
--temp_lhs;
--temp_rhs;
}
++lhs;
if (rhs == end) { break; }
++rhs;
--right_count;
if (sub_size == 1) { ++size; }
}
else
{
++lhs;
--left_count;
}
}
for (std::size_t i = 0; i < left_count; ++i)
{
++lhs;
}
for (std::size_t i = 0; i < right_count; ++i)
{
if (rhs == end || lhs == end) { break; }
++lhs;
++rhs;
if (sub_size == 1) { ++size; }
}
for (std::size_t i = 0; i < sub_size; ++i)
{
if (rhs == end) { break; }
++rhs;
if (sub_size == 1) { ++size; }
}
}
sub_size *= 2;
if (sub_size > size) { unsorted = false; }
}
}
}
#endif // !BRUGLESCO_DATASORTER_SORTING_FUNCTIONS_H
</code></pre>
<p><strong>I also have a small usage example:</strong></p>
<pre><code>#include "sorting_functions.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> test_collection{ 2, 97, 849, 38, 2, 13, 17, 2, 2, 22, 9 };
for (auto& item : test_collection)
{
std::cout << item << '\n';
}
std::cout << "\nSorting. . . !\n\n";
//bruglesco::bubble_sort(test_collection.begin(), test_collection.end());
//bruglesco::merge_sort(test_collection.begin(), test_collection.end());
//bruglesco::selection_sort(test_collection.begin(), test_collection.end());
//std::sort(test_collection.begin(), test_collection.end());
for (auto& item : test_collection)
{
std::cout << item << '\n';
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
</code></pre>
<hr>
<p>A couple of things I would love review on.</p>
<ol>
<li>Any glaring mistakes? (I don't feel like my testing is as good as it should be.)</li>
<li>Any performance optimizations I can make? *Assume for the sake of discussion that each function needs to represent said algorithm. (The best optimization for bubble sort is of course use a different algorithm.) Also assume that merge-sort needs to be done in-place.</li>
<li>I believe I managed to maintain stability(which was not a requirement.) No?</li>
<li>Any issues with readability or decisions I should have documented?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T10:02:01.243",
"Id": "390511",
"Score": "0",
"body": "(In `void merge_sort()`, counting the `size` unconditionally looks less clutter and may be no slower - faster, even.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creatio... | [
{
"body": "<p>I'll assume you have tested them enough to say they work for normal situations.</p>\n\n<h2>Overall.</h2>\n\n<p>Though perfectly fine. Your use on the outer loop \"looks\" strange. Personally I would replace them with <code>for()</code> loops. But that's just me.</p>\n\n<h3>Swap</h3>\n\n<p>Your use... | {
"AcceptedAnswerId": "202648",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T01:46:48.890",
"Id": "202625",
"Score": "8",
"Tags": [
"c++",
"performance",
"algorithm",
"sorting",
"reinventing-the-wheel"
],
"Title": "Sorting three ways"
} | 202625 |
<p>This code is intended to generate a class (domain) from a class with class with similar/identical properties (api). Motivation is to speed development time when using clean architecture.</p>
<pre><code>import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import javax.inject.Inject
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.findAnnotation
class DomainApiReflectionAdapter<DOMAIN : Any, API : Any> constructor(
val clazz: KClass<DOMAIN>
) {
fun fromApi(apiModel: API): DOMAIN {
return apiToDomain(apiModel, clazz)
}
inline fun <API : Any, DOMAIN : Any> apiToDomain(apiModel: API, clazz: KClass<DOMAIN>): DOMAIN {
val factory = Factory(clazz)
val apiProperties = toPropMap(apiModel)
val constructorMap = mutableMapOf<KParameter, Any?>()
for (param in factory.params) {
param.findAnnotation<AdapterValues>()?.let {
val iclass = param.type.classifier as KClass<*>
println(iclass)
constructorMap[param] = innerFactory.simpleConstruct(apiProperties)
} ?: {
if (param.name in apiProperties) {
constructorMap[param] = when {
param.type.classifier == List::class -> {
val itype = param.type.arguments[0].type!!.classifier as KClass<*>
(apiProperties[param.name] as List<*>).map {
it?.toDomain(itype)
}
}
param.type.classifier == DateTime::class -> DateTime(apiProperties[param.name] as Long, DateTimeZone.forID("UTC"))
else -> apiProperties[param.name]
}
}
}()
}
return factory.construct(constructorMap)
}
fun <K : Any> toPropMap(model: K): Map<String, Any?> {
return model.javaClass.kotlin.declaredMemberProperties
.map { prop ->
prop.name to prop.get(model)
}.toMap()
}
companion object {
inline fun <reified DOMAIN : Any, API : Any> instance(): DomainApiReflectionAdapter<DOMAIN, API> {
return DomainApiReflectionAdapter(DOMAIN::class)
}
}
inner class Factory<DOMAIN : Any>(clazz: KClass<DOMAIN>) {
private val constructor = clazz.constructors.first()
val params = constructor.parameters
fun construct(map: Map<KParameter, Any?>): DOMAIN {
return constructor.callBy(map)
}
fun simpleConstruct(apiProperties: Map<String, Any?>): DOMAIN {
val innerMap = mutableMapOf<KParameter, Any?>()
for (ip in params) {
innerMap[ip] = apiProperties[ip.name]
}
return construct(innerMap)
}
}
}
fun <DOMAIN : Any, API : Any> API.toDomain(clazz: KClass<DOMAIN>): DOMAIN {
val adapter = DomainApiReflectionAdapter<DOMAIN, API>(clazz)
return adapter.fromApi(this)
}
abstract class Adapter<A, B> : (B) -> A
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class AdapterClass()
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class AdapterValues(val parameters: Array<String>)
</code></pre>
| [] | [
{
"body": "<h2>inline functions</h2>\n\n<p>inline function are great when:</p>\n\n<ul>\n<li>You want to surround a lambda with a little code</li>\n<li>You want to use <a href=\"https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters\" rel=\"nofollow noreferrer\">reified types</a>.</l... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T03:59:12.193",
"Id": "202631",
"Score": "1",
"Tags": [
"android",
"reflection",
"kotlin"
],
"Title": "Kotlin reflection to generate one class from class similar with similar properties"
} | 202631 |
<p>I write this class to process and output xml/rss feeds. I'm still working on, but any suggestion will be appreciated.
As a little trick if the xml file come from an online resource, I've added a method to cache the xml file as a json file.</p>
<pre><code><?php
class NewsFeed{
public $url;
private $cachedFeed;
private $cachedFile;
private $feed;
private $xml;
private $json;
public function __construct($url){
$this->url = $url;
}
public function showLiveFeed(){
$feed = $this->processFeed();
return json_decode($feed, true);
}
public function showCachedFeed(){
$cachedFeed = $this->loadCachedFile();
return json_decode($cachedFeed, true);
}
private function processFeed(){
$feed = $this->url;
$xml = simplexml_load_file($feed, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xml);
$cacheFeed = file_put_contents('cachedFeed.json', $json);
return $json;
}
private function loadCachedFile(){
if(file_exists('cachedFeed.json')){
$cachedFile = file_get_contents('cachedFeed.json');
return $cachedFile;
}
}
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-29T07:06:05.840",
"Id": "390603",
"Score": "0",
"body": "How a programmer is supposed to choose which method to use, showLive or showCached?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-29T13:03:37.527",... | [
{
"body": "<p>A caching strategy is not well thought. There is no clear scenario, whether a cached or a non-cached version should be used. Besides, a cache must have a <em>timeout</em> after which it is considered staled and must be renewed. </p>\n\n<p>There is also a filename issue. With only a filename, which... | {
"AcceptedAnswerId": "202798",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T04:16:54.140",
"Id": "202633",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"json",
"xml"
],
"Title": "PHP RSS/XML reader basic class"
} | 202633 |
<p>I was working on this problem, where I am constructing a Object Oriented structure of file system where you can have Directories and Files. The Directories could have sub Directories and files. </p>
<p>I have the following layout and I am looking for feedback on improvements or if my approach is wrong.</p>
<p>My OOP design has three different classes Root, Directory and Files</p>
<pre><code>class Root {
constructor(name, size, writable, parent){
this.name = name;
this.size = size;
this.writable = writable;
this.parent = parent;
}
getName(){
return this.name;
};
setName(val){
this.name = val;
}
}
class Directory extends Root{
constructor(name, size, writable, parent){
super(name, size, writable, parent);
this.children = [];
}
addContent(obj){
this.children.push(obj);
}
getContent(){
return this.children;
}
}
class File extends Root{
constructor(name, size, writable, parent){
super(name, size, writable, parent);
}
getSize(){
return this.size;
}
}
let root = new Root('head', 100, true);
let directory1 = new Directory('sample', 40, true, root);
let file1 = new File('test', 12, true, directory1);
let file2 = new File('test2', 14, true, directory1);
let subDirectory = new Directory('sample2', 40, true, directory1);
directory1.addContent(file1);
directory1.addContent(file2);
directory1.addContent(subDirectory);
console.log(directory1.getContent());
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T12:28:16.843",
"Id": "390527",
"Score": "0",
"body": "What kind of data will be most commonly stored with this?"
}
] | [
{
"body": "<p>I'd say <code>Root</code> is a misnomer here, since at first glance I imagined it to represent the filesystem root (i.e. the <code>/</code> directory), not the root of your class tree. Moreover, instead of deriving <code>File</code> and <code>Directory</code> from a common (abstract) ancestor, I'd... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T06:19:51.073",
"Id": "202636",
"Score": "2",
"Tags": [
"javascript",
"file-system"
],
"Title": "OOP implementation of in-memory file system"
} | 202636 |
<p>I have a <code>WebView</code>, which loads the returned from a request <code>url</code>. The thing is, the <code>url</code> might be a scheme to my app, and if that's the case I need to handle it properly, rather than open it in a <code>WebView</code>. I am not sure if this is the best way to implement that check:</p>
<p>In <code>WebViewClient</code>:</p>
<pre><code>@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String appScheme = getResources().getString(R.string.app_scheme);
if (url.startsWith("http://" + appScheme + "//checkout")) {
url = url.substring(7);
url = new StringBuilder(url).insert(appScheme.length(), ":").toString();
} else if (url.startsWith("https://" + appScheme + "//checkout")) {
url = url.substring(8);
url = new StringBuilder(url).insert(appScheme.length(), ":").toString();
}
if (url.startsWith("http:") || url.startsWith("https:")) {
return super.shouldOverrideUrlLoading(view, url);
}
// Otherwise allow the OS to handle things.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
close();
return true;
}
</code></pre>
<p>I should also note, that the returned scheme sometimes looks like this:</p>
<pre><code>http://myAppScheme//checkout
</code></pre>
<p>when my app can read only this template:</p>
<pre><code>myAppScheme://checkout
</code></pre>
<p>I have no control over how the scheme is returned, because this happens from the payment provider I am working with. This is why I need to convert it in the proper template when it's returned in a wrong one.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T07:43:30.117",
"Id": "202640",
"Score": "1",
"Tags": [
"java",
"android",
"http",
"url",
"https"
],
"Title": "Differ returned web link from app scheme"
} | 202640 |
<p>I implemented the Dijkstra algorithm. I'm looking for feedback how to make this more pythonic. I'm also wondering if I should move <code>get_shortest_path</code> method out of the Graph class, this would mean I need to expose the vertex list. </p>
<p>The MutablePriorityQueue is just the code snippet from: <a href="https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes" rel="nofollow noreferrer">https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes</a>. So I can update the priority of an item in the queue. </p>
<pre><code>import math
from mutable_priority_queue import MutablePriorityQueue
class Graph:
def __init__(self):
self._vertices = []
def add_new_vertex(self, x, y):
"""
Adds a new vertex to the graph.
:param x: X position of the vertex.
:param y: Y position of the vertex.
:return: The newly added vertex in the graph.
"""
new_vertex_index = len(self._vertices)
new_vertex = Vertex(new_vertex_index, x, y)
self._vertices.append(new_vertex)
return new_vertex
def get_vertex(self, i):
"""
Returns the vertex at the i'th index.
:param i: The index of the vertex in our vertex list.
"""
return self._vertices[i]
@staticmethod
def _calculate_distance(v0, v1):
v_x = v0.x - v1.x
v_y = v0.y - v1.y
return math.sqrt(v_x * v_x + v_y * v_y)
@staticmethod
def _get_path(vertex):
path = [vertex]
previous_vertex = vertex.previous
while previous_vertex is not None:
path.insert(0, previous_vertex)
previous_vertex = previous_vertex.previous
return path
def get_shortest_path(self, source_vertex_index, destination_vertex_index):
"""
Calculates the shortest path between source and destination using Dijkstra's algorithm
:param source_vertex_index: The index of the vertex we start at.
:param destination_vertex_index: The index of the vertex we want to calculate a path to.
:return: A collection with the vertices making up the shortest path from source to destination.
"""
if source_vertex_index > len(self._vertices) - 1:
raise IndexError('source vertex index is out of range.')
if destination_vertex_index > len(self._vertices) - 1:
raise IndexError('destination vertex index is out of range.')
priority_queue = MutablePriorityQueue()
visited_vertices = set()
# The source is 0 distance away from itself.
source_vertex = self._vertices[source_vertex_index]
source_vertex.distance = 0
priority_queue.add_or_update(source_vertex, 0)
while priority_queue:
# Find an unvisited vertex that closest to our source vertex.
# Note: the first loop this will be our source vertex.
current_vertex = priority_queue.pop()
if current_vertex.index == destination_vertex_index:
return Graph._get_path(current_vertex)
visited_vertices.add(current_vertex)
# Loop over all the neighbouring vertices of our current vertex
for neighbour_index in range(current_vertex.degree):
neighbour_vertex = current_vertex.get_neighbour(neighbour_index)
# If we already visited this neighbour of the current vertex that means
# we have already calculated the distance between the two.
if neighbour_vertex in visited_vertices:
continue
# Calculate the total distance from the source to this current vertex
distance = Graph._calculate_distance(current_vertex, neighbour_vertex)
tentative_distance = current_vertex.distance + distance
# If the distance is lower we have found a more direct path (or this neighbour hadn't been visited yet)
if tentative_distance < neighbour_vertex.distance:
neighbour_vertex.distance = tentative_distance
neighbour_vertex.previous = current_vertex
priority_queue.add_or_update(neighbour_vertex, tentative_distance)
return Graph._get_path(current_vertex)
class Vertex:
def __init__(self, index, x, y):
if not isinstance(index, int):
raise TypeError('Index needs to be of type integer.')
if index < 0:
raise IndexError('Index out of range (-1).')
self.index = index
self.x = x
self.y = y
self.distance = float("inf")
self.previous = None
self._neighbours = []
self._degree = 0
@property
def degree(self):
"""
:return: The number of edges connected to this vertex.
"""
return self._degree
def get_neighbour(self, index):
"""
:param index: The 0-based index of our neighbour.
:return: The neighbour vertex at the provided index.
"""
return self._neighbours[index]
def create_edge(self, neighbour_vertex):
"""
Creates and edge between this vertex and the neighbour.
:param neighbour_vertex: The vertex we create an edge between.
"""
if neighbour_vertex in self._neighbours:
return
self._neighbours.append(neighbour_vertex)
self._degree += 1
neighbour_vertex.create_edge(self)
</code></pre>
<p>Unit tests:</p>
<pre><code>from unittest import TestCase
from undirected_graph import Graph, Vertex
class TestUndirectedGraph(TestCase):
def test_negative_vertex_index(self):
# arrange & act & assert
self.assertRaises(IndexError, lambda: Vertex(-1, 0, 0))
def test_add_neighbour_check_degree(self):
# arrange
v0 = Vertex(0, 10, 10)
v1 = Vertex(1, 20, 20)
# act
v0.create_edge(v1)
# assert
self.assertEqual(1, v0.degree)
self.assertEqual(1, v1.degree)
self.assertEqual(v1, v0.get_neighbour(0))
self.assertEqual(v0, v1.get_neighbour(0))
def test_add_first_vertex(self):
# arrange
graph = Graph()
# act
vertex = graph.add_new_vertex(10, 10)
# assert
self.assertEqual(0, vertex.index)
def test_add_two_vertices(self):
# arrange
graph = Graph()
# act
vertex0 = graph.add_new_vertex(10, 10)
vertex1 = graph.add_new_vertex(20, 20)
# assert
self.assertEqual(0, vertex0.index)
self.assertEqual(1, vertex1.index)
def test_distance_empty_graph(self):
# arrange
graph = Graph()
# act & assert
self.assertRaises(IndexError, lambda: graph.get_shortest_path(0, 0))
def test_distance_single_vertex(self):
# arrange
graph = Graph()
graph.add_new_vertex(0, 0)
# act
path = graph.get_shortest_path(0, 0)
# assert
self.assertEqual(len(path), 1)
self.assertEqual(path[0], graph.get_vertex(0))
def test_distance_two_vertices(self):
# arrange
graph = Graph()
v0 = graph.add_new_vertex(0, 0)
v1 = graph.add_new_vertex(10, 0)
v0.create_edge(v1)
# act
path = graph.get_shortest_path(0, 1)
# assert
self.assertEqual(len(path), 2)
self.assertEqual(path[0], graph.get_vertex(0))
self.assertEqual(path[1], graph.get_vertex(1))
</code></pre>
| [] | [
{
"body": "<p>My comments are not necessarily python specific but just questioning some modelling choices.</p>\n\n<ol>\n<li><p>Why does vertex take index as an argument? The array of vertices belongs to the graph, is maintained and manipulated by the graph. The question \"what is the index of this vertex\" shou... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T09:47:01.627",
"Id": "202650",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Dijkstra's algorithm with priority queue"
} | 202650 |
<p>I made an encoder/decoder for the <a href="https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher" rel="nofollow noreferrer">Vigenère cipher</a>. This one is using a table, not the remainder technique. Please let me know what you think can be done to improve performance, etc. </p>
<pre><code>import string
import itertools
class Vigenere:
"""
A class for vigenere encoding and decoding.
Doesn't preserve spaces, UPPERCASE letters.
Default alphabet is lowercase a-z.
"""
def __init__(self):
"""Initialize default values."""
self.__reset()
def __reset(self):
# Reset all attributes
self.alphabet = ""
self.key = ""
self.__looped_key = ""
self.text = ""
self.__dec_str = ""
self.__enc_str = ""
self.__matrix = []
def __create_matrix(self):
# create a vigenere matrix
tmp = 2 * self.alphabet
self.__matrix.append(list(self.alphabet))
for i in range(len(self.alphabet) - 1):
self.__matrix.append(list(tmp.split(tmp[i], 1)[1][:len(self.alphabet)]))
def __loop_key(self):
# loop the key and slice so it's length matches text's
looped = ''.join(list(itertools.repeat(self.key, int(len(self.text) / len(self.key)) + 1)))[:len(self.text)]
self.__looped_key = looped
def __set_key(self, key):
# remove spaces, lower, loop and set the key
self.key = key.replace(' ', '').lower()
self.__loop_key()
def __set_text(self, text):
# remove spaces, lower and set text
self.text = text.replace(' ', '').lower()
def __set_alphabet(self, alphabet):
# remove spaces and lower
alphabet = alphabet.replace(' ', '').lower()
self.__check_alphabet(alphabet) # check alphabet validity
self.alphabet = alphabet
self.__check_chars() # check key and text compability with alphabet
self.__create_matrix() # create a vigenere table
def __check_alphabet(self, alphabet):
# check alphabet for duplicates
if len(alphabet) != len(set(alphabet)):
raise ValueError('alphabet contains duplicate characters')
def __check_chars(self):
# check key and text compability with alphabet
t_key = ''.join(list(filter(lambda x: x not in self.alphabet, self.key)))
t_text = ''.join(list(filter(lambda x: x not in self.alphabet, self.text)))
if t_text != '':
raise ValueError('text includes characters not in alphabet')
if t_key != '':
raise ValueError('key includes characters not in alphabet')
def decode(self, text, key, alphabet=string.ascii_lowercase):
"""Decode text with key using given alphabet(default a-z)."""
# reset values
self.__reset()
# set attributes
self.__set_text(text)
self.__set_key(key)
self.__set_alphabet(alphabet)
# iterate through the looped key and decode string
for i in range(len(self.__looped_key)):
lst = self.__matrix[self.alphabet.index(self.__looped_key[i])]
dex = lst.index(self.text[i])
self.__dec_str += self.__matrix[0][dex]
return self.__dec_str
def encode(self, text, key, alphabet=string.ascii_lowercase):
"""Encode text with key using given alphabet(default a-z)."""
# reset values
self.__reset()
# set attributes
self.__set_text(text)
self.__set_key(key)
self.__set_alphabet(alphabet)
# iterate through the text and encode it
for i in range(len(self.text)):
lst = self.__matrix[self.alphabet.index(self.text[i])]
dex = self.__matrix[0].index(self.__looped_key[i])
self.__enc_str += lst[dex]
return self.__enc_str
vigenere = Vigenere()
encode = vigenere.encode
decode = vigenere.decode
if __name__ == '__main__':
# test
assert encode('d CO dE', 'KE y') == 'ngmni'
assert decode('NG mN i', ' ke Y') == 'dcode'
assert decode('1132xn5m dze HN j5rn9v4Mmzzx qpc7s', 'K ey', 'abcdEF ghijklM Nopqr sT uvwxyz123456789') == 'qwertyuiopasdfghjklzxcvbnm1234'
assert encode('qW ertYU iopasdfGhJk LzxcvbNM1234', 'KeY ', 'abcdEF ghijklM Nopqr sT uvwxyz123456789') == '1132xn5mdzehnj5rn9v4mmzzxqpc7s'
</code></pre>
| [] | [
{
"body": "<p>If the question is about both the Python implementation and the used algorithms, it would be nice to say more of the specifications of your class.</p>\n\n<p>After some tests of your code, I can say that you have built a class that can crypt a string using a vigenere cipher and a key. In both the t... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T12:33:03.117",
"Id": "202662",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"cryptography",
"vigenere-cipher"
],
"Title": "Vigenère decoder/encoder in Python (using matrix)"
} | 202662 |
<p>My version of implementation ObservableDictionary. Its should work as ObservableCollection, I hope. Based on referencesource Dictionary implementation. </p>
<p>.NET 4.5 framework</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
namespace Roing.CommonUI.Collections
{
public class ObservableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged
{
protected IDictionary<TKey, TValue> Dictionary { get; }
#region Constants (standart constants for collection/dictionary)
private const string CountString = "Count";
private const string IndexerName = "Item[]";
private const string KeysName = "Keys";
private const string ValuesName = "Values";
#endregion
#region .ctor
public ObservableDictionary()
{
Dictionary = new Dictionary<TKey, TValue>();
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary)
{
Dictionary = new Dictionary<TKey, TValue>(dictionary);
}
public ObservableDictionary(IEqualityComparer<TKey> comparer)
{
Dictionary = new Dictionary<TKey, TValue>(comparer);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
Dictionary = new Dictionary<TKey, TValue>(dictionary,comparer);
}
public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
Dictionary = new Dictionary<TKey, TValue>(capacity, comparer);
}
public ObservableDictionary(int capacity)
{
Dictionary = new Dictionary<TKey, TValue>(capacity);
}
#endregion
#region INotifyCollectionChanged and INotifyPropertyChanged
public event NotifyCollectionChangedEventHandler CollectionChanged;
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region IDictionary<TKey, TValue> Implementation
public TValue this[TKey key]
{
get
{
return Dictionary[key];
}
set
{
InsertObject(
key : key,
value : value,
appendMode : AppendMode.Replace,
oldValue : out var oldItem);
if (oldItem != null)
{
OnCollectionChanged(
action: NotifyCollectionChangedAction.Replace,
newItem: new KeyValuePair<TKey, TValue>(key, value),
oldItem: new KeyValuePair<TKey, TValue>(key, oldItem));
}
else
{
OnCollectionChanged(
action: NotifyCollectionChangedAction.Add,
changedItem: new KeyValuePair<TKey, TValue>(key, value));
}
}
}
public ICollection<TKey> Keys => Dictionary.Keys;
public ICollection<TValue> Values => Dictionary.Values;
public int Count => Dictionary.Count;
public bool IsReadOnly => Dictionary.IsReadOnly;
public void Add(TKey key, TValue value)
{
InsertObject(
key: key,
value: value,
appendMode: AppendMode.Add);
OnCollectionChanged(
action: NotifyCollectionChangedAction.Add,
changedItem: new KeyValuePair<TKey, TValue>(key, value));
}
public void Add(KeyValuePair<TKey, TValue> item)
{
InsertObject(
key: item.Key,
value: item.Value,
appendMode: AppendMode.Add);
OnCollectionChanged(
action: NotifyCollectionChangedAction.Add,
changedItem: new KeyValuePair<TKey, TValue>(item.Key, item.Value));
}
public void Clear()
{
if (!Dictionary.Any())
{
return;
}
var removedItems = new List<KeyValuePair<TKey,TValue>>(Dictionary.ToList());
Dictionary.Clear();
OnCollectionChanged(
action: NotifyCollectionChangedAction.Reset,
newItems: null,
oldItems: removedItems);
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return Dictionary.Contains(item);
}
public bool ContainsKey(TKey key)
{
return Dictionary.ContainsKey(key);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Dictionary.CopyTo(
array: array,
arrayIndex: arrayIndex);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return Dictionary.GetEnumerator();
}
public bool Remove(TKey key)
{
if(Dictionary.TryGetValue(key, out var value))
{
Dictionary.Remove(key);
OnCollectionChanged(
action: NotifyCollectionChangedAction.Remove,
changedItem: new KeyValuePair<TKey, TValue>(key,value));
return true;
}
return false;
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
if (Dictionary.Remove(item))
{
OnCollectionChanged(
action: NotifyCollectionChangedAction.Remove,
changedItem: item);
return true;
}
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
return Dictionary.TryGetValue(key, out value);
}
IEnumerator IEnumerable.GetEnumerator()
{
return Dictionary.GetEnumerator();
}
#endregion
#region IReadOnlyDictionary
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Dictionary.Keys;
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Dictionary.Values;
#endregion
#region ObservableDictionary inner methods
private void InsertObject(TKey key, TValue value, AppendMode appendMode)
{
InsertObject(key, value, appendMode, out var trash);
}
private void InsertObject(TKey key, TValue value, AppendMode appendMode, out TValue oldValue)
{
oldValue = default(TValue);
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if(Dictionary.TryGetValue(key, out var item))
{
if(appendMode == AppendMode.Add)
{
throw new ArgumentException("Item with the same key has already been added");
}
if (Equals(item, value))
{
return;
}
Dictionary[key] = value;
oldValue = item;
}
else
{
Dictionary[key] = value;
}
}
private void OnPropertyChanged()
{
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnPropertyChanged(KeysName);
OnPropertyChanged(ValuesName);
}
private void OnPropertyChanged(string propertyName)
{
if (string.IsNullOrWhiteSpace(propertyName))
{
OnPropertyChanged();
}
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void OnCollectionChanged()
{
OnPropertyChanged();
var handler = CollectionChanged;
handler?.Invoke(
this, new NotifyCollectionChangedEventArgs(
action:NotifyCollectionChangedAction.Reset));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> changedItem)
{
OnPropertyChanged();
var handler = CollectionChanged;
handler?.Invoke(
this, new NotifyCollectionChangedEventArgs(
action:action,
changedItem: changedItem));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> newItem, KeyValuePair<TKey, TValue> oldItem)
{
OnPropertyChanged();
var handler = CollectionChanged;
handler?.Invoke(
this, new NotifyCollectionChangedEventArgs(
action: action,
newItem: newItem,
oldItem: oldItem));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, IList newItems)
{
OnPropertyChanged();
var handler = CollectionChanged;
handler?.Invoke(
this, new NotifyCollectionChangedEventArgs(
action: action,
changedItems: newItems));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, IList newItems, IList oldItems)
{
OnPropertyChanged();
var handler = CollectionChanged;
handler?.Invoke(
this, new NotifyCollectionChangedEventArgs(
action: action,
newItems: newItems,
oldItems: oldItems));
}
#endregion
internal enum AppendMode
{
Add,
Replace
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:36:04.040",
"Id": "390559",
"Score": "0",
"body": "Do you mean for `c[1] = 0; c[1] = 0;` to cause two CollectionChanged events?"
}
] | [
{
"body": "<blockquote>\n<pre><code> protected IDictionary<TKey, TValue> Dictionary { get; }\n</code></pre>\n</blockquote>\n\n<p>I don't find this to be a very helpful name. FWIW my default choice for something like this would be <code>Wrapped</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> ... | {
"AcceptedAnswerId": "202670",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T12:41:03.897",
"Id": "202663",
"Score": "8",
"Tags": [
"c#"
],
"Title": "Simple ObservableDictionary implementation"
} | 202663 |
<p>On <a href="https://en.wikipedia.org/wiki/Quadratic_equation" rel="nofollow noreferrer">Wikipedia</a>, there is a graph shown:</p>
<p><a href="https://i.stack.imgur.com/12i6M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/12i6M.png" alt="Plots of quadratic function "></a></p>
<p>It shows the quadratic \$y = ax2 + bx + c\$, varying each coefficient separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0)</p>
<p>As a learning experience I decided to replicate these plots in Matplotlib as follows:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import math
#Plot the quadratic function y = ax2 + bx + c
#Varying each coefficient [a, b, c] separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0)
#Iterate these 5 coeficients and plot each line
coefs = [-2, -1, 0, 1, 2]
#set up the plot and 3 subplots (to show the effect of varying each coefficient)
f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(18, 6))
#some x values to plot
x = np.linspace(-2, 2, 30)
for idx, val in enumerate([ax1, ax2, ax3]):
for v in coefs:
a, b, c = 1, 0, 0
if idx == 0:
a = v
elif idx == 1:
b = v
else:
c = v
y = a * (x**2) + (b * x) + c
val.plot(x, y, label="Coeficient is " + str(coefs[i]))
val.axhline(y=0, color='k')
val.axvline(x=0, color='k')
val.grid()
val.legend(loc='lower center')
plt.show()
</code></pre>
<p>It works fine:</p>
<p><a href="https://i.stack.imgur.com/UeGgC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UeGgC.png" alt="My plot"></a></p>
<p>but I am new to programming and I have an uneasy feeling that using <code>if</code> statements isn't optimal. It feels like I should be iterating over something rather than using <code>if</code>s.</p>
<p>What other ways could I iterate over the coefficients a, b & c to produce the 3 different subplots?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T15:17:03.253",
"Id": "390548",
"Score": "0",
"body": "You know how to use an enumerate. What's keeping you from using it again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:35:03.197",
"Id":... | [
{
"body": "<p><strong>tl;dr</strong>: Use numpy's <a href=\"https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html\" rel=\"nofollow noreferrer\">broadcasting</a> features:</p>\n\n<pre><code>coefs = np.array([-2, -1, 0, 1, 2])\n\n#set up the plot and 3 subplots (to show the effect of varying each ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T15:07:36.630",
"Id": "202673",
"Score": "3",
"Tags": [
"python",
"beginner",
"iteration",
"matplotlib"
],
"Title": "Plotting quadratic equations with varying parameters"
} | 202673 |
<h2>Question</h2>
<blockquote>
<p>Input number of test cases.</p>
<p>Input each test case and output its next palindrome number.</p>
</blockquote>
<p>Link: <a href="https://www.spoj.com/problems/PALIN/" rel="nofollow noreferrer">https://www.spoj.com/problems/PALIN/</a></p>
<p>Language Used: C++14 (gcc 6.3)</p>
<hr>
<h2>My code</h2>
<pre><code>#include<iostream>
using namespace std;
int main()
{
long long int t,rev=0,x,no,f=0;
cin>>t;
while(t>0)
{
cin>>no;
no+=1;
f=0;
while(f==0)
{
x=no;
rev=0;
f=0;
while(x>0)
{
rev=(rev*10)+(x%10);
x/=10;
}
if(rev==no)
{cout<<rev<<endl;f=1;}
else
no+=1;
}
t-=1;
}
}
</code></pre>
<hr>
<p>This works for small numbers, but doesn't scale very well - online judge fails with "time limit exceeded".</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:35:11.570",
"Id": "390557",
"Score": "0",
"body": "Time limit exceeded is still a heck of a lot better than code that doesn't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:35:31.950",
... | [
{
"body": "<h1>Avoid <code>using namespace std;</code></h1>\n\n<p>Bringing all names in from a namespace is problematic; <code>namespace std</code> particularly so. See <a href=\"//stackoverflow.com/q/1452721\">Why is “using namespace std” considered bad practice?</a>.</p>\n\n<h1>Variable names could be more in... | {
"AcceptedAnswerId": "203034",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:24:57.293",
"Id": "202675",
"Score": "-2",
"Tags": [
"c++",
"time-limit-exceeded",
"c++14",
"integer",
"palindrome"
],
"Title": "Find the first palindrome larger than the given number"
} | 202675 |
<p>I'd love to get feedback on my first go at Dijkstra's algorithm in Rust:</p>
<pre><code>use std::cell::Cell;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
use std::fmt;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
fn main() {
let s = Vertex::new("s");
let t = Vertex::new("t");
let x = Vertex::new("x");
let y = Vertex::new("y");
let z = Vertex::new("z");
// A map from vertices to their adjacent vertices including costs
let mut adjacency_list = HashMap::new();
adjacency_list.insert(&s, vec![(&t, 10), (&y, 5)]);
adjacency_list.insert(&t, vec![(&y, 2), (&x, 1)]);
adjacency_list.insert(&x, vec![(&z, 4)]);
adjacency_list.insert(&y, vec![(&t, 3), (&x, 9), (&z, 2)]);
adjacency_list.insert(&z, vec![(&s, 7), (&x, 6)]);
dijkstra(&s, &adjacency_list);
adjacency_list.keys().for_each(|v| println!("{:?}", v));
}
// Multiple lifetime parameters to avoid the error:
// "borrowed value does not live long enough"
fn dijkstra<'a, 's: 'a>(
start: &'a Vertex<'s>,
adjacency_list: &'a HashMap<&'a Vertex<'s>, Vec<(&'a Vertex<'s>, usize)>>,
) {
start.distance.set(0);
// Fill the binary heap, vertices with the smallest distance go first
let mut to_visit = BinaryHeap::new();
adjacency_list.keys().for_each(|v| to_visit.push(*v));
// We visit the vertices with the smallest distance first, this is
// what makes Dijkstra a greedy algorithm
while let Some(v) = to_visit.pop() {
if let Some(neighbors) = adjacency_list.get(v) {
for (n, cost) in neighbors {
let new_distance = v.distance.get() + cost;
if new_distance < n.distance.get() {
n.distance.set(new_distance);
// n.predecessor.set(Some(Rc::new(*v)));
}
}
// When changing a vertex' distance, the BinaryHeap doesn't
// update the position of the vertex.
// That's why we create a new heap with the right order.
let mut new_heap = BinaryHeap::new();
to_visit.iter().for_each(|x| new_heap.push(*x));
to_visit = new_heap;
}
}
}
#[derive(Eq)]
struct Vertex<'a> {
name: &'a str,
distance: Cell<usize>,
// predecessor: Cell<Option<Rc<Vertex<'a>>>>,
}
impl<'a> Vertex<'a> {
fn new(name: &'a str) -> Vertex<'a> {
Vertex {
name,
distance: Cell::new(usize::max_value()),
// predecessor: Cell::new(None),
}
}
}
impl<'a> Hash for Vertex<'a> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
/// Since this Vertex will be put in a priority queue where the vertices
/// with the *smallest* distance should be processed first, `cmp`
/// returns GT if self.distance().get() < other.distance().get()
impl<'a> Ord for Vertex<'a> {
fn cmp(&self, other: &Vertex<'a>) -> Ordering {
other.distance.get().cmp(&self.distance.get())
}
}
impl<'a> PartialOrd for Vertex<'a> {
fn partial_cmp(&self, other: &Vertex<'a>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> PartialEq for Vertex<'a> {
fn eq(&self, other: &Vertex<'a>) -> bool {
self.name == other.name
}
}
impl<'a> Debug for Vertex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"name: {}, distance: {:?}",
self.name,
self.distance.get()
)
}
}
</code></pre>
<p>Things I'd especially like to improve and simplify, if possible:</p>
<ul>
<li>Type signatures: I've wrestled a bit with the borrow checker to get rid of "borrowed value doesn't live long enough". As a consequence I had to introduce (multiple) lifetime parameters at a couple of places</li>
<li>BinaryHeap: At first it seemed like a good data structure to have fast access to the vertex with the smallest distance. But since BinaryHeap doesn't resort the values when they change, I had to improvise (and incur worse performance)</li>
</ul>
| [] | [
{
"body": "<ol>\n<li><p><strong>Pay attention to compiler warnings</strong>. Rust is a statically-compiled language. One of the big reasons you choose such a language is to get information at compile time:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>warning: unused import: `std::rc::Rc`\n --> ... | {
"AcceptedAnswerId": "202879",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:38:29.587",
"Id": "202677",
"Score": "6",
"Tags": [
"algorithm",
"graph",
"rust"
],
"Title": "Dijkstra's algorithm in Rust"
} | 202677 |
<p>I wrote a simple data handler class.</p>
<p>I would like to know if I can make my class more simple and efficient for doing the identical feature.</p>
<p><strong>My Code :</strong></p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
using namespace std;
class MyData
{
public:
void add(const pair<string *, int> &elem)
{
size_t index = findIndex(elem.first);
if (index != -1) //if key exists, update the value
{
myVec[index].second = elem.second;
return;
}
myVec.push_back(elem);
}
void remove(string *strPtr)
{
size_t index = findIndex(strPtr);
if (index != -1)
myVec.erase(myVec.begin() + index);
}
void sort()
{
std::sort(myVec.begin(), myVec.end(), comp);
}
void print()
{
for (size_t i = 0; i < myVec.size(); ++i)
{
cout << *myVec[i].first << " : " << myVec[i].second << '\n';
}
}
private:
size_t findIndex(string *strPtr)
{
auto it = find_if(myVec.begin(), myVec.end(), [&](pair<string *, int> const & ref)
{
return ref.first == strPtr;
});
if (it != myVec.end())
return std::distance(myVec.begin(), it);
return -1;
}
static bool comp(const pair<string *, int> &a, const pair<string *, int> &b)
{
return a.second < b.second;
}
vector<pair<string *, int>> myVec;
};
int main()
{
string fruits[] = {"Apple", "Banana", "Orange", "Grapes", "Lemon"};
MyData data;
data.add(make_pair(&fruits[0], 13));
data.add(make_pair(&fruits[1], 52));
data.add(make_pair(&fruits[2], 33));
data.add(make_pair(&fruits[3], 8));
data.add(make_pair(&fruits[4], 22));
data.add(make_pair(&fruits[1], 17));
data.sort();
data.remove(&fruits[4]);
data.print();
}
</code></pre>
<p><strong>The Result :</strong></p>
<pre><code>Grapes : 8
Apple : 13
Banana : 17
Orange : 33
Program ended with exit code: 0
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-29T08:28:46.607",
"Id": "390615",
"Score": "0",
"body": "is there any reason to not use a standard container like `std::map` for the task?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-29T08:44:24.883",
... | [
{
"body": "<p>Don't use <code>using namespace std</code>. Its considered bad practice. </p>\n\n<p>See <a href=\"https://www.google.de/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice&ved=2ahUKEwji0KCo1JDdAhXMKewKHZX-AxQQ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:38:35.100",
"Id": "202678",
"Score": "-1",
"Tags": [
"c++"
],
"Title": "Simply adding/removing/sorting data"
} | 202678 |
<p>I just learned Merge sort, and I really like this Merge sort implementation since it is very logical and very easy to follow. If I was asked in an interview to implement merge sort, will this implementation suffice?</p>
<p>I know creating those new arrays every time the <code>mergeSort()</code> method is called is bad practice. I fully understand merge sort, I can explain it in very good detail as I implement it, but will this implementation lose me some "points" because of the the way I am creating all these new arrays?</p>
<p>Are there any other things that may lose me some points?</p>
<pre><code>public static void mergeSort(int[] a) {
if(a.length < 2) return;
int mid = a.length / 2;
int[] left = new int[mid];
int[] right = new int[a.length - mid];
//Filling left and right arrays.
for(int i = 0; i < left.length; i++)
left[i] = a[i];
for(int i = 0; i < right.length; i++)
right[i] = a[i + mid];
mergeSort(left);
mergeSort(right);
merge(left, right, a);
}
public static void merge(int[] left, int[] right, int[] a) {
int i = 0; //For left array
int j = 0; //For right array
int k = 0; //For a array
while(i < left.length && j < right.length) {
if(left[i] <= right[j])
a[k++] = left[i++];
else
a[k++] = right[j++];
}
//Filling remaining integers, for the array that has left over numbers.
while(i < left.length)
a[k++] = left[i++];
while(j < right.length)
a[k++] = right[j++];
}
</code></pre>
<p>This is tested and working.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-29T08:01:40.577",
"Id": "390644",
"Score": "0",
"body": "its a static method and it wont create a new array in the memory it will use the same static one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-31T... | [
{
"body": "<p>Here are some thoughts on things you might improve:</p>\n\n<p>Always use curly braces, even when they're optional. This is a common source of errors when existing code is modified.</p>\n\n<p><code>int i == 0; //For left array</code> should be <code>int leftArrayIndex = 0</code>. Don’t use a commen... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T16:49:51.940",
"Id": "202679",
"Score": "3",
"Tags": [
"java",
"algorithm",
"interview-questions",
"mergesort"
],
"Title": "Merge sort Java implementation for an interview"
} | 202679 |
<p>In a followup this application was turned into a GUI using FLTK: <a href="https://codereview.stackexchange.com/questions/202988/cleaning-a-file-word-query-gui-fltk">Cleaning a file / Word Query GUI (FLTK)</a></p>
<p>I did the following two exercises in <em>Programming: Principles and Practice Using C++ (2nd Edition)</em>, by Stroustrup, which build upon each other:</p>
<p>From Chapter 21 (Algorithms and Maps),</p>
<blockquote>
<ol start="13">
<li><p>Write a program to "clean up" a text file for use in a word query program; that is, replace punctuation with whitespace, put words into lower case, replace <em>don't</em> with <em>do not</em> (etc.), and remove plurals (e.g <em>ships</em> becomes <em>ship</em>). Don't be too ambitious. For example, it is hard to determine plurals in general, so just remove an <em>s</em> if you find both <em>ship</em> and <em>ships</em>. Use that program on a real-world text file with at least 5000 words (e.g., a research paper).</p></li>
<li><p>Write a program (using the output from the previous exercise) to answer questions such as: </p>
<ul>
<li>"How many occurrences of <em>ship</em> are there in a file?" </li>
<li>"Which word occurs most frequently?"</li>
<li>"Which is the longest word?"</li>
<li>"Which is the shortest?"</li>
<li>"List all words starting with <em>s</em>."</li>
<li>“List all four-letter words."</li>
</ul></li>
</ol>
</blockquote>
<p>I solved this tasks as follows:</p>
<p><strong>Cleaned_words.h</strong></p>
<pre><code>#ifndef CLEAN_FILE290320180702_GUARD
#define CLEAN_FILE290320180702_GUARD
#include <string>
#include <vector>
#include <map>
namespace cleaned_words {
using Word = std::string;
using Occurences = int;
std::map<Word, Occurences> read_words_from_file(const std::string& filename);
std::map<Word, Occurences> read_cleaned_words_with_occurence(std::istream& is);
bool contains_digits(const Word& word);
Word remove_invalid_signs(const Word& word, const std::string& invalid_signs);
inline unsigned char unsigned_isspace(char c)
{
return isspace(static_cast<unsigned char>(c));
}
Word remove_whitespace(const Word& word);
Word remove_capital_letters(const Word& word);
std::vector<Word> remove_contractions(const Word& word);
void remove_plural(std::map<Word, Occurences>& cleaned_words);
void write_cleaned_words_to_file(const std::string& filename, const std::map<Word, Occurences>& cleaned_words);
}
#endif
</code></pre>
<p><strong>Cleaned_words.cpp</strong></p>
<pre><code>#include "Cleaned_words.h"
#include <algorithm>
#include <cctype>
#include <fstream>
namespace cleaned_words {
std::map<Word, Occurences> read_words_from_file(const std::string& filename)
{
std::ifstream ifs{ filename };
if (!ifs) {
throw std::runtime_error("void read_words_from_file(const std::string& filename)\nFile could not be opened\n");
}
return read_cleaned_words_with_occurence(ifs);
}
std::map<Word, Occurences> read_cleaned_words_with_occurence(std::istream& is)
{
std::map<Word, Occurences> cleaned_words;
for (Word word; is >> word;) {
if (contains_digits(word)) continue;
word = remove_invalid_signs(word, R"(°-_^@{}[]<>&.,_()+-=?“”:;/\")");
word = remove_whitespace(word);
word = remove_capital_letters(word);
if (word.empty()) continue;
std::vector<Word> words = remove_contractions(word);
for (auto& word : words) { // remove ' after concatenations were run to not erase them to early
word = remove_invalid_signs(word, "'");
}
for (const auto& word : words) {
if (word.size() == 1 && word != "a" && word != "i" && word != "o") continue;
++cleaned_words[word];
}
}
remove_plural(cleaned_words);
return cleaned_words;
}
bool contains_digits(const Word& word)
{
if (word.empty()) return false;
for (const auto&x : word) { //erase digits etc
if (isdigit(static_cast<unsigned char>(x))) {
return true;
}
}
return false;
}
Word remove_invalid_signs(const Word& word,const std::string& invalid_signs)
// replace invalid signs with whitespace
{
Word cleaned_word = word;
for (auto it = cleaned_word.begin(); it != cleaned_word.end();)
{
if (std::find(invalid_signs.begin(), invalid_signs.end(), *it) != invalid_signs.end()) {
it = cleaned_word.erase(it);
}
else{
++it;
}
}
return cleaned_word;
}
Word remove_whitespace(const Word& word)
{
if (word.empty()) return word;
Word cleaned_word = word;
cleaned_word.erase(std::remove_if(cleaned_word.begin(), cleaned_word.end(), unsigned_isspace), cleaned_word.end());
return cleaned_word;
}
Word remove_capital_letters(const Word& word)
{
Word clean_word = word;
for (auto& letter : clean_word) {
letter = std::tolower(letter);
}
return clean_word;
}
std::vector<Word> remove_contractions(const Word& word)
{
const std::map<Word, std::vector<Word>> shorts_and_longs
{
{ "aren't",{ "are","not" }},
{ "can't", {"cannot"} },
{ "could've",{ "could","have" } },
{ "couldn't",{ "could","not" } },
{ "daresn't",{ "dare","not" } },
{ "dasn't",{ "dare","not" } },
{ "didn't",{ "did","not" } },
{ "doesn't",{ "does","not" } },
{ "don't",{ "do","not" } },
{ "e'er",{ "ever" } },
{ "everyone's",{ "everyone","is" } },
{ "finna",{ "fixing","to" } },
{ "gimme",{ "give","me" } },
{ "gonna",{ "going","to" } },
{ "gon't",{ "go","not" } },
{ "gotta",{ "got","to" } },
{ "hadn't",{ "had","not" } },
{ "hasn't",{ "has","not" } },
{ "haven't",{ "have","not" } },
{ "he've",{ "he","have" } },
{ "how'll",{ "how","will" } },
{ "how're",{ "how","are" } },
{ "I'm",{ "I","am" } },
{ "I'm'a",{ "I","am","about","to" } },
{ "I'm'o",{ "I","am","going","to" } },
{ "I've",{ "I","have" } },
{ "isn't",{ "is","not" } },
{ "it'd",{ "it","would" } },
{ "let's",{ "let","us" } },
{ "ma'am",{ "madam" } },
{ "mayn't",{ "may","not" } },
{ "may've",{ "may","have" } },
{ "mightn't",{ "might","not" } },
{ "might've",{ "might","have" } },
{ "mustn't",{ "must","not" } },
{ "mustn't've",{ "must","not","have" } },
{ "must've",{ "must","have" } },
{ "needn't",{ "need","not" } },
{ "ne'er",{ "never" } },
{ "o'clock",{ "of","the","clock" } },
{ "o'er",{ "over" } },
{ "ol'",{ "old" } },
{ "oughtn't",{ "ought","not" } },
{ "shan't",{ "shall","not" } },
{ "should've",{ "should","have" } },
{ "shouldn't",{ "should","not" } },
{ "that're",{ "that","are" } },
{ "there're",{ "there","are" } },
{ "these're",{ "these","are" } },
{ "they've",{ "they","have" } },
{ "those're",{ "those","are" } },
{ "'tis",{ "it","is" } },
{ "'twas",{ "it","was" } },
{ "wasn't",{ "was","not" } },
{ "we'd've",{ "we","would","have" } },
{ "we'll",{ "we","will" } },
{ "we're",{ "we","are" } },
{ "we've",{ "we","have" } },
{ "weren't",{ "were","not" } },
{ "what'd",{ "what","did" } },
{ "what're",{ "what","are" } },
{ "what've",{ "what","have" } },
{ "where'd",{ "where","did" } },
{ "where're",{ "where","are" } },
{ "where've",{ "where","have" } },
{ "who'd've",{ "who","would","have" } },
{ "who're",{ "who","are" } },
{ "who've",{ "who","have" } },
{ "why'd",{ "why","did" } },
{ "why're",{ "why","are" } },
{ "won't",{ "will","not" } },
{ "would've",{ "would","have" } },
{ "wouldn't",{ "would","not" } },
{ "y'all",{ "you","all" } },
{ "y'all'd've",{ "you","all","would","have" } },
{ "yesn't",{ "yes","not" } },
{ "you're",{ "you","are" } },
{ "you've",{ "you","have" } },
{ "whomst'd've",{ "whomst","would","have" } },
{ "noun's",{ "noun","is" } },
};
auto it = shorts_and_longs.find(word);
if (it == shorts_and_longs.end()) {
return std::vector<Word>{word};
}
else {
return it->second;
}
return std::vector<Word>{};
}
void remove_plural(std::map<Word, Occurences>& cleaned_words)
// assume a plural is a word with an additional s
// e.g. ship and ships
// if both are present ships gets deleted and ++ship
{
for (auto it = cleaned_words.begin(); it != cleaned_words.end();) {
if(!it->first.empty() && it->first.back() == 's') {
Word singular = it->first;
singular.pop_back(); // remove 's' at the end
auto it_singular = cleaned_words.find(singular);
if (it_singular != cleaned_words.end()) {
cleaned_words[it_singular->first]+= it->second;
it = cleaned_words.erase(it);
}
else {
++it;
}
}
else {
++it;
}
}
}
void write_cleaned_words_to_file(const std::string& filename, const std::map<Word, Occurences>& cleaned_words)
{
std::ofstream ofs{ filename };
for (const auto& word : cleaned_words) {
ofs << word.first << " " << word.second << '\n';
}
}
}
</code></pre>
<p><strong>Word_query.h</strong></p>
<pre><code>#ifndef WORD_QUERY_GUARD_270820181433
#define WORD_QUERY_GUARD_270820181433
#include <map>
#include <optional>
#include <string>
#include <vector>
namespace word_query {
using Word = std::string;
using Occurences = int;
using Length = std::map<Word, Occurences>::size_type;
int occurences_of_word(const Word& word, const std::map<Word, Occurences>& words_with_occurences);
std::optional<std::pair<Word, Occurences>> most_frequent_word(const std::map<Word, Occurences>& words_with_occurences);
std::optional<Word> longest_word(const std::map<Word, Occurences>& words_with_occurences);
std::optional<Word> shortest_word(const std::map<Word, Occurences>& words_with_occurences);
std::vector<Word> words_starting_with(const Word& begin_of_word, const std::map<Word, Occurences>& words_with_occurences);
std::vector<Word> words_with_length(Length length, const std::map<Word, Occurences>& words_with_occurences);
}
#endif
</code></pre>
<p><strong>Word_query.cpp</strong></p>
<pre><code>#include "Word_query.h"
#include <algorithm>
namespace word_query {
int occurences_of_word(const Word& word, const std::map<Word, Occurences>& words_with_occurences)
//How many occurences of x are there in a file?
{
auto it = words_with_occurences.find(word);
if (it == words_with_occurences.end()) {
return 0;
}
else {
return it->second;
}
}
std::optional<std::pair<Word, Occurences>> most_frequent_word(const std::map<Word, Occurences>& words_with_occurences)
//Which word occurs most frequently?
{
if (words_with_occurences.empty()) return std::nullopt;
using pair_type = std::map<Word, Occurences>::value_type;
auto most_frequent = std::max_element(
words_with_occurences.begin(), words_with_occurences.end(),
[](const pair_type a, const pair_type b)
{
return a.second < b.second;
}
);
if (most_frequent == words_with_occurences.end()) {
return std::nullopt;
}
else {
return std::optional<std::pair<Word, Occurences>>{*most_frequent};
}
}
std::optional<Word> longest_word(const std::map<Word, Occurences>& words_with_occurences)
//Which is the longest word in the file?
{
if (words_with_occurences.empty()) return std::nullopt;
using pair_type = std::map<Word, Occurences>::value_type;
auto most_frequent = std::max_element(
words_with_occurences.begin(), words_with_occurences.end(),
[](const pair_type a, const pair_type b)
{
return a.first.size() < b.first.size();
}
);
if (most_frequent == words_with_occurences.end()) {
return std::nullopt;
}
else {
return std::optional<Word>{most_frequent->first};
}
}
std::optional<Word> shortest_word(const std::map<Word, Occurences>& words_with_occurences)
//Which is the shortest word in the file?
{
if (words_with_occurences.empty()) return std::nullopt;
using pair_type = std::map<Word, Occurences>::value_type;
auto most_frequent = std::min_element(
words_with_occurences.begin(), words_with_occurences.end(),
[](const pair_type a, const pair_type b)
{
return a.first.size() < b.first.size();
}
);
if (most_frequent == words_with_occurences.end()) {
return std::nullopt;
}
else {
return std::optional<Word>{most_frequent->first};
}
}
std::vector<Word> words_starting_with(const Word& begin_of_word, const std::map<Word, Occurences>& words_with_occurences)
{
std::vector<Word> matched_words;
for (const auto& word : words_with_occurences) {
if (word.first.substr(0, begin_of_word.size()) == begin_of_word) {
matched_words.push_back(word.first);
}
}
return matched_words;
}
std::vector<Word> words_with_length(Length length, const std::map<Word, Occurences>& words_with_occurences)
//all words with n letters
{
if (length < 0) {
throw std::runtime_error(
"std::vector<Word> words_with_length(Length length, const std::map<Word, Occurences>& words_with_occurences)\nlength must be positive\n");
}
std::vector<Word> words;
for (const auto& element : words_with_occurences) {
if (element.first.size() == length)
words.push_back(element.first);
}
return words;
}
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <exception>
#include <iostream>
#include "Cleaned_words.h"
#include "Word_query.h"
int main()
try{
std::cout << "Enter filename:\n";
std::string filename;
std::cin >> filename;
auto words = cleaned_words::read_words_from_file(filename);
cleaned_words::write_cleaned_words_to_file( "out_" + filename , words);
std::cout << "Enter word to search occurences for:\n";
std::string occur_word;
std::cin >> occur_word;
std::cout << occur_word << " is present in "
<< filename << " "
<< word_query::occurences_of_word(occur_word, words)
<< " times\n";
auto most_frequent = word_query::most_frequent_word(words);
if (most_frequent) {
std::cout << "The most frequent word in " << filename
<< " is: " << most_frequent->first
<< " with " << most_frequent->second
<< " occurences\n";
}
auto longest = word_query::longest_word(words);
if (longest) {
std::cout << "The longest word in " << filename
<< " is: " << *longest << '\n';
}
auto shortest = word_query::shortest_word(words);
if (shortest) {
std::cout << "The shortest word in " << filename
<< " is: " << *shortest << '\n';
}
std::cout << "Enter begining of words:\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::string word_begining;
std::cin >> word_begining;
std::cout << "All words starting with " << word_begining << " present in " << filename << '\n';
auto words_starting_with = word_query::words_starting_with(word_begining, words);
for (const auto& word : words_starting_with) {
std::cout << word << '\n';
}
std::cout << "Enter word length:\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
auto length = 0;
std::cin >> length;
std::cout << "All words with length of " << length << " present in " << filename << '\n';
auto words_with_specific_length = word_query::words_with_length(length, words);
for (const auto& word : words_with_specific_length) {
std::cout << word << '\n';
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
}
catch (std::runtime_error& e) {
std::cerr << e.what() << "\n";
std::cin.get();
}
catch (...) {
std::cerr << "unknown error " << "\n";
std::cin.get();
}
</code></pre>
<p>Besides <code>main</code>, where all the functions can be tested on a real file and asking the user for decision, I also thought about testing the single functions independently. For that I dug into unit tests with googletest in MSVC2017. I found out MSVC by default allready has the option to set up a test project which can link to the code.</p>
<p>For more details about this, see <a href="https://docs.microsoft.com/de-de/visualstudio/test/how-to-use-google-test-for-cpp" rel="nofollow noreferrer">this</a> and <a href="https://docs.microsoft.com/de-de/visualstudio/test/writing-unit-tests-for-c-cpp" rel="nofollow noreferrer">this</a>.</p>
<p>When getting the unit tests to run I run into the issue that Google tests seem to use still stuff from <code>std::tr1</code> which leads to issues if MSVC is turned to C++17. The strange solution Google gave and which has worked was adding <code>/Zc:__cplusplus</code> on the command line in the test project.</p>
<p>Beside that MSVC generated a file test.cpp from which I could run all my added unit tests linked to the project code.</p>
<p><strong>test.cpp</strong></p>
<pre><code>#include "pch.h"
#include "../PP_CH21_EX13_clean_txt/Cleaned_words.h"
#include "../PP_CH21_EX13_clean_txt/Word_query.h"
#include <sstream>
namespace cleaned_words {
TEST(contains_digits_test, detect_digits)
{
ASSERT_FALSE(cleaned_words::contains_digits("hello"));
ASSERT_TRUE(cleaned_words::contains_digits("1234hello"));
ASSERT_TRUE(cleaned_words::contains_digits("hello1234"));
ASSERT_TRUE(cleaned_words::contains_digits("hel1lo"));
}
TEST(remove_invalid_signs_test, Invalid_sign_was_removed)
{
ASSERT_EQ("Hello", remove_invalid_signs(".,_()+-=?“”:;\"Hello.,_()+-=?“”:;\"", R"({}[]<>&.,_()+-=?“”:;/\")"));
ASSERT_EQ("a", remove_invalid_signs("\"a", R"({}[]<>&.,_()+-=?“”:;/\")"));
}
TEST(remove_whitespace_test, whitespace_gets_removed)
{
ASSERT_EQ("", remove_whitespace(""));
ASSERT_EQ("Hello", remove_whitespace("Hello"));
ASSERT_EQ("Hello", remove_whitespace(" H e l l o "));
}
TEST(remove_capital_letters_test, capital_letters_get_lowered)
{
ASSERT_EQ("", remove_capital_letters(""));
ASSERT_EQ("hellohello", remove_capital_letters("HELLOhello"));
}
TEST(remove_contractions_test, words_get_transformed_to_long_form)
{
std::vector<Word> a = { "are", "not" };
std::vector<Word> b = remove_contractions("aren't");
ASSERT_EQ(a.size(), b.size());
for (std::vector<Word>::size_type i = 0; i < a.size(); ++i) {
ASSERT_EQ(a[i], b[i]);
}
}
TEST(remove_plural_test, plural_gets_removed)
{
int c1 = 10;
int c2 = 5;;
std::map<Word, Occurences> test{
{"ship",c1},
{"ships",c2}
};
remove_plural(test);
ASSERT_TRUE(test.find("ships") == test.end());
ASSERT_TRUE(test.find("ship") != test.end());
ASSERT_TRUE(test.find("ship")->second == c1 + c2);
ASSERT_TRUE(test.size() == 1);
}
TEST(read_cleaned_words_with_occurence_test, words_get_cleaned)
{
std::string s = "HELLO hello this is a ship ships ships do not now 123test aren't";
std::istringstream ifs{ s };
auto res = read_cleaned_words_with_occurence(ifs);
ASSERT_TRUE(res["hello"] == 2);
ASSERT_TRUE(res["ship"] == 3);
ASSERT_TRUE(res.find("ships") == res.end());
ASSERT_TRUE(res.find("aren't") == res.end());
ASSERT_TRUE(res.find("are") != res.end());
ASSERT_TRUE(res.find("not") != res.end());
}
}
namespace word_query {
TEST(occurences_of_word_test, correct_occurence)
{
std::map<Word, Occurences> words
{
{"hello",20},
{"this",14}
};
ASSERT_TRUE(occurences_of_word("hello", words) == 20);
ASSERT_TRUE(occurences_of_word("this", words) == 14);
ASSERT_TRUE(occurences_of_word("is", words) == 0);
}
TEST(most_frequent_word_test, find_most_frequent)
{
std::map<Word, Occurences> words
{
{"hello",20},
{"this",14},
{"is",98},
{"a",3},
{"test",5}
};
ASSERT_EQ("is",(most_frequent_word(words))->first);
}
TEST(longest_word_test, find_longest_word)
{
std::map<Word, Occurences> words
{
{"hello",20},
{"this",14},
{"is",98},
{"a",3},
{"test",5}
};
ASSERT_EQ("hello", longest_word(words));
}
TEST(shortest_word_test, find_shortest_word)
{
std::map<Word, Occurences> words
{
{"hello",20},
{"this",14},
{"is",98},
{"a",3},
{"test",5}
};
ASSERT_EQ("a", shortest_word(words));
}
TEST(words_starting_with_test, find_words_starting_with)
{
std::map<Word, Occurences> words
{
{"hello",20},
{"this",14},
{"is",98},
{"a",3},
{"test",5}
};
std::vector<Word> res;
res = words_starting_with("th", words);
ASSERT_EQ(1, res.size());
ASSERT_EQ("this", res[0]);
res = words_starting_with("t", words);
ASSERT_EQ(2, res.size());
}
TEST(words_with_length_test, find_words_with_length)
{
std::map<Word, Occurences> words
{
{"hello",20},
{"this",14},
{"is",98},
{"a",3},
{"test",5}
};
std::vector<Word> res;
res = words_with_length(1, words);
ASSERT_EQ(1, res.size());
ASSERT_EQ("a", res[0]);
res = words_with_length(2, words);
ASSERT_EQ(1, res.size());
ASSERT_EQ("is", res[0]);
res = words_with_length(3, words);
ASSERT_TRUE(res.empty());
res = words_with_length(4, words);
ASSERT_TRUE(2, res.size());
ASSERT_EQ("this", res[1]);
ASSERT_EQ("test", res[0]);
}
}
</code></pre>
<p>Please let me know what you think about the presented code.</p>
<ol>
<li>Are there any improvements which could be done to solve these exercises?</li>
<li>Are there any bad practices in the code? Is there stuff made to complicated? Is there an easier solution?</li>
<li>How would you improve the tests?</li>
</ol>
| [] | [
{
"body": "<blockquote>\n<pre><code>inline unsigned char unsigned_isspace(char c)\n{\n return isspace(static_cast<unsigned char>(c));\n}\n</code></pre>\n</blockquote>\n\n<p>Misspelt <code>std::isspace</code>, and forgot to include <code><cctype></code>.</p>\n\n<p>A simpler implementation would ju... | {
"AcceptedAnswerId": "202726",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T17:05:49.940",
"Id": "202680",
"Score": "7",
"Tags": [
"c++",
"file",
"c++17"
],
"Title": "Cleaning a file / Word Query"
} | 202680 |
<p>I have been writing a lot of jQuery plugins lately, but I don't really know if what I am doing is any good. Here is one of my most recent plugins. It allows the user to add a data attribute to any class and load a full page view window (which is written to the body on render) to e.g. open a menu on mobile or read large pieces of text without taking up the entire page (scrolling on a product page for example):</p>
<pre><code>(function ($) {
var jelm = $('.js-full-page-view');
var methods = {
init: function () {
jelm.each(function () {
var id = $(this).attr('id'),
title = ($(this).data('caFullPageTitle')) ? $(this).data('caFullPageTitle') : '',
content = (!$(this).data('caSingle')) ? $(this).html() : '',
action_container = ($(this).data('caActionContainer')) ? $(this).data('caActionContainer') : '',
indented_content = ($(this).data('caNoIndentedContent')) ? '' : 'full-page-view--indented-content',
bottom_action_container = '';
if ($(this).data('caBottomActionContainer')) {
bottom_action_container = '<div class="full-page-view--footer-bar">' + $(this).data('caBottomActionContainer') + '</div>';
}
$('body').append(
'<div class="full-page-view js-full-page-view" id="fp_' + id
+ '"><div class="full-page-view--main-bar"><div class="full-page-view--action-container"><button class="full-page-view--action js-full-page-view-close"><svg class="icon-svg alt-flip"><use xlink:href="#icon-arrow"></use></svg></button></div><div class="full-page-view--title">' + title
+ '</div><div class="full-page-view--action-container">' + action_container + '</div></div><div class="full-page-view--scroll-pane full-page-view--content ' + indented_content + '">' + content
+ '</div>' + bottom_action_container + '</div>');
});
methods.bind();
},
bind: function () {
$('.js-full-page-view-open').on('click', function () {
var open_elm = ($(this).data('caTarget')) ? $("#" + $(this).data('caTarget')) : $(this).closest('.js-full-page-view');
if (methods.responsive_check(open_elm)) {
methods.open('#fp_' + open_elm.attr('id'));
}
});
$('.js-full-page-view-close').on('click', function () {
var close_elm = ($(this).data('caTarget')) ? $(this).data('caTarget') : $(this).closest('.js-full-page-view');
methods.close('#' + close_elm.attr('id'));
});
},
close: function (selector) {
$(selector).removeClass('active').ceScrollLock('body', 'rm');
if (methods.single_check('#' + selector.substring(4))) {
var focus = $(selector + ' .full-page-view--content');
var content = $(focus).html();
$('#' + selector.substring(4) + ' .full-page-view--content-placeholder').append(content);
focus.empty();
}
},
open: function (selector) {
$(selector).addClass('active');
setTimeout(function() {$(selector).ceScrollLock('body', 'add');}, 200);
if (methods.single_check('#' + selector.substring(4))) {
var focus = $('#' + selector.substring(4) + ' .full-page-view--content-placeholder');
var content = $(focus).html();
$(selector + ' .full-page-view--content').append(content);
focus.empty();
}
},
responsive_check: function (selector) {
return $.fn.getRealWidth() <= $(selector).data('caResponsiveMax');
},
responsive_resize: function () {
$('.js-full-page-view.active').each(function() {
if (!methods.responsive_check('#' + $(this).attr('id').substring(3))) {
methods.close('#' + $(this).attr('id'));
}
});
},
single_check: function (elem) {
return !!$(elem).data('caSingle');
}
};
$.fn.ceFullPageView = function (method) {
return $(this).each(function (i, elm) {
var errors = {};
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('fullpageview: method ' + method + ' does not exist');
}
});
};
if ($(document).ready()) {
$('.js-full-page-view').ceFullPageView();
$('.js-full-page-view-open').on('click', function () {
$(this).ceFullPageView('bind');
});
$('.js-full-page-view-close').on('click', function () {
$(this).ceFullPageView('bind');
});
$(window).resize(function () {
$(this).ceFullPageView('responsive_resize');
});
}
})(jQuery);
</code></pre>
<p>And the supportive functions</p>
<pre><code>(function (_, $) {
var methods = {
rm: function () {
$('body').removeClass('is-non-scrollable-fixed');
},
add: function() {
$('body').addClass('is-non-scrollable-fixed');
}
};
$.fn.ceScrollLock = function (selector, method) {
return methods[method].apply(this, arguments);
};
$.fn.ceIsIE = function (userAgent) {
userAgent = userAgent || navigator.userAgent;
return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1 || userAgent.indexOf("Edge/") > -1;
};
$.fn.getRealWidth = function () {
var outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo(outer).outerWidth();
outer.remove();
var scrollBarWidth = 100 - widthWithScroll;
if ($.fn.ceIsIE) {
return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}
if ($('.is-non-scrollable-fixed').length) {
return $('body').width();
} else {
return $('body').width() + scrollBarWidth;
}
};
})(jQuery);
</code></pre>
<p>And the HTML:</p>
<pre><code><div class="js-full-page-view" data-ca-single="true" data-ca-responsive-max="667" data-ca-full-page-title="{sl 'filter'}" id="full_page_product_filter">
<div class="full-page-view--content-placeholder">
Any HTML content
<div>
</div>
</code></pre>
<p>Let me know what you think.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T06:24:06.783",
"Id": "391994",
"Score": "0",
"body": "Thanks for adding the HTML and supportive js functions. I tried updating the fiddle cited in my answer but it didn’t work. I noticed the IiFE for the supportive functions passes... | [
{
"body": "<h2>Feedback</h2>\n\n<p>Overall the code seems to be architected acceptably (though see the first review point below about the DOM-ready code). Some of the HTML generation seems complex - perhaps using a template system (e.g. using a <a href=\"https://stackoverflow.com/a/4912608/1575353\">template <... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T17:20:28.697",
"Id": "202682",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"dom",
"plugin"
],
"Title": "jQuery plugin to load a full-page view window"
} | 202682 |
<p>Coming from a C/C++ background, this was my first python code I wrote to grasp a few basic concepts. The game involves giving random arithmetic operations to the users and scoring their responses. Player has 3 lives i.e he can mark 3 wrong answers at most. I've tried to time the game i.e the player gets 60 seconds to solve as many questions as possible. </p>
<p>Any suggestions and improvements are welcome. </p>
<pre><code>import random
import time
# Function to generate expressions
from typing import List
def generate_expression(no_of_operators):
operands = []
operators = []
operations = ['+', '-', '*', '/']
expression = []
operands_count = 0
operators_count = 0
for i in range(0, no_of_operators):
operands.append(random.randint(0, 20))
for i in range(0, no_of_operators - 1):
operators.append((random.choice(operations)))
for i in range(0, len(operators) + len(operands)):
if i % 2 == 0:
expression.append(operands[operands_count])
operands_count += 1
else:
expression.append(operators[operators_count])
operators_count += 1
expression = ''.join(str(x) for x in expression)
return expression
# Function to calculate the solution
def result(expression):
return (int(eval(expression)))
# Function to evaluate if the answer is right
def evaluate(solution, user_solution):
if solution == user_solution:
return True
else:
return False
# Display Message
print("""Welcome to the maths game !!!
-----------------------------
Test your basic arithematic skills by playing this simple game. With every 5 correct answers, the level increase
increasing the difficulty of the questions.
Remember :
----------
1. Write only the integral part of the answer
2. Operator precedence applies
3. You have 3 lives.
4. Total of 60 seconds will be provided.
5. The timer starts after the first answer is entered """)
input("Are you ready ?? Press any key to begin ! ")
# Variables on which the game operates
score = 0
level = 1
lives = 3
start = time.time()
finish_time = time.time() + 60 # for the timed mode, 60 seconds are needed
# While loop to drive the game
while lives != 0 and time.time() < finish_time:
# Increase the level of difficulty every 5 questions.
if score != 0 and score % 5 == 0:
level = level + 1
print("LEVEL : ", level)
no_of_operands = level + 1
question_expression = generate_expression(no_of_operands)
print(question_expression, end='')
# Checking for any divide by zero or numerical errors that may show up
correct_answer = 0
try:
correct_answer = result(question_expression)
except:
print("OOPS ! I messed up ! Lets do it again !")
continue
answer = int(input(" = "))
if evaluate(correct_answer, answer):
print("CORRECT ! ", end='')
score = score + 1
print("SCORE = ", score, "LIVES = ", lives)
else:
print("WRONG ! ", end='')
lives = lives - 1
print("SCORE = ", score, "LIVES = ", lives)
print("GAME OVER !!!")
print("Maximum Level = ", level, "SCORE = ", score)
</code></pre>
| [] | [
{
"body": "<p>Welcome to Code Review.</p>\n\n<p>The type <code>List</code>, imported by <code>from typing import List</code> is never used. You can delete this statement.</p>\n\n<p>The function <code>def generate_expression(no_of_operators):</code> is a little verbose and complex. You don't need to create sep... | {
"AcceptedAnswerId": "202687",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T17:30:36.063",
"Id": "202683",
"Score": "3",
"Tags": [
"python",
"beginner",
"quiz"
],
"Title": "Simple arithmetic game in Python"
} | 202683 |
<p>I'm learning <code>ASP.NET Core</code> with <code>MVC</code> pattern and I didn't find anything useful related to this argument. </p>
<p>Actually I'm looking for a way to handle all the application errors inside a single <code>View</code>. The first thing that I did was create the <code>View</code> for display the error, this is the design (pretty simple though):</p>
<pre><code><h2>@(ViewBag.ErrorMessage == null ? "An error happened" : "" + @ViewBag.ErrorMessage + "")</h2>
</code></pre>
<p>and this is the <code>Error</code> controller:</p>
<pre><code>public class ErrorController : Controller
{
[HttpGet]
public IActionResult Index(string errorMessage)
{
ViewBag.ErrorMessage = errorMessage;
return View();
}
}
</code></pre>
<p>Essentially, I used the <code>ViewBag</code> for valorize a property called <code>ErrorMessage</code> which contains the parameter <code>errorMessage</code>.</p>
<p>Let me show an example of this logic for the email confirmation:</p>
<pre><code>public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
if (userId == null || token == null)
{
return RedirectToAction("Index", "Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
if (user.EmailConfirmed)
{
return RedirectToAction("Index", "Error", new { errorMessage = "Email already confirmed" });
}
IdentityResult result;
try
{
result = await _userManager.ConfirmEmailAsync(user, token);
}
catch (InvalidOperationException ex)
{
return RedirectToAction("Index", "Error", new { errorMessage = ex.Message });
}
if (result.Succeeded)
{
//TODO: Send another email
return View("ConfirmEmail", user);
}
}
return RedirectToAction("Index", "Error", new { errorMessage = "Utser not found" });
}
</code></pre>
<p>Now, I'm not an expert yet of <code>ASP.NET Core</code> so I don't know if my practice is good enough for a production environment, someone could maybe propose a better way or improve my solution?</p>
| [] | [
{
"body": "<p>While I see no problem design-like or code-like, in the point of view of the user, It can be frustrating. </p>\n\n<p>I guess the method <code>ConfirmEmail</code> is called from a form. </p>\n\n<p>So, imagine how frustrating it is if you fill a form and if there is any error in this form, it redire... | {
"AcceptedAnswerId": "202868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T17:47:22.503",
"Id": "202684",
"Score": "2",
"Tags": [
"c#",
"error-handling",
"asp.net",
"asp.net-mvc"
],
"Title": "Displaying all application errors in a view"
} | 202684 |
<p>This is a coding interview I found online, to be solved within 30 minutes:</p>
<blockquote>
<p>Design an OOP concept for an application where employee can dispatch their incoming phone call according to their seniority level if they are not able to solve.</p>
</blockquote>
<p>I chose to use Chain of Responsibility pattern, I also used Null pattern.
Please review OOP principles and the specific design pattern implementation.</p>
<p>The unit test is just a code sample.</p>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DesignPatternsQuestions
{
[TestClass]
public class ChainOfResponsibilityTest
{
[TestMethod]
public void PhoneCallDispatchCORTest()
{
PhoneCallHandler gilad = new PhoneCallHandler(new LowLevel("Gilad"));
PhoneCallHandler bonno = new PhoneCallHandler(new LowLevel("Bonno"));
PhoneCallHandler batel = new PhoneCallHandler(new MediumLevel("Batel"));
PhoneCallHandler daniel = new PhoneCallHandler(new HighLevel("Daniel"));
gilad.RegisterNext(batel);
bonno.RegisterNext(batel);
batel.RegisterNext(daniel);
BankPhoneCall call1 = new BankPhoneCall(1500);
bool res = gilad.GetPhoneCall(call1);
Assert.IsTrue(res);
}
}
public interface IPhoneCall
{
int Budget { get; set; }
}
public class BankPhoneCall :IPhoneCall
{
public BankPhoneCall(int budget)
{
Budget = budget;
}
public int Budget { get; set; }
}
public interface IPhoneCallHandler
{
bool GetPhoneCall(IPhoneCall phoneCall);
//the same item is able to call next Item in the chain of command
void RegisterNext(IPhoneCallHandler employee);
}
public class PhoneCallHandler : IPhoneCallHandler
{
private IPhoneCallHandler _nextCallHandler = EndOfChainHandler.Instance;
private Employee _employee;
public PhoneCallHandler(Employee employee)
{
_employee = employee;
}
public bool GetPhoneCall(IPhoneCall phoneCall)
{
bool res = _employee.Resolve(phoneCall);
if (!res)
{
//handle _nextcallHandler == null with null pattern
return _nextCallHandler.GetPhoneCall(phoneCall);
}
return res;
}
public void RegisterNext(IPhoneCallHandler nextCallHandler)
{
_nextCallHandler = nextCallHandler;
}
}
/// <summary>
/// null pattern
/// </summary>
public sealed class EndOfChainHandler : IPhoneCallHandler
{
private static readonly Lazy<EndOfChainHandler> lazy = new Lazy<EndOfChainHandler>(()=> new EndOfChainHandler());
public static EndOfChainHandler Instance { get { return lazy.Value; } }
public bool GetPhoneCall(IPhoneCall phoneCall)
{
return false;
}
public void RegisterNext(IPhoneCallHandler employee)
{
throw new InvalidOperationException("can't register next to null");
}
}
public abstract class Employee
{
protected int _maxBudget;
public string Name { get;set; }
public Employee(string name, int maxBudget)
{
_maxBudget = maxBudget;
Name = name;
}
public bool Resolve(IPhoneCall phoneCall)
{
return phoneCall.Budget <= _maxBudget;
}
}
public class LowLevel : Employee
{
public LowLevel(string name)
: base(name, 1000)
{
}
}
public class MediumLevel : Employee
{
public MediumLevel(string name)
: base(name, 5000)
{
}
}
public class HighLevel : Employee
{
public HighLevel(string name)
: base(name, 10000)
{
}
}
}
</code></pre>
| [] | [
{
"body": "<h2>Review</h2>\n\n<p>Well done, there isn't much I would change in this implementation. I would grant you the <em>humble badge</em> for putting yourself as <code>LowLevel</code> employee :) </p>\n\n<p>The lazy and null pattern are well implemented (except a small issue that could possibly introduce ... | {
"AcceptedAnswerId": "227475",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T20:11:53.220",
"Id": "202690",
"Score": "5",
"Tags": [
"c#",
"design-patterns",
"interview-questions"
],
"Title": "Call center escalation excercise, using Chain of Responsibility pattern"
} | 202690 |
<p>Although this question has been asked a lot of times, I was hoping for a feedback on my approach.</p>
<blockquote>
<p>Tax Calculator Basic sales tax is applicable at a rate of 10% on all
goods, except books, food, and medical products that are exempt.
Import duty is an additional sales tax applicable on all imported
goods at a rate of 5%, with no exemptions.</p>
<p>When I purchase items I receive a receipt which lists the name of all
the items and their price (including tax), finishing with the total
cost of the items, and the total amounts of sales taxes paid. The
rounding rules for sales tax are that for a tax rate of n%, a shelf
price of p contains (np/100 rounded up to the nearest 0.05) amount of
sales tax.</p>
<p>Write an application that prints out the receipt details ...</p>
<p>Input 1:</p>
<pre class="lang-none prettyprint-override"><code>1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85
</code></pre>
<p>Output 1:</p>
<pre class="lang-none prettyprint-override"><code>1 book: 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83
</code></pre>
<p>Input 2:</p>
<pre class="lang-none prettyprint-override"><code>1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50
</code></pre>
<p>Output 2:</p>
<pre class="lang-none prettyprint-override"><code>1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15
</code></pre>
<p>Input 3:</p>
<pre class="lang-none prettyprint-override"><code>1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25
</code></pre>
<p>Output 3:</p>
<pre class="lang-none prettyprint-override"><code>1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
</code></pre>
</blockquote>
<p><strong>TaxCalculatorApplication</strong> </p>
<pre class="lang-java prettyprint-override"><code>class TaxCalculatorApplication {
Receipt generateReceipt(String[] inputs) {
List<Item> items = ItemFactory.from(inputs);
return new Receipt(items);
}
}
</code></pre>
<p><strong>ItemFactory</strong></p>
<pre class="lang-java prettyprint-override"><code>public class ItemFactory {
public static List<Item> from(String[] inputs) {
return Arrays.stream(inputs)
.map(ItemFactory::from)
.collect(Collectors.toList());
}
private static Item from(String input) {
Item item = ItemAdapter.createItemFromString(input);
ItemTaxCalculator.applyTaxes(item);
return item;
}
}
</code></pre>
<p><strong>ItemAdapter</strong></p>
<pre class="lang-java prettyprint-override"><code>public class ItemAdapter {
private static final String ITEM_ENTRY_REGEX = "(\\d+) ([\\w\\s]* )at (\\d+.\\d{2})";
public static Item createItemFromString(String input) {
Pattern pattern = Pattern.compile(ITEM_ENTRY_REGEX);
Matcher matcher = pattern.matcher(input);
matcher.find();
return new Item(matcher.group(1), matcher.group(2), matcher.group(3));
}
}
</code></pre>
<p><strong>ItemTaxCalculator</strong></p>
<pre class="lang-java prettyprint-override"><code>public class ItemTaxCalculator {
private static final double SALES_TAX_PERCENT = 0.1;
private static final double ADDITIONAL_SALES_TAX_PERCENT = 0.05;
public static void applyTaxes(Item item) {
if (!item.isExempted()) {
item.setBasicSalesTaxAmount(SALES_TAX_PERCENT);
}
if (item.isImported()) {
item.setAdditionalSalesTax(ADDITIONAL_SALES_TAX_PERCENT);
}
}
}
</code></pre>
<p><strong>Receipt</strong></p>
<pre class="lang-java prettyprint-override"><code>public class Receipt {
private double totalSalesTax = 0.0;
private double totalAmount = 0.0;
private String itemDetails;
public Receipt(List<Item> items) {
StringBuilder itemDetails = new StringBuilder();
for (Item item : items) {
itemDetails.append(item.toString()).append("\n");
totalSalesTax += item.getTaxAmount();
totalAmount += item.getFinalPrice();
}
totalAmount = MathUtils.roundOffAmount(totalAmount);
totalSalesTax = MathUtils.roundOffAmount(totalSalesTax);
this.itemDetails = itemDetails.toString();
}
public double getTotalAmount() {
return totalAmount;
}
public double getTotalSalesTax() {
return totalSalesTax;
}
@Override
public String toString() {
return "Receipt" + "\n"
+ itemDetails
+ "Sales Taxes: " + totalSalesTax + "\n"
+ "Total: " + totalAmount
+"\n*******************************\n";
}
}
</code></pre>
<p><strong>Item</strong></p>
<pre class="lang-java prettyprint-override"><code>public class Item {
private String name;
private int quantity;
private double basePrice;
private double basicSalesTaxAmount;
private double additionalSalesTaxAmount;
public Item(String quantity, String name, String basePrice) {
this.name = name;
this.quantity = Integer.valueOf(quantity);
this.basePrice = Double.valueOf(basePrice);
}
public double getFinalPrice() {
return MathUtils.roundOffAmount(quantity * basePrice + getTaxAmount());
}
public double getTaxAmount() {
return quantity * (basicSalesTaxAmount + additionalSalesTaxAmount);
}
public boolean isImported() {
return name.contains("imported");
}
public boolean isExempted() {
return Stream.of("book", "chocolate", "pill")
.anyMatch(exemptedItem -> name.contains(exemptedItem));
}
public void setBasicSalesTaxAmount(double factor) {
basicSalesTaxAmount = basePrice * factor;
}
public void setAdditionalSalesTax(double additionalSalesTaxPercent) {
additionalSalesTaxAmount = MathUtils.roundOffTax(basePrice * additionalSalesTaxPercent);
}
public String toString() {
return String.valueOf(quantity) +
" " +
name +
" : " +
getFinalPrice();
}
}
</code></pre>
<p><strong>MathUtils</strong></p>
<pre class="lang-java prettyprint-override"><code>public class MathUtils {
public static double roundOffTax(double number) {
return Math.ceil(number * 20) / 20;
}
public static double roundOffAmount(double number) {
return Math.round(number * 100.0) / 100.0;
}
}
</code></pre>
<p>The whole project is available at <a href="https://github.com/ankitprahladsoni/tax_calculator/tree/bf1da78d3d513c5b24149142e1e2de8d97fa4a3a" rel="nofollow noreferrer">this link</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T20:43:23.967",
"Id": "390576",
"Score": "1",
"body": "Obvious hole is the categorization of items. Items which erroneously get tax exempt status include “bookmarks” and “pillows”, and “chocolate flavoured lipstick”."
}
] | [
{
"body": "<p>First don't mix <code>Item</code> class with <code>Recipe</code>(<code>ShoppingCart</code>) class. the <code>quantity</code> should be part of <code>RecipeItem</code>(<code>ShoppingCartItem</code>), as well as <code>Tax</code>&<code>Cost</code>. The <code>TotalTax</code>&<code>TotalCost</c... | {
"AcceptedAnswerId": "206841",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T20:17:25.193",
"Id": "202691",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"interview-questions",
"calculator"
],
"Title": "A tax calculator application to calculate tax and print final receipt"
} | 202691 |
<p>I'm implementing a BFS traversal in a grid-like structure. Because I wanted to experiment with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*" rel="nofollow noreferrer">ES6 Generators</a> for a long time, I thought I'd implement the search using that abstraction.</p>
<p>I am sure there are obvious things I could improve in the code, because it looks fishy to me, especially after some "special constraints" that I needed to add.</p>
<p>Moreover, the code takes "forever" to run, and I was looking into any performance tips.</p>
<h2>Background and constraints</h2>
<ol>
<li>What I am looking for is not really <em>pathfinding</em>, actually. I need to return an area for all the possible grid tiles an entity could reach.</li>
<li>Each entity has a certain <code>movement range</code> score.</li>
<li>Each entity has a certain <code>action</code> score. For every <code>action</code> point, the entity can move up to its entire <code>movement range</code>.</li>
<li>The boundaries between each range multiplier need to be clearly visible (so they must be returned in different groups, and can't just be added together).</li>
<li>Diagonal movement across the grid counts as <code>1.5</code>, rather then the more classic Manhattan-distance <code>2</code>.</li>
</ol>
<p>Here are two images of what the result should be like:</p>
<p><a href="https://i.stack.imgur.com/h0bx6.png?s=256" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h0bx6.png?s=256" alt="1 action point"></a>
<a href="https://i.stack.imgur.com/SI1dI.png?s=256" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SI1dI.png?s=256" alt="4 action points"></a></p>
<p>As you can see in the first one, the green entity has <code>6 movement</code> range and <code>1 action</code>. In the second one, it is the same entity with <code>4 actions</code>, the different shades show the different areas.</p>
<h2>Implementation</h2>
<h3>Adjacent tiles</h3>
<p>First of all, I've got two simple helper functions to get tiles which are adjacent or diagonal from a given tile. Perhaps I could implement these in some other way too, so feedback is accepted.</p>
<pre><code>getTilesAdjacentTo(tile) {
const cost = tile.cost || 0;
return [
{ x: tile.x, y: tile.y + 1, cost: cost + 1 },
{ x: tile.x, y: tile.y - 1, cost: cost + 1 },
{ x: tile.x + 1, y: tile.y, cost: cost + 1 },
{ x: tile.x - 1, y: tile.y, cost: cost + 1 }
].filter(tile => {
return (tile.x >= 0 && tile.x < this.size.x)
&& (tile.y >= 0 && tile.y < this.size.y)
});
}
getTilesDiagonalTo(tile) {
const cost = tile.cost || 0;
return [
{ x: tile.x - 1, y: tile.y - 1, cost: cost + 1.5 },
{ x: tile.x - 1, y: tile.y + 1, cost: cost + 1.5 },
{ x: tile.x + 1, y: tile.y + 1, cost: cost + 1.5 },
{ x: tile.x + 1, y: tile.y - 1, cost: cost + 1.5 }
].filter(tile => {
return (tile.x >= 0 && tile.x < this.size.x)
&& (tile.y >= 0 && tile.y < this.size.y)
});
}
</code></pre>
<p>It filters out tiles that are outside of the grid.</p>
<h3>Search function</h3>
<pre><code>searchAroundTile: function* (tile, type = 'pathableOnly') {
let costStep = 0,
diagonalTiles = [],
frontier = [tile],
visitedTiles = [],
currentTile;
while(true) {
// Get the first tile out of the frontier
currentTile = frontier.shift();
if(!currentTile)
break;
// I want to yield every time a circle of range 1 has been completed
if(currentTile.cost <= costStep) {
if(
// Checking that the tile has not been visited yet.
// Is there a better way not to add tiles that have been
// visited to the frontier?
!visitedTiles.some(
tile => tile.x === currentTile.x && tile.y === currentTile.y
)
&& (
// Checks if the tile is pathable.
// The first check is required because the tile with the
// entity on it is technically not pathable.
currentTile === tile
|| type === 'all'
|| this.isPathable(currentTile)
)
) {
frontier = [ ...frontier, ...this.getTilesAdjacentTo(currentTile) ];
// I save diagonal tiles separately and concat them later so
// that I can be sure that the frontier is kept in order of
// cost, basically.
diagonalTiles = [ ...diagonalTiles, ...this.getTilesDiagonalTo(currentTile) ];
visitedTiles.push(currentTile);
}
}
else {
frontier.unshift(currentTile);
frontier = [ ...frontier, ...diagonalTiles ];
costStep += 1;
yield visitedTiles;
}
if(!frontier.length)
break;
}
yield visitedTiles;
}
</code></pre>
<h3>Calculate range function</h3>
<pre><code>calculateRange(from, range, min = 0, rangeType = 'all', repeat = 1) {
let area = [],
currentCost = 0,
i = 1,
search = this.searchAroundTile(
{ ...from, cost: 0 },
rangeType
),
visitedTiles;
// This is in order to divide each repeat, but not to have to start
// a separate search from scratch. That's where I think the generator
// pattern helps also.
while(repeat) {
visitedTiles = [];
// Just iterate the generator until the cost of the last tile is in range.
while(currentCost < range * i) {
visitedTiles = search.next().value;
currentCost = visitedTiles[visitedTiles.length - 1].cost;
}
area.push(visitedTiles.filter(
// `min` is an optional argument in case one wants minimum ranges.
// The second filter makes sure it removes from the current area
// tiles that are not within that range. Sometimes I would end up
// with a few tiles belonging to the previous area. This is
// probably a fault in the search algorithm which I didn't find.
tile => tile.cost >= min && tile.cost > range * (i - 1)
));
i++;
repeat--;
}
// `area` is an array of arrays, so it allows me to clearly identify
// each area separately as seen in the picture above.
return area;
}
</code></pre>
<p>For what is worth, I have tried to quickly hack a non generator version of this code, and performance is the same. So the generator iteration doesn't really impact on the performance issue as far as I understand.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-29T16:10:34.767",
"Id": "390739",
"Score": "0",
"body": "1) Your isVisited check is too inefficient. Use a 2 dimentional array to check in a single access if the grid is not too big, or use an object/set if its too big. Also don´t add ... | [
{
"body": "<h1>Too many arrays</h1>\n\n<p>You have some poor array techniques that will be thrashing GC and adding additional processing load that can be avoided.</p>\n\n<p>For example you add tiles to the array by recreating the array. That means that you need to keep both the old and new copies in memory and ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T21:33:07.263",
"Id": "202695",
"Score": "0",
"Tags": [
"javascript",
"performance",
"algorithm",
"pathfinding",
"breadth-first-search"
],
"Title": "BFS Pathfinding algorithm using Javascript generator"
} | 202695 |
<p>I am taking a class in mobile application development this fall. I have finished my first assignment of creating a class to divide an arbitrary dollar amount into the minimum number of bills and coins. I have completed the assignment and everything works as intended (outside of an occasional error I'm having with computing pennies, but I am working on that). My main reason for posting is I would like to try and make my code more Swift like. I am coming from a mostly C background so I am learning the ins and outs of Swift and OOP on the fly. So if you have any suggestions to making my code more "Swift like" I would greatly appreciate it.</p>
<pre><code>public class Cash
{
// Denominations of monies
let bills = [50.00, 20.00, 10.00, 5.00, 1.00, 0.25, 0.10, 0.05, 0.01]
// Backing variable
var value:Double
// Computed Property of minimum number of bills to satisfy the value sent in
public var minBills:[Int]? {
var tempArray = [Int]()
var tempValue: Double
if value >= 0 {
for index in 0..<bills.count {
tempValue = value / bills[index] //Calculating the amount of bills
value -= Double(Int(tempValue)) * bills[index] //Recalculating the value
tempArray.append(Int(tempValue)) //Adding number of bills needed to tempArray
}
return tempArray //Returns entire tempArray to minBills
}
else {
return nil
}
}
//Constructor
public init(value: Double) {
self.value = value
}
}
</code></pre>
| [] | [
{
"body": "<p>The computed property <code>minBills</code> modifies the <code>value</code> property, which would\nbe unexpected to the caller:</p>\n\n<pre><code>let cash = Cash(value: 50.0)\nprint(cash.minBills!) // [1, 0, 0, 0, 0, 0, 0, 0, 0] OK!\nprint(cash.minBills!) // [0, 0, 0, 0, 0, 0, 0, 0, 0] What?\n</... | {
"AcceptedAnswerId": "202736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T21:50:02.983",
"Id": "202696",
"Score": "3",
"Tags": [
"beginner",
"object-oriented",
"swift",
"homework",
"change-making-problem"
],
"Title": "Dividing an arbitrary dollar amount into the fewest bills and coins"
} | 202696 |
<p>I am the author of <a href="https://squiggle.readthedocs.org" rel="nofollow noreferrer">this</a> package that turns DNA sequences into two dimensional visualizations. DNA, for the unaware, consists of four letters (A, T, G, and C). To convert the sequence, I am using this code:</p>
<pre><code>import numpy as np
def transform(sequence):
running_value = 0
x, y = np.linspace(0, len(sequence), 2 * len(sequence) + 1), [0]
for character in sequence:
if character == "A":
y.extend([running_value + 0.5, running_value])
elif character == "C":
y.extend([running_value - 0.5, running_value])
elif character == "T":
y.extend([running_value - 0.5, running_value - 1])
running_value -= 1
elif character == "G":
y.extend([running_value + 0.5, running_value + 1])
running_value += 1
else:
y.extend([running_value] * 2)
return list(x), y
</code></pre>
<p>Note that <code>seq</code> may be a very long sequence, and this transformation process may be done (hundreds of) thousands of time.</p>
<p>What are some things I could do to improve performance?</p>
<p>Edit:</p>
<ul>
<li><p>The <code>else</code> clause is the because some DNA sequences have ambiguity (<em>i.e.</em> non ATGC characters) which must be accounted for as horizontal lines.</p></li>
<li><p><code>sequence</code> may safely assumed to be a string. For example, "GATTACA" is a valid DNA sequence that should return <code>([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0],
[0, 0.5, 1, 1.5, 1, 0.5, 0, -0.5, -1, -0.5, -1, -1.5, -1, -0.5, -1])</code>.</p></li>
<li><p>By "long", I mean anywhere from thousands to billions. That being said, the most common use case likely will involve fewer than ten thousand characters, although this process may be done to thousands of such sequences. For context, I am currently running this function over 400,000 sequences with a median length of 800 characters.</p></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-29T07:38:58.623",
"Id": "390607",
"Score": "0",
"body": "Could you provide som example data? How long is \"very long\"? A thousand? A billion? Is sequence a string, or a list of characters? Can you use numpy in the rest of the program,... | [
{
"body": "<p>First of all I'd like to say that your code is fast. From studying it, the major bottlenecks that I've found come from the input being a string, and from converting to numpy arrays and back.</p>\n\n<p>Since what you're doing is a kind of cumulative sum with some alterations, I'd go with <code>nump... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-28T22:46:49.773",
"Id": "202700",
"Score": "6",
"Tags": [
"python",
"performance",
"numpy",
"bioinformatics"
],
"Title": "Mapping DNA nucleotides into two-dimensional coordinates"
} | 202700 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.