body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>We are using spring-batch to extract data from a SAP system, during processing we pass the extracted full texts to a tagging service, in the end the enriched documents are stored in Solr to be served to the user.</p>
<p>The problem during this ETL chain is that the tagging service is slow. Unfortunately we cannot improve its performance problems as it is a bought vendor solution. The problem of this service is that it has a ramp-up time of 6 seconds for <em>each</em> request. It does offer a bulk interface to tackle this. So we can send 1 item for tagging or 5.000 items. Each request will take 6 seconds. Hence we would like to send the texts as bulk during processing.</p>
<p>This is where our review request comes into play.</p>
<p>As far as we understood spring-batch <a href="https://docs.spring.io/spring-batch/trunk/reference/html/readersAndWriters.html#itemProcessor" rel="nofollow noreferrer">processors</a> perform their operation on single records, not batches. Hence we have a problem, as we need to process 8 Million records.</p>
<p>I have setup <a href="https://github.com/cheffe/slowprocessor/tree/87e41d83d1ca9baf63835c89487e5c8fa22388ea" rel="nofollow noreferrer">a project on github</a> to illustrate the problem and our approach so far. To start the batch processing use the <code>SlowProcessorApplicationTests</code>.</p>
<p>The reader is a <code>FlatFileItemReader</code> as the sample data is included as CSV within the project</p>
<pre class="lang-java prettyprint-override"><code>@Bean
public FlatFileItemReader<InputItem> inputItemReader() {
return new FlatFileItemReaderBuilder<InputItem>()
.name("inputItemReader")
.resource(new ClassPathResource("input.csv"))
.linesToSkip(1)
.delimited()
.delimiter(";")
.names(new String[]{
"id",
"title",
"text"})
.fieldSetMapper(new BeanWrapperFieldSetMapper<InputItem>() {{
setTargetType(InputItem.class);
}})
.build();
}
</code></pre>
<p>The <code>ItemProcessor</code> is straight forward, but here is where the problem is. The call to <code>taggingService.analyze(...)</code> takes 6 seconds, each time.</p>
<pre class="lang-java prettyprint-override"><code>@Slf4j
@Component
public class CSVItemProcessor implements ItemProcessor<InputItem, OutputItem> {
@Autowired
private TaggingService taggingService;
@Override
public OutputItem process(InputItem inItem) throws InterruptedException {
log.trace("process {}", inItem);
OutputItem outItem = new OutputItem();
outItem.setId(inItem.getId());
outItem.setTitle(inItem.getTitle());
List<TaggingResponse> responses = taggingService.analyze(inItem.getText());
TaggingResponse response = responses.get(0);
outItem.setTags(response.getTags());
outItem.setWords(response.getWords());
return outItem;
}
}
</code></pre>
<p>The <code>Job</code> and its only <code>Step</code> are also quite simple:</p>
<pre class="lang-java prettyprint-override"><code>@Bean
public Job loadCSV(Step handleCSV) {
return jobBuilder.get("loadCSV")
.incrementer(new RunIdIncrementer())
.start(handleCSV)
.build();
}
@Bean
public Step handleCSV(
FlatFileItemReader<InputItem> inputItemReader,
CSVItemProcessor itemProcessor) {
return stepFactory.get("handleCSV")
.<InputItem, OutputItem>chunk(2)
.reader(inputItemReader)
.processor(itemProcessor)
.writer((ItemWriter<Object>) items -> log.debug("writing {} items", items.size()))
.build();
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T09:22:22.127",
"Id": "208434",
"Score": "1",
"Tags": [
"java",
"performance",
"csv",
"spring",
"etl"
],
"Title": "Handling slow processing the Spring batch way"
} | 208434 |
<p>I'd like to find the best way to format date to <strong>YYYY</strong>, <strong>YYYYMM</strong> or <strong>YYYYMMDD</strong>.<br>
Here is what I've got so far:</p>
<pre><code># gets the position of a character in the format
def get_pos(format, letter, number):
it_number = 0
it_pos = 0
for char in format:
if char == letter:
it_number += 1
if it_number == number:
return(it_pos)
it_pos += 1
return(-1)
# loops through all the characters forming a number
def format_loop(string, old_format, letter):
new = ''
pos = -2
it = 1
while(pos != -1):
pos = get_pos(old_format, letter, it)
if(pos >= 0):
new += string[pos]
it += 1
return(new)
# format a date
def date_format(string, old_format, new_format, delim):
new = format_loop(string, old_format, 'Y')
if(new_format in 'MD'):
new += delim + format_loop(string, old_format, 'M')
if(new_format == 'D'):
new += delim + format_loop(string, old_format, 'D')
return(new)
</code></pre>
<p>The function's intake parameters are, in order, the date string to format, its current format, the desired format in the form of 'Y', 'M' or 'D' and an optional delimiter to put in between the numbers.</p>
<p>I'm open for suggestions on shortening and optimising the code as well as on coding style and variables/functions naming.</p>
| [] | [
{
"body": "<p>For the first loop, there is a neat little function called <code>enumerate()</code> which allows you to iterate through an object and access both the element and the iteration number.</p>\n\n<p>You can also remove various parenthesis, for the <code>return</code>ed value and also for the <code>while</code> loop (although for big conditions it's handy to keep the parenthesis sometimes).</p>\n\n<pre><code>def get_pos(format, letter, number):\n it_number = 0\n # it_pos = 0 <--- not needed anymore because of the\n for it_pos, char in enumerate(format): # <--- enumerate\n if char == letter:\n it_number += 1\n if it_number == number:\n return it_pos\n # it_pos += 1 <--- same thing here\n return -1\n</code></pre>\n\n<p>For the second function I would suggest to use <code>while True</code> and <code>break</code> so that you don't have to declare <code>pos=-2</code> beforehand. </p>\n\n<pre><code>def format_loop(string, old_format, letter):\n new = ''\n # pos = -2 <--- replaced by a break\n it = 1\n while True:\n pos = get_pos(old_format, letter, it)\n if pos == -1:\n break\n elif pos >= 0:\n new += string[pos]\n it += 1\n return new\n</code></pre>\n\n<p>Also, I don't know if there is an official recommendation on that, but I like to use very explicit return values for special cases, for example the string <code>\"not found\"</code> instead of <code>-1</code>. That makes the code more English than Python when you read <code>if pos==\"not found\": break</code> and I rather like that. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T13:14:09.700",
"Id": "402563",
"Score": "0",
"body": "Well first I have to state that `enumerate()` is too good to be true, gonna use it everywhere. I'm not sure for the second modification as it would bring an action in the loop possibly making it slower"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T13:19:57.547",
"Id": "402565",
"Score": "0",
"body": "Yes `enumerate` is really helpful. Just remember the formulation is `for <iteration count>, <element> in enumerate(<iterable>):` (sometimes I tend to reverse them). Regarding your second remark, I'll time it and come back to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T13:29:48.750",
"Id": "402567",
"Score": "1",
"body": "No difference for me (4.5µs to perform date_format). I would add a default delimiter `delim=''` just in case is lazy to specify it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T13:01:49.473",
"Id": "208444",
"ParentId": "208436",
"Score": "1"
}
},
{
"body": "<p>When parsing and manipulating dates (or times), you should use the <a href=\"https://docs.python.org/3/library/datetime.html#module-datetime\" rel=\"nofollow noreferrer\"><code>datetime</code></a> module.</p>\n\n<p>It supports both <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime\" rel=\"nofollow noreferrer\">parsing strings with a given format</a> and <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime\" rel=\"nofollow noreferrer\">formatting <code>datetime</code> objects with another given format</a>. The only thing it doesn't support is adding a delimiter between numbers:</p>\n\n<pre><code>import datetime\n\ndef date_format(string, old_format, new_format):\n return datetime.strptime(string, old_format).strftime(new_format)\n</code></pre>\n\n<p>Note that the formats have to comply with <a href=\"https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior\" rel=\"nofollow noreferrer\"><code>datetime</code>s format specifiers</a>. In particular that means that instead of <code>\"YYYY\"</code>, <code>\"YYYYMM\"</code> and <code>\"YYYYMMDD\"</code> you would have to use <code>\"%Y\"</code>, <code>\"%Y%m\"</code> and <code>\"%Y%m%d\"</code>, respectively. These format specifiers are not arbitrary, they mostly resemble the ones supported by the corresponding C library (which has existed for quite some time).</p>\n\n<p>So, unless you <em>really</em> need that delimiter, I would use this, because it is vastly simpler and a lot easier to understand (especially by someone else). Even if you need the delimiter, it is probably easier to manipulate the output of this function to include it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:40:11.773",
"Id": "208521",
"ParentId": "208436",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208521",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T10:22:36.207",
"Id": "208436",
"Score": "2",
"Tags": [
"python",
"datetime"
],
"Title": "Python date formatter"
} | 208436 |
<p>I am no newcomer to Java. One thing that confounds me is why it is so messy to load values from .properties files.</p>
<p>I have an application where, if the .properties file is found, then the value if found, should be used. And in any other circumstance, to use the default. (In the correct deployment, the server is run with sufficient permissions to engage with the socket listener 443, whereas in the development environment or any other environment where a person goes to the trouble to insert the .properties file, another port will be used).</p>
<p>The location of the file is <code>com/foo/bar/webserver.properties</code> in the in the same directory as the class file <code>com/foo/bar/WebServer.class</code>.</p>
<p>The content of <code>webserver.properties</code> is simply:</p>
<pre><code> listen=4444
</code></pre>
<p>Since this such a terribly simple function I would like to know if the community of reviewers sees a more elegant/succinct/secure/complete/correct way to load the value. I feel like I must be overlooking something basic for what feels like, to me, should be a one-liner more like the imaginary API:</p>
<pre><code> // set int value for key "listen", or else default value 443
int port = Properties.loadProperties( "webserver.properties" ).getInt( "listen", 443 );
</code></pre>
<p>And here is my real code for review:</p>
<pre><code> int port;
try ( InputStream webserverProperties = WebServer.class.getResourceAsStream( "webserver.properties" ) ) {
if ( webserverProperties == null ) {
port = 443;
} else {
Properties p = new Properties();
p.load( webserverProperties );
String listen = p.getProperty( "listen", "443" );
port = Integer.parseInt( listen );
}
}
catch ( NumberFormatException e ) { port = 443; }
finally {}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T15:39:00.347",
"Id": "402590",
"Score": "0",
"body": "Have you consider using xml de/serializing to load and save the properties?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T16:02:26.670",
"Id": "402596",
"Score": "2",
"body": "Java's `Properties` class is old, and it shows. It's also designed specifically to work only with `String` values. It sounds like it's not a great choice for the problem you've got. You might want to consider using a different abstraction or writing your own. It shouldn't be that hard to compose a `Properties` instance into the fluent API you're describing as your ideal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T16:47:53.020",
"Id": "402601",
"Score": "0",
"body": "@tinstaafl, no I did not, because I am reading a single int value. I fail to see how that would simplify the operation, but I am happy to learn something from your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T17:11:47.373",
"Id": "402606",
"Score": "0",
"body": "I realize your code only loads one property value. However your title indicates you may want to load more than one. It seems to in that case de/serializing would be more efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T17:18:15.830",
"Id": "402611",
"Score": "0",
"body": "I think if I had many properties to read, I would write a Properties intermediary class with methods that would look very much like my code sample. And then, I think it would be appropriate. But, to only read a single int I think 12 lines of code is dubious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T18:21:28.200",
"Id": "402618",
"Score": "0",
"body": "The norm for this site is for question titles to state the task accomplished by the code, rather than how you seek to improve the code. Desires such as \"elegance\" are implied for all questions here, and do not need to be mentioned. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T19:22:41.530",
"Id": "402630",
"Score": "0",
"body": "@200_success many thanks. I improved the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T05:44:05.573",
"Id": "402678",
"Score": "0",
"body": "well it migh be a bit plain, but if you really really have only one parameter have you tried passing that value via startup arguments?"
}
] | [
{
"body": "<p>you could at least get rid of the <code>if</code> by combining the exceptions:</p>\n\n<pre><code>int port;\ntry ( InputStream webserverProperties = WebServer.class.getResourceAsStream( \"webserver.properties\" ) ) {\n Properties p = new Properties();\n p.load( webserverProperties );\n String listen = p.getProperty( \"listen\", \"443\" );\n port = Integer.parseInt( listen );\n}\ncatch ( NumberFormatException|NullPointerException e ) { port = 443; }\nfinally {}\n</code></pre>\n\n<p>or ignore exceptions at all:</p>\n\n<pre><code>int port= 443;\ntry ( InputStream webserverProperties = WebServer.class.getResourceAsStream( \"webserver.properties\" ) ) {\n Properties p = new Properties();\n p.load( webserverProperties );\n String listen = p.getProperty( \"listen\", \"443\" );\n port = Integer.parseInt( listen );\n}\ncatch ( Exception e ) {}\nfinally {}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:02:08.950",
"Id": "402903",
"Score": "0",
"body": "Yes, I think the second option is good, and in fact in this case the empty finally{} block can also be omitted. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T21:19:09.850",
"Id": "208574",
"ParentId": "208445",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208574",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T13:14:36.133",
"Id": "208445",
"Score": "3",
"Tags": [
"java",
"beginner",
"configuration",
"properties"
],
"Title": "Read a single int from an optional .properties file"
} | 208445 |
<p>I've been using Monogame for hobby game development for the last year now. My game assets aren't large so I usually load them all on startup.</p>
<p>I would have a static AssetManager class with a <code>public static Load(ContentManager content);</code> method. Assets would be loaded and stored in multiple Dictionaries like so:</p>
<pre class="lang-cs prettyprint-override"><code>private static void Dictionary<string, Spritesheet> _spritesheets = new Dictionary<string, Spritsheet>();
private static void Dictionary<string, Sprite> _sprites = new Dictionary<string, Sprite>();
private static void Dictionary<string, Tile> _tiles = new Dictionary<string, Tile>();
</code></pre>
<p>I would have multiple different methods to help with adding and getting assets. After a while, my AssetManager class starts to get rather large. </p>
<p>So to help maintain and easily access assets, I decided to create an AssetCache (to store assets of a specific type) and CacheManager (to manage the different asset caches). I use generic methods to get specific AssetCaches in the CacheManager. </p>
<p><strong>AssetCache.cs</strong><br>
This class stores assets of a specific type using a specific key. It contains various getters and setters.</p>
<p>For example, an asset cache that stores <code>Tile</code> objects using a <code>string</code> as a key: <code>new AssetCache<string, Tile>();</code></p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
namespace Project.Assets.Cache
{
/// <summary>
/// Stores multiple instances of the same data type.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TAsset"></typeparam>
public class AssetCache<TKey, TAsset> : ICache where TKey : IEquatable<TKey>
{
private readonly Dictionary<TKey, TAsset> _cache = new Dictionary<TKey, TAsset>();
/// <summary>
/// The amount of items stored in the cache.
/// </summary>
public int Count => _cache.Count;
/// <summary>
/// Whether or not the cache is empty.
/// </summary>
public bool IsEmpty => Count == 0;
/// <summary>
/// Check's if an asset with a specific name exists in the cache.
/// </summary>
/// <param name="key">The asset key.</param>
/// <returns>Whether or not the asset exists.</returns>
public bool Has(TKey key) => _cache.ContainsKey(key);
/// <summary>
/// Gets and sets an asset with a specific key.
/// </summary>
/// <param name="key">The asset key.</param>
/// <returns>An asset instance, if found.</returns>
/// <exception cref="KeyNotFoundException">Thrown if the asset key does not exist
/// in the cache.</exception>
/// <exception cref="InvalidOperationException">Thrown if the asset key is
/// already in use.</exception>
public TAsset this[TKey key]
{
get => Get(key);
set => Add(key, value);
}
/// <summary>
/// Gets an asset instance from the cache.
/// </summary>
/// <param name="key">The asset key.</param>
/// <returns>The asset instance.</returns>
/// <exception cref="KeyNotFoundException">Thrown if the asset key does not exist
/// in the cache.</exception>
public TAsset Get(TKey key)
{
if (!Has(key))
{
throw new KeyNotFoundException($"Cache item '{key}' not found.");
}
return _cache[key];
}
/// <summary>
/// Adds an asset to the cache.
/// </summary>
/// <param name="key">The asset key.</param>
/// <param name="asset">The asset instance to add.</param>
/// <exception cref="InvalidOperationException">Thrown if the key is already
/// in use.</exception>
public void Add(TKey key, TAsset asset)
{
if (Has(key))
{
throw new InvalidOperationException($"Cannot add asset as '{key}'. Key already exists.");
}
_cache.Add(key, asset);
}
/// <summary>
/// RemoveAsset a specific asset from the cache.
/// </summary>
/// <param name="key">The asset key to remove.</param>
/// <returns>Whether or not the asset was removed.</returns>
public bool Remove(TKey key)
{
return _cache.Remove(key);
}
/// <summary>
/// Clears all assets from the cache.
/// </summary>
public void Clear()
{
_cache.Clear();
}
}
}
</code></pre>
<p><strong>ICache.cs</strong><br>
The ICache interface is implemented by the AssetCache class above, is used by the CacheManager so I can store multiple AssetCache objects with different generic types in the same dictionary.</p>
<pre class="lang-cs prettyprint-override"><code>namespace Project.Assets.Cache
{
public interface ICache
{
void Clear();
}
}
</code></pre>
<p><strong>CacheManager.cs</strong><br>
The generic parameter of this class represents the key type that will be used when storing assets. This means I can use things like <code>int</code>'s, <code>string</code>'s or even custom structs like <code>Point2D</code> if I really wanted to.</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
namespace Project.Assets.Cache
{
/// <summary>
/// Stores multiple <see cref="AssetCache{TKey,TValue}"/> instances. All cache's use the
/// same key type, which must implement <see cref="IEquatable{T}"/>.
/// </summary>
/// <typeparam name="TKey"></typeparam>
public sealed class CacheManager<TKey> where TKey : IEquatable<TKey>
{
private readonly Dictionary<Type, ICache> _caches = new Dictionary<Type, ICache>();
/// <summary>
/// Count the amount of assets in a specific asset cache.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to check.</typeparam>
/// <returns>The amount of assets.</returns>
/// <exception cref="KeyNotFoundException">Thrown if the asset cache type does
/// not exist.</exception>
public int Count<TAsset>() => GetCache<TAsset>().Count;
/// <summary>
/// Check if an asset cache of a specific type is empty or not.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to check.</typeparam>
/// <returns>Whether or not the asset cache is empty.</returns>
/// <exception cref="KeyNotFoundException">Thrown if the asset cache type does
/// not exist.</exception>
public bool IsEmpty<TAsset>() => GetCache<TAsset>().IsEmpty;
/// <summary>
/// Check if a specific asset exists in a specific asset cache.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to look for.</typeparam>
/// <param name="key">The key of the asset to look for.</param>
/// <returns>Whether or not the asset exists or not.</returns>
/// <exception cref="KeyNotFoundException">Thrown if the asset cache type does
/// not exist.</exception>
public bool Has<TAsset>(TKey key) => GetCache<TAsset>().Has(key);
/// <summary>
/// Clear an asset cache of a specific type.
/// </summary>
/// <typeparam name="TAsset"></typeparam>
/// <exception cref="KeyNotFoundException">Thrown if the asset cache type does
/// not exist.</exception>
public void Clear<TAsset>() => GetCache<TAsset>().Clear();
/// <summary>
/// GetAsset a specific asset from a specified asset cache.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to use.</typeparam>
/// <param name="assetKey">The key of the asset to search for.</param>
/// <returns>The asset instance.</returns>
/// <exception cref="KeyNotFoundException">Thrown if the asset cache type does
/// not exist.</exception>
public TAsset GetAsset<TAsset>(TKey assetKey)
{
return GetCache<TAsset>().Get(assetKey);
}
/// <summary>
/// AddAsset a new asset to an asset cache. If the cache does not exist, it is created.
/// </summary>
/// <typeparam name="TAsset">The type of asset to add.</typeparam>
/// <param name="key">The key of the asset.</param>
/// <param name="asset">The asset to add.</param>
/// <exception cref="InvalidOperationException">Thrown if the key is already
/// in use.</exception>
public void AddAsset<TAsset>(TKey key, TAsset asset)
{
if (!TryGetCache(out AssetCache<TKey, TAsset> cache))
{
cache = AddCache<TAsset>();
}
cache.Add(key, asset);
}
/// <summary>
/// Removes an asset from a specified asset cache.
/// </summary>
/// <typeparam name="TAsset">The type of asset to remove.</typeparam>
/// <param name="key">The key of the asset to remove.</param>
/// <returns>Whether or not the asset was removed from the cache.</returns>
/// <exception cref="KeyNotFoundException">Thrown if the asset cache type does
/// not exist.</exception>
public bool RemoveAsset<TAsset>( TKey key)
{
return GetCache<TAsset>().Remove(key);
}
/// <summary>
/// Removes all assets from all caches.
/// </summary>
public void ClearAll()
{
foreach (ICache cache in _caches.Values)
{
cache.Clear();
}
}
/// <summary>
/// Adds a new <see cref="AssetCache{TKey,TValue}"/>. An exception is thrown if a cache
/// already exists with the same asset type.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to add.</typeparam>
/// <returns>The created asset cache.</returns>
/// <exception cref="InvalidOperationException">Thrown if an asset cache with the same type
/// already exists.</exception>
private AssetCache<TKey, TAsset> AddCache<TAsset>()
{
Type cacheType = typeof(TAsset);
if (_caches.ContainsKey(cacheType))
{
throw new InvalidOperationException($"Asset cache '{cacheType.Name}' already exists.");
}
var cache = new AssetCache<TKey, TAsset>();
_caches.Add(cacheType, cache);
return cache;
}
/// <summary>
/// Try and get an asset cache based on the methods generic type.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to search for.</typeparam>
/// <param name="cache">When the method returns, contains the cache associated with the
/// generic type, if the cache is found; otherwise, null is passed.</param>
/// <returns>Whether or not the asset cache was found.</returns>
public bool TryGetCache<TAsset>(out AssetCache<TKey, TAsset> cache)
{
if (!_caches.TryGetValue(typeof(TAsset), out ICache cacheFound))
{
cache = null;
return false;
}
cache = cacheFound as AssetCache<TKey, TAsset>;
return true;
}
/// <summary>
/// Gets an asset cache based on the methods generic type. An exception is thrown if the cache
/// is not found.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to search for.</typeparam>
/// <returns>The found asset cache.</returns>
/// <exception cref="CacheNotFoundException">Thrown if the asset cache cannot be found.</exception>
public AssetCache<TKey, TAsset> GetCache<TAsset>()
{
if (!TryGetCache(out AssetCache<TKey, TAsset> cache))
{
throw new CacheNotFoundException($"Asset cache for type '{typeof(TAsset).Name}' not found.");
}
return cache;
}
/// <summary>
/// Remove an asset cache of a specific type.
/// </summary>
/// <typeparam name="TAsset">The type of asset cache to remove.</typeparam>
/// <returns>Whether or not the asset cache was removed.</returns>
public bool RemoveCache<TAsset>()
{
return _caches.Remove( typeof( TAsset ) );
}
}
}
</code></pre>
<p>Usage is like so:</p>
<pre class="lang-cs prettyprint-override"><code>private static readonly CacheManager<string> _cache = new CacheManager<string>();
public static void Load()
{
_cache.AddAsset("floor", new Tile(0, "tile", new Character('#', Color.White), true));
Tile floor = _cache.GetAsset<Tile>( "floor" );
// Throws KeyNotFoundException
_cache.GetAsset<Tile>( "door" );
// Throws InvalidOperationException
_cache.AddAsset("floor", new Tile(0, null, null, true) );
// No exception, return true
bool removed = _cache.RemoveAsset<Tile>( "floor" );
// No exception, return false
bool removedCache = _cache.RemoveCache<Entity>();
// Throws CacheNotFoundException
_cache.GetAsset<Entity>( "monster" );
}
</code></pre>
<p>I'm throwing exceptions when trying to add or get an asset that doesn't exist in an AssetCache or when an AssetCache of a specific type does not exist.</p>
<p>When removing, I return a bool, whether the asset was actually removed or not.</p>
<p>The idea being if you are trying to get an asset that doesn't exist, something has gone wrong. Either you haven't added the asset, or the name is spelled wrong.</p>
<p>I don't think using the word "Cache" is appropriate in this case, seeing as assets aren't removed after X amount of time. Perhaps "Store" might be better.</p>
| [] | [
{
"body": "<p>I strongly dislike your <code>AssetCache</code> type. You are literally wrapping a dictionary. The only difference is the type of the exception you are throwing when adding an existing item. Just use a plain old <code>Dictionary<TKey, TAsset></code> directly.</p>\n\n<p>Your <code>ICache</code> interface is also incomplete. Of what use is an interface that lets you destroy data without being able to create it? You should either have an interface that is create-only so you can segment the code by duty and only expose parts of it to certain callers, or you should add the create methods do this interface. Don't go half-way on your interface use. Either use them or don't. If you do this, you won't need to return an <code>AssetCache</code> in the following method, but just an <code>ICache</code>.</p>\n\n<blockquote>\n<pre><code>public bool TryGetCache<TAsset>(out AssetCache<TKey, TAsset> cache)\n{\n if (!_caches.TryGetValue(typeof(TAsset), out ICache cacheFound))\n {\n cache = null;\n return false;\n }\n\n cache = cacheFound as AssetCache<TKey, TAsset>;\n return true;\n}\n</code></pre>\n</blockquote>\n\n<p>And finally, I'm a trifle concerned about those massive doc comments. They hide the code, and they are almost certain to get out of date as your code changes. I'm not saying to remove them, but with code this simple, I wouldn't have added them. And be careful to never update the methods without updating the doc comments too. For example, how does the following doc comment explain anything better than its accompanying code?</p>\n\n<blockquote>\n<pre><code>/// <summary>\n/// Gets an asset cache based on the methods generic type. An exception is thrown if the cache\n/// is not found.\n/// </summary>\n/// <typeparam name=\"TAsset\">The type of asset cache to search for.</typeparam>\n/// <returns>The found asset cache.</returns>\n/// <exception cref=\"CacheNotFoundException\">Thrown if the asset cache cannot be found.</exception>\npublic AssetCache<TKey, TAsset> GetCache<TAsset>()\n{\n if (!TryGetCache(out AssetCache<TKey, TAsset> cache))\n {\n throw new CacheNotFoundException($\"Asset cache for type '{typeof(TAsset).Name}' not found.\");\n }\n\n return cache;\n}\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T09:00:24.413",
"Id": "402687",
"Score": "0",
"body": "Thanks for the answer! I'm thinking I could remove the ICache interface and AssetCache class. Inside the CacheManager class I could use a `Dictionary<Type, Dictionary<TKey, object>>`. I can still keep methods like `TAsset GetAsset<TAsset>(TKey key)`, I just cast the found asset to the `TAsset` type. I see what you mean about the comments. I find it hard to write useful documentation without repeating myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T14:37:56.507",
"Id": "402735",
"Score": "2",
"body": "I want to chime in favor of the documentation comments, especially the `<summary>` tags. Getting a written-english description of a function's purpose and behavior just by mousing over its name is _valuable now_, even when the function is short and well-named. Plus, the broader but weaker \"_valuable someday_\" argument: Making these comments complete is a good habit to get into anyway, because it's feasible the code could be distributed as a .dll without source, but with documentation auto-generated from these comments."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T16:02:39.737",
"Id": "208456",
"ParentId": "208446",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "208456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T13:22:49.150",
"Id": "208446",
"Score": "5",
"Tags": [
"c#",
"game",
"generics",
"exception"
],
"Title": "Game asset manager"
} | 208446 |
<p>This is the beginning of my program that calculates simple interest. Interest rate will have the following format : 0.97 , 0.67 , 0.17 etc. They won't be bigger than 1. So if the user enter 9 for the interest, program will convert it to 0.09 (by dividing it by 100) . Also user can enter input using '/'. So program will convert input like 97/100 to 0.97.</p>
<p>I wrote the code below. It works but it seems to me that there might be a easier and more elegant solution to this. Maybe using more build-in functions etc. If you help me with that I would be very appreciated.</p>
<pre><code>def toNum(interest):
if '/' not in interest:
if float(interest) > 1:
return float(interest)/100
else:
return float(interest)
else:
l= []
n = 0
count = 1
list_interest=[]
for e in interest:
list_interest.append(e)
for e in list_interest:
if count == 1 or count == 3:
l.append(e)
count = count +1
continue
if e == '/':
n = n + 1
count = count +1
else:
l[n] = l[n] + e
return int(l[0]) / int(l[1])
interest = input("Interest rate: ")
interest = toNum(interest)
print(interest)
</code></pre>
| [] | [
{
"body": "<p>For reading a fraction such as \"97/100\", you can use the <code>fractions</code> library.</p>\n\n<p>For example:</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>from fractions import Fraction\n\nf = Fraction(\"97/100\")\n\nprint(float(f)) # prints 0.97\n</code></pre>\n\n<p>And because the constructor also takes a float, we can remove the check for <code>/</code>. Therefore, the final code is:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from fractions import Fraction\n\ndef toNum(interest):\n f = Fraction(interest)\n f = float(f)\n\n if f > 1:\n f /= 100\n\n return f\n\nprint(toNum(\"97/100\")) # prints 0.97\nprint(toNum(0.97)) # prints 0.97\nprint(toNum(9)) # prints 0.09\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T15:59:12.410",
"Id": "402595",
"Score": "1",
"body": "Why convert to `float` at all and not keep a `fractions.Fraction` object all along?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T16:14:56.233",
"Id": "402600",
"Score": "0",
"body": "@MathiasEttinger That's also a good option, just depends on preference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T14:11:51.340",
"Id": "208449",
"ParentId": "208448",
"Score": "4"
}
},
{
"body": "<p>While the <a href=\"https://codereview.stackexchange.com/a/208449/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/118395/esote\">@esote</a> is correct and I would also recommend using the <code>fractions</code> module, you should also work on your text parsing. In this case you could have used a simple <a href=\"https://www.pythonforbeginners.com/dictionary/python-split\" rel=\"nofollow noreferrer\"><code>str.split</code></a> and <a href=\"http://book.pythontips.com/en/latest/map_filter.html\" rel=\"nofollow noreferrer\"><code>map</code></a> to parse the string containing a <code>/</code>:</p>\n\n<pre><code>if \"/\" in interest:\n numerator, denominator = map(int, interest.split(\"/\"))\n return numerator / denominator\n</code></pre>\n\n<p>Note that <code>int</code> ignores whitespace, so this works with both <code>\"97/100\"</code>, <code>\"97 / 100\"</code> and any combination thereof.</p>\n\n<p>Note also that using sensible names makes it immediately obvious what this code does.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:27:36.693",
"Id": "208519",
"ParentId": "208448",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208449",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T13:51:15.273",
"Id": "208448",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Converting input containing special character to float"
} | 208448 |
<p>I am creating my first WP/WooCommerce plugin. I was following instructions from <a href="https://codex.wordpress.org/Writing_a_Plugin" rel="nofollow noreferrer">WordPress Codex</a> during development, but I wanted to review it here, to make sure I am on the right path. First things I would like to get reviewed are plugin-name.php file and plugin file/folders structure.</p>
<p>Questions/doubts:</p>
<ul>
<li>I was using singleton classes. Is that ok?</li>
<li>Did I miss something in plugin-name.php file? Is everything needed there?</li>
<li>Is order of code OK in plugin-name.php file? Are <code>if</code> statements OK?</li>
<li>About project folder and files structure, is it ok to put my global.css and functions.php in the root of the plugin, along with plugin-name.php file, or should I move them into folder(s)? If yes, how should I name those folders?</li>
<li>If there is something that should be different beside these things I mentioned above, please let me know.</li>
</ul>
<p><strong>plugin-name.php file:</strong> </p>
<pre><code><?php
/**
* Plugin Name: {Plugin name}
* Plugin URI: https://github.com/tahireu/{plugin_name}
* Description: {Description}
* Version: 1.0.0
* Author: Tahireu
* Author URI: https://github.com/tahireu/
* License: GPL
* License URI: http://www.opensource.org/licenses/gpl-license.php
*/
/*
* Prevent intruders from sneaking around
* */
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
/*
* Variables
* */
const {PLUGIN_NAME}_TEXT_DOMAIN = "wc-{plugin-name}";
/*
* Load {PLUGIN_NAME}_Activator class before WooCommerce check
* */
require plugin_dir_path( __FILE__ ) . 'includes/class-{plugin_name}-activator.php';
/*
* Check if WooCommerce is installed and active
* */
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
/*
* Current plugin version - https://semver.org
* This should be updated as new versions are released
* */
define( 'WC_{PLUGIN_NAME}_VERSION', '1.0.0' );
/*
* Load functions and classes
* */
require plugin_dir_path( __FILE__ ) . 'functions.php';
require plugin_dir_path( __FILE__ ) . 'admin/class-{plugin-name}-admin.php';
require plugin_dir_path( __FILE__ ) . 'public/class-{plugin-name}-public.php';
/*
* Create database table on plugin activation
* */
function create_table(){
{PLUGIN_NAME}_activator::create_{plugin-name}_table();
}
register_activation_hook( __FILE__, 'create_table' );
/*
* Do the work
* */
{PLUGIN_NAME}_admin::on_load();
{PLUGIN_NAME}_public::on_load();
} else {
/*
* Abort and display info message
* */
{PLUGIN_NAME}_activator::abort();
}
</code></pre>
<p><strong>Plugin files/folders structure:</strong></p>
<p><a href="https://i.stack.imgur.com/UAm9v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UAm9v.png" alt="enter image description here"></a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T15:10:59.420",
"Id": "208452",
"Score": "1",
"Tags": [
"php",
"plugin",
"wordpress"
],
"Title": "WordPress plugin development - plugin-name.php file and plugin files/folders structure"
} | 208452 |
<p>I'm making a CLI app for myself for tracking my budget. How can I improve this code?</p>
<pre><code>#!/usr/bin/python3
def t_lines():
import os
terminal_size = os.get_terminal_size()
print("-" * terminal_size.columns)
def main():
import sqlite3 as sql
conn = sql.connect("expenses.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS expenses \
(Date TEXT DEFAULT \"x\", \
item TEXT DEFAULT \"x\", \
category TEXT DEFAULT \"x\", \
Price REAL DEFAULT 0, \
Type TEXT DEFAULT \"e\")" )
t_lines()
print("Enter in the following format")
print("Enter 0 to quit")
print("Date (dd/mmm/yy), Item, Category, Price, Type ([e]xpense/[i]ncome)")
print("Example:")
print("12/nov/18, carrot, vegetable, 15.64, e")
print("13/aug/18, salary, work, 10000, income")
t_lines()
user_input = input()
# the vals below seems unnecessary
# vals = user_input.split(',')
while user_input != "0":
vals = user_input.split(',')
if len(vals) != 5:
print("Enter correctly")
else:
cur.execute("INSERT INTO expenses \
VALUES (?, ?, ?, ?, ?)", vals)
conn.commit()
user_input = input()
conn.close()
if __name__ == '__main__':
main()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T15:35:45.540",
"Id": "208454",
"Score": "2",
"Tags": [
"python",
"sqlite"
],
"Title": "Python CLI app for tracking budget"
} | 208454 |
<p>Sometimes I need to call <code>async</code> code from a synchronous method. This leads to repetition in code to wait for the task to complete, then ensure that the expected exception is thrown instead of an aggregate exception (assuming there's only 1 exception returned, as is the case unless we're iterating through a list / something like that; in which case we preserve the <code>AggregateException</code> as that's then expected by the handling code).</p>
<p>To avoid repetition, would a helper function called and defined as below be appropriate? Does something like this already exist in the framework?</p>
<p>Example calling code:</p>
<pre><code>bool MySyncMethod (bool throwException)
{
var task = MyAsyncMethod(throwException);
return task.WaitResultUnwrapException<bool>();
//or even
//return MyAsyncMethod(throwException).WaitResultUnwrapException<bool>();
}
async Task<bool> MyAsyncMethod (bool throwException)
{
if (throwException)
throw new ArgumentException(nameof(throwException));
return await Task.Run(() => true);
}
</code></pre>
<p>Example extension method:</p>
<pre><code>using System;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
namespace MyCompany.Threading.Tasks
{
public static class TaskExtensions
{
public static T WaitResultUnwrapException<T>(this Task<T> task)
{
if (task == null) throw new ArgumentNullException(nameof(task));
try
{
task.Wait();
return task.Result;
}
catch (AggregateException es)
{
if (es.InnerExceptions.Count == 1) {
var e = es.InnerExceptions[0];
ExceptionDispatchInfo.Capture(e).Throw();
}
throw;
}
}
public static void WaitResultUnwrapException(this Task task)
{
if (task == null) throw new ArgumentNullException(nameof(task));
try
{
task.Wait();
}
catch (AggregateException es)
{
if (es.InnerExceptions.Count == 1) {
var e = es.InnerExceptions[0];
ExceptionDispatchInfo.Capture(e).Throw();
}
throw;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T17:20:54.617",
"Id": "402612",
"Score": "0",
"body": "ps. After posting I just thought that we may be iterating a list / with catch logic defined to build an aggregate exception, but only have 1 exception returned; in which case the exception type would differ from expected... Therefore I'd likely change the above to add a `preserveAggegateException` parameter to avoid unwrapping aggregates where they're expected. `if (!preserveAggegateException && es.InnerExceptions.Count == 1)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T17:25:58.647",
"Id": "402613",
"Score": "4",
"body": "mhmm... I think this is not necessary as `task.GetAwaiter().GetResult()` will also unwrap the exception with much less code, see [this](https://stackoverflow.com/questions/17284517/is-task-result-the-same-as-getawaiter-getresult) on Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T17:31:28.077",
"Id": "402614",
"Score": "0",
"body": "Thanks; I'd not seen that approach; definitely makes sense / covers pretty much exactly what I've done above with less effort and the same caveat around moving you away from the benefits of being asynchronous. Thanks @t3chb0t."
}
] | [
{
"body": "<p>Per the comment by @t3chb0t, all I needed was this:</p>\n\n<pre><code>task.GetAwaiter().GetResult()\n</code></pre>\n\n<p>In context:</p>\n\n<pre><code>bool MySyncMethod (bool throwException)\n{\n return MyAsyncMethod(throwException).GetAwaiter().GetResult(); //this is the only line that's changed\n}\nasync Task<bool> MyAsyncMethod (bool throwException)\n{\n if (throwException)\n throw new ArgumentException(nameof(throwException));\n return await Task.Run(() => true);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T09:03:53.047",
"Id": "208505",
"ParentId": "208459",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208505",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T17:08:31.187",
"Id": "208459",
"Score": "2",
"Tags": [
"c#",
"error-handling",
"async-await"
],
"Title": "Extension method to run any async method synchronously"
} | 208459 |
<p>I made a B+Tree example for C++. I tested it a lot. I didn't get any errors or mistakes but i can't be sure it is really works (without any bug) or I don't know it is suitable for use (Memory problems, optimization etc.). I want your comments, test results and suggestions.</p>
<pre><code> /*
* C++ Program to Implement B+ Tree
*/
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <unistd.h>
using namespace std;
struct Student{
int number;
int failCount;
string name;
string surname;
string field;
};
struct less_than_key
{
inline bool operator() (const Student& struct1, const Student& struct2)
{
return (struct1.number < struct2.number);
}
};
const int numberofdatas = 4;
const int numberofkeys = numberofdatas+1;
struct BTreeNode
{
BTreeNode* parent;
vector<BTreeNode*> childLeafs;
vector<Student> datas;
BTreeNode(){
parent = NULL;
}
} * BTreeRoot = new BTreeNode;
void BTreeOpt(BTreeNode* tree){
if(!tree->childLeafs.empty()){
for(int i = 0; i < tree->childLeafs.size();i++){
tree->childLeafs[i]->parent = tree;
}
for(int i = 0; i < tree->childLeafs.size();i++){
BTreeOpt(tree->childLeafs[i]);
}
}
}
// Search in B+Tree and return last leaf
BTreeNode* BTreeSearch(BTreeNode* tree, int key){
BTreeOpt(BTreeRoot);
while(!tree->childLeafs.empty()){
if(key < tree->datas[0].number){
if(!tree->childLeafs.empty())
tree = tree->childLeafs[0];
}
if(tree->datas.size() > 1)
for(int i =0; i < tree->datas.size()-1; i++){
if(key >= tree->datas[i].number && key < tree->datas[i+1].number){
if(!tree->childLeafs.empty())
tree = tree->childLeafs[i+1];
}
}
if(key > tree->datas.back().number){
if(!tree->childLeafs.empty())
tree = tree->childLeafs[tree->datas.size()];
}
}
return tree;
}
void BTreeSplitT(BTreeNode* node){
BTreeNode * Parent, * Right = new BTreeNode, *Left = new BTreeNode;
// Control if node has Parent
if(node->parent != NULL){
Parent = node->parent;
}else{
Parent = new BTreeNode;
}
int middleInt = node->datas.size()/2;
Student middle = node->datas[middleInt];
// Load Left Node
for(int i=0; i< middleInt;i++){
Left->datas.push_back(node->datas[i]);
if(!node->childLeafs.empty()){
Left->childLeafs.push_back(node->childLeafs[i]);
}
}
// Load childLeafs
if(!node->childLeafs.empty()){
Left->childLeafs.push_back(node->childLeafs[middleInt]);
middleInt++;
Right->childLeafs.push_back(node->childLeafs[middleInt]);
}
// Load Right Node
for(int i=middleInt; i< node->datas.size();i++){
Right->datas.push_back(node->datas[i]);
if(!node->childLeafs.empty()){
Right->childLeafs.push_back(node->childLeafs[i+1]);
}
}
if(Parent->datas.empty()){
Parent->datas.push_back(middle);
Parent->childLeafs.push_back(Left);
Parent->childLeafs.push_back(Right);
Right->parent = Left->parent = Parent;
BTreeRoot = Parent;
}else{
int n = 0;
if(middle.number < Parent->datas[0].number){
n = 0;
}
for(int i =0; i < Parent->datas.size()-1; i++){
if(middle.number >= Parent->datas[i].number && middle.number < Parent->datas[i+1].number){
n = i+1;
}
}
if(middle.number > Parent->datas.back().number){
n = Parent->datas.size();
}
if(n == Parent->datas.size()){
Parent->childLeafs.pop_back();
Parent->datas.push_back(middle);
Parent->childLeafs.push_back(Left);
Parent->childLeafs.push_back(Right);
Left->parent = Right->parent = Parent;
}else{
Parent->datas.insert(Parent->datas.begin()+n, middle);
Parent->childLeafs.insert(Parent->childLeafs.begin()+n+1, Right);
Parent->childLeafs[n] = Left;
Left->parent = Right->parent = Parent;
}
if(Parent->datas.size() > numberofdatas){
BTreeSplitT(Parent);
}
}
}
// Insert to BTreeRoot
void BTreeInsert(Student student){
BTreeNode* temp = BTreeSearch(BTreeRoot, student.number);
temp->datas.push_back(student);
std::sort(temp->datas.begin(), temp->datas.end(), less_than_key());
if(temp->datas.size() >= numberofkeys){
BTreeSplitT(temp);
}
}
// Print B+Tree datas
void BTreePrint(BTreeNode* tree){
if(tree->childLeafs.size() != 0)
for(int i = 0; i < tree->childLeafs.size();i++){
BTreePrint(tree->childLeafs[i]);
}
if(tree->childLeafs.size() == 0)
for(int i = 0; i < tree->datas.size();i++){
cout << tree->datas[i].number << " -> ";
}
}
// Print B+Tree visual
void BTreePrint2(BTreeNode* tree){
for(int i = 0; i < tree->datas.size();i++){
cout << tree->datas[i].number << " -> ";
}
cout << endl;
if(tree->childLeafs.size() != 0)
for(int i = 0; i < tree->childLeafs.size();i++){
BTreePrint2(tree->childLeafs[i]);
}
}
int main()
{
Student ogr;
string line;
int no;
ifstream menuFile ("numbers.txt");
if (menuFile.is_open()){
while ( getline (menuFile,line) ){
std::istringstream os(line);
os >> no;
ogr.number = no;
printf("Adding: %d\n",no);
BTreeInsert(ogr);
BTreePrint2(BTreeRoot);
printf("---------------------------\n");
}
menuFile.close();
}
else cout << "Menu Dosyası Bulunamadı.";
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T01:54:40.557",
"Id": "402675",
"Score": "2",
"body": "Nitpicking: `data` is already plural (`datum` being singular)."
}
] | [
{
"body": "<p>Avoid <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std;</code></a>.</p>\n\n<p>You're not deleting any of the memory you allocate.</p>\n\n<p>The <code>operator()</code> in <code>less_than_key</code> is defined inline, so you can omit the <code>inline</code> keyword.</p>\n\n<p><code>BTreeRoot</code> is a global variable, which should be avoided. It would be better off being declared in <code>main</code> (where you use it), with all the <code>BTree</code> functions being members of <code>BTreeNode</code>. If you keep it as a global variable, declare it as the type (<code>BTreeNode BTreeRoot</code>), rather than as a pointer that you immediately allocate.</p>\n\n<p>Instead of <code>tree->childLeafs.size() != 0</code>, use <code>!tree->childLeafs.empty()</code>. Calling <code>size</code> on a vector may require a computation, while <code>empty</code> does not.</p>\n\n<p>In <code>BTreeSearch</code>, replace <code>tree->datas[tree->datas.size()-1]</code> with <code>tree->datas.back()</code>. This can be a bad access if <code>datas</code> is empty. The <code>for</code> loop with <code>i</code> can start indexing at <code>1</code>, with appropriate changes in the condition and body, which will simplify some of the code (by not needing to subtract 1 from the size all the time).</p>\n\n<p>All <code>#include</code> directives should be a the top of the file, rather than having some in the middle where they are hard to find (and makes it more likely that you'll include something twice).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T04:45:37.267",
"Id": "208498",
"ParentId": "208461",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T17:35:20.683",
"Id": "208461",
"Score": "3",
"Tags": [
"c++",
"tree"
],
"Title": "C++ B+Tree search & insert implementation"
} | 208461 |
<p>My main computer is a laptop which I run i3wm atop Arch Linux. As such, my monitor situation sometimes changes, so I wanted to code a script to configure my monitors based on which ones are connected to the system. The script runs on startup of i3wm.</p>
<p>As for the monitors, sometimes I may not have an external display connected, sometimes I may have an HDMI and a DP display connected, and sometimes I may be at another location with an HDMI and DP display connected but the DP appears as a different output.</p>
<p>The monitors are as follows:</p>
<ul>
<li><strong>eDP-1</strong> - Internal Display.</li>
<li><strong>HDMI-2</strong> - Either of my secondary displays, which have the same resolution and placement</li>
<li><strong>DP-1</strong> or <strong>DP-1-8</strong> - Either of my primary displays, which are the same monitor and placement, but appear as different outputs.</li>
</ul>
<p>The code is as follows:</p>
<pre><code>#!/usr/bin/env bash
# The xRandR names of my monitors, including the internal laptop monitor / display
readonly MON_INTERNAL='eDP-1'
readonly MON1='DP-1'
readonly MON1_FALLBACK='DP-1-8'
readonly MON2='HDMI-2'
# The resolutiond of the given xRandR monitors / displays. NOTE: $MON1 and $MON1_FALLBACK are the same display, so only one res is needed
readonly MON_INTERNAL_RES='1920x1080'
readonly MON1_RES='2560x1440'
readonly MON2_RES='1680x1050'
main_mon=''
sec_mon=''
# Store a count of how many monitors are connected
mon_count=$(xrandr -q | grep -w 'connected' | wc -l)
# Configure the monitors via xRandR
config_monitors() {
if [[ "$#" -eq "2" ]]; then
xrandr --output $1 --primary --mode $2 --rotate normal --pos 0x0
elif [[ "$#" -eq "4" ]]; then
xrandr --output $MON_INTERNAL --off --output $1 --mode $2 --pos 1680x0 --right-of $3 --output $3 --mode $4 --pos 0x0 --left-of $1
fi
}
# Determine which main monitor is available
if [[ $mon_count -gt 1 ]]; then
# The name of which main monitor is connected (either $MON1 or $MON1_FALLBACK)
main_mon=$(xrandr -q | grep -w 'connected'| grep "^$MON1\|^$MON1_FALLBACK" | awk '{ print $1 }')
else # fallback to laptop display $MON_INTERNAL because the hardcoded displays aren't connected
main_mon=$MON_INTERNAL
fi
# Determine whether the secondary HDMI monitor, $MON2 is connected
if [[ $mon_count -gt 1 ]] && [[ $(xrandr -q | grep $MON2 | awk '{ print $2 }') -eq connected ]]; then
sec_mon=$MON2
fi
# Configure both external monitors if they're set or use the internal display
# TODO: Actual fallback logic for when HDMI display is connected but not the primary DP-x..
if [[ -n $main_mon ]] && [[ -n $sec_mon ]]; then
config_monitors "$main_mon" "$MON1_RES" "$sec_mon" "$MON2_RES"
else
config_monitors "$MON_INTERNAL" "$MON_INTERNAL_RES"
fi
</code></pre>
<p>Any suggestions on how I could improve the functionality and/or readability of this script are greatly appreciated. This is my first true foray into writing a Bash script that actually serves a usable real-world purpose to me.</p>
| [] | [
{
"body": "<p>for a problem like this, it helps to break down the possible states and map out what you want to do for each, and then construct a data model that lets you minimize duplication.</p>\n\n<p>Here is my approach to your problem: </p>\n\n<ol>\n<li>hardcoded array of monitors by order of preference, allowing wildcards</li>\n<li>hardcoded assoc. array of screen resolutions for each preference</li>\n<li>hardcoded assoc. array of options templates for each possible configuration</li>\n<li>construct array of actual available monitor names from (1) and xrandr output</li>\n<li>construct array of resolutions from (2) and (4)</li>\n<li>get options template from (3) and (4)</li>\n<li>fill template using (4) and (5)</li>\n</ol>\n\n<p>__</p>\n\n<pre><code>#!/usr/bin/env bash\n\n# each PRIORITY entry must have matching entry in MODE; $displays will be sorted in priority order\ndeclare -ar PRIORITY=( \"DP-1*\" HDMI-2 eDP-1 )\ndeclare -Ar MODE=(\n [eDP-1]=1920x1080\n [DP-1*]=2560x1440\n [HDMI-2]=1680x1050\n )\n\n# options corresponding to each possible config. sorted in PRIORITY order. \n# left hand side is matched against space-separated list of actual monitor labels from xrandr\n# template values like <D2> are zero-based\ndeclare -Ar OPTS=(\n [DP-1* HDMI-2 eDP-1]='--output <D2> --off --output <D0> --mode <M0> --pos 1680x0 --right-of <D2> --output <D1> --mode <M1> --pos 0x0 --left-of <D0>'\n [HDMI-2 eDP-1]='--output <D1> --off --output <D0> --mode <M0> --pos 0x0'\n [eDP-1*]='--output <D0> --primary --mode <M0> --rotate normal --pos 0x0'\n )\n\ndeclare -ar ALL_CONNECTED=( $( { xrandr -q || exit 1; } | awk '$2 == \"connected\" {print $1}' ) )\n\n\n[[ ${#ALL_CONNECTED[@]} = 0 ]] && {\n echo no monitors connected\n exit 1\n}\n\ndeclare -a displays=()\ndeclare -a modes=()\n\n# populate displays and modes in preference order from ALL_CONNECTED \nfor (( i=0; i<${#PRIORITY[@]}; i++ )); do\n for (( j=0; j<${#ALL_CONNECTED[@]}; j++ )); do\n if [[ ${ALL_CONNECTED[$j]} == ${PRIORITY[$i]} ]]; then\n displays+=( ${ALL_CONNECTED[$j]} )\n modes+=( ${MODE[${PRIORITY[$i]}]} )\n break\n fi\n done\ndone\n\necho \"\nALL_CONNECTED: ${ALL_CONNECTED[@]}\ndisplays: ${displays[@]}\nmodes: ${modes[@]}\n\"\n\nfor i in \"${!OPTS[@]}\"; do\n if [[ \"${displays[@]}\" == $i ]]; then\n opts=${OPTS[$i]}\n opts=${opts//<M/<span class=\"math-container\">\\$\\{modes\\[} \n opts=${opts//<D/\\$</span>\\{displays\\[}\n opts=${opts//>/\\]\\}}\n set -x\n xrandr $( eval echo $opts )\n exit $?\n fi\ndone\necho \"no OPT setting found for connected display combination of ${ALL_CONNECTED[@]} [ ${displays[@]} ]\"\nexit 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T12:06:57.557",
"Id": "210309",
"ParentId": "208466",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T18:40:58.630",
"Id": "208466",
"Score": "3",
"Tags": [
"bash",
"linux",
"shell"
],
"Title": "BASH Script to Configure Monitors on Linux via xRandR"
} | 208466 |
<p>I'm doing a Daily Challenges to get better with Python.
I completed the first challenges with a working code but I want to make sure if there's anyway to improve or optimize it.</p>
<p>I have a function that adds 2 items from a list in search of those that will match the already defined result.</p>
<pre><code>def main():
listA = [10,11,3,7]
k = 21
for i in listA:
for e in listA:
result = i + e
if result == k:
print(i, '+', e, ' = ', k)
return
main()
</code></pre>
<p>I was thinking of reducing it to:</p>
<blockquote>
<pre><code>def main():
k = 21
listA=[10,11,3,7]
print (k,'=',[(i and e) for i in listA for e in listA if k==(i+e)])
main()
</code></pre>
</blockquote>
<p>… but that would print <code>21 = [10,11]</code> instead of <code>21 = 10 + 11</code>.</p>
| [] | [
{
"body": "<pre><code>def main():\n k = 21\n listA=[10,11,3,7]\n print (k,' = ',\" + \".join([str(i and e) for i in listA for e in listA if k==(i+e)]))\n\nmain()\n</code></pre>\n\n<p>This minor change to your code will do what you're after. Put a <code>\" + \".join( )</code> around your list creator and cast the <code>(i and e)</code> items to <code>str</code>, that will then join all string elements in the list together into a string with <code>+</code> as the separator (there are spaces in there, yes, and this is necessary to get the output you're after).</p>\n\n<p><a href=\"https://tio.run/##RY5BCoMwFET3OcXgxgQ/0tRFoZCF5xAXggn9TZtIzKanT0UFZ/eG4THLL79i6EqZrcN34iDVU2CPh8Fdn/DhNfdm0DfSmjp6jGe/JA4Z0lO9rWuq0KBq33HzDGtOkjGFGVbBxQQGh0O0o72QHbwxkhurRqWEOI6U8gc\" rel=\"nofollow noreferrer\">Proof of Concept</a> (via tio.run) that shows you how this will execute.</p>\n\n<p>Note I also made a change to add spaces around the equals sign, indentation, and extra spacing for readability, as well as indentation standardization (4 spaces for a single indentation level).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T21:59:47.777",
"Id": "402656",
"Score": "0",
"body": "Thanks, It worked perfectly. the .join() is that a built-in function in Python? Like append?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T01:35:06.540",
"Id": "402672",
"Score": "0",
"body": "@Mark-AndréTremblay it's a string function, a builtin as part of the `str` datatype. ([Python documentation for 3.7 on str.join](https://docs.python.org/3.7/library/stdtypes.html#str.join) is better probably for answering your question)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:55:27.650",
"Id": "208481",
"ParentId": "208471",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208481",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T19:58:22.430",
"Id": "208471",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Function that adds two items from a list in search of those that will match some given sum"
} | 208471 |
<p>I have a map that I want to print out sorted by value, I convert it to vector and sort the vector. Is this code correct?</p>
<pre><code>#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
int main()
{
std::map<char, int> freq;
std::string text;
std::getline(std::cin, text);
std::vector<std::pair<char, int>> items;
for(auto & ch: text)
freq[ch]++;
for(auto [key, value]: freq)
items.push_back(std::make_pair(key, value));
std::sort(items.begin(), items.end(),
[](auto a, auto b)
{ return a.second > b.second;});
for(auto [key, value]: items)
std::cout << key << " " << value << std::endl;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:47:08.380",
"Id": "402637",
"Score": "1",
"body": "You might want to wait a bit until you accept an answer. There are quite a lot of people on this site that want to comment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T22:15:05.383",
"Id": "402659",
"Score": "0",
"body": "Ok, I am a newbee, kind of excited to participate :)"
}
] | [
{
"body": "<p>The code is correct. However, I still have some recommendations:</p>\n\n<ol>\n<li><p>Sort the includes, so you can easily spot recurring/missed ones</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <map>\n#include <utility>\n#include <vector>\n</code></pre></li>\n<li><p>You do not need to run the loop, you can simply pass the map to the <code>std::vector</code> constructor. As you use structured bindings and therewith at least C++17, I suggest Template Argument Deduction to omit the type of the vector</p>\n\n<pre><code>std::vector items(freq.begin(), freq.end());\n</code></pre></li>\n<li><p>The comparison function takes the arguments by copy, which is not optimal. Rather use <code>const auto&</code>:</p>\n\n<pre><code>[] (const auto& a, const auto& b) { return a.second > b.second;})\n</code></pre></li>\n<li><p>Note that <code>std::sort</code> may change the ordering of elements with equal value. If you want those elements with equal frequency to appear in the same order than in the map you would need <code>std::stable_sort</code>. However, keep in mind that this requires additional resources in memory and compute time.</p></li>\n<li><p>You are using a <code>std::map</code>, which is an ordered container. If you are only interested in the frequencies then a <code>std::unordered_map</code> will generally offer better performance. Although for a simple alphabet this will most likely be negligible.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:49:47.563",
"Id": "402639",
"Score": "0",
"body": "I know we should not say thanks and become sentimental, but this was a very thorough and nice review of my code. Tnx."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T21:09:12.900",
"Id": "402645",
"Score": "0",
"body": "I could implement all the items, except for auto template arg deduction. Item 2. when I use auto items = std::vector(freq.begin(), freq.end()); clang++-6.0 complains about not being able to deduce vector type. perhaps I am doing something wrong ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T06:41:20.677",
"Id": "402679",
"Score": "1",
"body": "It seems that the compiler cannot deduce from the iterator constructor, so you will have to add the template argument there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T06:49:42.337",
"Id": "402681",
"Score": "2",
"body": "Clang is still adding support for Class Template Argument Deduction as much of the standard library had to be rewritten to accommodate the feature. Clang 7.0 was the first version to introduce CTAD for library types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T23:00:35.157",
"Id": "402826",
"Score": "0",
"body": "Passing small trivially-copyable types by value is *The Right Thing*. Not that it matters if the callee is such a simple function-object and the call thus gets inlined. Regarding the best container to use for calculating frequencies, it is hard to beat a plain native array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T08:07:55.653",
"Id": "402853",
"Score": "0",
"body": "@Deduplicator You are definitely correct with respect to small trivially copyable types. However, that is a conscious desicion and the default should be `const&`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:44:18.913",
"Id": "208477",
"ParentId": "208474",
"Score": "9"
}
},
{
"body": "<p>Just a few comments to add.</p>\n\n<h3>Data Structure</h3>\n\n<p>In this case, I'd tend to avoid <code>std::map</code> for counting frequencies. I probably wouldn't use <code>std::unordered_map</code> either though. Instead, I'd create a simple array:</p>\n\n<pre><code>std::array<int, std::numeric_limits<unsigned char>::max()> freq;\n</code></pre>\n\n<p>[Note: when using this, you want to convert the input characters to <code>unsiged char</code> before using them as indices.<sup>1</sup>]</p>\n\n<p>Both <code>map</code> and <code>unordered_map</code> do quite a bit of work to create something that acts like an array, but indexed using types (like strings) for which it's impractical to use the values of that type as an index directly because it would typically require <em>far</em> too much memory. In your case, however, you're using a <code>char</code> as an index, so creating an array that just allows all possible values of <code>char</code> as its index is utterly trivial. The amount of memory used is small enough that it's feasible even on thoroughly ancient computers (e.g., a Commodore 64 or Apple II). In this case, the array is so small (1 or 2 kilobytes) that it'll normally save space.</p>\n\n<p>In addition, the array will almost certainly be quite a bit faster than either a map or unordered_map.</p>\n\n<p>One time you'd want to think about using the map or unordered_map would be if you were going to support a character set like Unicode where using characters directly as array indices would lead to an inconveniently large array. In this case, you might (easily) want to us a map rather than an unordered_map. This would make it easy (for one example) to show frequencies for things like letters and digits, while ignoring things like punctuation and diacritics.</p>\n\n<h3>Formatting</h3>\n\n<p>I prefer to leave at least one blank line between the last header inclusion line, and whatever comes after it (in this case, the beginning of <code>main</code>).</p>\n\n<h3>Return value from <code>main</code></h3>\n\n<p>There's no need to <code>return 0;</code> from <code>main</code>--the compiler will do that automatically if you just let control flow off the end of <code>main</code>.</p>\n\n<h3>using of <code>std::endl</code></h3>\n\n<p>I advise against using <code>std::endl</code> in general. In addition to writing a new-line to the stream (which is all you probably want) it flushes the stream (which you almost never want). Especially if you're producing a lot of output, these unnecessary flushes can (and often do) slow programs substantially (a 10:1 margin is fairly common).</p>\n\n<p>On the relatively rare occasion that you want to writ a new line <em>and</em> flush the stream, I'd do that explicitly: <code>std::cout << '\\n' << std:flush;</code></p>\n\n<hr>\n\n<ol>\n<li>If you prefer, you can use a char that's signed (either by default or explicitly) and use it to index off of a pointer that points to the middle (usually the 128<sup>th</sup> element) of the array.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:24:34.200",
"Id": "402698",
"Score": "1",
"body": "The `std::array` might be problematic with plain `char` as index - it would be safer to convert input to `unsigned char` there."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T08:09:58.027",
"Id": "208502",
"ParentId": "208474",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "208477",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:22:20.183",
"Id": "208474",
"Score": "5",
"Tags": [
"c++",
"sorting",
"hash-map"
],
"Title": "sorting a map by converting it to vector"
} | 208474 |
<p>I've created my own take on a navigation bar using FlexBox (currently not refined for smaller screen media queries). I would just like someone to go through my code notes and see if I am going about it correctly.</p>
<p>It seems to work but am I doing this inefficiently? Should i be using other methods? Have I aligned using the best procedures etc?</p>
<p>Ignore the fact I haven't used classes please.</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-css lang-css prettyprint-override"><code> *{
margin: 0;
padding: 0;
}
body{
background-color: #FFF;
font-size: 1.2em;
}
header{
display: grid;
grid-template-columns: 20% 60% 20%; /*used to keep the grey bar along the whole of the top, but keep navigation selection area squashed in slightly*/
width: 100%;
background-color: #A6A6A6;
}
nav{
grid-column: 2;
}
nav ul{
display: flex;
min-width: 500px; /*stops list items overlapping when smaller screen - will later include media query to fix*/
margin: auto;
/*do not use 'justify content' this causes gaps between each list item, and i want seamless link to lin kwhen hovering*/
}
nav ul li{
width: 20%; /*width of each flex item is 20% as there are 5 items*/
text-align: center; /*move text to center of individual list item*/
list-style: none;
}
nav ul li a{
display: block; /*devault is set to inline which does not expand the 'link area' to fill the list element*/
color: #FFF;
padding: 20px; /*this padding changes size of parent list item too*/
text-decoration: none;
border-right: solid #FFF 1px;
}
/* border decoration-------------------------------------*/
nav ul li:hover{
background-color: #767676;
}
nav ul li:first-child{
border-left: solid #FFF 1px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/style.css" />
<meta name="viewport" content-type="width=device-width initial-scale=1" />
<title>NavBar Examples</title>
</head>
<body>
<header>
<nav class="centered-navigation-bar">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
</header>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>Here are a few thoughts:</p>\n\n<ol>\n<li><p>The universal selector to reset the margin and padding is slow and unnecessary in the case since none of the elements you're using have default margin or padding.</p></li>\n<li><p>The use of hover by itself is not mobile friendly, and if the user expects to click <code>Home</code> to go to the homepage, a more robust design would be better. For example:</p></li>\n</ol>\n\n<blockquote>\n <p>It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard\n For situations when the parent menu item needs to carry out a function, such as linking to a web page, a separate button can be added to the parent item, to open and close the submenu. This button can also act as a visual indicator for the presence of a submenu.</p>\n</blockquote>\n\n<ol start=\"3\">\n<li>For accessibility, add <code>aria-role=menubar</code> to the <code>ul</code> and <code>aria-role=menuitem</code> to each anchor tag.</li>\n</ol>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><p><a href=\"https://www.w3.org/WAI/tutorials/menus/flyout/\" rel=\"nofollow noreferrer\">Fly-out Menus • Menus • WAI Web Accessibility Tutorials</a></p></li>\n<li><p><a href=\"https://www.w3.org/TR/wai-aria-practices/examples/menubar/menubar-1/menubar-1.html\" rel=\"nofollow noreferrer\">Navigation Menubar Example | WAI-ARIA Authoring Practices 1.1</a></p></li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility\" rel=\"nofollow noreferrer\">Handling common accessibility problems - Learn web development | MDN</a></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T15:38:53.003",
"Id": "213050",
"ParentId": "208475",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:31:29.400",
"Id": "208475",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "SYNTAX QUERY - HTML and CSS responsive navigation bar using FlexBox"
} | 208475 |
<p>I have a simple web application where a user uploads a CSV of some dataset and some summary statistics and box plots are displayed. I heard that it is better to have so called skinny views and fat models, though I'm unsure how is best to divide the work. How could I improve my database schema and division of labour?</p>
<h1>views.py</h1>
<pre><code>class HomeView(View):
"""View that handles when users land on the homepage"""
def get(self, request):
return render(request, 'summary/home.html')
# Will currently raise an HttpResponseNotAllowed if POST request received to home
@method_decorator(login_required, name='dispatch')
class UploadView(TemplateView):
"""Users land here after successfully signing in and are prompted to upload a CSV file"""
form_class = UploadFileForm
template_name = 'summary/uploads.html'
def get(self, request):
form = self.form_class()
datasets = Dataset.objects.filter(user=request.user)
context = {
'datasets': datasets,
'csv_form': form,
'within_dataset_limit': request.user.within_dataset_limit()
}
return render(request, self.template_name, context=context)
def post(self, request):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
uploaded_file = request.FILES['dataset_file']
datasets = Dataset.objects.filter(user=request.user)
context = {
'datasets': datasets,
'csv_form': form,
'within_dataset_limit': request.user.within_dataset_limit(),
}
# Check the file is a CSV
if not str(uploaded_file).lower().endswith('.csv'):
context['error'] = 'File not in CSV format.'
return render(request, 'summary/uploads.html', context)
# Check the file size is within the set limit
elif not 0 < uploaded_file.size < request.user.max_dataset_size:
context['error'] = 'File exceeds size limit.'
return render(request, 'summary/uploads.html', context)
else:
ds = Dataset(user=request.user, dataset_name=str(uploaded_file), dataset_file=uploaded_file)
ds.save()
return redirect(f'/{request.user.pk}/{ds.id}/overview/')
@method_decorator(login_required, name='dispatch')
class OverviewView(TemplateView):
"""Display head and summary statistics of the uploaded dataset"""
template_name = 'summary/overview.html'
def get(self, request, upk, dpk):
if request.user.pk == upk:
ds = Dataset.objects.get(pk=dpk)
head, summary, df = dataset_stats(ds)
request.session['dataframe'] = df.to_json()
context = {
'first_five': head,
'summary_stats': summary,
}
return render(request, self.template_name, context)
def delete_dataset(request, upk, dpk):
if request.method == 'POST':
if request.user.is_authenticated and request.user.pk == upk:
try:
ds = Dataset.objects.get(pk=dpk)
os.remove(ds.dataset_file.path)
ds.delete()
return HttpResponse(status=200)
except Dataset.DoesNotExist:
return HttpResponseNotFound()
return HttpResponseForbidden()
return HttpResponseBadRequest()
def boxplot(request):
"""Generation of boxplots to be moved to computation server"""
# Get the selected columns from the overview view
selected_columns = request.GET['selectedColumns']
selected_columns = json.loads(selected_columns)
code, boxplot_html = generate_plots(selected_columns, request.session.get('dataframe'))
if boxplot_html is not None:
return HttpResponse(status=code, content=boxplot_html)
else:
error = "Could not create your plots"
return HttpResponse(status=code, content=error)
</code></pre>
<h1>models.py</h1>
<pre><code>def get_upload_path(instance, filename):
return "user_{}/{}".format(instance.user.pk, filename)
class Dataset(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
dataset_name = models.CharField(max_length=100)
date_added = models.DateTimeField(auto_now_add=True)
dataset_file = models.FileField(upload_to=get_upload_path)
def __str__(self):
return self.dataset_name
def save(self, *args, **kwargs):
user = CustomUser.objects.get(username=self.user)
if user.num_datasets == user.max_datasets:
return # Exceeding the max number of datasets
else:
user.num_datasets += 1
user.save()
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
user = CustomUser.objects.get(username=self.user)
user.num_datasets -= 1
user.save()
super().delete(*args, **kwargs)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:44:33.330",
"Id": "208478",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Django model and views to summarize and plot an uploaded CSV"
} | 208478 |
<p>I am coding in java since some time but I was not always really organized about methods and commentaries, here is a quick code to use the Cesar code :</p>
<pre><code>package cesar_code;
import java.text.Normalizer;
import java.util.Scanner;
public class CesarCode {
private static Scanner sc = new Scanner(System.in);
private static boolean stop = false;
private static boolean ready_to_translate = false;
private static String user_input;
private static String message_head;
public static void main (String[] args){
while(!stop){
choose_action_to_do();
if(ready_to_translate){
translate();
}
}
}
private static void choose_action_to_do(){
ready_to_translate = false;
System.out.println("\n\nType \"encrypt(message_to_encrypt)\" or \"decrypt(message_to_decrypt)\" please (or \"stop\" to stop).");
user_input = sc.nextLine();
user_input = (Normalizer.normalize(user_input, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "")).toLowerCase();
if(user_input.equals("stop")){
stop = true;
}
else if (user_input.length()>= 9){
message_head = user_input.substring(0,8);
if ((message_head.equals("encrypt(") || message_head.equals("decrypt(")) && user_input.charAt(user_input.length() - 1) == ')') {
ready_to_translate = true;
}
}
}
private static void translate(){
char[] alphabet = {'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', 'x', 'z'};
StringBuilder translated_message_build = new StringBuilder();
System.out.print("The encrypted message is : ");
for(int i = 8; i <= user_input.length()-2; i++) {
for(int j = 0; j< alphabet.length; j++){
if(user_input.charAt(i)==alphabet[j]){
if (message_head.equals("encrypt(")){
if(j!=26){
translated_message_build.append(alphabet[j+1]);
}
else{
translated_message_build.append((alphabet[j-26]));
}
break;
}
else if (message_head.equals("decrypt(")){
if(j!=0){
translated_message_build.append(alphabet[j-1]);
}
else{
translated_message_build.append((alphabet[j+26]));
}
break;
}
}
else if(j == 26){
translated_message_build.append(user_input.charAt(i));
}
}
System.out.print(translated_message_build.charAt(i-8));
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
</code></pre>
<p>Maybe there is something to improve ? Maybe commentaries are required here ?
Should I combine the encrypt and decrypt part in one just with a return method that change the + or the - depending if it is encrypt or decrypt that is asked ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T22:38:18.747",
"Id": "402660",
"Score": "0",
"body": "Welcome to Code Review. Are there two \"a\"s in \"caesar\" where you are from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T22:57:29.937",
"Id": "402663",
"Score": "1",
"body": "In France, I use to tell it \"Code Cesar\", but it seems that here it is more about a \"Caesar Cipher\" as 200_sucess edited my post. But anyway, that's not the subject ^^."
}
] | [
{
"body": "<p>While your code do everything as intended, there are quite a few things that are wrong or non-standard.</p>\n\n<p>In no particular order :</p>\n\n<ul>\n<li>the package name should usually start with an internet domain name extension, such as fr or com</li>\n<li>variable should not contains underscore, they are usually reserved to constants name so it should not be <code>user_input</code> but rather <code>userInput</code><br>\nHere is the convention from the oracle website : <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html</a></li>\n<li>same goes for method name</li>\n<li>there are some \"magic numbers\"... but more on that later</li>\n<li>it's more readable to have operator for comparisons separated from their operands by space such as <code>user_input.length() >= 9</code></li>\n<li>for readability as well, avoid line that are too long and put one space behind comma</li>\n<li>your methods are really hard to reuse : if you wanted to use your caesar cipher in some other place, you wouldn't manage because your cipher method mix a lot of differents things :\nit ciphers (as expected), it reads from standard input, it prints, it sleeps (why would it do that ?) and it knows that the user will write \"encrypt\" or \"decrypt\"\nYou should have made a method like this 'String cipher(String input)' that'll only do one thing : return the ciphered string\nIt is thus much easier to test and to reuse. If you are not convinced, I'd recommend trying to unit test your translate method... you'll see it's a real pain :)</li>\n<li>what's the point of separating <code>choose_action_to_do</code> and <code>translate</code> ? on paper they may sound like two differents features, but the fact that they are linked\nby a global variable demonstrates they are in fact tighly coupled in your code</li>\n<li>most static variables don't make much sense, and if you apply the two previous points it'll become highly apparent</li>\n<li>let's say you want to have another cipher method (like a \"One-time pad\" for example), making an interface to implement various Cipher method make sense IMO</li>\n</ul>\n\n<p>Here is a part of the solution using everything I recommended :\n(Please bear with the minimal javadoc :))</p>\n\n<pre><code>package fr.cipher;\n\nimport java.text.Normalizer;\nimport java.util.Scanner;\n\npublic class Launch {\n\n private static final String ENCRYPT = \"encrypt(\";\n private static final String DECRYPT = \"decrypt(\";\n private static final int HEAD_SIZE = 8;\n\n private static Scanner sc = new Scanner(System.in);\n\n private static boolean stop = false;\n\n public static void main(final String[] args) {\n while (!stop) {\n askActionAndApply();\n }\n }\n\n public static void askActionAndApply() {\n Cipher c = new CaesarCipher();\n System.out.println(\"\\n\\nType \\\"encrypt(message_to_encrypt)\\\" or \"\n + \"\\\"decrypt(message_to_decrypt)\\\" please (or \\\"stop\\\" to stop).\");\n\n String userInput = sc.nextLine();\n userInput = Normalizer.normalize(userInput, Normalizer.Form.NFD).replaceAll(\"[^\\\\p{ASCII}]\", \"\").toLowerCase();\n\n if(userInput.equals(\"stop\")) {\n stop = true;\n } else if (userInput.length() > HEAD_SIZE && userInput.endsWith(\")\")) {\n translate(c, userInput);\n }\n }\n\n private static void translate(final Cipher cipher, final String userInput) {\n String messageHead = userInput.substring(0, HEAD_SIZE);\n\n String content = userInput.substring(HEAD_SIZE, userInput.length() - 1);\n\n if (messageHead.equals(ENCRYPT)) {\n System.out.println(cipher.cipher(content));\n } else if (messageHead.equals(DECRYPT)) {\n System.out.println(cipher.decipher(content));\n }\n // if you want you can put your Thread.sleep here :)\n }\n}\n</code></pre>\n\n<p>You could (and should) also remove the \"stop\" field but I let it in place so it's easier to compare your code and mine.\nThe Cipher interface looks like this :</p>\n\n<pre><code>/**\n * This class represents a cryptography algorithm.\n * <p>\n * It is not suited for <i>Hash</i> algorithm.\n * \n * @author R Dhellemmes\n *\n */\npublic interface Cipher {\n String cipher(String input);\n\n String decipher(String input);\n}\n</code></pre>\n\n<p>And you'll have a <code>CaesarCipher</code> class implementing this <code>Cipher</code> interface.</p>\n\n<p>Hope it helps :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T10:23:30.180",
"Id": "402875",
"Score": "0",
"body": "Thanks a lot guys ! Seems like i still got a lot to learn :P. As it's completely a new way to code for me, I know that I'll still have some questions after changing all my program. It could take me few days to understand everything exactly, so I'll be back right after for last questions ^^."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:19:05.747",
"Id": "402914",
"Score": "0",
"body": "@ThomasCloarec no problems :) if you want us to review your upgraded code, you should ask a brand new question ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:19:06.227",
"Id": "208517",
"ParentId": "208480",
"Score": "1"
}
},
{
"body": "<p>One thing that stands out for me in your code is the lack of use of the remainder <code>%</code>. <code>i%n</code> gives you the remainder of the Euclidean division of <code>n</code> by <code>i</code>, which is a positive integer >=0 and < n.</p>\n\n<p>For example, <code>5%12 = 5</code> because <code>5 = 12*0 + 5</code>, and <code>13%12 = 1</code> because <code>13 = 12*1 + 1</code> (I am using <code>n=12</code> in this example because this is basically what we do when reading clocks).</p>\n\n<p>Anyways, this is useful if you have a list of things which is \"cyclic\", i.e. you would like to go back to the beginning after reaching the end, which is exactly the case here.</p>\n\n<p>So, for encryption, instead of </p>\n\n<pre><code> if(j!=26){\n translated_message_build.append(alphabet[j+1]);\n }\n else{\n translated_message_build.append((alphabet[j-26]));\n }\n</code></pre>\n\n<p>I would write</p>\n\n<pre><code>translated_message_build.append(alphabet[(j+1)%26]);\n</code></pre>\n\n<p>And for decryption</p>\n\n<pre><code>translated_message_build.append(alphabet[(j-1)%26]);\n</code></pre>\n\n<p>This works because (for encryption) if <code>j=26</code>, <code>j+1 = 27</code> and <code>27%26 = 1</code> because <code>27=26*1 + 1</code>.</p>\n\n<p>And (for decryption) if <code>j=0</code>, <code>j-1 = -1</code> and <code>-1%26 = 25</code> because <code>-1 = 26*(-1) +25</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T10:23:40.373",
"Id": "402876",
"Score": "0",
"body": "Thanks a lot guys ! Seems like i still got a lot to learn :P. As it's completely a new way to code for me, I know that I'll still have some questions after changing all my program. It could take me few days to understand everything exactly, so I'll be back right after for last questions ^^."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:25:17.550",
"Id": "208518",
"ParentId": "208480",
"Score": "1"
}
},
{
"body": "<p>As said in the other answers there is room to improvement. First of all you should apply the naming conventions to your \npackage, fields and methods. Then you may want to separate the concerns of asking the user and doing the translation so \nthat you can easily unit test your encoding and decoding algorithms. </p>\n\n<h3>Managing user interactions</h3>\n\n<p>The user interactions will be done by a dedicate class that, as you have done, continuously ask the user for an action \nand execute it. But if you want to use the \"functional\" constructs of Java8 you can see that actions as something that \nchange the state of your application by setting the <code>stop</code> flag to true or by translating the user input.</p>\n\n<pre><code>public void start() { \n do {\n Consumer<EncoderUi> action = askForAction();\n action.accept(this);\n } while (!stop);\n}\n\n\nprivate Consumer<EncoderUi> askForAction(){\n System.out.println(\"\\n\\nType \\\"encrypt(message_to_encrypt)\\\" or \\\"decrypt(message_to_decrypt)\\\" please (or \\\"stop\\\" to stop).\");\n final String input = Normalizer.normalize(sc.nextLine(), Normalizer.Form.NFD)\n .replaceAll(\"[^\\\\p{ASCII}]\", \"\")\n .toLowerCase();\n\n if ( \"stop\".equals(input) ) {\n return ui -> ui.stop = true;\n } else if ( input.startsWith(\"encrypt(\") ) {\n return translate(input, cipher::encode);\n } else if ( input.startsWith(\"decrypt(\") ) {\n return translate(input, cipher::decode);\n } else {\n return ui -> ui.print(\"Invalid action \\\"\"+input+\"\\\".\");\n }\n}\n</code></pre>\n\n<p>Your <em>encrypt</em> or <em>decrypt</em> actions are basically doing the same thing :</p>\n\n<ol>\n<li>Extract the message from the user input</li>\n<li>Transform the message</li>\n<li>Print the result</li>\n</ol>\n\n<p>The transformation is basically a <code>Function<String, String></code> that takes a string and return another. And this is the \nonly thing that changes in your process. You can use the method references to pass the correct transformation and keep\nthe whole process the same. </p>\n\n<pre><code>private Consumer<EncoderUi> translate(String input, Function<String, String> algorithm) {\n return ui -> {\n String message = parse(input);\n String result = algorithm.apply(message);\n ui.print(result);\n };\n}\n</code></pre>\n\n<p>You cannot unit test your user interactions but the code is quite clear so this is not a real issue. However if you want \nto do it, you can move the parsing of the user input to another method (or class) and test that each input produce an \naction that change your state as expected</p>\n\n<pre><code>MockedUi state = // ...\nConsumer<EncoderUi> action = parse(\"stop\");\naction.accept(state);\n\nassertThat(state.stop).isTrue();\n</code></pre>\n\n<h3>Improving your translation</h3>\n\n<p>As said in the other answers your translation code can also be refactored to something more reusable. As previously said\nthe encoding and decoding are basically a transformation of string with the only variation being the direction of the \nshift. The only difference is the way you compute the substitution character.</p>\n\n<pre><code>public String encode(String input) {\n return translate(input, chr -> chr+1);\n}\n\npublic String decode(String input) {\n return translate(input, chr -> chr-1);\n }\n\nprivate String translate(String input, IntUnaryOperator translation) {\n input.chars()\n .map(chr -> translation.apply(chr-'a'))\n .map(pos -> ALPHABET[pos % 26])\n .mapToObj(Objects::toString)\n .collect(joining());\n}\n</code></pre>\n\n<p>You can avoid the nested loops by using the <code>char[] ALPHABET = {'a', 'b',..}</code> array. \nThe <code>chr-'a'</code> is used to place to translate the Ascii char code to your array (<code>'a'</code> being at position <code>0</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T10:23:48.703",
"Id": "402877",
"Score": "0",
"body": "Thanks a lot guys ! Seems like i still got a lot to learn :P. As it's completely a new way to code for me, I know that I'll still have some questions after changing all my program. It could take me few days to understand everything exactly, so I'll be back right after for last questions ^^."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T13:12:48.783",
"Id": "402896",
"Score": "0",
"body": "You are welcome. Don't forget to accept one of the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T07:34:44.433",
"Id": "208589",
"ParentId": "208480",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "208517",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T20:55:09.703",
"Id": "208480",
"Score": "1",
"Tags": [
"java",
"caesar-cipher"
],
"Title": "Cesar code in Java"
} | 208480 |
<p>I've stumbled upon <a href="https://www.kevinhwong.com/articles/trello-s-hashing-interview-question" rel="nofollow noreferrer">this</a> pretty old article about a hashing interview question, and here it is converted to Swift in a more generic way:</p>
<pre><code>struct CustomHasher {
/// An enum of the errors that may be thrown
enum HashingError: Error {
/// Thrown by the initializer
/// when the alphabet contains repeating letters
case invalidAlphabet
/// Thrown by the initializer
/// when the base is negative
case invalidBase
/// Thrown by the initializer
/// when the offset is negative
case invalidOffset
/// Thrown by the hash(_:) function
/// when the string provided uses illegal letters
case outOfAlphabet(String)
/// Thrown by the hash(_:) function
/// when the string provided uses illegal letters
case exceedsInt64
/// Thrown by the reverseHash(_:) function
/// when the string provided uses illegal letters
case invalidHash
}
//Parameters
private let base: Int64
private let offset: Int64
private let alphabet: String
// An array that eases the access to the elements of the alphabet
private let alphabetArray: [Character]
private let stringLengthLimit: Int
/// Convinience inializer
/// - Parameters:
/// - alphabet: Must be a string of unique characters
/// - offset: A strictly positive Int64
/// - base: A strictly positive Int64
/// - Throws:
/// - HashingError.outOfAlphabet(String)
/// - HashingError.invalidOffset
init(alphabet: String, offset: Int64, base: Int64) throws {
self.alphabet = alphabet
self.alphabetArray = Array(alphabet)
guard alphabetArray.count == Set(alphabet).count else {
throw HashingError.invalidAlphabet
}
guard offset > 0 else {
throw HashingError.invalidOffset
}
self.offset = offset
guard base > 1 else {
throw HashingError.invalidBase
}
self.base = base
let b = Double(base)
let c = Double(alphabetArray.count)
let dOffset = Double(offset)
let int64limit = Double(Int64.max)
self.stringLengthLimit = ((0...).first {
let power = pow(b, Double($0))
let tail = $0 == 1 ? c * power : c * (power - 1) / (b - 1)
let head = dOffset * power
return head + tail > int64limit
} ?? 0) - 1
}
/// Takes a string and converts it to a corresponding Int64
/// - Parameters:
/// - str: The string to be hashed
/// - Throws:
/// - HashingError.outOfAlphabet(String)
/// - HashingError.exceedsInt64
func hash(_ str: String) throws -> Int64 {
guard Array(str).count <= stringLengthLimit else {
throw HashingError.exceedsInt64
}
var h: Int64 = offset
for char in str {
if let index: Int = alphabetArray.firstIndex(of: char) {
h = h * base + Int64(index)
} else {
throw HashingError.outOfAlphabet(alphabet)
}
}
return h
}
/// Reverses the hashing process
/// - Parameters:
/// - str: The string to be hashed
/// - Throws:
/// - HashingError.invalidHash
func reverseHash(_ hash: Int64) throws -> String {
guard hash >= offset else {
throw HashingError.invalidHash
}
//Reached the end
if hash == offset {
return ""
}
let remainder: Int64 = hash % base
let quotient: Int64 = (hash - remainder)/base
let index: Int = Int(truncatingIfNeeded: remainder)
guard index < alphabetArray.count else {
throw HashingError.invalidHash
}
let char: Character = alphabetArray[index]
return try reverseHash(quotient) + String(char)
}
}
</code></pre>
<p>And here it is in use:</p>
<pre><code>let base37 = try! CustomHasher(alphabet: "acdegilmnoprstuw",
offset: 7,
base: 37)
do {
try base37.hash("leepadg")
} catch {
print(error)
}
do {
try base37.reverseHash(680131659347)
} catch {
print(error)
}
</code></pre>
<p>Feedback on all aspects of the code is welcome, such as (but not limited to):</p>
<ul>
<li>Should such a hasher throw? Or would it be more natural/idiomatic to return nil if it fails?</li>
<li>Possible improvements (speed, clarity, especially the latter),</li>
<li>Naming,</li>
<li>Better comments.</li>
</ul>
| [] | [
{
"body": "<h3>General stuff</h3>\n\n<p>Several explicit type annotations are not needed, such as in </p>\n\n<pre><code>var h: Int64 = offset\n\nif let index: Int = alphabetArray.firstIndex(of: char)\n\nlet remainder: Int64 = hash % base\nlet quotient: Int64 = (hash - remainder)/base\n</code></pre>\n\n<h3>Error handling</h3>\n\n<ul>\n<li><p>In the initializer:</p>\n\n<p>Throwing an error for illegal parameters is fine, and allows to provide more details about the error than in a failable initializer. I only wonder why <code>offset</code> is required to be strictly positive. Is there any problem with allowing a zero offset?</p></li>\n<li><p>In the <code>hash</code> method:</p>\n\n<p>Again, throwing an error for bad input seems fine to me. However: Most hashing method accept arbitrary long input strings. If “overflow” is an error for this very special hasher then I would call just it <code>overflow</code> error instead of <code>exceedsInt64</code>.</p></li>\n<li><p>In the <code>reverseHash</code> method:</p>\n\n<p>This is again a special situation for this hasher, most hashing methods are designed in a way to make “dehashing” as computing intensive as possible. Here I would return <code>nil</code> instead of throwing an error if no matching source string is found, meaning “no result.”</p></li>\n</ul>\n\n<h3>The overflow checking</h3>\n\n<p>It is not immediately obvious how <code>self.stringLengthLimit</code> is calculated, this calls for an explaining comment. Also I am always a bit suspicious if integer and floating point arithmetic is mixed: A (64-bit) <code>Double</code> has a 53-bit significand precision and cannot store all 64-bit integers precisely.</p>\n\n<p><em>Anyway:</em> Detecting an overflow based on the string length alone cannot work in all cases. Here is an example: With </p>\n\n<pre><code>let base10 = CustomHasher(alphabet: \"0123456789\", offset: 9, base: 10)\n</code></pre>\n\n<p>the hash of \"223372036854775807\" fits into a 64-bit integer, but your program rejects that input string because its length exceeds <code>stringLengthLimit = 17</code>.\"223372036854775808\" has the same length, but its hash calculation would overflow.</p>\n\n<p>This shows that it is difficult to detect the overflow in advance. As an alternative, one could use the “overflow-reporting methods” for multiplication and addition. This is more code (and not nice to read) but detects overflow reliably:</p>\n\n<pre><code>guard let index = alphabetArray.firstIndex(of: char) else {\n throw HashingError.outOfAlphabet(alphabet)\n}\nguard\n case let r1 = h.multipliedReportingOverflow(by: base), !r1.overflow,\n case let r2 = r1.partialValue.addingReportingOverflow(Int64(index)), !r2.overflow\n else {\n throw HashingError.exceedsInt64\n}\nh = r2.partialValue\n</code></pre>\n\n<p>Of course these thoughts apply only to your special hasher. Usually one would accept arbitrary input, using (for example) <code>&+</code> and <code>&*</code> for addition and multiplication with automatic “wrap around.”</p>\n\n<h3>Simplifications</h3>\n\n<p>There is not very much to say, the code is written clearly. You store the given alphabet both as the original string and as an array of characters, but later use only the array.</p>\n\n<p>The second line in </p>\n\n<pre><code>let remainder = hash % base\nlet quotient = (hash - remainder)/base\n</code></pre>\n\n<p>can be simplified to </p>\n\n<pre><code>let quotient = hash/base\n</code></pre>\n\n<p>You can also compute both quotient and remainder with a call to the BSD library function <a href=\"https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/lldiv.3.html\" rel=\"nofollow noreferrer\"><code>lldiv</code></a></p>\n\n<pre><code>let remQuot = lldiv(hash, base)\n</code></pre>\n\n<p>but I doubt that it would be faster.</p>\n\n<p>The recursion in the dehasher could be replaced by an iteration, that would allow to <em>append</em> to the result string, and only reverse once, instead of prepending characters to a string repeatedly:</p>\n\n<pre><code>var hash = hash\nvar result = \"\"\nwhile hash > offset {\n let remainder = hash % base\n hash = hash / base\n let index = Int(truncatingIfNeeded: remainder)\n guard index < alphabetArray.count else {\n return nil\n }\n result.append(alphabetArray[index])\n}\nreturn hash < 0 ? nil : String(result.reversed())\n</code></pre>\n\n<p>But since the number of recursions/iterations is quite limited it probably won't make much of a difference, and you can choose what you find more natural.</p>\n\n<h3>Naming</h3>\n\n<p><code>CustomHasher</code> does not tell anything about the type. I am not good in finding names, perhaps <code>TrelloHasher</code> if you want to emphasize where it comes from, or <code>MultAddHasher</code> ... naming is difficult (and subjective)!</p>\n\n<p>Possible alternative method names would be</p>\n\n<pre><code>func hash(of s: String) {}\nfunc string(for hash: Int64) {}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:55:37.323",
"Id": "403084",
"Score": "0",
"body": "**General stuff** Type annotations were added purposefully to make the code clearer. It's a personal choice to make the reading experience seamless/effortless. Many errors occur out of misinferring the types. **Error handling)** With an offset equal to zero, the hash for an empty string would be the same as the one of the first character in the alphabet. **The overflow checking)** I'll have to adjust the `stringLengthLimit` by 1, and the formula for calculating it (the sum of a geometric series). The basic idea is checking that the max number generated by the `hash`function won't overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:56:00.477",
"Id": "403085",
"Score": "0",
"body": "(continuation) AFAIK `Int64.max`does fit into double precision: `Double.greatestFiniteMagnitude` is way bigger than `Int64.max`. and `Double(Int64.max) == 9223372036854775807` is true. I am avoiding *wrap around* since there might be overlaps (two -or more- words with the same hash). **Simplifications)** Thank you for the little `lldiv` jewel. [`quotientAndRemainder(dividingBy:)`](https://developer.apple.com/documentation/swift/int/2884924-quotientandremainder) was also possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T19:21:09.860",
"Id": "403162",
"Score": "0",
"body": "@Carpsen90: You are right about offset=0. – Overflow checking based on the string length alone cannot work, as I tried to demonstrate with \"223372036854775807\" and \"223372036854775808\". – Double cannot represent all Int64 precisely, try `print(Double(Int64.max) == Double(Int64.max - 500))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:02:21.440",
"Id": "403168",
"Score": "0",
"body": "You're right, there is a mathematical limit where `Double` wouldn't be precise enough. `Float80` seems to solve that (I'll have to check the docs)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:09:13.257",
"Id": "403170",
"Score": "0",
"body": "@Carpsen90: Yes, but just note that Float80 is not portable: https://github.com/apple/swift/blob/master/stdlib/public/core/FloatingPointTypes.swift.gyb#L1904: \"Float80 is only available on non-Windows x86 targets.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:06:30.853",
"Id": "403184",
"Score": "0",
"body": "As to the example of `\"223372036854775808\"`, the error message is not very helpful, since it warns about the possibility of overflowing with a string with 18 characters in the given example `base10` : The hash of a 18 character string with all `9`s in `base10` would be `9 999 999 999 999 999 999` which is is bigger than `Int64.max`. This is maybe too cautious, since some 18-character strings are still hashable using this hasher."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:25:29.650",
"Id": "403187",
"Score": "0",
"body": "@Carpsen90: But that is exactly what I said: You cannot detect a possible overflow based only on the string length (but you can detect it during the calculation). Of course you can be overly cautious and reject strings whose hashes *could* be computed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:25:33.057",
"Id": "403188",
"Score": "1",
"body": "Anyway: A review is always subjective. I have expressed my concerns and recommendations. You don't have to agree with all points."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T23:05:40.833",
"Id": "208653",
"ParentId": "208486",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208653",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T22:59:01.997",
"Id": "208486",
"Score": "1",
"Tags": [
"interview-questions",
"swift",
"hashcode"
],
"Title": "Hashing interview puzzle"
} | 208486 |
<h1>Introduction</h1>
<p>I decided to get my feet wet in Rust by going ahead an implementing a full crate with the tests, documentation, and all other accompanying stuff. This is a toy implementation of a library containing a function that checks whether a given <code>u64</code> is prime or not.</p>
<p>What I've also done is implement a <code>main.rs</code> in addition to the <code>lib.rs</code>, that produces an executable when the <code>cargo run</code> or <code>cargo build</code> command is issued. So far the toolchain hasn't complained yet. It seems to be working fine, but I seek adivce on the practicality of it.</p>
<h1>The organization</h1>
<p>Here is the full structure (excluding the <code>target</code> folder):</p>
<pre><code>prime
+- src
| +- lib.rs
| +- main.rs
| +- prime.rs
+- tests
| +- extern_test.rs
+- Cargo.lock
+- Cargo.toml
</code></pre>
<h1>The files</h1>
<h2><code>lib.rs</code></h2>
<pre><code>pub mod prime;
</code></pre>
<h2><code>main.rs</code></h2>
<pre><code>pub mod prime;
use std::env;
use std::io::stdin;
fn take_input() {
println!("Prime cheker utility.\n=====================\n");
loop {
process_single_line();
if user_wants_to_exit() {
break;
}
}
}
fn process_single_line() {
let mut num_str: String = String::new();
println!("Enter the number to check : ");
stdin().read_line(&mut num_str).unwrap();
process_string(num_str.trim());
}
fn user_wants_to_exit() -> bool {
let mut usr_str = String::new();
println!("Do you want to exit? (y/n) : ");
stdin()
.read_line(&mut usr_str)
.expect("Error while reading input.");
let trimmed = usr_str.trim();
trimmed == "y" || trimmed == "Y" || trimmed.to_lowercase() == "yes"
}
fn process_string(num_str: &str) {
let num = num_str.parse::<u64>().expect(INVALID_NUMBER);
println!(
"The integer {} is{} a prime.",
num,
match prime::is_prime(num) {
true => "",
false => " not",
}
);
}
const HELP_TEXT: &str = "USAGE:\n\n1. prime\n2. prime [unsigned integer]\n";
const INVALID_NUMBER: &str = "Please enter a valid unsigned integer.";
fn main() {
let args: Vec<String> = env::args().collect();
match args.len() {
1 => take_input(),
2 => process_string(args[1].trim()),
_ => {
println!("{}", HELP_TEXT);
}
}
}
</code></pre>
<h2><code>prime.rs</code></h2>
<pre><code>/// This function takes a 64-bit unsigned integer and checks if it is a prime.
///
/// If the number is prime, `true` is returned, and vice-versa.
///
/// #Example
///
/// ```rust
/// use prime_util::*;
///
/// let result = prime::is_prime(31);
/// assert_eq!(result, true);
/// ```
pub fn is_prime(num: u64) -> bool {
if num < 2 {
return false;
}
if num == 2 || num == 3 {
return true;
}
// Even numbers and multiples of 3 are eliminated
if num % 2 == 0 || num % 3 == 0 {
return false;
}
// Optimized divisor approach
// First we calculate the maximum limit of iteration
let limit = (num as f64).sqrt() as u64;
// We start the iteration from 5 (2 and 3 have been already tested)
let mut divisor = 5;
// The step alternates between 2 and 4 to keep the divisor of the form
// 6k +/- 1, where k is an integer
let mut step = 2;
while divisor <= limit {
if num % divisor == 0 {
return false;
}
divisor += step;
step = if step == 2 { 4 } else { 2 }
}
true
}
</code></pre>
<h2><code>extern_test.rs</code></h2>
<pre><code>extern crate prime_util;
#[cfg(test)]
mod integration_test {
use prime_util::prime;
#[test]
fn small_number_checks() {
assert_eq!(prime::is_prime(11), true);
assert_eq!(prime::is_prime(12), false);
assert_eq!(prime::is_prime(13), true);
}
#[test]
fn large_number_checks() {
assert_eq!(prime::is_prime(179434027), true);
assert_eq!(prime::is_prime(179434029), false);
assert_eq!(prime::is_prime(179434031), false);
assert_eq!(prime::is_prime(179434033), true);
}
#[test]
fn first_10_numbers_tested() {
assert_eq!(prime::is_prime(0), false);
assert_eq!(prime::is_prime(1), false);
assert_eq!(prime::is_prime(2), true);
assert_eq!(prime::is_prime(3), true);
assert_eq!(prime::is_prime(4), false);
assert_eq!(prime::is_prime(5), true);
assert_eq!(prime::is_prime(6), false);
assert_eq!(prime::is_prime(7), true);
assert_eq!(prime::is_prime(8), false);
assert_eq!(prime::is_prime(9), false);
assert_eq!(prime::is_prime(10), false);
}
}
</code></pre>
<h2>Others</h2>
<p>Cargo.toml is the default one. Nothing has been changed.</p>
<h2>Topics of interest</h2>
<p>I would like to point out some specific areas that I would like to hear advice on (although I always welcome comments on any aspect of the project):</p>
<ol>
<li>The fact that I have both <code>main.rs</code> and <code>lib.rs</code>. Cargo couldn't care less apparently. Because it executes all tests (even the documentation test) and also executes as a command-line program when <code>cargo run</code> is called (both with and without arguments).</li>
<li>The general quality of the code. I feel it can always be improved and made more <em>Rusty</em>.</li>
<li>The organization of the files and the containing code, and the documentation.</li>
<li>The external tests that I've included. Any additions/modifications necessary?</li>
</ol>
<p>I reiterate my invitation for general criticism as well.</p>
| [] | [
{
"body": "<p>First, instead of having your main in the root of src I would organize the project like this:</p>\n\n<pre><code>prime\n+- src\n| +- bin\n | +- main.rs\n| +- lib.rs\n| +- prime.rs\n+- tests\n| +- extern_test.rs\n+- Cargo.lock\n+- Cargo.toml\n</code></pre>\n\n<p>In your main.rs you would use your own crate like any other external crate (assuming the name of your lib is \"prime_util\" as it looks from your test file:</p>\n\n<h2>main.rs</h2>\n\n<pre><code>extern crate prime_util;\n\nuse std::env;\nuse std::io::stdin;\n\n...\n</code></pre>\n\n<p>Regarding code quality in general there are some un-idiomatic things there but nothing very serious, and definately some things that are just a matter of taste, like this part where you have a match statement as a parameter:</p>\n\n<pre><code>println!(\n \"The integer {} is{} a prime.\",\n num,\n match prime::is_prime(num) {\n true => \"\",\n false => \" not\",\n }\n);\n</code></pre>\n\n<p>I find that a bit hard to follow, and would either construct a string or have two different print statements based on the match, but I would say this is more a matter of taste than right/wrong.</p>\n\n<p>One thing that is something I really would look into is error handling. Your project is rather small and the only place your code can produce errors is in the application, and I would say it's OK to <code>unwrap()</code> or <code>expect()</code> there if you really mean that the error is unexpected and puts the program in an invalid state, but if you want the code to be as good as possible you would handle more error cases.</p>\n\n<p>I.e. If the user accidentally wrote <code>o</code> instead of <code>0</code> should the program really panic?</p>\n\n<p>Here's a small example with simple error handling, where you implement the simplest of error types with an enum. When you scale up you will see that this will make error handling quite a bit easier and the program much more robust:</p>\n\n<p>When you start working through like this you will also see that there are challenges with how you've split up the functions between <code>main</code> and <code>take_input</code>.</p>\n\n<p>But this is my opinion so take it for what it's worth. Hope it helps anyway :)</p>\n\n<h2>Main.rs (with some simple error handling)</h2>\n\n<pre><code>pub mod prime;\n\nuse std::env;\nuse std::io::stdin;\nfn take_input() {\n println!(\"Prime cheker utility.\\n=====================\\n\");\n loop {\n match process_single_line() {\n Err(e) => match e {\n MyError::InvalidDigit(msg) => {\n println!(\"{}\", msg);\n println!(\"Please try again\");\n },\n _ => break,\n },\n Ok(_) => (),\n }\n if user_wants_to_exit() {\n break;\n }\n }\n}\n\n#[derive(Debug)]\nenum MyError {\n InvalidDigit(String),\n // place your different errors here\n Other,\n}\n\nuse std::fmt;\nimpl fmt::Display for MyError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match self {\n MyError::InvalidDigit(msg) => write!(f, \"{}\", msg),\n MyError::Other => write!(f, \"Unexpected error\"),\n }\n }\n}\n\nimpl std::error::Error for MyError {}\n\nfn process_single_line() -> Result<(), MyError> {\n let mut num_str: String = String::new();\n\n\n println!(\"Enter the number to check : \");\n\n stdin().read_line(&mut num_str).unwrap();\n\n process_string(num_str.trim())\n}\n\nfn user_wants_to_exit() -> bool {\n let mut usr_str = String::new();\n\n println!(\"Do you want to exit? (y/n) : \");\n stdin()\n .read_line(&mut usr_str)\n .expect(\"Error while reading input.\");\n\n let trimmed = usr_str.trim();\n\n trimmed == \"y\" || trimmed == \"Y\" || trimmed.to_lowercase() == \"yes\"\n}\n\nfn process_string(num_str: &str) -> Result<(), MyError> {\n let num = num_str.parse::<u64>()\n .map_err(|_| MyError::InvalidDigit(format!(\"\\\"{}\\\" is not a valid digit.\", num_str)))?;\n\n println!(\n \"The integer {} is{} a prime.\",\n num,\n match prime::is_prime(num) {\n true => \"\",\n false => \" not\",\n }\n );\n Ok(())\n}\n\nconst HELP_TEXT: &str = \"USAGE:\\n\\n1. prime\\n2. prime [unsigned integer]\\n\";\nconst INVALID_NUMBER: &str = \"Please enter a valid unsigned integer.\";\n\nfn main() {\n let args: Vec<String> = env::args().collect();\n match args.len() {\n 1 => take_input(),\n 2 => {\n process_string(args[1].trim()).ok();\n },\n _ => {\n println!(\"{}\", HELP_TEXT);\n }\n }\n}\n</code></pre>\n\n<h2>Update</h2>\n\n<p>I created <a href=\"https://github.com/cfsamson/examples_codereview_prime\" rel=\"nofollow noreferrer\">this example repository</a> with some quick changes to project structure and code (mainly focusing on main.rs) to show some of the ideas I mentioned above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T14:03:39.887",
"Id": "406707",
"Score": "0",
"body": "Thanks for a really great answer! I'd really appreciate if you would illustrate how to write idiomatic code in this instance, for it would help me modify my style accordingly. Also, if it's not too much trouble, could you perhaps demonstrate how you would have split up the functions (or not at all?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T21:21:58.043",
"Id": "406799",
"Score": "0",
"body": "Shure. It's easier for me to just show you in a repo. See my updated asnwer or go directly to it here: https://github.com/cfsamson/examples_codereview_prime"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T21:25:46.423",
"Id": "406801",
"Score": "1",
"body": "I'll have to mention that I've spent limited time with this but I hope it shows some of the things I talked about above. That said. In a binary like this for only my own use I would unwrap() and not do proper error handling if it wasn't important if it's just a quick tool for me. But if I make it for someone else to use, and want it to be easy to expand later I would start out the way I show you here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T14:21:14.493",
"Id": "210363",
"ParentId": "208488",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "210363",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T23:15:00.887",
"Id": "208488",
"Score": "7",
"Tags": [
"beginner",
"primes",
"rust"
],
"Title": "A Rust crate with both `main.rs` and `lib.rs` performing primality checking"
} | 208488 |
<p>In a practice academic interview of mine, we discussed question six, round one, of the United Kingdom Mathematics Trust's 2015 British Mathematical Olympiad. Which states:</p>
<blockquote>
<p>A positive integer is called charming if it is equal to 2 or is of the form
3<sup>i</sup>5<sup>j</sup> where i and j are non-negative integers. Prove that every positive integer can be written as a sum of different charming integers.</p>
</blockquote>
<p>Having been able to successfully prove this, afterwards I then went on to implement, in Python, a program which can express any positive integer in terms of the sum of different charming numbers.</p>
<p>To do this I start by converting the integer into base 3 so that it is easier to find a charming number that is more than half the value of the original integer, but less than it. This value is then appended to a list, and the process is then repeated with the difference until left with either 1, 2, or 3. A list of charming numbers is then returned, which all sum to the original number.</p>
<p>I know this method works, simply as I used it somewhat in my proof.</p>
<p>I apologise in advance for the lack of comments.</p>
<pre><code>def to_base_3(base_10: int) -> str:
working_number = int(base_10)
output = ''
while True:
next_digit = working_number % 3
output = str(next_digit) + output
working_number = working_number // 3
if working_number == 0:
return output
def to_base_10(base_3: str) -> int:
output = 0
for i, char in enumerate(base_3[::-1]):
output += int(char) * (3 ** i)
return output
def find_charming_components(number: int, charming_components: list = None) -> list:
if charming_components is None:
charming_components = []
base_3_value = to_base_3(number)
digit = base_3_value[0]
component = 0
if len(base_3_value) == 1:
if digit != '0':
charming_components.append(int(digit))
return charming_components
if digit == '1':
component = to_base_10('1' + '0' * (len(base_3_value) - 1))
# Find the largest power of three that is lower than the current value. I.e: 3**4
charming_components.append(component)
# Append this charming number to the list of components
elif digit == '2':
component = to_base_10('12' + '0' * (len(base_3_value) - 2))
# Find the largest power of three times five that is lower than the current value. I.e: 3**4 * 5
charming_components.append(component)
# Append this charming number to the list of components
number -= component
# Repeat process with the difference
return find_charming_components(number, charming_components)
print(find_charming_components(int(input('Number: '))))
</code></pre>
<p>I just feel like doing a full base 3 conversion and back again isn't the most efficient method of doing this, and would appreciate some help on generally improving the algorithm.</p>
| [] | [
{
"body": "<p>Your <code>to_base_10(x)</code> function may be easily rewritten as:</p>\n\n<pre><code>def to_base_10(base_3):\n return int(base_3, 3)\n</code></pre>\n\n<p>However, you are only using the function to convert base 3 numbers of the forms <code>'1'</code> followed by <code>n</code> zeros, and <code>'12'</code> followed by <code>n</code> zeros. These can be directly computed as:</p>\n\n<ul>\n<li><code>to_base_10('1' + '0'*n)</code> --> <code>3 ** n</code></li>\n<li><code>to_base_10('12' + '0'*n)</code> --> <code>5 * 3**n</code></li>\n</ul>\n\n<hr>\n\n<p>The output of the <code>to_base_3(x)</code> function is only used to produce 2 values: <code>len(base_3_value)</code> and <code>digit = base_3_value[0]</code>. These can also be directly computed. </p>\n\n<pre><code>if number > 0:\n len_base_3_value = int(math.log(number, 3)) + 1\n digit = number // (3 ** (len_base_3_value - 1))\nelse:\n len_base_3_value = 1\n digit = 0\n</code></pre>\n\n<p>Note: <code>digit</code> is now an <code>int</code> (<code>0</code>, <code>1</code>, or <code>2</code>), not a <code>str</code> (<code>'0'</code>, <code>'1'</code>, or <code>'2'</code>)</p>\n\n<hr>\n\n<p>You recursively call and then return the value of <code>find_charming_components(number, charming_components)</code>. Python does not do tail recursion optimization, so this should be replaced with a simple loop, instead of recursion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T02:14:43.487",
"Id": "208496",
"ParentId": "208489",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code>def to_base_3(base_10: int) -> str:\n</code></pre>\n</blockquote>\n\n<p>Why <code>str</code>? I think it's simpler to use lists of digits.</p>\n\n<p><code>base_10</code> is a misleading name. It's an integer. It's actually in base 2 in just about every CPU this code will ever be run on.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def to_base_10(base_3: str) -> int:\n</code></pre>\n</blockquote>\n\n<p>Similarly: this is <code>from_base_3</code> to integer.</p>\n\n<blockquote>\n<pre><code> output = 0\n\n for i, char in enumerate(base_3[::-1]):\n output += int(char) * (3 ** i)\n\n return output\n</code></pre>\n</blockquote>\n\n<p>It's simpler to convert from a list of digits to an integer in big-endian order:</p>\n\n<pre><code>def to_base_10(base_3: str) -> int:\n output = 0\n\n for char in base_3:\n output = 3 * output + int(char)\n\n return output\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>def find_charming_components(number: int, charming_components: list = None) -> list:\n if charming_components is None:\n charming_components = []\n</code></pre>\n</blockquote>\n\n<p>Frankly this is ugly. I understand that you want to use <code>append</code> for efficiency, but it would be cleaner with an inner recursive method.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if digit == '1':\n component = to_base_10('1' + '0' * (len(base_3_value) - 1))\n # Find the largest power of three that is lower than the current value. I.e: 3**4\n charming_components.append(component)\n # Append this charming number to the list of components\n</code></pre>\n</blockquote>\n\n<p>I don't think I've ever seen comments after the code before, and it took me a while to work out what was going on.</p>\n\n<p>If you have closed form expressions, why call <code>to_base_10</code>?</p>\n\n<p>Also, surely it's \"no greater than\" rather than \"lower than\"?</p>\n\n<blockquote>\n<pre><code> elif digit == '2':\n</code></pre>\n</blockquote>\n\n<p>Why not just <code>else:</code>?</p>\n\n<blockquote>\n<pre><code> charming_components.append(component)\n</code></pre>\n</blockquote>\n\n<p>If the same code ends all the cases, it can be pulled out.</p>\n\n<hr>\n\n<p>At this point I have</p>\n\n<pre><code>def find_charming_components(number: int) -> list:\n charming_components = []\n\n def helper(n):\n base_3_value = to_base_3(n)\n digit = base_3_value[0]\n\n if len(base_3_value) == 1:\n if digit != 0:\n charming_components.append(digit)\n return\n\n component = 0\n if digit == 1:\n # Find the largest power of three that is no greater than the current value. E.g: 3**4\n component = 3 ** (len(base_3_value) - 1)\n else:\n # Find the largest power of three times five that is no greater than the current value. E.g: 3**4 * 5\n component = 5 * 3 ** (len(base_3_value) - 2)\n\n charming_components.append(component)\n # Repeat process with the difference\n helper(n - component)\n\n helper(number)\n return charming_components\n</code></pre>\n\n<p>Now, <code>helper</code> is clearly tail-recursive, so is easy to replace with a loop:</p>\n\n<pre><code>def find_charming_components(number: int) -> list:\n charming_components = []\n\n while number > 0:\n base_3_value = to_base_3(number)\n digit = base_3_value[0]\n\n if len(base_3_value) == 1:\n if digit != 0:\n charming_components.append(digit)\n break\n\n component = 0\n if digit == 1:\n # Find the largest power of three that is lower than the current value. E.g: 3**4\n component = 3 ** (len(base_3_value) - 1)\n else:\n # Find the largest power of three times five that is lower than the current value. E.g: 3**4 * 5\n component = 5 * 3 ** (len(base_3_value) - 2)\n\n charming_components.append(component)\n # Repeat process with the difference\n number -= component\n\n return charming_components\n</code></pre>\n\n<hr>\n\n<p>At this point, the remaining issue is the cost of the conversion to base 3. Observing the sequence of numbers, we can easily generate them and then filter:</p>\n\n<pre><code>def find_charming_components(number: int) -> list:\n candidates = [1, 2, 3]\n current = 3\n while current < number:\n candidates.extend([current // 3 * 5, current * 3])\n current *= 3\n\n charming_components = []\n for candidate in reversed(candidates):\n if number >= candidate:\n charming_components.append(candidate)\n number -= candidate\n\n return charming_components\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:42:55.623",
"Id": "208542",
"ParentId": "208489",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-26T23:29:37.820",
"Id": "208489",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"interview-questions",
"mathematics",
"integer"
],
"Title": "Expressing positive integers as the sum of different charming numbers"
} | 208489 |
<p>For plotting I often use a dictionary that contains my data of interest, regarding my numerical simulations. For example I have a <code>numpy array</code> let's call it <code>U</code> the contains a discretization of a equation in every simulation timestep. Simply put, my <code>U</code> is a 2D <code>np.array</code> where each row is a given timestep (first row first time step) and each column is a spatial discretization. For example:</p>
<pre><code>U = np.array([ [ 0, 0.25, 0.5, 0.25, 0 ],
[ 0.125, 0.225, 0.3, 0.225, 0.125 ],
[ 0.2, 0.2, 0.2, 0.2, 0.2] ])
</code></pre>
<p>Hence, U[0] is the initial positions, U<a href="https://i.stack.imgur.com/HpLeW.png" rel="nofollow noreferrer">1</a> is the first iteration, U<a href="https://i.stack.imgur.com/HViBh.png" rel="nofollow noreferrer">2</a> the last one, of course, is easy to get to thousands timesteps, lets move from here, since isn't important how <code>U</code> (or any simulation) is calculated.</p>
<p>Each simulation is packed in a "data structure" dictionary to guide the plotting, that contains some key information as: <code>x_data</code> spatial discretization, <code>y_data</code> functions evaluated in each point in spatial discretization in all time steps (The <code>U</code> above), data limits <code>x_lim</code>, <code>y_lim</code>, if I want to set them, <code>label</code> that is what <code>y_data</code> is related to, <code>title</code> a title to my graph, <code>linestyle</code> matplotlib linestyle, <code>color</code> color to plot this data. For example:</p>
<pre><code># These were pre-calculated somewhere else in code
V_x_support = np.linspace(...)
V_t_support = np.linspace(...)
V = np.array(...)
# Here starts the data to plot
ts_range = (0,3000,300) # I just want to pick some data to graph
V_dataplots = []
for pos in np.arange(*ts_range):
data = {
'x_data': V_x_support,
'y_data': V[pos],
'x_lim': [-1, 1],
'y_lim': [-1, 1],
'label': f'{V_t_support[pos]:.3g} s',
'title': f'{V_t_support[pos]:.3g} s',
'linestyle': '--',
'color': '.4',
}
</code></pre>
<p>Once I calculated some arrays, I would love to compare them using matplotlib, but I hate to repeat myself, hence I started to write functions to make the drawings, where I can just pass to my plot function</p>
<pre><code>fig = panelize(
data = [V_dataplots],
plot_function = single_plot,
title = 'V Mimetic 4th order',
labely='Velocity',
labelx='Position',
sharex=True,
sharey=True
)
</code></pre>
<p>This will pick my manually chosen positions in time and plot it in a panel. The function to do the panels and the plots are below.</p>
<p>How can I reduce the number o lines, keeping the code more cleaner and more readable while avoiding to repeat myself. There are any good MatPlotLib techniques to handle this?</p>
<p>First two examples of the image output</p>
<p><a href="https://i.stack.imgur.com/HpLeW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HpLeW.png" alt="single plot"></a></p>
<p><a href="https://i.stack.imgur.com/HViBh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HViBh.png" alt="compare plot"></a></p>
<pre><code># TODO:
# - If a panelized axes do not have associated data to plot it will
# not configure the axes and therefor will not be "prettified"
# need to fix this (or remove at all the not drawn plots).
#
# - Draw legend only if some plot has set a label, how to do this?
#
# - Make the font scale with less plots are drawn, less axes, bigger
# fonts.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import warnings
warnings.filterwarnings("ignore", category=mpl.MatplotlibDeprecationWarning)
def get_axes_diagonal(ax):
axes_limits = list(map(ax.transData.transform, zip(ax.get_xlim(), ax.get_ylim())))
return np.linalg.norm(axes_limits[1] - axes_limits[0])
def countour_every(ax, every, x_data, y_data,
color='black', linestyle='-', marker='o', **kwargs):
"""Draw a line with countour marks at each every points"""
ax_diag_size = get_axes_diagonal(ax)
diag_ratio = np.round(ax_diag_size/150, 1)
lw = .5*diag_ratio # line width
ms = 2*diag_ratio # Marker size
# Some variable parameters
every=int(len(x_data)/every)
line, = ax.plot(x_data, y_data, linestyle)
line.set_linewidth(lw)
line.set_color(color)
mark, = ax.plot(x_data, y_data, marker)
mark.set_markevery(every)
mark.set_markersize(ms)
mark.set_color('white')
contour, = ax.plot(x_data, y_data, marker)
contour.set_markevery(every)
contour.set_markersize(ms)
contour.set_color(color)
contour.set_fillstyle('none')
contour.set_markeredgewidth(lw)
return line
def prettify_axes(ax, data):
"""Makes my plot pretty"""
ax_diag_size = get_axes_diagonal(ax)
# Some variable parameters
diag_ratio = np.round(ax_diag_size/150, 1)
lw = .5*diag_ratio # line width
slw = 2*lw # spine line width
ln = 3*diag_ratio # Tick length
# Set spines
ax.spines['left'].set_linewidth(slw)
ax.spines['right'].set_linewidth(slw)
ax.spines['bottom'].set_linewidth(slw)
ax.spines['top'].set_linewidth(slw)
if 'x_label' in data:
ax.set_xlabel(data['x_label'])
if 'y_label' in data:
ax.set_ylabel(data['y_label'])
if 'title' in data:
ax.set_title(data['title'])
if 'y_lim' in data:
ax.set_ylim(data['y_lim'])
if 'x_lim' in data:
ax.set_xlim(data['x_lim'])
# Draw legend only if labels were set (HOW TO DO IT?)
# ax.get_legend_handles_labels() <-- maybe this can help
# if ax("has_some_label_set"):
ax.legend(loc='upper right', prop={'size': 6})
ax.title.set_fontsize(7)
ax.xaxis.set_tick_params(labelsize=6)
ax.xaxis.set_tick_params(width=lw)
ax.xaxis.set_tick_params(direction='in')
ax.xaxis.set_tick_params(length=ln)
ax.xaxis.set_tick_params(zorder=0)
ax.xaxis.label.set_size(7)
ax.yaxis.set_tick_params(labelsize=6)
ax.yaxis.set_tick_params(width=lw)
ax.yaxis.set_tick_params(direction='in')
ax.yaxis.set_tick_params(length=ln)
ax.yaxis.set_tick_params(zorder=0)
ax.yaxis.label.set_size(7)
def scale_loglog(ax, data):
"""Set a plot to loglog scale"""
def prettify_second_axes(ax):
ax_diag_size = get_axes_diagonal(ax)
# Some variable parameters
diag_ratio = np.round(ax_diag_size/150, 1)
lw = .5*diag_ratio # line width
slw = 2*lw # spine line width
ln = 3*diag_ratio # Tick length
ax.yaxis.set_tick_params(labelsize=6)
ax.yaxis.set_tick_params(width=lw)
ax.yaxis.set_tick_params(direction='in')
ax.yaxis.set_tick_params(length=ln)
ax.yaxis.set_tick_params(zorder=0)
ax.yaxis.set_tick_params(labelcolor='red')
ax.yaxis.label.set_size(7)
def compare_plot(ax, data):
"""Compare two plots and also gives the difference
optional:
show difference or not
difference axis independent or not
"""
ax_diag_size = get_axes_diagonal(ax)
line1 = countour_every(ax, 10, **data[0])
line2 = countour_every(ax, 10, **data[1])
if 'label' in data[0]:
line1.set_label(data[0]['label'])
if 'label' in data[1]:
line2.set_label(data[1]['label'])
ax2 = ax.twinx()
line3 = ax2.plot(
data[0]['x_data'],
data[0]['y_data']-data[1]['y_data'], '-',
color='red', alpha=.2, zorder=1, label='Diff')
prettify_axes(ax, data[0])
prettify_second_axes(ax2)
def single_plot(ax, data):
"""Plot a line data"""
if isinstance(data, (list,tuple)):
data = data[0]
ax_diag_size = get_axes_diagonal(ax)
line = countour_every(ax, 10, **data)
if 'label' in data:
line.set_label(data['label'])
prettify_axes(ax, data)
def panelize(data, plot_function,
title=None, labelx=None, labely=None,
sharex=False, sharey=False):
"""Put a group of data into a square panel"""
if isinstance(data[0], (list, tuple)):
ndata = len(data)
nplots = len(data[0])
else:
ndata = 1
nplots = len(data)
# Wider than taller
ncols = int(np.ceil(np.sqrt(nplots)))
nrows = int(np.ceil(nplots/ncols))
# Use grid instead subplots
fig, axes = plt.subplots(nrows, ncols, sharex=sharex, sharey=sharey)
# Calculate the panel distribution and size
max_width = 6
width_per_plot = max_width / ncols
height_ratio = 1
height_per_plot = height_ratio*width_per_plot
max_height = nrows*height_per_plot
fig.set_size_inches(max_width,max_height)
for n, (ax, d) in enumerate(zip(np.atleast_1d(axes).flatten(),zip(*data))):
plot_function(ax, d)
if title is not None:
fig.suptitle(title)
fig.set_tight_layout({'rect': [0, 0.03, 1, 0.95]})
else:
fig.set_tight_layout(True)
if sharex and labelx:
fig.text(0.5, 0.04, labelx, ha='center')
if sharey and labely:
fig.text(0.01, 0.5, labely, va='center', rotation='vertical')
return fig
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T00:58:17.747",
"Id": "208492",
"Score": "2",
"Tags": [
"python",
"matplotlib"
],
"Title": "Modularizing matplolib graphing based on a data dictionary"
} | 208492 |
<p>I've written a script in Python using multiprocessing to handle multiple process at the same time and make the scraping process faster. I've used locking within it to prevent two processes from changing its internal state. As I'm very new to implement locking within multiprocessing, I suppose there is room for improvement.</p>
<p>What the scraper does is collect the name, address and phone number of every coffee shop traversing multiple pages from Yellowpage listings.</p>
<pre><code>import requests
from lxml.html import fromstring
from multiprocessing import Process, Lock
link = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA&page={}"
itemstorage = []
def get_info(url,lock,itemstorage):
response = requests.get(url).text
tree = fromstring(response)
for title in tree.cssselect("div.info"):
name = title.cssselect("a.business-name span")[0].text
try:
street = title.cssselect("span.street-address")[0].text
except IndexError: street = ""
try:
phone = title.cssselect("div[class^=phones]")[0].text
except IndexError: phone = ""
itemstorage.extend([name, street, phone])
return printer(lock,itemstorage)
def printer(lock,data):
lock.acquire()
try:
print(data)
finally:
lock.release()
if __name__ == '__main__':
lock = Lock()
for i in [link.format(page) for page in range(1,15)]:
p = Process(target=get_info, args=(i,lock,itemstorage))
p.start()
</code></pre>
| [] | [
{
"body": "<h3>General Feedback</h3>\n\n<p>This code is fairly straight-forward and easy to read. There are only three functions and none of them extend beyond thirteen lines. If you really wanted more atomic functions you could abstract some functionality from <code>get_info</code>, for instance the code that parses each listing. </p>\n\n<p>The name <code>link</code> doesn’t feel as appropriate for a string literal that represents a URL as something like <code>url_template</code>. Also see the related section below about naming constants. </p>\n\n<p>The description was somewhat vague and didn’t specify whether each listing should correspond to an individual list within the returned list but if so, one could use <code>itemstorage.append()</code> instead of <code>itemstorage.extend()</code>.</p>\n\n<h3>Suggestions</h3>\n\n<p>While it isn’t a requirement, it is recommended that each function have a <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstring</a>. </p>\n\n<blockquote>\n <p><em>All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the <code>__init__</code> constructor) should also have docstrings.</em><sup><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p>Additionally, while constants aren’t really different than variables in python, idiomatically uppercase letters are used for the naming constants in python as well as many other languages. As was mentioned above, <code>url_template</code> feels more appropriate for the string currently named <code>link</code> so it may improve readability to use uppercase letters to signify that is a constant: <code>URL_TEMPLATE</code>.</p>\n\n<p><sup>1</sup><sub><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0257/</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-05T14:46:29.773",
"Id": "209078",
"ParentId": "208500",
"Score": "2"
}
},
{
"body": "<h1>Style</h1>\n<p>Please read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> and use a consistent style throughout your code:</p>\n<ul>\n<li>put a space after comas;</li>\n<li>use a linebreak after colons;</li>\n<li>use UPPERCASE names for constants…</li>\n</ul>\n<h1>Using locks</h1>\n<p>First off, <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Lock\" rel=\"nofollow noreferrer\">locks support the context manager protocol</a> and you can thus simplify your <code>printer</code> to:</p>\n<pre><code>def printer(lock, data):\n with lock:\n print(data)\n</code></pre>\n<p>which may not warant a method on its own.</p>\n<p>But most importantly, you say that</p>\n<blockquote>\n<p>I've used locking within it to prevent two processes from changing its internal state.</p>\n</blockquote>\n<p>but you're not changing any shared state at all. All you are doing with this lock is preventing outputs to be mismatched on the screen. Let's take a look at a modified version of your script: I’ve stored the process started so I can <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process.join\" rel=\"nofollow noreferrer\"><code>join</code></a> them and I print <code>itemstorage</code> after all computation is done.</p>\n<pre><code>if __name__ == '__main__':\n lock = Lock()\n processes = [\n Process(target=get_info, args=(link.format(page), lock, itemstorage))\n for page in range(1, 15)\n ]\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n print('itemstorage is', itemstorage)\n</code></pre>\n<p>This prints</p>\n<pre><code>[…actual results snipped…]\nitemstorage is []\n</code></pre>\n<p>This is because each process is operating on its own copy of <code>itemstorage</code> and nothing is done to retrieve data afterward. Instead, you should have your processes <code>return</code> the result and store them in <code>itemstorage</code> yourself. In fact, this very process is already implemented using <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map\" rel=\"nofollow noreferrer\"><code>multiprocessing.Pool.map</code></a>.</p>\n<h1>Simplifying element retrieval</h1>\n<p>Since you extract text from the dom 3 times per <code>title</code>, you can extract an helper function to simplify that task. Doing so, it will be even easier to build the return list using a list-comprehension:</p>\n<pre><code>def extract(element, descriptor, default=None):\n try:\n return element.cssselect(descriptor)[0].text\n except IndexError:\n if default is None:\n raise\n return default\n\n\ndef get_info(url):\n response = requests.get(url).text\n tree = fromstring(response)\n return [(\n extract(title, "a.business-name span"),\n extract(title, "span.street-address", ""),\n extract(title, "div[class^=phones]", ""),\n ) for title in tree.cssselect("div.info")]\n</code></pre>\n<p>This changes a bit the structure but I believe it is an improvement to better access the information. You can still use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable\" rel=\"nofollow noreferrer\"><code>itertools.chain.from_iterable</code></a> if need be to flatten the returned list.</p>\n<h1>Proposed improvements</h1>\n<pre><code>import itertools\nfrom multiprocessing import Pool\n\nimport requests\nfrom lxml.html import fromstring\n\n\nLINK = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA&page={}"\n\n\ndef extract(element, descriptor, default=None):\n try:\n return element.cssselect(descriptor)[0].text\n except IndexError:\n if default is None:\n raise\n return default\n\n\ndef get_info(url):\n response = requests.get(url)\n tree = fromstring(response.content)\n return [(\n extract(title, "a.business-name span"),\n extract(title, "span.street-address", ""),\n extract(title, "div[class^=phones]", ""),\n ) for title in tree.cssselect("div.info")]\n\n\nif __name__ == '__main__':\n pages_count = 14\n with Pool(processes=pages_count) as pool:\n urls = [LINK.format(page) for page in range(1, pages_count + 1)]\n itemstorage = pool.map(get_info, urls)\n for result in itertools.chain.from_iterable(itemstorage):\n print(result)\n</code></pre>\n<p>Note that I also changed the document parsing part. For one <code>lxml</code> is perfectly capable of handling <code>bytes</code> so you don't have to perform decoding yourself; for two decoding into a string blindly can lead to using an improper charset, which <code>lxml</code> can handle by looking into the appropriate <code>meta</code> tag.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-05T17:17:51.210",
"Id": "403996",
"Score": "0",
"body": "Always like to see your intervention @Mathias Ettinger. Very insightful. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-05T17:06:08.000",
"Id": "209087",
"ParentId": "208500",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209087",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T07:56:45.870",
"Id": "208500",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"locking",
"multiprocessing"
],
"Title": "Implementing lock within a Python script"
} | 208500 |
<p>The function receives a string containing a sentence. Its goal is to shorten every word in it to a length of 4 characters until the string is shorter than 38 characters and return. </p>
<p>The 38 characters max length is mandatory and must be reached with the least amount of deletion possible.</p>
<p>Here is what I've done:</p>
<pre><code># reduces each word to a lenght of 4
def shorten_words(string):
i = 0
j = 0
while(len(string) > 38 and i < len(string)):
array = list(string)
if(array[i] != ' ' and array[i] != '-'):
j += 1
else:
j = 0
if(j > 4):
array[i] = ''
i -= 1
i += 1
string = ''.join(array)
return(string)
</code></pre>
<p>I feel like the list/join method is inefficient and would like to know how I could improve this function</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T09:11:20.597",
"Id": "402689",
"Score": "2",
"body": "The post says, \"its goal is to shorten every word in it to a length of 4 characters\" but if the string is 38 characters or shorter, then the code returns the string unchanged. Could you fix the description of the problem please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T10:17:22.403",
"Id": "402691",
"Score": "0",
"body": "@GarethRees this has been done, thanks for letting me know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T18:36:03.733",
"Id": "402788",
"Score": "0",
"body": "What do you mean by \"least amount of deletion\" though? Is there a requirement that each word in the end should be as close in length as possible? If not the problem is much simpler."
}
] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li><strong>Naming</strong> is really important. <code>string</code>, <code>array</code>, <code>i</code> and <code>j</code> are not descriptive. After reading the entire function I <em>think</em> they could be renamed <code>sentence</code>, <code>words</code>, <code>string_index</code> and <code>word_length</code>.</li>\n<li>There's no point in adding empty strings to the array - they aren't printed anyway.</li>\n<li>What is the significance of 38? If it's not significant it should be removed, if it is it should be named something like <code>max_result_length</code>.</li>\n<li>In Python <code>return</code> is a <a href=\"https://docs.python.org/3/reference/simple_stmts.html\" rel=\"nofollow noreferrer\">simple statement</a>, which means its argument should not be put in parentheses.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T09:12:23.937",
"Id": "208506",
"ParentId": "208503",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T08:46:05.360",
"Id": "208503",
"Score": "1",
"Tags": [
"python",
"strings"
],
"Title": "Shortening words within a string"
} | 208503 |
<p>I created a where I select a video using <code>QOpenFileDialog</code> and play the video on <code>QGraphicsView</code>. After that I select an area on video using mouse and <code>QRubberBand</code> class and want to draw a rectangle on selected area when I release left mouse click.</p>
<p>Since I'm newbie can you tell me which parts of my code is bad practice, unoptimized etc.? Is there a way to do it more efficiently than what I already have?</p>
<p>Note: I tried using <code>QVideoWidget</code> but couldn't drive anything on it.</p>
<p><strong>mainwindow.h</strong></p>
<pre><code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCore>
#include <QtGui>
#include <QMediaPlayer>
#include <QFileDialog>
#include <QGraphicsScene>
#include <QGraphicsVideoItem>
#include <QSize>
#include "mygraphicsview.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_actionOpen_triggered();
private:
Ui::MainWindow *ui;
QGraphicsScene *scene;
QGraphicsVideoItem *videoItem;
QMediaPlayer* mediaPlayer;
};
#endif // MAINWINDOW_H
</code></pre>
<p><strong>mainwindow.cpp</strong></p>
<pre><code>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mediaPlayer = new QMediaPlayer(this);
videoItem = new QGraphicsVideoItem;
scene = new QGraphicsScene(this);
QSize videoSize = ui->graphicsView->size();
videoItem->setSize(videoSize);
ui->graphicsView->setScene(scene);
mediaPlayer->setVideoOutput(videoItem);
ui->graphicsView->scene()->addItem(videoItem);
ui->graphicsView->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionOpen_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this,"Select Video","","video Files (*.mp4)");
mediaPlayer->stop();
mediaPlayer->setMedia(QUrl::fromLocalFile(fileName));
mediaPlayer->play();
}
</code></pre>
<p><strong>mainwindow.ui</strong></p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1268</width>
<height>741</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralWidget">
<widget class="MyGraphicsView" name="graphicsView" native="true">
<property name="geometry">
<rect>
<x>20</x>
<y>20</y>
<width>848</width>
<height>480</height>
</rect>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1268</width>
<height>22</height>
</rect>
</property>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>File</string>
</property>
<addaction name="actionOpen"/>
</widget>
<addaction name="menuFile"/>
</widget>
<widget class="QToolBar" name="mainToolBar">
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
</widget>
<widget class="QStatusBar" name="statusBar"/>
<action name="actionOpen">
<property name="text">
<string>Open</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<customwidgets>
<customwidget>
<class>MyGraphicsView</class>
<extends>QWidget</extends>
<header>mygraphicsview.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
</code></pre>
<p><strong>myqgraphicsview.h</strong></p>
<pre><code>#ifndef MYGRAPHICSVIEW_H
#define MYGRAPHICSVIEW_H
#include <QObject>
#include <QWidget>
#include <QGraphicsView>
#include <QMouseEvent>
#include <QPainter>
#include <QRubberBand>
#include <QPoint>
#include <QDebug>
#include <QLabel>
class MyGraphicsView : public QGraphicsView
{
Q_OBJECT
public:
MyGraphicsView(QWidget *parent = nullptr);
protected:
void mouseMoveEvent(QMouseEvent *ev);
void mousePressEvent(QMouseEvent *ev);
void mouseReleaseEvent(QMouseEvent *ev);
void paintEvent(QPaintEvent *ev);
void getCoordinates(QPoint leftTop, QPoint rightBottom);
private:
QRubberBand *rubberBand;
QRect rect;
QPoint startPoint, endPoint;
};
#endif // MYGRAPHICSVIEW_H
</code></pre>
<p><strong>myqgraphicsview.cpp</strong></p>
<pre><code>#include "mygraphicsview.h"
MyGraphicsView::MyGraphicsView(QWidget *parent):
QGraphicsView (parent), rubberBand(nullptr){}
void MyGraphicsView::mousePressEvent(QMouseEvent *ev)
{
startPoint = ev->pos();
qDebug()<<"START POINT!: "<<startPoint;
if(!rubberBand)
rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
rubberBand->setGeometry(QRect(startPoint,QSize()));
rubberBand->show();
QGraphicsView::mousePressEvent(ev);
}
void MyGraphicsView::mouseMoveEvent(QMouseEvent *ev)
{
rubberBand->setGeometry(QRect(startPoint,ev->pos()).normalized());
QGraphicsView::mouseMoveEvent(ev);
}
void MyGraphicsView::mouseReleaseEvent(QMouseEvent *ev)
{
endPoint = ev->pos();
qDebug()<<"END POINT!: "<<endPoint;
rect = rubberBand->geometry();
rubberBand->hide();
update();
QGraphicsView::mouseReleaseEvent(ev);
}
void MyGraphicsView::paintEvent(QPaintEvent *ev)
{
QGraphicsView::paintEvent(ev);
QPainter painter(this->viewport());
painter.setBrush(QBrush(QColor(255,0,0,0)));
if(!rect.isNull()){
painter.drawRect(rect);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:17:41.797",
"Id": "402697",
"Score": "0",
"body": "This code doesn't compile: you're missing the definition of `Ui::MainWindow`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:26:07.407",
"Id": "402699",
"Score": "0",
"body": "@TobySpeight I just ran it on QT Creator and it compiles. Maybe its because I created the gui on gui designer ? Let me double check the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:27:59.543",
"Id": "402700",
"Score": "0",
"body": "Yes, include it in the editable form - i.e. the XML file, probably named with a `.ui` suffix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:31:45.630",
"Id": "402701",
"Score": "0",
"body": "@TobySpeight I added the **mainwindow.ui** can you check it now ?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T08:56:54.153",
"Id": "208504",
"Score": "1",
"Tags": [
"c++",
"qt"
],
"Title": "Drawing rectangle on a video with mouse in QT"
} | 208504 |
<p>I wrote this program just to remove duplicates from wordlist used for brute-force, but it can be used for every txt file i guess.
It is a pretty long program for what it does, and I'm sure there is a way I can make it easier and better for everyone to look at.
I'm still a beginner in python.</p>
<pre><code>def wordcount_initial(): # count the numbre of words in the input file
global num_words_initial
with open(file_initial, 'r') as f:
for line in f:
words = line.split()
num_words_initial += len(words)
def dupfilter():
content = open(file_initial, "r").readlines()
content_set = set(content) # filter duplicates
cleandata = open(file_final, "w+") # write the text filtered in the new file
for line in content_set:
cleandata.write(line)
def wordcount_final(): # count number of words in the new file
global num_words_final
with open(file_final, 'r') as f:
for line in f:
words = line.split()
num_words_final += len(words)
if __name__ == '__main__':
num_words = 0
num_words_initial = 0
num_words_final = 0
ready = False
while not ready:
file_initial = input("What is the name of the text?")
file_final = input("How do you want to name the filted file?")
if file_initial and file_final != "":
wordcount_initial()
ready = True
dupfilter()
wordcount_final()
print("Number of duplicates filtered:" + str(num_words_initial - num_words_final))
input("\nPress <ENTER> to quit the program.")
</code></pre>
| [] | [
{
"body": "<p><a href=\"https://www.python-course.eu/python3_global_vs_local_variables.php\" rel=\"noreferrer\">You should not use global variables unless you really need to</a>. Instead, pass relevant parameters as arguments to the functions and return the results. This makes them actually reusable. Currently you have two functions to count the initial and final number of words, when you could just have a <code>word_count</code> function:</p>\n\n<pre><code>def wordcount(file_name):\n \"\"\"count the number of words in the file\"\"\"\n with open(file_name) as f:\n return sum(len(line.split()) for line in f) \n\ndef dupfilter(file_initial, file_final):\n with open(file_initial) as in_file, open(file_final, \"w\") as out_file:\n out_file.writelines(set(in_file.readlines()))\n\nif __name__ == '__main__':\n while True:\n file_initial = input(\"What is the name of the text?\")\n file_final = input(\"How do you want to name the filtered file?\")\n if file_initial and file_final and file_initial != file_final:\n break\n\n num_words_initial = wordcount(file_initial)\n dupfilter(file_initial, file_final)\n num_words_final = wordcount(file_final)\n\n print(\"Number of duplicates filtered:\", num_words_initial - num_words_final)\n input(\"\\nPress <ENTER> to quit the program.\")\n</code></pre>\n\n<p>I also used <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"noreferrer\"><code>sum</code></a> with a <a href=\"https://medium.freecodecamp.org/python-list-comprehensions-vs-generator-expressions-cef70ccb49db\" rel=\"noreferrer\">generator expression</a> to simplify the <code>wordcount</code> function, used <a href=\"http://effbot.org/zone/python-with-statement.htm\" rel=\"noreferrer\"><code>with</code></a> to ensure that files are properly closed.\nIn addition, I replaced the <code>while not ready</code> loop with a <code>while True</code> loop and an explicit <code>break</code>. This is much more common in Python, especially for user input.</p>\n\n<p>Note that <code>if file_initial and file_final != \"\"</code> is only incidentally the same as <code>if file_initial != \"\" and file_final != \"\"</code> because non-empty strings are truthy. This is why it is also equivalent to <code>if file_initial and file_final</code>. But for example <a href=\"https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value\"><code>x and y == 3</code> is not the same as <code>x == 3 and y == 3</code></a>.</p>\n\n<p>You also don't need to call <code>str</code> on things to be printed, <code>print</code> does that for you if necessary.</p>\n\n<hr>\n\n<p>Note that using <code>set</code> does not guarantee the same order as the original file, for that you would want to use the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"noreferrer\"><code>itertools</code> recipe <code>unique_everseen</code></a>:</p>\n\n<blockquote>\n<pre><code>from itertools import filterfalse\n\ndef unique_everseen(iterable, key=None):\n \"List unique elements, preserving order. Remember all elements ever seen.\"\n # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n # unique_everseen('ABBCcAD', str.lower) --> A B C D\n seen = set()\n seen_add = seen.add\n if key is None:\n for element in filterfalse(seen.__contains__, iterable):\n seen_add(element)\n yield element\n else:\n for element in iterable:\n k = key(element)\n if k not in seen:\n seen_add(k)\n yield element\n</code></pre>\n</blockquote>\n\n<pre><code>def dupfilter(file_initial, file_final):\n with open(file_initial) as in_file, open(file_final, \"w\") as out_file:\n out_file.writelines(unique_everseen(in_file))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T13:43:56.527",
"Id": "402718",
"Score": "1",
"body": "Nice section on itertools instead of set!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:16:43.410",
"Id": "402751",
"Score": "1",
"body": "I didn't know that set could not give the same order when filtering the duplicate thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T13:17:44.223",
"Id": "208525",
"ParentId": "208508",
"Score": "7"
}
},
{
"body": "<p>Thanks for sharing your code!</p>\n\n<p>I'll begin by pointing out you don't need <code>global</code> variable, and you should avoid them when possible. Very often it only does make your code less readable and more fragile.</p>\n\n<p>Here your function <code>wordcount_initial</code> could be rewritten as: (same idea for <code>wordcount_final</code>)</p>\n\n<pre><code>def wordcount_initial(input_file):\n \"\"\"Return the number of words in the file given in parameter\n\n :param input_file: A file name\n :type input_file: string \n :return: The number of words in the file `input_file`\n :rtype: int\n \"\"\"\n num_words_initial = 0\n with open(input_file, 'r') as f:\n for line in f:\n words = line.split()\n num_words_initial += len(words)\n return num_words_initial\n</code></pre>\n\n<p>There are a few changes here:</p>\n\n<ul>\n<li>Removed <code>num_words_initial</code> as a global and return it's value at the end of the function. It's much more clean to return value that way when you can. It also help when you want to test your functions.</li>\n<li>Gives <code>input_file</code> as a parameter of your function instead of relying on another global. It makes your function more reusable.</li>\n<li>And I transformed your comment in docstring that can be used to generate documentation for your code. See <a href=\"http://docutils.sourceforge.net/rst.html#user-documentation\" rel=\"nofollow noreferrer\">ReStrusctured</a> and <a href=\"http://www.sphinx-doc.org/en/stable/index.html\" rel=\"nofollow noreferrer\">sphinx</a> for more information. Ideally every function should be documented (and every module too)</li>\n</ul>\n\n<p>Another remark, you name your function <code>dupfilter</code>, but every other name in your code has the format <code>first_last</code> which is a bit inconsistant. Also, don't try to gain a few letters when typing, write <code>duplicatefilter</code> or better (in my opinion) <code>filter_duplicate</code>.</p>\n\n<p>Naming is always a bit subjective, use your best judgement.</p>\n\n<p>And finally in your <code>__main__</code> you could have put the logic for initialising the name of the file into another function but that's not very important.</p>\n\n<p>On a more positive note I like how you laid out your code, it is well spaced, most of the name are clear when you read them and you have comment which is often important.</p>\n\n<p>Nice job!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:08:15.150",
"Id": "402742",
"Score": "0",
"body": "Thank a lot for your help i will try to apply all thoses advice to my futur programs!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T13:37:12.923",
"Id": "208528",
"ParentId": "208508",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "208525",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T09:46:11.650",
"Id": "208508",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"file"
],
"Title": "Text Duplicate filter in Python 3.7"
} | 208508 |
<p>I'm writing a application that reads from a queue of messages from a legacy mainframe system.</p>
<p>Some characteristics of message in the queue:</p>
<ul>
<li>Message from the Q is always fixed length plain text : 64 char length</li>
<li>Each index or group of index indicates some meaning full data</li>
<li>The first 20 chars represent first name, next 20 surname, character following that represents gender, then next 8 chars denote date in yyyyMMdd format</li>
</ul>
<p>I need to map these to Java objects. Here is the sample of what I'm doing.</p>
<pre><code>import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
@Slf4j
public class Solution {
public static void main(String[] args){
String input = "JOE BLOGG M19880101PX2018010199PNM";
log.info("Input length 64 = ",input.length());
log.info(empMapper(input).toString());
}
public static boolean boolMapper(char value){
return (value == 'Y') ? true:false;
}
public static LocalDate dateMapper(String value){
final String dateString = String.format("%s-%s-%s",value.substring(0,4),value.substring(4,6),value.substring(6));
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return LocalDate.parse(dateString, formatter);
}
public static Emp empMapper(String input){
final Emp emp = new Emp();
emp.setFirstName(input.substring(0,19).trim());
emp.setSurName(input.substring(19,39).trim());
emp.setGender(input.charAt(40));
emp.setDob(dateMapper(input.substring(41,49)));
emp.setEmpId(input.substring(49,61));
emp.setJobType(input.charAt(61));
emp.setShiftNeeded(boolMapper(input.charAt(62)));
emp.setEmpLevel(input.charAt(63));
return emp;
}
@Data
@NoArgsConstructor
public static class Emp{
private String firstName;
private String surName;
private char gender;
private LocalDate dob;
private String empId;
private char jobType;
private boolean shiftNeeded;
private char empLevel;
}
}
</code></pre>
<blockquote>
<p>Output: Emp(firstName=JOE, surName=BLOGG, gender=M, dob=1988-01-01,
empId=PX2018010199, jobType=P, shiftNeeded=false, empLevel=M)</p>
</blockquote>
<p>My question is there a better solution for doing this from a performance point of view</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:42:36.587",
"Id": "402764",
"Score": "0",
"body": "From a pure performance point of view replace `String.format(...)` with a [simple concatenation](https://redfin.engineering/java-string-concatenation-which-way-is-best-8f590a7d22a8). Note that on compiling concatenated Strings in the form of `String s = string1 + string2;` will result in the compiler using a [`StringBuilder`](https://stackoverflow.com/questions/11942368/why-use-stringbuilder-explicitly-if-the-compiler-converts-string-concatenation-t) anyway"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T21:00:13.110",
"Id": "402815",
"Score": "2",
"body": "Do you have any performance issue with your solution? *(You should never change a working solution for performance reasons unless you actually have a performance issue and **proven by measurement** that the code in question actually is the bottleneck **and** the alternative approach really solves the issue)*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T07:38:41.030",
"Id": "402852",
"Score": "2",
"body": "The only think that I see is the `dateMapper`. Why do you create another dash separated date wile you can parse the original one with ` DateTimeFormatter.ofPattern(\"yyyyMMdd \")` ?"
}
] | [
{
"body": "<p>Why is everything <code>static</code>? It's not necessarily wrong, but it may make integration into a larger project more ugly.</p>\n\n<p>EDIT: Some background to this: A static utility class makes other classes that depend on it difficult to use and test. It basically breaks the principal called <em><a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Inversion of control</a></em>. </p>\n\n<p>Instead of having a second class hard-code the reference to such a static \"employee factory\" like this, it is given an instance of a \"employee factory class\" (e.g. as a constructor argument). That way the \"employee factory\" can easily be replaced without touching the second class. </p>\n\n<p>This is especially interesting when you want to test that second class. In that case you don't need to worry about setting up the real \"employee factory\" and making sure that it works. Instead you can give the second class a so called mock class, that just simulates the workings of the \"employee factory\" and, for example, just returns hard-coded, predetermined employees.</p>\n\n<hr>\n\n<p>The conditional operator (<code>? :</code>) in <code>boolMapper</code> is unnecessary:</p>\n\n<pre><code>public static boolean boolMapper(char value){\n return value == 'Y';\n}\n</code></pre>\n\n<hr>\n\n<p>As @gervais.b says, formatting the date string to include the hyphens is unnecessary. You can parse the date directly with the pattern <code>yyyyMMdd</code>. Also you shouldn't create a new <code>DateTimeFormatter</code> instance in each method call. Instead use an instance stored in a static constant field:</p>\n\n<pre><code>private final static DateTimeFormatter EMPLOYEE_DATE_FORMATTER = DateTimeFormatter.ofPattern(\"yyyyMMdd\");\n\npublic static LocalDate dateMapper(String value){\n return LocalDate.parse(value, EMPLOYEE_DATE_FORMATTER);\n}\n</code></pre>\n\n<hr>\n\n<p>Don't unnecessarily abbreviate variable/class names. Use <code>Employee</code> instead of <code>Emp</code>, use <code>dateOfBirth</code> instead of <code>dob</code>, etc.</p>\n\n<hr>\n\n<p>Considering you are converting <code>dob</code> and <code>shiftNeeded</code> to \"proper\" Java types, you should consider also consider converting <code>gender</code>, <code>jobType</code> and <code>empLevel</code>, which you currently store as a <code>char</code>s, into something more Java-esk, eg. enumerations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T04:11:33.610",
"Id": "403056",
"Score": "1",
"body": "Why would everything being `static` potentially cause problems when integrating into a larger project?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T11:50:01.487",
"Id": "403092",
"Score": "0",
"body": "@Katie.Sun Good question. I've added an explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T12:43:35.927",
"Id": "403098",
"Score": "0",
"body": "Thanks for the explanation. Sorry to bug you again, but I'm just learning design patterns and wonder if you could give an example of *a \"employee factory class\" (e.g. as a constructor argument).*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:28:23.550",
"Id": "488942",
"Score": "0",
"body": "in real code it's not 'static' i made it for my sample code"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T11:09:07.263",
"Id": "208601",
"ParentId": "208512",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T10:12:52.503",
"Id": "208512",
"Score": "0",
"Tags": [
"java",
"performance",
"strings",
"parsing",
"lombok"
],
"Title": "Parsing messages with fixed-width fields into Employee objects"
} | 208512 |
<p>In this code, I generate the coordinates of a tube made of multiple rings. Finally, I write those x,y,z coordinates in a .csv file. I want to simplify this code (maybe using a for loop?).</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
bLength=1.6
numPoints=10
radius = bLength*numPoints / (2 * np.pi)
theta = np.linspace(0,2*np.pi,numPoints,endpoint=False)
dtheta=theta[1]-theta[0]
#creating the x, y coordinates of the first ring
x0,y0=(radius * np.cos(theta)), (radius * np.sin(theta))
#creating the x, y coordinates of the second ring
x1,y1=(radius * np.cos(theta+dtheta/2)) , (radius * np.sin(theta+dtheta/2))
#above first ring and second ring will come alternatively to form a tube.
#plt.plot(x0,y0)
#plt.show()
#plt.plot(x1,y1)
#plt.show()
#now generating the z-coordinate of the first ring, second ring, third ring, etc.
cons0=np.ones(x0.shape)*0
cons1=np.ones(x1.shape)*2
cons2=np.ones(x0.shape)*4
cons3=np.ones(x1.shape)*6
cons4=np.ones(x0.shape)*8
cons5=np.ones(x1.shape)*10
cons6=np.ones(x0.shape)*12
cons7=np.ones(x1.shape)*14
cons8=np.ones(x0.shape)*16
cons9=np.ones(x1.shape)*18
###Now saving the x, y, z coordinates in csv files.
np.savetxt('cooRing00.csv',np.c_[x0,y0,cons0],delimiter=' ',fmt='%10f')
np.savetxt('cooRing01.csv',np.c_[x1,y1,cons1],delimiter=' ',fmt='%10f')
np.savetxt('cooRing02.csv',np.c_[x0,y0,cons2],delimiter=' ',fmt='%10f')
np.savetxt('cooRing03.csv',np.c_[x1,y1,cons3],delimiter=' ',fmt='%10f')
np.savetxt('cooRing04.csv',np.c_[x0,y0,cons4],delimiter=' ',fmt='%10f')
np.savetxt('cooRing05.csv',np.c_[x1,y1,cons5],delimiter=' ',fmt='%10f')
np.savetxt('cooRing06.csv',np.c_[x0,y0,cons6],delimiter=' ',fmt='%10f')
np.savetxt('cooRing07.csv',np.c_[x1,y1,cons7],delimiter=' ',fmt='%10f')
np.savetxt('cooRing08.csv',np.c_[x0,y0,cons8],delimiter=' ',fmt='%10f')
np.savetxt('cooRing09.csv',np.c_[x1,y1,cons9],delimiter=' ',fmt='%10f')
###Now, I have the x, y, z coordinates in many files (based on the length of the tube I want.
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T15:48:36.417",
"Id": "404217",
"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 you should keep the most updated version in your question. Please see [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T18:30:50.993",
"Id": "404242",
"Score": "0",
"body": "Okay @SᴀᴍOnᴇᴌᴀ."
}
] | [
{
"body": "<p>Thanks for sharing your code.</p>\n\n<p>For the generation of your z-coordinate you can write something like:</p>\n\n<pre><code>def generate_z_coordinate(n, x0, x1):\n \"\"\"Generate the z-coordinate for the n first ring.\n :param n: the number of ring\n :param x0: x0 coordinate\n :param x1: x1 coordinate\n :return: A list of the z-coordinate for the n rings\n \"\"\"\n tmp = 0\n rings = []\n for i in range(0,n):\n if i % 2 == 0:\n x = x0\n else:\n x = x1\n rings.append(np.ones(x.shape) * tmp)\n tmp += 2\n return rings\n</code></pre>\n\n<p>I used <code>tmp</code> because I lack a better name, but there is probably a better way to name it.</p>\n\n<p>And saving in the csv:</p>\n\n<pre><code>def save(filename, rings, x0, y0, x1, y1):\n \"\"\"Save rings coordinate into filename\n :param filename: Name of the file to save data in\n :param rings: list of z-coordinate for the rings\n :param x0: x0 coordinate\n :param y0: y0 coordinate\n :param x1: x1 coordinate\n :param y1: y1 coordinate\n \"\"\"\n for i, elt in enumerate(rings):\n name = filename + str(i) + '.csv'\n if i % 2 == 0:\n x = x0\n y = y0\n z = rings[i]\n else:\n x = x1\n y = y1\n z = rings[i]\n\n np.savetxt(name, np.c_[x, y, z], delimiter=' ', fmt='%10f') \n</code></pre>\n\n<p>I am not sure it is more readable than your version but it's more scalable. Depend on what you need.</p>\n\n<p>Also try to be consistant in your code and follow Python style guide(see <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>):</p>\n\n<ul>\n<li>write <code>bLength = 1.6</code> instead of <code>bLength=1.6</code></li>\n<li><code>theta = np.linspace(0, 2 * np.pi, numPoints, endpoint=False)</code></li>\n</ul>\n\n<p>You can use <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">flake8</a> or <a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\">black</a> or <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">PyLint</a> to lint your code</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T13:40:52.197",
"Id": "403106",
"Score": "0",
"body": "I fixed the functions, is it working for you know?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T13:40:40.067",
"Id": "404190",
"Score": "0",
"body": "I fixed the generation of the filename try it again. Your filename was `cooRing00.csv` etc my function is more like `cooRing0.csv` (without the trailing 0 before the number, maybe that trigger the error? I cant find if savetext need the file to already exist"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T15:46:20.267",
"Id": "404215",
"Score": "0",
"body": "cooxyz.csv need to be a string, 'cooxyz.csv' and the function add csv automatically, try save(\"cooxyz\", rings, x0, y0, x1, y1)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T16:10:32.873",
"Id": "404218",
"Score": "0",
"body": "I added the change name = filename + str(i) + '.csv'. Still I get following error: save(cooxyz, rings, x0, y0, x1, y1)\nNameError: name 'cooxyz' is not defined"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T14:57:34.943",
"Id": "208535",
"ParentId": "208513",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T10:57:39.340",
"Id": "208513",
"Score": "1",
"Tags": [
"python",
"csv",
"numpy"
],
"Title": "Generate xyz coordinates of a tube made of multiple rings"
} | 208513 |
<p>I have read so many times that one should not subclass standard containers.
Is there cases that one can subclass them ?
for example, I have the following case:</p>
<pre><code>struct Materials
{
std::map<std::string, std::unique_ptr<Material>> materials;
void setFrom(const Database& db);
void echo(std::ostream&) const;
};
</code></pre>
<p>I want my materials class to act like a map, so I have to add methods like</p>
<pre><code>Material& getMaterial(std::string& key);
void addMaterial(std::string& key, Material& material);
</code></pre>
<p>which could have been avoided if I just sublcassed the container.</p>
<pre><code> struct Materials:public std::map<std::string, std::unique_ptr<Material>> materials;
{
void setFrom(const Database& db);
void echo(std::ostream&) const;
};
</code></pre>
<p>is this a horrible thing to do ? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T12:18:45.527",
"Id": "402706",
"Score": "3",
"body": "You seem to be asking about a practice in general — with this minimal excerpt serving merely as an example — rather than asking how your code should be improved. As per the [help/on-topic], that would make the question off-topic (and more appropriate for [softwareengineering.se] than Code Review). You could reframe the question as a good Code Review question by 1) posting a full class, including the implementation of `fromDatabase()`, 2) adding an example usage, 3) stating what task your code acccomplishes, and 4) retitling your question to state the task. See [ask]."
}
] | [
{
"body": "<p>Yes it is horrible.</p>\n\n<p>The only time where inheritance over composition makes any sense is when you want to take advantage of the empty baseclass optimization. A container is not a empty class.</p>\n\n<p>In a struct all fields are public so you don't need to public inherit anyway. </p>\n\n<p>None of the methods of the std containers are virtual so you cannot override them. Which in turn means you cannot prevent user code from invalidating any invariants you want to impose. This last is an issue with public member field as well.</p>\n\n<p>If you ever want to change containers to one with a different api you have to change all code dealing with the container part instead of only changing the type in the header and the implementation of the wrapper functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T12:25:13.597",
"Id": "208523",
"ParentId": "208514",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208523",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:00:23.373",
"Id": "208514",
"Score": "0",
"Tags": [
"c++"
],
"Title": "subclassing standard containers?"
} | 208514 |
<p>I have a question:</p>
<blockquote>
<p>Write a class that represents a sorted list of filenames. The filenames are sorted by most recently added first. Duplicates are not allowed.</p>
</blockquote>
<p>And I wrote this solution:</p>
<pre><code>public class RecentlyUsedList
{
private readonly List<string> items;
public RecentlyUsedList()
{
items = new List<string>();
}
public void Add(string newItem)
{
if (items.Contains(newItem))
{
int position = items.IndexOf(newItem);
string existingItem = items[position];
items.RemoveAt(position);
items.Insert(0, existingItem);
}
else
{
items.Insert(0, newItem);
}
}
public int Count
{
get
{
int size = items.Count;
return size;
}
}
public string this[int index]
{
get
{
int position = 0;
foreach (string item in items)
{
if (position == index)
return item;
++position;
}
throw new ArgumentOutOfRangeException();
}
}
}
</code></pre>
<p>Now, other person asked me, do the code review of your own code and tell the answers of following questions:</p>
<blockquote>
<p>Three operations are required:</p>
<ul>
<li><p>How long is the list?</p></li>
<li><p>Access filename at a given position</p></li>
<li><p>Add a filename to the list; if it already exists in the list it gets moved to the top otherwise the new filename is simply prepended to the
top.</p></li>
</ul>
</blockquote>
<p>I got confused and tried to look on Google but I didn't get much from there. What would be the best answers to these questions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T12:42:04.323",
"Id": "402714",
"Score": "1",
"body": "Your class supports all three operations, so what exactly are you confused about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T14:15:35.747",
"Id": "402727",
"Score": "0",
"body": "@Iztoksson Commenting on the use of whitespace would be a legitimate point for an answer. Changes to the code in the question, especially by people other than the OP, are rarely a good idea here on Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:00:48.847",
"Id": "402739",
"Score": "0",
"body": "What version of C# are you using? Given 6.0+, there are a number of language opportunities here."
}
] | [
{
"body": "<p>Empty lines as separation around code lines that are related are always a good idea. Your code has a little too much empty lines where it is not common in C# (or C/C++, Java, JavaScript):</p>\n\n<pre><code>public class RecentlyUsedList\n\n{\n</code></pre>\n\n<p>This in fact decreases readability. Instead just write:</p>\n\n<pre><code>public class RecentlyUsedList\n{\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> private readonly List<string> items;\n\n public RecentlyUsedList()\n\n {\n\n items = new List<string>();\n\n }\n</code></pre>\n</blockquote>\n\n<p>Here the constructor is not necessary. Just do:</p>\n\n<pre><code>private readonly List<string> items = new List<string>();\n</code></pre>\n\n<hr>\n\n<p>Your <code>Add(...)</code> method can be simplified to this:</p>\n\n<pre><code> public void Add(string newItem)\n {\n items.Remove(newItem);\n items.Insert(0, newItem);\n }\n</code></pre>\n\n<p><code>items.Remove(newItem)</code> just returns false, if the item is not present, so it's safe to use in any case. There is no need to be concerned about the existing string because it is the same as the <code>newItem</code>.</p>\n\n<hr>\n\n<p><code>public int Count...</code> can be simplified to:</p>\n\n<pre><code>public int Count => items.Count;\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>List<string> items</code></p>\n</blockquote>\n\n<p>has an indexer it self, so you can use that when implementing the indexer:</p>\n\n<pre><code> public string this[int index]\n {\n get\n {\n if (index < 0 || index >= items.Count)\n {\n throw new ArgumentOutOfRangeException();\n }\n return items[index];\n }\n }\n</code></pre>\n\n<p>Here I throw an exception if the <code>index</code> argument is out of range. You could let <code>items</code> handle that as well...</p>\n\n<p>In fact your <code>foreach</code>-loop is potentially much slower than the <code>List<T>[index]</code> because you make a kind of search where <code>List<T>[index]</code> just performs a look up. So you hide an efficient behavior with a not so efficient one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:07:34.803",
"Id": "208537",
"ParentId": "208515",
"Score": "11"
}
},
{
"body": "<p>In addition to Henrik Hansen's excellent answer, I'll add a note about encapsulation.</p>\n\n<p>Your class is currently acting as a wrapper around a List, hiding that list from public view. The only way for other actors to access that list is through your <code>Add</code>, <code>Count</code>, and indexer methods. This is a good thing, because it allows you to enforce the guarantee that the order of the elements in the list will be meaningful.</p>\n\n<p>The danger that I see is this: Perhaps in the future someone will want to iterate through this List and, having no way to do that, will simply pop in and make your private List into a protected, internal, or even public List. This will break the encapsulation, and you will no longer be able to guarantee that the order of elements is meaningful: an external class with a reference to the list itself will be able to add and remove elements at will.</p>\n\n<p>For that reason, I would <em>consider</em> implementing <code>IEnumerable<string></code> on your class. It can be as simple as adding these two lines:</p>\n\n\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public IEnumerator<string> GetEnumerator() => items.GetEnumerator();\npublic IEnumerator GetEnumerator() => this.GetEnumerator();\n</code></pre>\n\n<p>Now, adding this behavior before it's actually required is toying with <a href=\"https://martinfowler.com/bliki/Yagni.html\" rel=\"noreferrer\">YAGNI</a>, so you should consider carefully before you do so. But, you may find that it's a good idea and a good fit for your class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T17:00:50.120",
"Id": "208548",
"ParentId": "208515",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "208537",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T11:08:29.447",
"Id": "208515",
"Score": "6",
"Tags": [
"c#",
"sorting"
],
"Title": "Writing a class that represents a sorted list of filenames"
} | 208515 |
<p>I am trying to fill missing values with linearly interpolated values in an <code>Rcpp::NumericVector</code> -- leaving in place leading and trailing NA-values. </p>
<p>The desired output is below: </p>
<pre><code>R> x <- c(NA, NA, NA, 1:4, NA, 6:8, NA, 10, NA, NA, NA)
R> naLinInt(x)
R> [1] NA NA NA 1 2 3 4 5 6 7 8 9 10 NA NA NA
</code></pre>
<p>I've implemented it via the below, but as i am very new to C++ i'd very much benefit from some help in understanding how to do this better. </p>
<p>I feel that i've really hacked my way through this -- in particular i suspect i've over-used pointers and that there's a better way to do this sort of indexing and offsetting. </p>
<pre><code>#include<Rcpp.h>
//[[Rcpp::export]]
Rcpp::NumericVector naLinInt(Rcpp::NumericVector x) {
// This function linearly interpolates between NA values
Rcpp::Rcout << "We begin with: " << std::endl << x << std::endl;
double * it1 = x.begin();
double * it2 = x.begin();
int step = 0;
it1++;
while( it1 < x.end() ) {
if( Rcpp::NumericVector::is_na(*it1)) {
if( Rcpp::NumericVector::is_na(*(it1 - 1))) {
it1++;
continue;
} else {
it2 = it1;
step = 0;
while(it2 < x.end() && Rcpp::NumericVector::is_na(*it2)) {
step++;
it2++;
}
if( it2 == x.end()) break;
// step through missing values and replace
for(int j = 0; j < step; j++) {
*it1 = *(it1 - 1) + (*it2 - *(it1 - 1))/(step + 1 - j);
it1++;
}
it1 = it2 + 1;
}
} else {
it1++;
}
}
return x;
}
</code></pre>
| [] | [
{
"body": "<p>As you suggest, the code does look very \"pointery\". I think it might be made clearer with use of some standard algorithms:</p>\n\n<ul>\n<li><code>std::adjacent_find()</code> (with suitable predicate functions) to find a number followed by NA, or a NA followed by a number.</li>\n<li><code>std::generate()</code> (with suitable generator function) to populate a series of values from one iterator to another.</li>\n</ul>\n\n<p>With those, you won't need any arithmetic on iterators other than a subtraction to find the number of elements you're interpreting.</p>\n\n<hr>\n\n<p>The form of such a solution is something like this (untested):</p>\n\n<pre><code>#include <Rcpp.h>\n#include <algorithm>\n\nconstexpr auto is_na = Rcpp::NumericVector::is_na;\n\n//[[Rcpp::export]]\nRcpp::NumericVector naLinInt(Rcpp::NumericVector x) {\n // This function linearly interpolates to fill sequences of NA\n // values surrounded by valid numbers.\n static auto const detect_start_na = [](auto a, auto b){\n return !is_na(a) && is_na(b);\n };\n static auto const detect_end_na = [](auto a, auto b){\n return is_na(a) && !is_na(b);\n };\n\n auto start = x.begin();\n\n while (true) {\n // Find transitions to and from NA values. If we hit end of\n // vector whilst looking, our work is done.\n auto num_to_na = std::adjacent_find(start, x.end(), detect_start_na);\n auto na_to_num = std::adjacent_find(start, x.end(), detect_end_na);\n if (na_to_num == x.end()) {\n break;\n }\n\n // At this point, num_to_na points to the last number before\n // an interpolation block, and na_to_num points to the last NA\n // of that block.\n\n ++na_to_num; // Now, both iterators point to numbers.\n auto const base = *num_to_na;\n auto const target = *na_to_num;\n\n // To count rails rather than posts, measure difference before\n // incrementing the start position.\n auto const gaps = std::distance(na_to_num, num_to_na);\n\n ++num_to_na;\n // Now both iterators point immediately *after* transition.\n\n auto const make_value = [base, target, gaps, i = std::size_t{0}]()\n mutable { return base + (++i * (target - base) / gaps); };\n std::generate(na_to_num, num_to_na, make_value);\n\n // Advance onwards\n start = na_to_num;\n }\n\n return x;\n}\n</code></pre>\n\n<p>There are a couple of iterator increments there (because <code>std::adjacent_find</code> returns an iterator to the first of the matching pair), but there's quite a lot less arithmetic than the original. </p>\n\n<p>Although this is longer than the original, much of the difference is the comments that help the reader understand how the state changes through the loop. That's something that I think is an improvement (though perhaps the terms \"rails\" and \"posts\" require a link to a definition of <a href=\"https://en.wikipedia.org/wiki/Off-by-one_error#Fencepost_error\" rel=\"nofollow noreferrer\">fencepost error</a> for the uninitiated).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T18:12:13.963",
"Id": "402780",
"Score": "0",
"body": "Great review. One could also use `std::distance`, but I guess it will get too verbose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T18:13:55.240",
"Id": "402781",
"Score": "1",
"body": "Hi @Incomputable - I did show `std::distance` in the worked example; just didn't feel the need to pick it out as something that makes the code _clearer_ (because I think that's more arguable than the things from `<algorithm>`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T13:17:09.207",
"Id": "402898",
"Score": "0",
"body": "i get the below error when i try to run the code ... `naLinInt.cpp:51:16: error: constexpr function's return type '(lambda at naLinInt.cpp:53:12)' is not a literal type\nconstexpr auto na_transition(bool reverse)\n ^\nnaLinInt.cpp:53:12: note: '' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors\n return [reverse](auto a, auto b){\n ^\n1 error generated.\nmake: *** [naLinInt.o] Error 1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T13:22:25.177",
"Id": "402899",
"Score": "0",
"body": "I guess you're using an older C++ than me, @ricardo. Probably best to simply inline suitable definitions into the `naLinInt()` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T13:29:47.280",
"Id": "402900",
"Score": "0",
"body": "I've changed the code to a simpler C++14-compliant version that should be easier to work with."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T11:56:57.470",
"Id": "403093",
"Score": "0",
"body": "@TobySpeight I just realised that your code returns values with the wrong sign. So `X = nan nan nan 1 2 3 4 nan 6 7 8 nan 10 nan nan nan => [1] NA NA NA 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 NA NA NA`. I'm too new to this to figure out why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T12:41:10.503",
"Id": "403097",
"Score": "0",
"body": "@TobySpeight I figured part of it out. the last function is the wrong way about. It should be `target + (++i * (base - target)`. But that still leaves it out by one. So `X = nan nan nan 1 2 3 4 nan 6 7 8 nan 10 nan nan nan` => [1] NA NA NA 2 3 4 5 6 7 8 9 10 11 NA NA NA`. I'm tempted to just subtract one, but that's obv not a good strategy until i fully understand why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T12:44:34.017",
"Id": "403099",
"Score": "0",
"body": "Ah, I meant to write `base + (++i * ...)` there. I did state that it was *untested*!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:19:13.507",
"Id": "208544",
"ParentId": "208526",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T13:21:24.977",
"Id": "208526",
"Score": "1",
"Tags": [
"c++",
"rcpp"
],
"Title": "linearly interpolate NA values in Rcpp::NumericVector"
} | 208526 |
<p>If you split a string like <code>foobar</code> with something like <code>[::3], [1::3], [2::3]</code> it will give you <code>['fb','oa','or']</code>. I needed to then be able to rejoin that into <code>foobar</code> and I got given a challenge to make it in one line. This is my solution:</p>
<pre><code>split_join = lambda t:''.join(''.join([s.ljust(len(max(t,key=len))) for s in t])[i::len(max(t,key=len))] for i in range(len(max(t,key=len)))).replace(' ','')
</code></pre>
<p>and I was wondering if there was any neater or shorter way to make this.</p>
<p>EDIT: I also want it to be able to deal with strings of uneven lengths</p>
| [] | [
{
"body": "<p>First, in order to make this even remotely readable, let's convert it to a function and save intermediate results (especially the reused ones) to variables:</p>\n\n<pre><code>def split_join6(table):\n cols = max(map(len, table))\n justified = ''.join([col.ljust(cols) for col in table])\n y = ''.join(justified[i::cols] for i in range(cols))\n return y.replace(' ','')\n</code></pre>\n\n<p>Now, what you seem to want is similar to the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>roundrobin</code> recipe from <code>itertools</code></a>:</p>\n\n<blockquote>\n<pre><code>from itertools import cycle, islice\n\ndef roundrobin(*iterables):\n \"roundrobin('ABC', 'D', 'EF') --> A D E B F C\"\n # Recipe credited to George Sakkis\n num_active = len(iterables)\n nexts = cycle(iter(it).__next__ for it in iterables)\n while num_active:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n # Remove the iterator we just exhausted from the cycle.\n num_active -= 1\n nexts = cycle(islice(nexts, num_active))\n</code></pre>\n</blockquote>\n\n<pre><code>x = ['fb','oa','or']\nprint(\"\".join(roundrobin(*x))\n# foobar\n</code></pre>\n\n<p>Note that making things into one-liners can only get you so far. It does sometimes help you to learn some new concepts in a language, but quite often it makes your code unreadable. In Python you should keep your lines to 80 or 120 characters (as per Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>). Anything that does not fit into that is probably too complicated to understand again, even a month later.</p>\n\n<p>That being said, here is a shorter one-liner, albeit with one needed import:</p>\n\n<pre><code>from itertools import zip_longest\n\nf = lambda x: \"\".join(map(lambda t: \"\".join(filter(None, t)), zip_longest(*x)))\n\nf(['fb','oa','or'])\n# 'foobar'\n</code></pre>\n\n<p>The <code>zip_longest</code> and <code>filter(None, ...)</code> are only needed in case not all parts are the same length. Otherwise (which is at least true for <code>\"foobar\"</code>) it would just be:</p>\n\n<pre><code>f = lambda x: \"\".join(map(\"\".join, zip(*x)))\n</code></pre>\n\n<p>Both use the well-known trick of doing <code>zip(*iterable)</code> to transpose an iterable of iterables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:56:10.900",
"Id": "402756",
"Score": "0",
"body": "Thanks you for bringing my attention to the zip function, really neat"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:20:03.877",
"Id": "208538",
"ParentId": "208536",
"Score": "2"
}
},
{
"body": "<p>Using what @Graipher said and some other things I found my new solution is:</p>\n\n<pre><code>split_join = lambda t:''.join(sum(zip(*[s.ljust(len(max(t,key=len))) for s in t]),())).replace(' ','')\n</code></pre>\n\n<p>If I find any better way I will update this code</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T19:00:17.307",
"Id": "208559",
"ParentId": "208536",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "208538",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T15:05:22.647",
"Id": "208536",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "Join strings split with the python [::n] method into one string as they were before in one line"
} | 208536 |
<p>Is there a shorter way to write this?</p>
<pre><code>discounted_price = original_ticket_price - discount_value
if discounted_price < 0:
discounted_price = 0
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:03:55.740",
"Id": "402757",
"Score": "1",
"body": "Why would you want a shorter way to write it if you don't mind? Are you golfing or something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:12:59.690",
"Id": "402759",
"Score": "0",
"body": "What's the connection to golfing? I just want to learn it the best, shortest way. Thought there might be a better way to write it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:19:09.940",
"Id": "402760",
"Score": "0",
"body": "It's just that usually when people ask for the shortest way to write something it's for [code golf](https://en.wikipedia.org/wiki/Code_golf)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:40:58.107",
"Id": "402763",
"Score": "1",
"body": "Ahh, never heard of that. No, I actually just try to learn it the 'right' way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:50:25.047",
"Id": "402766",
"Score": "0",
"body": "Keep asking question then ;) Next time you post here, copy a more sizeable snippet of code, feedbacks will be way more interesting."
}
] | [
{
"body": "<p>Python has a syntax for ternary since 2.5. </p>\n\n<p>Syntax for it is <code>a if condition else b</code>, where condition is Truthy or Falsy( see Graipher comment). </p>\n\n<p>You can rewrite your code like:</p>\n\n<pre><code>discounted_price = original_ticket_price - discount_value\ndiscounted_price if discounted_price >= 0 else 0\n</code></pre>\n\n<p>Personnaly I find it harder to read but it is another way to write your code.</p>\n\n<p>EDIT you can find more info on ternary in this <a href=\"https://stackoverflow.com/a/394814/3729797\">SO post</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T17:24:39.797",
"Id": "402772",
"Score": "1",
"body": "`condition` does not have to be a boolean (`True` or `False`), a truthy or falsy value is sufficient (`[0]` and `[]` also work), as almost always in Python."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:22:28.780",
"Id": "208545",
"ParentId": "208543",
"Score": "3"
}
},
{
"body": "<p>Use the built-in <a href=\"https://docs.python.org/3/library/functions.html#max\" rel=\"noreferrer\"><code>max()</code></a> function:</p>\n\n<pre><code>discounted_price = max(0, original_ticket_price - discount_value)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:55:45.113",
"Id": "208546",
"ParentId": "208543",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "208546",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:00:26.993",
"Id": "208543",
"Score": "0",
"Tags": [
"python"
],
"Title": "Set discounted ticket price, with a floor of 0"
} | 208543 |
<p>I recently learned quick sort through <a href="https://www.geeksforgeeks.org/quick-sort/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/quick-sort/</a> but found it hard to follow. So, from what I understand wrote the following program. </p>
<pre><code>#include <stdio.h>
void quick_sort(int[],int,int);
int main(){
int arr[100];
int n;
printf("Enter the elements :");
scanf("%d",&n);
for(int i = 0 ; i < n ; i++){
printf("%d:",i+1);
scanf("%d",&arr[i]);
}
int arr_size = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i < n; i++){
printf("%d ",arr[i]);
}
printf("\n");
quick_sort(arr,0,n - 1);
for(int i = 0; i < n; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
void quick_sort(int arr[],int pivot_, int right_){
//Base condtion.
if(pivot_ == right_ )//pivot = left = right == no more check
return;
int i ;
int pivot, left ,right;
pivot = pivot_;//first element...
right = right_;//last element...
left = pivot + 1; // second element.
int middle;
while( left <= right ){
if(arr[left] >= arr[pivot]){
if(arr[right] <= arr[pivot]){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
right --;
left ++;
}else{
right --; // left > pivot but right !< pivot
}
}else{
left ++;// left is not > pivot.
}
}
i = pivot + 1;
while(arr[i] < arr[pivot]) i++;
i--; // last smaller value than pivot encountered.
middle = i; // swappppppp..
int temp = arr[pivot];
arr[pivot] = arr[i];
arr[i] = temp;
// now left of i is less than pivot and right of is greater than pivot.
quick_sort(arr,0,middle);
quick_sort(arr,middle + 1,right_);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T19:43:33.940",
"Id": "402806",
"Score": "0",
"body": "Minor: Consider a spell checker `//Base condtion.` --> `condition`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T03:16:04.397",
"Id": "402845",
"Score": "0",
"body": "I rolled back your edit. In this exchange you should not edit question after it has been answered, because it invalidates the answer."
}
] | [
{
"body": "<p>1) where is the 'compare' function? 2) The prototype for the quicksort() function is missing that parameter </p>\n\n<p>the posted code, (at best) can only handle an array of integers. I.E. it will not handle an array of struct nor an array of strings, etc.</p>\n\n<p>regarding: printf(\"Enter the elements :\"); scanf(\"%d\",&n); this fails to inform the user that the first number to be entered is actually the number of following numbers.</p>\n\n<p>the code does not work!</p>\n\n<p>Here is a typical run of the posted code:</p>\n\n<pre><code>Enter the elements :3\n1:3\n2:2\n3:1\n3 2 1 \n</code></pre>\n\n<p>Then the posted code maxes out a CPU and never gets done with the sorting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T01:37:26.910",
"Id": "402835",
"Score": "0",
"body": "Thanks, I found out that if the input is in the sorted form either ascending or descending it. It doesn't work:-'(..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T01:48:18.530",
"Id": "402840",
"Score": "0",
"body": "and now updated code `if (pivot_ >= right_)` solves problem."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T18:20:44.027",
"Id": "208552",
"ParentId": "208547",
"Score": "1"
}
},
{
"body": "<p>This is the kind of function that benefits from unit tests. I wrote a few simple tests in C++ with GoogleTest:</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>extern \"C\" {\n void quick_sort(int arr[],int pivot_, int right_);\n}\n\n#include <gtest/gtest.h>\n\n#include <algorithm>\n#include <iterator>\n#include <numeric>\n\nTEST(quick_sort, empty)\n{\n int a[1] = {};\n quick_sort(a, 0, 0-1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, one_element)\n{\n int a[] = { 0 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, two_same)\n{\n int a[] = { 0, 0 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, two_asc)\n{\n int a[] = { 0, 1 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, two_desc)\n{\n int a[] = { 1, 0 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, three_123)\n{\n int a[] = { 1, 2, 3 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, three_231)\n{\n int a[] = { 2, 3, 1 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, three_312)\n{\n int a[] = { 3, 1, 2 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, four)\n{\n int a[] = { 3, 1, 2, 0 };\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n\nTEST(quick_sort, large)\n{\n int a[100];\n std::iota(std::rbegin(a), std::rend(a), -50);\n quick_sort(a, 0, sizeof a / sizeof a[0] - 1);\n EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));\n}\n</code></pre>\n\n<p>The first thing this highlighted was the unusual calling convention - <code>right_</code> is an inclusive bound, but without any guidance, most C coders would expect an exclusive bound.</p>\n\n<p>(In passing, I'll also point out that <code>pivot_</code> isn't very meaningful to most callers - I think that <code>left</code> would be a better choice of name there.)</p>\n\n<p>The second thing we see (diagnosed by running under Valgrind) is undefined behaviour when we run off the end of the array here:</p>\n\n<pre><code> while(arr[i] < arr[pivot]) i++;\n</code></pre>\n\n<p>That needs to be fixed before this code is ready.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T19:42:38.907",
"Id": "402805",
"Score": "0",
"body": "Good detection of `quick_sort(a, 0, 0);` failure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T01:42:46.120",
"Id": "402836",
"Score": "0",
"body": "Thanks. for pointing out `quick_sort(a, 0, 0);` case. now I updated my question.problem was in BASE CONDITION `if(pivot_ >= right_){/...}` solves the problems..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T01:50:46.887",
"Id": "402841",
"Score": "0",
"body": "in the last 231 condition I think there should be expected = {1,2,3};"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T18:53:18.537",
"Id": "208558",
"ParentId": "208547",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208558",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T16:58:18.190",
"Id": "208547",
"Score": "0",
"Tags": [
"c",
"quick-sort"
],
"Title": "Quick Sort c program"
} | 208547 |
<p><strong>Edit</strong>
Found the original contract name resolution by .NET MEF, the code below is not useful anymore. See response!</p>
<p>My issue was to use existing code, to make a MEF <em><code>ExportFactory</code></em>, imported via <em><code>[Import]</code></em> attribute to a property, return instances of Moq mocks (for unit testing). Problem was, that the original code always used the <em><code>Type.FullName</code></em> property value as contract name. This worked fine for non-generic types, but not for generics.</p>
<p>Generic <code>FullName</code> is like:</p>
<blockquote>
<pre><code>My.Assembly.GenericType`1[My.Assembly.InnerType]
</code></pre>
</blockquote>
<p>but MEF expects a name like:</p>
<blockquote>
<pre><code>My.Assembly.GenericType(My.Assembly.InnerType)
</code></pre>
</blockquote>
<p>The complete unit test code actually extends the MEF <em><code>ExportProvider</code></em> class, to register <em><code>ExportDefinition</code></em> instances for an <em>ExportFactory</em> and it's <em><code>ProductDefinition</code></em>. The contract name goes to a metadata dictionary, using the key <em><code>CompositionConstants.ExportTypeIdentityMetadataName</code></em>.</p>
<p>This following code is only for the contract name conversion. It calls itself recursively, for generic arguments which are generic themselves. The regular expression matches by the `[digits] name extension, used by .NET for generic types. It would be nice to see a generally better way, or already existing functions from MEF, if such exists. </p>
<p>Edit: I added the incrementor and code for open (unspecified) generics, which have names with indexed curly brackets: instead of <em><code>IMyType<string,int></code></em> <em><code>IMyType<,></code></em>, resolved to contract name <em>IMyType({0},{1})</em>. Regex has also been changed to match, if no type names come after `[digits].</p>
<pre><code>private static readonly Regex GenericRegex =
new Regex(@"^(?<fullNameNonGeneric>\S+?)`\d+(\[.*\])*$",
RegexOptions.Compiled);
public static string ResolveGenericMefContractName(this Type type)
{
return ResolveGenericMefContractName(type, new IndexIncrementor());
}
private static string ResolveGenericMefContractName(Type type, IndexIncrementor incrementor)
{
var fullName = type?.FullName;
if (fullName == null)
{
return null;
}
var match = GenericRegex.Match(fullName);
if (!match.Success)
{
return type.FullName;
}
var fullNameNonGeneric = match.Groups["fullNameNonGeneric"].Value;
var genericArgs = type.GetGenericArguments();
return fullNameNonGeneric + "(" +
string.Join(",", genericArgs.Select(
ga => ResolveGenericMefContractName(ga, incrementor)
?? "{" + incrementor.GetAndIncrementValue() + "}"))
+ ")";
}
private class IndexIncrementor
{
private int _value;
public int GetAndIncrementValue() => _value++;
}
</code></pre>
| [] | [
{
"body": "<p>The code in the question was an attempt to generate type contract names, from the way I saw how MEF created them. Especially the difference from <code>Type.FullName</code>, which was previously used, when getting a contract name. For this reason, the code is a probably inferior re-implementation of MEF's own name generation, and should not be used for this purpose.</p>\n\n<p>This is the contract name resolution used by MEF in .NET framework (maybe different namespace in Core, Apps etc.):</p>\n\n<p>Namespace:</p>\n\n<blockquote>\n<pre><code>System.ComponentModel.Composition\n</code></pre>\n</blockquote>\n\n<p>Static method:</p>\n\n<blockquote>\n<pre><code>AttributedModelServices.GetContractName(Type)\n</code></pre>\n</blockquote>\n\n<p>Unfortunately, it's often easier to re-invent the wheel, than to find out about existing implementations...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T13:54:24.067",
"Id": "208930",
"ParentId": "208550",
"Score": "0"
}
},
{
"body": "<p>I see you've found the right solution but let's make a review anyway as there are few things that I'm not particularly fond of.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>var fullName = type?.FullName;\nif (fullName == null)\n{\n return null;\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of allowing <code>type</code> to be <code>null</code>, you should <code>throw</code> the <code>ArgumentNullException</code>. I cannot imagine any use-case where <code>type</code> being <code>null</code> would make sense. Usually this would mean a bug. You could return <code>null</code> later when resolving it fails but arguments should be always valid. Otherwise there are too many possibilities for the <code>null</code> result and it's could be difficult to tell why it didn't work.</p>\n\n<hr>\n\n<p>The method name is confusing becaues it says <em>Resolve</em> while it actually creates a <em>MefContractName</em> thus at first I thougt that when the regex fails here</p>\n\n<blockquote>\n<pre><code>if (!match.Success)\n{\n return type.FullName;\n}\n</code></pre>\n</blockquote>\n\n<p>then it should return <code>null</code>. While in the first casae this would make sense, it wouldn't for creation so I suggest naming this extension as <code>ToMefContractName</code>. Now it all makes sense again.</p>\n\n<p>I'm now sure what you need this <code>IndexIncrementor</code> for as the <code>type</code> should never be null so it will never be called.</p>\n\n<blockquote>\n<pre><code>var genericArgs = type.GetGenericArguments();\n\nreturn fullNameNonGeneric + \"(\" +\n string.Join(\",\", genericArgs.Select(\n ga => ToMefContractName(ga, incrementor)\n ?? \"{\" + incrementor.Next() + \"}\"))\n + \")\";\n</code></pre>\n</blockquote>\n\n<p>You can turn this into a more readable query without the helper variable <code>genericArgs</code> that this time doesn't help in any way.</p>\n\n<p>This is how I think it should look like (with <code>IndexIncrementor</code> removed because I could figure out what it is for):</p>\n\n<pre><code>private static string ToMefContractName(Type type)\n{\n if (type == null) throw new ArgumentNullException(nameof(type));\n\n var match = GenericRegex.Match(type.FullName);\n if (!match.Success)\n {\n return type.FullName;\n }\n\n var fullNameNonGeneric = match.Groups[\"fullNameNonGeneric\"].Value;\n\n var genericArguments =\n from genericArgument in type.GetGenericArguments()\n select ToMefContractName(genericArgument);\n\n return $\"{fullNameNonGeneric}({string.Join(\",\", genericArguments)})\";\n}\n</code></pre>\n\n<hr>\n\n<p>The <code>IndexIncrementor</code> should be called just <code>Index</code> and have one read-only property named <code>Value</code> and its method should be called <code>Next</code>. Saying <code>GetAndIncrementValue</code> reveals the internal implementation and this is not important to the user, he just wants to have the <em>next</em> value.</p>\n\n<pre><code>private class Index\n{\n public int Value { get; private set; }\n\n public int Next() => Value++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T09:40:34.580",
"Id": "404150",
"Score": "0",
"body": "OK, thanks. But on `Type`, method `GetGenericArguments()` returns null for open generics; in this case, the code worked as desired. This is different from the `GenericTypeArguments` property, which returns only specified generic arguments. I just noticed this later, when trying again with the property."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T07:40:52.440",
"Id": "209140",
"ParentId": "208550",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "208930",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T17:29:04.103",
"Id": "208550",
"Score": "1",
"Tags": [
"c#",
".net",
"mef"
],
"Title": "Retrieve generic contract names for Managed Extensibility Framework"
} | 208550 |
<p><strong>Requirement</strong>:</p>
<p>Based on <code>mainArray</code> which contains the master list of items, and <code>compArray</code> which has items of interest; construct a 2 dimensional third array that contains the array of contiguous elements.</p>
<p>The purpose of this requirement is for plotting poly-line on map wherever an incident occurred in contiguous manner, plotted using the <code>finalArray</code> of locations.</p>
<p><strong>Example</strong>:</p>
<pre class="lang-js prettyprint-override"><code>const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];
// produces finalArray
[[ 1, 2, 3 ],[ 6, 7 ],[ 11, 12, 13 ],[ 15 ]]
</code></pre>
<p><strong>My current solution</strong>:</p>
<pre class="lang-js prettyprint-override"><code>console.clear();
const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];
let compArrayIndex = 0;
let finalArray = [];
let currentArray = null;
for (let i = 0; i < mainArray.length; i++) {
const e = mainArray[i];
if (e === compArray[compArrayIndex]) {
if (!currentArray) {
currentArray = [];
}
currentArray.push(e);
compArrayIndex++;
} else {
if (currentArray) {
finalArray.push([...currentArray]);
currentArray = null;
}
}
}
if (currentArray) {
finalArray.push([...currentArray]);
currentArray = null;
}
console.log(mainArray);
console.log(compArray);
console.log('finl arr:');
for (let i = 0; i < finalArray.length; i++) {
const e = finalArray[i];
console.log(e);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:13:48.083",
"Id": "403119",
"Score": "1",
"body": "Why does this question have close votes? The problem is explained, there's an example and the code is there and seems to be working."
}
] | [
{
"body": "<p>The code could be reduced to a single line by utilizing <code>Array.prototype.reduce()</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];\nconst compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];\n\nconst finalArray = mainArray.reduce((a, b) => {\n // `c` is boolean result of checking if `compArray` includes `b`\n // `x` is first, and if matching elements found, last array in `finalResult`\n const [c, x] = [compArray.includes(b), a[a.length - 1]];\n // if `c` push `b` to last array of `a`\n if (c) x.push(b)\n // else if `x.length` push a new array to `a`\n else if (x.length) a.push([]);\n // return `a`\n return a;\n}, [[]]); // pass initial array containing single array `a` to `reduce`\n\nconsole.log(finalArray);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T04:10:45.150",
"Id": "402848",
"Score": "0",
"body": "To filter empty arrays in the case of `[1, 2, 3, 6, 7, 11, 12, 13]` you can chain `.filter(n=>n.length)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:56:51.813",
"Id": "402907",
"Score": "0",
"body": "I must point out your answer is not really a review, that the solution you give is O(n^2) while the op's is O(n), and that the comments are too much.. I would have down voted if you were not a newbie but rather I upvote and encourage you to keep posting, keeping these points in mind of course. Really!!! `.// return 'a'` for `return a;` and `// else if `x.length` push a new array to `a`` for `else if (x.length) a.push([]);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T00:37:49.007",
"Id": "403013",
"Score": "0",
"body": "@Blindman67 Not sure what you mean? How did you determine O(n^2) and O(n)? Is your only criticism the use of `.includes()` instead of `.find()`? \"down\" vote is meaningless to this user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T02:16:25.273",
"Id": "403050",
"Score": "0",
"body": "`Array.includes` or `Array.find` are both iterative searches, when done inside another iteration the worst case is O(n^2) with n the mean array size. Plus there is no way to exit early from `Array.reduce` if the other array is shorter."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T03:54:25.617",
"Id": "208583",
"ParentId": "208561",
"Score": "2"
}
},
{
"body": "<h1>Good algorithm</h1>\n\n<p>Your solution is good, however its implementation is somewhat poor. </p>\n\n<h2>Clear requirements</h2>\n\n<p>It is very unclear what inputs to expect so I must add...</p>\n\n<p>The input arrays are sorted and contain unique values, I must assume a requirement that is true.</p>\n\n<p>I deduce this from your code as if the above was not true your code would fail.</p>\n\n<h2>Style & code</h2>\n\n<ul>\n<li>The variable names are too long. Remember code is always in context and if you are handling arrays do you really need to add that in their names?</li>\n<li>Don't copy the array, just push it to the result. <code>finalArray.push([...currentArray]);</code> can be <code>finalArray.push(currentArray);</code> The copy halves the performance of your code (see below)</li>\n<li>Use <code>undefined</code> rather than <code>null</code></li>\n<li>Simplify the code by using <code>else if</code> when possible. You have <code>} else { if (currentArray) {</code> which can be <code>} else if (currentArray) {</code></li>\n<li><code>finalArray</code> should be a constant.</li>\n<li>Don't add code that is not needed. The last statement block up assign <code>null</code> to <code>currentArray</code> yet the variable is never used after that line.</li>\n</ul>\n\n<p>Apart from the above points your algorithm is good as it has low complexity (if you use <code>finalArray.push(currentArray)</code> you halve the complexity as [...currentArray] requires iteration of each item). </p>\n\n<p>You missed the opportunity to exit early. If you pass the end of the either arrays you know that no more items need to be added, however you continue to the end of the first array, which if longer than the second could mean many rundundent iterations.</p>\n\n<p>If you change the for loop to... </p>\n\n<pre><code>for (let i = 0; i < mainArray.length && compArrayIndex < compArray.length; i++) {\n</code></pre>\n\n<p>...you gain a reduction in overall complexity.</p>\n\n<h2>Cleaning up your solution</h2>\n\n<p>Thus we can rewrite your algorithm as</p>\n\n<pre><code>function extractRuns(main, comp) { \n var seq, j = 0;\n const result = [];\n for (let i = 0; i < main.length && j < comp.length; i++) {\n const e = main[i];\n if (e === comp[j]) {\n if (!seq) { seq = [] }\n seq.push(e);\n j++;\n } else if (seq) {\n result.push(seq);\n seq = undefined;\n }\n }\n if (seq) { result.push(seq) }\n return result;\n}\n</code></pre>\n\n<h2>Short is not always best</h2>\n\n<p>I must point out that the <a href=\"https://codereview.stackexchange.com/a/208583/120556\">existing answer</a> by guest271314 is very poor as it has very bad complexity by using <code>Array.includes</code> and is forced to iterate each item in the main array as it has no way to exit early from <code>Array.reduce</code>.</p>\n\n<h2>Rewrite</h2>\n\n<p>I personally would have written the solution as below as it gains a little performance (not by reduced complexity) via an inner while loop. (I am a bit of an off grid performance freak :) )</p>\n\n<pre><code>function extractRuns(main, comp) { // both arrays must be sorted and contain unique values\n var m = 0, c = 0, seq; // c and m are indexes \n const result = [], mLen = main.length, cLen = comp.length;\n while (m < mLen && c < cLen) {\n const a = main[m], b = comp[c];\n if (a === b) {\n c ++;\n m ++;\n result.push(seq = [a]);\n while (m < mLen && r < cLen && main[m] === comp[c]) {\n seq.push(main[m ++]);\n c ++;\n }\n } else if (b < a) { c ++ }\n else { m ++ }\n }\n return result;\n} \n</code></pre>\n\n<p>But I think your solution is far more readable and only a few % points slower to not be an issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:18:21.357",
"Id": "402913",
"Score": "1",
"body": "I agree with the review, although the long variable names were just for making my current solutions intentions more clear in the question. Thank you for the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:26:19.843",
"Id": "402918",
"Score": "1",
"body": "@Vijay Re long names, Understandable but we must take the code at face value. It is assumed that the posted code is working production (release) code. On that I did forget to make a point that it should also have been as a `function` but again I understand that you wrote it as an example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T00:40:05.837",
"Id": "403014",
"Score": "1",
"body": "@Blindman67 _\"I must point out that the existing answer by guest271314 is very poor\"_ Your answer should stand on its own without any reference to another users' answer. You should be able to remove that portion of text from your answer without affecting the remainder of your answer. At a minimum instead of referring to this user in you answer you could have simply suggested to use `.find()` instead of `.includes()` as that appears to be the only criticism of the answer that you are citing. Did not ask you to review this users' answer though since you insisted on doing so do so constructively"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:16:10.903",
"Id": "403120",
"Score": "1",
"body": "This is a good answer but I realllyyy can't agree with \"The variable names are too long\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:36:08.897",
"Id": "403142",
"Score": "0",
"body": "@IEatBagels How does `mainArray` improve on `main` its an array why add it to the name. `compArrayIndex` adds nothing to the readability of a 17 line function over `j` as a standard iteration index name. Long names make long lines that often means breaking lines apart that could be single line statements and expressions. Good names are short, don't include type, and are always read in context of the code they are declared in from which comes most of the semantic meaning. Long names are for long functions with many variables declared off page, and globals, both of which are bad."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:46:10.203",
"Id": "208618",
"ParentId": "208561",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208618",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T19:21:06.890",
"Id": "208561",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Construct an 2D array of contiguous elements comparing master and incident arrays"
} | 208561 |
<p>I wrote a matrix class for use in a ray tracer. I already have a 'scalar' version up and running, but now I'm trying to rewrite it to use Intel SIMD Instrinsics. I realize my compiler (clang-7.0.0) will probably generate code that is at least as fast as mine (chances are, it's going to be faster), but I'm doing this because I enjoy it, and because I find it interesting to think about things like this.</p>
<p>This is my version of a matrix-vector product. The matrix has a fixed dimension of 4x4, the vector has a fixed dimension of 4. I was wondering if I could take a different approach to make this function even faster?</p>
<p>My matrix class is set-up like this:</p>
<pre><code>class alignas(16 * sizeof(float)) matrix
{
private:
union
{
struct
{
__m256 ymm0;
__m256 ymm1;
};
float data [16];
};
...
public:
...
}
</code></pre>
<p><code>ymm0</code> stores rows 0 and 1, <code>ymm1</code> holds rows 2 and 3.</p>
<p>My <code>simd_vec4</code> class is just contains a single <code>__m128</code> called <code>xmm</code> that's aligned to 16 bytes (<code>4 * sizeof(float)</code>).
The vector stores its components in the as <code>{x, y, z, w}</code>.</p>
<p>Here's my reasoning for the algorithm:</p>
<ol>
<li><p>We basically need to perform 4 dot products; so the first thing I do is broadcast my 4-float vector to an 8-float vector with the same 4 floats in every lane.</p></li>
<li><p>Now, we perform the necessary multiplications, these only carry a data dependency with the vector from step 1, so they can be parallelized/out-of-order'ed.</p></li>
<li><p>(a) The next step is to reduce our 16 floats down to 4 floats. We do this by first performing 1 horzontal reduction on each of our 2-lane vectors, and then swapping lanes in one of them.</p>
<p>(b) The second portion of our reduction operation is to merge our two 2-lane vectors into one 2-lane vector, due to the way our data is laid out, we get the same data in both lanes (different order, but we need to fix that anyway...).</p></li>
<li><p>We now extract only the lower lane, because it has all the data we need.</p></li>
<li><p>Finally, we shuffle some data around in the lower lane to put the right components in the right places.</p></li>
</ol>
<p>And here's the code:</p>
<pre><code>simd_vec4 operator*(const simd_mat4& lhs, const simd_vec4& rhs) noexcept
{
// ymm0 = [ A B C D ][ E F G H ]
// ymm1 = [ I J K L ][ M N O P ]
__m256 broadcast = _mm256_set_m128(rhs.xmm, rhs.xmm); // Vec = [ x y z w ][ x y z w ]
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
__m256 xy_m256 = _mm256_mul_ps(lhs.ymm0, broadcast); // xy_m256 = [ Ax By Cz Dw ][ Ex Fy Gz Hw ]
__m256 zw_m256 = _mm256_mul_ps(lhs.ymm1, broadcast); // zw_m256 = [ Ix Jy Kz Lw ][ Mx Ny Oz Pw ]
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
__m256 acc0 = _mm256_hadd_ps(xy_m256, zw_m256); // acc0 = [ Ix + Jy Kz + Lw Ax + By Cz + Dw ][ Mx + Ny Oz + Pw Ex + Fy Gz + Hw ]
__m256 acc1 = _mm256_hadd_ps(zw_m256, xy_m256); // acc1 = [ Ax + By Cz + Dw Ix + Jy Kz + Lw ][ Ex + Fy Gz + Hw Mx + Ny Oz + Pw ]
acc1 = _mm256_permute2f128_ps(acc1, acc1, 0x01); // acc1 = [ Ex + Fy Gz + Hw Mx + Ny Oz + Pw ][ Ax + By Cz + Dw Ix + Jy Kz + Lw ]
__m256 merged = _mm256_hadd_ps(acc0, acc1); // merged = [Ex + Fy + Gz + Hw Mx + Ny + Oz + Pw Ix + Jy + Kz + Lw Ax + By + Cz + Dw][Ax + By + Cz + Dw Ix + Jy + Kz + Lw Mx + Ny + Oz + Pw Ex + Fy + Gz + Hw]
__m128 vec = _mm256_extractf128_ps(merged, 0); // vec = [Ax + By + Cz + Dw Ix + Jy + Kz + Lw Mx + Ny + Oz + Pw Ex + Fy + Gz + Hw]
vec = _mm_shuffle_ps(vec, vec, _MM_SHUFFLE(2, 1, 3, 0)); // vec = [Mx + Ny + Oz + Pw Ix + Jy + Kz + Lw Ex + Fy + Gz + Hw Ax + By + Cz + Dw]
return simd_vec4(vec);
}
</code></pre>
<p>I'm running this code on an Intel Core i7-5500U CPU @ 2.40GHz, so the allowed extensions are <a href="https://ark.intel.com/products/85214/Intel-Core-i7-5500U-Processor-4M-Cache-up-to-3-00-GHz-" rel="nofollow noreferrer">SSE4.1, SSE4.2, AVX2</a> (and below, I'm assuming).</p>
<p>Any advice is welcome, but one thing I do struggle with is coming up with meaningful names for the intermediate results, if anyone has any tips, you're more than welcome!</p>
<p>I've written two unit test so far, and both are passing (both are 'normal' cases though, I'm working on adding more 'edge' cases)</p>
<p>Here's the unit test code (I use <a href="https://github.com/catchorg/Catch2" rel="nofollow noreferrer">Catch2</a> btw):</p>
<pre><code>TEST_CASE("matrix * vec4", "[simd_matrix][vec4][multiplication][product]")
{
Math::matrix mat;
Math::simd_vec4 vec;
// First test case, tested by writing out all operations
constexpr std::array<float, 16> TEST_CASE_1 =
{0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15};
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
const int arrayIdx = (i * 4) + j;
mat(i, j) = TEST_CASE_1[arrayIdx];
}
}
vec = Math::simd_vec4(1.0f, 3.0f, 2.0f, 5.0f);
Math::simd_vec4 result = mat * vec;
Math::simd_vec4 EXPECTED_1 = Math::simd_vec4(
(0.0f * 1.0f) + (1.0f * 3.0f) + (2.0f * 2.0f) + (3.0f * 5.0f),
(4.0f * 1.0f) + (5.0f * 3.0f) + (6.0f * 2.0f) + (7.0f * 5.0f),
(8.0f * 1.0f) + (9.0f * 3.0f) + (10.0f * 2.0f) + (11.0f * 5.0f),
(12.0f * 1.0f) + (13.0f * 3.0f) + (14.0f * 2.0f) + (15.0f * 5.0f));
CHECK(result.x == Approx(EXPECTED_1.x));
CHECK(result.y == Approx(EXPECTED_1.y));
CHECK(result.z == Approx(EXPECTED_1.z));
CHECK(result.w == Approx(EXPECTED_1.w));
// Second test case, checked with Wolfram Alpha (https://www.wolframalpha.com/input/?i=%7B%7B1,+7,+23,+-5%7D,%7B0,+-9,+-5,+1%7D,%7B2,+6,+-3,+8%7D,%7B-1,+8,+11,+-5%7D%7D+*+%7B-7,+5,+-3,+1%7D)
constexpr std::array<float, 16> TEST_CASE_2 =
{1, 7, 23, -5,
0, -9, -5, 1,
2, 6, -3, 8,
-1, 8, 11, -5};
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
const int arrayIdx = (i * 4) + j;
mat(i, j) = TEST_CASE_2[arrayIdx];
}
}
vec = Math::simd_vec4(-7, 5, -3, 1);
Math::simd_vec4 EXPECTED_2 = Math::simd_vec4(-46, -29, 33, 9);
result = mat * vec;
CHECK(result.x == Approx(EXPECTED_2.x));
CHECK(result.y == Approx(EXPECTED_2.y));
CHECK(result.z == Approx(EXPECTED_2.z));
CHECK(result.w == Approx(EXPECTED_2.w));
}
</code></pre>
<p>For those that are interested: The full code can be found here:
<a href="https://bitbucket.org/ThomasCassimon/i-computer_graphics-raytracer/src/master/src/Math/simd/matrix.hpp" rel="nofollow noreferrer">Header</a>, <a href="https://bitbucket.org/ThomasCassimon/i-computer_graphics-raytracer/src/master/src/Math/simd/matrix.cpp" rel="nofollow noreferrer">Implementation</a>.
Should you have any problems building, here's my <a href="https://bitbucket.org/ThomasCassimon/i-computer_graphics-raytracer/src/master/CMakeLists.txt" rel="nofollow noreferrer">CMakeLists.txt</a>.</p>
<p><strong>Edit:</strong> I quickly got a <a href="https://gist.github.com/ThomasCassimon/28b227b88beb5c19930e5660cf316a2c" rel="nofollow noreferrer">gist</a> setup, it's got 5 files (2 for the matrix, 2 for the vector and 1 for main) along with a shell script that contains the command I used to compile this.</p>
<p>The example code runs the first test case. If any of the results are wrong, the error will be written to stderr.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T20:56:42.390",
"Id": "402814",
"Score": "0",
"body": "Hello, is it possible for you to publish the `matrix` class in its entirety, or a reduced version that will allow me to run `operator*`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T21:01:26.450",
"Id": "402816",
"Score": "0",
"body": "I added the necessary links to the bottom of the post, I'll get to work on a more minimal version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T21:43:20.400",
"Id": "402823",
"Score": "1",
"body": "@shmoo6000 minimal is explicitly discouraged here. We are not stack overflow. We need coffee in its entirety in order to review it effectively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-11T15:54:44.270",
"Id": "404833",
"Score": "0",
"body": "I could address mat4 x vec4 (which is an interesting problem in its own right) but are you sure you want to SIMDify that axis of your program? AFAIK the state of the art is still centered around ray packets and minor variants, which among other advantages allows SIMD to be applied in a more natural way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-14T19:45:05.080",
"Id": "405295",
"Score": "0",
"body": "@harold Thanks for the tip, but I'm already pretty far along the project, and the class I'm taking is an introductory class on computer graphics. It is also the last class on the subject I'll take, so I'd like to keep things simple for now."
}
] | [
{
"body": "<p>An issue with that code is that while it tries to pack the data to make efficient use of arithmetic throughput, actually arithmetic throughput is high anyway and it's the shuffles (including horizontal addition which has two shuffles internally) that are relatively expensive. Shuffles don't all have a low latency either, cross-slice shuffles such as <code>vperm2f128</code> take 3 cycles, so it's easy to accidentally build up a large delay that way.</p>\n\n<p>So, as far as I know, efficient single-vector mat4 x vec4 is still based on broadcasting the elements of the vector, multiplying that by columns of the matrix, and adding up the results (compilers tend to merge the add/mul into FMA if allowed). This would cost 4 shuffles pre-AVX or if the vector comes in a register, and potentially <em>zero shuffles</em> with AVX if the vector comes from memory, since a broadcast-from-memory has a \"free shuffle\" (it's just a load, and broadcasts for free, rather than going to the shuffle unit, though pre-AVX512 a broadcast-load cannot be a memory operand to an arithmetic operation). For example:</p>\n\n<pre><code>__m128 transform4(__m128* mat4, float *vec4) {\n __m128 x = _mm_set1_ps(vec4[0]);\n __m128 y = _mm_set1_ps(vec4[1]);\n __m128 z = _mm_set1_ps(vec4[2]);\n __m128 w = _mm_set1_ps(vec4[3]);\n\n __m128 p1 = _mm_mul_ps(x, mat4[0]);\n __m128 p2 = _mm_mul_ps(y, mat4[1]);\n __m128 p3 = _mm_mul_ps(z, mat4[2]);\n __m128 p4 = _mm_mul_ps(w, mat4[3]);\n\n return _mm_add_ps(_mm_add_ps(p1, p2), _mm_add_ps(p3, p4));\n}\n</code></pre>\n\n<p>With Clang 7, AVX2 enabled:</p>\n\n<pre><code>transform4(float __vector(4)*, float*): # @transform4(float __vector(4)*, float*)\n vbroadcastss xmm0, dword ptr [rsi]\n vbroadcastss xmm1, dword ptr [rsi + 4]\n vbroadcastss xmm2, dword ptr [rsi + 8]\n vbroadcastss xmm3, dword ptr [rsi + 12]\n vmulps xmm0, xmm0, xmmword ptr [rdi]\n vfmadd231ps xmm0, xmm1, xmmword ptr [rdi + 16] # xmm0 = (xmm1 * mem) + xmm0\n vfmadd231ps xmm0, xmm2, xmmword ptr [rdi + 32] # xmm0 = (xmm2 * mem) + xmm0\n vfmadd231ps xmm0, xmm3, xmmword ptr [rdi + 48] # xmm0 = (xmm3 * mem) + xmm0\n ret\n</code></pre>\n\n<p>This has a decent throughput, one transform every four cycles in the best case as it is, and better in a loop with the loads from the matrix factored out of the loop (hopefully a compiler can do that but better check the asm to make sure). The FMAs are tied together though (by Clang!), so the latency is not the greatest. Therefore it is best to batch transforms as much as reasonably possible, or otherwise latency could be reduced at the cost of an extra addition (and loss of source-level compatibility for pre-FMA processors)</p>\n\n<pre><code>__m128 transform4(__m128* mat4, float *vec4) {\n __m128 x = _mm_set1_ps(vec4[0]);\n __m128 y = _mm_set1_ps(vec4[1]);\n __m128 z = _mm_set1_ps(vec4[2]);\n __m128 w = _mm_set1_ps(vec4[3]);\n\n __m128 p1 = _mm_mul_ps(x, mat4[0]);\n __m128 p2 = _mm_fmadd_ps(y, mat4[1], p1);\n __m128 p3 = _mm_mul_ps(z, mat4[2]);\n __m128 p4 = _mm_fmadd_ps(w, mat4[3], p3);\n\n return _mm_add_ps(p2, p4);\n}\n</code></pre>\n\n<p>These approaches don't scale well to wider SIMD..</p>\n\n<p>With 8 SoA vectors to work with though, we can switch to broadcasting the matrix elements and doing 16 multiplications, which halves the number arithmetic instructions per transform. Since the matrix is being broadcasted from, its format is now free to choose, while this time the vector format is constrained. For example (not tested):</p>\n\n<pre><code>void transformBatch8(float *mat4, float *v) {\n __m256 m00 = _mm256_set1_ps(mat4[0]);\n __m256 m01 = _mm256_set1_ps(mat4[1]);\n __m256 m02 = _mm256_set1_ps(mat4[2]);\n __m256 m03 = _mm256_set1_ps(mat4[3]);\n __m256 m10 = _mm256_set1_ps(mat4[4]);\n __m256 m11 = _mm256_set1_ps(mat4[5]);\n __m256 m12 = _mm256_set1_ps(mat4[6]);\n __m256 m13 = _mm256_set1_ps(mat4[7]);\n __m256 m20 = _mm256_set1_ps(mat4[8]);\n __m256 m21 = _mm256_set1_ps(mat4[9]);\n __m256 m22 = _mm256_set1_ps(mat4[10]);\n __m256 m23 = _mm256_set1_ps(mat4[11]);\n __m256 m30 = _mm256_set1_ps(mat4[12]);\n __m256 m31 = _mm256_set1_ps(mat4[13]);\n __m256 m32 = _mm256_set1_ps(mat4[14]);\n __m256 m33 = _mm256_set1_ps(mat4[15]);\n __m256 x = _mm256_load_ps(v);\n __m256 y = _mm256_load_ps(v + 8);\n __m256 z = _mm256_load_ps(v + 16);\n __m256 w = _mm256_load_ps(v + 24);\n __m256 rx = _mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_mul_ps(m00, x), m01, y), m02, z), m03, w);\n __m256 ry = _mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_mul_ps(m10, x), m11, y), m12, z), m13, w);\n __m256 rz = _mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_mul_ps(m20, x), m21, y), m22, z), m23, w);\n __m256 rw = _mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_mul_ps(m30, x), m31, y), m32, z), m33, w);\n _mm256_store_ps(v, rx);\n _mm256_store_ps(v + 8, ry);\n _mm256_store_ps(v + 16, rz);\n _mm256_store_ps(v + 24, rw);\n}\n</code></pre>\n\n<p>Based on the cost of 20 loads, it takes at least 10 cycles per 8 transforms this way. Putting this in a loop and factoring out some loads would help, not all loads need to be factored out (and pre-AVX512 they cannot be, there are not enough registers), at least 4 so that the total number of loads per batch of 8 transforms goes down to 16, bringing down the minimum time down to 8 cycles per 8 transforms (in practice it often helps to reduce loads even further, but only to get closer to that bound of 8 cycles per 8 transforms because the FMAs alone already enforce that lower limit).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T18:20:35.407",
"Id": "210440",
"ParentId": "208565",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T20:08:21.530",
"Id": "208565",
"Score": "2",
"Tags": [
"c++",
"performance",
"matrix",
"simd"
],
"Title": "SIMD product of a 4×4 matrix and a vector"
} | 208565 |
<p>I did the following Excercise from <a href="https://automatetheboringstuff.com/chapter7/" rel="nofollow noreferrer">Automate the boring stuff with Python Chapter 7</a>:</p>
<blockquote>
<p>Write a function that uses regular exppressions to make sure the
password string it is passed is strong. A strong password is defined
as one that is at least eight characters long, contains both uppercase
and lowercase characters, and has a least one digit. You may need to
test the string against multiple regex patterns to validate its
strengh.</p>
</blockquote>
<p>My Solution:</p>
<p>I wrote four functions which check the individual aspects of the required password detection. Then these four functions are used to write the strong-password function which validates strings against all the requirements.</p>
<p>To test this i also checked out the unittest module.</p>
<p>Please let me know if theres sth to do better.</p>
<p>Is this a good way to test?
Are these good test cases?
Are there any bad practices/ little issues in the coding / testing?</p>
<p>Heres the code:</p>
<p><b> password.py </b></p>
<pre><code>import re
def valid_length(string):
"""checks if length is > 8 to be a strong password"""
lenght_regex = re.compile(r'.{8,}')
if not lenght_regex.search(string):
return False
return True
def has_upper(string):
"""Check if string contains one upper letter or more"""
upper_regex = re.compile(r'.*[A-Z]+.*')
if not upper_regex.search(string):
return False
return True
def has_lower(string):
"""Check if string contains one lower letter or more"""
lower_regex = re.compile(r'.*[a-z]+.*')
if not lower_regex.search(string):
return False
return True
def has_digit(string):
"""Check if one or more signs is a digit"""
digit_regex = re.compile(r'.*\d+.*')
if not digit_regex.search(string):
return False
return True
def strong_password(password):
"""
Validate if passed password is considered "strong",
Password is considered strong if:
- is eight characters or longer
- contains uppercase and lowercase characters
- has one digit or more
"""
if not valid_length(password):
return False
if not has_upper(password):
return False
if not has_lower(password):
return False
if not has_digit(password):
return False
return True
</code></pre>
<p><b> password_unit_test.py </b></p>
<pre><code>import unittest
import password as p
class TestIsStrongPassword(unittest.TestCase):
"""Test of strong password detection function."""
def test_valid_length(self):
"""Test that only a string length of > 8 is accecpted"""
self.assertEqual(p.valid_length('abcd'), False)
self.assertEqual(p.valid_length('abcdefg'), False)
self.assertEqual(p.valid_length('abcdefgh'), True)
self.assertEqual(p.valid_length('abcdefghi'), True)
def test_has_upper(self):
"""Test that only strings containing uppercase are accepted"""
self.assertEqual(p.has_upper('abcd'), False)
self.assertEqual(p.has_upper('aBcd'), True)
self.assertEqual(p.has_upper('aBCd'), True)
self.assertEqual(p.has_upper('Abcd'), True)
self.assertEqual(p.has_upper('abcD'), True)
self.assertEqual(p.has_upper('ABCD'), True)
def test_has_lower(self):
"""Test that only strings containing lowercase are accepted"""
self.assertEqual(p.has_lower('abcd'), True)
self.assertEqual(p.has_lower('aBcd'), True)
self.assertEqual(p.has_lower('aBCd'), True)
self.assertEqual(p.has_lower('Abcd'), True)
self.assertEqual(p.has_lower('abcD'), True)
self.assertEqual(p.has_lower('ABCD'), False)
def test_has_digit(self):
"""Test that only strings containing lowercase are accepted"""
self.assertEqual(p.has_digit('abcd'), False)
self.assertEqual(p.has_digit('a1cd'), True)
self.assertEqual(p.has_digit('a12d'), True)
self.assertEqual(p.has_digit('1bcd'), True)
self.assertEqual(p.has_digit('abc1'), True)
self.assertEqual(p.has_digit('1234'), True)
def test_strong_password(self):
"""
Test strong password function. Passed strings have to pass
all tests in valid_length, uppper, lower and digit functions.
"""
# Test from single functions should all fail
# (not met all criteria)
self.assertEqual(False, p.strong_password('abcd'))
self.assertEqual(False, p.strong_password('abcdefg'))
self.assertEqual(False, p.strong_password('abcdefgh'))
self.assertEqual(False, p.strong_password('abcdefghi'))
self.assertEqual(False, p.strong_password('abcd'))
self.assertEqual(False, p.strong_password('aBcd'))
self.assertEqual(False, p.strong_password('aBCd'))
self.assertEqual(False, p.strong_password('Abcd'))
self.assertEqual(False, p.strong_password('abcD'))
self.assertEqual(False, p.strong_password('ABCD'))
self.assertEqual(False, p.strong_password('abcd'))
self.assertEqual(False, p.strong_password('a1cd'))
self.assertEqual(False, p.strong_password('a12d'))
self.assertEqual(False, p.strong_password('1bcd'))
self.assertEqual(False, p.strong_password('abc1'))
self.assertEqual(False, p.strong_password('1234'))
# Combinations which met more than one cirteria
self.assertEqual(False, p.strong_password('12345678'))
self.assertEqual(False, p.strong_password('Abcdefgh'))
self.assertEqual(False, p.strong_password('A12345678'))
self.assertEqual(False, p.strong_password('Abcdfg1'))
self.assertEqual(True, p.strong_password('A12345678b'))
self.assertEqual(True, p.strong_password('Abcdefg1'))
self.assertEqual(True, p.strong_password('123456aB'))
self.assertEqual(True, p.strong_password('aB345678'))
if __name__ == '__main__':
unittest.main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T10:50:46.370",
"Id": "402878",
"Score": "0",
"body": "Just for the record, these are really bad criteria for strong passwords"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T10:56:02.540",
"Id": "402879",
"Score": "0",
"body": "@OscarSmith Yes in my answer I've added the obligatory xkcd as a note ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T11:12:49.297",
"Id": "402881",
"Score": "0",
"body": "well it is just an excercise not a real time application"
}
] | [
{
"body": "<p>Good job on the easily understandable code.</p>\n\n<h1>Good</h1>\n\n<ul>\n<li>Good functions, with clear names!</li>\n<li>Modular approach</li>\n<li>Unittests</li>\n<li>Docstrings</li>\n</ul>\n\n<h1>Improvements</h1>\n\n<ul>\n<li><p>Regex with lots of backtracking can produce some major performance loss</p>\n\n<p>Consider that this <code>re.search(r'.*[A-Z]+.*', string)</code> </p>\n\n<p>is equal to <code>re.search(r'[A-Z]+', string)</code> </p>\n\n<p>or even\n<code>re.search(r'[A-Z]', string)</code> as Toby correctly suggested. </p>\n\n<p>Since we only care if one character is in the given string.</p></li>\n<li><p>Return directly</p>\n\n<p>Instead of doing</p>\n\n<pre><code>if exdpression:\n return True\nreturn False\n</code></pre>\n\n<p>Return directly with <code>return expression</code></p></li>\n<li><p>Your <code>compile</code> has no performance gain, because with every new string it will compile again. Instead you could compile only onc,e and store it as a constant.</p></li>\n<li><p>Use the <code>all</code> keyword to check if all expressions evaluates to truthy.</p></li>\n<li><p>Instead of <code>assertEqual(expression, function)</code></p>\n\n<p>Do the more direct <code>assertFalse</code> or <code>assertTrue</code></p></li>\n</ul>\n\n<h1>Revised code</h1>\n\n<pre><code>import re\nimport unittest\n\nPASSWORD_CHECKS = [\n re.compile(r'[A-Z]'),\n re.compile(r'.{8,}'),\n re.compile(r'[a-z]'),\n re.compile(r'[0-9]'),\n]\n\ndef strong_password(password):\n \"\"\"\n Validate if passed password is considered \"strong\",\n Password is considered strong if:\n - is eight characters or longer\n - contains uppercase and lowercase characters\n - has one digit or more\n \"\"\"\n return all(check.search(password) for check in PASSWORD_CHECKS)\n\nclass TestIsStrongPassword(unittest.TestCase):\n \"\"\"Test of strong password detection function.\"\"\"\n def test_strong_password(self):\n \"\"\"\n Test strong password function. Passed strings have to pass \n all tests in valid_length, uppper, lower and digit functions.\n \"\"\"\n\n # Test from single functions should all fail \n # (not met all criteria)\n self.assertFalse(strong_password('abcd'))\n self.assertFalse(strong_password('abcdefg'))\n self.assertFalse(strong_password('abcdefgh'))\n self.assertFalse(strong_password('abcdefghi'))\n\n self.assertFalse(strong_password('abcd'))\n self.assertFalse(strong_password('aBcd'))\n self.assertFalse(strong_password('aBCd'))\n self.assertFalse(strong_password('Abcd'))\n self.assertFalse(strong_password('abcD'))\n self.assertFalse(strong_password('ABCD'))\n\n self.assertFalse(strong_password('abcd'))\n self.assertFalse(strong_password('a1cd'))\n self.assertFalse(strong_password('a12d'))\n self.assertFalse(strong_password('1bcd'))\n self.assertFalse(strong_password('abc1'))\n self.assertFalse(strong_password('1234'))\n\n # Combinations which met more than one cirteria\n self.assertFalse(strong_password('12345678'))\n self.assertFalse(strong_password('Abcdefgh'))\n self.assertFalse(strong_password('A12345678'))\n self.assertFalse(strong_password('Abcdfg1'))\n self.assertTrue(strong_password('A12345678b'))\n self.assertTrue(strong_password('Abcdefg1'))\n self.assertTrue(strong_password('123456aB'))\n self.assertTrue(strong_password('aB345678'))\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n\n<p><em>Notes</em></p>\n\n<p>What is a strong password? <a href=\"https://xkcd.com/936/\" rel=\"nofollow noreferrer\">Obligatory xkcd</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T17:12:46.120",
"Id": "403797",
"Score": "1",
"body": "I don't think the `+` in any of those regexes buys anything valuable - \"contains at least one\" means that you can be content after matching exactly one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T09:32:04.063",
"Id": "208597",
"ParentId": "208567",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "208597",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T20:25:02.530",
"Id": "208567",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"regex"
],
"Title": "Strong Password Detection"
} | 208567 |
<p>I built a small WinForm application that has checkboxes to filters users with different properties.</p>
<p>Each user has a name, color and number.<br>
With the program you can filter by color or name the users that you will see:<br>
<a href="https://i.stack.imgur.com/EeWH4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EeWH4.png" alt="enter image description here"></a></p>
<p>Inside the application there is a static list of users: </p>
<pre><code>// SomeUser(<name>, <color>, <number>);
SomeUser("user1", "red", "one");
SomeUser("user2", "blue", "one");
SomeUser("user3", "red", "two");
SomeUser("user4", "blue", "two");
SomeUser("user4", "yellow", "two");
SomeUser("user4", "blue", "three");
</code></pre>
<p>The application works as expected.
If you are not specified any filters, it will show you all.<br>
There is OR inside each groupbox.<br>
There is AND bettwen the groupboxes.
Meaning:<br>
If you checked <code>red</code> and <code>blue</code>, it will search for users that have red color <strong>OR</strong> blue color.<br>
If you checked <code>red</code>, <code>blue</code> and <code>one</code>, it will search for users that have red <strong>OR</strong> blue color <strong>AND</strong> <code>one</code> number.<br>
I hope you understand from these two small examples. </p>
<p>This is the filter function: </p>
<pre><code>void countFinding(CheckBox checkbox, string userField, ref int found)
{
if (checkbox.Checked)
{
if (userField == checkbox.Text)
{
found++;
}
}
}
private bool isFilter(SomeUser user)
{
bool isAllowed = false;
int shouldBeFound = 0;
int found = 0;
if(this.checkBoxRed.Checked || this.checkBoxBlue.Checked)
{
shouldBeFound++;
countFinding(this.checkBoxRed, user.color, ref found);
countFinding(this.checkBoxBlue, user.color, ref found);
}
if (this.checkBoxOne.Checked || this.checkBoxTwo.Checked)
{
shouldBeFound++;
countFinding(this.checkBoxOne, user.number, ref found);
countFinding(this.checkBoxTwo, user.number, ref found);
}
if (shouldBeFound == found)
{
isAllowed = true;
}
return isAllowed;
}
</code></pre>
<p>Inside the <code>isFilter()</code> function I am checking twice the same checkbox.<br>
In the first <code>if</code> I am checking:<br>
<code>if(this.checkBoxRed.Checked || this.checkBoxBlue.Checked)</code>
and if one of them is true it goes (twice) to an inner function (<code>countFinding()</code>)that also checks if the checkbox is checked. </p>
<p>So, it appear them I am checking at least one checkbox twice to see if it checked. </p>
<p>Is it possible to make it better? what do you think? </p>
| [] | [
{
"body": "<p>I don't think that checking the state of the box twice is an issue. However, I do think this could be written in a more general way that would be easier to add more boxes / fields to later. For example, sticking with the current class structure:</p>\n\n<pre><code>bool FieldMatchesFilterGroup(string field, params CheckBox[] group) \n{\n return group.All(box => !box.Checked) \n || group.Any(box => box.Checked && box.Text == field); \n}\n\nbool UserMatchesFilters(SomeUser user)\n{\n return FieldMatchesFilterGroup(user.color, checkBoxRed, checkBoxBlue)\n && FieldMatchesFilterGroup(user.number, checkBoxOne, checkBoxTwo);\n}\n</code></pre>\n\n<p>This could be made considerably more general, but at the cost of also becoming more complex, so whether that's worth doing depends on how you plan to use this code. The FieldMatchesFilterGroup method above is using LINQ, but you could do the same thing with a foreach loop:</p>\n\n<pre><code>bool FieldMatchesFilterGroup(string field, params CheckBox[] group)\n{\n bool any = false, found = false;\n foreach(var box in group) \n {\n if(box.Checked)\n {\n any = true;\n found |= (box.Text == field);\n }\n }\n return !any || found;\n}\n</code></pre>\n\n<p>Also, just as a style thing, the typical C# naming convention is UpperCamelCase for methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T00:58:08.577",
"Id": "208580",
"ParentId": "208570",
"Score": "2"
}
},
{
"body": "<p>Assuming you have a handler for the click event of the button(<code>filter</code>) to apply the filters. You can get all the checked boxes from each panel into separate collections. A LINQ query can then apply the filters against each user:</p>\n\n<pre><code>private void filter_Click(object sender, EventArgs e)\n{\n var checkedNumbers = numbers.Controls.OfType<CheckBox>().Where(x => x.Checked == true);\n var checkedColors = colors.Controls.OfType<CheckBox>().Where(x => x.Checked == true);\n dataGridView1.DataSource = (from user in users\n where (checkedNumbers.Count() == 0 ? true : checkedNumbers.Any(x => x.Text == user.number))\n && (checkedColors.Count() == 0 ? true : checkedColors.Any(x => x.Text == user.color))\n select user).ToList();\n}\n</code></pre>\n\n<p>For each filter set, if the count is 0 it returns true, or you could say unfiltered, otherwise it checks if the users complies with the filter(s). This follows the requirements you've stipulated.</p>\n\n<p>While the above will work for this specific case, having different properties that you want to filter by, could be problematic. Using the <code>group</code> clause it's fairly easy to get all the checked boxes grouped by the panel name. If the panel names are exactly like the property names in the <code>SomeUser</code> class and the checkboxes text's are exactly like the values for those properties, one can use some simple reflection to compare the values:</p>\n\n<pre><code>private void filter_Click(object sender, EventArgs e)\n{\n var checkedBoxes = (from panel in Controls.OfType<Panel>()\n from CheckBox cb in panel.Controls.OfType<CheckBox>()\n where cb.Checked == true\n group cb by panel.Name);\n dataGridView1.DataSource = (from SomeUser user in users\n where checkedBoxes.Count() == 0 ? true : checkedBoxes.All\n (grp => grp.Any\n (cb => cb.Text == $\"{user.GetType().GetProperty(grp.Key).GetValue(user)}\"))\n select user).ToList();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T05:18:26.840",
"Id": "208584",
"ParentId": "208570",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T20:47:51.930",
"Id": "208570",
"Score": "1",
"Tags": [
"c#",
"winforms"
],
"Title": "A WinForm application that filters users"
} | 208570 |
<p>For my first ML project I have modeled a dice game called Ten Thousand, or Farkle, depending on who you ask, as a vastly over-engineered solution to a computer player. You can find the complete game, with perfectly good computer player composed of about 15 lines of logic, <a href="https://github.com/llpk79/TenThousand/tree/bf04c540a62ae72b78d76bdd313184573c709f30" rel="nofollow noreferrer">here</a>.</p>
<p>In way of brief explanation of the game, 1's and 5' are always valid, scoring dice. Other numbers must be involved in 1) three or more of a kind, 2) a straight or, 3) three pairs to be scoring dice. I would like my model to predict which dice should be kept for a given roll. Thus far it is excellent at figuring out that 1's and 5's are keepers, but I am unable to improve on this with any amount of monkeying around thus far.</p>
<p>I'm looking for any advice on how to improve predictions to include scoring dice other than 1's and 5's. I've tried increasing the proportion of those situations in the training set, increasing and decreasing the complexity of the model both in structure and with various regularization methods, and even using convolution layers. </p>
<p>Specifically, are the RMSProp optimizer and sigmoid-cross-entropy loss appropriate here?</p>
<p>Setting things up.</p>
<pre><code>import tensorflow as tf
import numpy as np
import pandas as pd
from collections import Counter
from itertools import combinations_with_replacement as combos
from itertools import permutations as perms
import matplotlib.pyplot as plt
from tensorflow.keras import layers, Model
from tensorflow.data import Dataset
tf.enable_eager_execution()
tfe = tf.contrib.eager
</code></pre>
<p>I get my data by just making it, ensuring to make plenty of examples of special scoring situations.</p>
<pre><code>def make_some_features(numbers, clip):
features = set()
combinations = (combo for combo in combos(numbers, 6))
for i, comb in enumerate(combinations):
if i % clip == 0: # Keeping size reasonable
for perm in perms(comb):
features.add(perm)
return features
# I've looked through these and there are an expected proportion of three-of-a-kind or better examples.
features = make_some_features(list(range(1, 7)), 3)
# Make some three pairs features.
special_features = set()
for _ in range(1000):
half = [np.random.randint(1, 6) for _ in range(3)]
half += half
for perm in perms(half):
special_features.add(perm)
# We can only do so much with straights.
for perm in perms([1, 2, 3, 4, 5, 6]):
special_features.add(perm)
all_features = [np.array(feature) for feature in special_features]
all_features += [np.array(feature) for feature in features]
all_labels = [choose_dice(feature) for feature in special_features]
all_labels += [choose_dice(feature) for feature in features]
</code></pre>
<p>I put it all in a pandas dataframe for easy scrambling and partition off training, validation and test sets.</p>
<pre><code>def create_dataset(features, labels):
dice = pd.Series(features)
labels = pd.Series(labels)
dataset = pd.DataFrame({'dice': dice,
'labels': labels})
return dataset
all_dice = create_dataset(all_features, all_labels)
all_dice = all_dice.reindex(np.random.permutation(all_dice.index))
train_dice = all_dice.head(10000)
val_dice = train_dice.tail(5000)
test_dice = all_dice.tail(1936)
</code></pre>
<p>I one_hot encode the features and resize the label tensor.</p>
<pre><code>def pre_process_features(dice: pd.DataFrame) -> list:
rolls = []
for roll in dice['dice']:
roll = np.array(roll)
roll -= 1
roll = tf.one_hot(roll, depth=6, axis=-1)
rolls.append(roll)
return rolls
def pre_process_labels(dice: pd.DataFrame) -> list:
labels = [tf.reshape(tf.convert_to_tensor([label]), (6, 1)) for label in dice['labels']]
return labels
</code></pre>
<p>Model, optimizer, loss and gradient functions.</p>
<pre><code>model = tf.keras.Sequential([
layers.Dense(6, activation=tf.nn.relu, input_shape=(6, 6),
kernel_regularizer=tf.keras.regularizers.l2(regularization_rate)),
layers.Dense(64, activation=tf.nn.relu,
kernel_regularizer=tf.keras.regularizers.l2(regularization_rate)),
layers.Dense(128, activation=tf.nn.relu,
kernel_regularizer=tf.keras.regularizers.l2(regularization_rate)),
# layers.Dense(256, activation=tf.nn.relu,
# kernel_regularizer=tf.keras.regularizers.l2(regularization_rate)),
layers.Dense(32, activation=tf.nn.relu,
kernel_regularizer=tf.keras.regularizers.l2(regularization_rate)),
layers.Dense(1)])
optimizer = tf.train.RMSPropOptimizer(learning_rate=learning_rate)
global_step = tf.train.get_or_create_global_step()
def loss(model, features, labels):
logits = model(features)
if logits.shape == (1, 6, 1):
logits = tf.squeeze(logits, [0])
standard_loss = tf.losses.sigmoid_cross_entropy(logits=logits, multi_class_labels=labels)
return standard_loss
def grad(model, features, labels):
with tf.GradientTape() as tape:
loss_value = loss(model, features, labels)
return loss_value, tape.gradient(loss_value, model.trainable_variables)
</code></pre>
<p>Training loop.</p>
<pre><code>train_loss = []
train_accuracy = []
val_loss = []
val_accuracy = []
val_features, val_labels = iter(val_features), iter(val_labels)
val_feature, val_label = next(val_features), next(val_labels)
for epoch in range(num_epochs):
epoch_loss_ave = tfe.metrics.Mean('loss')
epoch_val_loss_average = tfe.metrics.Mean('loss')
epoch_accuracy = tfe.metrics.Accuracy('acc')
epoch_val_accuracy = tfe.metrics.Accuracy('acc')
for feature, label in zip(train_features, train_labels):
feature = tf.convert_to_tensor(feature.numpy().reshape(1, 6, 6))
loss_value, grads = grad(model, feature, label)
optimizer.apply_gradients(zip(grads, model.variables), global_step)
epoch_loss_ave(loss_value)
guessed_label = decode_label(model(feature))
epoch_accuracy(guessed_label, decode_label(label))
val_loss_value = loss(model, val_feature, val_label)
epoch_val_loss_average(val_loss_value)
val_guess_label = decode_label(model(val_feature))
epoch_val_accuracy(val_guess_label, decode_label(val_label))
train_loss.append(epoch_loss_ave.result())
train_accuracy.append(epoch_accuracy.result())
val_loss.append(epoch_val_loss_average.result())
val_accuracy.append((epoch_val_accuracy.result()))
if epoch % 20 == 0:
print(f'Epoch {epoch} Loss: {epoch_loss_ave.result()} Accuracy: {epoch_accuracy.result()}')
print(f'Validation loss: {epoch_val_loss_average.result()} Accuracy: {epoch_val_accuracy.result()}')
</code></pre>
<p>Testing and few predictions for random game inputs.</p>
<pre><code>test_results = []
test_accuracy = tfe.metrics.Accuracy('acc')
for feature, label in zip(test_features, test_labels):
guessed_label = decode_label(model(feature))
test_accuracy(guessed_label, decode_label(label))
print(f'Test accuracy: {test_accuracy.result()}')
for _ in range(25):
roll = np.array([np.random.randint(0, 5) for _ in range(6)])
turn = tf.one_hot(roll, depth=6, dtype=np.int32)
roll += 1
answer = choose_dice(roll)
print(f'Roll: {roll}')
print(f'Dice expected to be kept: {answer}')
turn = tf.convert_to_tensor(turn.numpy().reshape((1, 6, 6)), dtype=tf.float32)
predictions = model.predict(turn)
tf.nn.softmax(predictions)
predicted_label = []
for prediction in predictions[0]:
if prediction[0] > 0.:
predicted_label.append(1.)
else:
predicted_label.append(0.)
print(f'Dice predicted to be kept: {predicted_label}')
</code></pre>
<p>The complete code can be found <a href="https://github.com/llpk79/DNNTenThousand/tree/4f53c9542ef1255e0f75018b1b40144bbd0337bed" rel="nofollow noreferrer">here</a>.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-27T22:41:24.180",
"Id": "208575",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"machine-learning",
"dice",
"tensorflow"
],
"Title": "Tensorflow model for predicting dice game decisions"
} | 208575 |
<p>I'm currently trying to make a screen recorder in C#, and so far it works but the problem is that something as simple as a 20second video will take about 1GB of space. I have it setup so a timer continuously takes screenshots with this method:</p>
<pre><code>void takeScreenshot()
{
Rectangle bounds = Screen.FromControl(this).Bounds;
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
//Add screen to bitmap:
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
//Create and save screenshot:
string name = path + "//screenshot-" + fileCount + ".jpeg";
bitmap.Save(name, ImageFormat.Jpeg);
inputImageSequence.Add(name);
fileCount++;
//Dispose of bitmap:
bitmap.Dispose();
}
}
</code></pre>
<p>And then it stores those pictures in a temporary folder in the <code>D://</code> drive, and then when it's done it takes all the pictures and creates an AVI video out of them like this:</p>
<pre><code>//Set bounds of video to screen size:
Rectangle bounds = Screen.FromControl(this).Bounds;
int width = bounds.Width;
int height = bounds.Height;
var framRate = 5;
using (var vFWriter = new VideoFileWriter())
{
//Create new video file:
vFWriter.Open(outputPath+"//video.avi", width, height, framRate, VideoCodec.Raw);
//Make each screenshot into a video frame:
foreach (var imageLocation in inputImageSequence)
{
Bitmap imageFrame = System.Drawing.Image.FromFile(imageLocation) as Bitmap;
vFWriter.WriteVideoFrame(imageFrame);
imageFrame.Dispose();
}
vFWriter.Close();
}
//Delete the screenshots and temporary folder:
DeletePath(path);
</code></pre>
<p>Any help on reducing the inefficiency of this is appreciated, I'm fairly new to this kind of programming.</p>
| [] | [
{
"body": "<p><strong>takeScreenshot()</strong> </p>\n\n<ul>\n<li>Based on the <a href=\"https://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"noreferrer\">.NET Naming Guidelines</a> methods should be named using <code>PascalCase</code> casing <code>takeScreenshot()</code> => <code>TakeScreenshot()</code> </li>\n<li>You are enclosing the usage of the <code>Bitmap</code> inside a <code>using</code> statement which is the way to go but calling <code>Dispose()</code> on that <code>Bitmap</code> is superfluous because that is what a <code>using</code> statement is doing. </li>\n<li><p>If you have two <code>using</code> statements without any code between you can stack them which saves one level of indentation like so (already removed the <code>Dispose()</code>)</p>\n\n<pre><code>using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))\nusing (Graphics g = Graphics.FromImage(bitmap))\n{\n //Add screen to bitmap:\n g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);\n\n //Create and save screenshot:\n string name = path + \"//screenshot-\" + fileCount + \".jpeg\";\n bitmap.Save(name, ImageFormat.Jpeg);\n inputImageSequence.Add(name);\n fileCount++;\n} \n</code></pre></li>\n<li>Comments should explain <strong>why</strong> something is done in the way it is done. Let the code itself tell <strong>what</strong> is done by using meaningful named things. In this way your comments won't lie like e.g <code>//Create and save screenshot:</code> which isn't what that code does. Saving yes but no creating of a screenshot is taking place. </li>\n</ul>\n\n<hr>\n\n<p><strong>Creating the video</strong> </p>\n\n<ul>\n<li>Try to be consistent. Here you create a <code>Bitmap</code> and call <code>Dispose()</code> instead of using a <code>using</code> statement. In addition, sometime you use <code>var</code> and sometimes you use the concrete type although the type is seen at first glance. </li>\n<li>If you are using the <code>as</code> operator you should always add a <code>null</code> check for that object because an <code>as</code> operator won't throw an exception but the resulting object may be <code>null</code> which will trigger an exception somewhere else. </li>\n</ul>\n\n<p>Implementing these points will look like this: </p>\n\n<pre><code>Rectangle bounds = Screen.FromControl(this).Bounds;\nvar width = bounds.Width;\nvar height = bounds.Height;\n\nvar framRate = 5;\n\nusing (var vFWriter = new VideoFileWriter())\n{\n vFWriter.Open(outputPath+\"//video.avi\", width, height, framRate, VideoCodec.Raw);\n\n foreach (var imageLocation in inputImageSequence)\n {\n using(var imageFrame = (Bitmap)System.Drawing.Image.FromFile(imageLocation))\n {\n vFWriter.WriteVideoFrame(imageFrame);\n }\n }\n vFWriter.Close();\n}\nDeletePath(path);\n</code></pre>\n\n<hr>\n\n<p>My guess about the big file size is that you are using the <code>VideoCodec.Raw</code>. Try to change it to some other codec and see if this helps. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T05:43:26.470",
"Id": "208586",
"ParentId": "208582",
"Score": "13"
}
},
{
"body": "<p>You could write the screenshots directly to the video stream. This could save you a lot of disk space depending on your capture time.</p>\n\n<p>To make the video file smaller you need to use a codec that compresses the output like MPEG-4.</p>\n\n<p>Finally you could encapsulate the recording in its own class:</p>\n\n<pre><code>public sealed class ScreenRecorder : IDisposable\n{\n private readonly VideoFileWriter videoFileWriter = new VideoFileWriter();\n private readonly string videoFilePath;\n private readonly Rectangle bounds;\n\n public ScreenRecorder(string videoFilePath, Rectangle bounds, int frameRate = 5, VideoCodec videoCodec = VideoCodec.MPEG4)\n {\n if (string.IsNullOrWhiteSpace(videoFilePath))\n {\n throw new ArgumentException(\"Must be a valid filename\", nameof(videoFilePath));\n }\n\n if(frameRate < 1)\n {\n throw new ArgumentOutOfRangeException(nameof(frameRate));\n }\n\n this.videoFilePath = videoFilePath;\n this.bounds = bounds;\n videoFileWriter.Open(videoFilePath, bounds.Width, bounds.Height, frameRate, videoCodec);\n }\n\n public void TakeScreenshot()\n {\n if (disposed)\n {\n throw new ObjectDisposedException(nameof(ScreenRecorder));\n }\n\n using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))\n {\n using (Graphics g = Graphics.FromImage(bitmap))\n {\n //Add screen to bitmap:\n g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);\n }\n\n videoFileWriter.WriteVideoFrame(bitmap);\n }\n }\n\n public void Stop() => Dispose();\n\n #region IDisposable Support\n private bool disposed = false; // To detect redundant calls\n\n void Dispose(bool disposing)\n {\n if (!disposed)\n {\n if (disposing)\n {\n videoFileWriter.Dispose();\n }\n\n disposed = true;\n }\n }\n\n public void Dispose()\n {\n Dispose(true);\n }\n #endregion\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T09:33:18.307",
"Id": "208598",
"ParentId": "208582",
"Score": "8"
}
},
{
"body": "<p>Using string concatenation for creating file paths opens you up to a whole lot of headache. Should you use <code>/</code>, <code>//</code>, <code>\\</code> or <code>\\\\</code>? The answer depends on the environment you are running in. Luckily, the <code>Path</code> class can do all this logic for us:</p>\n\n<p>Instead of</p>\n\n<pre><code>path + \"//screenshot-\" + fileCount + \".jpeg\";\n</code></pre>\n\n<p>you could do</p>\n\n<pre><code>Path.Combine(path, $\"screenshot-{fileCount}.jpeg\");\n</code></pre>\n\n<p>and instead of</p>\n\n<pre><code>outputPath+\"//video.avi\"\nPath.Combine(outputPath, \"video.avi\")\n</code></pre>\n\n<p>This way you don't have to worry about using the right fileseparator.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:22:06.467",
"Id": "208614",
"ParentId": "208582",
"Score": "4"
}
},
{
"body": "<p>Thanks to all your help as well as the help of many others, I have actually fully compelted the screen recorder and have typed up an explanation here if anyone is interested: <a href=\"https://benbcompsci.wordpress.com/2018/12/04/c-screen-recorder/\" rel=\"nofollow noreferrer\">https://benbcompsci.wordpress.com/2018/12/04/c-screen-recorder/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T07:10:48.070",
"Id": "208985",
"ParentId": "208582",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T03:26:59.760",
"Id": "208582",
"Score": "8",
"Tags": [
"c#",
"compression",
"video"
],
"Title": "Screen recorder producing huge AVI files"
} | 208582 |
<p>I'm working on a program that aim to take sentences (currently in french) and compact them to a length of 38 characters while retaining as much information as possible.<br>
You can find another part of this project here <a href="https://codereview.stackexchange.com/questions/208675/replacing-words-with-their-abbreviations">replacing words with their abbreviations</a></p>
<p>I've made a function that removes determiners from a string using an external config file containing said determiners. It is functionnal but I think there's a lot to improve.</p>
<p>Here it is:</p>
<pre><code># determiners is the config file below parsed by configparser, l1 is the string
def remove_determiners(determiners, l1):
for key in determiners:
it_l1 = 0
# the goal is to obtain a string shorter than 38 char
while(it_l1 < len(l1) and len(l1) > 38):
# finds possible beginnig of words
if(l1[it_l1] in ' -' or it_l1 == 0):
if(it_l1 == 0):
it_l1 = -1
# finds possible end of words
it_word = 0
while(it_word < len(key) and it_l1 + it_word + 1 < len(l1)
and l1[it_l1 + it_word + 1] == key[it_word].upper()):
it_word += 1
if(it_word == len(key) and (it_l1 + it_word + 1 == len(l1)
or l1[it_l1 + it_word + 1] in ' -.')):
if(it_l1 == -1):
it_l1 = 0
# cuts the determiner out
l1 = l1[:it_l1] + l1[it_l1 + it_word + 1:]
it_l1 += 1
if(it_l1 == 0):
it_l1 = 1
return(l1)
</code></pre>
<p>Here is the configfile: (mostly french determiners)</p>
<pre><code>[remove]
& = nope
A = nope
AND = nope
AU = nope
AUX = nope
D = nope
DE = nope
DES = nope
DU = nope
EN = nope
FOR = nope
ET = nope
L = nope
LA = nope
LE = nope
LEUR = nope
LEURS = nope
LES = nope
OF = nope
OU = nope
PAR = nope
POUR = nope
SA = nope
SON = nope
SUR = nope
THE = nope
UN = nope
UNE = nope
</code></pre>
<p>Here is how its parsed:</p>
<pre><code>determiners = configparser.ConfigParser()
determiners.read('configuration//determiners.ini')
</code></pre>
<p>And here are some I/O examples:</p>
<pre><code>'JE SUIS LA BAGUETTE.' --> 'JE SUIS BAGUETTE.'
'LES PILES DE LA TELECOMMANDE.' --> 'PILES TELECOMMANDE.'
'QU ELLE HEURE EST IL ?' --> 'QU ELLE HEURE EST IL ?'
</code></pre>
<p>You may note the strings have been formatted to remove special characters and to be all upcase</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T10:07:14.150",
"Id": "402871",
"Score": "1",
"body": "Hello! From the code, it is hard to tell how the config example can be used to test the code. Could a provide one (or more) examples of inputs/outputs for `remove_determiners` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T10:20:11.547",
"Id": "402873",
"Score": "0",
"body": "@Josay This has been done"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T11:25:24.357",
"Id": "402882",
"Score": "0",
"body": "I'm trying to run the examples you've provided with no success. Here is what I've tried: https://pastebin.com/JcZ9qvAS . Please make sure that you provide enough information to be able to try your code easily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:04:25.953",
"Id": "403111",
"Score": "0",
"body": "Out of curiosity why 38 character long?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:08:14.370",
"Id": "403113",
"Score": "0",
"body": "@IEatBagels French postal addresses can't be longer than 38 characters"
}
] | [
{
"body": "<p>Thanks for sharing your code.</p>\n\n<p>It's a nice project you have there.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>You should take some time to choose carefully your variable. <code>l1</code> is not obvious, maybe <code>input</code>, <code>input_string</code>, <code>sentence</code> or <code>text</code> would be more appropriate? </p>\n\n<p>Without the commentary above the function, it would have been hard to find what that was supposed to be.</p>\n\n<p>Same for <code>it_l1</code> and <code>it_word</code>. After reading your code a few time, I am not sure what they are. Find a descriptive name, it helps tremendously when reading code.</p>\n\n<p><strong>Documentation</strong></p>\n\n<p>You have comments, that's good. But it is way better to have a good docstring for the function, and fewer comments.</p>\n\n<p>Your docstring should describe what the function try to accomplish, why it exists, the parameter (eventually their type) and what does the function return.</p>\n\n<p>And more annoying, some of your comments seem to be outdated/wrong?</p>\n\n<ul>\n<li><code># determiners is the config file below parsed by configparser</code> but it seems <code>determiners</code> is not a config file, but a list of string. (True it is the content of a file parsed by <code>configparser</code>, but it's not the same)</li>\n<li><code># the goal is to obtain a string shorter than 38 char</code> you did change your code but did not change that comment I presume? I couldn't find where it was supposed to restrict the size to 38char</li>\n</ul>\n\n<p><strong>Indentation</strong></p>\n\n<p>Your code here:</p>\n\n<pre><code>while(it_word < len(key) and it_l1 + it_word + 1 < len(l1)\nand l1[it_l1 + it_word + 1] == key[it_word].upper()):\n it_word += 1\nif(it_word == len(key) and (it_l1 + it_word + 1 == len(l1)\nor l1[it_l1 + it_word + 1] in ' -.')):\n</code></pre>\n\n<p>is very hard to read. Maybe it's because you pasted it into CodeReview, but be carefull when writing long and hard condition. The more difficult it is to read, the more difficult it is to debug/maintain/extend.</p>\n\n<p><strong>Putting it altogether</strong></p>\n\n<p>Note: <code>it_l1</code> and <code>it_word</code> are still in the code because I don't know how to name them properly but you should probably change them.</p>\n\n<pre><code>def remove_determiners(determiners, text):\n \"\"\"\n Removes determiners words from text\n\n :param determiners: the words to remove in `text`\n :param text: a text to remove determiner in\n :type determiners: List[str]\n :type text: str:\n :return: The value of `text` after removing all words present in determiners\n \"\"\"\n for key in determiners:\n it_l1 = 0\n\n while(it_l1 < len(text)):\n\n # Finds possible beginning of words\n if(text[it_l1] in ' -' or it_l1 == 0):\n if(it_l1 == 0):\n it_l1 = -1\n\n # Finds possible end of words\n it_word = 0\n while(it_word < len(key) \n and it_l1 + it_word + 1 < len(l1)\n and text[it_l1 + it_word + 1] == key[it_word].upper()):\n it_word += 1\n if(it_word == len(key)\n and (it_l1 + it_word + 1 == len(text)\n or text[it_l1 + it_word + 1] in ' -.')):\n if(it_l1 == -1):\n it_l1 = 0\n\n # cuts the determiner out\n text = l1[:it_l1] + l1[it_l1 + it_word + 1:]\n\n it_l1 += 1\n if(it_l1 == 0):\n it_l1 = 1\n return(text)\n</code></pre>\n\n<p><strong>Algorithm</strong></p>\n\n<p>You could also really simplify your code by using <a href=\"https://docs.python.org/3.7/library/stdtypes.html?highlight=set#set\" rel=\"nofollow noreferrer\">set</a>.</p>\n\n<p>Below is a code that works for the simple case, need to be improved to deal with punctuation. (if you have a text like \"LE, LA, ET.\", it will not remove the determiners. Or use a clean up step as shown below)</p>\n\n<pre><code>def remove_determiners(determiners, text):\n \"\"\"\n Removes determiners words from text\n\n :param determiners: the words to remove in `text`\n :param text: a text to remove determiner in\n :type determiners: List[str]\n :type text: str:\n :return: The value of `text` after removing all words present in determiners\n \"\"\"\n\n determiners_set = set(determiners)\n\n text_list = text.split(' ')\n\n resultat = []\n for element in text_list:\n if(element not in determiners_set):\n resultat.append(element)\n\n return ' '.join(resultat)\n</code></pre>\n\n<p>Or as a two-liner using list comprehension as @Josay pointed out in the comment:</p>\n\n<pre><code>def remove_determiners(determiners, text):\n determiners_set = set(determiners)\n return ' '.join(e for e in text.split(' ') if e not in determiners_set)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>determiners = ['AND',\n 'THE',\n 'ET',\n 'LE',\n 'LA',\n 'LES',\n 'DE']\n\ntext = 'LES PILES DE LA TELECOMMANDE'\n\nremove_determiners(determiners, text)\n# returns 'PILES TELECOMMANDE'\n</code></pre>\n\n<p><strong>Sidenote</strong></p>\n\n<p>Why in you config file you have <code>& = nope</code> instead of <code>&</code>? Is there more values than <code>nope</code>?</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Code changed slightly since my answer, adding the 38 char constraint. Should be straightforward to modify my response to accomodate this change</p>\n\n<p><strong>EDIT2</strong></p>\n\n<p>Also to address @Josay point about noise in the text, a cleaning step is possible like this:</p>\n\n<pre><code>def clean_text(text)\n \"\"\"Remove ponctuation from text and replace it by a empty char\n for -_,.?!:; and '\" by a space\n :param text: The text to remove punctuation in\n :return: Text cleaned up\n \"\"\"\n text = re.sub('[-_,.?!:;]', '', text)\n text = re.sub('[\\'\"]', ' ', text)\n return text\n</code></pre>\n\n<p>And usage</p>\n\n<pre><code>determiners = ['AND',\n 'THE',\n 'ET',\n 'LE',\n 'LA',\n 'LES',\n 'DE']\n\ntext = 'LES PILES DE-LA TELECOMMANDE'\n\nremove_determiners(determiners, clean_text(text))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:17:49.970",
"Id": "402912",
"Score": "0",
"body": "`nope` is a filler value for the config file, there is no other value. Can I remove it ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:20:59.767",
"Id": "402916",
"Score": "4",
"body": "Excellent answer! Please note that the function behavior is slightly different from the original one in situation such as \"PILES DE-LA TELE\" (which makes no sense in French but it is not the point). Also, you could use a list comprehension or generator expression to write something like: `return ' '.join(e for e in text.split(' ') if e not in determiners_set)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:36:08.283",
"Id": "402920",
"Score": "0",
"body": "I put a note saying it behave a bit differently with punctuation, but you are right it also behave differently with if there are any char not a space between words. Also thanks for the one liner, I'm not used enough to list comprehension"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:38:43.640",
"Id": "402921",
"Score": "0",
"body": "@Comte_Zero I don't know if you can, but maybe try to find out? It is really redondant and useless so if you can remove it without breaking your whole project, I think you should."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:42:07.413",
"Id": "402925",
"Score": "0",
"body": "I unfortunately can't"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:35:36.397",
"Id": "208617",
"ParentId": "208594",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "208617",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T09:07:53.747",
"Id": "208594",
"Score": "4",
"Tags": [
"python",
"strings",
"natural-language-processing"
],
"Title": "Remove determiners in a string"
} | 208594 |
<p>The exercise is from Alex Allain's book "Jumping into C++".
From Chapter 10 Practical Problem 4:</p>
<blockquote>
<ol start="4">
<li>Write a small tic-tac-toe program that allows two players to play
tic-tac-toe competitively. Your program should check to see if either
player has won, or if the board is filled completely (with the game
ending in a tie). Bonus: can you make your program detect if the game
cannot be won by either side before the entire grid is filled?</li>
</ol>
</blockquote>
<p>Here's my code. My main goal was a functioning tick-tack-toe game with little concern on the user experience (e.g.: the coordinates a player enters start from 0, or (0,0) coordinate is in the upper left corner no lower left as one would intuitively think). As for coding style I wanted the code to be as DRY as possible, with small, atomic, easy to understand functions doing most of the work.</p>
<pre><code>#include <iostream>
using namespace std;
bool checkWin(int board[][3], int player) {
// horizontal
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) return true;
}
// vertical
for (int i = 0; i < 3; i++) {
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) return true;
}
// diagonal
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player))
return true;
return false;
}
// TODO implement function if the game is a tie before the last move
bool fillPlace(int board[][3], int x, int y, int value) {
if (x > 2 || x < 0) {
cout << "Invalid x coordinate. Try again.\n";
return false;
} else if (y > 2 || y < 0) {
cout << "Invalid y coordinate. Try again.\n";
return false;
} else if (board[x][y] != 0) {
cout << "Place is already filled. Try again.\n";
return false;
} else {
board[x][y] = value;
return true;
}
}
void initBoard(int board[][3], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = 0;
}
}
}
void printBoard(int board[][3], int size) {
cout << "-----" << endl;
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
cout << "-----" << endl;
}
bool isBoardFilled(int board[][3]) {
bool isFilled = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 0) isFilled = false;
}
}
return isFilled;
}
int main() {
int board[3][3];
initBoard(board, 3);
printBoard(board, 3);
int playerOnesTurn = true;
while (true) {
int x, y;
if (playerOnesTurn) {
cout << "Player 1's turn" << endl;
do {
cout << "Enter x coordinate: "; cin >> x;
cout << "Enter y coordinate: "; cin >> y;
} while (!fillPlace(board, x, y, 1));
} else {
cout << "Player 2's turn" << endl;
do {
cout << "Enter x coordinate: "; cin >> x;
cout << "Enter y coordinate: "; cin >> y;
} while (!fillPlace(board, x, y, 2));
}
playerOnesTurn = !playerOnesTurn;
if (isBoardFilled(board)) {
cout << "The game is a tie.\n";
break;
}
printBoard(board, 3);
if (checkWin(board, 1)) {
cout << "Player 1 has won\n";
break;
} else if (checkWin(board, 2)) {
cout << "Player 2 has won\n";
break;
}
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<h2><a href=\"https://stackoverflow.com/q/1452721/3964927\">Avoid <code>using namespace std</code></a></h2>\n\n<p>This can cause name collisions because it adds every name in the <code>std</code> namespace to the global namespace. For a small program like this one it's unlikely that you'll run into any problems (then again, <a href=\"https://stackoverflow.com/q/31593548/3964927\">maybe not</a>) but it's best to get into the habit of using the <code>std::</code> prefix on names in the <code>std</code> namespace.</p>\n\n<p>Alternatively, you can introduce <a href=\"http://en.cppreference.com/w/cpp/language/namespace#Using-declarations\" rel=\"noreferrer\">using declarations</a> like <code>using std::cout;</code> to add specific names to the global namespace.</p>\n\n<h2>Avoid <code>std::endl</code> in favor of <code>\\n</code></h2>\n\n<p><a href=\"https://stackoverflow.com/q/213907/3964927\"><code>std::endl</code> flushes the stream, which can cause an unnecessary loss in performance.</a> In <code>printBoard()</code> you use <code>std::endl</code> three times but you can easily replace some of those uses with <code>\\n</code>.</p>\n\n<h2>Use a class for the Tic Tac Toe board</h2>\n\n<p>Instead of using a 3x3 array it's better to create a class to hold the state of the Tic Tac Toe board, with functions to set or get the value of a place on the board, determine whether or not the board is filled, etc. This allows you to hide implementation details which may change later on -- for example, if your compiler supports C++11 or will do so in the future you may want to change your internal representation of the board to use <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"noreferrer\"><code>std::array</code></a>. If you have a class for the Tic Tac Toe board the external interface would not change, only the code that implements the functionality.</p>\n\n<p>Here's what that class might look like:</p>\n\n<pre><code>class Board {\n int board[3][3];\npublic:\n typedef int value_type;\n\n // More modern alternative to typedef:\n //using value_type = int;\n\n Board() {\n for (std::size_t i = 0; i < 3; i++) {\n for (std::size_t j = 0; j < 3; j++) {\n board[i][j] = 0;\n }\n }\n }\n\n // Gets the value of a board place\n int place(std::size_t x, std::size_t y) const {\n // Might want to check coordinates and throw an exception (e.g. std::out_of_range) if coordinate(s) are invalid\n return board[x][y];\n }\n\n // Sets the value of a board place\n // It would probably be better to throw an exception (e.g. std::out_of_range) instead of printing to std::cout\n bool place(std::size_t x, std::size_t y, int value) {\n if (x > 2 || x < 0) {\n cout << \"Invalid x coordinate. Try again.\\n\";\n return false;\n } else if (y > 2 || y < 0) {\n cout << \"Invalid y coordinate. Try again.\\n\";\n return false;\n } else if (board[x][y] != 0) {\n cout << \"Place is already filled. Try again.\\n\";\n return false;\n } else {\n board[x][y] = value;\n return true;\n }\n }\n\n bool is_filled() const {\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n // Return immediately once we find a non-filled place\n if (board[i][j] == 0) return false;\n }\n }\n\n // All places were found to be filled\n return true;\n }\n};\n</code></pre>\n\n<p>(Note the use of <code>std::size_t</code> for the coordinate type and the <code>typedef</code> for the <code>int</code> value type, which mimic practices from the standard library.)</p>\n\n<p>You would no longer need <code>initBoard()</code> since the <code>Board</code> constructor performs the initialization, and some of your other functions would become member functions of the class. In some cases you can improve the performance of these functions -- e.g. you can keep a count of how many places are filled by incrementing the count each time a new place is filled by <code>Board::place()</code>, and then <code>Board::is_filled()</code> simply has to check if that count equals 9 rather than checking every place in the board (the performance gain is negligible for such a tiny board but the principle is important).</p>\n\n<h2>Overload <code>operator<<</code> for printing the board</h2>\n\n<p><code>printBoard()</code> only prints to <code>std::cout</code>. You can overload <code>operator<<</code> in order to insert the board into any <code>std::ostream</code>. Using the above <code>Board</code> class the code would look like this:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& os, Board board) {\n os << \"-----\\n\";\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n os << board.place(i, j) << \" \";\n }\n\n os << '\\n';\n }\n\n os << \"-----\" << std::endl;\n\n return os;\n}\n</code></pre>\n\n<p>(Note the replacement of some of the <code>std::endl</code> uses with '\\n`.)</p>\n\n<p>To print the board to <code>std::cout</code> you'd simply use <code>std::cout << board;</code>, and you can use the same function to print the board to a different <code>std::ostream</code> such as a <code>std::fstream</code> (for writing to a file).</p>\n\n<h2>Make your code DRYer</h2>\n\n<p>In some cases you can make your code DRYer. For example, the code in the <code>if</code> and <code>else</code> sections is very similar here:</p>\n\n<pre><code>if (playerOnesTurn) { \n cout << \"Player 1's turn\" << endl;\n do {\n cout << \"Enter x coordinate: \"; cin >> x;\n cout << \"Enter y coordinate: \"; cin >> y;\n } while (!fillPlace(board, x, y, 1));\n } else {\n cout << \"Player 2's turn\" << endl;\n do {\n cout << \"Enter x coordinate: \"; cin >> x;\n cout << \"Enter y coordinate: \"; cin >> y;\n } while (!fillPlace(board, x, y, 2));\n }\n</code></pre>\n\n<p>You can put that in a function like this:</p>\n\n<pre><code>// Capture Board by reference so we modify the original Board, not a copy\nvoid player_move(Board& board, int player) {\n cout << \"Player \" << player << \"'s turn\" << endl;\n\n std::size_t x, y;\n\n do {\n cout << \"Enter x coordinate: \"; cin >> x;\n cout << \"Enter y coordinate: \"; cin >> y;\n } while (!board.place(x, y, player));\n}\n</code></pre>\n\n<hr>\n\n<p>Here's a demo program with some of the changes I suggested:</p>\n\n<pre><code>#include <iostream>\n#include <ostream>\n\nusing namespace std;\n\nclass Board {\n int board[3][3];\npublic:\n typedef int value_type;\n\n // More modern alternative to typedef:\n //using value_type = int;\n\n Board() {\n for (std::size_t i = 0; i < 3; i++) {\n for (std::size_t j = 0; j < 3; j++) {\n board[i][j] = 0;\n }\n }\n }\n\n // Gets the value of a board place\n int place(std::size_t x, std::size_t y) const {\n // Might want to check coordinates and throw an exception (e.g. std::out_of_range) if coordinate(s) are invalid\n return board[x][y];\n }\n\n // Sets the value of a board place\n // It would probably be better to throw an exception (e.g. std::out_of_range) instead of printing to std::cout\n bool place(std::size_t x, std::size_t y, int value) {\n if (x > 2 || x < 0) {\n cout << \"Invalid x coordinate. Try again.\\n\";\n return false;\n } else if (y > 2 || y < 0) {\n cout << \"Invalid y coordinate. Try again.\\n\";\n return false;\n } else if (board[x][y] != 0) {\n cout << \"Place is already filled. Try again.\\n\";\n return false;\n } else {\n board[x][y] = value;\n return true;\n }\n }\n\n bool is_filled() const {\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n // Return immediately once we find a non-filled place\n if (board[i][j] == 0) return false;\n }\n }\n\n // All places were found to be filled\n return true;\n }\n};\n\nbool checkWin(Board& board, int player) {\n // horizontal\n for (int i = 0; i < 3; i++) {\n if (board.place(i, 0) == player && board.place(i, 1) == player && board.place(i, 2) == player) return true;\n }\n\n // vertical\n for (int i = 0; i < 3; i++) {\n if (board.place(0, i) == player && board.place(1, i) == player && board.place(2, i) == player) return true;\n }\n\n // diagonal\n if ((board.place(0, 0) == player && board.place(1, 1) == player && board.place(2, 2) == player) ||\n (board.place(0, 2) == player && board.place(1, 1) == player && board.place(2, 0) == player))\n return true;\n\n return false;\n}\n\n// TODO implement function if the game is a tie before the last move\n\nstd::ostream& operator<<(std::ostream& os, Board board) {\n os << \"-----\\n\";\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n os << board.place(i, j) << \" \";\n }\n\n os << '\\n';\n }\n\n os << \"-----\" << std::endl;\n\n return os;\n}\n\n// Capture Board by reference so we modify the original Board, not a copy\nvoid player_move(Board& board, int player) {\n cout << \"Player \" << player << \"'s turn\" << endl;\n\n std::size_t x, y;\n\n do {\n cout << \"Enter x coordinate: \"; cin >> x;\n cout << \"Enter y coordinate: \"; cin >> y;\n } while (!board.place(x, y, player));\n}\n\nint main() {\n Board board;\n std::cout << board;\n\n // should be a bool, not an int\n // alternatively, just use an int which is 1 when it's player 1's turn and 2 when player 2's turn\n bool playerOnesTurn = true;\n\n while (true) {\n player_move(board, playerOnesTurn ? 1 : 2);\n\n playerOnesTurn = !playerOnesTurn;\n\n if (board.is_filled()) {\n cout << \"The game is a tie.\\n\";\n break;\n }\n\n std::cout << board;\n\n if (checkWin(board, 1)) {\n cout << \"Player 1 has won\\n\";\n break;\n } else if (checkWin(board, 2)) {\n cout << \"Player 2 has won\\n\";\n break;\n }\n }\n\n return 0;\n}\n</code></pre>\n\n<p>I left a few other minor tips in the comments and I didn't make all the changes I suggested (e.g. I did not remove <code>using namespace std</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T16:42:55.517",
"Id": "208627",
"ParentId": "208607",
"Score": "5"
}
},
{
"body": "<p>Bug: if the winning move is the one that fills the board, the game ends in draw instead of a win. This is because you check for a draw before you check for a win. </p>\n\n<p>You can simplify things a bit: only the current player can win, so there is no need to check if the other player has won.</p>\n\n<p><code>main</code> doesn’t need a <code>return 0</code>, it is implied.</p>\n\n<p>Besides the redundancies already pointed out, <code>checkWin</code> is also a bit redundant, you can simply check to see if three values in a row are equal, it doesn’t matter what value they have. Thus, </p>\n\n<pre><code>board[0,i] == board[1,i] && board[0,i] == board[2,i]\n</code></pre>\n\n<p>suffices.</p>\n\n<p>That said, a lot of the work done here would be simpler if the board was stored in a flat array with <code>index = i + 3*j</code>.</p>\n\n<p>In this case, resetting the board is a simple call to <code>std::fill</code>, and checking to see if the board is full is a single call to <code>std::all_of</code>. Of course, if the board is a class, as suggested in the earlier answer, then you can implement an indexing operation that converts the <code>(i,j)</code> pair to a linear index.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:01:12.677",
"Id": "403017",
"Score": "0",
"body": "FWIW, I disagree with an implicit `return 0` on `main()`. Syntax should not be special. Explicit return values are useful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T23:46:48.097",
"Id": "208657",
"ParentId": "208607",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "208627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T12:15:20.713",
"Id": "208607",
"Score": "5",
"Tags": [
"c++",
"programming-challenge",
"tic-tac-toe"
],
"Title": "Tick-tack-toe (Jumping into C++)"
} | 208607 |
<p>This is my code to generate and store password localy hashed in txt file.
I would like to kindly ask you whether you could review my code. Btw it is coded as console app. I am currently working on making GUI. Thanks in advance.</p>
<pre><code>import random
import hashlib
class randomPass():
action = ''
def __init__(self):
# SETUP
self.passdic = {}
self.num_lines = sum(1 for line in open('passwords.txt'))
with open('passwords.txt', 'r') as rf:
for i in range(self.num_lines):
self.content = rf.readline()
self.content = list(self.content.split())
self.passdic[self.content[0]] = self.content[1]
self.leng = 14
self.action = ''
self.gPass = ''
# work as i want to
self.myPass = ''
print('perform one of the actions')
while self.action != 'break':
print('new action please')
self.action = input()
if self.action == 'generate':
print('determine your generated password length, We recommend above 14 characters')
self.leng = int(input())
self.gPass = self.generateRandomPassWord(self.leng)
print('generated')
elif self.action == 'read':
self.passRead()
elif self.action == 'save':
self.savePass(self.gPass)
else:
print(self.action + 'is not a valid action')
def generateRandomPassWord(self, lengthOfPassword=14):
znaky = ['"', "'", '!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', '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', '[',
']', '^', '_', '`', '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', '{', '|', '}', '~']
pword = ''.join([znaky[random.randint(0, len(znaky) - 1)] for i in range(lengthOfPassword)])
return pword
def savePass(self, generatedPassword):
print('to save the generated pass word type your key password')
self.myPass = hashlib.md5((input().encode('utf-8'))).hexdigest()
if self.myPass in self.passdic:
print('your key password already exists!')
else:
with open('passwords.txt', 'a') as af:
af.write(self.myPass + ' ' + generatedPassword + '\n')
self.passdic[self.myPass] = generatedPassword
print('password stored')
def passRead(self):
print('to read the generated pass word type your key password')
self.myPass = hashlib.md5((input().encode('utf-8'))).hexdigest()
if self.myPass in self.passdic:
print(self.passdic[self.myPass])
else:
print('we are sorry your password is non existant')
a = randomPass()
print('fin')
</code></pre>
| [] | [
{
"body": "<p>There is no particular need for this to be a class. While the reading of the file and the writing of the file are coupled, IMO this is not yet enough to make it into a class.</p>\n\n<p>What is especially confusing is that you use members even for local variables which are not needed in the other methods.</p>\n\n<hr>\n\n<p>Now, first, your reading of the file can be greatly simplified:</p>\n\n<pre><code>def read_password_file(file_name=\"passwords.txt\"):\n with open(file_name) as f:\n return {key: password for key, password in map(str.split, f)}\n</code></pre>\n\n<p>This also allows using a different file than the default. It uses a <a href=\"https://stackoverflow.com/a/1747827/4042267\">dictionary comprehension</a> and the fact that files are iterable.</p>\n\n<hr>\n\n<p>The generation of the random passwords should be separate from the CLI interface (in case you want to change one without the other). The generation itself can also be simplified by using the <a href=\"https://docs.python.org/3/library/string.html\" rel=\"nofollow noreferrer\"><code>string</code></a> module:</p>\n\n<pre><code>import random\nfrom string import ascii_lowercase, ascii_uppercase, digits, punctuation\n\nALLOWED_CHARS = ascii_lowercase + ascii_uppercase + digits + punctuation\n\ndef generate_random_pass_word(length=14, allowed_chars=ALLOWED_CHARS):\n return \"\".join(random.choices(allowed_chars, k=length))\n</code></pre>\n\n<p>This uses the <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.choices</code></a> function introduced in Python 3.6.</p>\n\n<hr>\n\n<p>Your saving and retrieving from the passwords dictionary can become this:</p>\n\n<pre><code>import hashlib\n\ndef get_key(name):\n return hashlib.md5(name.encode('utf-8')).hexdigest()\n\ndef save_password(passwords, password, file_name=\"passwords.txt\"):\n if password is None:\n print('First generate a password')\n return\n print('to save the generated pass word give it a name')\n name = get_key(input())\n if name in passwords:\n print('your key password already exists!')\n else:\n with open(file_name, 'a') as f:\n f.write(f\"{name} {password}\\n\")\n passwords[name] = password\n print('password stored')\n\ndef read_password(passwords):\n print('to read the generated pass word type its name')\n name = get_key(input())\n if names in passwords:\n print(passwords[name])\n else:\n print('we are sorry your password is non existent')\n</code></pre>\n\n<p>Note that I call your <code>self.myPass</code> what it is, a simple name. It is not really a password (you could look it up in the file and use a rainbow table to get the cleartext) and even the context of having to think of a good password to store your good password seems ridiculous (do you use this password generation function to generate this password? What password do you use to store that password?).</p>\n\n<p>I also used the new <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> (Python 3.6+) to simplify the writing to the file.</p>\n\n<hr>\n\n<p>And finally, your <code>main</code> function, which has the user interface:</p>\n\n<pre><code>def main():\n pass, action = None, None\n passwords = read_password_file()\n\n print('perform one of the actions')\n while action != 'break':\n action = input('new action please\\n')\n if action == 'generate':\n print('determine your generated password length, We recommend above 14 characters')\n length = int(input())\n pass = generate_random_pass_word(length)\n print('generated:', pass)\n elif action == 'read':\n read_password(passwords)\n elif action == 'save':\n save_password(passwords, pass)\n else:\n print(action + 'is not a valid action')\n\nif __name__ == \"__main__\":\n main()\n print('fin')\n</code></pre>\n\n<p>Note that I put the calling of <code>main</code> under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code></a> guard to allow importing from this script from another script.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:41:03.760",
"Id": "402948",
"Score": "0",
"body": "Thank you! I am planning to rewrite this to a simple GUI with tkinter module. Do you recommen me to put GUI and password generation in separate class? Btw the point behind this is only having to remember your simple password such as your name and you can use it to protect even the most private things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:17:33.390",
"Id": "402956",
"Score": "0",
"body": "@MatejNovosad Yes, I would put the GUI, the CLI and the password generation in different functions/classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:20:37.183",
"Id": "402957",
"Score": "0",
"body": "@MatejNovosad Well, if your name is your password, then now you have a weak password protecting your strong password, so now the only difference from having a weak password in the first place is some security by obscurity and the weak password being under your control (instead of on someone else's server). You are probably better of in having something like a password vault, which is protected by a single strong password, instead of each password being protected by its own potentially weak password."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:27:04.370",
"Id": "402960",
"Score": "0",
"body": "@MatejNovosad In addition, your logic is slightly wrong in another place. If I manage to read that file, I know all your passwords. They are saved in cleartext. I don't know for which site, but I know that they are passwords you use somewhere. You usually want to encrypt that part, not the identifier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:41:07.997",
"Id": "402965",
"Score": "0",
"body": "truth is when you manage to get to that file you can use generated passwords you have found in dictionary attack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:42:31.027",
"Id": "402966",
"Score": "0",
"body": "@MatejNovosad True, but saving passwords as plaintext files is not something you will find as good security advice anywhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:46:02.880",
"Id": "402968",
"Score": "0",
"body": "Yep and that is why you hash the user password or the 'name' part. In the end you can only hash one of the two informations. And when i was thinking about it i thought it may be better idea to hash the user typed password."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:15:49.977",
"Id": "208632",
"ParentId": "208613",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208632",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:13:48.747",
"Id": "208613",
"Score": "2",
"Tags": [
"python",
"beginner",
"object-oriented",
"python-3.x",
"hashcode"
],
"Title": "Password generator + storage console app"
} | 208613 |
<p>I have made a General Knowledge quiz in python as a project from my school</p>
<pre><code>import time
score=int()
print("Welcome to the General knowledge Quesions Quiz")
time.sleep(2)
print("Question 1")
time.sleep(2)
Question1 = input ("A vehicle with the national registration code ‘PK’ would originate from which country? ")
if Question1 == ("Pakistan") or Question1 == ("pakistan"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is Pakistan")
time.sleep(2)
print("Question 2")
time.sleep(2)
Question2 = input("In which English county is Blenheim Palace? ")
if Question2 == ("Oxfordshire") or Question2 == ("oxfordshire"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is Oxfordshire")
time.sleep(2)
print("Question 3")
time.sleep(2)
Question3 = input("How many hours are there in a leap year? ")
if Question3 == ("8784"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is 8784")
time.sleep(2)
print("Question 4")
time.sleep(2)
Question4 = input("In which sport could you win the Davis Cup? ")
if Question4 == ("Tennis") or Question4 == ("tennis"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is Tennis")
time.sleep(2)
print("Question 5")
time.sleep(2)
Question5 = input("What is the capital of Afghanistan? ")
if Question5 == ("Kabul") or Question5 == ("kabul"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is Kabul")
time.sleep(2)
print("Question 6")
time.sleep(2)
Question6 = input("How many golden stars feature on the flag of the European Union? ")
if Question6 == ("twelve") or Question6 == ("Twelve") or Question6 == ("12"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is twelve")
time.sleep(2)
print("Question 7")
time.sleep(2)
Question7 = input("In which year did Channel 4 begin transmission in the UK? ")
if Question7 == ("1982"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is 1982")
time.sleep(2)
print("Question 8")
time.sleep(2)
Question8=input("In which year did Theresa May become Prime Minister? ")
if Question8 == ("2016"):
print("Correct answer")
score = score + 1
else:
print("Incorrect answer, the correct answer is 2016")
time.sleep(2)
print("Question 9")
time.sleep(2)
Question9 = input("What is six-fourteenths of 112? ")
if Question9 == ("48") or Question9 == ("forty eight"):
print("Correct answer")
score = score + 1
else:
print("Incorrect asnwer, the correct answer is 48")
time.sleep(2)
print("Question 10")
time.sleep(2)
Question10 = input("Which type of angle is greater than 90 degrees but less than 180 degrees? ")
if Question10 == ("obtuse") or ("Obtuse"):
print("Correct answer")
score = score + 1
time.sleep(2)
print("This is the end of the quiz")
time.sleep(1)
print("You got",(score),"/ 10")
num1 = (score)
num2 = 10
print('{0:.2f}%'.format((num1 / num2 * 100)))
</code></pre>
<p>I have finished the quiz and if anyone has any suggestions on how I could have improved it, they will be greatly appreciated. So please suggest how I can improve it!</p>
<p>Thanks :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T19:25:25.497",
"Id": "403163",
"Score": "0",
"body": "is [this your post](https://codereview.stackexchange.com/q/208704/120114) by your unregistered account? if so we can request to have the accounts merged"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:21:53.863",
"Id": "403173",
"Score": "0",
"body": "No it isn't my account"
}
] | [
{
"body": "<p>You should generally avoid redundancy when programming.</p>\n\n<p>I'd make a list and loop through it</p>\n\n<pre><code>QUESTIONS = [(\"A vehicle with the national registration code ‘PK’ would originate from which country?\", \"Pakistan\"),\n (\"In which English county is Blenheim Palace?\", \"Oxfordshire\")] # Add more to this list\n\nfor n,(question, answer) in enumerate(QUESTIONS, 1):\n time.sleep(2)\n print(\"Question\", n)\n time.sleep(2)\n user_answer = input(question)\n if user_answer.lower() == answer.lower():\n print(\"Correct answer\")\n score += 1\n else:\n print(\"Incorrect answer, the correct answer is\", answer)\n</code></pre>\n\n<p>And so on</p>\n\n<p>Hope this helps :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T16:51:31.510",
"Id": "402935",
"Score": "1",
"body": "Im getting an error with your code so could you possible check over it please and this is the error if user_answer.tolower() == answer.tolower():\nAttributeError: 'str' object has no attribute 'tolower'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:41:20.437",
"Id": "402949",
"Score": "1",
"body": "As Paul pointed out, [`.lower()`](https://docs.python.org/2/library/stdtypes.html#str.lower) should be used instead of `.tolower()`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:40:20.270",
"Id": "208624",
"ParentId": "208616",
"Score": "6"
}
},
{
"body": "<p><code>score = int()</code></p>\n\n<p>Don't do this. Just say <code>score = 0</code>.</p>\n\n<p><code>Quesions</code> - run your UI text through spell check.</p>\n\n<p>Why are you calling <code>sleep()</code>? These calls are not really conducive to a useful user interface. If it's a matter of interacting with the user in a manner that waits to prepare them for the next question, there are better ways to do this - press any key to continue, or if the application calls for it, a countdown timer display. But blindly <code>sleep()</code>ing is generally not a good idea.</p>\n\n<p><code>score = score + 1</code></p>\n\n<p>Don't do this. Just do <code>score += 1</code></p>\n\n<p>In two places you write <code>(score)</code>. These parens don't do anything and should be dropped. Similarly, there's no need for double-parens around <code>((num1 / num2 * 100))</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T00:32:30.630",
"Id": "208660",
"ParentId": "208616",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "208624",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:31:52.580",
"Id": "208616",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"homework",
"quiz"
],
"Title": "General Knowledge quiz"
} | 208616 |
<p>I have two lists of Slots</p>
<pre><code>public class Slot
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
public List<Service> Services { get; set; }
}
public class Service
{
public int Id { get; set; }
public int Duration { get; set; }
}
public class MergingClass
{
public List<Slot> MergeSlots()
{
var mergedList = new List<Slot>();
var list1 = new List<Slot>
{
new Slot
{
Start = new DateTime(2018, 11, 1, 8, 0, 0),
End = new DateTime(2018, 11, 1, 11, 0, 0),
Services = new List<Service>
{
new Service
{
Duration = 20,
Id = 1
}
}
},
new Slot
{
Start = new DateTime(2018, 11, 1, 12, 0, 0),
End = new DateTime(2018, 11, 1, 16, 0, 0),
Services = new List<Service>
{
new Service
{
Duration = 20,
Id = 1
}
}
}
};
var list2 = new List<Slot>
{
new Slot
{
Start = new DateTime(2018, 11, 1, 8, 0, 0),
End = new DateTime(2018, 11, 1, 11, 0, 0),
Services = new List<Service>
{
new Service
{
Duration = 30,
Id = 2
}
}
},
new Slot
{
Start = new DateTime(2018, 11, 1, 12, 0, 0),
End = new DateTime(2018, 11, 1, 18, 0, 0),
Services = new List<Service>
{
new Service
{
Duration = 30,
Id = 2
}
}
}
};
return mergedList;
}
}
</code></pre>
<p>Start and End is block of time, that will be divided by service duration (service duration is int representing minutes). </p>
<p>So i have 2 lists (for 2 differenet services), and I need to merge them by Start and End dates into 3rd list (mergedList). </p>
<p>Method MergeSlots in this case should return:</p>
<pre><code>mergedList = new List<Slot>
{
new Slot
{
Start = new DateTime(2018, 11, 1, 8, 0, 0),
End = new DateTime(2018, 11, 1, 11, 0, 0),
Services = new List<Service>
{
new Service
{
Duration = 20,
Id = 1
},
new Service
{
Duration = 30,
Id = 2
}
}
},
new Slot
{
Start = new DateTime(2018, 11, 1, 12, 0, 0),
End = new DateTime(2018, 11, 1, 16, 0, 0),
Services = new List<Service>
{
new Service
{
Duration = 20,
Id = 1
},
new Service
{
Duration = 30,
Id = 2
}
}
},
new Slot
{
Start = new DateTime(2018, 11, 1, 16, 0, 0),
End = new DateTime(2018, 11, 1, 18, 0, 0),
Services = new List<Service>
{
new Service
{
Duration = 30,
Id = 2
}
}
}
};
</code></pre>
<p>Of course, both lists of slots come from a system that I can not influence and they will be different each time.</p>
<p>I tried to do it step by step, but solution is huge and ugly and error prone:</p>
<pre><code>foreach (var slot in list2)
{
var slotWithStartInList1 = list1.FirstOrDefault(x => x.Start <= slot.Start && x.End > slot.Start);
if (slotWithStartInList1 != null)
{
if (slot.Start == slotWithStartInList1.Start)
{
if (slot.End == slotWithStartInList1.End)
{
slot.Services.AddRange(slotWithStartInList1.Services);
mergedList.Add(slot);
continue;
}
if (slot.End < slotWithStartInList1.End)
{
slot.Services.AddRange(slotWithStartInList1.Services);
slotWithStartInList1.Start = slot.End;
mergedList.Add(slot);
mergedList.Add(slotWithStartInList1);
continue;
}
slotWithStartInList1.Services.AddRange(slot.Services);
slot.Start = slotWithStartInList1.End;
mergedList.Add(slotWithStartInList1);
mergedList.Add(slot);
continue;
}
if (slot.End == slotWithStartInList1.End)
{
slotWithStartInList1.End = slot.Start;
slot.Services.AddRange(slotWithStartInList1.Services);
mergedList.Add(slotWithStartInList1);
mergedList.Add(slot);
continue;
}
if (slot.End > slotWithStartInList1.End)
{
var tempSlot = new Slot
{
Start = slot.Start,
End = slotWithStartInList1.End,
Services = new List<Services>()
};
tempSlot.Services.AddRange(slotWithStartInList1.Services);
tempSlot.Services.AddRange(slot.Services);
slotWithStartInList1.End = tempSlot.Start;
slot.Start = tempSlot.End;
mergedList.Add(tempSlot);
mergedList.Add(slot);
mergedList.Add(slotWithStartInList1);
continue;
}
var tempSlot2 = new Slot
{
Start = slotWithStartInList1.Start,
End = slot.Start,
Services = new List<Services>()
};
tempSlot2.Services.AddRange(slotWithStartInList1.Services);
slot.Services.AddRange(slotWithStartInList1.Services);
slotWithStartInList1.Start = slot.End;
mergedList.Add(tempSlot2);
mergedList.Add(slot);
mergedList.Add(slotWithStartInList1);
continue;
}
var slotWithEndInList1 = list1.FirstOrDefault(x => x.Start < slot.End && x.End >= slot.End);
if (slotWithEndInList1 != null)
{
if (slot.End == slotWithEndInList1.End)
{
slot.End = slotWithEndInList1.End;
slotWithEndInList1.Services.AddRange(slot.Services);
mergedList.Add(slot);
mergedList.Add(slotWithEndInList1);
continue;
}
var tempSlot2 = new Slot
{
Start = slotWithEndInList1.Start,
End = slot.End,
Services = new List<Services>()
};
tempSlot2.Services.AddRange(slotWithEndInList1.Services);
tempSlot2.Services.AddRange(slot.Services);
slot.End = tempSlot2.Start;
slotWithEndInList1.Start = tempSlot2.End;
mergedList.Add(tempSlot2);
mergedList.Add(slot);
mergedList.Add(slotWithEndInList1);
continue;
}
mergedList.Add(slot);
}
foreach (var slot in list1)
{
if (mergedList.Any(x => x.Start == slot.Start))
{
continue;
}
mergedList.Add(slot);
}
return mergedList;
</code></pre>
<p>I can add few private methods to avoid code duplication, but I wonder if there is better (cleaner, shorter) way to accomplish my goal? </p>
<p>Maybe some linq extensions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T13:58:36.500",
"Id": "403109",
"Score": "4",
"body": "Could you explain what is the logic of the merge operation? In other words: what do you mean by merge? There can be different views: overwrite from left to right, from right to left, ignore, sum, extend, etc..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:23:12.253",
"Id": "403174",
"Score": "0",
"body": "Can you share the rest of the file as well? How are the functions used? In what place?"
}
] | [
{
"body": "<p>You have a lot of code to carefully, almost surgically, merge records from list2 into list1 based on a sorted order. Why not just (1) quickly merge the 2 lists without regards to order, followed immediately by (2) custom ordering? Something short like:</p>\n\n<pre><code>mergedList = list1.ToList().Union(list2).ToList();\nmergedList = mergedList.OrderBy(x => x.StartTime).ThenBy(x => x.EndTime).ToList();\n</code></pre>\n\n<p>Also, I think <code>Slot</code> is too generic a name. I suggest <code>TimeSlot</code> instead.</p>\n\n<p>You have no real checks when adding a time slot that <code>Start</code> occurs before <code>End</code>. You may also want to make sure all <code>DateTime</code> values are based on the same <code>DateTimeKind</code>. There is nothing in your code that prevents one time slot based on Utc and another based on Local.</p>\n\n<p><code>Duration</code> is an int representing minutes. This is ripe for confusion. You could rename the variable to be <code>DurationInMinutes</code>, but I would recommend using a <code>TimeSpan</code> instead. This makes the code more understandable with:</p>\n\n<pre><code>Duration = TimeSpan.FromMinutes(10);\n</code></pre>\n\n<p>Later you will probably be using that <code>Duration</code> with some conditional or other calculation with another <code>DateTime</code> and a <code>TimeSpan</code> is a great fit for that.</p>\n\n<p><strong>UPDATE MORE SUGGESTIONS</strong></p>\n\n<p>You are interested in a custom sort for your time slots, but I am guessing you want that sort always. You might want to consider making <code>TimeSlot</code> implement <code>IEquatable<TimeSlot></code> and <code>IComparable<TimeSlot></code>. You will need to add some methods to help out there, such as <code>Equals</code>, <code>CompareTo</code>, and <code>GetHashCode</code>.</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">IEquatable link</a></p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.icomparable-1?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">IComparable link</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T16:48:19.943",
"Id": "208628",
"ParentId": "208619",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:55:23.057",
"Id": "208619",
"Score": "1",
"Tags": [
"c#",
"linq"
],
"Title": "Merging two lists into one by dates"
} | 208619 |
<p>I wondered how an expandable list could be implemented. My first thought: You could create a class that has an array and you can create a new array each time the user wants to append an element and than you can copy the old array plus the new element into the new array. But this seems very inefficient to me. Then I read something about so called linked lists. The idea is very simple. Such a list has nodes. Nodes contain an object and another node. The nodes can be linked as required. I had my thoughts about that and I tried to write a class that follows this thought.</p>
<p>LinkedList.java</p>
<pre><code>package linkedList;
public class LinkedList<T> {
private Node<T> startNode;
public LinkedList() {
startNode = new Node<T>();
}
private Node<T> getEmptyNode() {
Node<T> currentNode = this.startNode;
while (currentNode.hasObject()) {
currentNode = currentNode.getNextNode();
}
return currentNode;
}
public void insert(T object) {
Node<T> emptyNode = getEmptyNode();
emptyNode.setObject(object);
emptyNode.setNextNode(new Node<T>());
}
public int getNumberOfElements() {
Node<T> currentNode = startNode;
int numberOfElements = 0;
while (currentNode.hasObject()) {
numberOfElements++;
currentNode = currentNode.getNextNode();
}
return numberOfElements;
}
private Node<T> getNodeByIndex(int index) {
Node<T> currentNode = startNode;
for (int i = 0; i < index; i++) {
currentNode = currentNode.getNextNode();
}
return currentNode;
}
public T get(int index) {
return getNodeByIndex(index).getObject();
}
public void delete(int index) {
if (index == 0) {
startNode = getNodeByIndex(1);
return;
}
// if index equals last available index
if (index == (getNumberOfElements() - 1)) {
Node<T> nodeBefore = getNodeByIndex(index - 1);
nodeBefore.setNextNode(null);
return;
}
Node<T> nodeBefore = getNodeByIndex(index - 1);
Node<T> nodeBehind = getNodeByIndex(index + 1);
nodeBefore.setNextNode(nodeBehind);
}
}
</code></pre>
<p>Node.java</p>
<pre><code>package linkedList;
public class Node<T> {
private T object;
private Node<T> nextNode;
public Node() {
this.object = null;
this.nextNode = null;
}
public boolean hasObject() {
return object != null;
}
public boolean hasNextNode() {
return nextNode != null;
}
public T getObject() {
return object;
}
public Node<T> getNextNode() {
return nextNode;
}
public void setNextNode(Node<T> nextNode) {
this.nextNode = nextNode;
}
public void setObject(T object) {
this.object = object;
}
}
</code></pre>
<p>Main.java</p>
<pre><code>package linkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<>();
linkedList.insert("Hallo");
linkedList.insert("Test");
linkedList.insert("Wie gehts?");
linkedList.insert("Freuen sie sich?");
System.out.println("Anzahl der Elemente: " + linkedList.getNumberOfElements());
System.out.println("Drittes Element: " + linkedList.get(2));
System.out.println("Alle Elemente:");
for (int i = 0; i < linkedList.getNumberOfElements(); i++) {
System.out.println(linkedList.get(i));
}
linkedList.delete(2);
System.out.println("Alle Elemente:");
for (int i = 0; i < linkedList.getNumberOfElements(); i++) {
System.out.println(linkedList.get(i));
}
}
}
</code></pre>
<p>Because this is my first attempt to do such stuff I am wondering what things can be improved. Is there a way to make this more efficient? Is the code clean and readable enough?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T16:41:33.747",
"Id": "402933",
"Score": "0",
"body": "Since you are not asking for a comparative review or the review of one implementation modeled after an already existing implementation, I think it would be better if you split this into two questions, one containing the Java implementation and one containing the Python version. This also makes it a lot easier for the reviewers. Since the two questions are related, you should probably add a link to the other one in both questions (by editing them after having created them)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:07:06.280",
"Id": "402937",
"Score": "1",
"body": "Ok I will do so"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:23:05.513",
"Id": "402959",
"Score": "1",
"body": "On a side note: a list based on arrays doesn't have to be mutated every time you add a single element, you can have an array of size `capacity` and when the array is full you can mutate it into an array of size `capacity * 2`, then `capacity * 3` and so on. That's how `java.util.ArrayList` is implemented."
}
] | [
{
"body": "<pre><code>Node<T> nodeBefore = getNodeByIndex(index - 1);\nNode<T> nodeBehind = getNodeByIndex(index + 1);\nnodeBefore.setNextNode(nodeBehind);\n</code></pre>\n\n<p>This is from the <code>delete()</code> function. You call <code>getNodeByIndex()</code> twice which iterates from the start of the list twice, instead you can just go 2 nodes forward from <code>nodeBefore</code>:</p>\n\n<pre><code>Node<T> nodeBefore = getNodeByIndex(index - 1);\nNode<T> nodeBehind = nodeBefore.getNextNode().getNextNode();\nnodeBefore.setNextNode(nodeBehind);\n</code></pre>\n\n<p>Also I would rename <code>nodeBehind</code> to <code>nodeAfter</code> for the sake of clarity.</p>\n\n<hr>\n\n<p>In the implementation of <code>getNumberOfElements()</code> you don't check if the first element is null.</p>\n\n<hr>\n\n<p>When deleting the last node in the list, you should turn the node into an empty node instead of removing it completely to ensure that <code>getEmptyNode()</code> will have a node to return.</p>\n\n<hr>\n\n<p>You can keep track of the number of nodes instead of re-counting them every time, that would greatly improve the performance of <code>getNumberOfElements()</code> and the other methods that use it:</p>\n\n<pre><code>public class LinkedList<T> {\n private Node<T> startNode;\n private int length; // increment/decrement this every time you add/remove an element\n</code></pre>\n\n<hr>\n\n<p>I don't like the idea of keeping an empty node at the end and using <code>getEmptyNode()</code> to find it by iterating over the whole list, it would be much simpler if you didn't keep an extra empty node at the end but kept a reference to the last node for internal use.</p>\n\n<hr>\n\n<p>In the constructor of <code>Node</code> you don't need to set the node's properties to null, they already are null.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T12:33:32.177",
"Id": "208685",
"ParentId": "208620",
"Score": "1"
}
},
{
"body": "<p>You are on the right track, and I think you would benefit by having your class implement the Java <code>List<T></code> interface like so:</p>\n\n<pre><code>public class LinkedList<T> implements List<T> {\n</code></pre>\n\n<p>You would then have to change your methods so that their names and signatures conform to the interface. You can read about the details <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/List.html\" rel=\"nofollow noreferrer\">here</a> for Java 7 or <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/List.html\" rel=\"nofollow noreferrer\">here</a> for Java 8. If you do this then you could pass instances of your class into already implemented functions like <code>Collections.sort</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T18:47:06.630",
"Id": "208709",
"ParentId": "208620",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208685",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T14:56:00.590",
"Id": "208620",
"Score": "2",
"Tags": [
"java",
"linked-list"
],
"Title": "My own expandable list"
} | 208620 |
<p>I am concerned about how certain processes of an exercise or CRUD example should be implemented in a PHP document, looking for the best practices in terms of security and development techniques of that script.</p>
<p>Suddenly, my question may be considered as opinion based, so I will try to be as specific as possible:</p>
<p><strong>Approach</strong></p>
<p>I need to make multiple processes to my database in MySQL, in a single request made to the PHP script. A person is trying to enter a section of a security company, so that each section or room of the company has a limit marked by the user:</p>
<p><strong>Fictitious Database Tables</strong></p>
<pre><code>|--------------------------|---------------------------|
| person | room |
|--------------------------|---------------------------|
|id_person |id_room |
|name_person |name_room |
|document_person |code_room |
|date_admission_person |number_room |
|id_document_type_person |capacity_room |
|id_blood_type_person |current_capacity_room |
|id_room_person |id_state_room |
|--------------------------|---------------------------|
</code></pre>
<p>The capacity of the room is 10 people, and the current capacity of the room is 8 people.</p>
<p><strong>Process</strong></p>
<ul>
<li>Validate if the room has the capacity to register.</li>
<li>Enter the record of a person in a table called person.</li>
<li>Update the current value of the room you are visiting <code>current_capacity_room</code>.</li>
</ul>
<p>There are three different procedures that must be performed in the same script:</p>
<ol>
<li><code>READ</code></li>
<li><code>CREATE</code></li>
<li><code>UPDATE</code></li>
</ol>
<p><strong>Sample Script</strong></p>
<pre><code><?php
//Declaration of system headers
header("Context-type: application/json;");
//includin connection with the db
require '../Connection/connection.php';
//Declaration of sessions
session_start();
$idCompany = $_SESSION['user']['id_company'];
//Decoding data by POST method
$_POST = json_decode(file_get_contents('php://input'), true);
//Declaration array for encode JSON format
$result= array();
//Evaluate if the connection it's ok
if ($mysqli)
{
if(isset($_POST) && !empty($_POST))
{
//Object format to UTF8
$mysqli->set_charset('utf8');
//Capturing variables
$namePerson = $_POST['name_person'];
$documentPerson = $_POST['document_person'];
$idDocumentTypePerson = $_POST['id_document_type_person'];
$idBloodTypePerson = $_POST['id_blood_type_person'];
$idRoomPerson = $_POST['id_room_person'];
/*
*****************************************************************************
*****************************************************************************
PREPARE QUERY TO VERIFY THE CAPACITY OF THE ROOM
*****************************************************************************
*****************************************************************************
*/
/* Query SQL */
$consult = $mysqli->prepare("SELECT *
FROM room
WHERE id_room = ?
AND current_capacity_room < capacity_room
AND id_company = ?");
/* check if the query was prepared correctly */
if ($consult === false)
{
$result['message'] = "Failed to prepare the query.";
}
/*assign the first "?"*/
$consult->bind_param('ii', $idRoomPerson, $idCompany);
/* check if the query was executed correctly */
if ($consult->execute() === false)
{
$result['message'] = "Error checking the execution of the query.";
}
/* Here we get the record (if there is one) */
if ($consult->fetch() !== true)
{
$result['message'] = "The room does not have enough capacity to register.";
}
else
{
$consult->next_result(); // Dump the extra resultset.
$consult->free_result(); // Does what it says.
/*
*****************************************************************************
*****************************************************************************
REGISTER THE PERSON IN THE SYSTEM
*****************************************************************************
*****************************************************************************
*/
$consult_sql = "INSERT INTO `person`(`id_person`, `name_person`, `document_person`,
`date_admission_person`, `id_document_type_person`, `id_blood_type_person`,
`id_room_person`)
VALUES (NULL, ?, ?, CURDATE(), ?, ?, ?)";
$insert_person = $mysqli->prepare($consult_sql);
/*
* Use the method bind_param() to capture the variables in the Database
*/
$insert_person->bind_param('ssiii', $namePerson,
$documentPerson,
$idDocumentTypePerson,
$idBloodTypePerson,
$idRoomPerson);
//Execute query
if ($insert_person->execute())
{
$insert_person->next_result(); // Dump the extra resultset.
$insert_person->free_result(); // Does what it says.
/*
* Verify if there were affected rows
* Decide the status of the message with a ternary operator
*/
/*
*****************************************************************************
*****************************************************************************
UPDATE THE CAPACITY OF THE ROOM IN THE SYSTEM
*****************************************************************************
*****************************************************************************
*/
$consult_sql = "UPDATE `room`
SET `current_capacity_room` = current_capacity_room + 1
WHERE id_room` = ?;";
$update_room = $mysqli->prepare($consult_sql);
/*
* Use the method bind_param() to capture the variables in the Database
*/
$update_room->bind_param('i', $idRoomPerson);
//Execute query
if ($update_room->execute())
{
$insertedRows = $update_room->affected_rows;
$message = ($insertedRows > 0) ? "The person in the system has been correctly registered." : "It was not possible to register the person, try again later." . $update_room->error;
$result['message'] = $message;
}
else
{
$result['message'] = "An error has occurred: " . $mysqli->error;
}
}
else
{
$result['message'] = "An error has occurred: " . $mysqli->error;
}
}
}
else
{
$result['message'] = "The request with the respective POST method is inappropriate for the URL visited.";
}
}
else
{
$result['message'] = "The connection could not be established.";
}
echo json_encode($result);
?>
</code></pre>
<p><strong>Questions</strong></p>
<ol>
<li>Is this the correct way to perform the multiple processes shown in the script?</li>
<li>If a process fails, what is expected is that at some point modifications are made to the database, but does not allow it to be an integral way. Let me explain: It is consulted, it is registered but it is not updated by x or and reason, the script failed, so at the time it would not register the increase in the room. What would be the ideal way to guarantee the executions and if one fails to undo the changes?</li>
<li>What is there to improve in the script?</li>
<li>In terms of security, how vulnerable can it be?</li>
</ol>
<p><strong>Improvements</strong></p>
<ol>
<li><p>By A. Cedano's suggestions I made the respective change <code>die('SQL Error:'.$query->error);</code> to be controlled by a message in JSON.</p></li>
<li><p>The conditional <code><= a <</code> of the first query is changed since, being less or equal, it would enable the person to pass, leaving the <code>current_capacity_room</code> in a value greater than the <code>capacity_room</code> at the moment of updating. That is, if the visit were at its maximum capacity (12) and was to consult for the access of another person, being <code>12 <= a 12</code> would enable the step and would increase one person leaving the c<code>urrent_capacity_room</code> in 13.</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:20:20.790",
"Id": "402940",
"Score": "0",
"body": "Who is A. Cedano? And why a client should be concerned about prepare() function's failure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T19:18:07.043",
"Id": "402977",
"Score": "0",
"body": "You are asking how to ensure consistency when multiple SQL operations are involved, but your code currently doesn't do that correctly, which makes your question off-topic for Code Review. (See the [help/on-topic].) Hint: you want to use [transactions](https://dev.mysql.com/doc/refman/8.0/en/commit.html)."
}
] | [
{
"body": "<p>In general, there is A LOT of unnecessary and useless code, the whole stuff could be written in a few lines</p>\n\n<pre><code><?php\nheader(\"Context-type: application/json;\");\nrequire '../Connection/connection.php';\nsession_start();\n$idCompany = $_SESSION['user']['id_company'];\n$_POST = json_decode(file_get_contents('php://input'), true);\n$result= array();\n\nif($_POST)\n{\n $consult = $mysqli->prepare(\"SELECT 1 FROM room WHERE id_room = ? \n AND current_capacity_room < capacity_room AND id_company = ?\");\n $consult->bind_param('ii', $_POST['id_room_person'], $idCompany);\n $consult->execute();\n if ($consult->fetch() !== true)\n {\n $result['message'] = \"The room does not have enough capacity to register.\";\n } else {\n $sql = \"INSERT INTO `person`(`id_person`, `name_person`, `document_person`,\n `date_admission_person`, `id_document_type_person`,\n `id_blood_type_person`, `id_room_person`)\n VALUES (NULL, ?, ?, CURDATE(), ?, ?, ?)\";\n $stmt = $mysqli->prepare($consult_sql);\n $insert_person->bind_param('ssiii', $_POST['name_person'],\n $_POST['document_person'],\n $_POST['id_document_type_person'],\n $_POST['id_blood_type_person'],\n $_POST['id_room_person']);\n $insert_person->execute();\n $result['message'] = \"The person in the system has been correctly registered.\";\n }\n}\necho json_encode($result);\n</code></pre>\n\n<p>Basically, to improve this code, you must </p>\n\n<ul>\n<li>move setting the db charset into connection.php and also set the proper error reporting for mysqli. See a correct example for connection.php in my article, <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">How to properly connect to Mysql database using mysqli</a>.</li>\n<li>set up a <strong>proper</strong> error handler for your code. A <a href=\"https://phpdelusions.net/pdo/common_mistakes#json\" rel=\"nofollow noreferrer\">a simple error handler for JSON API</a> can be seen also in my other article.</li>\n<li>as a result, remove all laborious error checking code blocks</li>\n<li>remove the code that is just useless, like \n\n<ul>\n<li><code>if ($mysqli)</code> an error handler should handle this</li>\n<li><code>isset($_POST)</code> it makes no sense to test if a variable is set if it was defined two lines above</li>\n<li><code>!empty($_POST)</code> same</li>\n<li><code>$consult->next_result()</code> makes no sense. there is no extra resultset</li>\n<li><code>$consult->free_result()</code> useless</li>\n<li>... etc.</li>\n</ul></li>\n<li>such a prolific commenting is also considered a bad practice. A skilled in Engish programmer could tell that a code <code>require '../Connection/connection.php';</code> does include a connection with the db.</li>\n</ul>\n\n<p>But what you should really think of is a race condition when inbetween your select and insert queries squeezed another select query and you will have 9 spaces occupied. Answers can be found on Stack Overflow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T19:22:43.490",
"Id": "402978",
"Score": "0",
"body": "You're right, but I have a little question, what can I do with the query that update data on the same script that you've written?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T19:47:32.873",
"Id": "402981",
"Score": "0",
"body": "Sorry I don't quite get what you mean"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T19:53:22.670",
"Id": "402983",
"Score": "0",
"body": "Look my code and I've written three different operations, READ, INSERT and UPDATE. In your script you just wrote two of them (READ and INSERT)... So part, I'm trying to improve my code and how to ensure consistency when multiple SQL operations are involved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T19:56:40.293",
"Id": "402985",
"Score": "0",
"body": "Ah sorry. Indeed I missed it. To ensure the consistency *transactions* are used. They guarantee that wither all or none statements were successfully executed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T20:05:23.753",
"Id": "402986",
"Score": "0",
"body": "Can you show me how?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T20:10:08.093",
"Id": "402987",
"Score": "1",
"body": "I've got an example for [PDO transactions](https://phpdelusions.net/pdo#transactions), for mysqli it's pretty much the same. But really it's off topic already. Try to google your question"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:47:58.830",
"Id": "208636",
"ParentId": "208621",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208636",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:00:50.570",
"Id": "208621",
"Score": "0",
"Tags": [
"php"
],
"Title": "Performing multiple CRUD processes"
} | 208621 |
<p>Any tips or improvement to speed my code? I'm looping each file in the specify folder and subfolders. I will open each file and get the values I need and copy it to my activesheet. It is taking quit some time, any tips to help?</p>
<pre><code>FolderName = InputBox("Enter path", "Get File")
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder(FolderName)
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
For Each oSubfolder In oFolder.SubFolders
If UCase(oSubfolder.Name) <> "DO NOT USE" Then
queue.Add oSubfolder 'enqueue
Else
End If
Next oSubfolder
Dim lastUsedRow As Long
lastUsedRow = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row + 1
For Each oFile In oFolder.Files
'Process each file but exclude files such as "~xxxxxx" or thumbs.db or xxxx.tmp files
If oFile.Type = "Microsoft Excel Worksheet" Then
If Not oFile.Name Like "*~*" Then
Dim app As New Excel.Application
Dim Filename As String
Filename = oFile.Path
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(Filename)
ActiveSheet.Range("A" & lastUsedRow) = oFile.Name
ActiveSheet.Range("B" & lastUsedRow) = oFile.DateCreated
ActiveSheet.Range("E" & lastUsedRow) = book.Sheets("mySheet").Range("D3").Value
ActiveSheet.Range("F" & lastUsedRow) = book.Sheets("mySheet").Range("G12").Value
ActiveSheet.Range("G" & lastUsedRow) = book.Sheets("mySheet").Range("C9").Value
ActiveSheet.Range("H" & lastUsedRow) = book.Sheets("mySheet").Range("C13").Value
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
lastUsedRow = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row + 1
End If
End If
Next oFile
Loop
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:38:56.773",
"Id": "402922",
"Score": "0",
"body": "Other than some minor tweaks like `With` blocks, I doubt you're going to speed this up much - you're opening files so this is largely IO bound."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:39:13.563",
"Id": "402923",
"Score": "0",
"body": "You're creating a new `Excel.Application` instance for each file in the folder, as well as a new file altogether... is that intended? In any case, the `app` instance should be pulled out of the loop, and if the code is hosted in Excel then there's no need to even create an instance of it. `As New` is also interfering with the `=Nothing` assignment at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:43:21.340",
"Id": "402926",
"Score": "0",
"body": "Depends what you need to do, but as a rule of thumb I see no need to re-instantiate Excel *for every single file you want to process* when you're already in Excel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:38:51.810",
"Id": "402964",
"Score": "1",
"body": "Welcome To Code Review! I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
}
] | [
{
"body": "<p>As Mathieu Guindon mentioned in the comments, the main slow down is that you are creating a new Excel.Application for each file. I would personally just use the current Application and turn off <code>Application.ScreenUpdating</code>.</p>\n\n<p>Using an <code>InputBox</code> to prompt an user to enter a folder path is very prone to error. You should test if the folder exists.</p>\n\n<blockquote>\n<pre><code>FolderName = InputBox(\"Enter path\", \"Get File\")\nDo While Len(Dir(FolderName, vbDirectory)) = 0\n If Len(Dir(FolderName, vbDirectory)) = 0 Then\n If MsgBox(\"Do you wish to continue?\", vbYesNo, \"Invalid Folder\") <> vbYes Then\n Exit Sub\n Else\n FolderName = InputBox(\"Enter path\", \"Get File\")\n End If\n End If\nLoop\n</code></pre>\n</blockquote>\n\n<p>Or better yet just use <code>Application.FileDialog(msoFileDialogFolderPicker)</code> to pick the folder. It's the right tool for the job.</p>\n\n<p>Using an Array to collect the data and writing it to a range of cells in one operation is much faster the writing each piece of data to an individual cell.</p>\n\n<h2>Refactored Code</h2>\n\n<p>Here is how I would write the code. Notice that I created a subroutine to collect the files and another to get the Folder Path. This allows me to debug each part of the code separately. </p>\n\n<pre><code>Sub LoopFoldersAndXLFiles()\n Dim t As Double: t = Timer\n Const SheetName As Variant = 1\n Dim FileList As Collection\n addExcelFileList FileList\n If FileList.Count = 0 Then Exit Sub\n\n Dim oFile As Object, xlApp As New Excel.Application\n Dim r As Long\n Dim results() As Variant\n ReDim results(1 To FileList.Count, 1 To 8)\n For r = 1 To FileList.Count\n Set oFile = FileList(r)\n With xlApp.Workbooks.Add(oFile.Path)\n results(r, 1) = oFile.Name\n results(r, 2) = oFile.DateCreated\n results(r, 5) = .Sheets(SheetName).Range(\"D3\").Value\n results(r, 6) = .Sheets(SheetName).Range(\"G12\").Value\n results(r, 7) = .Sheets(SheetName).Range(\"C9\").Value\n results(r, 8) = .Sheets(SheetName).Range(\"C13\").Value\n .Close SaveChanges:=False\n End With\n Next\n\n xlApp.Quit\n\n With ActiveSheet\n With .Range(\"A\" & .Rows.Count).End(xlUp).Offset(1)\n .Resize(UBound(results), UBound(results, 2)).Value = results\n End With\n End With\n Debug.Print Round(Timer - t, 2)\nEnd Sub\n\nSub addExcelFileList(ByRef FileList As Collection, Optional FolderName As String, Optional fso As Object)\n If Len(FolderName) = 0 Then\n FolderName = getFolderPath\n If Len(FolderName) = 0 Then Exit Sub\n End If\n If FileList Is Nothing Then Set FileList = New Collection\n If fso Is Nothing Then Set fso = CreateObject(\"Scripting.FileSystemObject\")\n\n Dim oFolder As Object, oSubfolder As Object\n\n Set oFolder = fso.GetFolder(FolderName)\n\n For Each oSubfolder In oFolder.SubFolders\n If UCase(oSubfolder.Name) <> \"DO NOT USE\" Then addExcelFileList FileList, oSubfolder.Path, fso\n Next\n\n Dim oFile As Object\n For Each oFile In oFolder.Files\n If oFile.Type = \"Microsoft Excel Worksheet\" And Not oFile.Name Like \"*~*\" Then FileList.Add oFile\n Next\nEnd Sub\n\nFunction getFolderPath() As String\n With Application.FileDialog(msoFileDialogFolderPicker)\n .Title = \"Select a Folder\"\n .AllowMultiSelect = False\n .InitialFileName = Application.DefaultFilePath\n If .Show <> -1 Then Exit Function\n getFolderPath = .SelectedItems(1)\n End With\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:32:57.200",
"Id": "402961",
"Score": "0",
"body": "this works but it's actually slower than what i have after I modified it to work. I will edit my post."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T18:02:37.620",
"Id": "208637",
"ParentId": "208622",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "208637",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T15:24:04.947",
"Id": "208622",
"Score": "0",
"Tags": [
"vba"
],
"Title": "Loop each folder and subfolder to get values"
} | 208622 |
<p>I develop this mini project as an exercise. It is a simplified employee salary calculator.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>Employees are characterized by name, employment date, employee group and base salary.</li>
<li>There are three groups of employees: Employee, Manager, Salesman.</li>
<li>Each employee might have a supervisor.</li>
<li>Each employee except "Employee" group might have subordinates of any group.</li>
<li><p>Salary should be calculated the following way:</p>
<ul>
<li><p>For "Employee" group - base salary + 3% for each year of work since employment date, but no more than 30% over.</p></li>
<li><p>For "Manager" group - base salary + 5% for each year of work, but no more than 40% over + 0,5% of salary of all direct(first level) subordinates.</p></li>
<li><p>For "Salesman" group - base salary + 1% for each year of work, but no more than 35% over + 0,3% of salary of ALL subordinates, direct or indirect.</p></li>
</ul></li>
<li><p>The app should allow a user to get calculated salary of any selected employee at any given moment as well as summary of ALL company employees' salaries.</p></li>
</ul>
<p><strong>My solution:</strong></p>
<pre><code>public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime EmploymentDate { get; set; }
public string EmployeeGroup { get; set; }
public int BaseSalary { get; set; }
public int? SupervisorId { get; set; }
public string Lineage { get; set; }
public int Depth { get; set; }
public Employee Supervisor { get; set; }
public List<Employee> Subordinates { get; set; }
}
public class EmployeesDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public EmployeesDbContext(DbContextOptions<EmployeesDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasOne(e => e.Supervisor)
.WithMany(e => e.Subordinates)
.HasForeignKey(e => e.SupervisorId);
}
}
public interface IEmployeeRepository
{
void Add(Employee employee);
void AddRange(IEnumerable<Employee> employees);
void Delete(Employee employee);
Task<List<Employee>> ListAllAsync();
Task<Employee> FindByIdAsync(int id);
Task<List<Employee>> GetAllSubordinatesAsync(Employee employee);
Task<List<Employee>> GetFirstLevelSubordinatesAsync(Employee employee);
IQueryable<Employee> GetAsQueryable();
Task<int> GetEmployeeTreeDepth();
Task<List<Employee>> GetAllOfLevel(int depth);
Task SaveChangesAsync();
}
public class EmployeeRepository : IEmployeeRepository
{
private readonly EmployeesDbContext _employeesDbContext;
public EmployeeRepository(EmployeesDbContext dbContext)
{
_employeesDbContext = dbContext;
}
public void Add(Employee employee)
{
_employeesDbContext.Add(employee);
}
public void Delete(Employee employee)
{
_employeesDbContext.Remove(employee);
}
public void AddRange(IEnumerable<Employee> employees)
{
_employeesDbContext.AddRange(employees);
}
public async Task<List<Employee>> GetAllSubordinatesAsync(Employee employee)
{
var result = await _employeesDbContext.Employees
.FromSql("SELECT * FROM Employees WHERE lineage LIKE '{0}-%'", employee.Lineage)
.ToListAsync();
return result;
}
public async Task<Employee> FindByIdAsync(int id)
{
return await _employeesDbContext.FindAsync<Employee>(id);
}
public async Task<List<Employee>> GetFirstLevelSubordinatesAsync(Employee employee)
{
var result = await _employeesDbContext.Employees
.FromSql("SELECT * FROM Employees WHERE lineage LIKE '{0}-%' AND depth = {1}", employee.Lineage, employee.Depth + 1)
.ToListAsync();
return result;
}
public async Task<List<Employee>> ListAllAsync()
{
return await _employeesDbContext.Employees.AsNoTracking().ToListAsync();
}
public IQueryable<Employee> GetAsQueryable()
{
return _employeesDbContext.Employees.AsQueryable().AsNoTracking();
}
public async Task<int> GetEmployeeTreeDepth()
{
return await _employeesDbContext.Employees.MaxAsync(e => e.Depth);
}
public async Task<List<Employee>> GetAllOfLevel(int depth)
{
return await _employeesDbContext.Employees.Where(e => e.Depth == depth).ToListAsync();
}
public async Task SaveChangesAsync()
{
await _employeesDbContext.SaveChangesAsync();
}
}
public interface ISalaryCalculator
{
Task<int> CalculateSalaryAsync(Employee employee);
Task<int> CalculateSalariesSumAsync();
}
public class SalaryCalculator : ISalaryCalculator
{
private readonly ISalaryCalculatorFactory _salaryCalculatorFactory;
private readonly IEmployeeRepository _employeeRepository;
public SalaryCalculator(ISalaryCalculatorFactory salaryCalculatorFactory, IEmployeeRepository employeeRepository)
{
_salaryCalculatorFactory = salaryCalculatorFactory;
_employeeRepository = employeeRepository;
}
public async Task<int> CalculateSalariesSumAsync()
{
var employees = await _employeeRepository.ListAllAsync();
IEnumerable<Task<int>> calcSalaryTasksQuery = employees.Select(e => CalculateSalaryAsync(e));
Task<int>[] calcSalaryTasks = calcSalaryTasksQuery.ToArray();
int[] salaries = await Task.WhenAll(calcSalaryTasks);
var salarySum = salaries.Sum();
return salarySum;
}
public async Task<int> CalculateSalaryAsync(Employee employee)
{
var calculator = _salaryCalculatorFactory.CreateCalculator(employee.EmployeeGroup);
var salary = await calculator.CalculateSalaryAsync(employee);
return salary;
}
}
public interface ISalaryCalculatorFactory
{
BaseSalaryCalculator CreateCalculator(string employeeGroup);
}
public class SalaryCalculatorFactory : ISalaryCalculatorFactory
{
private Dictionary<string, Func<BaseSalaryCalculator>> salaryCalculators;
public SalaryCalculatorFactory(IEmployeeRepository employeeRepository)
{
salaryCalculators = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => typeof(BaseSalaryCalculator).IsAssignableFrom(t) && t.IsAbstract == false)
.Select(t => new Func<BaseSalaryCalculator>(() => Activator.CreateInstance(t,employeeRepository, this) as BaseSalaryCalculator))
.ToDictionary(f => f().EmployeeGroup);
}
public BaseSalaryCalculator CreateCalculator(string employeeGroup)
{
return salaryCalculators[employeeGroup]();
}
}
public abstract class BaseSalaryCalculator
{
public abstract string EmployeeGroup { get; }
protected readonly IEmployeeRepository _employeeRepository;
protected readonly ISalaryCalculatorFactory _salaryCalculatorFactory;
protected BaseSalaryCalculator(IEmployeeRepository employeeRepository, ISalaryCalculatorFactory salaryCalculatorFactory)
{
_employeeRepository = employeeRepository;
_salaryCalculatorFactory = salaryCalculatorFactory;
}
public abstract Task<int> CalculateSalaryAsync(Employee employee);
protected int CalcEmployeeExperience(DateTime employmentDate)
{
return (int)Math.Floor(DateTime.Now.Subtract(employmentDate).TotalDays / 365);
}
protected int CalcExperiencePremium(int baseSalary, int premiumPercentForEachYearExp, int maxExperiencePremiumPercent, int experience)
{
var experiencePremium = baseSalary / 100 * premiumPercentForEachYearExp;
var maxExpPremium = baseSalary / 100 * maxExperiencePremiumPercent;
var premium = experiencePremium * experience;
if (premium > maxExpPremium) premium = maxExpPremium;
return premium;
}
protected async Task<int> CalcSupervisorPremium(IEnumerable<Employee> subordinates, float supervisorPremiumPercent)
{
int salarySum = 0;
foreach (var employee in subordinates)
{
var calculator = _salaryCalculatorFactory.CreateCalculator(employee.EmployeeGroup);
var salary = await calculator.CalculateSalaryAsync(employee);
salarySum += salary;
}
var premium = (int)Math.Ceiling(salarySum / 100 * supervisorPremiumPercent);
return premium;
}
}
public class EmployeeSalaryCalculator : BaseSalaryCalculator
{
public override string EmployeeGroup => "Employee";
private const int _premiumPercentForEachYearExp = 3;
private const int _maxExperiencePremiumPercent = 30;
public EmployeeSalaryCalculator(IEmployeeRepository employeeRepository, ISalaryCalculatorFactory salaryCalculatorFactory)
: base(employeeRepository, salaryCalculatorFactory)
{
}
public override async Task<int> CalculateSalaryAsync(Employee employee)
{
var salary = await Task.Run(() =>
{
var experience = CalcEmployeeExperience(employee.EmploymentDate);
var experiencePremium = CalcExperiencePremium(employee.BaseSalary, _premiumPercentForEachYearExp, _maxExperiencePremiumPercent, experience);
var totalSalary = employee.BaseSalary + experiencePremium;
return totalSalary;
});
return salary;
}
}
public class ManagerSalaryCalculator : BaseSalaryCalculator
{
public override string EmployeeGroup => "Manager";
private const int _premiumPercentForEachYearExp = 5;
private const int _maxExperiencePremiumPercent = 40;
private const float _supervisorPremiumPercent = 0.5f;
public ManagerSalaryCalculator(IEmployeeRepository employeeRepository, ISalaryCalculatorFactory salaryCalculatorFactory)
: base(employeeRepository, salaryCalculatorFactory)
{
}
public override async Task<int> CalculateSalaryAsync(Employee employee)
{
var experience = CalcEmployeeExperience(employee.EmploymentDate);
var experiencePremium = CalcExperiencePremium(employee.BaseSalary, _premiumPercentForEachYearExp, _maxExperiencePremiumPercent, experience);
var subordinates = await _employeeRepository.GetFirstLevelSubordinatesAsync(employee);
var supervisorPremium = await CalcSupervisorPremium(subordinates, _supervisorPremiumPercent);
var totalSalary = employee.BaseSalary + experiencePremium + supervisorPremium;
return totalSalary;
}
}
public class SalesmanSalaryCalculator : BaseSalaryCalculator
{
public override string EmployeeGroup => "Salesman";
private const int _premiumPercentForEachYearExp = 1;
private const int _maxExperiencePremiumPercent = 35;
private const float _supervisorPremiumPercent = 0.3f;
public SalesmanSalaryCalculator(IEmployeeRepository employeeRepository, ISalaryCalculatorFactory salaryCalculatorFactory)
: base(employeeRepository, salaryCalculatorFactory)
{
}
public override async Task<int> CalculateSalaryAsync(Employee employee)
{
var experience = CalcEmployeeExperience(employee.EmploymentDate);
var experiencePremium = CalcExperiencePremium(employee.BaseSalary, _premiumPercentForEachYearExp, _maxExperiencePremiumPercent, experience);
var subordinates = await _employeeRepository.GetAllSubordinatesAsync(employee);
var supervisorPremium = await CalcSupervisorPremium(subordinates, _supervisorPremiumPercent);
var totalSalary = employee.BaseSalary + experiencePremium + supervisorPremium;
return totalSalary;
}
}
</code></pre>
<p>As you can see I ended up with a kind of circular dependency between SalaryCalculatorFactory and specific calculators it creates. And I don't know how to solve this elegantly and avoid duplicate code in <code>CalcSupervisorPremium</code> method without creating the circular dependency and tight coupling (or it is okay and there's a good way to call SalaryCalculator's method, I don't know).
It seems this circularity is a natural part of the algorithm since to calculate some managers' and salesmans' salaries we need to calculate salaries of their subordinates. </p>
<p>So, how to improve the design?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:34:52.247",
"Id": "402946",
"Score": "6",
"body": "If you downvote, explain why, please."
}
] | [
{
"body": "<p>You should use <code>decimal</code> or at least <code>double</code> as data type for financial figures. You usually operate with (at least) two decimals in financial calculations.</p>\n\n<hr>\n\n<p><code>IEmployeeRepository</code> should inherit from <code>IDisposable</code> to force implementers to implement <code>IDisposable</code> to dispose of the <code>EmployeesDbContext</code> instance. \n And that means that <code>ISalaryCalculator</code> should do the same in order to dispose of the <code>EmployeeRepository</code> instance.</p>\n\n<hr>\n\n<p>I'm not sure I understand the \"Lineage\" concept. To me it looks like you \n maintain two parent-child relationships on the same objects: <code>Subordinaries</code> and <code>Lineage</code> (and what role has the <code>SupervisorId</code>\n in that equation?) Why don't you rely on the hierarchical\n relationship through <code>Subordinates</code> (maintained through the navgation property(ies))?</p>\n\n<hr>\n\n<p>There is a \"conceptual meltdown\" in having <code>CalcSupervisorPremium(...)</code> as a member of the <code>BaseSalaryCalculator</code>\n because it is a specialization of the common salary calculation - related only to certain employee types.\n I would create an <code>abstract class SupervisorSalaryCalculator : BaseSalaryCalculator</code> as base class for <code>ManagerSalaryCalculator</code> and <code>SalesmanSalaryCalculator</code>\n and because the two sub classes are almost identical except for the values of their members you can let the new base class do the calculations:</p>\n\n<pre><code> public abstract class SupervisorSalaryCalculator : BaseSalaryCalculator\n {\n public override string EmployeeGroup { get; }\n private int PremiumPercentForEachYearExp { get; }\n private int MaxExperiencePremiumPercent { get; }\n private float SupervisorPremiumPercent { get; }\n\n public SupervisorSalaryCalculator(\n string employeeGroup, \n int experienceRate, \n int experienceRateMax,\n float supervisorRate,\n IEmployeeRepository employeeRepository, \n ISalaryCalculatorFactory salaryCalculatorFactory)\n : base(employeeRepository, salaryCalculatorFactory)\n {\n EmployeeGroup = employeeGroup;\n PremiumPercentForEachYearExp = experienceRate;\n MaxExperiencePremiumPercent = experienceRateMax;\n SupervisorPremiumPercent = supervisorRate;\n }\n\n protected async Task<int> CalcSupervisorPremium(IEnumerable<Employee> subordinates, float supervisorPremiumPercent)\n {\n int salarySum = 0;\n foreach (var employee in subordinates)\n {\n var calculator = _salaryCalculatorFactory.CreateCalculator(employee.EmployeeGroup);\n var salary = await calculator.CalculateSalaryAsync(employee);\n salarySum += salary;\n }\n var premium = (int)Math.Ceiling(salarySum / 100 * supervisorPremiumPercent);\n return premium;\n }\n\n async public override Task<int> CalculateSalaryAsync(Employee employee)\n {\n var experience = CalcEmployeeExperience(employee.EmploymentDate);\n var experiencePremium = CalcExperiencePremium(employee.BaseSalary, PremiumPercentForEachYearExp, MaxExperiencePremiumPercent, experience);\n var subordinates = await GetSubordinatesAsync(employee);\n var supervisorPremium = await CalcSupervisorPremium(subordinates, SupervisorPremiumPercent);\n var totalSalary = employee.BaseSalary + experiencePremium + supervisorPremium;\n return totalSalary;\n }\n\n abstract protected Task<List<Employee>> GetSubordinatesAsync(Employee employee);\n }\n\n public class ManagerSalaryCalculator : SupervisorSalaryCalculator\n {\n public ManagerSalaryCalculator(IEmployeeRepository employeeRepository, ISalaryCalculatorFactory salaryCalculatorFactory)\n : base(\"Manager\", 5, 40, 0.5f, employeeRepository, salaryCalculatorFactory)\n {\n }\n\n async protected override Task<List<Employee>> GetSubordinatesAsync(Employee employee)\n {\n return await _employeeRepository.GetFirstLevelSubordinatesAsync(employee);\n }\n }\n\n public class SalesmanSalaryCalculator : SupervisorSalaryCalculator\n {\n public SalesmanSalaryCalculator(IEmployeeRepository employeeRepository, ISalaryCalculatorFactory salaryCalculatorFactory)\n : base(\"Salesman\", 1, 35, 0.3f, employeeRepository, salaryCalculatorFactory)\n {\n }\n\n async protected override Task<List<Employee>> GetSubordinatesAsync(Employee employee)\n {\n return await _employeeRepository.GetAllSubordinatesAsync(employee);\n }\n }\n</code></pre>\n\n<hr>\n\n<p>The calculation of years of employment is not always correct.\n Try for instance <code>employmentDate = new DateTime(2000, 12, 3)</code> and <code>now = new DateTime(2018, 11, 29)</code>\n It will give 18 years, where it should give 17 (whole) years, while <code>employmentDate = new DateTime(2000, 12, 7)</code>\n gives the correct 17 for the same <code>now</code> value. 365 is not a reliable number of days per year.</p>\n\n<p>Instead you can do something like this:</p>\n\n<pre><code> years = now.Year - employmentDate.Year;\n if (now.Date < employmentDate.AddYears(years).Date)\n years--;\n return years;\n</code></pre>\n\n<p>Not very fancy but more reliable.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public SalaryCalculatorFactory(IEmployeeRepository employeeRepository)\n{\n salaryCalculators = Assembly.GetExecutingAssembly().GetTypes()\n .Where(t => typeof(BaseSalaryCalculator).IsAssignableFrom(t) && t.IsAbstract == false)\n .Select(t => new Func<BaseSalaryCalculator>(() => Activator.CreateInstance(t,employeeRepository, this) as BaseSalaryCalculator))\n .ToDictionary(f => f().EmployeeGroup);\n}\n</code></pre>\n</blockquote>\n\n<p>To investigate all types in an <code>assembly</code> to find the few you can use may be an expensive task every time the salary factory is created. If working\n in a large assembly with lots of types, that may be a bottleneck. You'll have to measure on that. You could consider to make the calculator dictionary static, so it is only loaded once, or \n have the calculators in a dedicated assembly, and/or read the types from a configuration file.</p>\n\n<hr>\n\n<p>Your naming is very descriptive, but some names maybe a little too much: <code>premiumPercentForEachYearExp</code>; \n maybe <code>experienceRate</code> or the like would be descriptive enough? IMO both abbreviated and too long names influence the readability negatively.</p>\n\n<p>More about naming:</p>\n\n<p>You have <code>SalaryCalculator</code> which is the main \"interface\" for clients to use and then you have <code>BaseSalaryCalculator</code> etc. which takes care of the \n actual calculations. Maybe a little confusing with the similar names, when they are not directly related? - if confused me at least.</p>\n\n<hr>\n\n<p>According to the overall design and structure, you show good understanding of dependency injection, dependency inversion, repository and factory patterns\n and having these concepts at hand is very useful when it comes to larger projects. But here the amount of code lines seems rather overwhelming, which is increased by your rather verbose naming style.</p>\n\n<p>But then again the overall impression is a code that is thought through and well-structured. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:13:01.333",
"Id": "403133",
"Score": "1",
"body": "Very good answer except ... `Decimal` for salary always and never `Double`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T19:45:17.947",
"Id": "403165",
"Score": "1",
"body": "Ditto @RickDavin. DoctorWhy, Use every coding task as an opportunity to [read the documentation](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal) even if it is only a review for you . It's especially helpful at that time because you have use case context."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:35:04.567",
"Id": "208695",
"ParentId": "208635",
"Score": "4"
}
},
{
"body": "<p><strong>Think separation of concerns</strong></p>\n\n<blockquote>\n <p>I ended up with a kind of circular dependency between SalaryCalculatorFactory and specific calculators</p>\n</blockquote>\n\n<p>The SalaryCalculator design conflates its proper functions with the using/client code. That is why you have that dependency problem. Think of objects as doing a discrete thing and then separately think about the code using it.</p>\n\n<hr>\n\n<p><strong>Factory</strong></p>\n\n<p>Keeping a factory reference in the class it creates doesn't make sense. A factory builds stuff, that's all. It should not keep anything on behalf of what it creates. Just like after a car rolls off the assembly line, the factory has nothing to do with it. There <s>are</s> will be other entities for that.</p>\n\n<p>Tell the factory what to build and have that returned; done. If a collection class holding all the instantiated calculators is needed then make one, don't use the factory for that - it's not a warehouse.</p>\n\n<hr>\n\n<p><strong><code>enum</code> is your friend</strong></p>\n\n<p>Use <code>enum</code> to define employee groups. It avoids all the problems using strings. <code>enum</code> is type safe, and best of all it shows up in intellisense. Typos are caught at compile time. <code>enum</code> has a very documenting quality. Here, you're declaring all employee groups that exist, named \"EmployeeGroup\", and very significantly <em>in one place.</em></p>\n\n<hr>\n\n<p><strong>Zombie <code>interface</code>s</strong></p>\n\n<p>The code smells:</p>\n\n<ul>\n<li>The fact that there are specific custom calculators tells me that all those (\"capital I\") interfaces are not used effectively. </li>\n<li>a general/abstract \"calculate\" method is not defined anywhere. </li>\n<li>object reference variables are not of the interface types.</li>\n</ul>\n\n<p>My Spidey Sense ™ tells me you are thinking you must use interfaces and this imperative is over-powering coherent, sensible design. The principle <em>code to interfaces not implementation</em> does not mean only \"capital I\" <code>interface</code>. \"interface\" can mean an <code>interface</code>, <code>abstract class</code>, delegates and even, I do dare say, a concrete class. </p>\n\n<p><code>interface</code> is not needed in the calculator design. Get rid of them. </p>\n\n<hr>\n\n<p>Do not imbed implementation details in variable names. Do.not.do.this. Do not use type either - no \"intSalary\", \"objEmployee\", etc - you don't do that, I'm just saying. Good class names and use-variable names give plenty of context. client code should not know and does not care about these things. </p>\n\n<pre><code>CalculateSalariesSumAsync(); // no\nCalculateSalaries(); // much better\n</code></pre>\n\n<hr>\n\n<p><strong>Calculator Design</strong></p>\n\n<p>Insight: Calculators are all the same, they all <code>CalcSalary()</code>. Only one class needed. We just need a way to insert the one thing that does change - the calculating algorithm code. </p>\n\n<p>Insight: Don't try to design everything all at once. The basic calculator here, I'll worry about the factory next. I'll think about how to get calculators and employee lists [do not imply any specific implementation] together later.</p>\n\n<p>Insight: You will modify classes as design progresses. Don't worry about it.</p>\n\n<p>So I'm picturing this:</p>\n\n<pre><code> SalaryFactory salaryGenerator = new SalaryFactory();\n SalaryCalculator employeeCalculator = salaryGenerator.Create( EmployeeGroup.Employee );\n SalaryCalculator managerCalculator = salaryGenerator.Create( EmployeeGroup.Manager );\n SalaryCalculator salesmanCalculator = salaryGenerator.Create( EmployeeGroup.Salesman ); \n</code></pre>\n\n<p>And a couple possibilities for SalaryCalculator class:</p>\n\n<p>Oh, Look Mo! A concrete class as interface.</p>\n\n<pre><code>public class SalaryCalculator {\n public SalaryCalculator(Func<decimal> algorithm){\n SalaryAlgorithm = algorithm;\n }\n public Func<decimal> CalcSalary ( ) { return SalaryAlgorithm(); }\n\n protected Func<decimal> SalaryAlgorithm; // the factory supplies this\n}\n</code></pre>\n\n<p>I like abstract classes a lot:</p>\n\n<pre><code>public abstract class SalaryCalculator {\n\n abstract public Func<decimal> CalcSalary ( ) { ... } // the factory supplies this\n}\n</code></pre>\n\n<hr>\n\n<p><strong><code>interface</code>, <code>abstract class</code>, concrete <code>class</code></strong></p>\n\n<p>First, it all depends on overall design. Nothing is absolute.</p>\n\n<p>Generally an <code>interface</code> is for giving unrelated classes common behavior. With inheritance an <code>abstract class</code> is my first choice. A concrete <code>class</code> is a valid choice because we can still use composition, that's what constructors are for.</p>\n\n<p><code>abstract class</code> allows for both base implementation and \"placeholder\" declarations a-la <code>interface</code>. Mixing these two features in the code flow/logic is called a Template Pattern (google it). </p>\n\n<p>Using <code>interface</code> and then hoping every class implements base functionality the same is delusional. </p>\n\n<hr>\n\n<p><strong>group salaries</strong></p>\n\n<p>Group functionality is distinct from individual employee functionality and should be a separate class, even if group salary is the only group function (for now).</p>\n\n<p>The goal is a general <code>Employees</code> class that can participate in a composition to calculate manager salaries. </p>\n\n<hr>\n\n<p><strong>single responsibility</strong></p>\n\n<ul>\n<li>A factory should only create objects.</li>\n<li>A employee class should be only about and directly about an individual employee.</li>\n<li>A calculator should only calculate salary and not care who, what, where, why it's calculate function was called.</li>\n<li>Group functionality uses a collection of these \"individual\" objects and are their own classes.</li>\n</ul>\n\n<p>Uh-oh! Bob is suggesting more classes. Yes. Yes I am. This is the nature good OO design. You end up with classes doing higher level/complex things which are compositions of more basic classes, every class lazer focused on doing it's own thing. </p>\n\n<hr>\n\n<p><strong>Employees</strong></p>\n\n<p>I see a general <code>Employees</code> class that contains a <code>List<Employee></code> with functionality like this:</p>\n\n<pre><code>public class Employees {\n // List may or may not be the ideal choice for the collection. It depends. \n protected List<Employee> Employees {get; set;}\n\n public decimal GroupSalary() {\n var decimal groupSalary = 0;\n\n forEach(var employee in this.Employees) {\n groupSalary += employee.Salary();\n }\n return groupSalary;\n }\n\n // all other group functionality as needed.\n}\n</code></pre>\n\n<p>I did not create a <code>GroupSalary</code> property, private or otherwise. A calculated value should always be re-calculated when used/called. I guarantee future problems if you don't.</p>\n\n<p>Pending further design analysis I don't see a need for a GroupSalaryCalculator. </p>\n\n<hr>\n\n<p><strong>static</strong></p>\n\n<p>Given overall single responsibility application consider making the factory and generated calculators <code>static</code>.</p>\n\n<p><code>static</code> objects should not hold state for external objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T10:31:58.407",
"Id": "403280",
"Score": "2",
"body": "I disagree with your review that `CalculateSalariesSumAsync` should be `CalculateSalaries`. `Async` is a well-established suffix for async methods so consumers can separate sync methods from async methods. Secondly, the name `CalculateSalaries` suggests that the salaries will be calculated, but does not suggest that a sum of the salaries will be returned, which is a relevant distinction to make compared to the `CalculateSalaryAsync` method (which only calculcates a salary and does not return a sum)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T15:53:39.660",
"Id": "403322",
"Score": "0",
"body": "As a general rule one should name things for what they are/do in the context of the business domain. At first I thought `CalculateSalariesSum...` , \"sum\" was redundant. If it's not then it's a different problem. It would be crystal clear without \"sum\" if part of an `Employees` class. As for `Async` suffix I'll reflect on that. A very prevalent thing in earlier days - me too - but I've come to understand the power of good encapsulation, of which names are a key element."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T22:51:23.073",
"Id": "208727",
"ParentId": "208635",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208695",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T17:31:20.027",
"Id": "208635",
"Score": "6",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Salary-calculating classes, supporting several types of employees"
} | 208635 |
<p>I have currently two use-cases that require JSON transformations before it can be deserialized.</p>
<ul>
<li>The first use-case requires changing the custom short type property name from <code>$t</code> to <code>$type</code> and resolving full type names from their aliases. This is the same as in my <a href="https://codereview.stackexchange.com/questions/205940/making-typenamehandling-in-json-net-more-convenient">previous</a> question.</li>
<li>The second use-case is about fixing property names that contain whitespaces and need to be trimmed like <code>> Name <</code> instead of <code>>Name<</code> (yeah, I've spent quite some time spotting this mistake in a large file recently).</li>
</ul>
<p>My previous solution supported only resolving type names and was build with a custom <code>JsonTextReader</code>. Now that I wanted to add another trasnformation to it, I noticed that it cannot be chained because the reader supports forward-only reading and there is no way to add to it.</p>
<p>I've changed my strategy and used the <code>JToken.Parse</code> instead with a couple of visitors that work similar to the <code>ExpressionVisitor</code>.</p>
<p>The first one of them is the <code>JsonVisitor</code> that recursively rebuilds the tree and allows to intercept this process by overriding <code>VisitProperty</code>:</p>
<pre><code>public delegate JToken VisitJsonCallback(JToken token);
public class JsonVisitor
{
public static JToken Visit(JToken token, params JsonVisitor[] visitors)
{
return visitors.Aggregate(token, (current, visitor) => visitor.Visit(current));
}
public static VisitJsonCallback Create(params JsonVisitor[] visitors) => jToken => Visit(jToken, visitors);
public JToken Visit(JToken token)
{
return
token is JValue
? token
: VisitInternal(token, CreateJContainer(token.Type));
}
private JToken VisitInternal(JToken token, JContainer result)
{
if (token is JValue)
{
return token;
}
foreach (var element in token)
{
switch (element)
{
case JProperty property:
var visitedProperty = VisitProperty(property);
result.Add(visitedProperty);
break;
default:
result.Add(Visit(element));
break;
}
}
return result;
}
protected virtual JProperty VisitProperty(JProperty property)
{
return new JProperty(property.Name, Visit(property.Value));
}
private static JContainer CreateJContainer(JTokenType tokenType)
{
switch (tokenType)
{
case JTokenType.Object: return new JObject();
case JTokenType.Array: return new JArray();
default: throw new ArgumentOutOfRangeException($"Invalid type: {tokenType}");
}
}
}
</code></pre>
<p>Since I didn't have any other use cases yet, it's the only overridable API right now but I think it should be easy to extend it in future.</p>
<p>Then I have two more of them that cover both use-cases (here in the reverse order)</p>
<pre><code>public class PropertyNameTrimmer : JsonVisitor
{
protected override JProperty VisitProperty(JProperty property)
{
return new JProperty(property.Name.Trim(), Visit(property.Value));
}
}
public class TypeResolver : JsonVisitor
{
private readonly string _typePropertyName;
private readonly Func<string, string> _resolveType;
public TypeResolver(string typePropertyName, Func<string, string> resolveType)
{
_typePropertyName = typePropertyName;
_resolveType = resolveType;
}
protected override JProperty VisitProperty(JProperty property)
{
return
property.Name == _typePropertyName
? new JProperty("$type", _resolveType(property.Value.Value<string>()))
: base.VisitProperty(property);
}
}
</code></pre>
<hr />
<h3>Example</h3>
<p>I would use them by passing the result from one to the other:</p>
<pre><code>void Main()
{
var json = @"{ ""$t"": ""MyType"", ""User "": ""John"", ""Nested"": { ""$t"": ""OtherType"", "" ZIP"": 12345 }, ""Numbers"": [1, 2, 3 ] }";
var jToken = JToken.Parse(json);
jToken.ToString().Dump("Original");
var propertyNameTrimmer = new PropertyNameTrimmer();
var typeResolver = new TypeResolver("$t", shortName => shortName + "_resolved");
var trimmed = propertyNameTrimmer.Visit(jToken);
trimmed.ToString().Dump(nameof(PropertyNameTrimmer));
var typeResolved = typeResolver.Visit(trimmed);
typeResolved.ToString().Dump(nameof(TypeResolver));
}
</code></pre>
<p>So calling them in this order produces:</p>
<p><strong>Original</strong></p>
<pre class="lang-json prettyprint-override"><code>{
"$t": "MyType",
"User ": "John",
"Nested": {
"$t": "OtherType",
" ZIP": 12345
},
"Numbers": [
1,
2,
3
]
}
</code></pre>
<p><strong>PropertyNameTrimmer</strong> - whitespaces removed from property names</p>
<pre class="lang-json prettyprint-override"><code>{
"$t": "MyType",
"User": "John",
"Nested": {
"$t": "OtherType",
"ZIP": 12345
},
"Numbers": [
1,
2,
3
]
}
</code></pre>
<p><strong>TypeResolver</strong> - property names changed and types resolved</p>
<pre class="lang-json prettyprint-override"><code>{
"$type": "MyType_resolved",
"User": "John",
"Nested": {
"$type": "OtherType_resolved",
"ZIP": 12345
},
"Numbers": [
1,
2,
3
]
}
</code></pre>
<hr />
<p>How do you like this solution? Have I missed anything important (but null-checks) and can I improve this in any way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T09:56:02.313",
"Id": "403071",
"Score": "0",
"body": "Your visitor looks fine for what it does, but why rewrite property names instead of throwing an exception: `\"Unknown property: 'User ' at position ...\"`? That also catches other problems like typos (`\"Usr\"`) and case differences (`\"Zip\"`), which are difficult to auto-correct due to ambiguity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:02:13.243",
"Id": "403072",
"Score": "0",
"body": "@PieterWitvoet yeah, it's a tough decision and I actually wasn't sure (and I'm still not) which one would be better, fixing or throwing exceptions. I was also going to allow dashes in property names that I would rewrite to `C#` valid names. Typos are difficult to handle anyway because if a property is optional it's hard to say whether it's something else or a typo. I guess I cannot eliminate all mistakes but at least reduce the probability. Btw, json is case-insensitive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:05:34.560",
"Id": "403073",
"Score": "0",
"body": "@PieterWitvoet for a complete validation I'll probably should use json-schema but I'm not sure about its license and whether I could use it at work... most likely not so I'm not even trying but even when using json-schema I still need to rewrite some parts of it ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:24:42.283",
"Id": "403075",
"Score": "0",
"body": "JSON isn't case-insensitive, but I see what you mean - Json.NET will try to find an exact match, but falls back to a case-insensitive check. Either way, it looks like passing a `JsonSerializerSettings` instance with `MissingMemberHandling` set to `Error` should do the trick."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:31:38.703",
"Id": "403076",
"Score": "0",
"body": "@PieterWitvoet ok, it looks like you're correct with the [case sensitivity](https://stackoverflow.com/a/2738375/235671), however, I'm glad nobody takes this rule serious, it'd break the entire internet if it suddenly would be respected - I find this rule is pretty stupid ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:42:38.237",
"Id": "403078",
"Score": "0",
"body": "That's JSON-RPC, not JSON itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T08:21:45.487",
"Id": "403391",
"Score": "1",
"body": "A tiny improvement could be to insert a `case JValue value: result.Add(value); break;` in the loop in `VisitInternal(...)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T08:26:30.607",
"Id": "403394",
"Score": "0",
"body": "@HenrikHansen ah, right, good idea, this would help to avoid the unnecessary recursion and I see I can now throw away the `JValue` precondition. For `_resolveType` I use the `PrettyTypeResolver` from the [previous](https://codereview.stackexchange.com/questions/205940/making-typenamehandling-in-json-net-more-convenient) question. This is the main purpose why I build all this ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T08:29:50.063",
"Id": "403395",
"Score": "0",
"body": "@HenrikHansen the most up-to-date and working code is [here](https://github.com/he-dev/Gunter/blob/dev/Gunter/src/Services/TestFileSerializer.cs#L69) where one of my tools loads json files using the new visitor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T08:30:57.370",
"Id": "403397",
"Score": "1",
"body": "@HenrikHansen sorry, for the confusion, I only abandoned the `JsonTextReader` for transforming, I moved it's logic to the `JsonVisitor` but both are using the `PrettyTypeResolver` as a dependency. This is the nice part when you have separated everything and can change one implementation and still reuse the others ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T08:34:07.437",
"Id": "403399",
"Score": "0",
"body": "@HenrikHansen the `JsonTextReader` and `JsonVisitor` should be just seen as tools for _scanning_ a json tree and/or modifying it. The actual work is done by other components. The disadvantage of the former approach was that you cannot chain them if you would like to do more then one thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T10:48:05.097",
"Id": "403403",
"Score": "0",
"body": "@PieterWitvoet I borrowed from both ideas - I'll keep fixing property names with leading/trailing whitespace but at the same time I created another vistor that will validate property names whether they are allowed or not and this one will throw exceptions if there is an unknown one - this way I can fix what is fixable and throw where nothing can be done - this time I can have a cake and eat it too ;-)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T19:09:14.800",
"Id": "208641",
"Score": "5",
"Tags": [
"c#",
"json",
"json.net",
"visitor-pattern"
],
"Title": "Chaining JSON transformations with visitors"
} | 208641 |
<p>The program interacts between cards and four players among whom cards are to be distributed.</p>
<p>The Program do the following function </p>
<ul>
<li>Creates a deck of cards.</li>
<li>Shuffle the deck.</li>
<li>Shows the deck.</li>
<li>Deal cards equally among four players.</li>
<li>Show the cards of each Player.</li>
</ul>
<hr>
<p>Please suggest some better ways of doing this program.</p>
<p>Also suggest new functions and modifications in this program.</p>
<hr>
<pre><code>package cardgame;
public class Card {
String suit;
String rank;
public Card(String cardSuit, String cardRank){
this.suit = cardSuit;
this.rank = cardRank;
}
}
</code></pre>
<hr>
<pre><code>package cardgame;
import java.util.*;
public class DeckOfCards {
final int size = 52;
Card[] deckOfCards = new Card[size];
public DeckOfCards(){
int count=0;
String[] suits = {"Diamonds","Clubs","Hearts","Spades"};
String[] ranks ={"King","Queen","Jack","Ten","Nine","Eight","Seven","Six","Five","Four","Three","Deuce","Ace",};
for (String s:suits){
for (String r:ranks){
Card card = new Card(s, r);
this.deckOfCards[count] = card;
count++;
}
}
}
public void ShuffleCards(){
Random rand = new Random();
int j;
for(int i=0; i<size; i++){
j = rand.nextInt(52);
Card temp = deckOfCards[i];
deckOfCards[i]=deckOfCards[j];
deckOfCards[j]= temp;
}
}
public void showCards(){
System.out.println("---------------------------------------------");
int count =0;
for (Card card : deckOfCards){
System.out.print(card.rank + " of " + card.suit + " ");
count++;
if(count%4==0)
System.out.println("");
}
System.out.println("---------------------------------------------");
}
public void dealCards(Players player1,Players player2,Players player3,Players player4){
int count = 0;
for (Card card : deckOfCards){
if (count>38){
player1.playCards[count%13] = card;
//System.out.println(player1.playCards[count/12].rank+" "+player1.playCards[count/12].suit);
}
else if (count>25){
player2.playCards[count%13] = card;
}
else if (count>12){
player3.playCards[count%13] = card;
}
else{
player4.playCards[count%13] = card;
}
count++;
}
}
}
</code></pre>
<hr>
<pre><code>package cardgame;
public class Players {
String name;
Card[] playCards = new Card[13];
public Players(String name){
this.name = name;
}
public void ShowPlayerCards(){
System.out.println("---------------------------------------------");
for (Card card : playCards){
if(card!=null)
System.out.println(card.rank + " of " + card.suit);
}
System.out.println("---------------------------------------------");
}
public String getName(){
return name;
}
}
</code></pre>
<hr>
<pre><code>package cardgame;
import java.util.*;
public class CardGame {
public static void main(String[] args) {
DeckOfCards deck = new DeckOfCards();
System.out.println("UnShuffeled Cards.");
deck.showCards();
deck.ShuffleCards();
System.out.println("Shuffeled Cards.");
deck.showCards();
Scanner input = new Scanner(System.in);
System.out.println("Player One...\nEnter Name:");
Players player1 = new Players(input.nextLine());
System.out.println("Player Two...\nEnter Name:");
Players player2 = new Players(input.nextLine());
System.out.println("Player Three...\nEnter Name:");
Players player3 = new Players(input.nextLine());
System.out.println("Player Four...\nEnter Name:");
Players player4 = new Players(input.nextLine());
deck.dealCards(player1, player2, player3, player4);
System.out.println("---------------------------------------------");
System.out.println(player1.getName());
player1.ShowPlayerCards();
System.out.println(player2.getName());
player2.ShowPlayerCards();
System.out.println(player3.getName());
player3.ShowPlayerCards();
System.out.println(player4.getName());
player4.ShowPlayerCards();
}
}
</code></pre>
| [] | [
{
"body": "<p>Ok... I am not sure how to show you all of the refactorings I did in a way that will make sense, so I'm just going to post the refactored classes and go from there. </p>\n\n<h2>Main:</h2>\n\n<pre><code>public static void main(String[] args) {\n\n Scanner input = new Scanner(System.in);\n Players[] players = new Players[4];\n Card[] deck = Dealer.getDeckOfCards();\n\n System.out.println(\"Un-shuffled Cards.\");\n Dealer.showCards(deck);\n Card[] shuffledCards = Dealer.shuffleCards(deck);\n System.out.println(\"Shuffled Cards.\");\n Dealer.showCards(shuffledCards);\n\n for(int i = 0; i < players.length; i++) {\n System.out.println(\"Enter Player Name: \");\n players[i] = new Players(input.nextLine());\n }\n\n Players[] playersWithCards = Dealer.dealCards(players, shuffledCards);\n\n System.out.println(\"---------------------------------------------\");\n\n for(Players player : playersWithCards) {\n System.out.println(player.getName());\n player.showPlayerCards();\n }\n\n}\n</code></pre>\n\n<h2>Players:</h2>\n\n<pre><code>class Players {\n\n private String name;\n private Card[] cards = new Card[13];\n\n Players(String name){\n this.name = name;\n }\n void showPlayerCards(){\n System.out.println(\"---------------------------------------------\");\n for (Card card : cards){\n //you had been checking here if this was null, but there was no need for that check\n System.out.printf(\"%s of %s\\n\", card.rank, card.suit);\n }\n System.out.println(\"---------------------------------------------\");\n }\n void receiveCard(Card card, int position){\n cards[position] = card;\n }\n String getName(){\n return name;\n }\n\n}\n</code></pre>\n\n<h2>Dealer (formerly DeckOfCards)</h2>\n\n<pre><code>class Dealer {\n private static final int SIZE = 52;\n private static Card[] deckOfCards = new Card[SIZE];\n\n static Card[] getDeckOfCards() {\n\n int count = 0;\n\n String[] suits = {\"Diamonds\", \"Clubs\", \"Hearts\", \"Spades\"};\n String[] ranks = {\"King\", \"Queen\", \"Jack\", \"Ten\", \"Nine\", \"Eight\", \"Seven\", \"Six\", \"Five\", \"Four\", \"Three\", \"Deuce\", \"Ace\"};\n\n for (String s : suits) {\n for (String r : ranks) {\n\n Card card = new Card(s, r);\n deckOfCards[count] = card;\n count++;\n }\n }\n\n return deckOfCards;\n\n }\n\n static Card[] shuffleCards(Card[] deckOfCards) {\n Random rand = new Random();\n int j;\n for (int i = 0; i < SIZE; i++) {\n j = rand.nextInt(SIZE);\n Card temp = deckOfCards[i];\n deckOfCards[i] = deckOfCards[j];\n deckOfCards[j] = temp;\n }\n return deckOfCards;\n }\n\n static void showCards(Card[] deckOfCards) {\n System.out.println(\"---------------------------------------------\");\n int count = 0;\n for (Card card : deckOfCards) {\n System.out.printf(\"%s of %s\\t\", card.rank, card.suit); //use print f with \\t (tab character)\n count++;\n if (count % 4 == 0)\n System.out.println();\n }\n System.out.println(\"---------------------------------------------\");\n }\n\n static Players[] dealCards(Players[] players, Card[] deck) {\n int numOfCardsPerPlayer = deck.length / players.length;\n for (int i = 0; i < deck.length; i++) {\n int positionInHand = i % numOfCardsPerPlayer;\n players[i % players.length].receiveCard(deck[i], positionInHand);\n }\n\n return players;\n }\n}\n</code></pre>\n\n<h2>and Card:</h2>\n\n<pre><code>class Card {\n String suit;\n String rank;\n\n Card(String cardSuit, String cardRank){\n this.suit = cardSuit;\n this.rank = cardRank;\n }\n}\n</code></pre>\n\n<ol>\n<li><p>The first thing I did after refactoring your <code>Main</code> to use loops whenever possible was to ensure that you weren't unnecessarily making code <code>public</code>. All of your <code>classes</code> are in the same <code>package</code>, so you can make them <code>package-private</code> by removing the <code>public</code> modifiers. This is just generally considered good practice so that when you start working on projects with many classes, (some of which may have the same name) you are limiting conflicts.</p></li>\n<li><p>Probably the single biggest difference between your code and the way I refactored it was that I changed <code>DeckOfCards</code> to a <code>Dealer</code>, and made it static. In programming, an abstraction of a <code>DeckOfCards</code> is really just an <em>array</em> of cards, like <code>Card[] deck = Dealer.getDeckOfCards();</code>. It seemed to me that most of the tasks you were calling from <code>DeckOfCards</code> were really the job of a <code>Dealer</code>, so I changed the code to reflect that, passing in the values created in the driver class as the program progresses. (For example in the line <code>Card[] shuffledCards = Dealer.shuffleCards(deck);</code>) If you look at this class, you'll see that all of its methods are static, which is really just a preference thing. If you wanted to make a constructor like <code>Dealer dealer = new Dealer();</code> for a dealer and view it more as an entity than a doer, you could. </p></li>\n</ol>\n\n<p>I'm sure I probably missed some stuff so if you have any questions let me know. All in all I think you did a really good job for a new developer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T23:45:11.920",
"Id": "403009",
"Score": "0",
"body": "It was really helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T23:48:03.183",
"Id": "403010",
"Score": "0",
"body": "I want dealCards method to deal one card to player#1 and second to player#2 at one time and so on, so that each of the four player have 13 cards with them. what shoud i do? the current method gives 13 cards to player1 and other 13 to next and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T04:00:27.350",
"Id": "403055",
"Score": "1",
"body": "@KhAhmed I updated that method in my answer so it works that way. If you're up for another challenge, you might try refactoring this so you could have a dynamic number of players. Would force you to look at some parts of it a different way."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T22:06:06.777",
"Id": "208651",
"ParentId": "208644",
"Score": "6"
}
},
{
"body": "<p>I have the following suggestions:</p>\n\n<ol>\n<li>Make Suit and Rank enums since they are fixed and are not going to be altered.</li>\n<li>It is usually a good practice to make all instance variables private and have getter and setter methods to access them.</li>\n<li>Make size final static since it is a constant value and is not going to be changed.</li>\n</ol>\n\n<p>Here's the complete code:</p>\n\n<h3>Suit enum</h3>\n\n<pre><code>package cardGame;\n\nenum Suit {\n DIAMONDS,\n CLUBS,\n SPADES,\n HEARTS;\n}\n</code></pre>\n\n<h3>Rank enum</h3>\n\n<pre><code>package cardGame;\n\nenum Rank {\n ACE,\n DEUCE,\n THREE,\n FOUR,\n FIVE,\n SIX,\n SEVEN,\n EIGHT,\n NINE,\n TEN,\n JACK,\n QUEEN,\n KING;\n}\n</code></pre>\n\n<h3>Card class</h3>\n\n<pre><code>package cardGame;\n\nclass Card {\n private final Suit suit;\n private final Rank rank;\n\n Card(Suit suit, Rank rank) {\n this.suit = suit;\n this.rank = rank;\n }\n\n Rank getRank() {\n return rank;\n }\n\n Suit getSuit() {\n return suit;\n }\n\n @Override\n public String toString() {\n return rank + \" of \" + suit;\n }\n}\n</code></pre>\n\n<h3>DeckOfCards class</h3>\n\n<pre><code>package cardGame;\n\nimport java.util.Random;\n\nclass DeckOfCards {\n public static final int SIZE = 52;\n private final Card[] cards = new Card[SIZE];\n\n DeckOfCards() {\n int currentCardIndex = 0;\n\n for (Suit suit : Suit.values()) {\n for (Rank rank : Rank.values()) {\n cards[currentCardIndex++] = new Card(suit, rank);\n }\n }\n }\n\n Card[] getCards() {\n return cards;\n }\n\n Card getCard(int index) {\n return cards[index];\n }\n\n void shuffleDeck() {\n Random rand = new Random();\n\n for (int i = 0; i < SIZE; i++) {\n int j = rand.nextInt(SIZE);\n swapCards(i, j);\n }\n }\n\n void swapCards(int i, int j) {\n Card temp = cards[i];\n cards[i] = cards[j];\n cards[j] = temp;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n stringBuilder.append(\"Current Deck:\\n\");\n\n for (int i = 0; i < DeckOfCards.SIZE; i++) {\n stringBuilder.append(\"Card #\" + (i + 1) + \": \" + getCard(i) + \"\\n\");\n }\n\n return stringBuilder.toString();\n }\n}\n</code></pre>\n\n<h3>Player class</h3>\n\n<pre><code>package cardGame;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Player {\n private String name;\n private List<Card> cards = new ArrayList<>();\n\n Player(String name) {\n this.name = name;\n }\n\n void giveCard(Card card) {\n cards.add(card);\n }\n\n List<Card> getCards() {\n return cards;\n }\n\n String printPlayerCards() {\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(name + \" has the following cards:\\n\");\n\n for (Card card : cards) {\n stringBuilder.append(card + \"\\n\");\n }\n\n return stringBuilder.toString();\n }\n\n @Override\n public String toString() {\n return name;\n }\n}\n</code></pre>\n\n<h3>CardGame class</h3>\n\n<pre><code>package cardGame;\n\nimport java.util.Scanner;\n\npublic class CardGame {\n private static final int NO_OF_PLAYERS = 4;\n private final Player[] players = new Player[NO_OF_PLAYERS];\n private final DeckOfCards deckOfCards = new DeckOfCards();\n\n public static void main(String[] args) {\n CardGame cardGame = new CardGame();\n\n System.out.println(\"WELCOME TO THE CARD GAME\\n\");\n System.out.println(\"Enter the four players' name below\");\n\n Scanner scan = new Scanner(System.in);\n for (int i = 0; i < NO_OF_PLAYERS; i++) {\n cardGame.players[i] = new Player(scan.next());\n }\n\n cardGame.deckOfCards.shuffleDeck();\n\n System.out.println(cardGame.deckOfCards);\n\n cardGame.dealCards();\n\n cardGame.displayCardsForAllPlayers();\n }\n\n\n private void dealCards() {\n for (int i = 0; i < DeckOfCards.SIZE; i++) {\n players[i % NO_OF_PLAYERS].giveCard(deckOfCards.getCard(i));\n }\n }\n\n private void displayCardsForAllPlayers() {\n for (int i = 0; i < NO_OF_PLAYERS; i++) {\n System.out.println(players[i].printPlayerCards());\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T02:24:11.630",
"Id": "208664",
"ParentId": "208644",
"Score": "6"
}
},
{
"body": "<p>Welcome on Code Review!</p>\n<p>Addendum to what others say:</p>\n<h2>Naming</h2>\n<hr />\n<h3>Singular & plural nouns</h3>\n<p>A player is a <code>Player</code> not a <code>Players</code>, you should use singular names when you talk about <strong>one</strong> thing, and plural when you talk about many. ie:</p>\n<pre><code>Player[] players = new Player[4];\n</code></pre>\n<hr />\n<h3>Avoid redundancy</h3>\n<p>Try to avoid redundancy in naming, so instead of having:</p>\n<pre><code>DeckOfCards.shuffleDeck()\n</code></pre>\n<p>you can write:</p>\n<pre><code>DeckOfCards.shuffle()\n</code></pre>\n<hr />\n<h3>Keep them simple</h3>\n<p>There's not much chance here that reader think about a loading deck if you simply named your class <code>Deck</code>. In this context, it's pretty obvious that's a cards' deck.</p>\n<hr />\n<h2>MISC</h2>\n<h3>Be generic when possible</h3>\n<p>Try to be as generic as possible, avoid magic values. The size of your deck if the sum of all possible combinations, so for example, taking again the use of enums advised in one of the other answer:</p>\n<pre><code>private static final int SIZE = Suit.values().length * Rank.values().length;\n</code></pre>\n<p>Like that, if later you decide to change the type of deck, eg removing aces or figures, the change will be reflected automatically in the rest of your code. And you know... «Less code to refactor make developers happier».</p>\n<h3>Think about underlying types</h3>\n<p>You can maybe store just the index of the card, with a simple <code>int</code>. A card can be represented by an index relative to its place in a new deck. [range 0-51].</p>\n<p>To retrieve suits and ranks from indexes, depending on how cards are ordered in the deck.</p>\n<p>If ordered by rank (A♡, A♢, A♠, A♣, 2♡, 2♢, ..., K♡, K♢, K♠, K♣) :</p>\n<pre><code>Rank r = Rank.values()[i / 4];\nSuit s = Suit.values()[i % 4];\n</code></pre>\n<p>If ordered by suit (A♡, 2♡, 3♡, ..., J♣, Q♣, K♣) :</p>\n<pre><code>Rank r = Rank.values()[i % 13];\nSuit s = Suit.values()[i / 13];\n</code></pre>\n<p>(and for faster/better way to cast int to enum, check <a href=\"https://stackoverflow.com/questions/5878952/cast-int-to-enum-in-java\">this SO post</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T13:24:48.507",
"Id": "208688",
"ParentId": "208644",
"Score": "3"
}
},
{
"body": "<p>In addition to the other answers:</p>\n\n<p>Your shuffle algorithm is unfair. It will not produce all card distributions with the same probability. Luckily someone thought about this problem before and wrote the generic solution. You just need to use it:</p>\n\n<pre><code>Collections.shuffle(Arrays.asList(cards), rand);\n</code></pre>\n\n<p>See <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Wikipedia</a> for more details.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:12:22.470",
"Id": "208733",
"ParentId": "208644",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208651",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T19:47:53.873",
"Id": "208644",
"Score": "5",
"Tags": [
"java",
"beginner",
"playing-cards",
"shuffle"
],
"Title": "Cards shuffling and dealing program"
} | 208644 |
<h1>Problem</h1>
<p>Dupe detection for a vector of ints. I simply want a count of the unique input characters that occurred at least twice. The goal is to count a dupe only once and ignore that input character if another dupe of it is seen in the future. A test input could look something like this <code>vector<int> test = { 4,5,9,6,9,9,6,3,4 };</code></p>
<h1>Looking for Feedback on</h1>
<p>Looking for basic feedback on the data structures I'm using and the possibility of using the vector erase method to iterate and take advantage of the space allocated to my numbers vector instead of using a map to not count dups more than once. Any C++ 11 or 17 features I can take advantage of here too?</p>
<pre><code>int countDuplicates(vector<int> numbers) {
int dups = 0;
set<int> s;
map<int, int> m;
for (int n : numbers) {
if (s.insert(n).second == false && m.find(n) == m.end()) {
dups++;
m.insert(pair<int, int>(n,0));
// better to remove from vector than increase space with the map?
// numbers.erase(remove(numbers.begin(), numbers.end(), n), numbers.end());
} else {
s.insert(n);
}
}
return dups;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T08:04:39.640",
"Id": "403067",
"Score": "0",
"body": "Not really enough for a full answer, but `m.insert(pair<int, int>(n, 0))` can be replaced with simply `m.emplace(n, 0)` saving you from writing out the pair constructor."
}
] | [
{
"body": "<h1>Basic Algorithm</h1>\n<p>At least if I understand the intent correctly, you simply want a count of the unique input characters that occurred at least twice.</p>\n<p>In that case, I think I'd do something like this:</p>\n<pre><code>int count_dupes(std::vector<int> const &inputs) { \n std::map<int, int> counts;\n\n for (auto i : inputs)\n ++counts[i];\n\n return std::count_if(counts.begin(), counts.end(),\n [](auto const &p) { return p.second >= 2; });\n}\n</code></pre>\n<p>I'd also consider using an array instead of a map, as outlined in an answer to an earlier question: <a href=\"https://codereview.stackexchange.com/a/208502/489\">https://codereview.stackexchange.com/a/208502/489</a> --but this can depend on the range of values you're dealing with. With a 16-bit int, it's no problem at all on most machines. With a 32-bit <code>int</code> (and no other constraints on values) it's still possible on many machines, but probably impractical. For arbitrary 64-bit int, an array won't be practical.</p>\n<h1>Parameter Passing</h1>\n<p>Right now, you're passing the input by value. This means when you call the function with some vector, a copy of the original vector will normally be made and passed to the function. As a general rule, something like a vector that's potentially large and slow to copy should be passed by reference to const, as shown in the code above.</p>\n<h1>Logical Comparisons</h1>\n<p>Comparing a Boolean value to <code>true</code> or <code>false</code> is generally a poor idea. <code>if (x==true)</code> is equivalent to <code>if (x)</code> and <code>if (x == false)</code> is equivalent to <code>if (!x)</code>. Normally, if it's Boolean in nature, a variable should be given a name that reflects that nature, and should be used directly rather than being compared to <code>true</code> or <code>false</code>. For example, <code>s.insert(n).second == false</code> wold be better written as: <code>if (!s.insert(n).second)</code>.</p>\n<p>Some people (understandably, I guess) prefer to use the written form: if <code>if (not s.insert(n).second)</code>. I've written C and C++ long enough that I have no difficulty with reading <code>!</code> as meaning "not", but especially if it may be read by people less accustomed to programming, it may make more sense to use the words instead of symbols.</p>\n<h1>Formatting/Indentation</h1>\n<p>At least to me, this indentation looks a bit odd:</p>\n<pre><code> if (s.insert(n).second == false && m.find(n) == m.end()) {\n dups++;\n m.insert(pair<int, int>(n,0));\n // better to remove from vector than increase space with the map?\n // numbers.erase(remove(numbers.begin(), numbers.end(), n), numbers.end()); \n } else {\n s.insert(n);\n }\n</code></pre>\n<p>If you use indentation like that consistently, I guess it's not necessarily terrible, but I think more people are accustomed to something more like this:</p>\n<pre><code> if (s.insert(n).second == false && m.find(n) == m.end()) {\n dups++;\n m.insert(pair<int, int>(n,0));\n // better to remove from vector than increase space with the map?\n // numbers.erase(remove(numbers.begin(), numbers.end(), n), numbers.end()); \n } else {\n s.insert(n);\n }\n</code></pre>\n<p>...where each closing brace is vertically aligned with the beginning of the block it closes. As a side-note, there are almost endless debates about the efficacy of various bracing styles. I'm not going to advocate for or against any of the well known styles, but I think there's a fair amount to be gained from using a style that's well known, and then using it consistently. I don't see much to gain from style that's different from what almost anybody else uses.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T00:04:28.713",
"Id": "403011",
"Score": "0",
"body": "If my understanding is correct, `count_if` iterates over counts and increments `p` when it finds a unique input that occurred at least twice. `++counts[i]` is a very clean map update, I've not seen this before and took me a moment to understand, but both the key and value are updated. Agree on logical comparison feedback. I've gone back and fort with `false` and `!`, I've used `false` more often for readability, but I'm at the point in my life we're brevity and speed are becoming more important. Brace indent was a paste error, but good catch and raised my awareness of this detail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:39:43.933",
"Id": "403036",
"Score": "1",
"body": "Yes, `++counts[i]` will insert a new record for `i` if it hasn't been inserted yet. That newly inserted record will have its count at 0. The `++` will then increment the current count. `count_if` just counts the number of elements in a collection that meet the specified criteria, so it basically just counts and returns the number of items for which your predicate returned `true`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T11:37:42.097",
"Id": "403088",
"Score": "2",
"body": "It would also be quite easy to do with the original version, as it makes a copy. One could then sort copied vector, apply `std::unique` and get `std::distance` between begin and returned iterator. It is not really certain which version is better though. I've written this comment with relation to the one above, but it seems to be deleted now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T11:49:20.120",
"Id": "403091",
"Score": "0",
"body": "You might want to attach a caveat to the suggestion to use an array, since `int` has a much wider range of values than `char` (so we're not in quite the same context as that other question)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T11:57:15.180",
"Id": "403094",
"Score": "1",
"body": "@Incomputable: yes, it was my comment, I had some doubts about its validity after reading the original question again. It might have been justified. / sadly `std::unique` doesn't do the job if what we need to count is the number of elements appearing at least twice"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T23:24:27.270",
"Id": "208656",
"ParentId": "208648",
"Score": "7"
}
},
{
"body": "<p>I don't agree with @JerryCoffin on two accounts: algorithm and paramater passing, the latter being a consequence of the former. That's why I submit this extra review, even if @JerryCoffin's has already been accepted, and even if I agree with the other points he made.</p>\n\n<p>When you design an algorithm, especially in C++, you want it to be as efficient as possible, in as many situations as possible. It's a good idea to take a look at existing algorithms in the standard library to see how it can be achieved, all the more when there is an algorithm there that is closely related to the one you're designing: <a href=\"https://en.cppreference.com/w/cpp/algorithm/unique\" rel=\"nofollow noreferrer\"><code>std::unique</code></a>, that removes all but the first of consecutive equivalent elements. What's interesting is 1) that it operates on a sorted range and 2) that it modifies the input sequence: thus it makes it optimal when the input sequence is already sorted, and also when it's disposable. Can we benefit from <code>std::unique</code>s interface in our largely similar problem? I would say so:</p>\n\n<pre><code>#include <algorithm>\n\ntemplate <typename Iterator>\nint count_duplicates(Iterator first, Iterator last) {\n // requires a sorted range\n int count = 0;\n while (true) {\n first = std::adjacent_find(first, last);\n if (first == last) return count;\n first = std::adjacent_find(++first, last, std::not_equal_to<>());\n ++count;\n }\n}\n</code></pre>\n\n<p>Let's now compare with @JerryCoffin's proposed solution, which allocates memory for a <code>std::map</code> and then has in all cases a complexity of <code>O(n*log(n))</code> for populating it + <code>O(n)</code> for counting elements with a frequency higher than 1:</p>\n\n<ul>\n<li><p>if the input range is already sorted, this algorithm has <code>O(n)</code> complexity, which is better</p></li>\n<li><p>if the input range is disposable but not sorted, this algorithm has the same complexity (<code>O(n*log(n))</code> for prior sorting and <code>O(n)</code> for counting), but doesn't allocate memory and has better cache locality</p></li>\n<li><p>if the input is neither sorted nor disposable, we have the same complexity and memory requirements (we need to copy the input range) but we keep the better cache locality</p></li>\n</ul>\n\n<p>On the other hand it lacks the possibility of relying on a more efficient structure to count the occurrences of each element, such as an array or a hash table. We could then theoretically go from <code>O(n*log(n))</code> to <code>O(n)</code> when looking for duplicates. But I'm still unconvinced because those data structures would be oversized if the input range has a small alphabet.</p>\n\n<p>EDIT: I think I've read the submitted code and the question a bit too fast. If what we need is not only to count elements appearing at least twice, but erasing other elements of the vector, then the solution is different, even if most building blocks remain:</p>\n\n<pre><code>#include <vector>\n#include <algorithm>\n#include <iostream>\n\ntemplate <typename Iterator>\nIterator one_of_duplicates(Iterator first, Iterator last) {\n // requires a sorted input\n auto current = first;\n while (true) {\n // find a duplicated element, move it behind 'first' \n // and find the next different element\n current = std::adjacent_find(current, last);\n if (current == last) return first;\n *first++ = std::move(*current);\n std::cerr << *current << std::endl;\n current = std::adjacent_find(current, last, std::not_equal_to<>());\n }\n}\n\n\nint main() {\n\n std::vector<int> data = { 0, 1, 2, 3, 4, 5, 1, 2, 2, 3, 5, 5, 5 };\n std::sort(data.begin(), data.end());\n data.erase(one_of_duplicates(data.begin(), data.end()), data.end());\n for (auto i : data) std::cout << i << ',';\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T11:26:33.223",
"Id": "208682",
"ParentId": "208648",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "208656",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T21:05:52.137",
"Id": "208648",
"Score": "4",
"Tags": [
"c++",
"vectors",
"hash-map",
"set"
],
"Title": "Data Structures for Counting Duplicates and using std::vector::erase"
} | 208648 |
<p>I've been working on a note tool for my company to help streamline verifying and noting accounts. I've added in extra features that help with different aspects of the job as well.</p>
<p>I'm wondering if there is anything I can do to streamline some of the functions I've created. </p>
<p>Such as the "Prefill options". They take the contents of hidden divs and append to the note text boxes. I'm sure there is a better way of doing this but I've been looking at it for too long now I think.</p>
<p>Any feedback is welcome!</p>
<p>I've stripped out any references to the company to avoid any issues of posting that information.</p>
<p>Full source too large to paste here:
<a href="https://pastebin.com/pdYH2DMq" rel="nofollow noreferrer">https://pastebin.com/pdYH2DMq</a></p>
<p>Below is how I'm currently filling in boxes with pre-made templates.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* Fill issue and resolution boxes with templates */
$(document).ready(function() {
$('.prefill').on("click", function(e) {
var id = $(this).attr('id');
id1 = id + "1";
id2 = id + "2";
id3 = id + "3";
if (document.getElementById("issue").value != '') {
document.getElementById("issue").value += '\n'
}
if (document.getElementById("reso").value != '') {
document.getElementById("reso").value += '\n'
}
if (document.getElementById("scratch").value != '') {
document.getElementById("scratch").value += '\n'
}
document.getElementById("issue").value += document.getElementById(id1).innerHTML;
document.getElementById("reso").value += document.getElementById(id2).innerHTML;
if (document.getElementById(id3).innerHTML != '') {
document.getElementById("scratch").value += document.getElementById(id3).innerHTML;
}
$('textarea').autoHeight();
});
});
/* Add End Result buttons */
$(document).ready(function() {
$('.ending').on("click", function(e) {
endid = $(this).attr('id');
endid1 = endid + "1";
if (document.getElementById("reso").value != '') {
document.getElementById("reso").value += '\n'
}
document.getElementById("reso").value += document.getElementById(endid1).innerHTML;
$('textarea').autoHeight();
})
})
/* //Add End Result */</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- css and js files -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" integrity="sha384-kW+oWsYx3YpxvjtZjFXqazFpA7UP/MbiY4jvs+RWZo2+N94PFZ36T6TFkc9O3qoB" crossorigin="anonymous"></script>
<!-- Prefill dropdowns -->
<div class="row" id="prefillrow">
<div class="col-lg-12">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-dollar-sign fa-fw"></i>
</button>
<div class="dropdown-menu">
<h6 class="dropdown-header">Billing Issues</h6>
<a class="dropdown-item prefill" href="#" id="paybill">Pay Bill</a>
<a class="dropdown-item prefill" href="#" id="aru">ARU Issue</a>
<a class="dropdown-item prefill" href="#" id="sd">Restore Soft Disconnect</a>
<a class="dropdown-item prefill" href="#" id="npd">Non-Pay Disconnect</a>
<a class="dropdown-item prefill" href="#" id="reload">Reload Prepaid Internet</a>
<a class="dropdown-item prefill" href="#" id="myvyve">MyVyve Setup/Issue</a>
<a class="dropdown-item prefill" href="#" id="increase">Unexpected Bill Increase</a>
<a class="dropdown-item prefill" href="#" id="upgrade">Upgrade Options</a>
<a class="dropdown-item prefill" href="#" id="raf">Refer A Friend</a>
</div>
</div>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-globe-americas fa-fw"></i>
</button>
<div class="dropdown-menu">
<h6 class="dropdown-header">Internet Issues</h6>
<a class="dropdown-item prefill" href="#" id="internetout">Internet Out</a>
<a class="dropdown-item prefill" href="#" id="custmodem">Add Customer Owned Modem</a>
<a class="dropdown-item prefill" href="#" id="wifi">Can't Connect to WiFi</a>
<a class="dropdown-item prefill" href="#" id="custrouter">Customer Owned Router Issue</a>
</div>
</div>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-warning dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-tv fa-fw"></i>
</button>
<div class="dropdown-menu">
<h6 class="dropdown-header">Video Issues</h6>
<a class="dropdown-item prefill" href="#" id="videoout">No Video</a>
<a class="dropdown-item prefill" href="#" id="tvpair">Pair TV</a>
<a class="dropdown-item prefill" href="#" id="dtapair">Pair DTA</a>
<a class="dropdown-item prefill" href="#" id="audio">No Audio/Wrong Language</a>
<a class="dropdown-item prefill" href="#" id="noequip">No Equip Issue</a>
<a class="dropdown-item prefill" href="#" id="activate">"Activate Service"</a>
<a class="dropdown-item prefill" href="#" id="notinsub">"Not In Subscription"</a>
<a class="dropdown-item prefill" href="#" id="dvr">"DVR Service Unavailable"</a>
<a class="dropdown-item prefill" href="#" id="glitch">Video Glitching</a>
<a class="dropdown-item prefill" href="#" id="tivonet">Xstream Network Issue</a>
</div>
</div>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-light dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-phone fa-fw"></i>
</button>
<div class="dropdown-menu">
<h6 class="dropdown-header">Phone Issues</h6>
<a class="dropdown-item prefill" href="#" id="phoneout">Phone Out</a>
<a class="dropdown-item prefill" href="#" id="phnport">Port Phone Number</a>
<a class="dropdown-item prefill" href="#" id="phnchange">Request Phone Number Change</a>
</div>
</div>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Other
</button>
<div class="dropdown-menu">
<a class="dropdown-item prefill" href="#" id="outage">Outage</a>
<a class="dropdown-item prefill" href="#" id="wheretech">Where's The Tech?</a>
</div>
</div>
</div>
</div>
<!-- //Prefill dropdowns -->
<br>
<!-- Issue Box -->
<div class="row">
<div class="col-lg-12">
<div class="input-group">
<textarea type="textarea" placeholder="REASON FOR CALL" class="form-control form-control-sm" rows="3" name="issue" id="issue" title="REASON FOR CALL" tabindex="11" required></textarea>
<div class="input-group-append">
<button type="button" class="btn btn-info btn-osx btn-sm" name="hipchat" style="info" id="hipchat" onclick="return genHipChatNote()">Ask<br> <i class="far fa-comment"></i>HipChat<br> Note <i class="far fa-copy"></i></button>
</div>
</div>
</div>
</div>
<!-- Issue Box -->
<br>
<!-- Resolution Box -->
<div class="row">
<div class="col-lg-12">
<textarea type="textarea" placeholder="STEPS TAKEN AND OUTCOME OF CALL" class="form-control form-control-sm" rows="3" name="reso" id="reso" title="STEPS TAKEN AND OUTCOME OF CALL" style="width: 100%;" tabindex="12" required></textarea>
</div>
</div>
<!-- Resolution Box -->
<br>
<!-- End Results Hidden Container -->
<div class="row" id="endbuttonsrow">
<div class="col-lg-12">
<button type="button" id="fixed" class="btn btn-success btn-sm ending"><i class="far fa-thumbs-up"></i> Fixed</button>
<button type="button" id="notfixed" class="btn btn-danger btn-sm ending"><i class="far fa-thumbs-down"></i> Not Fixed</button>
<button type="button" id="wo" class="btn btn-info btn-sm ending"><i class="fas fa-truck"></i> WO
</button>
<button type="button" id="coswo" class="btn btn-info btn-sm ending"><i class="fas fa-truck"></i> COS WO
</button>
<div class="d-none">
<!-- Resolution addons- Not displayed - these are the details that get added to the Resolution Text box -->
<div id="fixed1">RESOLVED</div>
<div id="notfixed1">NOT RESOLVED</div>
<div id="wo1">CREATED WORK ORDER TO FURTHER TROUBLESHOOT THE ISSUE</div>
<div id="coswo1">CREATED WORK ORDER FOR TECH TO FINISH UPGRADE</div>
</div>
</div>
</div>
<!-- End Results Hidden Container -->
<!-- Scratch Pad Box -->
<div class="row">
<div class="col-lg-12">
<textarea type="textarea" placeholder="SCRATCH PAD NOTES. NOT PART OF CUST NOTES" class="form-control form-control-sm" name="scratch" rows="3" id="scratch" title="SCRATCH PAD NOTES. NOT PART OF CUST NOTES" tabindex="13"></textarea>
</div>
</div>
<!-- Scratch Pad Box -->
<!-- Prefill Content Hidden DO NO INDENT! Indents appear in prefill contents -->
<div class="d-none">
<!-- Other Issues Templates -->
<div id="outage1">Service Out</div>
<div id="outage2">Informed CST of current outage in the area</div>
<div id="outage3">Suggested steps
step1
step2</div>
<div id="wheretech1">Where's the tech</div>
<div id="wheretech2"></div>
<div id="wheretech3">Suggested steps
step1
step2</div>
<!-- Billing Templates -->
<div id="paybill1">Billing - CST Calling to pay bill</div>
<div id="paybill2"></div>
<dir id="paybill3">Suggested steps
step1
step2</dir>
<div id="sd1">Billing - Account in Soft Disconnect</div>
<div id="sd2"></div>
<div id="sd3">Suggested steps
step1
step2</div>
<div id="reload1">Billing - Need to reload prepaid internet</div>
<div id="reload2"></div>
<div id="reload3">Suggested steps
step1
step2</div>
<div id="npd1">Billing - Non Pay Disconnect</div>
<div id="npd2"></div>
<div id="npd3">Suggested steps
step1
step2</div>
<div id="aru1">Billing - ARU not working</div>
<div id="aru2"></div>
<div id="aru3">Suggested steps
step1
step2</div>
<div id="myacct2"></div>
<div id="myacct3">Suggested steps
step1
step2</div>
<div id="increase1">Billing - Unexpected Bill Increase</div>
<div id="increase2"></div>
<div id="increase3">Suggested steps
step1
step2</div>
<div id="upgrade1">Billing - Customer would like to discus upgrade options</div>
<div id="upgrade2"></div>
<div id="upgrade3">Suggested steps
step1
step2</div>
<div id="raf1">Billing - Refer a Friend</div>
<div id="raf2"></div>
<div id="raf3">Suggested steps
step1
step2</div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<!-- Internet Templates -->
<div id="internetout1">Internet - Out</div>
<div id="internetout2"></div>
<div id="internetout3">Suggested steps
step1
step2</div>
<div id="custmodem1">Internet - CST wants to add customer owned modem
MAC address of new modem: ##########</div>
<div id="custmodem2"></div>
<div id="custmodem3">Suggested steps
step1
step2</div>
<div id="wifi1">Internet - Cant connect to WiFi</div>
<div id="wifi2"></div>
<div id="wifi3">Suggested steps
step1
step2</div>
<div id="custrouter1">Internet - Customer owned router issue</div>
<div id="custrouter2"></div>
<div id="custrouter3">Suggested steps
step1
step2</div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<!-- Video Templates -->
<div id="videoout1">Video - Out</div>
<div id="videoout2"></div>
<div id="videoout3">Suggested steps
step1
step2</div>
<div id="glitch1">Video - Glitching</div>
<div id="glitch2"></div>
<div id="glitch3">Suggested steps
step1
step2</div>
<div id="tvpair1">Video - Cant change volume or turn TV power on/off
TV Brand: </div>
<div id="tvpair2"></div>
<div id="tvpair3">Suggested steps
step1
step2</div>
<div id="audio1">Video - Audio/Language Issue</div>
<div id="audio2"></div>
<div id="audio3">Suggested steps
step1
step2</div>
<div id="dtapair1">Video - Cant change channels/open guide/menus</div>
<div id="dtapair2"></div>
<div id="dtapair3">Suggested steps
step1
step2</div>
<div id="noequip1">Video - No equipment to troubleshoot</div>
<div id="noequip2"></div>
<div id="noequip3">Suggested steps
step1
step2</div>
<div id="activate1">Video - "Your service needs to be activated before continuing" message on screen</div>
<div id="activate2"></div>
<div id="activate3">Suggested steps
step1
step2</div>
<div id="notinsub1">Video - "Not included in your current subscription" message on screen</div>
<div id="notinsub2"></div>
<div id="notinsub3">Suggested steps
step1
step2</div>
<div id="dvr1">Video - "DVR service unavailable" Message on screen</div>
<div id="dvr2"></div>
<div id="dvr3">Suggested steps
step1
step2</div>
<div id="tivonet1">VIDEO - XSTREAM BOX NOT CONNECTING TO INTERNET</div>
<div id="tivonet2"></div>
<div id="tivonet3">Suggested steps
step1
step2</div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<!-- Phone Templates -->
<div id="phoneout1">Phone Out</div>
<div id="phoneout2"></div>
<div id="phoneout3">Suggested steps
step1
step2</div>
<div id="phnport1">Phone - Port Number from previous carrier</div>
<div id="phnport2"></div>
<div id="phnport3">Suggested steps
step1
step2
</div>
<div id="phnchange1">Phone - CST requesting to change phone number</div>
<div id="phnchange2"></div>
<div id="phnchange3">Suggested steps
step1
step2
</div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
</div>
<!-- Prefill Content Hidden DO NO INDENT! Indents appear in prefill contents --></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>This code has <strong>a lot</strong> of DOM Lookups. Those are expensive so it is wise to store those in a variable and utilize the variable instead of repeatedly querying the DOM each time. It also mixes jQuery selectors with vanilla JS DOM methods like <code>document.getElementById()</code>. If you are going to use jQuery for somethings, why not be consistent and use it for all DOM lookups? For example, the <a href=\"https://api.jquery.com/val\" rel=\"nofollow noreferrer\"><code>.val()</code></a> method can be used to get or set the value of the first element in a jQuery collection.</p>\n\n<pre><code>$(function() { //newer format for $(document).ready()\n var prefillEls = $('.prefill');\n var endingEls = $('.ending');\n var issueEl = $('#issue');\n var resoEl = $('#reso');\n var scratchEl = $('#scratch');\n\n prefillEls.on(\"click\", function(e) {\n //...\n if (issueEl.val() != '') {\n issueEl.val(issueEl.val() + '\\n');\n }\n if (resoEl.val() != '') {\n resoEl.val(resoEl.val() + '\\n');\n }\n if (scratchEl.val() != '') {\n scratchEl.val(scratchEl.val() + '\\n');\n }\n</code></pre>\n\n<p>Additionally, the code can lookup associated values for Issue, resolution and scratch in JS memory instead of repeatedly querying the DOM. One could create mappings for those associations:</p>\n\n<pre><code>var issues = {\n \"outage\": \"Service Out\",\n \"wheretech\": \"Where's the tech\",\n \"paybill\": \"Billing - CST Calling to pay bill\",\n /* ... more ... */\n};\nvar resolutions = {\n \"outage\": \"Informed CST of current outage in the area\",\n /* ... more ... */\n};\n</code></pre>\n\n<p>Then use those mapping to determine if a value should be used:</p>\n\n<pre><code>var id = $(this).attr('id');\nif (id in issues) {\n issueEl.val(issueEl.val() + issues[id]);\n}\nif (id in resolutions) {\n resoEl.val(resoEl.val() + '\\n');\n}\n</code></pre>\n\n<p>One could also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> object could also be used instead of plain objects. Removing the values from the HTML will greatly simplify the markup and reduce DOM queries.</p>\n\n<p>Similarly, those three repeated checks to see if a textarea has a value and append a new line character, followed by the new text to insert could be abstracted into a function.</p>\n\n<hr>\n\n<p>There are two DOM ready callback blocks (i.e. <code>$(document).ready(function() {</code>). While it isn't wrong to have two, the code can be combined into one callback. If you wanted to keep them separate, you could abstract them into two separate functions and have them called from a single callback function.</p>\n\n<hr>\n\n<p>The line endings are inconsistent- some lines have semi-colons and some don't. While <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic Semicolon Insertion</a> will typically handle such inconsistencies, it is advisable not to depend on it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:41:38.260",
"Id": "208780",
"ParentId": "208649",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T21:12:27.860",
"Id": "208649",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"form",
"twitter-bootstrap"
],
"Title": "Note Tool - Fill text box with template"
} | 208649 |
<p>I tried writing my very first template engine today. I designed it to just replace variables in templates, and keep it basic for now. Can anyone give me some constructive criticism? </p>
<p>I'm getting ready to write my own mini framework, and want to improve as much as I can. I just need to know if this is the default way (logic) to write one, or is there a better way?</p>
<pre><code><?php
class Template {
public $variables = [];
public function assign($key, $value) {
$this->variables[$key] = $value;
}
public function render($template, $variables = []) {
if (empty($variables)) {
$variables = $this->variables;
}
$code = file_get_contents($template);
foreach ($this->variables as $key => $variable) {
$code = str_replace('%' . $key . '%', $this->variables[$key], $code);
}
return $code;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:04:58.457",
"Id": "403019",
"Score": "0",
"body": "I'm not sure you're handing the variables in a clever way. What if you want to use the `assign()` method, but supply some more variable to `render()` at the same time? Why not merge the two arrays so you can use both?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T02:21:32.760",
"Id": "403051",
"Score": "0",
"body": "Id put this down to design preference, personal preference that is but its an interesting point which I share with you. I'm looking to make the code better, not different. But I do agree that this would probably be a better design choice."
}
] | [
{
"body": "<p>This template is either unusable or would make you write HTML in the business logic part spoiling the whole idea.</p>\n\n<p>A template engine is a more complex application than people often think. There is always a <em>presentation logic</em> that could be quite complex. Which means a template must support programming statements. At least loops and conditions. Without them, it will be almost unusable.</p>\n\n<p>Imagine you need to list 10 posts an a blog. How it could be done in your template? Going to add all the HTML formatting to variables before assigning them? Really?</p>\n\n<p>So, such a simple template could be made viable only by letting PHP to interpret the template. So it could be like</p>\n\n<pre><code>public function render($template, $variables = []) {\n array_merge($this->variables, $variables);\n extract($variables)\n ob_start();\n include $template;\n return ob_get_clean();\n}\n</code></pre>\n\n<p>this way you will be able to use full featured templates that will contain all the logic needed for the presentation of your data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T08:41:11.063",
"Id": "208672",
"ParentId": "208654",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-28T23:16:11.333",
"Id": "208654",
"Score": "2",
"Tags": [
"php",
"template"
],
"Title": "Simple template engine in PHP"
} | 208654 |
<p>Before I start writing my first MVC framework, I want to improve my code quality as much as I can, can anyone give me some constructive criticism on how I can improve this?</p>
<p>It is a simple router, built for simple use. It should be pretty simple what's going on, and the usage should be easy to picture. It's nothing major but works well for simple functionality using it.</p>
<pre><code><?php
class Router {
public $routes = [];
public $routeMethods = [];
public function get($route, $settings) {
$this->add($route, $settings, ['GET']);
}
public function post($route, $settings) {
$this->add($route, $settings, ['POST']);
}
public function add($route, $settings, $methods) {
$this->routes[$route] = $settings;
$this->routeMethods[$route] = $methods;
}
public function dispatch() {
$requestUrl = $_SERVER['QUERY_STRING'];
if (array_key_exists($requestUrl, $this->routes)) {
$route = $this->routes[$requestUrl];
$methods = $this->routeMethods[$requestUrl];
$method = $_SERVER['REQUEST_METHOD'];
if (!in_array($method, $methods)) {
echo 'Method ' . $method . ' not allowed.';
}
else {
$controller = $route['controller'];
if (class_exists($controller)) {
$class = new $controller(); // grab from di cache when we have one
$action = $route['action'];
if (method_exists($class, $action)) {
$class->$action();
}
else {
echo 'We couldn\'t find action \'' . $action . '\ in controller \'' . $controller . '\'';
}
}
else {
echo 'We couldn\'t find controller \'' . $controller . '\'';
}
}
}
else {
echo '404 not found';
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T08:04:39.353",
"Id": "403066",
"Score": "0",
"body": "_SERVER should be provided from outside. What if action shoul accept parameters?"
}
] | [
{
"body": "<ul>\n<li>set <code>public $routes</code> to private or protected if its jsut an internal resource of this class. Just use public if other classes/code explicitly should call the mothod/property</li>\n<li><code>method_exists</code> doesn't check if the method is callable. But that might be important if you execute legacy code</li>\n<li>Avoid <code>echo 'some text'</code> Better use exceptions and an exception handler</li>\n<li>If you use <code>if (){} else{}</code> you could think about using the if for the termination condition and the function continues regulary if its ok</li>\n<li>Your note about the dependency injection cache is good. Keep your idea. You are on the rigth way.</li>\n<li>I would recommend to use doc-blocks as annotation and for IDE autocompletion for all public functions as well as class properties. This will increase the readability </li>\n<li>You didn't said which version of PHP you are using. Switch to >= 7.1 because 7.0 will reach its end of life soon. So you should use return types and type hinting </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T13:09:23.293",
"Id": "208687",
"ParentId": "208658",
"Score": "1"
}
},
{
"body": "<p>Expanding on the answer provided by unherz;</p>\n\n<h2>Validate the programmer</h2>\n\n<p>Sometimes we make mistakes so you should check the <code>$settings</code> provided by the programmer are correct as you require them to pass at least two parameters <code>action</code> & <code>controller</code> so I would add a method <code>validateRouteSettings</code> I also implemented unherz answer to show how early returns (exceptions in this case) would look</p>\n\n<h2>Naming</h2>\n\n<p>You call object methods \"actions\" which is in-correct, should try to be consistent in naming structures</p>\n\n<p>Any way here an updated implementation</p>\n\n<pre><code><?php\n\nclass Router {\n\n protected $routes = [];\n protected $routeMethods = [];\n\n public function get(string $route, array $settings) :void {\n $this->add($route, $settings, ['GET']);\n }\n\n public function post(string $route, array $settings) :void {\n $this->add($route, $settings, ['POST']);\n }\n\n public function add(string $route, array $settings, array $methods) :void {\n $this->validateRouteSettings($route, $settings);\n $this->routes[$route] = $settings;\n $this->routeMethods[$route] = $methods;\n }\n\n private function validateRouteSettings(string $route, array $settings) :bool\n {\n if(!isset($settings[\"controller\"])){\n throw new \\Exception(\"Missing controller for $route\", 1);\n }elseif(!isset($settings[\"method\"])){\n throw new \\Exception(\"Missing method for $route\", 1);\n }\n\n return true;\n }\n\n public function dispatch() :void {\n $requestUrl = $_SERVER['QUERY_STRING'];\n\n if (!array_key_exists($requestUrl, $this->routes)) {\n throw new \\Exception('404 not found', 1);\n }\n\n $route = $this->routes[$requestUrl];\n $methods = $this->routeMethods[$requestUrl];\n $method = $_SERVER['REQUEST_METHOD'];\n\n if (!in_array($method, $methods)) {\n throw new \\Exception('Method ' . $method . ' not allowed.', 1);\n }\n\n $controller = $route['controller'];\n\n if (!class_exists($controller)) {\n throw new \\Exception('We couldn\\'t find controller \\'' . $controller . '\\'', 1);\n }\n\n $class = new $controller(); // grab from di cache when we have one\n\n $method = $route['method'];\n\n if (!method_exists($class, $method)) {\n throw new \\Exception('We couldn\\'t find method \\'' . $method . '\\ in controller \\'' . $controller . '\\'', 1);\n }\n\n $class->$method();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T15:14:06.950",
"Id": "208770",
"ParentId": "208658",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T00:05:57.120",
"Id": "208658",
"Score": "1",
"Tags": [
"php",
"mvc",
"url"
],
"Title": "Simple router in PHP"
} | 208658 |
<p>I've created a somewhat "Brute-force search engine" based on a document's filename, as well as an additional keyword that describes the said document. I had to make one as my company's resources are a mess and not fully structured, so it's tough to search for a document using just the regular Windows search tool.</p>
<p>What I first did is to simply extract the filepath of all documents using CMD and DIR, and output it to a csv file which I processed.
Then, using an excel formula, extract the filename from the path and remove the filetype as well. I've added an extra column for the keywords portion, which is split via commas.</p>
<p>Once a search is initiated, the search term is broken down to each individual words via spaces. This goes the same for the filename, and keywords. After that, a simple for loop just iterates each word and see if's a match. If it is, a counter is added. Once done, the data is copied onto a temporary sheet.</p>
<p>After checking all available filepaths and moving the matched result on the temporary sheet, I sort them based on the counter, so that the highest match goes on top. Then, I copy the results (including the path) to the main sheet with the searchbox, display the results, and add a hyperlink so that it can be clicked.</p>
<pre><code>Sub Searchresult()
Dim x As Range, y As Long, count As Long, i As Integer, j As Integer, k As Integer, l As Integer
Dim names() As Variant, namesdup() As Variant
Dim search() As String, keyword() As String, namesraw() As String, searchval As String
Dim result As String
Dim tbl As ListObject, sortcol As Range, lrow As Long, lrow2 As Long
OptimizeVBA True 'Makes processing this a lot faster
searchval = Worksheets("Sheet1").Range("E8").Value 'Gets the searchbox text
With Worksheets("Sheet3") 'Prep for placing results in table.
Set tbl = .ListObjects("tblSearch")
Set sortcol = .Range("tblSearch[sort]")
tbl.DataBodyRange.ClearContents
End With
With Worksheets("Sheet2")
search = Split(Trim(searchval), " ") 'split search terms via spaces
lrow2 = .Cells(Rows.count, 1).End(xlUp).Row
For Each x In Range("A2:A" & lrow2) 'Iterate all values in Sheet2
count = 0
lrow = Worksheets("Sheet3").Cells(Rows.count, 1).End(xlUp).Row + 1 'get the last row in Sheet2
keyword() = Split(.Range("d" & x.Row), ",") ' split keywords via comma
namesraw() = Split(Replace(Replace(Replace(Replace(Replace(.Range("c" & x.Row), "-", " "), "(", ""), ")", ""), "'", ""), "_", " "), " ") 'splits names via spaces, deleting any unwanted characters
'This section converts the String array from above to a Variant array
ReDim namesdup(LBound(namesraw) To UBound(namesraw))
Dim index As Long
For index = LBound(namesraw) To UBound(namesraw)
namesdup(index) = namesraw(index)
Next index
'end section
names() = RemoveDupesColl(namesdup())
'We need to remove duplicates from the name search, as it affects accuracy.
'For example, if you search for something that has the word "loc", the filename that repeats this word multiple times will get top results.
'//SEARCH FUNCTION STARTS HERE
'This first part will compare each word typed in the searchbox form each word in the keywords column in Sheet2.
For i = LBound(keyword) To UBound(keyword) 'Iterate the number of keywords in a given row
For j = LBound(search) To UBound(search) 'Iterate the number of words in the searchbox
If UCase(search(j)) Like "*" & UCase(keyword(i)) & "*" Or UCase(keyword(i)) Like "*" & UCase(search(j)) & "*" Then 'compare search term and keyword
Worksheets("Sheet3").Range("A" & lrow, "B" & lrow).Value = .Range("A" & x.Row, "B" & x.Row).Value 'Copy A & B to Sheet3.
count = count + 1
Worksheets("Sheet3").Range("C" & lrow).Value = count 'Put a count on Sheet3
Worksheets("Sheet3").Range("D" & lrow).Value = .Range("E" & x.Row).Value 'Copy D to Sheet3
End If
Next
Next
For k = LBound(names) To UBound(names) 'Iterate the number of names that were split from the document name.
For l = LBound(search) To UBound(search) 'Iterate the number of words in the searchbox
If Len(names(k)) <= 3 And Len(names(k)) > 1 Then 'Prevents getting top results for being part of a long word, for ex: the word LOC will be found on all words that has it, like "LOCATION".
If UCase(search(l)) = UCase(names(k)) Or UCase(names(k)) = UCase(search(l)) Then 'If it's a short word, it must be the same as the search term
Worksheets("Sheet3").Range("A" & lrow, "B" & lrow).Value = .Range("A" & x.Row, "B" & x.Row).Value
count = count + 1
Worksheets("Sheet3").Range("C" & lrow).Value = count
Worksheets("Sheet3").Range("D" & lrow).Value = .Range("E" & x.Row).Value
End If
Else
If (UCase(search(l)) Like "*" & UCase(names(k)) & "*" Or UCase(names(k)) Like "*" & UCase(search(l)) & "*") And Len(names(k)) > 2 And Len(search(l)) > 2 Then 'compare search term and document name
Worksheets("Sheet3").Range("A" & lrow, "B" & lrow).Value = .Range("A" & x.Row, "B" & x.Row).Value
count = count + 1
Worksheets("Sheet3").Range("C" & lrow).Value = count
Worksheets("Sheet3").Range("D" & lrow).Value = .Range("E" & x.Row).Value
End If
End If
Next
Next
'//SEARCH FUNCTION ENDS HERE
Next x
End With
With tbl.Sort 'sort everything based on count to get best result on top
.SortFields.Clear
.SortFields.Add Key:=sortcol, SortOn:=xlSortOnValues, Order:=xlDescending
.Header = xlYes
.Apply
End With
End Sub
Sub copysearch()
Dim linkrange As Range, c As Range
Dim namerange As Range
Dim hyp As Hyperlink
Dim hyps As Hyperlinks
With Worksheets("Sheet1")
Worksheets("Sheet3").Range("A2:D21").Copy 'Copy the first 20 results
.Range("D13").PasteSpecial Paste:=xlPasteValues 'and paste them on Sheet1
Application.CutCopyMode = False
Set linkrange = .Range("D13:D32")
Set namerange = .Range("E13:E32")
For Each c In namerange 'Iterates all cells from E13 to E32
c.ClearHyperlinks 'Remove all hyperlinks if there are any
If c <> "" Then 'Make sure to not add hyperlinks on empty cells
c.Hyperlinks.Add c, .Range("D" & c.Row) 'Add a hyperlink based on the value of D.
If .Range("G" & c.Row).Value = True Then 'Check if G value is True
.Range("E" & c.Row).Font.Color = vbWhite 'Link is valid, so it's colored white
Else
.Range("E" & c.Row).Font.Color = vbRed 'Link is not valid, colored Red, needs updating.
End If
End If
Next
.Range("E13:E32").Font.Underline = False
.Range("E13:E32").Font.name = "Cambria"
End With
OptimizeVBA False
End Sub
Sub OptimizeVBA(isOn As Boolean) 'Optimize VBA by not running calculations, events, and updates up until Macro is done. Found online.
Application.Calculation = IIf(isOn, xlCalculationManual, xlCalculationAutomatic)
Application.EnableEvents = Not (isOn)
Application.ScreenUpdating = Not (isOn)
End Sub
Function RemoveDupesColl(MyArray As Variant) As Variant 'Online code to remove any duplicates in an array.
'DESCRIPTION: Removes duplicates from your array using the collection method.
'NOTES: (1) This function returns unique elements in your array, but
' it converts your array elements to strings.
'SOURCE: https://wellsr.com
'-----------------------------------------------------------------------
Dim i As Long
Dim arrColl As New Collection
Dim arrDummy() As Variant
Dim arrDummy1() As Variant
Dim item As Variant
ReDim arrDummy1(LBound(MyArray) To UBound(MyArray))
For i = LBound(MyArray) To UBound(MyArray) 'convert to string
arrDummy1(i) = CStr(MyArray(i))
Next i
On Error Resume Next
For Each item In arrDummy1
arrColl.Add item, item
Next item
Err.Clear
ReDim arrDummy(LBound(MyArray) To arrColl.count + LBound(MyArray) - 1)
i = LBound(MyArray)
For Each item In arrColl
arrDummy(i) = item
i = i + 1
Next item
RemoveDupesColl = arrDummy
End Function
</code></pre>
<p>Everything is working as intended, though I believe that the code can be further optimized. Please note that I only dabble at VBA and had some experience with VB.Net but am not really a programmer. However, I understand formatting so I still made sure that my coding can still be understood. Comments are added everywhere as I am only a temp in the company and would like to pass it on to someone else just in case..</p>
<p>My difficulties when I started this out:</p>
<ul>
<li>Singular/Plural terms: That's why there's an "Or" statement that
inverts the variables in the "Like" statement as a resolution.</li>
<li>2-3 letter words being found inside bigger words: As we're using
acronyms or shortcuts, there are times that there are results that
are being found that's not really related to what's supposed to show.
So an additional If statements were added specifically for the short
words.</li>
<li>Repeating words in filenames: For some reason, there are filenames that repeat the same word multiple times (The acronyms), and it skews the top result as it matches multiple times. I've used an online code to remove the duplicates via collection method. Hence, there was a need to convert the array to a Variant.</li>
<li>Opening write-protected documents: Sadly, this wasn't fixed, but basically a Word popup when asking to open as read only does not show on top of the Excel program. Excel meanwhile, is unresponsive until the popup box was answered. Wait too long, and an OLE error will show up. A workaround to this one is to have another Word program open, and the popup will show there.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:30:04.407",
"Id": "403030",
"Score": "0",
"body": "@Comintern As the codes were sourced online, I wasn't sure if I have to really put it in, but if that's required, I've added it in now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:36:12.677",
"Id": "403033",
"Score": "0",
"body": "Thanks. The other question I have is what you're referring to with the \"Word popup when asking to open as read only\". I didn't catch any references in there that would indicate that you're automating Word. Is that what the hyperlinks target? (I think the Z-ordering is a Windows 10 \"feature\" - i.e. bug)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:40:42.950",
"Id": "403039",
"Score": "0",
"body": "Yes, the hyperlink also targets Word (.docx) files, as well as PDF, excel files, etc. The other files are opened without issues, and Word documents will open fine too as long as they're not write-protected. Write-protected, meaning it prompts for a password upon opening the file, yet also offers Read Only mode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:42:07.207",
"Id": "403042",
"Score": "0",
"body": "I've experimented with this, and as long as Word does not prompt any popup box, it will be fine. Changing the file property to Read Only will also work, but the documents are updated on a daily basis, so passwords are used as protection instead. Also we're using Windows 7."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T03:06:25.760",
"Id": "403053",
"Score": "0",
"body": "Using dictionaries would greatly simplify and speed up your code. Regex would be best but it can be complicated."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T00:56:07.397",
"Id": "208661",
"Score": "3",
"Tags": [
"vba",
"excel"
],
"Title": "Document \"Search Engine\" in Excel"
} | 208661 |
<p>I am trying to solve a coding challenge:</p>
<blockquote>
<p>Given <em>N</em> integers <em>A</em><sub>1</sub>, <em>A</em><sub>2</sub>, …, <em>A</em><sub><em>N</em></sub>, count the number of triplets (<em>x</em>, <em>y</em>, <em>z</em>) (with 1 ≤ <em>x</em> < <em>y</em> < <em>z</em> ≤ <em>N</em>) such that at least one of the following is true:</p>
<p><em>A</em><sub><em>x</em></sub> = <em>A</em><sub><em>y</em></sub> × <em>A</em><sub><em>z</em></sub>, and/or<br>
<em>A</em><sub><em>y</em></sub> = <em>A</em><sub><em>x</em></sub> × <em>A</em><sub><em>z</em></sub>, and/or<br>
<em>A</em><sub><em>z</em></sub> = <em>A</em><sub><em>x</em></sub> × <em>A</em><sub><em>y</em></sub></p>
<h3>Sample case 1</h3>
<p>5 2 4 6 3 1</p>
<p>In Sample Case #1, the only triplet satisfying the condition given in the problem statement is (2, 4, 5). The triplet is valid since the second, fourth, and fifth integers are 2, 6, and 3, and 2 × 3 = 6. thus the answer here is <strong>1</strong>.</p>
<h3>Sample case 2</h3>
<p>2 4 8 16 32 64</p>
<p>The six triplets satisfying the condition given in the problem statement are: (1, 2, 3), (1, 3, 4), (1, 4, 5), (1, 5, 6), (2, 3, 5), (2, 4, 6). so the answer here is 6.</p>
</blockquote>
<p>My Code in python:</p>
<pre><code>import itertools
count=0
for t in itertools.combinations(l,3):
if t[0]*t[1]==t[2] or t[1]*t[2]==t[0] or t[0]*t[2]==t[1]:
count+=1
print(count)
</code></pre>
<p>This is the naive way of generating all possible 3 length combinations and checking for the condition. This works fine for smaller input but when the inout size increase time complexity increases. I am assuming for an example that has <code>1,2,3,6,8</code> the combinations generated are <code>(2,3,6),(2,3,8)</code> 2,3,6 satisfy the condition so the checking for 2,3,8 is unnecessary and can be avoided. How can I modify my code to take advantage of this observation ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T06:16:37.543",
"Id": "403060",
"Score": "1",
"body": "Is this from https://codejam.withgoogle.com/codejam/contest/5374486/dashboard ?"
}
] | [
{
"body": "<p>Your <code>combinations(…, 3)</code> loop makes your algorithm O(<em>N</em><sup>3</sup>).</p>\n\n<p>It's easy to improve it to be O(<em>N</em><sup>2</sup>). The question is, essentially: for every pair of entries, how many occurrences of their product are in the list? So, make an <code>indexes</code> data structure to help you find, in O(1) time, where the product might be located.</p>\n\n<pre><code>from collections import defaultdict\nfrom itertools import combinations\n\na = [int(ai) for ai in input('Input: ').split()]\n\nindexes = defaultdict(set)\nfor i, ai in enumerate(a):\n indexes[ai].add(i)\n\ntriplets = set()\nfor x, y in combinations(range(len(a)), 2):\n for z in indexes[a[x] * a[y]].difference([x, y]):\n triplets.add(tuple(sorted((x, y, z))))\n\nprint(len(triplets))\n</code></pre>\n\n<p>Here, I've chosen to stick closer to the notation used in the challenge itself, with <code>a</code> being the list, and <code>x</code>, <code>y</code>, <code>z</code> as the indexes of entries (but 0-based rather than 1-based).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:59:40.557",
"Id": "403335",
"Score": "0",
"body": "Can you add few examples"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:12:06.800",
"Id": "403345",
"Score": "0",
"body": "Examples of what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:15:38.817",
"Id": "403350",
"Score": "0",
"body": "How would this logic work for [1,1,1,1] and [5,2,4,6,3,1]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T18:04:59.043",
"Id": "403355",
"Score": "0",
"body": "You're right: the code in Rev 1 broke in the case of `[1, 1, 1, 1]`, giving 12 instead of 4 because it was counting all permutations of (x, y, z)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T06:32:05.070",
"Id": "208669",
"ParentId": "208662",
"Score": "1"
}
},
{
"body": "<p>Your answer is a faithful implementation of the problem description. Unfortunately, that makes it <span class=\"math-container\">\\$O(N^3)\\$</span></p>\n\n<p>200_success has described an <span class=\"math-container\">\\$O(N^2)\\$</span> solution to this problem; I’m thinking we can do a little better, perhaps not as good as <span class=\"math-container\">\\$O(N \\log N)\\$</span>, but maybe close.</p>\n\n<p>We’ve not been asked to find the tuples <code>(x,y,z)</code>, <code>x < y < z</code>, which satisfy that <code>A[x],A[y],A[z]</code> represent (in any order) multiplier, multiplicand, and product; we’ve been asked to find only the number of such tuples. This means we can change the order of values in <code>A[]</code>, reindex the <code>A[]</code> array, or even change the representation of <code>A[]</code> to a list of value, count pairs, and still obtain the same answer. </p>\n\n<p>The first step should be to sort the <code>A[]</code> values. <span class=\"math-container\">\\$O(N \\log N)\\$</span>. This guarantees <code>A[x] ≤ A[y] ≤ A[z]</code>, when <code>x < y < z</code>, and we now only need to look for tuples where <code>A[x]*A[y]=A[z]</code>.</p>\n\n<p>We can loop <code>for x in range(N-2)</code> and <code>for y in range(x+1, N-1)</code>, and find the product’s indexes in the manner suggested by 200_success, but now we can break out of the inner loop when <code>A[x]*A[y] > A_max</code>, and break the outer loop when <code>A[x]*A[x+1] > A_max</code>, which should reduce the number of iterations significantly. </p>\n\n<p>But again we really don’t care what the indices are which correspond to the product. We only care about how many there are. So after sorting <code>A[]</code>, we can count the number of occurrences of each unique value <code>C[]</code>, and eliminate the duplicates from <code>A[]</code>. If <code>C[p] > 0</code> for <code>p = A[x] * A[y]</code>, then the number of tuples for that multiplier, multiplicand, product combination is <code>C[A[x]] * C[A[y]] * C[p]</code>, if <code>A[x] ≠ 1</code>. When <code>A[x]=1</code>, then <code>p=A[y]</code> for all <code>x<y</code>, and the number of tuples for these combinations is <code>C[1] * C[p] * (C[p]-1)/2</code>. In addition, there are <code>C[1] * (C[1]-1) * (C[1]-2)/6</code> combinations of <code>1*1=1</code>. Lastly, we need to count any combinations of bases and their squares: <code>p = A[x] * A[x]</code> which is <code>C[p] * C[A[x]] * (C[A[x]]-1)/2</code>.</p>\n\n<pre><code>from collections import Counter\n\ndef tuple_products(*A):\n c = Counter(A) # Record # of duplicates\n A = sorted(c) # Sorted list of unique values\n\n largest = A[-1] # For early loop termination\n\n triplets = 0 # Number of product triplets\n\n # Handle (1, A[y], A[y]) triplets first\n if A[0] == 1:\n\n c1 = c[1] # Number of 1's\n\n # Number of (1, 1, 1) triplets\n triplets += c1 * (c1-1) * (c1-2) // 6\n\n A = A[1:] # Remove 1 from A list and\n del c[1] # from count dictionary\n\n # Number of (1, A[y], A[y]) triplets (A[y] != 1)\n triplets += c1 * sum(cy * (cy-1) for cy in c.values()) // 2\n\n\n # Handle (A[x], A[y], A[z]) triplets (A[x] != 1)\n for x, ax in enumerate(A[:-1]):\n\n # Break outer loop if beyond possible products\n square = ax*ax\n if square > largest:\n break\n\n # Number of (A[x], A[x], A[x]^2) triplets\n cx = c[ax]\n triplets += cx * (cx-1) * c[square] // 2\n\n # Handle (A[x], A[y], A[z]) triplets\n for ay in A[x+1:-1]:\n\n # Break inner loop when beyond possible products\n product = ax*ay\n if product > largest:\n break\n\n # Number of (A[x], A[y], A[z]) triplets\n triplets += cx * c[ay] * c[product]\n\n\n print(triplets)\n\ntuple_products(4,4,4,4,16)\ntuple_products(5,2,4,6,3,1)\ntuple_products(2,4,8,16,32,64)\ntuple_products(1,1,1,1)\ntuple_products(8,1,1,4,2,1,4,1,2)\n</code></pre>\n\n<hr>\n\n<p>We are still <span class=\"math-container\">\\$O(N^2)\\$</span>, but we’ve made N smaller by eliminating any duplicate numbers, and eliminated many of the <span class=\"math-container\">\\$N^2\\$</span> combinations by sorting and breaking out of the loops early. Can we do any better? I think so. Here’s why:</p>\n\n<p>Consider the numbers 3, 5, 7, 8, 9, 10, 11, 14, 36, 42, 45. The outer loop would start at <code>x=0, A[x]=3</code>. The inner loop would start at <code>y=1, A[y]=5</code>, with the product <code>product=3*5=15</code>. Since <code>A[]</code> is sorted, we can perform a bisection search for the <code>15</code> and find the next number higher than <code>15</code>, which is <code>36</code>. Dividing <code>36/A[x]</code> gives us <code>12</code>, performing a bisection search, and getting the next higher number retrieves <code>14</code>. Multiplying <code>A[x]*14</code> gives us <code>42</code>, which can actually be found in the <code>A[]</code> list. Advancing past <code>14</code> takes us to <code>36</code> and <code>3*36</code> is greater than the maximum so we can break out of the inner loop. Using this bisection search technique has skipped over the numbers 7, 8, 9, 10, and 11. I think this means we’ve got <code>log N</code> numbers in each inner loop, and a <code>log N</code> bisection search giving an inner loop complexity of <span class=\"math-container\">\\$O(log^2 N)\\$</span>, which combined with the outer loop gives <span class=\"math-container\">\\$O(N \\log^2 N)\\$</span>. I think. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T07:00:10.033",
"Id": "208913",
"ParentId": "208662",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T01:26:55.007",
"Id": "208662",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "Given some integers, find triplets where the product of two numbers equals the third number"
} | 208662 |
<p>I'm struggling to make a React/JS map I have more efficient. Essentially, I have a list of cards, and then a map of markers. When I hover on one of the cards, it changes the styling of the marker.</p>
<p>Here’s what it looks like: </p>
<p><a href="https://i.stack.imgur.com/GNTxV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GNTxV.png" alt="enter image description here"></a></p>
<p>But the way I'm doing this...I'm pretty sure is really inefficient, so here's how I have it setup in a couple of components:</p>
<pre><code>//LocationsGrid.js
class LocationsGrid extends React.Component {
state = {
hoveredCardId: ""
};
setCardMarkerHover = location => {
this.setState({
hoveredCardId: location.pageid
});
};
resetCardMarkerHover = () => {
this.setState({
hoveredCardId: ""
});
};
render() {
const { locations } = this.props;
{locations.map((location, index) => (
<LocationCard
setCardMarkerHover={this.setCardMarkerHover}
resetCardMarkerHover={this.resetCardMarkerHover}
location={location}
/>
))}
// map stuff
<div className={classes.mapDiv}>
<MapAndMarkers
locations={locations}
hoveredCardId={this.state.hoveredCardId}
/>
</div>
//LocationCard.js
class LocationCard extends React.Component {
render() {
const { classes, location } = this.props;
return (
<Card
className={classes.card}
onMouseEnter={e => this.props.setCardMarkerHover(location)}
onMouseLeave={e => this.props.resetCardMarkerHover()}
>
<CardContent className={classes.cardContentArea}>
</CardContent>
</Card>
);
}
}
// MapAndMarkers.js
class MapAndMarkers extends React.Component {
render() {
const { locations, hoveredCardId, pageid } = this.props;
let MapMarkers = locations.map((location, index) => {
return (
<MapMarker
key={location.id}
lat={location.lat}
lng={location.lng}
pageid={location.pageid}
hoveredCardId={hoveredCardId}
/>
);
});
return (
<div>
<GoogleMapReact>
{MapMarkers}
</GoogleMapReact>
</div>
);
}
}
// MapMarker.js
import classNames from 'classnames';
class MapMarker extends React.Component {
render() {
const { classes, pageid, hoveredCardId } = this.props;
return (
<div className={classes.markerParent}>
<span className={classNames(classes.tooltips_span, pageid == hoveredCardId && classes.niftyHoverBackground)}>{this.props.name}</span>
</div>
);
}
}
</code></pre>
<p>The problem with doing it this way is I'm pretty sure there's a whole bunch of wasted rendering. When I pulled out the mouse events from my <code>LocationCard</code>, everything else runs faster.</p>
<p>What would be a more efficient way of tracking hovered list items so that I can change the map marker style?</p>
<p><a href="https://github.com/kpennell/airnyt/tree/1478a459fa5e7b7d44939ed102b02900e31a5afd" rel="nofollow noreferrer">GitHub</a></p>
<p><a href="http://airnyt.surge.sh" rel="nofollow noreferrer">Demo</a></p>
| [] | [
{
"body": "<p>While I wouldn't say your code is inefficiently styled, you can definitely improve the performance of your components.</p>\n\n<p>React performs in a tree format, when a component updates, all their children will attempt to update and potentially re-render. This is part of what React calls the <a href=\"https://reactjs.org/docs/reconciliation.html\" rel=\"nofollow noreferrer\">Reconciliation process</a>.</p>\n\n<p>There is a function you can add to your component classes called <code>componentShouldUpdate</code>, which comes with parameters <code>(nextProps, nextState)</code>. The idea of this function is to decide whether the component needs to re-render. You can find some more information on this property <a href=\"https://reactjs.org/docs/react-component.html#shouldcomponentupdate\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>For example, if you were to hover and change the colour of one of the markers, the entire list of markers rerenders, but, you can make a check to see whether the specific marker is the one you want to color and so needs to be updated.</p>\n\n<p>These kinds of stops on rerendering means as high as possible in your render trees means you can get the most performance gains.</p>\n\n<pre><code>shouldComponentUpdate(nextProps) { // inside MapMarker.js\n const { props } = this;\n return props.hoveredCardId !== nextProps.hoveredCardId\n || nextProps.hoveredCardId !== props.pageid;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:09:23.127",
"Id": "405905",
"Score": "1",
"body": "This is a helpful tip. I'll look more into that lifecycle method"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T04:54:51.040",
"Id": "209958",
"ParentId": "208665",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209958",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T03:54:44.697",
"Id": "208665",
"Score": "3",
"Tags": [
"react.js",
"jsx",
"google-maps"
],
"Title": "Hover on list items to change map marker styling"
} | 208665 |
<p>For scanning my subnet using my IP address, I need to run the following command</p>
<pre><code>nmap -sn 192.168.100.*
</code></pre>
<p>I want to extend this functionality such that I don't have to manually specify the first three parts of the IP range myself. I came up with this rough solution.</p>
<pre><code>ip=$( hostname -I | awk '{print $1}' | awk -F. '{print $1; print $2; print $3}' ORS="."; echo -n "*");
nmap -sn $ip
</code></pre>
<p>Is there a more cleaner way of achieving the same?</p>
| [] | [
{
"body": "<p>This is pretty reasonable. I'd have <code>awk</code> do a bit more of the work:</p>\n\n<pre><code>ip=$( hostname -I | awk '{print $1}' | awk -F. '{OFS=\".\"; print $1, $2, $3,\"*\"}'; );\n</code></pre>\n\n<p>I switched from <code>ORS</code> (output record separator) to <code>OFS</code> (output field separator) to use <code>print</code> in <code>awk</code> with commas. The commas tell it that we have multiple fields which gets rid of two \"extra\" <code>print</code> statements. This also let me move the literal <code>*</code> inside of <code>awk</code> which eliminates the shell <code>echo</code>. So I feel this is more succinct without being harder to follow.</p>\n\n<p>It might be nice to combine the <code>awk</code>s into one, but it is pretty clear what each one does and it isn't like you're processing reams of data here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:22:22.887",
"Id": "403353",
"Score": "2",
"body": "You could drop `awk '{print $1}'` in the middle and expect the same output ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:32:50.847",
"Id": "208693",
"ParentId": "208667",
"Score": "4"
}
},
{
"body": "<p>You can do it purely in Bash, using <a href=\"https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion\" rel=\"noreferrer\"><code>${<em>parameter</em>%<em>word</em>}</code></a> to strip off the last octet from the IP address.</p>\n\n<pre><code>hostname -I | while read ip _ ; do\n nmap -sn ${ip%.*}.\\*\ndone\n</code></pre>\n\n<p>Note that <code>hostname -I</code> is not portable: the <code>-I</code> option appears to be a GNU extension.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:27:47.970",
"Id": "403354",
"Score": "3",
"body": "Although it's reasonable to expect that `hostname -I` will not output something malicious, as a rule of thumb it's always good to double-quote variables used in command arguments, and written like this might be slightly kinder on the eyes too: `nmap -sn \"${ip%.*}.*\"`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T19:18:50.900",
"Id": "208710",
"ParentId": "208667",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "208693",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T04:31:13.747",
"Id": "208667",
"Score": "3",
"Tags": [
"bash",
"ip-address",
"awk"
],
"Title": "Code to get the IP address and format it to run in nmap"
} | 208667 |
<p>I was faced with below interview question today and I came up with below solution but somehow interviewer was not happy. I am not sure why..</p>
<blockquote>
<p>Given a binary search tree, find the kth smallest element in it.</p>
</blockquote>
<p>Is there any better or more efficient way to do this problem?</p>
<pre><code> /*****************************************************
*
* Kth Smallest Iterative
*
******************************************************/
public int kthSmallestIterative(TreeNode root, int k) {
Stack<TreeNode> st = new Stack<>();
while (root != null) {
st.push(root);
root = root.left;
}
while (k != 0) {
TreeNode n = st.pop();
k--;
if (k == 0)
return n.data;
TreeNode right = n.right;
while (right != null) {
st.push(right);
right = right.left;
}
}
return -1;
}
</code></pre>
<p>I mentioned time and space complexity as O(n). My iterative version takes extra space. Is there any way to do it without any extra space?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T05:36:54.287",
"Id": "403058",
"Score": "0",
"body": "Is the tree mutable? Is `O(k)` memory acceptable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T05:57:52.343",
"Id": "403059",
"Score": "0",
"body": "I didn't asked this question to the interviewer but let's say if it is not mutable then can we optimize anything? And let's say if it is mutable then how efficiently we can do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T06:42:53.863",
"Id": "403061",
"Score": "1",
"body": "Do you have control over the `TreeNode` class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:08:58.743",
"Id": "403131",
"Score": "0",
"body": "If it is mutable, the [Morris traversal](https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/) is an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T19:58:17.100",
"Id": "403167",
"Score": "0",
"body": "(Following proper specification and comments,) I guess I'd a) try to get hands on a capacity limited Deque b) push a dummy \"super root\" `sr` (`root.clone()`?) with `sr.right = root`, increase `k` and get rid of the duplicated *push left-path*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:45:37.470",
"Id": "403178",
"Score": "0",
"body": "(Originally [asked in SO](https://stackoverflow.com/q/53530050/3789665).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T22:54:03.703",
"Id": "403673",
"Score": "0",
"body": "How is `TreeNode` defined? If it contains the size of the subtree, you can solve the problem in O(1) space, O(log k) time (average), O(k) time worst case."
}
] | [
{
"body": "<p>The \"not happy interviewer\" case is probably not connected to the efficiency of the algorithm, but to a few problems with the codes cleanliness:</p>\n\n<ul>\n<li>You modify method parameters. While this is technically possible, it is generally frowned upon as it makes code hard to read and even harder to debug. Don't do this. Period.</li>\n<li>Variable names don't match. <code>root</code> becomes a general pointer to a tree node (which is not root any more), <code>right</code> becomes left. This is a mumble jumble of hard to understand code, which is a nightmare to maintain.</li>\n<li>The way you find the target element is not obvious at a glance. At least add a comment on what you do and why it solves the original problem.</li>\n</ul>\n\n<p>From the interviewers perspective, you managed to solve a simple problem with a piece of code, which already is problematic to understand and maintain. Imagine what happens if you get a real complex task with 100 classes and 10000 lines of code involved...</p>\n\n<p>Thus: work on maintainability and clarity first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:52:18.207",
"Id": "403126",
"Score": "1",
"body": "I agree with what you said, but would also add that this code (even if it's pseudocode) doesn't read like Java, which I would find concerning if I were interviewing someone who would be working primarily in Java"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T08:11:29.263",
"Id": "208671",
"ParentId": "208668",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>I mentioned time and space complexity as O(n).</p>\n</blockquote>\n\n<p>Those bounds seem rather loose. If the tree is self-balancing then on a quick glance, and without attempting to prove it, I think your code probably has time complexity <span class=\"math-container\">\\$O(k + \\lg n)\\$</span> and space <span class=\"math-container\">\\$O(\\lg n)\\$</span>.</p>\n\n<blockquote>\n <p>My iterative version takes extra space. Is there any way to do it without any extra space?</p>\n</blockquote>\n\n<p>Assuming that by \"<em>without any extra space</em>\" you really mean \"<em>with <span class=\"math-container\">\\$O(1)\\$</span> extra space</em>\", it depends. Does <code>TreeNode</code> have a reference to its parent?</p>\n\n<p>The way to really do this efficiently is for <code>TreeNode</code> to have a variable which tracks the size of the subtree rooted at that node.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T18:29:07.760",
"Id": "403160",
"Score": "0",
"body": "what if the tree is not self-balancing then what is the time and space complexity I have for my above code? So we cannot solve this without any extra space without modifying BST?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T19:35:51.060",
"Id": "403164",
"Score": "0",
"body": "`[if balanced probable] time complexity O(k+lgn)` or more generally \\$O(k+Height(T))\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:29:45.777",
"Id": "403177",
"Score": "0",
"body": "@user5447339: `if the tree is not self-balancing then what is the time and space complexity [of] above code?` You may need to go all the way down a tree without right nodes. You *never* need to go back more than *k* steps. \\$k \\in O(n)\\$ (number of tree nodes - unknown) is generally presumed, but *not* guaranteed expressly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T09:04:52.440",
"Id": "208673",
"ParentId": "208668",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T05:20:12.767",
"Id": "208668",
"Score": "2",
"Tags": [
"java",
"algorithm",
"interview-questions",
"tree"
],
"Title": "Find kth smallest element in binary search tree"
} | 208668 |
<p>I'm working on a program that aim to take sentences (currently in french) and compact them to a length of 38 characters while retaining as much information as possible.<br>
You can find another part of this project here <a href="https://codereview.stackexchange.com/questions/208594/remove-determiners-in-a-string">Remove determiners in a string</a><br>
You can also find a follow up for this question here: <a href="https://codereview.stackexchange.com/questions/208759/replacing-words-with-their-abbreviations-follow-up">Replacing words with their abbreviations - Follow up</a></p>
<p>This particular function's goal is to replace words with their abbreviations by compairing each word with all of those in the config file and replacing whenever a match is found, the goal is to keep a géneral idea of what the string meant so its not a problem that a word once replaced could ressemble an other as long as they refer to roughly the same thing.<br>
String is always upper case and free of special characters.</p>
<p>Here is how I do it:</p>
<pre><code>def shorten_words(abbreviations, string):
# abbreviations is a file parsed with configparser
for key in abbreviations:
# finds beginning of possible words
it_string = 0
while it_string < len(string) and len(string) > 38:
if string[it_string] == ' ' or it_string == 0:
if it_string == 0:
it_string = -1
# finds end of possible words
it_word = 0
while(it_word < len(key) and it_string + it_word + 1 < len(string)
and string[it_string + it_word + 1] == key[it_word].upper()):
it_word += 1
# cuts the line
if(it_word == len(key) and (it_string + it_word + 1 == len(string)
or string[it_string + it_word + 1] == ' ')):
string = string[:it_string + 1] + abbreviations[key].upper() + string[it_string + it_word + 1:]
# cuts the line for the same word with an 'S' at the end
elif(it_word == len(key) and (string[it_string + it_word + 1] == 'S'
and (it_string + it_word + 2 == len(string)
or string[it_string + it_word + 2] == ' '))):
it_word += 1
string = string[:it_string + 1] + abbreviations[key].upper() + string[it_string + it_word + 1:]
it_string += 1
if(it_string == 0):
it_string = 1
return(string)
</code></pre>
<p>here is a sample of the configfile (if key and value are equal the line is made to remove plural):</p>
<pre><code>[abbreviation]
AVANCEE = AVANC
COMPOSANT = COMPO
VERT = VERT
AGRAIRE = AGRAIR
MECANIQUE = MECA
CARROSSERIE = CARROS
SIGNALISATION = SIGNAL
FOURNITURE = FOURNI
LAITIERE = LAIT
INTERPROFESSIONNEL = INTRPRO
ATLANTIQUE = ATLAN
REALISATION = REAL
INCENDIE = INCEND
MARBRERIE = MARB
FUNEBRE = FUNEBR
POMPE = POMPE
ANTICIPATION = ANTICIP
OBJET = OBJET
ANTIQUITE = ANTIQ
MOBILITE = MOBIL
ASSOCIATIF = ASSO
ANCIENNE = ANC
TELECOMMUNICATION = TELECOM
RESEAUX = RESEAU
LOCALE = LOCAL
RESPIRE = RESPI
QUAND = QND
CHRETIENNE = CHRET
OUVRIERE = OUVRI
JEUNESSE = JEUNE
INTERCULTUREL = INTRCULT
VALORISATION = VALOR
ALIMENTAIRE = ALIMEN
COMMUNALE = COMMUNE
LAIQUE = LAIQ
CASSATION = CASS
TRAVAUX = TRAVAU
ONCOLOGIE = ONCO
RELIGION = RELIG
PLURALISME = PLURAL
FLOTTANTE = FLOT
EOLIENNE = EOLIEN
HUMAINE = HUMAIN
POTENTIEL = POTENT
AMELIORATION = AMELIO
MUSIQUE = MUSIQ
MUNICIPALE = MUNI
EVANGELIQUE = EVANG
BIOLOGISTE = BIOLOG
REPUBLICAIN = REPU
SYMPATHISANT = SYMPAT
ELU = ELU
INTERCONNEXION = INTRCONN
CONSULTANT = CONSULT
ORGANIZATION = ORGA
OLYMPIQUE = OLYMP
CAPACITE = CAPA
RENFORCEMENT = RENFOR
CLEF = CLEF
FRIGORIFIQUE = FRIGO
ENTREPOSAGE = ENTREPO
COLLABORATIF = COLLAB
TROUBLE = TROUBL
ENTRAIDE = ENTRAID
REPRESENTANT = REPRESENT
ADHERENT = ADHER
FOLKLORIQUE = FOLKLO
STADE = STAD
AMI = AMI
EMPEREURS = EMPER
CONFRERIE = CONFRER
SOUTENUE = SOUTENU
LISTE = LIST
ELECTION = ELECT
ELECTORALE = ELECT
FINANCEMENT = FINANC
CATHOLIQUE = CATHO
HARMONIE = HARMO
DEBOUT = DEBOU
VENT = VENT
CERCLE = CERCL
FOOTBALL = FOOT
IMPROVISATION = IMPROV
POPULAIRE = POPU
SECOURS = SECOUR
ART = ART
DRAMATURGIE = DRAMA
POETIQUE = POET
TRAVAILLANT = TRAVAIL
SYNCHRONISEE = SYNCHRO
NATATION = NATA
LOCATAIRES = LOCAT
AMICALE = AMICA
DEPARTEMENT = DEPART
INDISCIPLINEE = INDISCIPL
PARTAGE = PARTA
MEDIATION = MEDIAT
CITOYEN = CITOY
CULTIVONS = CULTIV
QUARTIER = QUART
DOMICILE = DOMI
ADMINIS = ADMIN
APPLIQUEE = APPLI
SOPHROLOGIE = SOPHRO
SPECTACLE = SPECTA
ABANDONNE = ABANDON
COMMUNAUTAIRE = COMMUN
PARTICULIER = PARTICUL
METALLIQUE = METAL
COOPERATION = COOP
PROGRAMMATION = PROGRAM
KINESITHERAPEUTE = KINESITHERAP
ENVIRON = ENVIRON
ARTISAN = ARTIS
COMMUNICATION = COM
TRANSMISSION = TRANSMIS
APPROVISIONNEMENT = APPRO
IMAGERIE = IMAGE
MANAGEMENT = MANAG
ASSOCIEE = ASSO
INFIRMIERE = INFIRM
FONDS = FOND
EMBOUTISSAGE = EMBOUTISS
DECOUPAGE = DECOUP
OUTILLAGE = OUTIL
TERRASSEMENT = TERRASS
DEMOLITION = DEMOLIT
BILINGUE = BILINGU
ECOLE = ECOL
HABITAT = HABITA
PRODUCTION = PROD
DURABLE = DURABL
PRATIQUE = PRATIQ
TRANSPORT = TRANSPOR
ASSOCIATIVE = ASSO
CRECHE = CRECH
SPECIALISEE = SPECIAL
COUVERTURE = COUVERT
ETANCHEITE = ETANCH
TOITURE = TOIT
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:32:28.470",
"Id": "403122",
"Score": "0",
"body": "I think it would help *a lot* if you explained the process behind your algorithm. How do you decide when to cut off a word? Is it a problem that `Toiture -> toit` could be confused with `toit`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:31:24.237",
"Id": "403140",
"Score": "0",
"body": "I get it it looks clear. I wouldn't worry much about the database freeing but you are right that these comments are now obsolete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:55:47.030",
"Id": "403147",
"Score": "0",
"body": "It seems like you've asked a few other questions which code looking fairly similar. In may be a good idea to take into account the answers to these questions. It shows that you are actually interested in improving your code writing skills."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T08:32:48.213",
"Id": "403258",
"Score": "0",
"body": "@Josay, I thought I did, maybe you can point me more specificaly to what I didn't do"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:02:00.640",
"Id": "403262",
"Score": "0",
"body": "what is wrong with [`str.replace`](https://docs.python.org/3.7/library/stdtypes.html#str.replace)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:11:32.917",
"Id": "403264",
"Score": "0",
"body": "@MaartenFabré Nothing I guess, I didin't knew this function"
}
] | [
{
"body": "<p>Comments from answers on your other questions</p>\n\n<p>From <a href=\"https://codereview.stackexchange.com/a/208617/9452\">Julien Rousé's answer</a>:</p>\n\n<blockquote>\n <p><strong>Documentation</strong></p>\n \n <p>You have comments, that's good. But it is way better to have a good\n docstring for the function, and fewer comments.</p>\n \n <p>Your docstring should describe what the function try to accomplish,\n why it exists, the parameter (eventually their type) and what does the\n function return.</p>\n</blockquote>\n\n<p>Also, there are <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">Python Docstrings conventions</a> (which are not always fully followed but they are definitly worh reading).</p>\n\n<blockquote>\n <p><strong>Indentation</strong></p>\n \n <p>Your code here: is very hard to read. Maybe it's because\n you pasted it into CodeReview, but be carefull when writing long and\n hard condition. The more difficult it is to read, the more difficult\n it is to debug/maintain/extend.</p>\n</blockquote>\n\n<p>From <a href=\"https://codereview.stackexchange.com/a/208506/9452\">l0b0's answer</a>:</p>\n\n<blockquote>\n <p>Naming is really important. string, array, i and j are not\n descriptive. After reading the entire function I think they could be\n renamed sentence, words, string_index and word_length.</p>\n</blockquote>\n\n<p>Then</p>\n\n<blockquote>\n <p>What is the significance of 38? If it's not significant it should be\n removed, if it is it should be named something like max_result_length.</p>\n</blockquote>\n\n<p>And</p>\n\n<blockquote>\n <p>In Python return is a simple statement, which means its argument\n should not be put in parentheses.</p>\n</blockquote>\n\n<hr>\n\n<p>My own comments</p>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide called PEP 8</a>. It is worth reading and trying to apply. Among other things it gives advices about naming, spacing, etc.</p>\n\n<p><strong>Tests</strong></p>\n\n<p>Your function takes 2 inputs and return an output. It would be a nice touch to write a few tests for it.\n(It may be worth pointing out that the <code>abbreviations</code> parameter does not need to be a config file object, any object acting like a dictionnary would do the trick. This can make writing tests easier and more explicit and you do not need to use external modules to load config files nor to have configuration in a different file.</p>\n\n<p><strong>Taking the most out of dicts</strong></p>\n\n<p>You can iterate over pairs of (key, values) on a dictionnary using <code>items()</code>. Also, you can take this chance to rename (key, val) to (longword, shortword) to be more explicit.</p>\n\n<p>Work in progress: at this stage, I have</p>\n\n<pre><code>MAX_RESULT_LENGTH = 38\n\ndef shorten_words(abbreviations, string):\n \"\"\"Shorten string `str` using the dictionnary_like object `abbreviations`.\"\"\"\n for longword, shortword in abbreviations.items():\n\n # finds beginning of possible words\n it_string = 0\n while it_string < len(string) and len(string) > MAX_RESULT_LENGTH:\n if string[it_string] == ' ' or it_string == 0:\n if it_string == 0:\n it_string = -1\n\n # finds end of possible words\n it_word = 0\n while (it_word < len(longword) and\n it_string + it_word + 1 < len(string) and\n string[it_string + it_word + 1] == longword[it_word].upper()):\n it_word += 1\n\n # cuts the line\n if (it_word == len(longword) and\n (it_string + it_word + 1 == len(string) or string[it_string + it_word + 1] == ' ')):\n string = string[:it_string + 1] + shortword.upper() + string[it_string + it_word + 1:]\n # cuts the line for the same word with an 'S' at the end\n elif (it_word == len(longword) and\n (string[it_string + it_word + 1] == 'S' and\n (it_string + it_word + 2 == len(string) or string[it_string + it_word + 2] == ' '))):\n it_word += 1\n string = string[:it_string + 1] + shortword.upper() + string[it_string + it_word + 1:]\n\n it_string += 1\n if it_string == 0:\n it_string = 1\n return string\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:33:50.493",
"Id": "403270",
"Score": "0",
"body": "I see what you mean, it is true I did not apply these advices to their full potential if at all, I did not know there was an official style guide though, thanks for pointing it out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:48:43.963",
"Id": "403274",
"Score": "0",
"body": "Also, I would like the dictionnary to remain in the form aof a config file so that it can be modified by people that don't necessarly do code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:52:07.063",
"Id": "403275",
"Score": "1",
"body": "Yep, you can keep the config file object but you can also feed your function a dictionnary. It makes testing easier because you can just write something like \"check if I shorten this strings with these abbreviations, I get the expected result\" without relying on a different file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:56:49.867",
"Id": "403278",
"Score": "0",
"body": "good idea, also, you create a variable out of the function, does that works like a global variable ? Where should I put it in the code ? (note that 38 is a redundant variable in all of the program)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:08:18.593",
"Id": "208751",
"ParentId": "208675",
"Score": "2"
}
},
{
"body": "<h1>reinvent the wheel.</h1>\n\n<p>what is wrong with <a href=\"https://docs.python.org/3/library/stdtypes.html#str.replace\" rel=\"nofollow noreferrer\"><code>str.replace</code></a></p>\n\n<h1>unclear variable names</h1>\n\n<p>It was unclear to me what <code>it_string</code> and <code>it_word</code> are until I've looked at all the code. pick variable names that express what the purpose of the variable is</p>\n\n<h1>magic numbers</h1>\n\n<p>you use <code>38</code> as a magic number. It is unclear where this comes from.\nThis is the maximum length a line should be, then extract a variable in your function to say so. You can also make this an argument to the function with default value 38.</p>\n\n<h1>line length</h1>\n\n<p>Try to limit the line length. For long expression (the <code>if</code> and <code>while</code> classes, I would split the across lines. To help me be consistent here, I use <a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\">black</a></p>\n\n<h1>Shadow standard modules</h1>\n\n<p><code>string</code> is a standard module, so I would pick another name for this argument.</p>\n\n<h1>Alternative approach</h1>\n\n<p>In python, it is very easy to split a line into words (<code>line.split(' ')</code>), So you can work per word instead of per character, and then look that word up in the <code>abbreviations</code> dict</p>\n\n<pre><code>def shorten_words(abbreviations, line, max_length=38):\n while len(line) > max_length:\n for word in line.split(\"\\t\"):\n if word in abbreviations or word + \"S\" in abbreviations:\n line = line.replace(word, abbreviations[word])\n break\n return line\n</code></pre>\n\n<p>This will enter an endless loop if <code>word == abbreviations[word]</code>. To counter that, you need to keep a set of replaced words. I also made a mistake in the handling of multiples:</p>\n\n<pre><code>def shorten_words(abbreviations, line, max_length=38):\n replacements = set()\n while len(line) > max_length:\n for word in line.split(\" \"):\n if (\n word[-1] == \"S\"\n and word not in abbreviations\n and word[:-1] in abbreviations\n ):\n word = word[:-1]\n if word not in replacements and word in abbreviations:\n line = line.replace(word, abbreviations[word])\n if word == abbreviations[word]:\n replacements.add(word)\n break\n return line\n</code></pre>\n\n<h1>testing</h1>\n\n<p>My mistakes show the importance of testing code. Make some unittests to see if the code does what you want it to do, and run them each time you change the code. A good IDE can be a large help here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:45:48.560",
"Id": "403273",
"Score": "0",
"body": "This is really good, though I do have a new version of that function myself that I'd like to compare with yours, what would be the best way to do it ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T10:58:54.773",
"Id": "403282",
"Score": "1",
"body": "open a new question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T11:25:31.970",
"Id": "403283",
"Score": "0",
"body": "I did and linked it at the top of the question"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:17:58.230",
"Id": "208753",
"ParentId": "208675",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208753",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T09:38:11.417",
"Id": "208675",
"Score": "1",
"Tags": [
"python",
"strings",
"natural-language-processing"
],
"Title": "replacing words with their abbreviations"
} | 208675 |
<p>I have made a Rubiks Cube object which builds a Cube out of Cubelet objects and then allows you to move it. Things I still plan to do is add tower cubes and triangles and other shapes as well as a method to save and load files and a graphics program to use it however I decided it was probably done enough to see what people thought about it.</p>
<pre><code>#0: Red, 1: White, 2: Green, 3: Orange, 4: Yellow, 5: Blue
from copy import deepcopy
class Cubelet:
def __init__(self, up=None, left=None, front=None, down=None, right=None,
back=None, patterned = False):
self.up = up
self.left = left
self.front = front
self.down = down
self.right = right
self.back = back
self.patterned = patterned
def __str__(self):
message = ""
if self.up != None: message += "up: " + str(self.up) + ", "
if self.left != None: message += "left: " + str(self.left) + ", "
if self.front != None: message += "front: " + str(self.front) + ", "
if self.down != None: message += "down: " + str(self.down) + ", "
if self.right != None: message += "right: " + str(self.right) + ", "
if self.back != None: message += "back: " + str(self.back) + ", "
if message == "": message = "no attributes "
return("Cubelet object with " + message[:-2])
def rotate(self, x=0, y=0, z=0):
for i in range(x%4):
up, front, down, back = self.up, self.front, self.down, self.back
self.up, self.front, self.down, self.back = front, down, back, up
if self.patterned:
sides = ["up", "back", "down", "front"]
if type(self.left) == tuple:
self.left = self.left[0], sides[(sides.index(self.left[1])+1)%4]
if type(self.right) == tuple:
self.right = self.right[0], sides[(sides.index(self.right[1])+3)%4]
for i in range(y%4):
front, left, back, right = self.front, self.left, self.back, self.right
self.front, self.left, self.back, self.right = right, front, left, back
if self.patterned:
sides = ["left", "back", "right", "front"]
if type(self.up) == tuple:
self.up = self.up[0], sides[(sides.index(self.up[1])+1)%4]
if type(self.down) == tuple:
self.down = self.down[0], sides[(sides.index(self.down[1])+3)%4]
for i in range(z%4):
up, right, down, left = self.up, self.right, self.down, self.left
self.up, self.right, self.down, self.left = left, up, right, down
if self.patterned:
sides = ["left", "up", "right", "down"]
if type(self.front) == tuple:
self.front = self.front[0], sides[(sides.index(self.front[1])+1)%4]
if type(self.back) == tuple:
self.back = self.back[0], sides[(sides.index(self.back[1])+3)%4]
return self
class Cube:
def __init__(self, form="3"):
if form[-1] == "p":
self.patterned = True
self.size = int(form[:-1])
else:
self.patterned = False
self.size = int(form)
self.form = form
self.cube = [[[] for i in range(self.size)] for j in range(self.size)]
if self.patterned: side_values = [(1, "front"), (4, "back"), (5, "up"),
(2, "down"), (0, "left"), (3, "right")]
else: side_values = [1, 4, 5, 2, 0, 3]
for y in range(self.size):
for z in range(self.size):
for x in range(self.size):
cubelet = Cubelet()
if x == 0: cubelet.left=side_values[0]
if x == self.size-1: cubelet.right=side_values[1]
if z == 0: cubelet.back=side_values[2]
if z == self.size-1: cubelet.front=side_values[3]
if y == 0: cubelet.up=side_values[4]
if y == self.size-1: cubelet.down=side_values[5]
self.cube[y][z].append(cubelet)
self.set_faces()
self.moves = 0
def __getitem__(self, index):
return(self.cube[index[0]][index[1]][index[2]])
def __setitem__(self, index, value):
self.cube[index[0]][index[1]][index[2]] = value
self.set_faces()
def __str__(self):
if self.patterned: return("A size " + str(self.size) + " patterned cube")
else: return("A size " + str(self.size) + " cube")
def set_faces(self):
self.up = [[self[0,z,x].up for x in range(self.size)] for z in range(self.size)]
self.left = [[self[y,z,0].left for z in range(self.size)] for y in
range(self.size)]
self.front = [[self[y,self.size-1,x].front for x in range(self.size)] for y in
range(self.size)]
self.down = [[self[self.size-1,z,x].down for x in range(self.size-1,-1,-1)] for z in
range(self.size-1,-1,-1)]
self.right = [[self[y,z,self.size-1].right for z in range(self.size-1,-1,-1)] for y in
range(self.size-1,-1,-1)]
self.back = [[self[y,0,x].back for x in range(self.size-1,-1,-1)] for y in
range(self.size-1,-1,-1)]
def move_side(self, side, amount=1, depth=1):
for i in range(amount%4):
copy = deepcopy(self)
for j in range(self.size):
for k in range(self.size):
if side == "front":
self[k,self.size-depth,j] = copy[self.size-1-j,self.size-depth,k].rotate(z=1)
elif side == "back":
self[k,depth-1,j] = copy[j,depth-1,self.size-1-k].rotate(z=-1)
elif side == "right":
self[k,j,self.size-depth] = copy[j,self.size-1-k,self.size-depth].rotate(x=1)
elif side == "left":
self[k,j,depth-1] = copy[self.size-1-j,k,depth-1].rotate(x=-1)
elif side == "up":
self[depth-1,k,j] = copy[depth-1,j,self.size-1-k].rotate(y=-1)
elif side == "down":
self[self.size-depth,k,j] = copy[self.size-depth,self.size-1-j,k].rotate(y=1)
self.set_faces()
self.moves += 1
</code></pre>
<p>Possible way of using this is:</p>
<pre><code>c = Cube("4") #Creates a 4x4x4 Rubiks Cube
cp = Cube("3p") #Creates a 3x3x3 patterned Rubiks Cube (each cubelet face is a vector rather than scalar)
c.move_side("front", depth=2) #moves the face one layer back from the front move 90° clockwise
print(c.left) #print the left side as a list (mainly for other python code to use)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T13:38:24.993",
"Id": "403105",
"Score": "1",
"body": "Could you maybe add an example of how you'd use it? It would help to make a better review to understand every parameters, for example."
}
] | [
{
"body": "<h2>Cube class</h2>\n\n<p>I <em>feel</em> like your <code>form</code> parameter would be something taken out of a command line argument. With possible values like <code>32</code>, <code>32p</code>, <code>3</code>, etc. </p>\n\n<p>But if I'm using your code, I don't know what's the use of the <code>form</code> parameter, it's actually very confusing to see that its a <code>string</code> parameter. You should probably have two parameters, <code>patterned</code> and <code>size</code>. This would be much more intuitive.</p>\n\n<p>OOP wise, I don't think the <code>save</code> and <code>load</code> methods should be part of your <code>Cube</code> class. <strong>Especially</strong> the <code>load</code> one. How do I use it? Should I initialize a \"dummy\" cube to then call <code>load</code> on it? It doesn't make much sense. If I were you, I'd get another object that would take care of the saving and loading of a cube.</p>\n\n<h2>Cublet class</h2>\n\n<p>There's a lot of very similar code in the <code>rotate</code> method, I think some of it (especially the <code>if</code> and everything below) could be extracted in another method that you could reuse in your 3 loops.</p>\n\n<h2>Coding style</h2>\n\n<p>This is pretty confusing. I had to read about three times to make sure the assignations on the first line were matching (front with front, etc) and that the changes on the second line made sense.</p>\n\n<pre><code>front, left, back, right = self.front, self.left, self.back, self.right\nself.front, self.left, self.back, self.right = right, front, left, back\n</code></pre>\n\n<p>I'll offer two options which in my opinion might be better : </p>\n\n<ol>\n<li>Have it all on one line <code>self.front, self.left, self.back, self.right = self.right, self.front, self.left, self.back</code></li>\n<li><p>Split the assignments on multiple lines. This is probably the best option as it makes it clear what happens. : </p>\n\n<pre><code>self.front = self.right\nself.left = self.front\n...\n</code></pre></li>\n</ol>\n\n<p>Considering the second option, I'm aware you might tell yourself \"My code is already long enough as it is, no need to add so many other lines\" but I really think it would help on readability, which would be a big plus.</p>\n\n<h3>If one-liners</h3>\n\n<p>Once again I guess you did this to \"save space\" but really the readability is hindered by the fact that in some places you have <code>if</code> statement on one line vs more than one.</p>\n\n<pre><code>if cubelet.front == None: parts.extend((\"None\", \"None\"))\n</code></pre>\n\n<p>vs. </p>\n\n<pre><code>if type(self.left) == tuple:\n self.left = self.left[0], sides[(sides.index(self.left[1])+1)%4]\n</code></pre>\n\n<p>Truth is I believe all your <code>if</code> statement should be on at least two lines (like the second option). It's simply easier to read (this might just be an opinion)</p>\n\n<h3>Spacing</h3>\n\n<p>Your code is very cluttered and blank lines don't cost a thing :) At least put them between your methods, it will help tremendously to read and to quickly find your way around the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:49:56.713",
"Id": "403125",
"Score": "0",
"body": "Thanks for the comments, the reason form is like this is because in the future I plan to add the ability to put something like '2x2x4p' into form for a tower cube so I decided it would be best for it to be flexible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:30:01.143",
"Id": "403139",
"Score": "0",
"body": "You could use a `tuple` kind of like `numpy` uses for its arrays initialization. It's something like `np.array(dim=(2,2,4))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:34:30.600",
"Id": "403141",
"Score": "0",
"body": "However, I also might in the future add tetrahedron puzzles which would be created like t3p or something so I am trying to create my options open"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T13:59:56.830",
"Id": "208689",
"ParentId": "208676",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T09:46:32.780",
"Id": "208676",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"python-3.x"
],
"Title": "Python Rubiks Cube Object"
} | 208676 |
<p><strong>I was asked to define a function that takes a list as an argument and returns the index of the smallest value.</strong></p>
<p><strong><hr>This is what I came up with:</strong></p>
<pre><code>def index_finder(lst):
"""
parameters: lst of type list
returns: index of the lst's smallest value
"""
for i in range(len(lst)):
if lst[i]==index(lst):
print(i)
return None
def index(lst):
"""
parameters: lst of type list
returns: the smallest value of that lst
"""
if len(lst)==1:
return lst[0]
if lst[0]<lst[1]:
lst.append(lst[0])
return index(lst[1:])
index_finder([3,2,4,0,1,5,-6,2,5])
</code></pre>
<p><strong>This will output the following:</strong></p>
<pre><code>6
</code></pre>
<p>As you can see I had to use separate functions in order to get the result. Is there <em>a concise, yet simple</em> way to do this?</p>
<p>By concise I mean short and by simple I mean using only simple functions.</p>
| [] | [
{
"body": "<p>Yes, there is a concise way to do this, even without a recursive function and that is to use the built-in <a href=\"https://docs.python.org/3/library/functions.html#min\" rel=\"nofollow noreferrer\"><code>min</code></a> function with a custom <code>key</code>:</p>\n\n<pre><code>from operator import itemgetter\n\ndef min_index(x):\n return min(enumerate(x), key=itemgetter(1))[0]\n</code></pre>\n\n<p>The <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> function adds the indices and the <a href=\"https://docs.python.org/3/library/operator.html#operator.itemgetter\" rel=\"nofollow noreferrer\"><code>operator.itemgetter</code></a> ensures that <code>min</code> cares only about the actual value (here it is equivalent to <code>lambda t: t[1]</code>). The <code>[0]</code> at the end gets the index from the minimum tuple.</p>\n\n<p>The usage is almost the same as your function, it returns the value so you have to print it yourself. This is actually good practice because this way you can use the output of the function for other things afterwards.</p>\n\n<pre><code>if __name__ == \"__main__\":\n print(min_index([3,2,4,0,1,5,-6,2,5]))\n # 6\n</code></pre>\n\n<hr>\n\n<p>If you want to use <code>numpy</code> (i.e you are going to do some heavy calculations with these objects), there is a function which does exactly what you want already implemented, <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html\" rel=\"nofollow noreferrer\"><code>numpy.argmin</code></a>:</p>\n\n<pre><code>import numpy as np\n\nnp.argmin([3,2,4,0,1,5,-6,2,5])\n# 6\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:26:56.350",
"Id": "208678",
"ParentId": "208677",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T10:10:59.027",
"Id": "208677",
"Score": "2",
"Tags": [
"python",
"recursion"
],
"Title": "Search a list recursively and return the index of the smallest value"
} | 208677 |
<p>I have written my own expendable list in Java.
<a href="https://codereview.stackexchange.com/questions/208620/my-own-expendable-list">LinkedList in Java</a>
Now I tried to write that thing in Python. Did I have used the elements of the python language properly?</p>
<pre><code>class Node:
def __init__(self):
self.object = None
self.nextNode = None
def hasObject(self):
return self.object != None
def hasNextNode(self):
return nextNode != None
class LinkedList:
def __init__(self):
self.startNode = Node()
def getEmptyNode(self):
currentNode = self.startNode
while currentNode.hasObject():
currentNode = currentNode.nextNode
return currentNode
def insert(self, obj):
emptyNode = self.getEmptyNode()
emptyNode.object = obj
emptyNode.nextNode = Node()
def getNumberOfElements(self):
currentNode = self.startNode
numberOfElements = 0
while currentNode.hasObject():
numberOfElements += 1
currentNode = currentNode.nextNode
return numberOfElements
def getNodeByIndex(self, index):
currentNode = self.startNode
for i in range(index):
currentNode = currentNode.nextNode
return currentNode
def get(self, index):
node = self.getNodeByIndex(index)
return node.object
def delete(self, index):
if index == 0:
startNode = self.getNodeByIndex(1)
return
# if index equals last available index
if index == (self.getNumberOfElements) - 1:
nodeBefore = self.getNodeByIndex(index - 1)
nodeBefore.nextNode = None
nodeBefore = self.getNodeByIndex(index - 1)
nodeBehind = self.getNodeByIndex(index + 1)
nodeBefore.nextNode = nodeBehind
linkedList = LinkedList()
linkedList.insert("Hello")
linkedList.insert("How are you")
linkedList.insert(3)
linkedList.insert("I feel fine")
print(linkedList.getNumberOfElements())
print(linkedList.get(2))
for i in range(linkedList.getNumberOfElements()):
print(linkedList.get(i))
</code></pre>
| [] | [
{
"body": "<p>Just some random things I noticed while looking over your code:</p>\n\n<hr>\n\n<p>The way you're handling additions is a little odd to me. You seem to be continually maintaining an \"empty node\" at the end of the list, then when you add, you iterate to that node, replace its content then give it a new, empty node. Why not just have <code>nextNode</code> remain <code>None</code>, then iterate while <code>currentNode.hasNextNode()</code> to find the last node? Something like:</p>\n\n<pre><code>def getLastNode(self):\n currentNode = self.startNode\n while currentNode.hasNextNode():\n currentNode = currentNode.nextNode\n return currentNode\n\ndef insert(self, obj):\n newNode = Node()\n newNode.object = obj\n\n lastNode = self.getLastNode()\n lastNode.nextNode = newNode\n</code></pre>\n\n<p>From my experience, this is a far more typical set up. This also has the <em>miniscule</em> benefit of using <em>slightly</em> less memory, since you're no longer keeping one more node than needed in memory at all times. This also does away with the need for the <code>hasObject</code> method.</p>\n\n<hr>\n\n<p>The definition of <code>getNumberOfElements</code> is completely impractical for most applications. You can assume for most, if not all data structures (besides maybe lazy lists), that a <code>size</code> method will run in O(1) time. Iterating the entire list every time you want to get the size has the opportunity to bring your application to a crawl; especially if the user of the class isn't aware that <code>getNumberOfElements</code> is O(n).</p>\n\n<p>Just give your class a <code>n_nodes</code> field, and increment/decrement it in the appropriate methods:</p>\n\n<pre><code>def insert(self, obj):\n newNode = Node()\n newNode.object = obj\n\n lastNode = self.getLastNode()\n lastNode.nextNode = newNode\n\n self.n_nodes += 1 # Here\n</code></pre>\n\n<p>Then change <code>getNumberOfElements</code> to something like:</p>\n\n<pre><code>def size(self):\n return self.n_nodes\n</code></pre>\n\n<p>You can now get the size of the list nearly instantly instead of requiring a full iteration. The only drawback is you need to take care to properly manage <code>n_nodes</code> in all the methods that can change the size of the list.</p>\n\n<hr>\n\n<p>Python isn't my main language, but I'm pretty sure snake_case is idiomatic Python. Coming from Java, you're probably more used to camelCase, but adhering to conventions is important for allowing other people to read your code easier. One thing you need to adjust to when writing in multiple languages is remembering what conventions the language you're writing uses. Clojure, my main language, uses dash-case; but this isn't even valid in many languages (like Python). I've gotten yelled at many times on Stack Overflow when answering questions in languages I don't use often because I forgot to adjust my naming conventions, and end up using either unidiomatic, or outright illegal names.</p>\n\n<hr>\n\n<p>It would likely simplify your life if you gave the <code>Node</code> constructor the ability to directly set <code>nextNode</code> and <code>object</code> fields:</p>\n\n<pre><code>def __init__(self, newObject = None, newNextNode = None):\n self.object = newObject\n self.nextNode = newNextNode\n</code></pre>\n\n<p>That will save you a couple lines in the few places by just directly passing the object:</p>\n\n<pre><code>def insert(self, obj):\n newNode = Node(obj)\n\n # No longer needed!\n # newNode.object = obj\n\n lastNode = self.getLastNode()\n lastNode.nextNode = newNode\n\n self.n_nodes += 1\n</code></pre>\n\n<hr>\n\n<p>The \"start node\" of a linked list is more typically referred to as the \"root\".</p>\n\n<hr>\n\n<pre><code>def delete(self, index):\n if index == 0:\n startNode = self.getNodeByIndex(1)\n...\n</code></pre>\n\n<p>Could probably be written more cleanly as simply</p>\n\n<pre><code>def delete(self, index):\n if index == 0:\n startNode = startNode.nextNode\n...\n</code></pre>\n\n<hr>\n\n<p>For efficiency, you might also want to maintain a <code>lastNode</code> field. Right now, to get to the last node, you're needing to iterate the entire list, which is quite expensive. If you just keep a reference to the last node when you do an insertion, you can just use that reference instead of needing to iterate.</p>\n\n<hr>\n\n<pre><code>if index == (self.getNumberOfElements) - 1:\n</code></pre>\n\n<p>Is broken. You need to call the method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:30:42.043",
"Id": "208722",
"ParentId": "208690",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208722",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:10:16.037",
"Id": "208690",
"Score": "1",
"Tags": [
"python",
"linked-list"
],
"Title": "My own expandable list in Python"
} | 208690 |
<p>I have made a C++ class to manipulate 3D vectors in Cartesian coordinates.</p>
<p>However, the performance of my class is much slower (about 2.5x) than simply using something like <code>double p [3]</code> and then running <code>for</code> loops for additions, subtractions, etc.</p>
<p>My specific concerns are:</p>
<ul>
<li>Is there something fundamentally wrong that I am doing, that is causing this slowdown?</li>
<li>Is there a way to achieve what I am trying, but without as much of a slowdown?</li>
<li>Is this just a fundamental limitation of classes and operator overloading that I have to live with, in return for the convenience?</li>
</ul>
<p>Here is the class:</p>
<pre><code>#ifndef COORD_H
#define COORD_H
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <complex>
#include <vector>
#include <map>
#include <stdlib.h>
#include "math.h"
// Useful reference: http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
/*! \brief Class to store and manipulate points or position vectors in 3D, in Cartesian coordinates.*/
class vect3D
{
public:
double x = 0.0, y = 0.0, z = 0.0;
double tol = 1.0e-15;
// Constructors
vect3D() {};
vect3D(std::initializer_list<double> RHS) { x = *RHS.begin(); y = *(RHS.begin()+1); z = *(RHS.begin()+2); };
vect3D(std::vector<double> &RHS) { x = RHS[0]; y = RHS[1]; z = RHS[2]; };
vect3D(double *RHS) { x = RHS[0]; y = RHS[1]; z = RHS[2]; };
// Assignment
vect3D& operator=(const vect3D &RHS) { x = RHS.x; y = RHS.y; z = RHS.z; return *this; };
// Addition and subtraction
vect3D& operator+=(const vect3D &RHS) { x += RHS.x; y += RHS.y; z += RHS.z; return *this; };
vect3D& operator-=(const vect3D &RHS) { x -= RHS.x; y -= RHS.y; z -= RHS.z; return *this; };
vect3D& operator+=(const double &RHS) { x += RHS; y += RHS; z += RHS; return *this; };
vect3D& operator-=(const double &RHS) { x -= RHS; y -= RHS; z -= RHS; return *this; };
vect3D operator+(const vect3D &RHS) { return vect3D(*this) += RHS; };
vect3D operator-(const vect3D &RHS) { return vect3D(*this) -= RHS; };
vect3D operator+(const double &RHS) { return vect3D(*this) += RHS; };
vect3D operator-(const double &RHS) { return vect3D(*this) -= RHS; };
// Scalar product and division
vect3D& operator*=(const double &RHS) { x *= RHS; y *= RHS; z *= RHS; return *this; };
vect3D& operator/=(const double &RHS) { x /= RHS; y /= RHS; z /= RHS; return *this; };
vect3D operator*(const double &RHS) { return vect3D(*this) *= RHS; };
vect3D operator/(const double &RHS) { return vect3D(*this) /= RHS; };
friend vect3D operator*(double c, vect3D &vec) { return vec*c; };
friend vect3D operator/(double c, vect3D &vec) { return vec/c; };
// Comparisons
bool operator==(const vect3D &RHS) { return ((x - RHS.x < x*tol) && (y - RHS.y < y*tol) && (z - RHS.z < z*tol)); };
bool operator!=(const vect3D &RHS) { return !(*this == RHS); };
bool operator>=(const vect3D &RHS) { return ((x >= RHS.x) && (y >= RHS.y) && (z >= RHS.z)); };
bool operator<=(const vect3D &RHS) { return ((x <= RHS.x) && (y <= RHS.y) && (z <= RHS.z)); };
bool operator>(const vect3D &RHS) { return !(*this <= RHS); };
bool operator<(const vect3D &RHS) { return !(*this >= RHS); };
// Euclidean norm
double norm2() { return std::sqrt(std::pow(x, 2) + std::pow(y, 2) + std::pow(z, 2)); };
friend double norm2(vect3D const &a) { return std::sqrt(std::pow(a.x, 2) + std::pow(a.y, 2) + std::pow(a.z, 2)); };
// Dot product
friend double dot(vect3D const &a, vect3D const &b) { return a.x*b.x + a.y*b.y + a.z*b.z; };
// Cross product
friend vect3D cross(vect3D const &a, vect3D const &b) { return {(a.y*b.z - a.z*b.y), (a.z*b.x - a.x*b.z), (a.x*b.y - a.y*b.x)}; };
// Print to stream
friend std::ostream& operator<<(std::ostream &stream, vect3D const &p) { return stream << "(" << p.x << ", " << p.y << ", " << p.z << ")" << std::flush; };
// Function to explicitly return coordinates as an array of doubles, if needed
void DoubleArray(double *v) { v[0] = x; v[1] = y; v[2] = z; return; };
// To access coordinates using square bracket notation, for convenience
std::vector<double *> p = std::vector<double *> {&x, &y, &z};
double operator [] (int ii) const { return *(p[ii]); };
};
#endif
</code></pre>
<p>Thanks!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:33:36.893",
"Id": "403114",
"Score": "2",
"body": "Hey, welcome to Code Review! If your code works but you want it to be better (in terms of speed or maintainability), you have come to the right place. [so] is a better place if you are looking for why something does not work or how to do something in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:03:39.497",
"Id": "403169",
"Score": "1",
"body": "Have you thought about inverting the access? E.g. store `std::array<double, 3>` and provide x(), y(), z() functions returning a reference to their corresponding elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T18:32:26.087",
"Id": "403357",
"Score": "0",
"body": "@Incomputable Now that you mention it, I refer to the x, y, z members almost as frequently through [ ] as through .x, .y etc., so I'll try out what you suggest and assess the impact on performance."
}
] | [
{
"body": "<p>This is a general review, not a specific performance review.</p>\n\n<hr>\n\n<p>Many of the operators ought to be const-qualified. Relational operators are of questionable value, given there isn't a natural ordering for coordinate vectors.</p>\n\n<hr>\n\n<p>The constructors are fragile because they don't enforce the requirement that the caller provide at least three values. The <code>initializer_list</code> constructor is pointless really - just provide an ordinary 3-argument constructor that will be properly checked at the call site, and prefer initialization to assignment (this last may be a performance issue):</p>\n\n<pre><code>vect3D(double x, double y, double z)\n : x{x}, y{y}, z{z}\n{}\n</code></pre>\n\n<hr>\n\n<p>I don't think there's any need for the assignment operator, unless you really don't want to copy <code>tol</code> as the compiler-generated one does - in which case, I'd recommend an explanatory comment, because it just looks like you forgot that member.</p>\n\n<hr>\n\n<p>You seem to missing an include of <code><cmath></code> for <code>std::pow()</code> and <code>std::sqrt()</code>. However, you don't want to be using those functions, given that <code><cmath></code> provides a (much better behaved and possibly more efficient) <code>std::hypot()</code> function:</p>\n\n<pre><code>// Euclidean norm\ndouble norm2() const { return std::hypot(x, y, z); };\nfriend double norm2(vect3D const &a) { return a.norm2(); };\n</code></pre>\n\n<p>(Note: in C++14 and earlier, <code>std::hypot()</code> only took two arguments, so you had to write <code>std::hypot(std::hypot(x, y), z)</code> or similar.)</p>\n\n<hr>\n\n<p>The extra <code>std::vector</code> of pointers that each <code>vect3D</code> carries around with it is likely to be a performance drag. If you really want that help for indexing, consider a <code>static constexpr</code> array of member-pointers instead (which won't take space in the object, nor need to allocate when it's copied):</p>\n\n<pre><code> // To access coordinates using square bracket notation, for convenience\n double operator[](int i) const { return this->*p[i]; };\n double& operator[](int i) { return this->*p[i]; };\n\nprivate:\n static constexpr double vect3D::*p[] = { &vect3D::x, &vect3D::y, &vect3D::z };\n</code></pre>\n\n<hr>\n\n<p>Don't stream <code>std::flush</code> when writing output. If callers want output to be flushed, they will do this themselves; if not, they certainly don't want it to be imposed upon them.</p>\n\n<hr>\n\n<p>Header rationalisation - in conjunction with the other improvements I recommend, we only need</p>\n\n<pre><code>#include <cmath>\n#include <ostream>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:48:17.877",
"Id": "403123",
"Score": "0",
"body": "These are extremely helpful; thank you. In case it is helpful to others, I want to note that implementing your replacement of std::vector with the `static constexpr` improved performance by ~2x, so now the class is almost on par with using raw pointers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:55:08.480",
"Id": "403127",
"Score": "1",
"body": "I'm not sure whether you ever give different coordinates different `tol` values; if not, then making that member a static const would reduce the object size by 25%, probably with a corresponding speed boost."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:26:40.257",
"Id": "403175",
"Score": "1",
"body": "What do you think about this: a free standing template function `component`, which has component’s name as first argument and vector as second, input to function argument? That would allow crazy extensibility. Here is an example `component<vec3d::x>(line3d)`. One could also write delegate like `x_component(line3d)` to make it less verbose."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:19:53.113",
"Id": "208699",
"ParentId": "208691",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>Is this just a fundamental limitation of classes and operator overloading that I have to live with, in return for the convenience?</p>\n</blockquote>\n\n<p>Not at all! C++ is all about abstractions with zero overhead. The design behind C++ is that it shouldn't leave any place for another language closer to the machine, while providing powerful abstractions to leverage native speed.</p>\n\n<p>Further down a semi-complete review of your code (@TobySpeight already covered much ground).</p>\n\n<pre><code>#ifndef COORD_H\n#define COORD_H\n\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n</code></pre>\n\n<p>That seems a bit heavy on I/O headers</p>\n\n<pre><code>#include <cstring>\n#include <complex>\n#include <vector>\n#include <map>\n#include <stdlib.h>\n</code></pre>\n\n<p>There's a bit of clean up to do here</p>\n\n<pre><code>//#include \"math.h\"\n\n\n// Useful reference: http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html\n\n\n/*! \\brief Class to store and manipulate points or position vectors in 3D, in Cartesian coordinates.*/\nclass vect3D\n</code></pre>\n\n<p>Why not a <code>struct</code>? Since your data is public anyway </p>\n\n<pre><code>{\npublic:\n\n double x = 0.0, y = 0.0, z = 0.0;\n double tol = 1.0e-15;\n</code></pre>\n\n<p>What you're looking for is standardized here <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon</a></p>\n\n<pre><code> // Constructors\n vect3D() {};\n</code></pre>\n\n<p>Why would you define such a useless constructor? Just default it: <code>vect3D() = default</code></p>\n\n<p>By the way, there's a useless superfluous semi-colon at the end of all your function definitions.</p>\n\n<pre><code> vect3D(std::initializer_list<double> RHS) { x = *RHS.begin(); y = *(RHS.begin()+1); z = *(RHS.begin()+2); };\n</code></pre>\n\n<p>If you conceive your vect3D as an aggregate (no user provided constructor, no virtual functions, and some other restrictions) you can use aggregate initialization directly (<code>vect3D v{1., 2., 3.};</code>) without having to define a brace-list constructor</p>\n\n<pre><code> vect3D(std::vector<double> &RHS) { x = RHS[0]; y = RHS[1]; z = RHS[2]; };\n</code></pre>\n\n<p>So what if I provide a <code>vector</code> with one or two elements? Or even with six elements: that's clearly a mistake that won't be called out by the compiler.</p>\n\n<pre><code> vect3D(double *RHS) { x = RHS[0]; y = RHS[1]; z = RHS[2]; };\n</code></pre>\n\n<p>Same here. The advice is to provide an interface that is hard to misuse </p>\n\n<p>By the way, did you wonder why you got a lot of warnings about a deprecated implicit copy constructor? do you see why? Think of what will happen when the default copy constructor will copy your vector member by member, your vector of pointers included</p>\n\n<pre><code> // Assignment\n vect3D& operator=(const vect3D &RHS) { x = RHS.x; y = RHS.y; z = RHS.z; return *this; };\n\n // Addition and subtraction\n vect3D& operator+=(const vect3D &RHS) { x += RHS.x; y += RHS.y; z += RHS.z; return *this; };\n vect3D& operator-=(const vect3D &RHS) { x -= RHS.x; y -= RHS.y; z -= RHS.z; return *this; };\n\n vect3D& operator+=(const double &RHS) { x += RHS; y += RHS; z += RHS; return *this; };\n vect3D& operator-=(const double &RHS) { x -= RHS; y -= RHS; z -= RHS; return *this; };\n\n vect3D operator+(const vect3D &RHS) { return vect3D(*this) += RHS; };\n vect3D operator-(const vect3D &RHS) { return vect3D(*this) -= RHS; };\n\n vect3D operator+(const double &RHS) { return vect3D(*this) += RHS; };\n vect3D operator-(const double &RHS) { return vect3D(*this) -= RHS; };\n\n\n // Scalar product and division\n vect3D& operator*=(const double &RHS) { x *= RHS; y *= RHS; z *= RHS; return *this; };\n vect3D& operator/=(const double &RHS) { x /= RHS; y /= RHS; z /= RHS; return *this; };\n\n vect3D operator*(const double &RHS) { return vect3D(*this) *= RHS; };\n vect3D operator/(const double &RHS) { return vect3D(*this) /= RHS; };\n\n friend vect3D operator*(double c, vect3D &vec) { return vec*c; };\n friend vect3D operator/(double c, vect3D &vec) { return vec/c; };\n\n\n // Comparisons\n bool operator==(const vect3D &RHS) { return ((x - RHS.x < x*tol) && (y - RHS.y < y*tol) && (z - RHS.z < z*tol)); };\n bool operator!=(const vect3D &RHS) { return !(*this == RHS); };\n\n bool operator>=(const vect3D &RHS) { return ((x >= RHS.x) && (y >= RHS.y) && (z >= RHS.z)); };\n bool operator<=(const vect3D &RHS) { return ((x <= RHS.x) && (y <= RHS.y) && (z <= RHS.z)); };\n bool operator>(const vect3D &RHS) { return !(*this <= RHS); };\n bool operator<(const vect3D &RHS) { return !(*this >= RHS); };\n\n\n // Euclidean norm\n double norm2() { return std::sqrt(std::pow(x, 2) + std::pow(y, 2) + std::pow(z, 2)); };\n\n friend double norm2(vect3D const &a) { return std::sqrt(std::pow(a.x, 2) + std::pow(a.y, 2) + std::pow(a.z, 2)); };\n</code></pre>\n\n<p>You don't need all those friends since x, y and z are public. That only clutters your class interface.</p>\n\n<pre><code> // Dot product\n friend double dot(vect3D const &a, vect3D const &b) { return a.x*b.x + a.y*b.y + a.z*b.z; };\n\n // Cross product\n friend vect3D cross(vect3D const &a, vect3D const &b) { return {(a.y*b.z - a.z*b.y), (a.z*b.x - a.x*b.z), (a.x*b.y - a.y*b.x)}; };\n\n\n // Print to stream\n friend std::ostream& operator<<(std::ostream &stream, vect3D const &p) { return stream << \"(\" << p.x << \", \" << p.y << \", \" << p.z << \")\" << std::flush; };\n\n\n // Function to explicitly return coordinates as an array of doubles, if needed\n void DoubleArray(double *v) { v[0] = x; v[1] = y; v[2] = z; return; };\n\n // To access coordinates using square bracket notation, for convenience\n std::vector<double *> p = std::vector<double *> {&x, &y, &z};\n</code></pre>\n\n<p>I'm amazed that someone with a sane mind (at least I hope so) would have such an extravagant idea. I'm not sure that square bracket notation is\na convenience here -it might as well persuade the user that <code>vect3D</code> behaves like an array or a pointer- but even if you want to provide it, creating\na vector of pointers is crazy, without even mentioning what will happen when a user naively calls for the third dimension with <code>vec[3]</code> (and they will).\nIf you really want the bracket operator, implement it with a switch: <code>case 0: return x; ...; default: throw std::out_of_bonds();</code></p>\n\n<pre><code> double operator [] (int ii) const { return *(p[ii]); };\n\n};\n\n#endif\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:01:50.523",
"Id": "208715",
"ParentId": "208691",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "208699",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:14:19.250",
"Id": "208691",
"Score": "3",
"Tags": [
"c++",
"performance",
"coordinate-system",
"overloading"
],
"Title": "Class to store and manipulate Cartesian coordinates and vectors"
} | 208691 |
<p>I have the following input:</p>
<pre><code>case class Client(key: String, time: Option[Instant], bool: Boolean)
val l = List (
Client("87658763", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), true)
)
</code></pre>
<p>For context, this data is the result of concatenated Lists from two API calls - one to get all Clients, and one to specifically get all Clients where bool is true.</p>
<p>I want the info to be distinct on the key and time. Also, where there are multiple Clients with the same key and time, if at least one of the Clients contains bool = true, I want to return a single client with bool = true otherwise return a single client with bool = false ... ie I want the output of above to be:</p>
<pre><code>List (
Client(87658763,Some(1970-01-01T00:00:00Z),false),
Client(87658769,Some(1970-01-01T00:00:00Z),true)
)
</code></pre>
<p>What I have so far is the following code:</p>
<pre><code>import java.time.Instant
case class Client(key: String, time: Option[Instant], bool: Boolean)
val l = List (
Client("87658763", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), true)
)
l.groupBy(client => (client.key, client.time)).map {
case (_, v) if v.exists(_.bool) => v.head.copy(bool = true)
case (_, v) => v.head
}.toList
</code></pre>
<p>I am curious about efficiency and code style - this is the only way to solve this problem that I could come up with, but I wonder if there is a more efficient way to do this (I don't know much about what the Scala compiler does under the hood with things like groupBy and copy), or a more elegant way to do this.</p>
<p>I've not had to make elements distinct by more than one field before and this call will be made hundreds of times in my application (I am writing this as part of a Play! app) so need it to be as efficient as possible.</p>
| [] | [
{
"body": "<p><strong>Your code is fine</strong></p>\n\n<p>There's nothing wrong with the way you've implemented it. It's readable, and will have reasonable O(n) performance.</p>\n\n<p><strong>Alternative implementation</strong></p>\n\n<p>You've mentioned l is created by concatenation of two lists. As far as I understood one of the lists contains only clients with <code>bool=false</code> and one only clients with <code>bool=true</code>. Some clients will appear on both lists. Example:</p>\n\n<pre><code>val l1 = List(\n Client(\"87658763\", Some(Instant.EPOCH), false),\n Client(\"87658769\", Some(Instant.EPOCH), false),\n)\n\nval l2 = List(\n Client(\"87658769\", Some(Instant.EPOCH), true)\n)\n</code></pre>\n\n<p>If this is correct, then an alternative way to implement you function is:</p>\n\n<pre><code>val m1 = l1.map(c => (c.key, c.time) -> c).toMap\nval m2 = l2.map(c => (c.key, c.time) -> c).toMap\n\n(m1 ++ m2).values.toList\n</code></pre>\n\n<p>Or for better (most likely) performance you can use the <code>breakOut</code> trick which will do the mapping and List to Map transformation in single step.</p>\n\n<pre><code>val m1: Map[(String, Option[Instant]), Client] = l1.map(c => (c.key, c.time) -> c)(scala.collection.breakOut)\nval m2: Map[(String, Option[Instant]), Client] = l2.map(c => (c.key, c.time) -> c)(scala.collection.breakOut)\n\n(m1 ++ m2).values.toList\n</code></pre>\n\n<p>Whether this solution is more elegant than your's is subjective. I leave it up to you to decide which one you like more. Whether it's faster should be determined by measurement under production-like load.</p>\n\n<p><strong>First measure & profile</strong></p>\n\n<p>First of all, if you're doing these operations once per the pair of mentioned API calls, then it's likely that the performance will get dominated by the API calls, not this code. If you're doing it more often, then you could remember the results. Before optimising the code I recommend you to measure the performance and determine where is the bottleneck.</p>\n\n<p><strong>Performance factors</strong></p>\n\n<p>If you come to a conclusion that performance of this code is indeed critical, then most likely the problem will be one of these:</p>\n\n<ul>\n<li>allocation of garbage - <code>groupBy</code>, <code>map</code>, <code>toList</code> each allocate a new data structure. No, the Scala compiler does not optimise this in any way. While allocation is a cheap process, all the garbage will have to be collected, and Garbage Collection can be expensive in some scenarios.</li>\n<li>passes over the data set - <code>groupBy</code>, <code>map</code>, <code>toList</code> each is an O(n) operation iterating over the data. Additional these operations may slow down if the data won't easily fit in CPUs cache.</li>\n</ul>\n\n<p>Which one will be dominant, will depend on Heap and GC configuration, the size of <code>l</code>, other workloads in the JVM and other factors. Both can be improved by doing as small number of passes over the data as possible.</p>\n\n<p><strong>Less passes over the data</strong></p>\n\n<p>These are the hints I can give on reducing the number of passes over the data, in this, and other similar situations:</p>\n\n<ul>\n<li>Check If you can avoid some collection conversions. Maybe the <code>Iterable[Client]</code> returned by <code>my</code> is ok, and you don't have to convert it <code>toList</code>. </li>\n<li>Use breakOut. </li>\n<li>Try doing more in single step. <code>foldLeft</code> is a powerful operation which lets you combine many operations on a collection into one (at the expense of readability). </li>\n<li>Use mutable structures under the hood. Keep immutables in the API.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:10:34.580",
"Id": "209993",
"ParentId": "208696",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209993",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:41:46.950",
"Id": "208696",
"Score": "0",
"Tags": [
"scala"
],
"Title": "Efficiency of grouping a List of case classes by more than one field"
} | 208696 |
<p>In my application, the user may or may not want to ignore some directories. I can do that, but it seems like I am repeating myself. Does anyone have an idea to refactor that?</p>
<pre><code>from os import walk, path
exclude = ['dir1/foo']
for root, dirs, files in walk('.', topdown=True):
if exclude != None:
dirs[:] = [d for d in dirs if d not in exclude]
for name in files:
for excluded in exclude:
if excluded not in root:
print path.join(root, name)
else:
for name in files:
print path.join(root, name)
</code></pre>
<p><code>exclude</code> is <code>None</code> when there are no dirs to exclude. I thought of setting it to an empty list, but then, this loop <code>for excluded in exclude:</code> won't execute at all. My ambition was to avoid such a big <code>if</code>/<code>else</code>. Any ideas?</p>
<hr>
<p>Example:</p>
<pre><code>gsamaras@pc:~/mydir$ ls */*
dir1/bar:
test.txt
dir1/foo:
test.txt
dir2/bar:
test.txt
dir2/foo:
test.txt
</code></pre>
<p>I am getting:</p>
<pre><code>./dir2/foo/test.txt
./dir2/bar/test.txt
</code></pre>
<p>./dir1/bar/test.txt</p>
<p>If I want, I can do an <code>exclude = ['foo']</code>, and then get:</p>
<pre><code>./dir2/bar/test.txt
./dir1/bar/test.txt
</code></pre>
<p>meaning that I ignored all directories named "foo".</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T01:25:28.907",
"Id": "403225",
"Score": "0",
"body": "Why are you using generic names (`foo` and `bar`) for this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T08:42:16.797",
"Id": "403260",
"Score": "0",
"body": "Maybe I should have used subdir @Jamal, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T01:59:21.217",
"Id": "403380",
"Score": "0",
"body": "Just make sure to use the original names that were used with the project."
}
] | [
{
"body": "<p>You are already modifiyin the list of directories, so that should be enough. But your <code>exclude</code> includes the full path, so your check in the list comprehension does not actually filter the excluded directories, you only do that in the <code>for</code> loop below when already having descended into those excluded directories (wasting time).</p>\n\n<p>So, this should work:</p>\n\n<pre><code>from os import walk, path\n\nexclude = {'./dir1/foo'}\n\nfor root, dirs, files in walk('.'):\n if exclude is not None:\n dirs[:] = [d for d in dirs if path.join(root, d) not in exclude]\n for name in files:\n print path.join(root, name)\n</code></pre>\n\n<p>Note that <code>exclude</code> needs to contain paths starting with the starting point of <code>os.walk</code>, so in this case <code>.</code>.</p>\n\n<p>I also made <code>exclude</code> a set (<span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> <code>in</code> lookup), used the fact that <code>topdown=True</code> by default and <a href=\"https://stackoverflow.com/questions/3965104/not-none-test-in-python\">used <code>is not</code> instead of <code>!=</code> for comparison to <code>None</code></a>.</p>\n\n<hr>\n\n<p>If you want to instead exclude folder names (regardless of their position in the directory tree), you can do that as well like this:</p>\n\n<pre><code>from os import walk, path\n\nexclude = {'foo'}\n\nfor root, dirs, files in walk('.'):\n if exclude is not None:\n dirs[:] = [d for d in dirs if d not in exclude]\n for name in files:\n print path.join(root, name)\n</code></pre>\n\n<p>What is not possible with either of these two approaches is to include <code>foo</code> only in sub-directories of <code>dir1</code>, like in your example. However, I think this is more consistent behaviour, so you should choose one of the two, IMO.</p>\n\n<hr>\n\n<p>As a last point, you should probably switch to Python 3 sooner rather than later if at all possible, because <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">support for Python 2 will end in a bit more than a year</a> (at the time of writing this).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T15:06:03.790",
"Id": "403118",
"Score": "0",
"body": "Very pythonic answer. However, check my example (edited), where I have two directories named `foo`. With my ugly code, the user can ignore both `foo's, or specify further. Also, note that in your code, the user has to specify the absolute path, while in mine's, just the name in the generic approach. Still, a +1, but you might want to play around, if you have some time. As for the last point, not possible now. :/ Or maybe, I should switch to your approach, because the user might have forgotten that (s)he has two foo folders........... ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:00:17.213",
"Id": "403128",
"Score": "0",
"body": "@gsamaras: Yeah, you have to decide if you only want to exclude folders by their full path (relative to the top) or all folders by that name. In the latter case, you can just do `[d for d in dirs if d not in exclude]` and should still not need your two cases, because it will never descend into excluded folders (so there is no need to continue checking if the path contains an excluded folder)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T16:10:37.473",
"Id": "403132",
"Score": "0",
"body": "Right! What I really liked with my code, is that I could say `dir2`, instead of `./dir2` with your approach. However, your code might be safer for the user, and also much cleaner. It's a trade-off that I will have to think, when I have time.. Thanks for your time, and since I talked about time, I want you to enjoy my [God of Time 10 yrs Stackoverflow](https://meta.stackexchange.com/questions/318910/time-for-some-more-swag/319020#319020) post, as a thank you gesture, if you have some time, of course! :) This comment selfdestruct at some time tomorrow..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:56:50.287",
"Id": "208698",
"ParentId": "208697",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208698",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T14:43:30.073",
"Id": "208697",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"file-system"
],
"Title": "List directories, subdirectories and files, while ignoring some dirs"
} | 208697 |
<p>My VBA macro displays an animation based on a row-by-row time step simulation in the worksheet. The user enters the desired inputs and the worksheet calculates the evolution of the simulation in a 1000 row table. The user then runs the macro to display the results in an animation. The macro loops through the rows in the simulation. For each row, the macro extracts four values and applies them as positions to four shapes in the worksheet.</p>
<p>The macro runs fast when I open the workbook and run the macro without doing else first. If I do an edit to the worksheet that causes it to recalculate the simulation, then the macro runs about 1/3 as fast.</p>
<p>The Task Manager shows some interesting things about the memory usage. When the macro is run without an edit, the usage jumps 66,000 K every run. When the macro is run after an edit, the usage jumps only 2,000 K every run. I've checked the values of ScreenUpdating, EnableEvents, Calculation and DisplayPageBreaks, and they don't change if the worksheet is edited.</p>
<p>Is there something I can do to prevent this other than saving and reopening the workbook after I make an edit?</p>
<pre><code>Sub playfast()
Dim arrRangeValues() As Variant
Dim j As Long
Dim vpos As Double
Dim hpos As Double
Dim calcflag As Boolean
Dim chartflag As Boolean
Dim eventflag As Boolean
If iVal = 0 Then iVal = 1
If iVal = 1000 Then iVal = 1
If iVal = 1001 Then iVal = 1
isCancelled = False
calcflag = ActiveSheet.Cells(8, 12).Value
chartflag = ActiveSheet.Cells(9, 12).Value
eventflag = ActiveSheet.Cells(10, 12).Value
ActiveSheet.Cells(7, 15).Value = "PLAYING"
vpos = ActiveSheet.Cells(6, 12).Value
hpos = ActiveSheet.Cells(7, 12).Value
arrRangeValues = Range("a41:q1041").Value
For j = iVal To 1001 Step ActiveSheet.Cells(24, 12).Value
iVal = j
show hpos, vpos, vpos - arrRangeValues(j, 4) * 2, vpos - arrRangeValues(j, 17) * 2, vpos - arrRangeValues(j, 5) * 2
ActiveSheet.Cells(17, 10).Value = arrRangeValues(j, 1) 'Write time into worksheet
If eventflag Then DoEvents 'Yield to operating system.
If calcflag Then ActiveSheet.Calculate 'May be necessary for animation to move after worksheet is changed
If chartflag Then
ActiveSheet.ChartObjects("uprchart").Activate
ActiveSheet.ChartObjects("uprchart").Chart.Refresh
ActiveSheet.ChartObjects("lwrchart").Activate
ActiveSheet.ChartObjects("lwrchart").Chart.Refresh
End If
If isCancelled Then GoTo EarlyExit
Next j
EarlyExit:
isCancelled = False
ActiveSheet.Cells(7, 15).Value = "STOPPED"
End Sub`
Sub show(leftedge As Double, groundtop As Double, bodytop As Double, wheelstop As Double, passengerstop As Double)
ActiveSheet.Shapes("ground").Left = leftedge
ActiveSheet.Shapes("ground").Top = groundtop
ActiveSheet.Shapes("body").Left = leftedge
ActiveSheet.Shapes("body").Top = bodytop
ActiveSheet.Shapes("wheels").Left = leftedge
ActiveSheet.Shapes("wheels").Top = wheelstop
ActiveSheet.Shapes("passengers").Left = leftedge
ActiveSheet.Shapes("passengers").Top = passengerstop
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T13:18:09.313",
"Id": "403290",
"Score": "0",
"body": "A few questions: Where is `iVal` coming from? What are the type of calculations performed in the worksheet (through the formulas), especially those that are necessary each time your code loops? You're bringing your 1000 row range into an array prior to the loop, but if the worksheet recalculates values in that area, the updated values are not re-copied into the array (so the calculations don't matter). Do you have sample data that we can use to replicate the behavior you're seeing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T22:30:49.527",
"Id": "403368",
"Score": "0",
"body": "iVal is used to save the current place in the loop if the user wants to stop the animation. The loop stops via EarlyExit if the user sets isCancelled to True while the loop is running. When the user runs playfast() again, the loop resumes where it stopped."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T23:44:32.743",
"Id": "403372",
"Score": "0",
"body": "The range actually does get re-copied if the user runs playfast() again, and the loop starts with j set to the value stored in iVal. Ordinarily the user will reset iVal via another macro called reset() before playing the animation again if he edits the worksheet. I can provide sample data if that would be helpful."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:17:43.597",
"Id": "208711",
"Score": "2",
"Tags": [
"performance",
"beginner",
"vba",
"animation",
"simulation"
],
"Title": "Excel VBA animation runs slowly after editing worksheet"
} | 208711 |
<p>I am an extreme novice in Java and thus trying to practise some online exercises. One of them involved creating a basic student record system.
This is what I've come up with but I think a lot of things are quite redundant in my code so any reviews are greatly appreciated.</p>
<h3>Student.java</h3>
<pre><code>class Student {
int rollno;
String name;
Student(int r, String n) {
this.rollno = r;
this.name = n;
}
}
</code></pre>
<h3>StudentDB.java</h3>
<pre><code>import java.util.Scanner;
class Main {
public static void getStudents(Student ...students) {
int i = 1;
for (Student x : students) {
System.out.println("Student Number : " + i);
System.out.println("Name -> "+ x.name);
System.out.println("Roll Number -> " + x.rollno + "\n");
i++;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number of students? ");
int num = sc.nextInt();
String[] name = new String[num];
int[] rollno = new int[num];
System.out.println("Enter those " + num + " students one by one");
for (int i = 0; i < num; i++) {
System.out.println("Enter details for student no. " + (i + 1));
System.out.print("Enter Name: ");
name[i] = sc.next();
System.out.print("Enter Roll Number: ");
rollno[i] = sc.nextInt();
System.out.println("\n");
}
Student[] students = new Student[num];
for (int i = 0; i < num; ++i) {
students[i] = new Student(rollno[i], name[i]);
}
getStudents(students);
}
}
</code></pre>
<p>I would really love it if someone could tell me as to how can I pass those <strong>name</strong> and <strong>rollno</strong> arrays directly to the vararg function <strong>getStudents</strong> without creating that <strong>Student[]</strong> object array.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:46:12.277",
"Id": "403179",
"Score": "0",
"body": "Why don't you want to create a `Student[]` ? If you don't, you just have a seemingly unrelated collection of names and roll numbers. Not to mention no use for the `Student` class"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:55:38.900",
"Id": "403180",
"Score": "0",
"body": "@Katie.Sun I just thought it seemed a bit redundant making Student[ ] when my function takes varargs as parameter."
}
] | [
{
"body": "<h2>Main:</h2>\n\n<pre><code>import java.util.Scanner;\n\nclass Main {\n\n public static void main(String[] args) {\n\n Scanner scanner = new Scanner(System.in);\n Student[] students = StudentRoll.gatherStudents(scanner);\n StudentRoll.printStudents(students);\n\n }\n}\n</code></pre>\n\n<h2>Student:</h2>\n\n<pre><code>class Student {\n\n private int rollNumber;\n private String name;\n\n Student(int rollNumber, String name) {\n this.rollNumber = rollNumber;\n this.name = name;\n }\n\n int getRollNumber() {\n return rollNumber;\n }\n void setRollNumber(int rollNumber) {\n this.rollNumber = rollNumber;\n }\n\n String getName() {\n return name;\n }\n void setName(String name) {\n this.name = name;\n }\n}\n</code></pre>\n\n<h2>StudentRoll:</h2>\n\n<pre><code>class StudentRoll {\n\n static Student[] gatherStudents(Scanner scanner){\n\n System.out.print(\"Number of students? \");\n int numberOfStudents = scanner.nextInt();\n\n System.out.println(\"Enter those \" + numberOfStudents + \" students one by one\");\n Student[] students = new Student[numberOfStudents];\n\n for (int index = 0; index < numberOfStudents; index++) {\n System.out.println(\"Enter details for the next student no. \");\n System.out.print(\"Enter Name: \");\n String studentName = scanner.next();\n System.out.print(\"Enter Roll Number: \");\n int rollNumber = scanner.nextInt();\n students[index] = new Student(rollNumber, studentName);\n System.out.println(\"\\n\");\n }\n return students;\n }\n\n static void printStudents(Student[] students){\n int i = 1;\n for (Student x : students) {\n System.out.println(\"Student Number : \" + i);\n System.out.println(\"Name -> \" + x.getName());\n System.out.println(\"Roll Number -> \" + x.getRollNumber() + \"\\n\");\n i++;\n }\n }\n}\n</code></pre>\n\n<p>I can't post many notes right now, but will as soon as I can. Think the main thing here is that your code isn't very object-oriented, but Java is an object-oriented language. It's also generally a good idea to name variables something other than <code>num</code>, so that when you're working on a method that has 5 different <code>int</code> variables, you aren't tempted to call them <code>num1</code> , <code>num2</code>, etc., but what they actually represent. I'm also not a big fan of using a <code>for-in</code> when you reference an index, but it didn't seem like the worst thing in the world so I left it in there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:11:22.480",
"Id": "403185",
"Score": "0",
"body": "This is really great! Thank you! I will try to amend my habit of giving variables arbitrary names and will try to be more object-oriented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:19:04.227",
"Id": "403186",
"Score": "0",
"body": "For some reason, I'm getting a NullPointerException on line no. 16 of StudentRoll class which I am not able to correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T22:15:52.627",
"Id": "403193",
"Score": "0",
"body": "Hmmm. I am not at computer right now so I can't look at it. Is it when you are inputting a value? Sorry, I didn't actually test this before I posted it and I don't write console apps very often."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T22:24:00.200",
"Id": "403195",
"Score": "0",
"body": "Actually, try adding a default constructor in your Student class. Just Student(){}. I wonder if the Student[] isn't actually being initialized with Students because there is no default constructor available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T22:55:54.477",
"Id": "403199",
"Score": "0",
"body": "The default constructor didn't help. And yes, It's when I input the name and press enter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T23:23:31.237",
"Id": "403208",
"Score": "0",
"body": "The code `new Student[]` really only creates an array of `null` values. So before assigning to `students[i]`, you'd have to say `students[i] = new Student()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:00:54.813",
"Id": "403210",
"Score": "0",
"body": "Ah yes, I was starting to think somewhere along the lines of what you just said. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:59:30.653",
"Id": "403215",
"Score": "0",
"body": "@RolandIllig Thanks. Sorry, apparently I don't work with arrays often enough either lol. Will update my post accordingly"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:05:30.193",
"Id": "208718",
"ParentId": "208712",
"Score": "4"
}
},
{
"body": "<p>Your code is efficient, and luckily your problem domain is quite limited, which is also good to get early feedback and then improve the program structure before you go on to write complex systems with millions of lines of code.</p>\n\n<h2>The Student class</h2>\n\n<p>Let's start with the very small details, the <code>Student</code> class. You wrote:</p>\n\n<pre><code>class Student {\n\n int rollno;\n String name;\n\n Student(int r, String n) {\n this.rollno = r;\n this.name = n;\n }\n}\n</code></pre>\n\n<p>For the two fields, you chose to list the rollno first and the name second. This is good since rollno is the <em>identifying</em> field of the student, which should always come first. The describing fields should then follow, as you do in your code.</p>\n\n<p>It looks strange that the fields have these pretty names but the parameters of the constructor are abbreviated for no reason. The fields, as well as their names, are considered an <em>implementation detail</em> and should not be visible outside the Student class. Therefore, their names are limited in scope.</p>\n\n<p>The parameters of the constructor, on the other hand, are part of the \"API\" (application programming interface) of the Student class. These names are important so they should be chosen carefully. It is common to name the constructor parameters exactly the same as the fields. So that should be <code>Student(int rollno, String name)</code>.</p>\n\n<p>Later, when your code becomes more than a toy program, you will need to add <em>getter and setter</em> methods for the fields of the Student class. This is a convention in the Java world. It's a lot of code to type, but people got used to that. In fact, the IDE (integrated development environment) will generate this code for your. It is called boilerplate code because it has more text than would be ideally necessary.</p>\n\n<p>Later, your Student class should look like this:</p>\n\n<pre><code>public class Student { // The \"public\" is new here.\n\n private final int rollno; // The \"private\" and \"final\" is new here.\n private String name; // The \"private\" is new here.\n\n public Student(int rollno, String name) { // The \"public\" is new here\n this.rollno = rollno;\n this.name = name;\n }\n\n public int getRollno() {\n return rollno;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}\n</code></pre>\n\n<p>I made the rollno field <code>final</code> because once chosen, it will never change. The name of a student, on the other hand, may change. It doesn't occur very often, but it can. Therefore there is a combination of the getName/setName methods.</p>\n\n<p>Above I mentioned the boilerplate code since this code is much longer than your current code but doesn't really contain more information. It could be written much shorter, if only the Java programming language would support it. Maybe it will in some future, but currently it doesn't. There is a similar programming language called Kotlin, in which the equivalent code looks like this:</p>\n\n<pre><code>data class Student(\n val rollno: Int,\n var name: String)\n</code></pre>\n\n<p>That's it. There is no repetition anymore, and this short code can be automatically translated to the above bloated Java code because the Java code doesn't contain any more <em>real information</em> than this very short code.</p>\n\n<h2>The StudentRoll class (Katie's version)</h2>\n\n<p>(Note: I accidentally reviewed not the code from the question, but the code from Katie's answer. Since I don't want this work to be wasted, I'm leaving it as is. See below for the review of the original class.)</p>\n\n<pre><code>class StudentRoll {\n\n static Student[] gatherStudents(Scanner scanner){\n</code></pre>\n\n<p>I noticed that you wrote <code>){</code> without any space in-between. That's unusual but is nothing you should worry about. Since the rest of your code is perfectly formatted (the indentation from the left is consistent, as well as the spacing between the tokens that make up the code), I assume that you are either very disciplined or are using an IDE that formats the code for you. Either of these is good. The IDE should do this boring task of layouting the code so that you can concentrate on what the code <em>means</em> instead of what it looks like.</p>\n\n<pre><code> System.out.print(\"Number of students? \");\n int numberOfStudents = scanner.nextInt();\n</code></pre>\n\n<p>This pattern of asking for the number of items first and then reading the items one by one is very typical of textbooks and introductory programs. It is impractical for the user of your program, though. Does the user really know in advance how many students there will be? Probably not. Therefore the program should rather ask the user to \"enter the student rollno, leave it empty to finish the input\".</p>\n\n<pre><code> System.out.println(\"Enter those \" + numberOfStudents + \" students one by one\");\n Student[] students = new Student[numberOfStudents];\n</code></pre>\n\n<p>Introductory programming courses typically use arrays since technically they are simpler to understand than Java classes and <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html\" rel=\"nofollow noreferrer\">the whole collections framework</a>. Arrays are harder to use though since you need to know the number of elements when you create the array.</p>\n\n<p>By using a <code>List<Student></code> (pronounced: list of student) instead of a <code>Student[]</code>, you can simply say <code>students.add(student)</code> and don't have to worry whether the list is large enough. This is much simpler.</p>\n\n<pre><code> for (Student student : students) {\n System.out.println(\"Enter details for the next student no. \");\n System.out.print(\"Enter Name: \");\n student.setName(scanner.next());\n System.out.print(\"Enter Roll Number: \");\n student.setRollNumber(scanner.nextInt());\n System.out.println(\"\\n\");\n</code></pre>\n\n<p>In the Student class, you wrote the rollno first, for whatever reason. I thought it was because the rollno is the <em>identifying</em> field. But now it gets weird: you let the user enter the fields of the student in a different order than that in the Student class. This is a bad smell. It is not necessarily wrong, but it draws attention. Why do you do this. This should be explained in a comment for the human readers of your code.</p>\n\n<p>The prompt to \"Enter details for the next student no. \" has an unnecessary space at the end. That is not visible and it has no meaning, therefore you should remove it. Before that space is \"no.\", which <em>is</em> visible and it is wrong. The user is going to enter the details for the next <em>student</em>, not for its <em>number</em>. Maybe it was <code>\"no. \" + i</code> in a previous version of the code, where <code>i</code> was a sequence number, and that made sense. The current version of the code doesn't make sense.</p>\n\n<p>To get the user's input, you use <code>scanner.next()</code>. This is almost always wrong. Currently, when the user is asked to enter a name and just presses Enter, the user expects that something has been entered. Yet, the program still waits for \"something\", since calling <code>scanner.next()</code> means \"read from the input until the next <em>word</em>\".</p>\n\n<p>When the user enters a double name, only the first name will end up in <code>student.name</code>, the other name will still be in the input queue, waiting to be read in later. Therefore, instead of <code>scanner.next()</code>, use <code>scanner.nextLine()</code>.</p>\n\n<p>The same applies for the rollno. When the users just presses Enter here, the program continues to wait for a <em>word</em> to be entered, without giving any intermediate feedback. This makes a bad user experience since the user and the program have a different idea about what is happening right now. Therefore, instead of <code>scanner.nextInt()</code>, use <code>Integer.parseInt(scanner.nextLine())</code>.</p>\n\n<p>Error handling will be handled later, that would be too large a topic for now.</p>\n\n<p>For the benefit of readers of your code, you should add an empty line before the \"Enter roll number\" line. This will structure your code into paragraphs, just like in a good book. <a href=\"https://www.youtube.com/watch?v=cVaDY0ChvOQ\" rel=\"nofollow noreferrer\">This video</a> explains why this is a good thing.</p>\n\n<pre><code> }\n return students;\n }\n\n static void printStudents(Student[] students){\n int i = 1;\n for (Student x : students) {\n System.out.println(\"Student Number : \" + i);\n System.out.println(\"Name -> \" + x.getName());\n System.out.println(\"Roll Number -> \" + x.getRollNumber() + \"\\n\");\n i++;\n }\n }\n}\n</code></pre>\n\n<p>The printStudents method prints the students details, each separated by an empty line. This empty line is not visible when looking only at the beginnings of the code lines.</p>\n\n<p>Experienced programmers often only read the first word of each line to get a general idea of what the code does. In this example, it would be:</p>\n\n<ul>\n<li><code>for Student</code></li>\n<li><code>System.out.println</code></li>\n<li><code>System.out.println</code></li>\n<li><code>System.out.println</code></li>\n</ul>\n\n<p>From that, readers of your code will conclude that for each student, there are 3 lines printed. But this is not what the program does. It prints 4 lines. Therefore the code should look like this:</p>\n\n<pre><code> static void printStudents(Student[] students) {\n int i = 1;\n for (Student student : students) {\n System.out.println(\"Student Number : \" + i);\n System.out.println(\"Name -> \" + student.getName());\n System.out.println(\"Roll Number -> \" + student.getRollNumber());\n System.out.println();\n i++;\n }\n }\n</code></pre>\n\n<p>There you have it, four times <code>println</code>, four lines of output. Now the code has the same structure as the output it produces. No more surprises for the reader.</p>\n\n<p>By the way, there are subtle differences between <code>println()</code> and printing <code>\"\\n\"</code>, but only on Windows systems. When you write <code>\\n</code> in your code, the Windows Notepad editor will not show the linebreak that should be there. Granted, it's almost the only program that is living in the past, most other programs can handle these differences in line endings since about 20 years. And finally, since <a href=\"https://blogs.msdn.microsoft.com/commandline/2018/05/08/extended-eol-in-notepad/\" rel=\"nofollow noreferrer\">May 2018, Windows Notepad can do it, too</a>. Still, your code should not generate these inconsistent line endings. Therefore: don't write <code>\\n</code> in your code, prefer <code>println()</code> over it. At least until you know what exactly you are doing.</p>\n\n<h2>The Main class</h2>\n\n<p>You saved the code in the file <code>StudentDB.java</code>, yet your class is called <code>Main</code>. Unless you have a very good reason, the class name should correspond to the file name. This makes for less surprises.</p>\n\n<p>You wrote:</p>\n\n<pre><code>import java.util.Scanner;\n\nclass Main {\n\n public static void getStudents(Student ...students) {\n int i = 1;\n for (Student x : students) {\n System.out.println(\"Student Number : \" + i);\n System.out.println(\"Name -> \"+ x.name);\n System.out.println(\"Roll Number -> \" + x.rollno + \"\\n\");\n i++;\n }\n }\n</code></pre>\n\n<p>This method should be called <code>printStudents</code> since the word <code>get</code> is practically reserved for methods that retrieve a little detail information (like <code>Student.getName</code>) and have no side-effects. Printing something <em>is</em> a side-effect.</p>\n\n<p>The printStudents method prints the students details, each separated by an empty line. This empty line is not visible when looking only at the beginnings of the code lines.</p>\n\n<p>Experienced programmers often only read the first word of each line to get a general idea of what the code does. In this example, it would be:</p>\n\n<ul>\n<li><code>for Student</code></li>\n<li><code>System.out.println</code></li>\n<li><code>System.out.println</code></li>\n<li><code>System.out.println</code></li>\n</ul>\n\n<p>From that, readers of your code will conclude that for each student, there are 3 lines printed. But this is not what the program does. It prints 4 lines. Therefore there should be another line <code>System.out.println();</code> after the other 3 lines.</p>\n\n<p>There are subtle differences between <code>println()</code> and printing <code>\"\\n\"</code>, but only on Windows systems. When you write <code>\\n</code> in your code, the Windows Notepad editor will not show the linebreak that should be there. Granted, it's almost the only program that is living in the past, most other programs can handle these differences in line endings since about 20 years. And finally, since <a href=\"https://blogs.msdn.microsoft.com/commandline/2018/05/08/extended-eol-in-notepad/\" rel=\"nofollow noreferrer\">May 2018, Windows Notepad can do it, too</a>. Still, your code should not generate these inconsistent line endings. Therefore: don't write <code>\\n</code> in your code, prefer <code>println()</code> over it. At least until you know what exactly you are doing.</p>\n\n<pre><code> public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n System.out.print(\"Number of students? \");\n int num = sc.nextInt();\n</code></pre>\n\n<p>This pattern of asking for the number of items first and then reading the items one by one is very typical of textbooks and introductory programs. It is impractical for the user of your program, though. Does the user really know in advance how many students there will be? Probably not. Therefore the program should rather ask the user to \"enter the student rollno, leave it empty to finish the input\".</p>\n\n<pre><code> String[] name = new String[num];\n int[] rollno = new int[num];\n</code></pre>\n\n<p>Having these two arrays is often the wrong approach. If you would explain the program (not the code) to a colleague, you would not say \"the user enters a list of names and a list of roll numbers\". You would say instead \"the user enters a list of student details\". The code should match this description as closely as possible.</p>\n\n<p>Therefore your code should construct a proper <code>Student</code> object as soon as it has all the necessary details (in this case rollno and name).</p>\n\n<p>Introductory programming courses typically use arrays since technically they are simpler to understand than Java classes and <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html\" rel=\"nofollow noreferrer\">the whole collections framework</a>. Arrays are harder to use though since you need to know the number of elements when you create the array.</p>\n\n<p>By using a <code>List<Student></code> (pronounced: list of student) instead of a <code>Student[]</code>, you can simply say <code>students.add(student)</code> and don't have to worry whether the list is large enough. This is much simpler.</p>\n\n<pre><code> System.out.println(\"Enter those \" + num + \" students one by one\");\n\n for (int i = 0; i < num; i++) {\n System.out.println(\"Enter details for student no. \" + (i + 1));\n</code></pre>\n\n<p>Very good. This pattern of using the range [0,n) internally and [1,n] for communicating with humans is typical for all kinds of programs. It's important to get used to this pattern and apply it consistently.</p>\n\n<p>There are other programming languages (Pascal, Lua, some versions of Basic) where arrays typically start at index 1. See <a href=\"https://en.wikipedia.org/wiki/Zero-based_numbering\" rel=\"nofollow noreferrer\">Zero based numbering</a> for a lengthy discussion about this topic.</p>\n\n<pre><code> System.out.print(\"Enter Name: \");\n name[i] = sc.next();\n System.out.print(\"Enter Roll Number: \");\n rollno[i] = sc.nextInt();\n</code></pre>\n\n<p>In the Student class, you wrote the rollno first, for whatever reason. I thought it was because the rollno is the <em>identifying</em> field. But now it gets weird: you let the user enter the fields of the student in a different order than that in the Student class. This is a bad smell. It is not necessarily wrong, but it draws attention. Why do you do this. This should be explained in a comment for the human readers of your code.</p>\n\n<p>To get the user's input, you use <code>scanner.next()</code>. This is almost always wrong. Currently, when the user is asked to enter a name and just presses Enter, the user expects that something has been entered. Yet, the program still waits for \"something\", since calling <code>scanner.next()</code> means \"read from the input until the next <em>word</em>\".</p>\n\n<p>When the user enters a double name, only the first name will end up in <code>student.name</code>, the other name will still be in the input queue, waiting to be read in later. Therefore, instead of <code>scanner.next()</code>, use <code>scanner.nextLine()</code>.</p>\n\n<p>The same applies for the rollno. When the users just presses Enter here, the program continues to wait for a <em>word</em> to be entered, without giving any intermediate feedback. This makes a bad user experience since the user and the program have a different idea about what is happening right now. Therefore, instead of <code>scanner.nextInt()</code>, use <code>Integer.parseInt(scanner.nextLine())</code>.</p>\n\n<p>Error handling will be handled later, that would be too large a topic for now.</p>\n\n<p>For the benefit of readers of your code, you should add an empty line before the \"Enter roll number\" line. This will structure your code into paragraphs, just like in a good book. <a href=\"https://www.youtube.com/watch?v=cVaDY0ChvOQ\" rel=\"nofollow noreferrer\">This video</a> explains why this is a good thing.</p>\n\n<pre><code> System.out.println(\"\\n\");\n }\n\n Student[] students = new Student[num];\n\n for (int i = 0; i < num; ++i) {\n students[i] = new Student(rollno[i], name[i]);\n }\n\n getStudents(students);\n }\n}\n</code></pre>\n\n<h2>My version of the Main class</h2>\n\n<pre><code>class Main {\n\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n Student[] students = readStudents(sc);\n printStudents(students);\n }\n</code></pre>\n\n<p>I have put the main method at the top of the file because it serves as a table of contents. It should be this short to let the reader quickly decide: Is this the code I'm looking for? What does it do when viewed from a high level perspective?</p>\n\n<pre><code> private static Student[] readStudents(Scanner scanner) {\n System.out.print(\"Number of students? \");\n int num = Integer.parseInt(scanner.nextLine());\n\n System.out.println(\"Enter those \" + num + \" students one by one\");\n\n Student[] students = new Student[num];\n for (int i = 0; i < num; i++) {\n System.out.println(\"Enter details for student no. \" + (i + 1));\n students[i] = readStudent(scanner);\n }\n\n return students;\n }\n</code></pre>\n\n<p>As I said, <code>scanner.nextLine</code> is preferable to <code>scanner.next</code>.</p>\n\n<p>There are no separate arrays of names and rollnos anymore since that was not the ideal design for this code. This code deals with students, not with names and rollnos. The code should always serve as an explanation of the core concepts to the human reader.</p>\n\n<p>The main work is left to another method that reads a single student. Splitting up the work into several small parts makes each part understandable. For that, it's important to choose good names for each method. You should spend at least a third of the time thinking about <a href=\"https://martinfowler.com/bliki/TwoHardThings.html\" rel=\"nofollow noreferrer\">how to name things</a>.</p>\n\n<pre><code> static Student readStudent(Scanner scanner) {\n System.out.print(\"Enter Roll Number: \");\n int rollno = Integer.parseInt(scanner.nextLine());\n\n System.out.print(\"Enter Name: \");\n String name = scanner.nextLine();\n\n System.out.println();\n\n return new Student(rollno, name);\n }\n</code></pre>\n\n<p>I placed rollno first because it is the identifying field. Like in the method above, I only use <code>scanner.nextLine</code> and then process this line further.</p>\n\n<p>This method reads the individual fields and then constructs a proper Student object. From then on, the code doesn't deal with names or rollnos anymore, and that's exactly how it should be.</p>\n\n<pre><code> public static void printStudents(Student... students) {\n int i = 1;\n for (Student x : students) {\n System.out.println(\"Student Number : \" + i);\n System.out.println(\"Name -> \" + x.name);\n System.out.println(\"Roll Number -> \" + x.rollno);\n System.out.println();\n i++;\n }\n }\n}\n</code></pre>\n\n<p>There are 4 lines of code corresponding to 4 lines of output. No surprise here, as it should.</p>\n\n<h2>Summary</h2>\n\n<p>Even though your program was quite short, there were a lot of topics to talk about, and many hidden assumptions and details. Knowing these from the beginning is impossible. But in the end, attention to all these small details is what differentiates between an ok program and a great program. It's worth taking time for that, the users of your program will (silently) thank you for it, or at least, they won't complain as much. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T23:07:34.933",
"Id": "403202",
"Score": "0",
"body": "I'm really thankful for such a detailed response! This was more than I could ask for! But I did not trick you. IMO, you looked at @Katie.Sun code instead of mine. I posted the exact same thing I wrote. And I use VSCode with a few Java extentions for formatting and stuff"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T23:11:11.863",
"Id": "403205",
"Score": "0",
"body": "Not to worry! It was amazing and thoughtful of you to write this! But could also maybe check my StudentDB class as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:07:05.080",
"Id": "403213",
"Score": "0",
"body": "I'm really obliged by such extensive help! I'll try to follow these guidelines and edit my code accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:14:20.910",
"Id": "403214",
"Score": "0",
"body": "When you're done with editing your code or have added any new features, you are welcome to post it as a new question on this site, mentioning this question as the followed-up one."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T23:02:04.787",
"Id": "208728",
"ParentId": "208712",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "208728",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:23:30.057",
"Id": "208712",
"Score": "6",
"Tags": [
"java",
"beginner"
],
"Title": "A novice student record system"
} | 208712 |
<p>I did the following Excercise from <a href="https://automatetheboringstuff.com/chapter8/" rel="nofollow noreferrer">Automate the boring stuff with Python Chapter 8</a>:</p>
<blockquote>
<p>Create a Mad Libs program that reads in text files and lets the user
add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
appears in the text file. For example, a text file may look like this:</p>
<p>The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN
was unaffected by these events. The program would find these
occurrences and prompt the user to replace them.</p>
<p>Enter an adjective:<br> silly <br>
Enter a noun:<br> chandelier<br> Enter a verb:<br>
screamed<br> Enter a noun:<br> pickup truck<br><br> The following text file would then
be created:</p>
<p>The silly panda walked to the chandelier and then screamed. A nearby
pickup truck was unaffected by these events. The results should be
printed to the screen and saved to a new text file.</p>
</blockquote>
<p>I decided to read from all the text files which are in the same folder as the python script.
All new created files then end with _mad.txt</p>
<p>I would like to know if this is a good solution.</p>
<p>Are there any bad practices?
Is the code easy to understand?
What can be improved?
Are there better approaches for some parts int the code?</p>
<p>Please feel free to comment on anything you can find.</p>
<p>Heres the code:</p>
<p><b> mad_libs.py </b></p>
<pre><code>"""
Mad Libs
Scans for all .txt files in the working folder.
If a file is found the file is scanned for the keywords
-ADJECTIVE
-NOUN
-ADVERB
-VERB
Then the user is prompted to add a replacing word for the keyword.
A File with the name <source_name>_mad.txt is created in the folder.
In this file the keywords are replaced with the user input
"""
import os
import sys
import re
def filenames_in_script_folder():
"""
Returns all the filenames which are located in the same folder
as this running python script
"""
os.chdir(os.path.dirname(sys.argv[0]))
return os.listdir(os.getcwd())
def words_from_file(filename):
"""
Reads text file and returns all the words in it
"""
file = open(filename)
file_content = file.read()
file.close()
return file_content.split()
def ask_for_replace_word(keyword):
"""
Asks for a replace for mentioned keyword.
Checks if keyword is a vowel to follow english grammar correct
"""
vowel_regex = re.compile('^[aeiou]')
if vowel_regex.search(keyword):
return input("Enter an " + keyword.lower() + "\n")
return input("Enter a " + keyword.lower() + "\n")
def replace_word(word, keywords):
"""
Replaces provided word if it matches with one of the keywords.
Any non alphabetical signs are ignored in keyword compare
Otherwise returns provided word
"""
no_char_regex = re.compile('[^a-zA-Z]')
clean_word = no_char_regex.sub('', word)
for keyword in keywords:
if clean_word == keyword:
new_word = ask_for_replace_word(keyword)
return word.replace(keyword, new_word)
return word
def write_data_to_file(data, filename):
"""
Writes provided data to file.
If no file exists a new one is created first
"""
file = open(filename, 'w')
file.write(data)
file.close()
def mad_libs():
"""
Main function reads from file, replaces keywords
and writes to new file
"""
for filename in filenames_in_script_folder():
if filename.lower().endswith('.txt'):
new_words = []
replaced_a_word = False
for word in words_from_file(filename):
KEYWORDS = ('ADJECTIVE', 'NOUN', 'VERB', 'ADVERB')
replace = replace_word(word, KEYWORDS)
if replace != word:
replaced_a_word = True
new_words.append(replace)
if replaced_a_word:
new_data = ' '.join(new_words)
print(new_data)
write_data_to_file(new_data, filename[:-4] + "_mad.txt")
mad_libs()
</code></pre>
<p><strong>Bonus question:</strong> <br>
I run Pylint over the code and in the definition of the Keywords in the mad_libs function it gives me:</p>
<blockquote>
<p>Severity Code Description Project File Line Suppression State
Message Variable name "KEYWORDS" doesn't conform to snake_case naming
style</p>
</blockquote>
<p>Shouldnt this be ALLCAPS like i did because these words are supposed to be constants?</p>
<p>edit:
To see some results when run the programm you need to add a txt file like the example one in the same folder as the script.</p>
<p>I added a panda.txt with the text mentioned aboth and after aks for the words a panda_mad.txt is created in the folder.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:01:24.307",
"Id": "403183",
"Score": "2",
"body": "\"Shouldnt this be ALLCAPS like i did because these words are supposed to be constants?\" Not true. You re-assign the values in a `for` loop. Should you take out the assignment to the top level, outside of any loops or function calls, yes, then it would be a pseudo-const."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T08:55:54.710",
"Id": "403503",
"Score": "0",
"body": "so it would be better to declare it before the for loops."
}
] | [
{
"body": "<p>Thanks for sharing your code!</p>\n\n<p>Almost everything looks good to me.</p>\n\n<ul>\n<li>You have documentation for the module :)</li>\n<li>You have documentations for all your functions.</li>\n<li>Naming seems good to me.</li>\n<li>I did not see 'unpythonic' things in your code, maybe someone more experienced will have more to say on this?</li>\n<li>You use a linter</li>\n</ul>\n\n<p>The major things I would change is adding a <code>__main__</code> to your script.</p>\n\n<pre><code>if __name__ == \"__main__\":\n mad_libs()\n</code></pre>\n\n<p>When you run you script with <code>python mad_libs.py</code> it will behave the same but if you import your module in another script, it will not execute the function upon importing, which is I think the desired behavior.</p>\n\n<p>As for improvements:</p>\n\n<ul>\n<li>you could use type annotations to do static validation with <a href=\"http://www.mypy-lang.org/\" rel=\"nofollow noreferrer\">MyPy</a></li>\n<li>write some tests with unittest, pytest, nose ...</li>\n</ul>\n\n<p>Very nice code in my opinion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:06:50.620",
"Id": "208782",
"ParentId": "208713",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208782",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T20:35:20.617",
"Id": "208713",
"Score": "2",
"Tags": [
"python",
"beginner",
"strings",
"file"
],
"Title": "Mad Libs excercise"
} | 208713 |
<p>I am trying to compare any performance gain(s) from moving a current offset-based pagination endpoint to a cursor based one.</p>
<p>I have the following ruby code:</p>
<pre><code>@limit = 25
@max_pages = 200
def query
@q ||= MyDataBaseClass.where(status: "open").order(:id)
end
def offset_paginatiion
# count is currently an implementation for this appraoch
total = query.count
ctr = 0
page_size = 1
while page_size < @max_pages
query.limit(@limit).offset(ctr).load
ctr += @limit
page_size += 1
end
end
def keyset_pagination
current_page = query.limit(@limit)
page_size = 1
while true
break if page_size >= @max_pages
page_size += 1
last_id = current_page.last.id
current_page = query.where("id > ?", last_id).limit(@limit).load
end
end
require 'benchmark/ips'
Benchmark.ips do |x|
x.report("offset_pagination") { offset_paginatiion }
x.report("keyset_pagination") { keyset_pagination }
x.compare!
end
</code></pre>
<p>I've seeded the database with 1 million rows but you can see here I'm only trying to page up to 200 pages (or 5,000 results).</p>
<p>The two methods are returning the exact same data in the same order so they are functionally equivalent and after running the benchmark are performing nearly the same:</p>
<pre><code>│Calculating -------------------------------------
│ offset_pagination 0.009 (± 0.0%) i/s - 1.000 in 110.100327s
│ keyset_pagination 0.009 (± 0.0%) i/s - 1.000 in 112.732942s
│
│Comparison:
│ offset_pagination: 0.0 i/s
│ keyset_pagination: 0.0 i/s - 1.02x slower
</code></pre>
<p>I was under the impression performance (<a href="https://blog.novatec-gmbh.de/art-pagination-offset-vs-value-based-paging/" rel="nofollow noreferrer">from numerous</a> <a href="https://slack.engineering/evolving-api-pagination-at-slack-1c1f644f8e12" rel="nofollow noreferrer">articles</a>) was a benefit to moving to cursor pagination but have yet to been able to reproduce - what am I doing worng?</p>
| [] | [
{
"body": "<p>I'm not surprised at your results, bar a few minor details that any decent database will optimize away your implementations are the same. You are also basically just re-implementing the <code>find_each</code> method. </p>\n\n<p>Note, you might find a real difference if you used database cursors but that is a completely different thing.</p>\n\n<p>The real difference between the two is that cursor based pagination responds better when the underlying data changes. i.e. using offset based pagination you might have a record included twice or skipped if a record is inserted or deleted by another process.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:12:08.837",
"Id": "208752",
"ParentId": "208720",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T21:24:42.200",
"Id": "208720",
"Score": "2",
"Tags": [
"performance",
"ruby",
"api",
"postgresql",
"pagination"
],
"Title": "Offset vs Cursor Pagination"
} | 208720 |
<p>Given a string, for example "I hate AI", I need to find out if the sentence is in English, German or French. Unigram Model makes the prediction on the basis of each character frequency in a training text, while Bigram model makes prediction based on what character follows another character.</p>
<p>The following code has 2 methods 1. <strong>getBigramResult()</strong> 2. <strong>getUnigramResult()</strong>.</p>
<p>Both the methods take an <code>ArrayList<Character></code> as a parameter and return a <code>HashMap<Language,Double></code> with Key as the Language (French, English, German) and the probability associated with each language for the given character list as the value. The two methods are almost the same except for </p>
<ol>
<li><p>The for loop-> </p>
<pre><code>for(int j = 0; j < textCharList.size() - 1; j++)// getBigramResult()
for(int j=0; j<textCharList.size(); j++)// getUnigramResult()
</code></pre></li>
<li><p>The if condition-></p>
<pre><code>if(textCharList.get(i) !='+' && textCharList.get(i+1) !='+')// getBigramResult()
if(textCharList.get(i)!='+')// getUnigramResult()
</code></pre></li>
<li><p>The probability calculating function</p>
<pre><code>getConditionalProbability(textCharacter.get(i),textCharacter.get(i+1)) // getBigramResult()
getProbability(textCharacter.get(i))// getUnigramResult()
</code></pre></li>
<li><p>getBigramResult() works on a class call <code>BigramV2</code> and getUnigramResult() works on a class call <code>Unigram</code>. </p></li>
</ol>
<p>The code of the methods are as follows</p>
<pre><code>public static HashMap<Language, Double> getBigramResult(ArrayList<Character> textCharList) {
HashMap<Language, Double> totalProbabilities = new HashMap<Language, Double>();
for (int j = 0; j < textCharList.size() - 1; j++) {
if (textCharList.get(j) != '+' && textCharList.get(j + 1) != '+') {
FileHandler.writeSentences("BIGRAM :"+textCharList.get(j)+""+textCharList.get(j + 1),false);
for (int k = 0; k < biGramList.size(); k++) {
BiGramV2 temp = biGramList.get(k);
double conditionalProbability = Math.log10(temp.getConditionalProbabilty(textCharList.get(j),
textCharList.get(j + 1)));
updateTotalProbabilities(totalProbabilities,temp.getLanguage(),conditionalProbability);
FileHandler.writeSentences(temp.getLanguage().toString()+ ": p("+textCharList.get(j+1)+"|"+textCharList.get(j) +") ="+conditionalProbability+"==> log prob of sentence so far: " +totalProbabilities.get(temp.getLanguage()),false);
}
FileHandler.writeSentences("",false);
}
}
return totalProbabilities;
}
public static HashMap<Language, Double> getUnigramResult(ArrayList<Character> textCharList) {
HashMap<Language, Double> totalProbabilities = new HashMap<Language, Double>();
for (int j = 0; j < textCharList.size(); j++) {
if (textCharList.get(j) != '+') {
FileHandler.writeSentences("UNIGRAM :"+textCharList.get(j),false);
for (int k = 0; k < uniGramList.size(); k++) {
Unigram temp = uniGramList.get(k);
double conditionalProbability = Math.log10(temp.getProbabilty(textCharList.get(j)));
updateTotalProbabilities(totalProbabilities,temp.getLanguage(),conditionalProbability);
FileHandler.writeSentences(temp.getLanguage().toString()+ ": p("+textCharList.get(j)+") ="+conditionalProbability+"==> log prob of sentence so far: " +totalProbabilities.get(temp.getLanguage()),false);
}
FileHandler.writeSentences("",false);
}
}
return totalProbabilities;
}
</code></pre>
<p>Both the above methods <code>getBigramResult()</code> and <code>getUnigramResult()</code> are very similar, and I feel like it's not design efficient, but I am not able to refactor them because of the different outer <code>for</code>-loop, <code>if</code> block and different probability calculating methods. </p>
<p>My BiGramV2 class </p>
<pre><code>public class BiGramV2 {
private double delta;
private Language language;
public BiGramV2(double delta, Language language) {
this.delta = delta;
this.language = language;
}
public static List<Character> dictCharacters = Arrays.asList('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');
double[][] storage = new double[dictCharacters.size()][dictCharacters.size()];
private double[] countOfRows = new double[dictCharacters.size()];
public void fit(List<Character> characters) {
for (int i = 0; i < characters.size() - 1; i++) {
if (characters.get(i) != '+' && characters.get(i + 1) != '+')
{
int rowNo = dictCharacters.indexOf(characters.get(i));
int columnNo = dictCharacters.indexOf(characters.get(i + 1));
storage[rowNo][columnNo]++;
countOfRows[rowNo]++;
}
}
}
public Language getLanguage()
{
return language;// Enum of GERMAN, FRENCH and ENGLISH
}
public double getConditionalProbabilty(char first, char second)
{
int rowNo = dictCharacters.indexOf(first);
int columnNo = dictCharacters.indexOf(second);
double numerator=storage[rowNo][columnNo] + delta;
double denominator=countOfRows[rowNo]+ (delta*dictCharacters.size());
double conditionalProbability=numerator/denominator;
return conditionalProbability;
}}
</code></pre>
<p>And my Unigram Class is</p>
<pre><code>public class Unigram {
HashMap<Character,Integer> storage = new HashMap<Character,Integer>();
private double delta;
private Language language;
private int noOfCharacters=0;
public static List<Character> dictCharacters = Arrays.asList('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');
public Unigram(double delta, Language language) {
this.delta = delta;
this.language = language;
}
public Language getLanguage()
{
return language;
}
public void fit(List<Character> characters)
{
for (int i = 0; i < characters.size() ; i++) {
if (characters.get(i) != '+')
{
storage.put(characters.get(i), storage.getOrDefault(characters.get(i), 0)+1);
noOfCharacters++;
}
}
}
public double getProbabilty(char first)
{
double numerator=storage.get(first) + delta;
double denominator=noOfCharacters+ (delta*dictCharacters.size());
double probability=numerator/denominator;
return probability;
}
</code></pre>
<p>}</p>
<p>Any suggestion on my code would be appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T02:58:20.680",
"Id": "403239",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Do you think the edits I made are OK?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T03:08:07.733",
"Id": "403240",
"Score": "0",
"body": "Please update the title to express *what the code does* not your *concerns* for the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T03:14:56.927",
"Id": "403241",
"Score": "0",
"body": "@bruglesco Do you think its ok now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T03:26:48.453",
"Id": "403242",
"Score": "0",
"body": "The title is better. I think its also a good question but it's a bit of a grey area. I cant vote to reopen however so it will be up to the rest of the community. Good Luck!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T06:34:34.057",
"Id": "403251",
"Score": "0",
"body": "Please show your `BiGramV2` and `Unigram` classes as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T07:24:33.473",
"Id": "403255",
"Score": "0",
"body": "@200_success Edited. Thanks for the suggestion."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T22:09:55.070",
"Id": "208724",
"Score": "1",
"Tags": [
"java",
"natural-language-processing"
],
"Title": "Language-detection heuristic (English, French or German) based on Unigram and Bigram models"
} | 208724 |
<p>Before I can perform a more or less complex mappings, treatments in business objects and saving results in databases, I often need to validate contents from flat text files or excel files </p>
<p>All the validation libraries I know are designed to validate the content of strongly typed objects. The parsers or readers I tried are really good to load or write data but in case of an error in file, they are design for logging purpose and not for the end user. In addition, I'd like to use a library to do the validation only and be able to change the parser/reader if necessary. My goal is to validate the content of theses files and provide maximun feedbacks to the end users as if it was a form validation in web page.</p>
<p>Instead of wrting code that for sure no one will ever review, I decided to spend the day trying to create a library as an exercice and publish it on GitHub for differents reasons : try to write a fluent API, learn to use GitHub and git more accurately, create unit tests with xUnit and use a CI to automate test project (Travis, AppVeyor...), learn how to create a Nuget package and now try to collect some comments, ideas, remarks...and maybe use the library</p>
<p>For the time being, I end up with something like this :</p>
<p>I define a class with string properties that represent the columns of the files (I could also use a dynamic object) and validate with :</p>
<pre><code>public class Row
{
public string Key { get; set; }
public string DecimalValue { get; set; }
public string DateTimeValue { get; set; }
}
// ...
ClassValidator<Row> validator = ClassValidator<Row>
.Init()
.AddProperty(PropertyValidator<Row>.For(x => x.Key).IsNotNull().HasLength(5,10))
.AddProperty(PropertyValidator<Row>.For(x => x.DateTimeValue).IsNotNull().IsDateTime("yyyyMMdd"))
.AddProperty(PropertyValidator<Row>.For(x => x.DecimalValue).IsNotNull().IsDecimal())
.Validate(new Row()
{
Key = "thiskey",
DateTimeValue = "20181201",
DecimalValue = "123,45"
});
</code></pre>
<p>The <code>ClassValidator</code> contains N <code>PropertyValidator</code> for the N properties to validate. Each <code>PropertyValidator</code> can contains N <code>MethodValidator</code> to do the validation (IsNull, TryDecimal, TryRegex ...). Most of the methods are defined as <code>Func, Action</code> delegates executed only when the Validate method is called.</p>
<p>The <code>ClassValidator</code> constructor is private and the <code>Init</code> method can receive some options. The <code>Validate</code> method loop over the <code>List<PropertyValidator<TRow>></code> populated with the <code>AddProperty</code> method</p>
<pre><code>/// <summary>
/// Validation at class level.
/// </summary>
/// <typeparam name="TRow">The type of the model.</typeparam>
public class ClassValidator<TRow>
{
private readonly IClassValidatorOptions options;
private readonly List<PropertyValidator<TRow>> listValidator = new List<PropertyValidator<TRow>>();
/// <summary>
/// Initializes a new instance of the <see cref="ClassValidator{TRow}"/> class.
/// Private constructor.
/// </summary>
private ClassValidator()
{
}
private ClassValidator(IClassValidatorOptions options)
{
this.options = options;
}
/// <summary>
/// Gets validation errors.
/// </summary>
public List<ValidationError> ValidationErrors { get; private set; } = new List<ValidationError>();
/// <summary>
/// Gets a value indicating whether the validation is successful or not.
/// </summary>
public bool IsValid
{
get { return this.ValidationErrors.Count == 0; }
}
/// <summary>
/// Create an instance with no option.
/// </summary>
/// <returns>The created instance.</returns>
public static ClassValidator<TRow> Init()
{
return new ClassValidator<TRow>();
}
/// <summary>
/// Create an instance with option.
/// </summary>
/// <param name="options">options.</param>
/// <returns>The created instance.</returns>
public static ClassValidator<TRow> Init(IClassValidatorOptions options)
{
return new ClassValidator<TRow>(options);
}
/// <summary>
/// Add a property validator. <see cref="PropertyValidator{TRow}"/>.
/// </summary>
/// <param name="propValidator">Targeted property validator.</param>
/// <returns>current instance.</returns>
public ClassValidator<TRow> AddProperty(PropertyValidator<TRow> propValidator)
{
this.listValidator.Add(propValidator);
return this;
}
/// <summary>
/// Validation for one row.
/// </summary>
/// <param name="row">Row to validate.</param>
/// <returns>Current instance.</returns>
public ClassValidator<TRow> Validate(TRow row)
{
foreach (var validator in this.listValidator)
{
validator.Validate(row);
if (!validator.IsValid)
{
this.ValidationErrors.AddRange(validator.ValidationErrors);
}
}
return this;
}
/// <summary>
/// Validation for rows collection.
/// </summary>
/// <param name="rows">rows collection to validate.</param>
/// <returns>Current instance.</returns>
public ClassValidator<TRow> ValidateList(IEnumerable<TRow> rows)
{
int index = 0;
foreach (var row in rows)
{
foreach (var validator in this.listValidator)
{
if (this.options != null && this.options.ShowRowIndex)
{
validator.SetRowIndex(index);
}
validator.Validate(row);
if (!validator.IsValid)
{
this.ValidationErrors.AddRange(validator.ValidationErrors);
}
}
index++;
}
return this;
}
}
</code></pre>
<ul>
<li>If the generic type is set on the top class <code>ClassValidator <Row></code>.
Ideally, I would like to set the type once and reuse the same type
for <code>PropertyValidator</code>. In the sample, I have to define the type for
<code>ClassValidator</code> and for each<code>PropertyValidator</code>, <strong>which could lead
to some inconsistency.</strong></li>
</ul>
<p>The PropertyValidator exposes all the methods to do the validation of the property. Each validation method (eg : TryParseDecimal ) adds a MethodValidator in the Collection>.</p>
<pre><code>/// <summary>
/// Define a validator for a property in <see cref="PropertyValidator{TRow}"/> type.
/// </summary>
/// <typeparam name="TRow">Type for this validator.</typeparam>
public class PropertyValidator<TRow> : IPropertyValidatorAction<TRow>
{
private readonly Collection<MethodValidator<TRow>> methods = new Collection<MethodValidator<TRow>>();
private int? rowIndex;
private string fieldName;
private Func<TRow, string> getter;
private Expression getterExpression;
private dynamic extraObject;
private bool preserveErrorHeader = true;
private PropertyValidator()
{
}
/// <summary>
/// Gets the list of validation errors.
/// </summary>
public List<ValidationError> ValidationErrors { get; private set; } = new List<ValidationError>();
/// <summary>
/// Gets a value indicating whether the validation is successfull.
/// </summary>
public bool IsValid
{
get { return this.ValidationErrors.Count == 0; }
}
/// <summary>
/// Creates a property validator for the given property.
/// </summary>
/// <param name="getterExpression">The targeted property.</param>
/// <param name="overrideFieldName">To override field Name. By default uses the name of property.</param>
/// <returns>A property validator.</returns>
public static PropertyValidator<TRow> For(Expression<Func<TRow, string>> getterExpression, string overrideFieldName = null)
{
PropertyValidator<TRow> prop = new PropertyValidator<TRow>();
prop.getter = getterExpression.Compile();
prop.getterExpression = getterExpression;
prop.fieldName = overrideFieldName != null ? overrideFieldName : ExpressionUtiities.PropertyName(getterExpression);
return prop;
}
/// <summary>
/// Creates a property validator for a dynamic property.
/// </summary>
/// <param name="getter">The targeted dynamic property.</param>
/// <param name="fieldName">Fieldname for the dynamic property.</param>
/// <returns>A property validator.</returns>
public static PropertyValidator<dynamic> ForDynamic(Func<dynamic, string> getter, string fieldName)
{
PropertyValidator<dynamic> prop = new PropertyValidator<dynamic>();
prop.getter = getter;
prop.fieldName = fieldName;
return prop;
}
/// <summary>
/// Allow to set a row index. Usefull to display a line number in error message.
/// </summary>
/// <param name="rowIndex">Row index.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> SetRowIndex(int rowIndex)
{
this.rowIndex = rowIndex;
return this;
}
/// <summary>
/// Allow to set an object to pass an extra object to the validator.
/// </summary>
/// <param name="extraObject">Extra dynamic object.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> SetExtraObject(dynamic extraObject)
{
this.extraObject = extraObject;
return this;
}
/// <summary>
/// Allow overriding default error message.
/// </summary>
/// <param name="msgErrorFunc">Custom error message as a Func.</param>
/// <param name="preserveErrorHeader">Preserve line, field name header in error message.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> OverrideErrorMessage(Func<TRow, string> msgErrorFunc, bool preserveErrorHeader = false)
{
this.preserveErrorHeader = preserveErrorHeader;
this.methods.Last().OverrideErrorMessage = (current) => msgErrorFunc(current);
return this;
}
/// <summary>
/// Check if property is not null.
/// </summary>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> IsNotNull()
{
StringMethods<TRow> method = new StringMethods<TRow>((x) => this.getter(x));
method.IsNotNull();
this.methods.Add(method);
return this;
}
/// <summary>
/// Check if property is not null or empty.
/// </summary>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> IsNotNullOrEmpty()
{
StringMethods<TRow> method = new StringMethods<TRow>((x) => this.getter(x));
method.IsNotNullOrEmpty();
this.methods.Add(method);
return this;
}
/// <summary>
/// Check if property is convertible to decimal.
/// </summary>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> TryParseDecimal()
{
DecimalMethods<TRow> method = new DecimalMethods<TRow>((x) => this.getter(x));
method.TryParseDecimal();
this.methods.Add(method);
return this;
}
/// <summary>
/// Check if property is convertible to DateTime.
/// </summary>
/// <param name="format">specified format.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> TryParseDateTime(string format)
{
DateTimeMethods<TRow> method = new DateTimeMethods<TRow>((x) => this.getter(x));
method.TryParseDateTime(format);
this.methods.Add(method);
return this;
}
/// <summary>
/// Check if property has required length.
/// </summary>
/// <param name="min">min length.</param>
/// <param name="max">maw length.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> HasLength(int min, int max)
{
StringMethods<TRow> method = new StringMethods<TRow>((x) => this.getter(x));
method.HasLength(min, max);
this.methods.Add(method);
return this;
}
/// <summary>
/// Check if property is in list values.
/// </summary>
/// <param name="values">List of values.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> IsStringValues(string[] values)
{
StringMethods<TRow> method = new StringMethods<TRow>((x) => this.getter(x));
method.IsStringValues(values);
this.methods.Add(method);
return this;
}
/// <summary>
/// Check if property value match regex.
/// </summary>
/// <param name="pattern">Regex pattern.</param>
/// <param name="options">Regex options.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> TryRegex(string pattern, RegexOptions options = RegexOptions.None)
{
StringMethods<TRow> method = new StringMethods<TRow>((x) => this.getter(x));
method.TryRegex(pattern, options);
this.methods.Add(method);
return this;
}
/// <summary>
/// Add a condition on a validation action of <see cref="IPropertyValidatorAction"/>.
/// </summary>
/// <param name="ifFunc">Condition as a predicate.</param>
/// <param name="action">
/// Validation action from <see cref="IPropertyValidatorAction{TRow}"/> interface.
/// Action may add 1 to N methods.
/// </param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> If(Func<TRow, bool> ifFunc, Action<IPropertyValidatorAction<TRow>> action)
{
// track method count before and after to link condition on all new methods.
var before = this.methods.Count;
action(this);
var after = this.methods.Count;
var nbAdded = after - before;
// take last N methods
var newMethods = this.methods.Skip(Math.Max(0, after - nbAdded));
// add condition on new methods
foreach (var item in newMethods)
{
item.Condition = (current) => ifFunc(current);
}
return this;
}
/// <summary>
/// Add a condition on a custom validation action.
/// </summary>
/// <param name="predicate">Condition as a predicate.</param>
/// <param name="tocheck">tocheck if condition is ok. TRow as the current row.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> If(Func<TRow, bool> predicate, Func<TRow, bool> tocheck)
{
MethodValidator<TRow> method = new MethodValidator<TRow>((x) => this.getter(x));
method.Condition = (current) => predicate(current);
method.ToCheck = (current) => tocheck(current);
method.ErrorMessage = (current) => Translation.IfError;
this.methods.Add(method);
return this;
}
/// <summary>
/// Add a condition on a custom validation action.
/// </summary>
/// <param name="predicate">Condition as a predicate.</param>
/// <param name="tocheck">todo if condition is ok.</param>
/// <returns>Current instance.</returns>
public PropertyValidator<TRow> If(Func<TRow, bool> predicate, Func<TRow, dynamic, bool> tocheck)
{
MethodValidator<TRow> method = new MethodValidator<TRow>((x) => this.getter(x));
method.Condition = (current) => predicate(current);
method.ToCheck = (current) => tocheck(current, this.extraObject);
method.ErrorMessage = (current) => Translation.IfError;
this.methods.Add(method);
return this;
}
/// <summary>
/// Validate the property with the current row.
/// </summary>
/// <param name="row">Current row.</param>
public void Validate(TRow row)
{
this.ValidationErrors = new List<ValidationError>();
foreach (var method in this.methods)
{
bool condition = true;
if (method.Condition != null)
{
condition = method.Condition(row);
}
if (condition)
{
bool ok = method.ToCheck(row);
if (!ok)
{
this.ValidationErrors.Add(ValidationError.Failure(this.fieldName, this.MessageErrorFactory(row, method)));
break; // by default breaks if error
}
}
}
}
/// <summary>
/// Create an error message.
/// </summary>
/// <param name="current">Current element.</param>
/// <param name="messageError">Error informations from method. <see cref="IMethodMessageError{TRow}"/>.</param>
/// <returns>Error message.</returns>
private string MessageErrorFactory(TRow current, IMethodMessageError<TRow> messageError)
{
StringBuilder errorMsg = new StringBuilder();
// when overriden error message suppress header by default
if (this.preserveErrorHeader)
{
if (this.rowIndex.HasValue)
{
errorMsg.Append($"{Translation.Row} {this.rowIndex} ");
}
errorMsg.Append($"{Translation.Field} {this.fieldName} : ");
}
// default or override msg
if (messageError.OverrideErrorMessage == null)
{
errorMsg.Append(messageError.ErrorMessage(current));
}
else
{
errorMsg.Append(messageError.OverrideErrorMessage(current));
}
return errorMsg.ToString();
}
}
</code></pre>
<ul>
<li>The If methods should look for the last method added to the
collection. I do not like this way of adding the condition on the
MethodValidtor <strong>as it does not seem robust and reliable</strong></li>
</ul>
<p>The MethodValidator defines delegates to get the value, the method for validation and and optional condition.</p>
<p>The concrete implemenation is done in sub classes of the MethodValidator.</p>
<pre><code>/// <summary>
/// Define a method to validate a property.
/// </summary>
/// <typeparam name="TRow">Type to validate.</typeparam>
public class MethodValidator<TRow> : IMethodMessageError<TRow>
{
/// <summary>
/// Initializes a new instance of the <see cref="MethodValidator{TRow}"/> class.
/// </summary>
/// <param name="value">delegate to get the value to validate.</param>
public MethodValidator(Func<TRow, string> value)
{
this.Value = value;
}
/// <summary>
/// Gets a method returning the value to validate.
/// </summary>
public Func<TRow, string> Value { get; private set; }
/// <summary>
/// Gets or sets a condition prior to check if property value is valid.
/// </summary>
public Func<TRow, bool> Condition { get; set; }
/// <summary>
/// Gets or sets a method to check if property value is valid.
/// </summary>
public Func<TRow, bool> ToCheck { get; set; }
/// <summary>
/// Gets or sets a method to define a custom error message.
/// <summary>
public Func<TRow, string> OverrideErrorMessage { get; set; }
/// <summary>
/// Gets or sets a method to define the final error message.
/// <summary>
public Func<TRow, string> ErrorMessage { get; set; }
}
</code></pre>
<p>The whole source code is here : <a href="https://github.com/NicoDvl/StringContentValidator/tree/7e37f686fcc6992a1e3dcdb075ef8318ea92385f" rel="nofollow noreferrer">https://github.com/NicoDvl/StringContentValidator</a></p>
<p>What do you think of that ? How to improve the design, the source code ? Could you find the library useful ? What am I missing ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T23:59:09.180",
"Id": "403209",
"Score": "0",
"body": "Welcome to Code Review! The code that you have posted in the question is just an example usage, rather than the implementation of the validator. Therefore, I am voting to close this question due to the code not being included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:02:04.240",
"Id": "403212",
"Score": "0",
"body": "@200_success I'll include more parts of the implementation. I did not want it to be too long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T01:15:14.627",
"Id": "403220",
"Score": "0",
"body": "@200_success I added parts of the implementation and precised \nsome questions. Do not hesitate to tell me if it's better or not. Regards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T05:50:13.777",
"Id": "403249",
"Score": "0",
"body": "Thanks for adding the code. It's much better now. Close vote retracted."
}
] | [
{
"body": "<p>I'll take time to review just one of the APIs which I find is the most confusing one:</p>\n\n<blockquote>\n<pre><code>public void Validate(TRow row)\n{\n this.ValidationErrors = new List<ValidationError>();\n\n foreach (var method in this.methods)\n {\n bool condition = true;\n if (method.Condition != null)\n {\n condition = method.Condition(row);\n }\n\n if (condition)\n {\n bool ok = method.ToCheck(row);\n if (!ok)\n {\n this.ValidationErrors.Add(ValidationError.Failure(this.fieldName,this.MessageErrorFactory(row, method)));\n\n break; // by default breaks if error\n }\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>This method does some very strange things:</p>\n\n<ul>\n<li>calls <code>.Condition</code> that returns a <code>condition</code></li>\n<li>if <code>condition</code> is <code>true</code> then <code>ToCheck</code> returns a <code>bool</code> and if that one is <code>false</code> the validation failes</li>\n<li>stops evaluating other methods on first error without any particular reason</li>\n</ul>\n\n<p>There is not a single helpful name here. Every single line just makes it worse. But at least you have commented these APIs so that one can look there for an explanation:</p>\n\n<blockquote>\n<pre><code>/// <summary>\n/// Gets or sets a condition prior to check if property value is valid.\n/// </summary>\npublic Func<TRow, bool> Condition { get; set; }\n</code></pre>\n</blockquote>\n\n<p>OK, I understand it's a <em>pre-validation-condition</em> but why do we need this at all? This should be part of the validation logic. A value is either valid or not. This puts it somehow inbetween. One could argue that it's <em>inconclusive</em> when <code>Condition</code> is <code>false</code> but I'd say if it's not invalid then it's valid. How else would I handle the <em>inconclusive</em> state?</p>\n\n<p>I would remove this step or if you <em>insist</em> on keeping it than you should rename it to something like <code>CanValidate</code>.</p>\n\n<blockquote>\n<pre><code>/// <summary>\n/// Gets or sets a method to check if property value is valid.\n/// </summary>\npublic Func<TRow, bool> ToCheck { get; set; }\n</code></pre>\n</blockquote>\n\n<p>This API also needs to be changed. Since this is the actual validation method then you should name it <code>IsValid</code>.</p>\n\n<blockquote>\n<pre><code>break; // by default breaks if error\n</code></pre>\n</blockquote>\n\n<p>There is still this unexplained <code>break</code>. I see what it's doing so this comment does not help me to understand the logic. You need to tell the reader <strong>why</strong> this is the default. To me, a casual reader, it's simply weird that it cannot continue with other checks.</p>\n\n<p>When you apply these suggestions and squeeze the conditions together then the method can be shortend to this nice LINQ:</p>\n\n<pre><code>public void Validate(TRow row)\n{\n ValidationErrors = \n (\n from method in methods\n where method.CanValidate(row) && !method.IsValid(row)\n select ValidationError.Failure(fieldName, MessageErrorFactory(row, method))\n ).ToList();\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:24:34.410",
"Id": "403267",
"Score": "0",
"body": "Perfectly right, I will improve the naming : .Condition that return a condition by .PreCondition that return a result. This PreCondition is used to condition a Validation eg : .If(x => x.Type == \"P\", p.IsNotNull().TryParseDecimal())); that's why it's not included in the validation. The unexplained break stands for : stop validation on first failure. It could be helpfull if a validator depends on the previous validator to succeed. I agree it should not be the default and need clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:26:18.197",
"Id": "403268",
"Score": "0",
"body": "@NicoD _I agree it should not be the default_ - not quite what I mean ;-) it can be default but there has to be a reason for that. If you have one then it's perfectly fine, just put this reason as a comment above the `break` - you virtually should write `// by default breaks if error because...` ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:31:28.923",
"Id": "403269",
"Score": "0",
"body": "I really think it should not be the default but seems easier for the first draft ;). I will update this part and comments. \nWhat is the best way to share corrections: I update the code in my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:34:25.477",
"Id": "403271",
"Score": "0",
"body": "@NicoD _I update the code in my question?_ - no, please don't - it's not allowed when there are already answers posted - the best you can do is to wait a couple of days for more reviews to come and when you think there is some helpful information you can accept one answer and post your new code either as a self-answer or a new question is you'd like to have one more review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:39:42.387",
"Id": "403272",
"Score": "1",
"body": "That makes sense. I will update the Git repository and I'll keep you informed if you want to take a look. Thank you for the review :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T08:41:27.390",
"Id": "208750",
"ParentId": "208729",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T23:26:44.957",
"Id": "208729",
"Score": "3",
"Tags": [
"c#",
"validation",
"csv",
"library",
"fluent-interface"
],
"Title": "Simple fluent library to validate text content"
} | 208729 |
<p>I am working on a component for a navigation bar. This navigation bar currently has two variations: a "back" version, and a "close" version.</p>
<p>I have come up with three different implementations but I am uncertain of which one is the best. Currently, I am leaning towards this implementation as it reads the best in my opinion.</p>
<pre><code>const NAVIGATION_BAR_TYPE = {
back: "back",
close: "close",
}
const NavigationBar = ({ type = NAVIGATION_BAR_TYPE.back, text, linkTo }) => {
return (
<div className={`navigation-button ${type}`}>
<Link to={linkTo}>{text}</Link>
</div>
)
}
NavigationBar.Close = (props) => (
<NavigationBar { ...props } type={NAVIGATION_BAR_TYPE.close} />
)
NavigationBar.Back = (props) => (
<NavigationBar { ...props } type={NAVIGATION_BAR_TYPE.back} />
)
// Usage: <NavigationBar.Close linkTo="/" />
</code></pre>
<p>This is similar to the first one, but you need to import the object that holds the navigation bar types:</p>
<pre><code>const NAVIGATION_BAR_TYPE = {
back: "back",
close: "close",
}
const NavigationBar = ({ type = NAVIGATION_BAR_TYPE.back, text, linkTo }) => {
return (
<div className={`navigation-button ${type}`}>
<Link to={linkTo}>{text}</Link>
</div>
)
}
// Usage: <NavigationBar type={NAVIGATION_BAR_TYPE.back} linkTo="/" />
</code></pre>
<p>Or this one, leveraging props:</p>
<pre><code>const NavigationBar = ({ back, close, text, linkTo }) => {
const navigationType = back ? 'back' : 'close'
return (
<div className={`navigation-button ${navigationType}`}>
<Link to={linkTo}>{text}</Link>
</div>
)
}
// Usage: <NavigationBar back linkTo="/" />
</code></pre>
<p>I don't like the third solution because if I need to add more variations, I feel like it clutters the props. And I don't like the second solution because then you are importing this enum-like object to define the type.</p>
| [] | [
{
"body": "<p>Without knowing the context of how this navigation bar is used in your app its hard to say which one would be more preferable. Does the navigation type dictate only the styling of the navigation bar or also some type of action too? Is the navigation type only tied to some sort of button within the navigation bar that displays differently and points to a different direction? Maybe doing something like this would work for that:</p>\n\n<pre><code><NavigationBar>\n <NavigationBar.ActionButton type='back' />\n</NavigationBar>\n</code></pre>\n\n<p>All the variants you provided seem like good solutions, I think you are in best judgement here to decide what fits your apps needs. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:05:07.190",
"Id": "403338",
"Score": "0",
"body": "It's a mix of styling and functionality. For instance: the \"back\" variant should expect a linkTo prop, but the \"close\" variant could be used on a modal, so that would expect a callback function. I think a solution like you posted may be a better. I have also considered taking an approach similar to how it is handled in iOS's UIKit. You call the `UINavigationBar` and you set the `backBarButtonItem`. I could achieve this using a `backButton` prop that expects a component, and pass it either a link, or a button for instance. Thanks for the input!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:17:28.837",
"Id": "208777",
"ParentId": "208731",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-29T23:45:16.893",
"Id": "208731",
"Score": "1",
"Tags": [
"comparative-review",
"react.js",
"jsx"
],
"Title": "Navigation bar React component, with a \"back\" and a \"close\" variant"
} | 208731 |
<p>I tried to write a function <code>bin_add()</code> in C to add two positive binary numbers represented as zero terminated strings:</p>
<pre><code>#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX(x, y) ((x) > (y) ? (x) : (y))
size_t gpp(char const *s)
{
char *n = strchr(s, '.');
return n ? (size_t)(n - s + 1) : 0;
}
char* bin_add(char const *a, char const *b)
{
char const *inp[] = { a, b };
size_t ll[] = { strlen(a), strlen(b) };
size_t pp[] = { gpp(a), gpp(b) };
size_t OO[2], off[2];
for (size_t i = 0; i < 2; ++i) {
OO[i] = pp[i] ? pp[i] - 1 : ll[i];
pp[i] = pp[i] ? ll[i] - pp[i] : 0;}
for (size_t i = 0; i < 2; ++i)
off[i] = OO[i] < OO[!i] ? OO[!i] - OO[i] : 0;
size_t ML = MAX(OO[0], OO[1]) + MAX(pp[0], pp[1]) + (!!pp[0] || !!pp[1]);
char *Ol = calloc(ML + 2, 1);
if(!Ol) return Ol;
char ops[2];
int xc = 0;
size_t lO = ML;
unsigned cc[2] = { 0 };
for (size_t i = ML; i; --i) {
bool pt = false;
for (size_t l = 0; l < 2; ++l) {
ops[l] = i <= ll[l] + off[l] && i - off[l] - 1
< ll[l] ? inp[l][i - off[l] - 1] : '0';
if (ops[l] == '.') {
if (cc[l]) {
free(Ol);
return NULL;
}
pt = true;
++cc[l];
}
ops[l] -= '0';
}
if (pt) {
Ol[i] = '.';
continue;
}
if ((Ol[i] = ops[0] + ops[1] + xc) > 1) {
Ol[i] = 0;
xc = 1;
}
else xc = 0;
lO = (Ol[i] += '0') == '1' ? i : lO;
}
if((Ol[0] = '0' + xc) == '1') return Ol;
for (size_t i = 0; i <= ML - lO + 1; ++i)
Ol[i] = Ol[lO + i];
return Ol;
}
int main(void)
{
char a[81], b[81];
while (scanf(" %80[0.1] %80[0.1]", a, b) & 1 << 1) {
char *c = bin_add(a, b);
if (!c && errno == ENOMEM) {
fputs("Not enough memory :(\n\n", stderr);
return EXIT_FAILURE;
}
else if (!c) {
fputs("Input error :(\n\n", stderr);
goto clear;
}
char* O[] = { a, b, c };
size_t lO[3], Ol = 0;
for (size_t i = 0; i < 3; ++i) {
lO[i] = gpp(O[i]);
lO[i] = lO[i] ? lO[i] : strlen(i[O]) + 1;
Ol = lO[i] > Ol ? lO[i] : Ol;
}
putchar('\n');
for (size_t i = 0; i < 3; ++i) {
for (size_t l = 0; l < Ol - lO[i]; ++l, putchar(' '));
puts(O[i]);
}
putchar('\n');
free(c);
clear :{ int c; while ((c = getchar()) != '\n' && c != EOF); }
}
}
</code></pre>
<p>The <code>main()</code> is just included to provide input to the function and pretty-print its results. Every C99 compliant compiler should be able to compile above code.</p>
<p>Do you see any flaws in my code and anything that could be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:12:31.587",
"Id": "403329",
"Score": "0",
"body": "\"`A revised version of the code will be posted in an update to this question.`\" Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:26:30.147",
"Id": "403331",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I'll move the reply to an answer."
}
] | [
{
"body": "<blockquote>\n <p>Do you see any flaws in my code and anything that could be improved?</p>\n</blockquote>\n\n<p><strong>Segregate code</strong></p>\n\n<p>Splitting into <code>bin_add.c</code>, <code>bin_add.h</code>, <code>main.c</code> would help delineate what is the code, its user interface and test code.</p>\n\n<p><strong>No compilation errors</strong></p>\n\n<p>As posted now, I did not notice any warnings either- good.</p>\n\n<p><strong>Some comments would help</strong></p>\n\n<p><code>gpp()</code> would benefit with at least a line comment about its goal, expected input, output, etc. Same for <code>bin_add()</code> - which should alert that the return pointer needs to be free'd. This becomes even more important when the user only has access to the declaration in a <code>.h</code> file.</p>\n\n<p>Commenting some of the block of code would help too.</p>\n\n<p><strong>When to shift</strong></p>\n\n<p>When there is not a final carry, code shifts <code>Ol[]</code>. As a final carry with this FP-like code is more rare, I'd shift when there is a carry.</p>\n\n<p><strong>Collapsing</strong></p>\n\n<p>With floating point strings, I expect code to drop trailing zero digits to the right of the <code>'.'</code>. </p>\n\n<p>Leading zero digits are possible based on input. Perhaps eat those too with an early <code>while (*a == '0') a++;</code> and with <code>b</code>. - depends on coding goals though. </p>\n\n<p><strong>Inconsistent bracket style</strong></p>\n\n<pre><code>// v ?? \npp[i] = pp[i] ? ll[i] - pp[i] : 0;}\n</code></pre>\n\n<p>Hopefully code is auto-formatted.</p>\n\n<p><strong>Inconsistent indentation</strong></p>\n\n<pre><code>if((Ol[0] = '0' + xc) == '1') return Ol;\n// v Why indented here?\n for (size_t i = 0; i <= ML - lO + 1; ++i)\n Ol[i] = Ol[lO + i];\n</code></pre>\n\n<p>This implies code is not auto formatted. Save time, and use auto-formatting. </p>\n\n<p><strong>Terse digit like object names lose clarity</strong></p>\n\n<p>The short object names <code>OO, lO, O, Ol, ll</code> look too much like <code>00, 10, 0, 01, 11</code>. Consider more clear alternatives.</p>\n\n<p>Other examples:<br>\n<code>int xc</code> as the carry bit looks more clear as <code>int carry</code>.\n<code>size_t ML</code> more meaningful as <code>MaxLength</code>.</p>\n\n<p><strong>Input error detection</strong></p>\n\n<p>I'd suggest a separate <code>bool bin_valid(const char *s)</code> and let <code>bin_add()</code> assume valid strings <code>a,b</code>. This would help simplify - a <code>NULL</code> return would only indicate out-of-memory.</p>\n\n<p><strong>Good use of cast to ward off warnings</strong></p>\n\n<pre><code>return n ? (size_t)(n - s + 1) : 0;\n// ^------^\n</code></pre>\n\n<p><strong>Misc.</strong></p>\n\n<p><code>ops[2], cc[2]</code> could be local to <code>for (size_t i = ML; i; --i) {</code></p>\n\n<p>Good use of <code>const</code>.</p>\n\n<p>Good use of <code>size_t</code>.</p>\n\n<p>Personal preference: Consider <code>char *Ol = calloc(ML + 2, sizeof *Ol);</code></p>\n\n<hr>\n\n<p>Main</p>\n\n<p><strong>Do not assume <code>EOF</code> is -1</strong></p>\n\n<p>Simply test if the <code>scanf()</code> result is 2.</p>\n\n<pre><code>// while (scanf(\" %80[0.1] %80[0.1]\", a, b) & 1 << 1) {\nwhile (scanf(\" %80[0.1] %80[0.1]\", a, b) == 2) {\n</code></pre>\n\n<p><strong>ENOMEM</strong></p>\n\n<p><code>ENOMEM</code> is not part of the standard C.</p>\n\n<p><strong>Test cases</strong></p>\n\n<p>Some specific example test cases would be useful.</p>\n\n<blockquote>\n <p>maybe even C90/C89</p>\n</blockquote>\n\n<p>Not quite.</p>\n\n<p>Lots of <code>error: 'for' loop initial declarations are only allowed in C99 or C11 mode</code> problems</p>\n\n<p><code>warning: control reaches end of non-void function [-Wreturn-type]</code></p>\n\n<p><code>error: redefinition of 'i'</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:28:05.837",
"Id": "403332",
"Score": "0",
"body": "I replied to your great review in an answer to the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T03:43:07.227",
"Id": "208741",
"ParentId": "208734",
"Score": "3"
}
},
{
"body": "<h3>In reply to <a href=\"https://codereview.stackexchange.com/a/208741/176102\">@chux review</a>:</h3>\n\n<blockquote>\n <p><strong>Segregate code</strong></p>\n \n <p>Splitting into <code>bin_add.c</code>, <code>bin_add.h</code>, <code>main.c</code> would help delineate what is the code, its user interface and test code.</p>\n</blockquote>\n\n<p>I understand. Please note that I posted the code contained within one \"file\" to make copy & paste for testing easier for the readers. I concur, the code should be split up in a header and it's accompanying source file.</p>\n\n<blockquote>\n <p><strong>Some comments would help</strong></p>\n \n <p><code>gpp()</code> would benefit with at least a line comment about its goal, expected input, output, etc. Same for <code>bin_add()</code> - which should alert that the return pointer needs to be free'd. This becomes even more important when the user only has access to the declaration in a <code>.h</code> file.</p>\n</blockquote>\n\n<p>I wrote short specifications of the both functions to go in front of their declaration (prototype) and definition (implementation).</p>\n\n<blockquote>\n <p>Commenting some of the block of code would help too.</p>\n</blockquote>\n\n<p>I'd appreciate your input on where coments might be needed on the cleaned up version of the code since I believe in self-documenting code.</p>\n\n<blockquote>\n <p><strong>When to shift</strong></p>\n \n <p>When there is not a final carry, code shifts <code>Ol[]</code>. As a final carry with this FP-like code is more rare, I'd shift when there is a carry.</p>\n</blockquote>\n\n<p>Um. Since the code \"shifts away\" all leading zeros I am not sure your conclusion and suggestion \"As a final carry with this FP-like code is more rare, I'd shift when there is a carry\" is applicable.</p>\n\n<blockquote>\n <p><strong>Collapsing</strong></p>\n \n <p>With floating point strings, I expect code to drop trailing zero digits to the right of the <code>'.'</code>.</p>\n</blockquote>\n\n<p>Yes, that is an oversight of the initial implementation. I'll add code to discard trailing zeros from the result.</p>\n\n<blockquote>\n <p>Leading zero digits are possible based on input. Perhaps eat those too with an early <code>while (*a == '0') a++;</code> and with <code>b</code>. - depends on coding goals though.</p>\n</blockquote>\n\n<p>Whith discarding leading zeros at an early stage as you suggest, it is no longer needed to keep track of the last <code>'1'</code> written to the output string. I'll add code to discard leading zeros in the input strings.</p>\n\n<blockquote>\n <p><strong>Inconsistent bracket style</strong></p>\n\n<pre><code>// v ?? \npp[i] = pp[i] ? ll[i] - pp[i] : 0;}\n</code></pre>\n \n <p>Hopefully code is auto-formatted.</p>\n</blockquote>\n\n<p>You are right, that bracket should to to the next line.</p>\n\n<blockquote>\n <p><strong>Inconsistent indentation</strong></p>\n\n<pre><code>if((Ol[0] = '0' + xc) == '1') return Ol;\n// v Why indented here?\n for (size_t i = 0; i <= ML - lO + 1; ++i)\n Ol[i] = Ol[lO + i];\n</code></pre>\n \n <p>This implies code is not auto formatted. Save time, and use auto-formatting.</p>\n</blockquote>\n\n<p>That was an oversight when posting the question. The original code is properly indented.</p>\n\n<blockquote>\n <p><strong>Terse digit like object names lose clarity</strong></p>\n \n <p>The short object names <code>OO</code>, <code>lO</code>, <code>O</code>, <code>Ol</code>, <code>ll</code> look too much like <code>00</code>, <code>10</code>, <code>0</code>, <code>01</code>, <code>11</code>. Consider more clear alternatives.</p>\n \n <p>Other examples:\n <code>int xc</code> as the carry bit looks more clear as <code>int carry</code>. <code>size_t ML</code> more meaningful as <code>MaxLength</code>.</p>\n</blockquote>\n\n<p>I'll think of better names.</p>\n\n<blockquote>\n <p><strong>Input error detection</strong></p>\n \n <p>I'd suggest a separate <code>bool bin_valid(const char *s)</code> and let <code>bin_add()</code> assume valid strings <code>a</code>, <code>b</code>. This would help simplify - a <code>NULL</code> return would only indicate out-of-memory.</p>\n</blockquote>\n\n<p>Good point. This will allow to drop counting of radix points from <code>bin_add()</code>. I'll implement a function <code>bool is_valid_binary_string(char const *s)</code>.</p>\n\n<blockquote>\n <p><strong>Misc.</strong></p>\n \n <p><code>ops[2]</code>, <code>cc[2]</code> could be local to <code>for (size_t i = ML; i; --i) {</code></p>\n</blockquote>\n\n<p>Right. I changed the point of definition of <code>ops[2]</code>. <code>cc[2]</code> will be dropped as it is no longer needed if the function can rely on valid input.</p>\n\n<blockquote>\n <p>Personal preference: Consider <code>char *Ol = calloc(ML + 2, sizeof *Ol);</code></p>\n</blockquote>\n\n<p>This would help to avoid a pitfall if the code were ever to be changed to work with wide characters. Changed.</p>\n\n<blockquote>\n <p><strong>Do not assume <code>EOF</code> is -1</strong></p>\n \n <p>Simply test if the scanf() result is 2.</p>\n</blockquote>\n\n<p>The original code does not assume <code>EOF</code> to be -1. It compares the result of <code>scanf()</code> to 2 just as you suggest, albeit in a rather obfuscated way. I'll change <code>== 1 << 1</code> to <code>== 2</code>.</p>\n\n<blockquote>\n <p><strong><code>ENOMEM</code></strong></p>\n \n <p><code>ENOMEM</code> is not part of the standard C.</p>\n</blockquote>\n\n<p>Since it is no longer needed with <code>bin_add()</code> relying on valid input, I will drop checking <code>errno</code> for <code>ENOMEM</code>.</p>\n\n<p>Also I'll drop the speculation about the code being C89/90 compliant from my post since it contains variable definitions local to <code>for</code>-loops which is not allowed in pre C99 code. Didn't think about that.</p>\n\n<p>A revised version of the code:</p>\n\n<pre><code>#include <stdbool.h>\n#include <stddef.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#define MAX(x, y) ((x) > (y) ? (x) : (y))\n\n/* gpp() (get point position) expects a zero terminated string as input and\n will return the 1-based position of the first occurrence of character '.'\n or 0 if no such character is present in the input string.\n*/\nsize_t gpp(char const *s)\n{\n char *n = strchr(s, '.');\n return n ? (size_t)(n - s + 1) : 0;\n}\n\n/* Determines if its parameter is a valid binary number consisting only of\n '0' and '1' and containing at most one radix point. The return value is\n true if a valid binary number is passed and false otherwise.\n*/\nbool is_valid_binary_string(char const *s)\n{\n int num_points = 0;\n for (; *s; ++s) {\n if (*s != '1' && *s != '0' && *s != '.')\n return false;\n if (*s == '.' && ++num_points > 1)\n return false;\n }\n return true;\n}\n\n/* bin_add() expects two zero terminated strings as input. The both strings\n must not contain other characters than '0' and '1'. Both may contain no or\n one radix point ('.'). The function returns a zero terminated string which\n is the result of the addition of both input strings done in base 2. The\n caller is responsible for deallocating the memory to which a pointer is\n returned. If memory allocation failes the function returns NULL and errno\n is ENOMEM. If one or both input strings do not conform to the expectations\n of the function, it returns NULL.\n*/\nchar* bin_add(char const *a, char const *b)\n{\n while (*a == '0') ++a;\n while (*b == '0') ++b;\n\n char const *input[] = { a, b };\n size_t length[] = { strlen(a), strlen(b) };\n size_t point_position[] = { gpp(a), gpp(b) };\n size_t integer_part[2];\n size_t offset[2];\n\n for (size_t i = 0; i < 2; ++i) {\n integer_part[i] = point_position[i] ? point_position[i] - 1 : length[i];\n point_position[i] = point_position[i] ? length[i] - point_position[i] : 0;\n }\n\n for (size_t i = 0; i < 2; ++i)\n offset[i] = integer_part[i] < integer_part[!i]\n ? integer_part[!i] - integer_part[i]\n : 0;\n\n size_t maximum_length = MAX(integer_part[0], integer_part[1]) +\n MAX(point_position[0], point_position[1]) +\n (!!point_position[0] || !!point_position[1]);\n\n char *result = calloc(maximum_length + 2, sizeof(*result));\n if (!result)\n return NULL;\n\n int carry = 0;\n bool result_contains_point = false;\n for (size_t i = maximum_length; i; --i) {\n char ops[2];\n bool is_radix_point = false;\n for (size_t l = 0; l < 2; ++l) {\n ops[l] = i <= length[l] + offset[l] && i - offset[l] - 1\n < length[l] ? input[l][i - offset[l] - 1] : '0';\n if (ops[l] == '.') {\n result_contains_point = is_radix_point = true;\n break;\n }\n ops[l] -= '0';\n }\n if (is_radix_point) {\n result[i] = '.';\n continue;\n }\n if ((result[i] = ops[0] + ops[1] + carry) > 1) {\n result[i] = 0;\n carry = 1;\n }\n else carry = 0;\n result[i] += '0';\n }\n\n result[0] = '0' + carry;\n\n if(result_contains_point)\n while (result[maximum_length] == '0')\n result[maximum_length--] = '\\0';\n\n if (result[0] == '1')\n return result;\n\n for (size_t i = 0; i <= maximum_length + 1; ++i)\n result[i] = result[i + 1];\n return result;\n}\n\nint main(void)\n{\n char a[81], b[81];\n\n while (scanf(\" %80[0.1] %80[0.1]\", a, b) == 2) {\n if (!is_valid_binary_string(a) || !is_valid_binary_string(b)) {\n fputs(\"Input error :(\\n\\n\", stderr);\n goto clear;\n }\n\n char *c = bin_add(a, b);\n if (!c) {\n fputs(\"Not enough memory :(\\n\\n\", stderr);\n return EXIT_FAILURE;\n }\n\n char* numbers[] = { a, b, c };\n size_t point_position[3];\n size_t offset = 0;\n\n for (size_t i = 0; i < 3; ++i) {\n point_position[i] = gpp(numbers[i]);\n point_position[i] = point_position[i] ? point_position[i] : strlen(numbers[i]) + 1;\n offset = point_position[i] > offset ? point_position[i] : offset;\n }\n\n putchar('\\n');\n for (size_t i = 0; i < 3; ++i) {\n for (size_t l = 0; l < offset - point_position[i]; ++l, putchar(' '));\n puts(numbers[i]);\n }\n putchar('\\n');\n\n free(c);\n\nclear: { int ch;\n while ((ch = getchar()) != '\\n' && ch != EOF);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:00:14.707",
"Id": "403336",
"Score": "0",
"body": "Re: \"final carry with this FP-like code is more rare\" --> `bin_add(\"101010\", \"111\")`, `bin_add(\"0.101010\", \"111\")` do not generate a carry. Same magnitude ones do like `bin_add(\"101010\", \"101010\")` - and hence more rare."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:02:10.757",
"Id": "403337",
"Score": "0",
"body": "@chux I got you, but I really don't feel like rewriting the code based on this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:05:12.530",
"Id": "403339",
"Score": "0",
"body": "`is_valid_binary_string(\"\")` and `is_valid_binary_string(\".\")` return true. I'd expect false - your call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:12:11.133",
"Id": "403346",
"Score": "0",
"body": "*Oh i see you have updated.* – Yes, didn't want to lose a point to you for that one too ^^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:13:08.877",
"Id": "403347",
"Score": "0",
"body": "`\"\"` and `\".\" are both considered `\"0\"` by `bin_add()` so they are valid as far as `bin_add()` is concerned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:13:52.903",
"Id": "403348",
"Score": "0",
"body": "You're right, `&& result[maximum_length] != '.'` can be dropped. Updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:15:20.747",
"Id": "403349",
"Score": "0",
"body": "Good update to your overall code UV - although I still think some comments is the general code are warranted - higher level words, not code re-hash. Look forward to your future postings and reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T17:17:27.420",
"Id": "403351",
"Score": "0",
"body": "*Look forward to your future postings and reviews.* – I don't usually post on codereview. You do know where to find me, though. Btw, what about our quarrel about passing `unsigned` values to variadic functions in C? ;p"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:27:37.180",
"Id": "208778",
"ParentId": "208734",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208741",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:18:22.080",
"Id": "208734",
"Score": "3",
"Tags": [
"c",
"strings"
],
"Title": "Function to add two binary numbers in C"
} | 208734 |
<p>Here's some code I wrote to manage the different types of morphism and their compositions in C++17.</p>
<p>Let me know if you had any suggestions for substantial simplifications or improvements, or if I missed something.</p>
<p>There's an example at the end that composes a number of different morphisms together and then confirms that the final result can be used in a <code>constexpr</code> context.</p>
<pre><code>#include <iostream>
#include <vector>
#include <type_traits>
/// Extract the first argument type from a map.
template <typename R, typename A0, typename ... As>
constexpr A0 firstArg (R(*)(A0, As...));
/** Set theoretic morphisms **/
template<typename S, typename T>
struct Homomorphism {
constexpr static T value(const S);
};
template<typename S, typename T>
struct Monomorphism: Homomorphism<S, T> {
constexpr static T value(const S);
};
template<typename S, typename T>
struct Epimorphism: Homomorphism<S, T> {
constexpr static T value(const S);
};
template<typename S>
struct Endomorphism: Homomorphism<S, S> {
constexpr static S value(const S);
};
template<typename S, typename T>
struct Isomorphism: Monomorphism<S, T>, Epimorphism<S, T> {
constexpr static T value(const S);
};
template<typename S>
struct Automorphism: Endomorphism<S>, Isomorphism<S, S> {
constexpr static S value(const S);
};
template<typename H1,
typename H2,
typename S = std::decay_t<decltype(firstArg(&H1::value))>,
typename T1 = std::decay_t<decltype(H1::value(std::declval<S>()))>,
typename T2 = std::decay_t<decltype(firstArg(&H2::value))>,
typename R = std::decay_t<decltype(H2::value(std::declval<T2>()))>>
struct MonomorphismComposition: Monomorphism<S, R> {
static_assert(std::is_base_of_v<Monomorphism<S, T1>, H1>);
static_assert(std::is_base_of_v<Monomorphism<T2, R>, H2>);
static_assert(std::is_same_v<T1, T2>);
constexpr static R value(const S &s) {
return H2::value(H1::value(s));
}
};
template<typename H1,
typename H2,
typename S = std::decay_t<decltype(firstArg(&H1::value))>,
typename T1 = std::decay_t<decltype(H1::value(std::declval<S>()))>,
typename T2 = std::decay_t<decltype(firstArg(&H2::value))>,
typename R = std::decay_t<decltype(H2::value(std::declval<T2>()))>>
struct EpimorphismComposition: Epimorphism<S, R> {
static_assert(std::is_base_of_v<Epimorphism<S, T1>, H1>);
static_assert(std::is_base_of_v<Epimorphism<T2, R>, H2>);
static_assert(std::is_same_v<T1, T2>);
constexpr static R value(const S &s) {
return H2::value(H1::value(s));
}
};
template<typename H1,
typename H2,
typename S = std::decay_t<decltype(firstArg(&H1::value))>,
typename T1 = std::decay_t<decltype(H1::value(std::declval<S>()))>,
typename T2 = std::decay_t<decltype(firstArg(&H2::value))>,
typename R = std::decay_t<decltype(H2::value(std::declval<T2>()))>>
struct IsomorphismComposition: Isomorphism<S, R> {
static_assert(std::is_base_of_v<Isomorphism<S, T1>, H1>);
static_assert(std::is_base_of_v<Isomorphism<T2, R>, H2>);
static_assert(std::is_same_v<T1, T2>);
constexpr static R value(const S &s) {
return H2::value(H1::value(s));
}
};
template<typename H1,
typename H2,
typename T1 = std::decay_t<decltype(firstArg(&H1::value))>,
typename T2 = std::decay_t<decltype(firstArg(&H2::value))>,
typename T = std::enable_if_t<std::is_same_v<T1, T2>, T1>>
struct EndomorphismComposition: Endomorphism<T> {
static_assert(std::is_base_of_v<Endomorphism<T>, H1>);
static_assert(std::is_base_of_v<Endomorphism<T>, H2>);
constexpr static T value(const T &s) {
return H2::value(H1::value(s));
}
};
template<typename H1,
typename H2,
typename T1 = std::decay_t<decltype(firstArg(&H1::value))>,
typename T2 = std::decay_t<decltype(firstArg(&H2::value))>,
typename T = std::enable_if_t<std::is_same_v<T1, T2>, T1>>
struct AutomorphismComposition: Automorphism<T> {
static_assert(std::is_base_of_v<Automorphism<T>, H1>);
static_assert(std::is_base_of_v<Automorphism<T>, H2>);
constexpr static T value(const T &s) {
return H2::value(H1::value(s));
}
};
template<typename H1,
typename H2,
typename S = std::decay_t<decltype(firstArg(&H1::value))>,
typename T1 = std::decay_t<decltype(H1::value(std::declval<S>()))>,
typename T2 = std::decay_t<decltype(firstArg(&H2::value))>,
typename R = std::decay_t<decltype(H2::value(std::declval<T2>()))>>
struct HomomorphismComposition: Homomorphism<S, R> {
static_assert(std::is_base_of_v<Homomorphism<S, T1>, H1>);
static_assert(std::is_base_of_v<Homomorphism<T2, R>, H2>);
static_assert(std::is_same_v<T1, T2>);
constexpr static R value(const S &s) {
return H2::value(H1::value(s));
}
};
template<typename T>
struct IdentityAutomorphism: Automorphism<T> {
constexpr static T value(const T &t) {
return t;
}
};
/** This is a monomorphism if the type of S is a subset of T, i.e. is convertible to T. **/
template<typename S, typename T>
struct EmbeddingMonomorphism: Monomorphism<S, T> {
static_assert(std::is_convertible_v<S, T>);
constexpr static T value(const S &s) {
return s;
}
};
/*** EXAMPLE ***/
struct divby2: Automorphism<double> { constexpr static double value(double d) { return d / 2; }};
struct embed_divby2: MonomorphismComposition<EmbeddingMonomorphism<int, double>, divby2> {};
struct squared: Monomorphism<int, int>, Endomorphism<int> { constexpr static int value(int i) { return i * i; } };
struct squared_embed_divby2: MonomorphismComposition<squared, embed_divby2> {};
struct S {
explicit constexpr S(int val): val{val} {};
const int val;
};
struct s_to_int: Isomorphism<S, int> { constexpr static int value(const S &s) { return s.val; } };
struct bighom: MonomorphismComposition<s_to_int, squared_embed_divby2> {};
struct biggerhom: MonomorphismComposition<bighom, IdentityAutomorphism<double>> {};
constexpr auto sum() {
double d = 0;
for (int i = 0; i < 10; ++i)
d += biggerhom::value(S{i});
return d;
}
int main() {
for (int i = 0; i < 10; ++i)
std::cout << biggerhom::value(S{i}) << '\n';
constexpr double d = sum();
std::cout << "Sum is: " << d << '\n';
}
</code></pre>
| [] | [
{
"body": "<p>I'm under the impression that this code is part of a larger design, whose extent and intentions I can't entirely guess. Sorry if my review seems a bit restrictive or short sighted in that regard.</p>\n<h1>General design</h1>\n<p>My understanding is that you want to build a mathematical type system over the fairly permissive C++ set of function and function-like types. That's a noble undertaking but I'm afraid that they are so different realities that it will end in a misunderstanding.</p>\n<p>Take your definition of what a c++ application is: <code>R(*)(A0, As...)</code> (in the <code>firstArg</code> signature). This will match a function pointer, but function references, lambdas, member functions, functors, pointer to member functions are as legitimate targets and they won't necessarily match this signature.</p>\n<p>Then there is also the problem of function overloading: what if <code>foo</code> has three overloads? Which one will <code>R(*)(A0, As...)</code> match? (the answer is none, it simply won't compile).</p>\n<p>Three lines further, in contrast to this vigorous simplification, you begin to build a complex inheritance tree whose semantics are transparent to the compiler, at least beyond the identity between argument and return type: how would the compiler decide if a function really is a monomorphism?</p>\n<p>I believe you would be better off with a simpler design uncoupling c++ types and mathematical types, at least to a certain extent.</p>\n<h1>C++ application composition</h1>\n<p>That is already a hard problem on its own right, depending on how much you want to constrain the domain. But it's certainly easier if you want to only accept applications exposing <code>S value(T)</code> as an interface. What I'd suggest then is to provide a handier template:</p>\n<pre><code>template <typename R, typename A>\nstruct Application {\n\n using result_type = R;\n using argument_type = A;\n \n template <typename F>\n Application(F f) : fn(f) {}\n\n R value(A) { return fn(a); } // no need to have it static now\n\n std::function<R(A)> fn;\n};\n</code></pre>\n<p>You can then turn any complying function-like object into a compatible <code>Application</code>: <code>auto square = Application<double, double>([](auto n) { return n * n; };</code>. Verifying application composition is now trivial: <code>std::is_same<typename F::argument_type, typename G::result_type</code> (<code>std::is_convertible</code> might be a choice too).</p>\n<h1>Morphisms classification</h1>\n<p>I'm a bit skeptical about this all-encompassing inheritance tree. The first thing to note is that simple inheritance won't constrain <code>value</code> in the derived class based on its specification in the base class. Inheriting from <code>endomorphism</code> won't constrain a class to expose a <code>value</code> function whose argument type and return type are the same. Virtual functions would constrain it, but frankly, with multiple inheritance that seems unnecessarily dangerous and complex.</p>\n<p>What you could do is keep the kind of morphism as a tag and then constrain the function <code>value</code> with <code>std::enable_if</code> and <code>std::conditional</code>:</p>\n<pre><code>template <typename R, typename A, typename Morphism>\nstruct Application {\n // ...\n using morphism_tag = Morphism;\n using result_type = std::conditional_t<std::is_base_of_v<Endomorphism, morphism_tag>,\n std::enable_if_t<std::is_same_v<R, A>, R>,\n R\n >;\n result_type value(argument_type);\n // ...\n};\n</code></pre>\n<p>Your code won't compile if you generate an <code>Application</code> with an <code>Endomorphism</code> tag whose return type doesn't match the argument type.</p>\n<p>I'm not sure how extensible it would be though, and which rules we would be able to enforce.</p>\n<h1>Morphisms composition</h1>\n<p>With this infrastructure, you would be able to compose morphisms more easily, along those lines:</p>\n<pre><code>template <typename R1, typename A1, typename T1,\n typename R2, typename A2, typename T2>\nconstexpr auto resulting_morphism(Application<R1, A1, T1>, Application<R2, A2, T2>) {\n if constexpr (std::is_base_of_v<Endomorphism, T1> && std::is_base_of_v<Endomorphism, T2>)\n return Monomorphism();\n else if constexpr ( /*...*/ )\n // ...\n else throw std::logical_error(); // throw in constexpr context simply won't compile\n)\n\ntemplate <typename R1, typename A1, typename T1,\n typename R2, typename A2, typename T2>\nconstexpr auto compose(Application<R1, A1, T1> a1, Application<R2, A2, T2> a2) {\n return Application<R1, A2, decltype(resulting_morphism(a1, a2)>([](auto arg) {\n return a1(a2(arg));\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T15:52:47.270",
"Id": "403321",
"Score": "0",
"body": "This is all excellent. Thank you so much for the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T21:58:12.110",
"Id": "403367",
"Score": "0",
"body": "A question: I suppose this would limit `Application` to not being `constexpr` since `std::function` is not `constexpr`. (I believe it has a non-trivial destructor?) I am quite inexperienced with tags and have never used `std::conditional`, so this is teaching me a lot. I'm very thankful for your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T12:38:12.550",
"Id": "403409",
"Score": "0",
"body": "Also, the code was just my brain spiralling out again upon realizing - months ago - that there is an epi between mazes with infinitesimally thin walls, and mazes where the walls have the same thickness as the cells themselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T11:43:19.970",
"Id": "403509",
"Score": "0",
"body": "@Sebastian: I believe you're right about the constexpr thing. The second comment I didn't understand."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T11:16:26.653",
"Id": "208757",
"ParentId": "208736",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "208757",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T00:58:14.240",
"Id": "208736",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"inheritance",
"c++17",
"polymorphism"
],
"Title": "Managing different types of morphism and their compositions"
} | 208736 |
<p>I have written a simple script that searches twitter for keywords and saves them to a csv file if they contain those words. It can be found on my github <a href="https://github.com/ishikawa-rei/Cyber-Security-Sentiment-based-Situational-Awareness-System/tree/f42f52bd4a03b633af2e7d801b5daed72e7ffca4" rel="nofollow noreferrer">here</a>.</p>
<p>How can I improve this code to generally be more efficient and be up to coding standards ?</p>
<pre><code>"""
Script that goes through english tweets that are filtered by security words and posted in the last one hour and stores the polarity, id, date time, query, username and text into a csv file.
"""
import tweepy
import datetime, time, csv, codecs
from textblob import TextBlob
import cleanit
##setting authorization stuff for twitter##
consumer_key = "xxx"
consumer_secret = "xxx"
access_token = "xxx"
access_token_secret = "xxx"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
##initializing lists##
big_list = []
text_list = []
id_list = []
name_list = []
created_list = []
query_list = []
polarityy = []
t = 0
#use words in this list as search terms for tweepy.cursor function
security_words = ['phishing','dos','botnet','xss','smb','wannacry','heartbleed','ransomware','trojan','spyware','exploit','virus','malware','mitm']
# if word in security words list and double_meaning_words list if text also contains word from gen words list, if it does store if not discard
double_meaning_words = ['petya','smb','dos','infosec','hacker','backdoor']
gen_words = ["attack","security","hit","detected","protected","injection","data","exploit", "router", 'ransomware', 'phishing', 'wannacry', 'security']
def storing_data(stat):
##store id,username,datetime,text and polarity for filtered tweets in csv##
text_list.append(str(cleanit.tweet_cleaner_updated(status.text)).encode("utf-8"))
id_list.append(str(status.id)) # append id number to list
name_list.append(str(status.user.screen_name)) # append user name to list
created_list.append((status.created_at).strftime('%c')) # append date time to list
analysis = TextBlob(status.text)
analysis = analysis.sentiment.polarity # use textblob on text to get sentiment score of text
if analysis >= -1 and analysis <= 0: # append sentiment score to list
polarityy.append("4")
else:
polarityy.append("0")
def rejects(stat):
##store tweets which do not pass filters into csv##
with open('rejects.csv', "a", newline='', encoding='utf-8') as rejectfile:
logger = csv.writer(rejectfile)
logger.writerow([status.text])
while True:
print ('running', datetime.datetime.now())
with open('sec_tweet_dataset_5.csv', "a", newline='', encoding='utf-8') as logfile:
logger = csv.writer(logfile)
for i in security_words:
alex = []
for status in tweepy.Cursor(api.search, i,lang="en").items(40): #search twitter for word in security word list in english
if (status.retweeted == False) or ('RT @' not in status.text): #is tweet is retweeted dont store it
if i in double_meaning_words and i in status.text: #if search term being used from security words list also in double meaning words check if it also contains word -
for words in gen_words: # - from gen_words list. If it does continue to storing if not dont store.
if words in status.text:
storing_data(status)
break
else:
rejects(status)
else:
storing_data(status)
rejects(status)
while t < len(polarityy):
alex = ([polarityy[t],id_list[t],created_list[t],name_list[t],text_list[int(t)]])
t += 1
logger.writerow(alex)
time.sleep(1800)
</code></pre>
| [] | [
{
"body": "<p>These following rules are pretty general and take time to internalize. I hope you can apply some of them to your code anyways.</p>\n\n<p>Global variables (variables you don't declare in functions, but at the top level) should be avoided). Constants (variables which you never change) are okay. Instead of changing/mutating global variables in your functions, try to rewrite them so they take input and return something. </p>\n\n<p>Try to break your code up into more functions.</p>\n\n<p>Give descriptive variable names (What does \"t\" do in your code?).</p>\n\n<p>Read through PEP8(<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a>) and try to apply it to your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T14:05:16.653",
"Id": "208763",
"ParentId": "208740",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T02:27:07.660",
"Id": "208740",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"pandas",
"twitter"
],
"Title": "twitter data mining script in python"
} | 208740 |
<p>First time implementing a hash table.</p>
<ul>
<li><p>I resolve collisions using the separate chaining method (closed addressing), i.e with linked lists.</p></li>
<li><p>The hash function used is: <code>murmurhash3</code> (please tell me why this could be a bad choice or why it is a good choice (briefly)).</p></li>
<li><p>If you want to investigate it more, or even test it, all dependencies and a <code>test_main.c</code> are ready made in the following Github repo: <a href="https://github.com/AymenTM/Harvard-CS50/tree/master/5Pset/Data%20Structures/Hash%20Tables" rel="nofollow noreferrer">click here</a>. Litterally just download and press <code>make</code>.</p></li>
</ul>
<hr>
<p>Please be ruthless, relentless and blunt in your review... like seriously embarrass me, humiliate me. And THANK you in advance for your time.</p>
<p>Also if you have any advice, tips, any good habit I should adopt/start doing, please let me know, I am relatively speaking still a beginner !</p>
<p>Oh and is this kind of commenting of the code encouraged or annoying ?
Also should I comment in functions ? Some say its bad practice...</p>
<hr>
<p><em><strong>Note:</strong> I implement my own standard library functions, so just don't worry about that it is intentional, just assume they work perfectly.</em> </p>
<hr>
<p>Here's the code:</p>
<hr>
<p><strong>Header:</strong> <code>hashtable.h</code></p>
<pre><code>/* * * * * * * * * * * *
========================
HASH TABLE HEADER
========================
* * * * * * * * * * * */
#ifndef FT_HASHTABLE_H
# define FT_HASHTABLE_H
# define HASHCODE(key, buckets) (hash(key, ft_strlen(key)) % buckets)
# define MIN_LOAD_FACTOR 0.0
# define MAX_LOAD_FACTOR 0.7
typedef struct s_entry
{
char *key;
void *value;
struct s_entry *successor;
} t_entry;
typedef struct s_hashtable
{
unsigned int entries;
unsigned int num_buckets;
t_entry **bucket_list;
} t_hashtable;
t_hashtable *hashtable_alloc_table(unsigned int num_entries);
int hashtable_grow_table(t_hashtable **table);
int hashtable_shrink_table(t_hashtable **table);
t_entry *hashtable_fetch_entry(t_hashtable *table, char *key);
int hashtable_insert_entry(t_hashtable **table,
char *key,
void *value);
int hashtable_delete_entry(t_hashtable **table, char *key);
int hashtable_rehash_entry(t_hashtable **table_to,
t_entry **entry);
int hashtable_rehash_table(t_hashtable **table_from,
t_hashtable **table_to);
int hashtable_destroy_table(t_hashtable **table);
int hashtable_set_appropriate_load_factor(t_hashtable **table);
t_entry *entry_create(char *key, void *value);
void entry_free(t_entry **entry);
void bucket_free(t_entry **head);
#endif
</code></pre>
<hr>
<p><strong>Functions:</strong> <code>hashtable.c</code></p>
<pre><code>// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// ======================================================================= //
// HASH TABLE FUNCTION LIBRARY //
// ======================================================================= //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include <stdlib.h>
#include "hashtable.h"
#include "utils.h"
#include "murmurhash3/murmurhash3.h"
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Creates/allocates an empty hash table of size 'num_entries'
and then some (inorder to get to the nearest prime
number).
RETURN VALUES: If successful, returns a pointer to the
hash table. If an error occurs the function
will return a NULL pointer.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
t_hashtable *hashtable_alloc_table(unsigned int num_entries)
{
t_hashtable *table;
unsigned int i;
if (num_entries < 1)
return (NULL);
if (!(table = malloc(sizeof(t_hashtable))))
return (NULL);
num_entries = (unsigned int)ft_find_next_prime(num_entries);
if (!(table->bucket_list =
malloc(sizeof(t_entry*) * num_entries)))
{
free(table);
return (NULL);
}
table->num_buckets = num_entries;
table->entries = 0;
i = 0;
while (i < num_entries)
(table->bucket_list)[i++] = NULL;
return (table);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Inserts a key-value pair into the hash table.
NOTE: in this implementation ownership of 'value' is
taken, that is to say that free'ing of 'value' will be
taken care of, but 'value' MUST be allocated before hand
somewhere in the code, if you fail to do so, upon free'ing
of an entry or the hash table you WILL get a 'bad free'
error.
As for the 'key', a duplicate of it will be made (i.e
memory will be allocated inorder to make a duplicate of
it). The memory will then be free'd.
RETURN VALUES: If successful, returns 0; otherwise -1.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_insert_entry(t_hashtable **table,
char *key,
void *value)
{
t_entry *entry;
unsigned int index;
if (table && *table && key && value)
{
if (hashtable_set_appropriate_load_factor(table) == -1)
return (-1);
if (!(entry = entry_create(key, value)))
return (-1);
index = HASHCODE(key, (*table)->num_buckets);
entry->successor = ((*table)->bucket_list)[index];
((*table)->bucket_list)[index] = entry;
(*table)->entries += 1;
return (0);
}
return (-1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Finds and returns (retrieves) an entry.
RETURN VALUES: If the entry is found, a pointer to the entry is
returned; otherwise a NULL pointer is returned.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
t_entry *hashtable_fetch_entry(t_hashtable *table, char *key)
{
t_entry *cur_entry;
unsigned int index;
if (table && key)
{
index = HASHCODE(key, table->num_buckets);
cur_entry = (table->bucket_list)[index];
while (cur_entry)
{
if (ft_strcmp(cur_entry->key, key) == 0)
return (cur_entry);
cur_entry = cur_entry->successor;
}
}
return (NULL);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Finds and deletes/frees an entry in the hash
table.
RETURN VALUES: If the entry is found, and is successfully
deleted/free'd, the function returns 0;
otherwise the function returns -1.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_delete_entry(t_hashtable **table, char *key)
{
t_entry *prev_entry;
t_entry *cur_entry;
unsigned int index;
if (table && key)
{
index = HASHCODE(key, (*table)->num_buckets);
cur_entry = ((*table)->bucket_list)[index];
while (cur_entry)
{
if (ft_strcmp(cur_entry->key, key) == 0)
{
if (cur_entry == ((*table)->bucket_list)[index])
((*table)->bucket_list)[index] = cur_entry->successor;
else
prev_entry->successor = cur_entry->successor;
entry_free(&cur_entry);
(*table)->entries -= 1;
return (0);
}
prev_entry = cur_entry;
cur_entry = cur_entry->successor;
}
}
return (-1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Deletes/frees the entire hash table
and all the entries contained in it.
RETURN VALUES: If successful returns 0; otherwise -1.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_destroy_table(t_hashtable **table)
{
unsigned int i;
if (table)
{
if (*table)
{
if ((*table)->bucket_list)
{
i = 0;
while (i < (*table)->num_buckets)
{
if (((*table)->bucket_list)[i])
bucket_free(&((*table)->bucket_list)[i]);
i++;
}
free((*table)->bucket_list);
(*table)->bucket_list = NULL;
}
free(*table);
(*table) = NULL;
}
return (0);
}
return (-1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Checks that the current load factor is
neither greater than nor smaller than
the desired max load factor and desired
minimum load factor respectively.
If either is the case, a procedure to
realloc (grow) or dealloc (shrink) the
table will ensue.
If neither is the case, nothing happens.
RETURN VALUES: If nothing happens, or a successful
reallocation or deallocation happens,
0 is returned. If an error occurs -1
is returned.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_set_appropriate_load_factor(t_hashtable **table)
{
if (table && *table)
{
if ((float)(*table)->entries / (float)(*table)->num_buckets
> MAX_LOAD_FACTOR)
{
if (hashtable_grow_table(table) == -1)
return (-1);
return (0);
}
if ((float)(*table)->entries / (float)(*table)->num_buckets
< MIN_LOAD_FACTOR)
{
if (hashtable_shrink_table(table) == -1)
return (-1);
return (0);
}
else
{
return (0);
}
}
return (-1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Grows the hash table by a factor of 2 and then some
(inorder to get to the nearest prime number).
RETURN VALUES: If successful returns 0; otherwise -1.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_grow_table(t_hashtable **table)
{
t_hashtable *new_table;
if (table && *table)
{
new_table = hashtable_alloc_table((*table)->num_buckets * 2);
if (new_table == NULL)
return (-1);
if (hashtable_rehash_table(table, &new_table) == -1)
return (-1);
hashtable_destroy_table(table);
(*table) = new_table;
return (0);
}
return (-1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Shrinks the hash table by half and then some
(inorder to get to the nearest prime number).
RETURN VALUES: If successful returns 0; otherwise -1.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_shrink_table(t_hashtable **table)
{
t_hashtable *new_table;
if (table && *table)
{
if ((*table)->num_buckets > 1)
{
new_table = hashtable_alloc_table((*table)->num_buckets / 2);
if (new_table == NULL)
return (-1);
if (hashtable_rehash_table(table, &new_table) == -1)
return (-1);
hashtable_destroy_table(table);
(*table) = new_table;
return (0);
}
return (0);
}
return (-1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Rehashs one entry in the 'table_to' hashtable.
RETURN VALUES: If successful returns 0; otherwise -1.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_rehash_entry(t_hashtable **table_to, t_entry **entry)
{
unsigned int index;
if (table_to && *table_to && entry && *entry)
{
index = HASHCODE((*entry)->key, (*table_to)->num_buckets);
(*entry)->successor = ((*table_to)->bucket_list)[index];
((*table_to)->bucket_list)[index] = (*entry);
(*table_to)->entries += 1;
return (0);
}
return (-1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Rehashs all the entries in the hashtable
'table_from' into the hashtable 'table_to'.
RETURN VALUES: If successful returns 0; otherwise -1.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
int hashtable_rehash_table(t_hashtable **table_from,
t_hashtable **table_to)
{
t_entry *cur_entry;
t_entry *temp;
unsigned int i;
if (table_from && *table_from && table_to && *table_to)
{
i = 0;
while (i < (*table_from)->num_buckets)
{
if (((*table_from)->bucket_list)[i])
{
cur_entry = ((*table_from)->bucket_list)[i];
while (cur_entry)
{
temp = cur_entry->successor;
if (hashtable_rehash_entry(table_to, &cur_entry) == -1)
return (-1);
cur_entry = temp;
}
((*table_from)->bucket_list)[i] = NULL;
}
i++;
}
}
return (((*table_to)->entries == (*table_from)->entries) ? 0 : -1);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Takes a key and a value and creates an entry out
of them.
NOTE: 'value' MUST have previously been
allocated, otherwise in the free'ing of
an entry, you WILL get a 'bad free' error.
RETURN VALUES: If successful, the function returns a pointer
to the new entry; if an error occurs, it returns
a NULL pointer.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
t_entry *entry_create(char *key, void *value)
{
t_entry *new_entry;
if (key && value)
{
if (!(new_entry = malloc(sizeof(t_entry))))
return (NULL);
new_entry->key = ft_strdup(key);
new_entry->value = value;
new_entry->successor = NULL;
return (new_entry);
}
return (NULL);
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Deletes/frees an entry (this is for use with entries that
have members that were allocated only).
NOTE: if 'entry->value' was not allocated somewhere in
the code, you WILL get a 'bad free' error.
RETURN VALUES: none.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
void entry_free(t_entry **entry)
{
if (entry && *entry)
{
if ((*entry)->key)
free((*entry)->key);
if ((*entry)->value)
free((*entry)->value);
free(*entry);
(*entry) = NULL;
}
}
/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
DESCRIPTION: Deletes/frees the entire bucket (linked
list).
RETURN VALUES: none.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — */
void bucket_free(t_entry **head)
{
t_entry *temp;
if (head)
{
while (*head)
{
temp = (*head);
(*head) = (*head)->successor;
entry_free(&temp);
}
}
}
</code></pre>
<hr>
<p><strong>Testing:</strong> <a href="https://github.com/AymenTM/Harvard-CS50/tree/master/5Pset/Data%20Structures/Hash%20Tables/Testing" rel="nofollow noreferrer">click here!</a></p>
<hr>
<p>Thank you for your time!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T06:45:10.120",
"Id": "403253",
"Score": "4",
"body": "_\"Please be ruthless, relentless and blunt in your review... like seriously embarrass me, humiliate me. \"_ Code Reviews usually aren't meant to satisfy a masochist's lust :3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T10:17:20.643",
"Id": "403279",
"Score": "0",
"body": "@πάνταῥεῖ ῥεῖ ... Lol I didn't mean it that way. I meant like I really am curious to know about any little thing I could improve on, fix. I'm just super eager to improve.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T13:51:15.517",
"Id": "403299",
"Score": "0",
"body": "It would be easier for someone to give you a thorough review if they were able to run your code. Many of your dependencies are not included in the code you have posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T14:19:57.347",
"Id": "403304",
"Score": "0",
"body": "@MikeBorkland Borkland i gave a link to the github repo, all the dependencies are present, as well as a ready made `test_main.c`, you can litterally download the directory, then just hit `make` and you can play around with the `test_main.c` file. [Again here is the github repo](https://github.com/AymenTM/Harvard-CS50/tree/master/5Pset/Data%20Structures/Hash%20Tables)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T13:20:23.840",
"Id": "403415",
"Score": "0",
"body": "Not that easy: `test_main.c:42:9: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘void *’ [-Werror=format=]`. But yes, that's a minor problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T14:01:11.447",
"Id": "403421",
"Score": "0",
"body": "@KIIV Oops meant to write (char*) instead of the (void*) 's, ill update that :3 On my mac it runs fine tho, but your right, it should be changed, thank u."
}
] | [
{
"body": "<p>Few observations:</p>\n\n<ul>\n<li><p>Long comments stating mostly obvious but completely ommits for example information about the <code>hashtable_insert_entry</code> takes ownership of the <code>value</code>, but it makes it's own copy of the <code>key</code>. And you've got memory leak in your test program because of it.\nIt's noted for <code>ft_entry_create</code>, but it's little bit hidden. <br><br>\nMaking the copy of key is fine, it can be local string, or even some internal static buffer (many standard functions without reentrancy support has it), or constant. None of those should be freed.<br><br>\nFreeing the <code>value</code> poointer, that is the question. For example in the C++ none of the STL containers are releasing raw pointers. \n<br></p></li>\n<li><p>Those comments should be in header file. Usual scenario is you'll get header and precompiled library (if it's not the open source).</p></li>\n<li><p>Reimplementing wheel? Why do you need the own dup, strlen and so on? </p></li>\n<li><p>The prime number computation - so many \"optimizations\" and then you are using that weird condition inside loop with the <code>result</code>. You can bet the <code>int nb</code> never will be more than that constant, therefore you cant get i*i biger than that (well, you can, but it'll never get into the loop, as it fails condition <code>i*i < nb</code>). Not to mention something like INT_MAX would be much better than magically loking <code>2147483647</code>.</p></li>\n<li><p>Dependency on <code>HASHCODE</code> macro? But nothing about it's dependency on <code>hash</code> function. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T17:41:21.440",
"Id": "403444",
"Score": "0",
"body": "Couldn't ask for better, thank you for taking the time. I do want to address your observations. So #3, yeah no i would never actually do that, but '42' the school im in makes us redo those funcs, so no worries about those. Obs #5, i dont consider the hash function part of my code so.. yea left it out. About obs #2, that's interesting i didnt know that thank you, so basically your saying to place that info above every prototype of the functions, in the header file ? Obs #1, i see, so your saying, that i need to mention that piece of info, i didnt think of that, and ur right its pretty important"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T17:54:23.347",
"Id": "403447",
"Score": "0",
"body": "Obs #4: Yeah that was pretty stupid on my part :33 and the `2147483647` was really bad and sloppy, should defently be macro'd. @KIIV"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T18:17:51.953",
"Id": "403451",
"Score": "0",
"body": "For observation #1, i added the missing info & in `test_main.c`, fixed the memory leak, thanks for that. I'll take note of observation #2 for next time, and for the future. Observation #4, got rid of the `if (... || result == 2147483647)`, and will macro from now on those things and stop being lazy. For observation #5, i added below every `HASHCODE()` the `hash()` dep. And on top of all that, a big thanks, again. :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T18:22:30.950",
"Id": "403452",
"Score": "0",
"body": "I have a question, you know how my implementation does this: \"__the `hashtable_insert_entry` takes ownership of the value, but it makes it's own copy of the key__\" ; should it be like that or should it be different ? Is that the correct way of doing it, how would you make it ? or what's the convention; from what i've seen, people make duplicates of the key and some make a copy of the value if it is a `char *`, but obviously if its a `void *` you can't do that, so they just take ownership of it.. right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T18:25:39.623",
"Id": "403453",
"Score": "0",
"body": "@AymenTM How do I know? I used the valgrind to check memory leaks and it showed to me some lost memory related to the ft_strdup and hashtable_insert_entry, so I take a look to the code and the value is directly assigned into the item, but key is duplicated by another ft_strdup. The taking ownership means your library takes over the responsibility for freeing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T18:37:39.927",
"Id": "403455",
"Score": "0",
"body": "First time i hear of 'owernship', you taught me something new [√]. As for valgrind, i didn't test the `test_main.c` with it, I should've !"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T14:11:19.153",
"Id": "208823",
"ParentId": "208744",
"Score": "1"
}
},
{
"body": "<p>Overall, this seems fairly well written. But you said to be relentless and blunt, so here's what I really think! </p>\n<blockquote>\n<p>If you want to investigate it more, or even test it, all dependencies and a test_main.c are ready made in the following Github repo: click here. Litterally just download and press make.</p>\n</blockquote>\n<p>Ugh. This seems to me to straddle the line in the <a href=\"https://codereview.stackexchange.com/help/how-to-ask\">rules for the site</a>:</p>\n<blockquote>\n<p>Be sure to embed the code you want reviewed in the question itself; you can leave supporting, but non-essential, code in links to other sites.</p>\n</blockquote>\n<p>I wouldn't consider missing <code>#includes</code> to be "supporting but non-essential code". If your actual code is separated into a header and a source file, you should post them both separately here rather than inlining the header and omitting the includes.</p>\n<h1>Style</h1>\n<p>I have to say that while I am one of these people who likes to line things up to some degree, you've gone overboard with aligning things, in my opinion. For me, it's actually harder to read with your formatting. I don't think that every variable and function declaration throughout the code needs the same spacing. Furthermore, the spacing on functions that go longer than you like makes it look like another function declaration on the next line, but an invalid one. If you're going to wrap the arguments, it's tradition to either indent them one level, or line them up with the function arguments on the previous line.</p>\n<p>You should avoid declaring variables until you need them. If a person reading your code wants to know what type a variable is, it's easier to find if it's close to its first use. Likewise, if you want to change a type, it's easier to do if it's near where it's used.</p>\n<h1>Naming</h1>\n<p>I think your function names could be shorter. There's a lot of redundant words in their names. For example, <code>hashtable_alloc_table()</code> could just be <code>hashtable_alloc()</code>, and <code>hashtable_insert_entry()</code> could just be <code>hashtable_insert()</code>. (What else would you be inserting into a hash table? A dinner plate?)</p>\n<p>Adding <code>t_</code> to the front of every type is unnecessary. Types are obviously types from the context in which they're used. If you must add something, make it a suffix of <code>_t</code> like every other C programmer so it's consistent. Also, what's the purpose of giving <code>struct</code> names a prefix of <code>s_</code>? Are you ever going to write the type as <code>struct s_whatever</code> instead of <code>t_whatever</code>? If not, just give it the same name, so it's:</p>\n<pre><code>typedef struct foo {\n // fields\n} foo;\n</code></pre>\n<p>In <code>hashtable_alloc_table()</code>, the argument is called <code>size</code>, but the units aren't clear. My assumption on reading the declaration was that it was going to be in bytes. But it's actually the number of entries to hold. As such, I would name it <code>numEntries</code> rather than <code>size</code> because <code>size</code> is ambiguous.</p>\n<p>The difference between <code>hashtable_dealloc_table()</code> and <code>hashtable_destroy_table()</code> is surprising given their names. It seems like <code>hashtable_dealloc_table()</code> should be renamed to <code>hashtable_shrink_table()</code> or something more in line with what it's doing.</p>\n<p>The name <code>hashtable_check_load_factor()</code> is also misleading. I wouldn't expect a function which is named "check " to change anything. I would call it something like <code>hashtable_set_appropriate_load_factor()</code> or something like that so that a caller knows that it may change the hash table.</p>\n<p>Finally, what does the prefix <code>ft</code> stand for? It's not at all clear from the code you posted. A comment about its meaning somewhere might be appropriate.</p>\n<h1>Memory Leak in <code>hashtable_alloc_table()</code></h1>\n<p>There's a memory leak in 'hashtable_alloc_table()<code>. If the table is allocated, but the bucket list isn't, it returns </code>NULL`, but it never frees the table. That memory is now considered in-use by the OS making it unavailable to be re-used.</p>\n<h1>Redundancy</h1>\n<p>Why have the caller pass in a pointer to a pointer to <code>hashtable_realloc_table()</code>, and then return a pointer to a hash table? You should do one or the other. A pointer to a pointer allows you to change the value of the pointer the caller uses, so you don't need to also return the new one. You can simply delete the old one and replace it with the new one.</p>\n<h1>Comments</h1>\n<p>I think you have too much info in your function comments. Why should I care which functions you call from that function? I shouldn't need to know that info. I shouldn't need to know which headers include the functions that any given function depends on. They should simply be included at the top of the file (which they aren't here).</p>\n<p>The problem with comments is that they can get out of date with the code. That has happened with your <code>hashtable_realloc_table()</code> function. It says that it "Grows the hash table by half", but it actually doubles the hash table size. Perhaps it used to only grow it by half, but now it doubles it?</p>\n<p>I have no idea what "search tags" are in this context, and it seems unnecessary. I either already know what to search for or I don't. If I search for the function name, I'll find the function definition, so I don't need the tag.</p>\n<h1>Standard Library</h1>\n<p>You say:</p>\n<blockquote>\n<p><em>Note: I implement my own standard library functions</em></p>\n</blockquote>\n<p><b>Oh <i>Heck</i> no!</b> The original implementors of the standard library <a href=\"https://en.wikipedia.org/wiki/C_standard_library#Concepts,_problems_and_workarounds\" rel=\"nofollow noreferrer\">made all kinds of mistakes in how they designed</a> the standard library functions. Your implementations likely have all those same mistakes plus a whole bunch more due to the fact that you're a beginner at this. It's an interesting exercise to learn the language, but you shouldn't use them in real code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T06:27:24.007",
"Id": "403490",
"Score": "0",
"body": "First of all, @user1118321 , God bless you, this is a great review! For the first remark, I separated the files, and add the includes, was lazy on my part. For remark #2, the \"**Style**\", I did not mention but, **I am following (42's) my school's mandatory style**, that's why everything is insanely aligned, also why all variables are at the top of functions and separated by 1 line, although I totally see what your saying and it absolutely makes sense; as for the wrapping of function arguments, I changed it to the way you suggested, I actually prefer it, let me know if I did it wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T06:35:36.270",
"Id": "403492",
"Score": "0",
"body": "Remark #4, \"**Naming**\"; your right, my function names are terribly long, I was thinking of just '`ht_`' instead of '`hashtable_`' and also, what you said makes sense, this is just a preference of mine to be terribly explicity, even tho, yes it is pretty dumb obvious what a hashtable inserts, I did leave the names for this one. Next, the '`t_`' & '`s_`' are just my school's mandatory style for structs and typedefs, so yeah, would defently do the '`_t`' and ommit the '`s_`', in my own code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T06:44:45.613",
"Id": "403497",
"Score": "0",
"body": "Next, the `hashtable_alloc_table()` variable `size` is yes pretty damn ambigious, changed it to `num_entries`, thank you. Next, the `hashtable_dealloc_table() ` makes no sense your right, + not very explicative of what it does different from `_destroy_table()`, renamed both the `hashtable_realloc_table()` & `hashtable_dealloc_table()` to `hashtable_grow_table()` & `hashtable_shrink_table()`. Next, the \"`ft_`\" is again just (42's) my school's convention to name functions, I should mention that in the post commentary up top."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T06:48:42.423",
"Id": "403498",
"Score": "0",
"body": "oops, Naming was remark 3, i'll just keep going with it; Remark #5, \"**Memory Leak**\", yep that was a mistake on my part, big time, thank you, fixed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T06:51:08.050",
"Id": "403499",
"Score": "0",
"body": "Remark #6: \"**Comments**\". Got rid of the dependencies and the search tags & fixed the outdated comment. And yes it's pretty damn easy to forget to update one of the comments. Will take into consideration for the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T06:53:24.403",
"Id": "403500",
"Score": "0",
"body": "Remark #7: \"**Standard Library**\". This again is just something (42) my school makes us do, cuz we're not allowed to use standard library functions, and yes it is an exercice to learn the language; I would never re-invent the wheel, and besides standard library functions, are far superior to what i could do."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T01:24:51.403",
"Id": "208845",
"ParentId": "208744",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T06:12:24.397",
"Id": "208744",
"Score": "1",
"Tags": [
"c",
"library",
"hash-map"
],
"Title": "Quick & Simple Hash Table Implementation in C"
} | 208744 |
<p>I have a code where the goal is to give score to strings based on how much score certain substrings are worth (including repeating substrings).</p>
<p>The way my code (which is based on the <a href="https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm" rel="nofollow noreferrer">Aho-Corasick algorithm</a>) works is:</p>
<ol>
<li>Creating a tree-like data structure where each node represents one prefix of a string (or the full string, along with the data needed to calculate score for this match) from the set of substrings being searched for, with some extra links pointing from some of the nodes <code>a</code> to a node that represents the largest suffix of the string that <code>a</code> represents, to avoid backtracking.</li>
<li>The search function uses this structure to find all the substrings (not remembering the matched results, only adding score if a match is found) with near O(N) complexity in most cases.</li>
</ol>
<p>The performance bottleneck of my code is <code>interlink()</code> which creates these "extra links" in the tree, everything else works reasonably fast, any suggestions for how to improve this function's time complexity or merge it with the tree creation process (while reducing time complexity) are greatly appreciated.</p>
<p>The input strings for <code>createTree()</code> and <code>scan()</code> are expected to contain only lowercase a-z characters, and they can get as long as millions of chars.</p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
public class Tree{
private int[] scores;
private int[] scoreIndexes;
private Tree[] branches = new Tree[26];
private Tree link;
private Tree(){}
/**
* @param strs - The substrings this tree will search for.
* @param scores - An array of equal length to <b>strs</b> where each <i>scores[i]</i> represents how much score <i>strs[i]</i> is worth.
*/
public Tree(String[] strs, int[] scores){
this.scores = scores;
Tree currentNode;
String str;
int strLength;
for(int i = 0; i < strs.length; i++){
currentNode = this;
str = strs[i];
strLength = str.length();
for(int c = 0; c < strLength; c++){
int idx = str.charAt(c) - 'a';
if(currentNode.branches[idx] == null)
currentNode.branches[idx] = new Tree();
currentNode = currentNode.branches[idx];
if(strLength == c + 1)
currentNode.addScoreIndex(i);
}
}
interlink();
}
/**
* @param str - The string to be scanned.
* @param minIdx - The first index from which scores from the tree's <b>scores</b> array are counted towards the total value of <b>str</b>.
* @param maxIdx - The last index from which scores from the tree's <b>scores</b> array are counted towards the total value of <b>str</b>.
* @return - The score <b>str</b> is worth.
*/
public long scan(String str, int minIdx, int maxIdx){
long score = 0L;
ArrayList<Tree> nodes = new ArrayList<Tree>();
int branchIndex;
Tree node;
for(int index = 0; index < str.length(); index++){
branchIndex = str.charAt(index) - 'a';
for(int e = 0; e < nodes.size(); e++) // advance nodes to next char
nodes.set(e, nodes.get(e).branches[branchIndex]);
while(nodes.remove(null));
if(nodes.isEmpty()){ // if no nodes left, continue the search from first node
nodes.add(this.branches[branchIndex]);
nodes.remove(null);
}
for(int e = 0; e < nodes.size(); e++){
node = nodes.get(e);
if(node.link != null)
if(!nodes.contains(node.link))
nodes.add(node.link);
if(node.scoreIndexes != null)
for(int x = 0; x < node.scoreIndexes.length; x++)
if(node.scoreIndexes[x] >= minIdx && node.scoreIndexes[x] <= maxIdx)
score += scores[node.scoreIndexes[x]];
}
}
return score;
}
/** Creates links in the tree, which are used to avoid backtracking in <b>scan(...)</b>. */
private void interlink(){
int[] path = new int[1];
for(int i = 0; i < 26; i++)
if(branches[i] != null){
path[0] = i;
branches[i].interlinkRecursive(this, path);
}
}
private void interlinkRecursive(Tree mainTree, int[] path){
int pathLength = path.length;
int[] newPath = null;
for(int i = 0; i < 26; i++)
if(branches[i] != null){
if(newPath == null)
newPath = Arrays.copyOf(path, pathLength + 1);
newPath[pathLength] = i;
branches[i].interlinkRecursive(mainTree, newPath);
}
if(pathLength < 2) return;
Tree node;
for(int k = 1; k < pathLength; k++){
node = mainTree;
for(int c = k; c < pathLength; c++){
node = node.branches[path[c]];
if(node == null) break;
}
if(node != null){
link = node;
break;
}
}
}
private void addScoreIndex(int index){
if(scoreIndexes == null) scoreIndexes = new int[1];
else scoreIndexes = Arrays.copyOf(scoreIndexes, scoreIndexes.length + 1);
scoreIndexes[scoreIndexes.length - 1] = index;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T20:17:03.717",
"Id": "403557",
"Score": "0",
"body": "Your code does not seem to work. I always get an `ArrayIndexOutOfBoundsException` when I try to run it. It would also be good to know how the class should be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T20:34:34.703",
"Id": "403558",
"Score": "0",
"body": "`createTree()`'s first input is the substrings to be found, and the second input must be of equal length - representing the score each substring is worth. `scan()`'s inputs are: `str` is the string to search substrings in. the other two are the min and max index to count score for in the substrings array, you can just use `minIdx = 0; maxIdx = strs.length;` for testing. @aventurin"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T21:08:19.817",
"Id": "403559",
"Score": "0",
"body": "If the `path` parameter of `interlink` can become long then the nested for-loop's O(n^2) time complexity might be the cause of the performance degradation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T21:10:01.543",
"Id": "403560",
"Score": "0",
"body": "@aventurin This is indeed the cause of the performance degradation, my question is how to improve this time complexity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T21:29:33.470",
"Id": "403561",
"Score": "0",
"body": "I don't understand why you have the outer loop. Sure you need it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T21:54:57.133",
"Id": "403564",
"Score": "0",
"body": "@aventurin I need it because I'm creating links to **suffixes** and not **prefixes**, this means I need to go through different nodes in the tree if the first (longest) suffix isn't found."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T22:11:50.363",
"Id": "403566",
"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 you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T22:13:04.480",
"Id": "403567",
"Score": "0",
"body": "@SimonForsberg I did not incorporate answers, only other changes I made since posting the code (which are not directly related to my question), as well as adding documentation so people know how to test it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T22:18:25.733",
"Id": "403569",
"Score": "0",
"body": "@potato Okay, I just acted automatically as it contained several changes. I rolledback my rollback now. Keep on coding :)"
}
] | [
{
"body": "<p>Thanks for sharing your code.</p>\n\n<p>Note that what follows are guesses because I can't run your code, but might gives you an idea for better performance.</p>\n\n<hr>\n\n<p>First thing in your <code>interlink</code> method you call <code>path.length()</code> a few times, the Sun implementation is <strong>O(1)</strong> but it still adds function calls for no good reason (unless the compiler is smart enough to change it itself). So I'd do something like that:</p>\n\n<pre><code>private void interlink(Tree mainTree, String path){\n int pathLength = path.length(); // compute it once here\n for(int i = 0; i < branches.length; i++){\n if(branches[i] != null)\n branches[i].interlink(mainTree, path + (char)(i + 'a'));\n }\n if(pathLength < 2) return;\n Tree node;\n for(int k = 1; k < pathLength; k++){\n\n node = mainTree;\n for(int c = k; c < pathLength; c++){\n node = node.branches[path.charAt(c) - 'a'];\n if(node == null)\n break;\n }\n if(node != null){\n link = node;\n break;\n }\n }\n}\n</code></pre>\n\n<p>I think it also is a good things to keep in mind in general as function calls are sometimes expensives.</p>\n\n<p>Another thing is you could use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\">StringBuilder</a> to do the String concatenation.</p>\n\n<pre><code>for(int i = 0; i < branches.length; i++){\n if(branches[i] != null)\n builder = new StringBuilder();\n builder.append(path);\n builder.append((char)(i + 'a'));\n branches[i].interlink(mainTree, builder.toString());\n}\n</code></pre>\n\n<p>But the overhead of creating a new <code>StringBuilder</code> inside the loop might kill the performance even more. </p>\n\n<p>Last thing I see is <code>(char)(i + 'a')</code>. Instead of casting the char, if you had an array of char like:</p>\n\n<pre><code>char[] alphabet = {'a', 'b', 'c' ....};\n</code></pre>\n\n<p>You could use it like</p>\n\n<pre><code>for(int i = 0; i < branches.length; i++){\n if(branches[i] != null)\n branches[i].interlink(mainTree, path + alphabet[i]);\n}\n</code></pre>\n\n<p>(or with the <code>StringBuilder</code> version)</p>\n\n<p>And maybe make it a <code>static</code> member of your class <code>Tree</code> to not have a separate copy of it on all instance of your <code>Tree</code>.</p>\n\n<hr>\n\n<p>All of those above are cheap tricks that probably won't make your program run ten times as fast, the biggest gain would be to call <code>interlink</code> less but I cannot see how to do that right now. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T18:53:29.457",
"Id": "403359",
"Score": "1",
"body": "Thanks for the suggestions, making a static list of chars and storing the value of `path.length()` made a little difference, but overall the performance is still about the same. My problem is in the algorithm design, need to find a better way to create these links with less time complexity, maybe somehow incorporate it into the process of constructing the tree in `createTree()`, improving time complexity is the only thing that can make a big difference in performance here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T07:21:28.440",
"Id": "403387",
"Score": "1",
"body": "Creation of a local StringBuilder is exactly what happens under the hood when you perform string catenation with \"+\". Thus the code you write in the StringBuilder paragraph is equivalent to the original `path + (char)(i + 'a')`. You might however get rid of the repeated object instantiation by creating a StringBuilder once and reusing it (setLength(0)). (Though I doubt that this has any serious effect, as object creation is really cheap nowadays.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T15:37:56.463",
"Id": "403433",
"Score": "0",
"body": "Thanks @mtj I totally overlooked `setLength(0)` to reset the StringBuilder. And good to know that string concatenation is done automatically"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T17:05:34.723",
"Id": "403442",
"Score": "0",
"body": "I replaced the `path` string with an int array, using it in such a way that I only need to copy it once in each node instead of once for every branch of that node, and it doesn't require subtracting `'a'` from the chars to get the index."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:02:17.080",
"Id": "208774",
"ParentId": "208746",
"Score": "1"
}
},
{
"body": "<p>I solved my problem, the trick was to create the links row by row in the tree so I can use the links in the higher rows to find the largest suffix faster. Now it's complexity is O(N). Here is the final code: (also includes some other changes I made like adding support for bigger numbers)</p>\n\n<pre><code>import java.math.BigInteger;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\npublic class Tree{\n private int[] scores;\n private int[] scoreIndexes;\n private Tree[] branches = new Tree[26];\n private Tree link, parent, shortcut;\n\n private Tree(){}\n /**\n * @param strs - The substrings this tree will search for.\n * @param scores - An array of equal length to <b>strs</b> where each <i>scores[i]</i> represents how much score <i>strs[i]</i> is worth.\n */\n public Tree(String[] strs, int[] scores){\n this.scores = scores;\n Tree currentNode;\n String str;\n int strLength;\n\n for(int i = 0; i < strs.length; i++){\n currentNode = this;\n str = strs[i];\n strLength = str.length();\n\n for(int c = 0; c < strLength; c++){\n int idx = str.charAt(c) - 'a';\n if(currentNode.branches[idx] == null){\n currentNode.branches[idx] = new Tree();\n currentNode.branches[idx].parent = currentNode;\n }\n currentNode = currentNode.branches[idx];\n if(strLength == c + 1)\n currentNode.addScoreIndex(i);\n }\n }\n interlink();\n }\n\n /**\n * @param str - The string to be scanned.\n * @param minIdx - The first index from which scores from the tree's <b>scores</b> array are counted towards the total value of <b>str</b>.\n * @param maxIdx - The last index from which scores from the tree's <b>scores</b> array are counted towards the total value of <b>str</b>.\n * @return - The score <b>str</b> is worth.\n */\n public BigInteger scan(String str, int minIdx, int maxIdx){\n BigInteger score = new BigInteger(\"0\");\n //long score = 0;\n Tree currentNode = this;\n Tree nextNode;\n int branchIndex;\n int strLength = str.length();\n for(int c = 0; c < strLength; c++){\n branchIndex = str.charAt(c) - 'a';\n\n while((nextNode = currentNode.branches[branchIndex]) == null){\n if(currentNode == this){\n if(++c == strLength) return score;\n branchIndex = str.charAt(c) - 'a';\n }\n else currentNode = currentNode.link;\n }\n currentNode = nextNode;\n\n while(nextNode != null){\n score = score.add(new BigInteger(Long.toString(nextNode.getScore(scores, minIdx, maxIdx))));// += nextNode.getScore(scores, minIdx, maxIdx);\n nextNode = nextNode.shortcut;\n }\n }\n return score;\n }\n\n private void interlink(){\n\n Queue<Tree> queue = new LinkedList<>();\n queue.add(this);\n Tree node;\n while(!queue.isEmpty()){\n node = queue.poll();\n for(int i = 0; i < branches.length; i++)\n if(node.branches[i] != null){\n node.branches[i].setLinks(i);\n queue.add(node.branches[i]);\n }\n }\n }\n private void setLinks(int index){\n Tree currentNode = parent;\n while(link == null){\n if(currentNode.parent == null){\n link = currentNode;\n }\n else{\n currentNode = currentNode.link;\n link = currentNode.branches[index];\n }\n }\n shortcut = link;\n while(shortcut != null){\n if(shortcut.scoreIndexes != null)\n break;\n shortcut = shortcut.link;\n }\n }\n\n private void addScoreIndex(int index){\n if(scoreIndexes == null) scoreIndexes = new int[1];\n else scoreIndexes = Arrays.copyOf(scoreIndexes, scoreIndexes.length + 1);\n scoreIndexes[scoreIndexes.length - 1] = index;\n }\n\n private long getScore(int[] scores, int minIdx, int maxIdx){\n long score = 0;\n if(scoreIndexes != null)\n for(int x = 0; x < scoreIndexes.length; x++)\n if(scoreIndexes[x] >= minIdx && scoreIndexes[x] <= maxIdx)\n score += scores[scoreIndexes[x]];\n return score;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T10:19:08.637",
"Id": "208993",
"ParentId": "208746",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208993",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T07:18:22.907",
"Id": "208746",
"Score": "2",
"Tags": [
"java",
"algorithm",
"strings",
"complexity"
],
"Title": "Substrings search (Aho-Corasick algorithm)"
} | 208746 |
<p>I'm recently working on a project that involves animation in the background. It works well on desktop but performance drops drastically on mobile. I'm using Paper.js to import a svg and animate it. This is the <a href="https://codepen.io/julian-gaventure/pen/yqjdQb" rel="nofollow noreferrer">demo</a>.</p>
<pre><code>paper.project.importSVG(svg, function(item) {
var moveSpeed = 70;
var movementRadius = 15;
var boundingRec = item.bounds;
var lines = [];
var circles = [];
/*
Arrange lines and circles into different array
*/
$.each(item.getItems({
recursive: true,
}), function(index, item) {
if (item instanceof paper.Shape && item.type == 'circle') {
item.data.connectedSegments = [];
item.data.originalPosition = item.position;
circles.push(item);
}
if (item instanceof paper.Path) {
lines.push(item);
}
});
/*
Loop through all paths
Checks if any segment points is within circles
Anchors the point to the circle if within
*/
$.each(lines, function(pathIndex, path) {
$.each(path.segments, function(segmentIndex, segment) {
$.each(circles, function(circleIndex, circle) {
if (circle.contains(segment.point)) {
circle.data.connectedSegments.push( segment.point );
return false;
}
});
});
});
/*
Animate the circles
*/
$.each(circles, function(circleIndex, circle) {
var originalPosition = circle.data.originalPosition;
var radius = circle.radius * movementRadius;
var destination = originalPosition.add( paper.Point.random().multiply(radius) );
circle.onFrame = function() {
while (!destination.isInside(boundingRec)) {
destination = originalPosition.add( paper.Point.random().multiply(radius) );
}
var vector = destination.subtract(circle.position);
circle.position = circle.position.add(vector.divide(moveSpeed));
// move connected segments based on circle
for (var i = 0; i < circle.data.connectedSegments.length; i++) {
circle.data.connectedSegments[i].set({
x: circle.position.x,
y: circle.position.y,
});
}
if (vector.length < 5) {
destination = originalPosition.add( paper.Point.random().multiply(radius) );
}
}
});
});
</code></pre>
<p>A single SVG animation alone is causing the CPU usage to go up to 90% on mid-tier mobile devices and it go to the point that the interface becomes unusable. Any advice or help is much appreciated.</p>
| [] | [
{
"body": "<p>This might be a small improvement but there is no need to check that <code>destination</code> is inside <code>boundingRec</code> on each frame, you just need to check it when creating a new destination.</p>\n\n<p>Here is a <a href=\"https://codepen.io/sasensi/pen/pQqPVd\" rel=\"nofollow noreferrer\">modified codepen</a> in which destination creation is done in a separated function, removing the unneeded check:</p>\n\n<pre><code>function createNewDestination(originalPosition, radius) {\n var destination = null;\n while (!destination || !destination.isInside(boundingRec)) {\n destination = originalPosition.add(paper.Point.random().multiply(radius));\n }\n return destination;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:54:00.350",
"Id": "403277",
"Score": "0",
"body": "Thanks for the suggestion. Added the improvement that you've suggested, but i'm still getting pretty low frame rates (around 20fps) on mobile. I'm thinking of implementing offscreen canvas in web workers. Problem is, offscreen canvas is still a experimental technology."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T09:27:55.670",
"Id": "208754",
"ParentId": "208748",
"Score": "2"
}
},
{
"body": "<h2>SVG for animation is Bad :(</h2>\n\n<p>SVG is a very difficult medium to use for animation as it can incur huge overheads when you use seamingly common sense structure.</p>\n\n<p>I must also point out that many of the SVG frameworks such as <a href=\"http://paperjs.org/about/\" rel=\"nofollow noreferrer\">Paper.js</a> add to the problem with poor code and an apparent indifference to the need to create performant interfaces.</p>\n\n<h2>To review your code</h2>\n\n<p>As this is a review I must review your code.</p>\n\n<ul>\n<li><p>There is no need to use jQuery as the standard DOM API's do it all and much faster.</p></li>\n<li><p>Use constant declarations for variables that don't change, eg <code>var lines = [];</code> should be <code>const lines = [];</code> and <code>var moveSpeed = 70</code> should be <code>const moveSpeed = 70;</code></p></li>\n<li><p>You have a random search for each point to test if it is inside the bounds. If you have a point outside the bounds by a distance greater than the radius, this loop may run forever trying to find a random point that is inside the bounds.</p>\n\n<p>It is non deterministic search, with a worst case complexity of O(Infinity) (something that computers just do not do well LOL)</p>\n\n<p><code>while (!destination.isInside(boundingRec)) {\n destination = originalPosition.add(paper.Point.random().multiply(radius));\n}</code></p>\n\n<p>A much better deterministic approach is to test for the bounds, and if not in bounds find the closest point that is and set the point to that. this reduces the worst case complexity to O(1) which computers do very well. (see example code)</p></li>\n</ul>\n\n<p>Apart from that your code is well written.</p>\n\n<hr>\n\n<h2><a href=\"http://paperjs.org/about/\" rel=\"nofollow noreferrer\">Paper.js</a></h2>\n\n<p>I did first write this answer assuming that the content was all SVG but a second look and I see that you are rendering SVG to a canvas via paper.js. </p>\n\n<p>I personal think paper.js is a slow and poorly coded framework. Its core (low level) functions are bloated with overheads that far exceed the time to perform the basic functions purpose.</p>\n\n<p>Rather than list the miles of overhead you add using paper.js I just compared your code to a rewrite without frameworks and using the canvas only avoiding SVG as a image source.</p>\n\n<p>I then compared the run time via chrome's performance recorder in dev tools.</p>\n\n<p>The code using paper.js took 6.89ms to render a frame.</p>\n\n<p>The rewrite took 0.53ms to do the same.</p>\n\n<h2>Canvas size</h2>\n\n<p>I dont know how you are sizing the canvas for the handheld devices, but make sure that they match the screen resolution and do not use a large canvas that you then size to fit as you can seriously kill performance that way.</p>\n\n<p>The canvas must not be larger than as follows or you use too much RAM and end up rendering pixels that are not seen.</p>\n\n<pre><code>canvas.width = innerWidth;\ncanvas.height = innerHeight;\n</code></pre>\n\n<h2>Rewrite</h2>\n\n<p>So I will just go over the rewrite.</p>\n\n<p>For your code there are 5 basic parts</p>\n\n<ol>\n<li>Define the points and lines</li>\n<li>Move the points</li>\n<li>Render the lines</li>\n<li>Render the circles</li>\n<li>Animate and present the content</li>\n</ol>\n\n<h2>Define the points</h2>\n\n<p>As we are not going to use the SVG we need to define the points in javascript.</p>\n\n<p>I have extracted the circles (AKA verts)\nI am not going to process the data you have and just assume that lines are between a vert and the 6 closest verts. Thus we define the verts and create a function to find the lines.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const numberLines = 6; // Number of lines per circle\nconst verts = [ \n {id :1 , x: 30.7, y: 229.2 },\n {id :2 , x: 214.4, y: 219.6},\n {id :3 , x: 278.4, y: 186.4},\n {id :4 , x: 382.5, y: 132.5},\n {id :5 , x: 346.8, y: 82 },\n {id :6 , x: 387.9, y: 6.7 },\n {id :7 , x: 451.8, y: 60.8 },\n {id :8 , x: 537.0, y: 119.9},\n {id :9 , x: 545.1, y: 119.9},\n {id :9 , x: 403.5, y: 122.1},\n {id :10 , x: 416.3, y: 130 },\n {id :11 , x: 402.6, y: 221.4},\n {id :12 , x: 409.9, y: 266.4},\n {id :13 , x: 437.1, y: 266.8},\n {id :14 , x: 478.1, y: 269.6},\n {id :15 , x: 242.6, y: 306.1},\n {id :16 , x: 364.0, y: 267 },\n {id :17 , x: 379.1, y: 310.7},\n {id :18 , x: 451.2, y: 398.9},\n {id :19 , x: 529.6, y: 377.9},\n {id :20 , x: 644.8, y: 478.3},\n {id :21 , x: 328.3, y: 324.5},\n {id :22 , x: 314.4, y: 364.3},\n {id :23 , x: 110.2, y: 327.8},\n {id :24 , x: 299.1, y: 219.6},\n {id :25 , x: 130.4, y: 218.1},\n {id :26 , x: 307.4, y: 298.4},\n {id :27 , x: 431.3, y: 360.1},\n {id :28 , x: 551.7, y: 414.4},\n {id :29 , x: 382.5, y: 239.7},\n];\nconst line = (p1, p2) => ({p1, p2});\nvar lines = new Map(); // is var as this is replaced with an array after finding near verts\nfunction findClosestVertInDist(vert,min, max, result = {}) {\n const x = vert.x, y = vert.y;\n result.minDist = max;\n result.closest = undefined;\n for (const v of verts) { \n const dx = v.x - x;\n const dy = v.y - y;\n const dist = (dx * dx + dy * dy) ** 0.5;\n if (dist > min && dist < result.minDist) {\n result.minDist = dist;\n result.closest = v;\n }\n }\n return result;\n}\n// this is a brute force solution. \nfunction createLines() {\n var hash;\n lines.length = 0; \n const mod2Id = verts.length; // to get unique hash for a line\n const closeVert = {}\n for (const v of verts) { \n closeVert.minDist = 0;\n for (let i = 0; i < numberLines; i++) {\n findClosestVertInDist(v, closeVert.minDist, Infinity, closeVert);\n if(closeVert.closest) { // if you have less than 6 verts you need this test\n if (v.id < closeVert.closest.id) {\n hash = closeVert.closest.id * mod2Id + v.id;\n } else {\n hash = closeVert.closest.id + v.id * mod2Id;\n }\n lines.set(hash,line(v,closeVert.closest));\n } else {\n i--; \n }\n }\n }\n lines = [...lines.values()]; // Dont need the map so replace with array of lines\n verts.forEach(v => { // verts dont need the id but need an origin so add \n // the relevant data\n v.ox = v.x; // the verts origin\n v.oy = v.y;\n v.dx = v.x; // the destination to move to\n v.dy = v.y;\n v.moveSpeed = Math.random() * (moveSpeedMax - moveSpeedMin) + moveSpeedMin;\n v.move = 1; // unit value how far vert has moved to new point,\n // 0 is at start, 1 is at destination\n delete v.id; // remove the id\n }); \n\n}\ncreateLines();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>After this is run you get a data structure very similar to the SVG. A set of points <code>verts</code> and a set of lines <code>lines</code> that reference points.</p>\n\n<h2>Rendering</h2>\n\n<p>The canvas <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D\" rel=\"nofollow noreferrer\">2D API</a> is very easy to use and has functions to draw lines and circles. It can render content as paths (very similar to SVG <a href=\"https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path\" rel=\"nofollow noreferrer\">path element</a>) and uses the GPU and is just as fast (if not faster on some browsers than the SVG renderer)</p>\n\n<p>So to create the element and render to it we need the following</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Script is placed after the canvas element via load event, \n\n// the 2D API called context or abbreviated as ctx\n// You may want to query the DOM with document.getElementById(\"canvas\") but not needed\nconst ctx = canvas.getContext(\"2D\"); \ncanvas.width = innerWidth;\ncanvas.height = innerHeight;\n\nMath.PI2 = Math.PI * 2; // create a 360 radians constant\n// Define the styles\nconst lineStyle = {\n lineWidth : 1,\n strokeStyle : \"#FFFFFF88\",\n}\nconst circleStyle = {\n fillStyle : \"cyan\",\n}\nconst circleRadius = 2.5;\nconst moveDist = 70;\n// min and max vert speeds so points donty all change direction at once.\nconst moveSpeedMax = 1 / 120; // unit speed (at 60fps this moves to destination in two seconds)\nconst moveSpeedMin = 1 / 240; // unit speed (at 60fps this moves to destination in four seconds)\n\n\n\n\nfunction drawLines(ctx, lines, style) { // ctx where to draw, lines what to draw\n Object.assign(ctx, style);\n // start a new 2D path \n ctx.beginPath();\n for (const line of lines) {\n ctx.moveTo(line.p1.x, line.p1.y);\n ctx.lineTo(line.p2.x, line.p2.y);\n }\n // the path has been defined so render it in one go.\n ctx.stroke();\n}\nfunction drawCircles(ctx, verts, radius, style) { // ctx where to draw, verts what to draw\n // radius (say no more)\n // and style\n Object.assign(ctx, style);\n ctx.beginPath();\n for (const vert of verts) {\n // to prevent arcs connecting you need to move to the arc start point \n ctx.moveTo(vert.x + radius, vert.y);\n ctx.arc(vert.x, vert.y, radius, 0, Math.PI2);\n }\n // the path has been defined so render it in one go.\n ctx.fill();\n}\n\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!-- replaces the SVG element -->\n<canvas id=\"canvas\" width = \"642\" height = \"481\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Animation</h2>\n\n<p>As we are animating the content we need to make sure that what we render is presented correctly and in sync with the display. All browsers provide a special callback event via <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\" rel=\"nofollow noreferrer\"><code>requestAnimationFrame</code></a> that lets you make changes to the DOM that will only be presented on the next display refresh.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>requestAnimationFrame(update); // starts the animation\nfunction update(){\n ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n animateCircles(verts, ctx.canvas); // animate the verts\n drawLines(ctx, lines, lineStyle);\n drawCircles(ctx, verts, circleRadius, circleStyle);\n\n // All done request the next frame\n requestAnimationFrame(update); \n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function animateCircles(verts, canvas){\n for(const vert of verts){\n vert.move += vert.moveSpeed;\n if (vert.move >= 1) { // point at dest so find a new random point\n // using polar coords to randomly move a point \n const dir = Math.random() * Math.PI2; \n const dist = Math.random() * moveDist;\n vert.ox = vert.dx; // set new origin\n vert.oy = vert.dy; \n let x = vert.ox + Math.cos(dir) * dist;\n let y = vert.oy + Math.sin(dir) * dist;\n\n // bounds check\n if (x < circleRadius) { x = circleRadius }\n else if (x >= canvas.width - circleRadius) { x = canvas.width - circleRadius }\n if (y < circleRadius) { y = circleRadius }\n else if (y >= canvas.height - circleRadius) { y = canvas.height - circleRadius }\n\n // point is in bounds and within dist of origin so set its new destination\n vert.dx = x;\n vert.dy = y;\n vert.move = 0; // set ubit dist moved.\n\n }\n\n vert.x = (vert.dx - vert.ox) * vert.move + vert.ox;\n vert.y = (vert.dy - vert.oy) * vert.move + vert.oy;\n\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>So to make you code work using the canvas I have replaced the <code>onframe</code> events for a single function that handles all the circles in one pass, and added a better bounds check that uses the canvas size to check circles are inside.</p>\n\n<h2>Put it all together</h2>\n\n<p>So now putting all the above into a working snippet we have side stepped the SVG elements and improved the code by handling the array of verts and lines as single entities.</p>\n\n<p>We have also reduced the workload and RAM needs of the page, as we have only one layer (the canvas) and one composite operation (which can also be avoided on some browsers)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ctx = canvas.getContext(\"2d\"); \ncanvas.width = innerWidth;\ncanvas.height = innerHeight;\nMath.PI2 = Math.PI * 2; \nconst lineStyle = {\n lineWidth : 1,\n strokeStyle : \"#FF000055\",\n};\nconst circleStyle = {\n fillStyle : \"blue\",\n};\nconst circleRadius = 2.5;\nconst moveDist = 70;\nconst moveSpeedMax = 1 / 120; \nconst moveSpeedMin = 1 / 240; \n\nconst numberLines = 6;\nconst verts = [ \n {id :1 , x: 30.7, y: 229.2 },\n {id :2 , x: 214.4, y: 219.6},\n {id :3 , x: 278.4, y: 186.4},\n {id :4 , x: 382.5, y: 132.5},\n {id :5 , x: 346.8, y: 82 },\n {id :6 , x: 387.9, y: 6.7 },\n {id :7 , x: 451.8, y: 60.8 },\n {id :8 , x: 537.0, y: 119.9},\n {id :9 , x: 545.1, y: 119.9},\n {id :9 , x: 403.5, y: 122.1},\n {id :10 , x: 416.3, y: 130 },\n {id :11 , x: 402.6, y: 221.4},\n {id :12 , x: 409.9, y: 266.4},\n {id :13 , x: 437.1, y: 266.8},\n {id :14 , x: 478.1, y: 269.6},\n {id :15 , x: 242.6, y: 306.1},\n {id :16 , x: 364.0, y: 267 },\n {id :17 , x: 379.1, y: 310.7},\n {id :18 , x: 451.2, y: 398.9},\n {id :19 , x: 529.6, y: 377.9},\n {id :20 , x: 644.8, y: 478.3},\n {id :21 , x: 328.3, y: 324.5},\n {id :22 , x: 314.4, y: 364.3},\n {id :23 , x: 110.2, y: 327.8},\n {id :24 , x: 299.1, y: 219.6},\n {id :25 , x: 130.4, y: 218.1},\n {id :26 , x: 307.4, y: 298.4},\n {id :27 , x: 431.3, y: 360.1},\n {id :28 , x: 551.7, y: 414.4},\n {id :29 , x: 382.5, y: 239.7},\n];\nconst line = (p1, p2) => ({p1, p2});\nvar lines = new Map(); \nfunction findClosestVertInDist(vert,min, max, result = {}) {\n const x = vert.x, y = vert.y;\n result.minDist = max;\n result.closest = undefined;\n for (const v of verts) { \n const dx = v.x - x;\n const dy = v.y - y;\n const dist = (dx * dx + dy * dy) ** 0.5;\n if(dist > min && dist < result.minDist) {\n result.minDist = dist;\n result.closest = v;\n }\n }\n return result;\n}\n\nfunction createLines() {\n var hash;\n lines.length = 0; \n const mod2Id = verts.length; \n const closeVert = {}\n for (const v of verts) { \n closeVert.minDist = 0;\n for (let i = 0; i < numberLines; i++) {\n findClosestVertInDist(v, closeVert.minDist, Infinity, closeVert);\n if (closeVert.closest) { \n if (v.id < closeVert.closest.id) {\n hash = closeVert.closest.id * mod2Id + v.id;\n } else {\n hash = closeVert.closest.id + v.id * mod2Id;\n }\n lines.set(hash,line(v,closeVert.closest));\n } else {\n i--; \n }\n }\n }\n lines = [...lines.values()]; \n verts.forEach(v => { \n v.ox = v.x; \n v.oy = v.y;\n v.dx = v.x;\n v.dy = v.y;\n v.moveSpeed = Math.random() * (moveSpeedMax - moveSpeedMin) + moveSpeedMin;\n v.move = 1; \n delete v.id; \n }); \n\n}\ncreateLines();\n\nfunction drawLines(ctx, lines, style) { \n Object.assign(ctx, style);\n ctx.beginPath();\n for (const line of lines) {\n ctx.moveTo(line.p1.x, line.p1.y);\n ctx.lineTo(line.p2.x, line.p2.y);\n }\n ctx.stroke();\n}\nfunction drawCircles(ctx, verts, radius, style) { \n Object.assign(ctx, style);\n ctx.beginPath();\n for (const vert of verts) { \n ctx.moveTo(vert.x + radius, vert.y);\n ctx.arc(vert.x, vert.y, radius, 0, Math.PI2);\n }\n ctx.fill();\n}\n\n\nrequestAnimationFrame(update); // starts the animation\nfunction update(){\n // to check is resized\n if (canvas.width !== innerWidth || canvas.height !== innerHeight) {\n canvas.width = innerWidth;\n canvas.height = innerHeight;\n } else { // resize clears the canvas so I use else here\n ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n animateCircles(verts, ctx.canvas); \n drawLines(ctx, lines, lineStyle);\n drawCircles(ctx, verts, circleRadius, circleStyle);\n requestAnimationFrame(update); \n}\n\nfunction animateCircles(verts, canvas){\n for(const vert of verts){\n vert.move += vert.moveSpeed;\n if (vert.move >= 1) { \n const dir = Math.random() * Math.PI2; \n const dist = Math.random() * moveDist;\n vert.ox = vert.dx; \n vert.oy = vert.dy; \n let x = vert.ox + Math.cos(dir) * dist;\n let y = vert.oy + Math.sin(dir) * dist;\n\n if (x < circleRadius) { x = circleRadius }\n else if (x >= canvas.width - circleRadius) { x = canvas.width - circleRadius }\n if (y < circleRadius) { y = circleRadius }\n else if (y >= canvas.height - circleRadius) { y = canvas.height - circleRadius }\n\n vert.dx = x;\n vert.dy = y;\n vert.move = 0; \n }\n vert.x = (vert.dx - vert.ox) * vert.move + vert.ox;\n vert.y = (vert.dy - vert.oy) * vert.move + vert.oy;\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!-- replaces the SVG element -->\n<canvas id=\"canvas\" width = \"642\" height = \"481\" style=\"position:absolute;top:0px;left:0px\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This should now run on event the lowlest of devices that have a GPU and support the canvas. Remember that you must size the canvas to the screen via its width and height properties NOT via its style width and height properties.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T07:57:48.273",
"Id": "403390",
"Score": "0",
"body": "wow, that's a pretty detailed explanation. Unfortunately, many animations of my project is already using paper.js, so it would take to long for me to change to canvas2D api or any other library. As for canvas size, i am actually using css to make the canvas the same size as the body, since certain animation will be running through the whole page. Is this a really bad practise?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T08:26:16.113",
"Id": "403393",
"Score": "0",
"body": "@JulianTong Yes it is bad. `canvas.style.width` and `canvas.style.height` set the display size not the resolution of the canvas, To set the canvas resolution you need to set the `canvas.width` and `canvas.height` properties. You will also need to scale the content. I am sure that paper has a way to scale the content to fit the new canvas size, as it is a standard function in the canvas 2D API"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T05:01:03.170",
"Id": "208806",
"ParentId": "208748",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208806",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T07:58:55.150",
"Id": "208748",
"Score": "1",
"Tags": [
"javascript",
"performance",
"animation",
"canvas",
"paper.js"
],
"Title": "Wireframe animation on canvas is slow"
} | 208748 |
<p>I wrote an iterator to access the pixel in an packed image.
It works, but it is slow. </p>
<p>1.Are there any mistakes that can be avoided and might lead to better speed?</p>
<p>2.Are there any pitfalls that wait for me when using this code?</p>
<p>3.Is there a solution to the operator-> ?</p>
<p>4.Has any of the above an extra answer when using this iterator with cuda?
(In an kernel and the intern iterator of GroupIterator is an pointer to device memory). Or is there an other approch when accesing pixel in cuda?</p>
<pre><code>template<unsigned int N, class T>
class Pixel_values;
template<unsigned int N, class T>
class Pixel_reference;
template<unsigned int N, class T>
class Pixel_values{
private:
T values[N];
public:
using size_type = size_t;
Pixel_values(){}
Pixel_values(const Pixel_values<N,T>& other);
Pixel_values(const Pixel_reference<N,T>& other);
~Pixel_values(){}
Pixel_values& operator=(const Pixel_values<N,T>&);
Pixel_values& operator=(const Pixel_reference<N,T>&);
T operator[](size_type) const;
T& operator[](size_type);
};
template<unsigned int N, class T>
class Pixel_reference{
private:
T* values;
public:
using size_type = size_t;
Pixel_reference(){}
Pixel_reference(T* values):values(values){}
Pixel_reference(const Pixel_reference<N,T>& other):values(other.values){}
~Pixel_reference(){}
Pixel_reference& operator=(const Pixel_values<N,T>&);
Pixel_reference& operator=(const Pixel_reference<N,T>&);
T operator[](size_type) const;
T& operator[](size_type);
};
/**
* @brief The GroupIterator class durchläuft einen anderen random_access_iterator in Sprüngen und fast die überSprungenen ETräge zu einem PixelTypen zusammen.
*/
template<unsigned int N, class T>
class GroupIterator{
public:
using base_type = typename std::iterator_traits<T>::value_type;
using size_type = typename std::iterator_traits<T>::difference_type;
using difference_type = size_type;
using value_type = Pixel_values<N,base_type>;
using reference = Pixel_reference<N,base_type>;
using pointer = Pixel_reference<N,base_type>*;
using iterator_category = std::random_access_iterator_tag;
GroupIterator();
GroupIterator(T);
GroupIterator(const GroupIterator&);
~GroupIterator();
GroupIterator<N,T>& operator=(const GroupIterator<N,T>&);
bool operator==(const GroupIterator<N,T>&) const;
bool operator!=(const GroupIterator<N,T>&) const;
bool operator<(const GroupIterator<N,T>&) const;
bool operator>(const GroupIterator<N,T>&) const;
bool operator<=(const GroupIterator<N,T>&) const;
bool operator>=(const GroupIterator<N,T>&) const;
GroupIterator<N,T>& operator++();
GroupIterator<N,T> operator++(int);
GroupIterator<N,T>& operator--();
GroupIterator<N,T> operator--(int);
GroupIterator<N,T>& operator+=(size_type);
GroupIterator<N,T> operator+(size_type) const;
friend GroupIterator<N,T> operator+(size_type, const GroupIterator<N,T>&);
GroupIterator<N,T>& operator-=(size_type);
GroupIterator<N,T> operator-(size_type) const;
difference_type operator-(GroupIterator<N,T>) const;
reference operator*() const;
//pointer operator->() const;
reference operator[](size_type) const;
private:
T position;
};
/// Pixel_values
template<unsigned int N, class T>
Pixel_values<N,T>::Pixel_values(const Pixel_values<N,T>& other){
for(T i = 0; i < N; ++i){
values[i] = other[i];
}
}
template<unsigned int N, class T>
Pixel_values<N,T>::Pixel_values(const Pixel_reference<N,T>& other){
for(T i = 0; i < N; ++i){
values[i] = other[i];
}
}
template<unsigned int N, class T>
T& Pixel_values<N,T>::operator[](size_type index){
return values[index];
}
template<unsigned int N, class T>
T Pixel_values<N,T>::operator[](size_type index) const{
return values[index];
}
/// Pixel_reference
template<unsigned int N, class T>
T& Pixel_reference<N,T>::operator[](size_type index){
return values[index];
}
template<unsigned int N, class T>
T Pixel_reference<N,T>::operator[](size_type index) const{
return values[index];
}
/// GroupIterator
template<unsigned int N, class T>
GroupIterator<N,T>::GroupIterator(){}
template<unsigned int N, class T>
GroupIterator<N,T>::GroupIterator(T position):position(position){}
template<unsigned int N, class T>
GroupIterator<N,T>::GroupIterator(const GroupIterator<N,T>& other):position(other.position){}
template<unsigned int N, class T>
GroupIterator<N,T>::~GroupIterator(){}
template<unsigned int N, class T>
GroupIterator<N,T>& GroupIterator<N,T>::operator=(const GroupIterator<N,T>& other){ this->position = other.position;}
template<unsigned int N, class T>
bool GroupIterator<N,T>::operator==(const GroupIterator<N,T>& other) const{return this->position == other.position;}
template<unsigned int N, class T>
bool GroupIterator<N,T>::operator!=(const GroupIterator<N,T>& other) const{return this->position != other.position;}
template<unsigned int N, class T>
bool GroupIterator<N,T>::operator< (const GroupIterator<N,T>& other) const{return this->position < other.position;}
template<unsigned int N, class T>
bool GroupIterator<N,T>::operator> (const GroupIterator<N,T>& other) const{return this->position > other.position;}
template<unsigned int N, class T>
bool GroupIterator<N,T>::operator<=(const GroupIterator<N,T>& other) const{return this->position <= other.position;}
template<unsigned int N, class T>
bool GroupIterator<N,T>::operator>=(const GroupIterator<N,T>& other) const{return this->position >= other.position;}
template<unsigned int N, class T>
GroupIterator<N,T>& GroupIterator<N,T>::operator++() {
this->position += N;
return *this;
}
template<unsigned int N, class T>
GroupIterator<N,T> GroupIterator<N,T>::operator++(int){
GroupIterator<N,T>&result(this->position);
this->position += N;
return result;
}
template<unsigned int N, class T>
GroupIterator<N,T>& GroupIterator<N,T>::operator--() {
this->position -= N;
return *this;
}
template<unsigned int N, class T>
GroupIterator<N,T> GroupIterator<N,T>::operator--(int){
GroupIterator<N,T>&result(this->position);
this->position -= N;
return result;
}
template<unsigned int N, class T>
GroupIterator<N,T>& GroupIterator<N,T>::operator+=(size_type step){
this->position += step*N;
return *this;
}
template<unsigned int N, class T>
GroupIterator<N,T> GroupIterator<N,T>::operator+(size_type step) const{
return GroupIterator(this->position+step*N);
}
template<unsigned int N, class T>
GroupIterator<N,T> operator+(typename GroupIterator<N,T>::size_type step, const GroupIterator<N,T>& g_itr){
return GroupIterator<N,T>(g_itr.position+step*N);
}
template<unsigned int N, class T>
GroupIterator<N,T>& GroupIterator<N,T>::operator-=(size_type step){
this->position -= step*N;
return *this;
}
template<unsigned int N, class T>
GroupIterator<N,T> GroupIterator<N,T>::operator-(size_type step) const{
return GroupIterator(this->position-step*N);
}
template<unsigned int N, class T>
typename GroupIterator<N,T>::difference_type GroupIterator<N,T>::operator-(GroupIterator<N,T> other) const{
return (this->position-other.position)/N; // NOTE: Division in operator- könnte kostenstelle sein
}
template<unsigned int N, class T>
typename GroupIterator<N,T>::reference GroupIterator<N,T>::operator*() const{
return reference(&(*this->position));
}
template<unsigned int N, class T>
Pixel_reference<N,T> foo(T* position){
return Pixel_reference<N,T>(position);
}
//template<unsigned int N, class T>
//typename GroupIterator<N,T>::poTer GroupIterator<N,T>::operator->() const{
// return &foo<N,T>(this->position);//&Pixel_reference<N,T>(this->position);
//}
// error: taking address of temporary
template<unsigned int N, class T>
typename GroupIterator<N,T>::reference GroupIterator<N,T>::operator[](size_type index) const{
return reference(&(this->position[index*N]));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T18:15:38.483",
"Id": "403356",
"Score": "2",
"body": "I don't understand what you are trying to accomplish with this code. Could you explain a bit further what this code does?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T08:29:04.770",
"Id": "208749",
"Score": "2",
"Tags": [
"c++",
"iterator",
"cuda"
],
"Title": "Iterator that groups elements of its source"
} | 208749 |
<p>I'm relatively new to Python from a strong Java background. I am trying to create a base class to do <a href="https://en.wikipedia.org/wiki/Hoare_logic" rel="nofollow noreferrer">Hoare Logic</a>. Function decorators seem to be the way to go with this. I've produced the following code, can you comment on this, and suggest an easier way to do this? It seems awfully over complicated to how easy this would be with an abstract function in Java. I'm quite liking Python's function points from my C/C++ days, something Java doesn't easily support without introspection.</p>
<p><strong>Hoare Logic</strong></p>
<pre><code>{P} {C} {Q}
</code></pre>
<p>Where:</p>
<ul>
<li>P is the pre-condition</li>
<li>C is the command</li>
<li>Q is the post-condition or invariant.</li>
</ul>
<p><strong>The python decorator</strong></p>
<pre><code>def hoare_logic(description, pre_execution=None, post_execution=None):
def decorator_func(function_to_decorate):
def wrapper_func(*args, **kwargs):
# Hoare Pre-Condition
if pre_execution is not None:
pre_condition = pre_execution(*args, **kwargs)
print("Hoare Pre-Condition {!r}".format(description, pre_condition))
# Hoare Command
return_value = function_to_decorate(*args, **kwargs)
# Hoare Post-Condition
if post_execution is not None:
post_condition = post_execution(*args, **kwargs)
print("Hoare Post-Condition {!r}".format(description, post_condition))
return return_value
return wrapper_func
return decorator_func
</code></pre>
<p><strong>Stubs for the pre & post-conditions</strong></p>
<pre><code>def pre_condition():
return True
def post_condition():
return True
</code></pre>
<p><strong>Typical usage I want to perform</strong></p>
<p>This is representative of the code under test in a specific scenario, with the pre & post conditions I'd expect to collect several of these into a BDD behaviour class extending the python <code>unittest.TestCase</code> class, or perhaps my own extension of that.</p>
<pre><code>@hoare_logic(description='description of command', pre_condition, post_condition)
def command(arg):
if arg is not None:
print("command")
if arg == 'foobar':
return False
else:
return True
else:
raise ValueError
</code></pre>
<p>These are just stubs for exercising the decorator usage above, this is not the way I will really expect to use this in practice, but it is so you can run this code.</p>
<pre><code> # self.assertRaises(ValueError, command, None)
command(True)
command(False)
command('foo')
command('bar')
command('foobar')
</code></pre>
<p>Once I have a grip with the basic mechanism, I intend to adapt this to provide API contracts & a BDD type scenario functionality framework for behaviour & scenario testing. So please keep this in mind. I'm interested in serious scrutiny of the core functionality implementation of the Hoare logic in python.</p>
<p>I'm unsure of my treatment of <code>*args, **kwargs</code> but from what I can see I need this for Python decorators. Is there a better way to handle parametrisation of the wrapped function?</p>
<p>I've deliberately exclude class wrapper & imports to make this simpler run & follow. The commented stub does work if this a class, but not as a script, not quite sure why.</p>
<p>Ultimately I want to be able to do the following, but didn't include this because it is not complete, so consider it pseudo code of my final objective.</p>
<pre><code>@scenario(narrative='short description', givens=[given_one, given_two], thens=[then_one])
def the_behaviour_under_test(arg):
...
</code></pre>
<p><em>Please be kind, if I've broken the question rules, please help me improve the compliance of the question with comments rather than just close it</em>.</p>
<p><strong>Here is everything together</strong>
Comments suggested I need to add more code, so the full file, this will run as a stand alone python script.</p>
<pre><code>#!/usr/bin/env python
def hoare_logic(description, pre_execution=None, post_execution=None):
def decorator_func(function_to_decorate):
def wrapper_func(*args, **kwargs):
# Hoare Pre-Condition
if pre_execution is not None:
pre_condition = pre_execution()
print("Hoare Pre-Condition {!r}".format(description, pre_condition))
# Hoare Command
return_value = function_to_decorate(*args, **kwargs)
# Hoare Post-Condition
if post_execution is not None:
post_condition = post_execution()
print("Hoare Post-Condition {!r}".format(description, post_condition))
return return_value
return wrapper_func
return decorator_func
def pre_condition():
return True
def post_condition():
return True
@hoare_logic(description='description of command', pre_execution=pre_condition, post_execution=post_condition)
def command(arg):
if arg is not None:
print("command")
if arg == 'foobar':
return False
else:
return True
else:
raise ValueError
# command()
# self.assertRaises(ValueError, command, None)
command(True)
command(False)
command('foo')
command('bar')
command('foobar')
@hoare_logic(description='command')
def naked_command(arg):
if arg is not None:
print("command")
if arg == 'foobar':
return False
else:
return True
else:
raise ValueError
# naked_command()
# self.assertRaises(ValueError, naked_command, None)
naked_command(True)
naked_command(False)
naked_command('foo')
naked_command('bar')
naked_command('foobar')
@hoare_logic(description='description of command', pre_execution=pre_condition)
def pre_command(arg):
if arg is not None:
print("command")
if arg == 'foobar':
return False
else:
return True
else:
raise ValueError
# pre_command()
# self.assertRaises(ValueError, pre_command, None)
pre_command(True)
pre_command(False)
pre_command('foo')
pre_command('bar')
pre_command('foobar')
@hoare_logic(description='description of command', post_execution=post_condition)
def post_command(arg):
if arg is not None:
print("command")
if arg == 'foobar':
return False
else:
return True
else:
raise ValueError
# naked_command()
# self.assertRaises(ValueError, naked_command, None)
post_command(True)
post_command(False)
post_command('foo')
post_command('bar')
post_command('foobar')
@hoare_logic(description='description of command', pre_execution=pre_condition, post_execution=post_condition)
def post_command(arg):
if arg is not None:
print("command")
if arg == 'foobar':
return False
else:
return True
else:
raise ValueError
# post_command()
# self.assertRaises(ValueError, post_command, None)
post_command(True)
post_command(False)
post_command('foo')
post_command('bar')
post_command('foobar')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T12:35:06.743",
"Id": "403289",
"Score": "3",
"body": "Can you explain in more detail what you are trying to do here? The code in the post appears to be unfinished — there is no actual Hoare logic, just printing of conditions, and the example does not even have any conditions that would need to be printed. It is very hard to review code in this kind of state — we'd rather you made your best effort to get it working before posting here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T13:50:03.527",
"Id": "403298",
"Score": "2",
"body": "I've fixed the indent issue, elaborated the question and posted with the entire file I've been experimenting with at the end, rather than the cut down example. Originally I didn't want to cloud thins by posting too much code."
}
] | [
{
"body": "<p>You are ignoring the <code>pre_execution</code> and <code>post_execution</code> return values.</p>\n\n<pre><code>def invariant(lst):\n return len(lst) > 0\n\n@hoare_logic(\"Invariants\", invariant, invariant)\ndef append_hello(lst):\n \"\"\"Append 'hello' to a non-empty list\"\"\"\n\n lst.append(\"Hello\")\n\nlst = []\nappend_hello(lst)\n</code></pre>\n\n<blockquote>\n <p>Hoare Pre-Condition 'Invariants'<br>\n Hoare Post-Condition 'Invariants'</p>\n</blockquote>\n\n<p>Neither the <code>False</code> nor the <code>True</code> returned by <code>invariant</code> is used or printed. This comes from your print statement, which only has 1 format code <code>{!r}</code>, but two values are being passed to <code>format()</code>.</p>\n\n<pre><code>print(\"Hoare Pre-Condition {!r}\".format(description, pre_condition))\n</code></pre>\n\n<p>You should either usefully use the <code>pre_condition</code> and <code>post_condition</code> return values, or the <code>pre_execution</code> and <code>post_execution</code> should not be expected to return values, and should <code>raise</code> an exception to indicate a failure of the pre/post conditions.</p>\n\n<hr>\n\n<p>Your <code>@hoare_logic</code> decorator will hide any <code>\"\"\"docstring\"\"\"</code> which is added to functions:</p>\n\n<pre><code>help(append_hello)\n</code></pre>\n\n<p>ends up describing the <code>wrapper_func</code> instead of <code>append_hello</code>!</p>\n\n<pre><code>Help on function wrapper_func in module __main__: \n\nwrapper_func(*args, **kwargs)\n</code></pre>\n\n<p>You should use <code>@functools.wraps</code> to transfer the <code>__name__</code>, docstring, signature, argument type hints, etc from the wrapped function to the wrapping function. After decorating the wrapper ...</p>\n\n<pre><code>import functools\n\ndef hoare_logic(description, pre_execution=None, post_execution=None):\n def decorator_func(function_to_decorate):\n @functools.wraps(function_to_decorate) # <-- new\n def wrapper_func(*args, **kwargs):\n # ... body omitted for brevity ...\n return wrapper_func\n return decorator_func\n</code></pre>\n\n<p>... then <code>help(append_hello)</code> produces the expected result:</p>\n\n<pre><code>Help on function append_hello in module __main__:\n\nappend_hello(lst)\n Append 'hello' to a non-empty list\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T21:07:47.327",
"Id": "208793",
"ParentId": "208755",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T10:43:44.023",
"Id": "208755",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"meta-programming"
],
"Title": "Using Python decorators to do Hoare Logic"
} | 208755 |
<p>Recently, I've been doing more and more Batch "programming".</p>
<p>I always find myself in the need to extract a file and do <em>something</em> with the files.<br>
This is not my first version, and a few non-general-purpose were written.</p>
<p>However, I've re-written it all to be general-purpose.</p>
<pre><code>:extractfile
REM extracts the file with whichever program is available
REM %1 = file to extract, %2 = optional target for extraction, %3 = log file path
REM exit: 0 = extracted, 1 = not found, 2 = failed, 3 = no program
set "extractfile="
setlocal EnableDelayedExpansion
set "folder=%~dp1"
set "file=%~nx1"
set "filename=%~n1"
IF NOT EXIST "!folder!!file!" (
exit /b 1
)
set "target=%~dp2"
IF "!target!" EQU "" (
SET "target=!folder!!filename!\"
)
REM set "LOG=%~dpnx3"
REM https://codereview.stackexchange.com/questions/208756/function-to-extract-a-file-in-batch#comment405176_208756
IF "%~3" EQU "" (
set "LOG=nul"
) else (
set "LOG="%~dpnx3""
)
set "CMD="
echo === COMPRESSED FILE EXTRACTION === >> !LOG!
REM yeah, not pretty, but the %ProgramFiles(x86)% causes syntax errors
FOR %%d IN ("%ProgramFiles%" "%ProgramFiles(x86)%") DO IF "!CMD!" EQU "" (
set "DIR=%%d"
IF "!DIR!" NEQ "" (
set "DIR=!DIR:"=!"
IF EXIST "!DIR!\7-Zip\7z.exe" (
REM https://stackoverflow.com/q/14122732
set "CMD="!DIR!\7-Zip\7z.exe" x "!folder!!file!" -bd -y -o"!target!\""
) ELSE IF EXIST "!DIR!\WinRAR\winrar.exe" (
REM https://stackoverflow.com/a/19337595
set "CMD="!DIR!\WinRAR\winrar.exe" x -ibck "!folder!!file!" *.* "!target!\""
) ELSE IF EXIST "!DIR!\winzip\wzzip.exe" (
REM http://kb.winzip.com/kb/entry/125/ - WZCLINE.CHM
set "CMD="!DIR!\winzip\wzzip.exe" -d "!folder!!file!" "!target!\""
)
)
)
IF "!CMD!" EQU "" (
echo Error 3: Extraction failed, no program found >> !LOG!
echo === COMPRESSED FILE EXTRACTION FINISHED === >> !LOG!
exit /b 3
)
echo Extracting using command: >> !LOG!
echo !CMD! >> !LOG!
call !CMD! >> !LOG! 2>&1
IF ERRORLEVEL 1 (
echo Error 2: Extraction failed with error %ERRORLEVEL% >> !LOG!
echo === COMPRESSED FILE EXTRACTION FINISHED === >> !LOG!
exit /b 2
)
echo === COMPRESSED FILE EXTRACTION FINISHED === >> !LOG!
endlocal & set "extractfile=!target!\"
goto :eof
</code></pre>
<p>This function uses the available program to extract the file and "returns" the path to the folder.</p>
<p>Assuming the following basic example:</p>
<pre><code>call :extractfile a.zip abc
echo %extractfile%
</code></pre>
<p>This should output something like <code>c:\[...]\abc</code> on success.<br>
Also responds with the following error codes:</p>
<ul>
<li>0: extraction succeeded</li>
<li>1: file not found</li>
<li>2: extraction failed</li>
<li>3: couldnt find a suitable program to extract</li>
</ul>
<p>If the 2nd argument isn't passed, it is supposed to create a sub-folder with everything inside.</p>
<p><sub>(You can see this in action in <a href="https://github.com/ismael-miguel/bnsbuddy_mod_installer/blob/master/mod_installer.bat" rel="nofollow noreferrer">https://github.com/ismael-miguel/bnsbuddy_mod_installer/blob/master/mod_installer.bat</a>)</sub></p>
<p>I've tried to keep it as DRY as possible, and as short as I could.</p>
<p>Is there anything I've missed or that I should improve?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T11:52:42.097",
"Id": "403284",
"Score": "1",
"body": "/OT - This looks like magic to me - have you ever considered using `PowerShell`? I admire you for working with `batch` scripts ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T11:59:21.247",
"Id": "403285",
"Score": "0",
"body": "I have considered, but this that I'm writting is to go to a variety of systems, which have a variety of PowerShell versions with a variety of functionalities. I definetivelly should try learning PowerShell, but my interest has been a bit low on it. And for what I'm doing, Batch works just fi... okay-ish..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-13T18:40:41.353",
"Id": "405176",
"Score": "0",
"body": "**1st**: if supplied `%2` then `%~dp2` already contains trailing backslash; hence, use `set \"target=%~dp2\"` and then `IF \"!target!\"==\"\" (`. **2nd** ad `mod_installer.bat` (above this topic): define `if \"%~3\"==\"\" (set \"LOG=nul\") else set \"LOG=%~dpnx3\"`; then you could save all next `IF \"!LOG!\" NEQ \"\" (` tests just using `>>\"!LOG!\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-31T17:14:55.190",
"Id": "407223",
"Score": "0",
"body": "@JosefZ Thank you for the tips. I've been having some syntax issues with some edits I was doing and only fixed them today. The version that was present here was fully functional, but isn't the latest in the github. As such, I've ninja-edited the latest version."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T11:13:31.930",
"Id": "208756",
"Score": "1",
"Tags": [
"file",
"compression",
"batch"
],
"Title": "\"Function\" to extract a file in Batch"
} | 208756 |
<p>This is the follow up for a question you can find here: <a href="https://codereview.stackexchange.com/questions/208675/replacing-words-with-their-abbreviations">replacing words with their abbreviations</a></p>
<p>The goal here is to compare two petential way of answering said question that was:</p>
<blockquote>
<p>This particular function's goal is to replace words with their abbreviations by compairing each word with all of those in the config file and replacing whenever a match is found, the goal is to keep a general idea of what the string meant so its not a problem that a word once replaced could ressemble an other as long as they refer to roughly the same thing.<br>
String is always upper case and free of special characters.</p>
</blockquote>
<p>The two functions are:</p>
<p>From @Maarten Fabré:</p>
<pre><code>def shorten_words(abbreviations, line, max_length=38):
replacements = set()
while len(line) > max_length:
for word in line.split(" "):
if (
word[-1] == "S"
and word not in abbreviations
and word[:-1] in abbreviations
):
word = word[:-1]
if word not in replacements and word in abbreviations:
line = line.replace(word, abbreviations[word])
if word == abbreviations[word]:
replacements.add(word)
break
return line
</code></pre>
<p>and:</p>
<pre><code>def shorten_words(abbreviations_file, sentence):
"""Shorten string `sentence` using the dictionnary_like object `abbreviations`."""
abbreviations = set(abbreviations_file)
word_list = sentence.split(' ')
size = len(sentence)
resultat = []
for word in word_list:
if word[-1] == "S" and word not in abbreviations and word[:-1] in abbreviations:
word = word[:-1]
if word.lower() not in abbreviations or size <= POSTAL_LINE_LENGTH:
resultat.append(word)
else:
resultat.append(abbreviations_file[word])
size -= len(word) - len(abbreviations_file[word])
return ' '.join(resultat)
</code></pre>
<p>The two main point of comparison are performance and readablility, those answer may still be reviewed as usual.</p>
<p>here is a sample of the configfile (some lines have key and value equal this is meant to remove plural):</p>
<pre><code>[abbreviation]
AVANCEE = AVANC
COMPOSANT = COMPO
VERT = VERT
AGRAIRE = AGRAIR
MECANIQUE = MECA
CARROSSERIE = CARROS
SIGNALISATION = SIGNAL
FOURNITURE = FOURNI
LAITIERE = LAIT
INTERPROFESSIONNEL = INTRPRO
ATLANTIQUE = ATLAN
REALISATION = REAL
INCENDIE = INCEND
MARBRERIE = MARB
FUNEBRE = FUNEBR
POMPE = POMPE
ANTICIPATION = ANTICIP
OBJET = OBJET
ANTIQUITE = ANTIQ
MOBILITE = MOBIL
ASSOCIATIF = ASSO
ANCIENNE = ANC
TELECOMMUNICATION = TELECOM
RESEAUX = RESEAU
LOCALE = LOCAL
RESPIRE = RESPI
QUAND = QND
CHRETIENNE = CHRET
OUVRIERE = OUVRI
JEUNESSE = JEUNE
INTERCULTUREL = INTRCULT
VALORISATION = VALOR
ALIMENTAIRE = ALIMEN
COMMUNALE = COMMUNE
LAIQUE = LAIQ
CASSATION = CASS
TRAVAUX = TRAVAU
ONCOLOGIE = ONCO
RELIGION = RELIG
PLURALISME = PLURAL
FLOTTANTE = FLOT
EOLIENNE = EOLIEN
HUMAINE = HUMAIN
POTENTIEL = POTENT
AMELIORATION = AMELIO
MUSIQUE = MUSIQ
MUNICIPALE = MUNI
EVANGELIQUE = EVANG
BIOLOGISTE = BIOLOG
REPUBLICAIN = REPU
SYMPATHISANT = SYMPAT
ELU = ELU
INTERCONNEXION = INTRCONN
CONSULTANT = CONSULT
ORGANIZATION = ORGA
OLYMPIQUE = OLYMP
CAPACITE = CAPA
RENFORCEMENT = RENFOR
CLEF = CLEF
FRIGORIFIQUE = FRIGO
ENTREPOSAGE = ENTREPO
COLLABORATIF = COLLAB
TROUBLE = TROUBL
ENTRAIDE = ENTRAID
REPRESENTANT = REPRESENT
ADHERENT = ADHER
FOLKLORIQUE = FOLKLO
STADE = STAD
AMI = AMI
EMPEREURS = EMPER
CONFRERIE = CONFRER
SOUTENUE = SOUTENU
LISTE = LIST
ELECTION = ELECT
ELECTORALE = ELECT
FINANCEMENT = FINANC
CATHOLIQUE = CATHO
HARMONIE = HARMO
DEBOUT = DEBOU
VENT = VENT
CERCLE = CERCL
FOOTBALL = FOOT
IMPROVISATION = IMPROV
POPULAIRE = POPU
SECOURS = SECOUR
ART = ART
DRAMATURGIE = DRAMA
POETIQUE = POET
TRAVAILLANT = TRAVAIL
SYNCHRONISEE = SYNCHRO
NATATION = NATA
LOCATAIRES = LOCAT
AMICALE = AMICA
DEPARTEMENT = DEPART
INDISCIPLINEE = INDISCIPL
PARTAGE = PARTA
MEDIATION = MEDIAT
CITOYEN = CITOY
CULTIVONS = CULTIV
QUARTIER = QUART
DOMICILE = DOMI
ADMINIS = ADMIN
APPLIQUEE = APPLI
SOPHROLOGIE = SOPHRO
SPECTACLE = SPECTA
ABANDONNE = ABANDON
COMMUNAUTAIRE = COMMUN
PARTICULIER = PARTICUL
METALLIQUE = METAL
COOPERATION = COOP
PROGRAMMATION = PROGRAM
KINESITHERAPEUTE = KINESITHERAP
ENVIRON = ENVIRON
ARTISAN = ARTIS
COMMUNICATION = COM
TRANSMISSION = TRANSMIS
APPROVISIONNEMENT = APPRO
IMAGERIE = IMAGE
MANAGEMENT = MANAG
ASSOCIEE = ASSO
INFIRMIERE = INFIRM
FONDS = FOND
EMBOUTISSAGE = EMBOUTISS
DECOUPAGE = DECOUP
OUTILLAGE = OUTIL
TERRASSEMENT = TERRASS
DEMOLITION = DEMOLIT
BILINGUE = BILINGU
ECOLE = ECOL
HABITAT = HABITA
PRODUCTION = PROD
DURABLE = DURABL
PRATIQUE = PRATIQ
TRANSPORT = TRANSPOR
ASSOCIATIVE = ASSO
CRECHE = CRECH
SPECIALISEE = SPECIAL
COUVERTURE = COUVERT
ETANCHEITE = ETANCH
TOITURE = TOIT
</code></pre>
| [] | [
{
"body": "<h3>1. Both versions</h3>\n\n<ol>\n<li><p>Splitting on spaces causes words not to be abbreviated if they are followed or preceded by punctuation.</p></li>\n<li><p>Testing for plurals is done for every word. When there are many sentences to be reduced, it would be better to handle plurals by preprocessing the abbreviations dictionary beforehand. (Better because of speed and because of <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a>, for example pluralization rules are language-dependent.)</p></li>\n<li><p>Each word is looked up in the abbreviations mapping four times. It would be better to look it up just once and remember the result.</p></li>\n</ol>\n\n<h3>2. First version (Maarten Fabré's)</h3>\n\n<ol>\n<li><p>There's no docstring.</p></li>\n<li><p>Runtime is quadratic in the length of the input string due to the use of repeated string replacement.</p></li>\n<li><p>Replacement does not respect word boundaries, for example, if CERCLE is found the in the sentence, then it would be changed to its abbreviation CERCL, but also RECERCLER would be changed to RECERCLR, which is not what is wanted.</p></li>\n</ol>\n\n<h3>3. Second version</h3>\n\n<ol>\n<li><p>There is no need for <code>abbreviations = set(abbreviations_file)</code> since <code>ConfigParser</code> objects <a href=\"https://docs.python.org/3/library/configparser.html#mapping-protocol-access\" rel=\"nofollow noreferrer\">support the mapping protocol</a>.</p></li>\n<li><p>It would be better to take the maximum sentence length as a keyword argument rather than a global variable: this is more flexible and convenient for testing.</p></li>\n</ol>\n\n<h3>4. Revised code</h3>\n\n<pre><code>import re\n\ndef shorten_sentence(abbreviations, sentence, max_length=0):\n \"\"\"Shorten sentence by abbreviating words until it is max_length\n characters or shorter. First argument abbreviations must be a\n dictionary mapping words to their abbreviations.\n\n \"\"\"\n length = len(sentence)\n words = []\n for word in re.split(r'(\\W+)', sentence):\n if length > max_length:\n abbrev = abbreviations.get(word, word)\n else:\n abbrev = word\n words.append(abbrev)\n length -= len(word) - len(abbrev)\n return ''.join(words)\n</code></pre>\n\n<p>I recommend that pluralization be implemented separately, perhaps like this:</p>\n\n<pre><code>def plural_fr(word):\n \"\"\"Return a naïve guess at the French plural of word.\"\"\"\n if word.endswith(('AU', 'EU', 'OU')):\n return word + 'X'\n else:\n return word + 'S'\n\ndef pluralize(abbreviations, plural):\n \"\"\"Return copy of abbreviations with uppercased keys, together with the\n plurals of the keys, produced by calling the plural function.\n\n \"\"\"\n result = {key.upper(): value for key, value in abbreviations.items()}\n for key, value in abbreviations.items():\n result.setdefault(plural(key.upper()), value)\n return result\n</code></pre>\n\n<p>Then in the main part of the program you would build the table of abbreviations and their plurals like this:</p>\n\n<pre><code>config = configfile.ConfigParser()\nconfig.read('abbreviations.ini')\nabbrevations = pluralize(config['abbreviation'], plural_fr)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T14:12:28.400",
"Id": "403301",
"Score": "0",
"body": "I do not understand how the pluralize function works, could you explain it ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T14:12:57.490",
"Id": "403302",
"Score": "1",
"body": "See updated answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T14:48:20.103",
"Id": "403310",
"Score": "0",
"body": "`RECERCLER` would only be reduced if it is found in the `abbreviations`, so would not be reduced to `RECERCLR`. My version can be considered quadratic in relation to the amount of words in the sentence, but since the goal was to get the sentence below 38 characters, the amount of words to expect would be limited. I see now that it would result in an infinite loop if the sentence can not be reduced to below the maximum length. All in all your version is a lot better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T15:07:23.280",
"Id": "403312",
"Score": "0",
"body": "@MaartenFabré: I've added a clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T15:11:14.197",
"Id": "403314",
"Score": "0",
"body": "yet again demonstrating why testing code is needed :s"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T13:45:50.790",
"Id": "208762",
"ParentId": "208759",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208762",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T11:23:19.613",
"Id": "208759",
"Score": "1",
"Tags": [
"python",
"strings",
"comparative-review",
"natural-language-processing"
],
"Title": "Replacing words with their abbreviations - Follow up"
} | 208759 |
<p>Hypothetically, I have a bunch of generators that never end, like:</p>
<blockquote>
<pre><code>function* progression() {
let n = 0;
while (true) {
yield n++;
}
}
</code></pre>
</blockquote>
<p>I want to take first N items from that generator. So I made a function <code>take</code> for that:</p>
<pre><code>function* take(n, generator) {
let i = 0;
let values = generator();
for (let v of values) {
if (++i > n) {
return;
}
yield v;
}
}
</code></pre>
<p>Is there a better way, maybe standard ES6+ API or a more concise syntax to achieve the same thing? If this function could fail under circumstances that I didn't account for, please give me a hint.</p>
| [] | [
{
"body": "<p>I would write it as:</p>\n\n<pre><code>function* take(n, generator) {\n let values = generator();\n\n let i = 0;\n while (i++ < n) {\n yield values.next().value;\n }\n}\n</code></pre>\n\n<p>this seems to match the intent more closely though its mostly a matter of personal preference.</p>\n\n<h3>Update</h3>\n\n<p>You can also add the <code>take</code> method as an extension to the generator so you could call it like <code>generator().take(3)</code>. See <a href=\"https://stackoverflow.com/a/47534339/1575353\">this SO answer</a> if you are interested in that approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T14:51:36.857",
"Id": "208767",
"ParentId": "208760",
"Score": "3"
}
},
{
"body": "<p>Given that the yielded value can be from <code>N</code> (1) to <code>Infinity</code> you can use <code>.next()</code>, check if the returned object property <code>done</code> is <code>undefined</code>, if <code>true</code>, <code>break</code> loop, else <code>yield</code> <code>value</code>, continue up to <code>N</code>. </p>\n\n<p>A second function could also be used to pass a single or different <code>N</code> values and \"a bunch of generators\" to as <code>rest</code> parameters, where the return value will be an array of arrays or an object containing a property for each <code>N</code> and, or generator.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function* progression0() {\n let n = 0;\n while (true) {\n yield n++;\n }\n}\nfunction* progression1() {\n let n = 0;\n while (n < 1) {\n yield n++; // only 1 value yielded from this generator\n }\n}\nfunction* take(n, gen) {\n const g = gen();\n for (let i = 0; i < n; i++) {\n const {value, done} = g.next();\n // break if `done`\n if (done) {break};\n yield value;\n }\n}\nlet n = 7;\nlet [...a] = take(n, progression0); // individual variable `a`\nlet [...b] = take(n, progression1); // individual variable `b`\nconsole.log({a, b});\nconst processProgression = (n, ...gen) => gen.map(g => [...take(n, g)]);\nlet [c, d] = processProgression(n, progression0, progression1);\n// same as `a`, `b` using function to process `N`, and n generators\nconsole.log({c, d}); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T21:17:12.623",
"Id": "208794",
"ParentId": "208760",
"Score": "2"
}
},
{
"body": "<p>Some minor changes to improve use and protect misuse.</p>\n\n<p>The <code>take</code> function only takes from the start. It would be more flexible if you pass the generator, not the generator function. That way you can take from a generator where you left off.</p>\n\n<pre><code>function *take(n, values) { \n while (n-- > 0) { yield values.next().value }\n}\n</code></pre>\n\n<p>and then used as</p>\n\n<pre><code>take(10, progression()); //to take the first 10\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>const values = progression();\ntake(10, values); // take ten\ntake(10, values); // take ten more\n</code></pre>\n\n<p>There is a danger someone might use the infinite generator to fill an array</p>\n\n<pre><code>const array = [...progression()]; // uncatchable page crash\n</code></pre>\n\n<p>Which is an uncatchable error that will crash the page.</p>\n\n<p>You could create an interface that protects the infinity by hiding the <code>progression</code> in closure. You can also then add some extras if need be.</p>\n\n<pre><code>const progression = (()=>{\n function *progression() {\n var n = 0;\n while (true) { yield n++ }\n }\n var current = progression();\n return {\n restart() { current = progression() },\n *take(count) {\n current = progression();\n while (count-- > 0) { yield current.next().value }\n },\n *more(count) {\n while (count-- > 0) { yield current.next().value }\n },\n get next() { return current.next().value }\n };\n})();\n</code></pre>\n\n<p>And used as </p>\n\n<pre><code>progression.take(10); /// get first ten\nprogression.take(10); /// get first ten again\nprogression.more(10); /// get ten more\nconst v = progression.next; // get next value (21st)\nprogression.restart();\nconst first = progression.next; // get next value (1st)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T06:30:59.947",
"Id": "208809",
"ParentId": "208760",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208767",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T11:45:13.790",
"Id": "208760",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"generator"
],
"Title": "Take a limited number of items from a potentially infinite generator"
} | 208760 |
<p>I would like to know opinions about the design I came up with to handle stdout capture to show progress in a <code>PyQt5</code> application.</p>
<p>So, I have this module which is meant to be run as a command line application. When called with some arguments, it takes time to run, giving progress to <code>stdout</code> and in the end returning some data.</p>
<p>In my <code>PyQt5</code> application, I'm able to load that module, run it, and get its data. However, since it takes time to run, I'd like to give progress feedback.</p>
<p>I'm handling this using <code>contextlib.redirect_stdout</code>. However, the data fetching happens in a sub-thread and must update widgets in the main thread, so I must use signals. Also, to be able to capture multiple progress messages in one single function call of the data fetching function in the command line module, I need to have a listener for <code>stdout</code>, which I put in a second sub-thread. </p>
<p>Below is a minimalist code representing the real case. Note the global variable <code>out</code> - this is what I came up with to be able to handle communication between 2 sub threads. I don't particularly like having this global variable, but it did solve the problem and looks simple. Any suggestions here would be welcome.</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
import sys
import requests
from contextlib import redirect_stdout
from PyQt5 import QtCore, QtGui, QtWidgets
# target for stdout - global variable used by sub-threads
out = io.StringIO()
class OutputThread(QtCore.QThread):
# This signal is sent when stdout captures a message
# and triggers the update of the text box in the main thread.
output_changed = QtCore.pyqtSignal(object)
def run(self):
'''listener of changes to global `out`'''
while True:
out.flush()
text = out.getvalue()
if text:
self.output_changed.emit(text)
# clear the buffer
out.truncate(0)
out.seek(0)
class FetchDataThread(QtCore.QThread):
# Connection between this and the main thread.
data_fetched = QtCore.pyqtSignal(object, object)
def __init__(self, url_list):
super(FetchDataThread, self).__init__()
self.url_list = url_list
def update(self, url_list):
self.url_list = url_list
def run(self):
for url in self.url_list:
# Can write directly to `out`
out.write('Fetching %s\n' % url)
# This context manager will redirect the output from
# `sys.stdout` to `out`
with redirect_stdout(out):
data = fetch_url(url)
out.write('='*80 + '\n')
# Send data back to main thread
self.data_fetched.emit(url, data)
def fetch_url(url):
'''This is a dummy function to emulate the behavior of the module
used in the real problem.
The original module does lots of things and prints multiple
progress messages to stdout.
'''
print('Fetching', url)
page = requests.get(url)
print('Decoding', url)
data = page.content.decode()
print('done')
return data
class MyApp(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MyApp, self).__init__(parent)
# ###############################################################
# ### GUI setup
self.centralwidget = QtWidgets.QWidget(self)
self.setCentralWidget(self.centralwidget)
self.button = QtWidgets.QPushButton('Go', self.centralwidget)
self.button.clicked.connect(self.go)
self.output_text = QtWidgets.QTextEdit()
self.output_text.setReadOnly(True)
layout = QtWidgets.QVBoxLayout(self.centralwidget)
layout.addWidget(self.button)
layout.addWidget(self.output_text)
# ### end of GUI setup
# ###############################################################
self.url_list = ['http://www.duckduckgo.com',
'http://www.stackoverflow.com']
self.url = list()
self.data = list()
# Thread to update text of output tab
self.output_thread = OutputThread(self)
self.output_thread.output_changed.connect(self.on_output_changed)
# Start the listener
self.output_thread.start()
# Thread to fetch data
self.fetch_data_thread = FetchDataThread(self.url_list)
self.fetch_data_thread.data_fetched.connect(self.on_data_fetched)
self.fetch_data_thread.finished.connect(lambda: self.button.setEnabled(True))
def go(self):
if not self.fetch_data_thread.isRunning():
self.button.setEnabled(False)
self.fetch_data_thread.update(self.url_list)
self.fetch_data_thread.start()
def on_data_fetched(self, url, data):
self.url.append(url)
self.data.append(data)
def on_output_changed(self, text):
self.output_text.append(text.strip())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MyApp()
window.setGeometry(100, 50, 1200, 600)
window.show()
sys.exit(app.exec_())
</code></pre>
| [] | [
{
"body": "<p><code>OutputThread.run</code> contains a <em>busy loop</em>: it is continuously checking for new input. That's a huge waste of CPU time. The least you could do to avoid that would be insert a <code>time.sleep(0.1)</code> inside the loop. A better approach would be to redirect <code>stdout</code> to a custom object that emits signals when written to. AFAIK it would suffice to implement <code>write</code> and <code>flush</code> methods in the custom object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-05T07:49:34.400",
"Id": "403898",
"Score": "0",
"body": "Good spotted regarding the busy loop - I had corrected that like you mention. I'll give it a try in your suggested approach and see how it goes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T12:57:53.267",
"Id": "208999",
"ParentId": "208766",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T14:49:32.793",
"Id": "208766",
"Score": "1",
"Tags": [
"python",
"pyqt"
],
"Title": "Capturing stdout in a QThread and update GUI"
} | 208766 |
<p>I'm looking for feedback on ways to improve the maintainability and readability of my code. I'm especially interested in hearing about ways I could improve the code's adherence to good object oriented practices. Thank you!</p>
<p>Purpose of the code:</p>
<p>Reject a client's requests if that client has already made 100 requests in the last second. The client who sent a request is identified on the request with a <code>clientID</code>.</p>
<p>Usage:</p>
<pre><code>let rateLimiter = new RateLimiter();
let request = { clientID: 1, time: 0 };
let isRequestAllowed = rateLimiter
.addRequestAndCheckIsAllowed(request);
</code></pre>
<p>Implementation:</p>
<pre><code>const MAX_REQUESTS_IN_TIME_FRAME = 100;
const REQUEST_MAX_AGE = 1000;
class RateLimiter {
constructor () {
this._clientRequests = {};
}
addRequestAndCheckIsAllowed (request) {
this._storeRequest(request);
return this._clientRequestCount(request.clientID) <=
MAX_REQUESTS_IN_TIME_FRAME;
}
_storeRequest (request) {
const clientID = request.clientID;
this._clientRequests[clientID] =
this._clientRequests[clientID] ||
new RequestBuffer(REQUEST_MAX_AGE);
this._clientRequests[clientID].store(request);
}
_clientRequestCount(clientID) {
if (this._clientRequests[clientID] === undefined) {
return 0;
}
return this._clientRequests[clientID].count();
}
};
class RequestBuffer {
constructor (requestMaxAge) {
this._requestMaxAge = requestMaxAge;
this._requests = [];
}
store (request) {
this._requests.push(request);
const maxTime = Date.now() - this._requestMaxAge;
this._requests =
this._requests.filter(request => request.time > maxTime);
}
count () {
return this._requests.length;
}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T01:54:23.333",
"Id": "403379",
"Score": "1",
"body": "I have looked at your code a few times, and have some thoughts, but I am wondering if you might be able to give a better description of its purpose, or at least confirm that it is meant to limit the number of requests a client sends a server within a specific period of time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T19:53:54.173",
"Id": "403460",
"Score": "0",
"body": "@Katie.Sun I've updated the original question to clarify the purpose of the code. I'd love to hear any thoughts you have!"
}
] | [
{
"body": "<h1>Object Oriented Javascript</h1>\n\n<p>Many people think that to write OO javascript you need to use the class syntax. This is not at all true. You can write very good OO javascript without ever using the class syntax, including inheritance, encapsulation (private and protected states), static properties, and polymorphism (JS is the polymorphic king) </p>\n\n<h2>Style and code</h2>\n\n<p>I can't help but feel there is a lot missing from your code.</p>\n\n<p>Problems I see</p>\n\n<ul>\n<li>It drops requests if they timeout but only when a new request is added by the same client. The object ignores all existing client requests if the client makes no more requests.</li>\n<li>You have a const <code>MAX_REQUESTS_IN_TIME_FRAME</code> but the code keeps on adding requests irrespective of this value when <code>addRequestAndCheckIsAllowed</code> is called.</li>\n<li>There is no easy way to know that the limit has been reached without creating and adding a new request. To me it seems like you may use the two objects to deduce this state, if so that would violate encapsulation rules, as that is for the object to do not external code.</li>\n</ul>\n\n<p>Some points on you code.</p>\n\n<ul>\n<li>Id is an abbreviation and as such is named with a lower case \"d\" ie <code>clientId</code> not <code>clientID</code></li>\n<li>Using <code>Array.filter</code> to remove items from an array is easy, but it generates lots of unused arrays for GC to clean up. Splicing items is far more efficient.</li>\n<li>It is good to break long lines into multiple lines to stop them going past the right of screen. However doing so for short lines just makes the code harder to read. You have done this in 3 places for lines that fit even the stack's snippets thin format. More thought on good names can help reduce line lengths.</li>\n<li><code>addRequestAndCheckIsAllowed</code> that is a mouth full, maybe <code>addRequestValidate</code> is a better option?</li>\n</ul>\n\n<h2>OO points</h2>\n\n<ul>\n<li>Underscore does not make a private variable, avoid its use as its just noise</li>\n<li>The constants <code>MAX_REQUESTS_IN_TIME_FRAME</code> and <code>REQUEST_MAX_AGE</code> also are public, and just add to the global scope. Put them inside the objects that use them.</li>\n<li><code>RequestBuffer</code> is only used by <code>RateLimiter</code>, it should not be visible outside <code>RateLimiter</code></li>\n<li><code>RequestBuffer</code> need only expose a way to store requests and a way to see if a request is valid. This can be done via a getter <code>allowed</code> and a setter <code>store</code></li>\n<li><code>RequestLimiter</code> should only expose the function <code>addRequestAndCheckIsAllowed</code> all the rest should be protected as private functions and properties.</li>\n<li>You create a client request ad hoc, should be an object created via a function. Better yet as it is strongly associated with the <code>RequestLimiter</code> you can add it as a static such as <code>RequestLimiter.Request</code> In the example I add it using define property to ensure it is protected</li>\n</ul>\n\n<h2>Encapsualtion and private state</h2>\n\n<p>An important part of OO code is that you can protect the object's state by limiting access. In many languages this is done by declaring private variables and methods. Javascript does have a way to define private objects properties but it is very new, and personally because it adds a prefix to the variable name I can not agree with its use. There is a better way.</p>\n\n<p>If you use function syntax to define objects. You can protect state via closure. You can protect object properties using <code>Object.freeze</code> or use <code>Object.defineProperty</code>. You can add statics directly to the function or via <code>Object.defineProperty</code> to protect them.</p>\n\n<h2>Getters and Setters</h2>\n\n<p>Additionally to help protect an object's state, objects use functions to access properties. These are called getters and setters and allow the objects to ensure only valid states can be set, or read. It also allows you to easily define read or write only properties.</p>\n\n<h2>Rewrite</h2>\n\n<p>The rewrite uses function syntax to create the same objects as your code. It includes examples of a getter, a setter, a static and private properties and objects via closure. I renamed <code>RequestBuffer</code> to just <code>Buffer</code> as it is inferred by context what it holds and the name no longer lives in the global scope.</p>\n\n<p>The code feels like its missing functionality, but I can only go by what you have supplied.</p>\n\n<pre><code>function RateLimiter() {\n const buffers = {}, MAX_IN_TIME_FRAME = 100, MAX_AGE = 1000;\n function Buffer(maxAge = MAX_AGE) {\n const requests = [];\n function update() { \n var i = requests.length;\n const maxTime = Date.now() - maxAge; \n while (i--) {\n if (requests[i].time >= maxTime) { requests.splice(i, 1) }\n }\n }\n return {\n set store(request) {\n requests.push(request);\n update();\n },\n get allowed() { return requests.length <= MAX_IN_TIME_FRAME }\n };\n }\n function addClient(id) {\n if (buffers[id]) { return buffers[id] }\n return buffers[id] = Buffer();\n }\n return Object.freeze({ // freeze the interface to protect state \n addRequestValidate(request) {\n const buffer = addClient(request.clientId);\n buffer.store = request;\n return buffer.allowed;\n },\n canClientRequest(id) { return buffers[id] ? buffers[id].allowed : true }\n });\n}\nObject.defineProperty(RateLimiter, 'Request', { // Request constructor as a static of RateLimiter\n enumerable: false, configurable: false, writable: false,\n value: function(clientId) { return { clientId, time: Date.now() } }\n});\n</code></pre>\n\n<p>Using function syntax to define object makes the <code>new</code> token optional.</p>\n\n<pre><code>const rateLimiter = new RateLimiter(); \n//const rateLimiter = RateLimiter();// works the same\n\nconst request = RateLimiter.Request(1);\n// or \n// const request = new RateLimiter.Request(1);\n\nconst isRequestAllowed = rateLimiter.addRequestValidate(request);\n</code></pre>\n\n<h2>The state of <code>this</code></h2>\n\n<p>I personally believe that good OO JavaScript rarely uses the <code>this</code> token. You will notice that <code>this</code> is not used at all in the above code.</p>\n\n<p>The token <code>this</code> can be so ubiquitous that it occurs multiple times on almost every line of code, it becomes noise, detracting from the overall readability. You used the token 'this' 15 times and your code contains 15 lines of expressions and statements.</p>\n\n<p>More importantly <code>this</code> is JavaScript's achilles heel as it can be easily hijacked. Many people do this as standard practice via <code>Function.call</code>. This means that no matter how much effort you put into protecting an object's state you can never fully trust the state of <code>this</code></p>\n\n<p>Example using <code>Function.call</code> to change object's state</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class ObjA1 {\n constructor() { this.a = \"A\" }\n log() { console.log(this.a) }\n}\nconst a = new ObjA1();\na.log(); // State is correct\n\n// Hijacking the state.\na.log.call({get a(){console.log(\"Hijacked and running external code\"); return \"Boo\"; }}); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>What is even more worrying is if you have code running on a public page (ie you have 3rd party advertising scripts) <code>this</code> can be hijacked by malicious 3rd parties and used to gain access to secure content. </p>\n\n<p>The class syntax encourages you to use the token <code>this</code> while function syntax is more conducive to defining a trusted named state.</p>\n\n<pre><code>function ObjA1() {\n const obj = { // this is replaced by obj\n a : \"A\",\n log() { console.log(obj.a) }\n }\n return obj;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T19:55:16.510",
"Id": "403461",
"Score": "0",
"body": "Thank you so much for your extensive comments. Your thoughts on privacy, security and getters and setters are extremely useful. And thank you for your example refactor. I'm going to do my own refactor based on your remarks to try out your ideas. Thank you so much! @Blindman67"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T12:20:29.500",
"Id": "208817",
"ParentId": "208771",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T15:58:48.927",
"Id": "208771",
"Score": "1",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Request rate limiter"
} | 208771 |
<h1>Input</h1>
<p><code>n</code> number of workers and <code>m</code> jobs to be scheduled, followed by <code>m</code> lines of time <code>t</code> taken by a particular job to be completed.</p>
<p>workers(or threads) take jobs in the order they are given in the input. If there is a free thread, it immediately
takes the next job from the list. If a thread has started processing a job, it doesn’t interrupt or stop
until it finishes processing the job. If several threads try to take jobs from the list simultaneously, the
thread with smaller index takes the job. For each job you know exactly how long will it take any thread
to process this job, and this time is the same for all the threads. You need to determine for each job
which thread will process it and when will it start processing.</p>
<h1>Output</h1>
<p><code>m</code> lines. <code>i-th</code> line containing two space-separated integers - 0 based index of the thread which will process the <code>i-th</code> job and its start time</p>
<h1>Constraints</h1>
<p>0 ≤ n ≤ 10<sup>5</sup> (<em>number of workers</em>)</p>
<p>0 ≤ m ≤ 10<sup>5</sup> (<em>number of jobs</em>)</p>
<p>0 ≤ t ≤ 10<sup>9</sup> (<em>time taken for each job</em>)</p>
<h1>My Approach</h1>
<p>I have used a heap to represent a priority queue of the threads to determine the next worker. The workers are first prioritized by their <code>next free time</code> and then by their <code>index</code>. To represent these two quantities I've used the <code>pair</code> in c++ stl.</p>
<p>Here is my code:</p>
<pre><code>#include <algorithm>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::make_pair;
using std::pair;
using std::swap;
using std::vector;
class JobQueue {
private:
int num_workers_;
vector<int> jobs_;
vector<int> assigned_workers_;
vector<long long> start_times_;
void WriteResponse() const {
for (int i = 0; i < jobs_.size(); ++i) {
cout << assigned_workers_[i] << " " << start_times_[i] << "\n";
}
}
void ReadData() {
int m;
cin >> num_workers_ >> m;
jobs_.resize(m);
for (int i = 0; i < m; ++i) cin >> jobs_[i];
}
void heapify(vector<pair<int, long long>> &heap, int k) {
int smallest = k;
int left = (2 * k) + 1;
int right = (2 * k) + 2;
if (left < heap.size()) {
if (heap[left].second < heap[smallest].second)
smallest = left;
else if (heap[left].second == heap[smallest].second) {
if (heap[left].first < heap[smallest].first) smallest = left;
}
}
if (right < heap.size()) {
if (heap[right].second < heap[smallest].second)
smallest = right;
else if (heap[right].second == heap[smallest].second) {
if (heap[left].first < heap[smallest].first) smallest = right;
}
}
if (left < heap.size() && right < heap.size() &&
heap[left].second == heap[right].second) {
if (heap[left].first < heap[right].first)
smallest = left;
else
smallest = right;
}
if (smallest != k) {
swap(heap[k], heap[smallest]);
heapify(heap, smallest);
}
}
void changePriority(vector<pair<int, long long>> &heap, int incr) {
heap[0].second += incr;
heapify(heap, 0);
}
void AssignJobs() {
assigned_workers_.resize(jobs_.size());
start_times_.resize(jobs_.size());
vector<pair<int, long long>> next_free_time(num_workers_);
for (int i = 0; i < num_workers_; i++) {
next_free_time[i].first = i;
next_free_time[i].second = 0;
}
for (int i = 0; i < jobs_.size(); ++i) {
pair<int, long long> next_worker = next_free_time[0];
assigned_workers_[i] = next_worker.first;
start_times_[i] = next_worker.second;
changePriority(next_free_time, jobs_[i]);
}
}
public:
void Solve() {
ReadData();
AssignJobs();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
JobQueue job_queue;
job_queue.Solve();
return 0;
}
</code></pre>
<h1>Complexity</h1>
<p>if <code>J</code> is the number of jobs and <code>T</code> the number of threads, the complexity here (I might be wrong, please correct me if I am) should be <code>O(J log T)</code></p>
<h1>Question</h1>
<p>The code exceeds time limit in certain cases, how can I optimize it? (Time limit: 1 sec)</p>
| [] | [
{
"body": "<p>Know your standard library! In this case, there's a heap container provided for us, called <code>std::priority_queue</code>. If we use it, we can remove all of the heap management code we've reinvented, and focus on the algorithm itself. Note that we will need to <code>pop()</code> and <code>push_back()</code> to reposition a thread when we assign work; this operation remains O(log <em>T</em>), and is likely much better than re-heapifying the entire heap at each iteration.</p>\n\n<p>Remember that <code>std::pair</code> already has a <code><</code> operator that does exactly what we want, if we order it so that next free time is the first element and thread index the second.</p>\n\n<p>The split between <code>main()</code> and <code>JobQueue</code> seems a bit stilted to me. I'd expect <code>main()</code> to read the initial inputs and use them to create an appropriately-dimensioned <code>JobQueue</code>, and then to feed inputs to it. And finally, to inspect the next starting time and to print it. At present, <code>JobQueue</code> seems to have two responsibilities mixed together - it's both calculating and performing I/O and it's hard to separate the two (e.g. for unit testing).</p>\n\n<p>I don't think there's any need to store the job values or the start times - we can simply return the start time from the <code>insert_job()</code> method and print it immediately.</p>\n\n<p><del>To store times, <code>long long</code> could be overkill - for a range of 0 to 10⁹, we only need 30 bits, so we could use <code>uint_fast32_t</code> for those.</del> For the number of workers, <code>std::size_t</code> is probably most appropriate, as we'll use that for capacity in our heap.</p>\n\n<p>We need a range of 0 to 10¹⁴ for times, so <code>long long</code> could be overkill. We could possibly get away with maintaining a single \"epoch\" value and only store the last few dozen bits in a <code>uint_fast32_t</code> in the pair - use one or more high-order bits to determine whether value is relative to the current epoch or to the previous one. Remember that with each individual job limited to 10⁹ units, there's only two valid epochs to consider at any given time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T11:34:52.707",
"Id": "208923",
"ParentId": "208772",
"Score": "1"
}
},
{
"body": "<p>Sadly, I have to disagree with some parts of Toby Speights answer.</p>\n<h1>Heap performance</h1>\n<p>Using a <code>std::priority_queue</code> (or falling back onto <code>std::make_heap</code>) sounds like a good idea at the first moment - until you look at what <code>heapify</code> actually does.</p>\n<ul>\n<li><p><code>std::priority_queue::pop</code> basically has to move the last element into the first place, and then bubble it down using likely <span class=\"math-container\">\\$\\mathcal{O}(\\log T)\\$</span> bubble down operations (since it was on the lowest level before, it will likely return there).</p>\n</li>\n<li><p><code>std::priority_queue::push</code> (not <code>push_back</code>) then inserts the changed element at the last position of the heap, then bubbling it up until it reaches its final position. This depends on the actual time values on the heap, so I call this <span class=\"math-container\">\\$R\\$</span> bubble up operations.</p>\n</li>\n<li><p><code>heapify</code> instead changes the value of the front element directly, and then bubbles it down. Using the values from above, this will take <span class=\"math-container\">\\$\\mathcal{O}(\\log T) - R\\$</span> bubble down operations.</p>\n</li>\n</ul>\n<p>Unless the newly inserted value will be on the lowest level of the heap (i.e. <span class=\"math-container\">\\$R = 0\\$</span>), heapify will require less operations (<span class=\"math-container\">\\$\\mathcal{O}(\\log T) - R\\$</span>) than <code>pop</code> + <code>push</code> (<span class=\"math-container\">\\$\\mathcal{O}(\\log T) + R\\$</span>).</p>\n<h1>Time compression</h1>\n<p>The suggested time compression format, while likely working, seems a bit overkill. Unless testing shows it's measurably faster in the intended use case I'd stay with the more readable current version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T01:21:48.143",
"Id": "403692",
"Score": "0",
"body": "@TobySpeight: Usually, I would have written a comment about this instead of an answer, but I couldn't fit my arguments into one. I fully agree with the other parts of your answer not mentioned here, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T01:17:08.713",
"Id": "208969",
"ParentId": "208772",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T15:59:01.713",
"Id": "208772",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"simulation"
],
"Title": "Parallel processing simulation"
} | 208772 |
<p>When you try to use several decorators it can get <em>ugly</em> pretty quickly and you'll end up with:</p>
<blockquote>
<pre><code>new RelativeFileProvider(
new SystemVariableFileProvider(
new PhysicalFileProvider()
),
"%TEMP%"
);
</code></pre>
</blockquote>
<p>or if you prefer one-liners then like that:</p>
<blockquote>
<pre><code>new RelativeFileProvider(new SystemVariableFileProvider(new PhysicalFileProvider()), "%TEMP%");
</code></pre>
</blockquote>
<p>I thought I turn them into extensions and make them play along nicer in a functional way so I created a couple of helper methods that allow me to do this:</p>
<pre><code>new PhysicalFileProvider()
.DecorateWith(SystemVariableFileProvider.Create())
.DecorateWith(RelativeFileProvider.Create("%TEMP%"));
</code></pre>
<p>Don't be confused about the empty classes. To be able to experiment without being distracted by the implementations I extracted the interface and the classes from my question about <a href="https://codereview.stackexchange.com/questions/207585/multiple-file-access-abstractions">Multiple file access abstractions
</a> that I'm going to use this <em>pattern</em> for. They all have implementations that have been already reviewed there. This question is about the additional <em>decorator helper</em> APIs and they are implementation-netural.</p>
<p>Here are the types I used:</p>
<h3>Version 1 - with an exntesion</h3>
<pre><code>interface IFileProvider
{
}
class PhysicalFileProvider : IFileProvider
{
public static PhysicalFileProvider Create()
{
return new PhysicalFileProvider();
}
}
class RelativeFileProvider : IFileProvider
{
public RelativeFileProvider(IFileProvider fileProvider, string basePath)
{
}
public static Func<IFileProvider, RelativeFileProvider> Create(string basePath)
{
return decorable => new RelativeFileProvider(decorable, basePath);
}
}
class SystemVariableFileProvider : IFileProvider
{
public SystemVariableFileProvider(IFileProvider fileProvider)
{
}
public static Func<IFileProvider, SystemVariableFileProvider> Create()
{
return decorable => new SystemVariableFileProvider(decorable);
}
}
static class FileProviderExtensions
{
public static IFileProvider DecorateWith(this IFileProvider decorable, Func<IFileProvider, IFileProvider> createDecorator)
{
return createDecorator(decorable);
}
}
</code></pre>
<hr>
<h3>Version 2 - with an interface</h3>
<p>This API forces each type to implement the <code>DecorateWith</code> method instead of relying on an extension.</p>
<pre><code>interface IDecorable<T>
{
T DecorateWith(Func<T, T> createDecorator);
}
interface IFileProvider : IDecorable<IFileProvider>
{
}
class PhysicalFileProvider : IFileProvider, IDecorable<IFileProvider>
{
public static PhysicalFileProvider Create()
{
return new PhysicalFileProvider();
}
public IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)
{
return createDecorator(this);
}
}
class RelativeFileProvider : IFileProvider, IDecorable<IFileProvider>
{
public RelativeFileProvider(IFileProvider fileProvider, string basePath)
{
}
public static Func<IFileProvider, RelativeFileProvider> Create(string basePath)
{
return decorable => new RelativeFileProvider(decorable, basePath);
}
public IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)
{
return createDecorator(this);
}
}
class SystemVariableFileProvider : IFileProvider, IDecorable<IFileProvider>
{
public SystemVariableFileProvider(IFileProvider fileProvider)
{
}
public static Func<IFileProvider, SystemVariableFileProvider> Create()
{
return decorable => new SystemVariableFileProvider(decorable);
}
public IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)
{
return createDecorator(this);
}
}
</code></pre>
<hr>
<p>And these are the <strong>why</strong>s about the factories:</p>
<ul>
<li>I chose static factory methods over <em>free</em> arguments to keep parameter names and their order.</li>
<li>I chose them also to avoid <code>new</code>.</li>
</ul>
<hr>
<p>What do you think of this <em>system</em>? Do you prefer one version over the other? Can this be made even more convinient? Or would you say this is madness?</p>
| [] | [
{
"body": "<p>IMO the first version is easier to maintain, and I don't see from the shown code, what you gain by the second.</p>\n\n<hr>\n\n<p>In the second version:</p>\n\n<p>Each <code>FileProvider</code> class doesn't need to explicitly inherit <code>IDecorable<IFileProvider></code> because that is inherited via <code>IFileProvider</code>.</p>\n\n<hr>\n\n<p>I maybe overlooking something or you may find it too obvious to show, but I don't like that you implement the interface <code>IFileProvider</code> in all the provider classes, because they then are forced to implement all (I can see there aren't any (yet)) possible common members, which could be taken care of in a base class. Therefore I would create an abstract base class for the providers like:</p>\n\n<pre><code> interface IDecorable<T>\n {\n T DecorateWith(Func<T, T> createDecorator);\n }\n\n interface IFileProvider : IDecorable<IFileProvider>\n {\n\n }\n\n abstract class FileProvider : IFileProvider\n {\n public virtual IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)\n {\n return createDecorator(this);\n }\n }\n\n class PhysicalFileProvider : FileProvider\n {\n public static PhysicalFileProvider Create()\n {\n return new PhysicalFileProvider();\n }\n }\n\n class RelativeFileProvider : FileProvider\n {\n public RelativeFileProvider(IFileProvider fileProvider, string basePath)\n {\n\n }\n\n public static Func<IFileProvider, RelativeFileProvider> Create(string basePath)\n {\n return decorable => new RelativeFileProvider(decorable, basePath);\n }\n }\n ...\n</code></pre>\n\n<p>In this way you gain both the benefits of normal OOP inheritance/polymorphic behavior and the decorator pattern and at the same time are still free to chain <code>.DecorateWith(...)</code> with other implementers of <code>IFileProvider</code></p>\n\n<hr>\n\n<p>Madness is a strong word. The shown chain looks a little nicer than a chain of <code>new xx()</code> statements, and you explicitly \"explain\" the pattern and behavior. And the first version doesn't need much attention when first written, so no harm done at least.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T08:04:18.360",
"Id": "208812",
"ParentId": "208775",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208812",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T16:06:01.070",
"Id": "208775",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"comparative-review",
"extension-methods"
],
"Title": "Squeezing decorators into functional extensions"
} | 208775 |
<p>I have one route that switches the routes based on the permission the user has. Here is a little example:</p>
<pre><code>public function show(Company $company)
{
if(auth()->user()->hasPermission('read-companies')) {
return view('portal.company.showAdmin', compact('company'));
} elseif (auth()->user()->hasPermission('read-company') && auth()->user()->companies->contains($company)) {
return view('portal.company.showEntrepreneur', compact('company'));
} elseif(auth()->user()->hasPermission('read-companies_v') && $company->visible()) {
return view('portal.company.showTrainee', compact('company'));
} else {
abort('403');
}
}
</code></pre>
<p>This basicly returns to 3 views based on the permissions of the user. A lot of my controller functions look like this. Now my question: Is this "One controller/route for multiple actions" approach a bad Idea? What if I want to add a role to the <code>auth()->user()->companies->contains($company)</code> many to many relationship? I would need to add all my controller functions. Is it better to have a function on the user model like <code>IsAbleToShowOnCompany($company)</code>? But than I would have houndreads of functions like that, because, e.g., Companys can create pokes, and I would need to check if the role of the many to many relation to company would allow that. </p>
<p>Do you have any refactor Ideas?</p>
<p>I've heard about service and repository classes, but how can I refactor this into a servivce? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:46:06.467",
"Id": "449938",
"Score": "0",
"body": "Are the views all that different from each other? If not, maybe you could check permissions in the view"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T18:08:07.293",
"Id": "208783",
"Score": "1",
"Tags": [
"php",
"laravel",
"controller",
"authorization"
],
"Title": "Laravel Controller function to return view based on user permission"
} | 208783 |
<p>Question is taken from Leetcode and solution works for their test cases. I do see a scope of improvement and make it more functional (getting rid of vars and mutables data structures). Please suggest improvement to help me.</p>
<p><strong>Problem</strong></p>
<p>Given a string, find the length of the longest substring without repeating characters.</p>
<pre><code>Input: "abcabcbb"
Output: 3
Input: "bbbbb"
Output: 1
Input: "pwwkew"
Output: 3
</code></pre>
<p><strong>code</strong></p>
<pre><code>import scala.collection.mutable.HashMap
object Solution extends App{
def lengthOfLongestSubstring(s: String): Int = {
if (s.isEmpty) 0
else {
val lookupTable = HashMap[Char,Int]()
var start = 0
var length = 0
for ( (c, i) <- s.zipWithIndex) {
if (!(lookupTable contains c)) {
lookupTable(c) = i
} else {
val newLength = i - start
if (newLength > length) length = newLength
start = lookupTable(c) + 1
lookupTable.retain((k,v) => v >= start)
lookupTable(c) = i
}
}
Math.max(length, (s.length - start))
}
}
Seq("abcabcbb", "pwwkew", "", "nnnn", "b", " ", "aab" , "abca" ,"abba") foreach { s =>
println(s + " = " + lengthOfLongestSubstring(s))
}
}
</code></pre>
<p><strong>Output</strong></p>
<pre><code>abcabcbb = 3
pwwkew = 3
= 0
nnnn = 1
b = 1
= 1
aab = 2
abca = 3
abba = 2
</code></pre>
| [] | [
{
"body": "<p>Some observations while looking over the code:</p>\n\n<ol>\n<li><code>if (s.isEmpty) 0</code> - This isn't necessary. The code produces the correct results without this test. Removing it would reduce the level of indenting for the rest of the code.</li>\n<li><code>if (!(lookupTable contains c))</code> - <a href=\"https://en.wikipedia.org/wiki/Edsger_W._Dijkstra\" rel=\"nofollow noreferrer\">Dijkstra</a> suggests that it is usually better to test for the positive condition, especially when there is an <code>else</code> block. It's often much easier to read and parse that way. In this case the <code>else</code> condition is \"NOT table has c == false\". (<em>Ouch!</em>)</li>\n<li><code>val newLength</code> - You actually don't need this variable. Try:<code>length = length max i - start</code></li>\n<li><p><code>lookupTable(c) = i</code> - This assignment is made on both sides of the <code>if</code> test, which means it really doesn't belong there.</p>\n\n<pre><code>if (lookupTable contains c) {\n length = length max i - start\n start = lookupTable(c) + 1\n lookupTable.retain((k,v) => v >= start)\n}\nlookupTable(c) = i\n</code></pre></li>\n</ol>\n\n<p>But, of course, the most noteworthy is the use of mutable variables and data structures. Sometimes we have to fall back on imperative programming if functional means/methods are creating a bottleneck, but, short of that, the point of learning/using Scala is its Functional Programming capability.</p>\n\n<p>Here's a reworking of the same algorithm using two index values to access a static array of characters. Each index is advanced via tail-recursive methods so everything remains immutable.</p>\n\n<pre><code>def lengthOfMaxSubstring(s: String): Int = {\n val chars: Array[Char] = s.toArray\n\n def headForward(leadx: Int, rearx: Int, cSet: Set[Char], best: Int): Int = {\n\n def tailForward(tlx: Int, cs: Set[Char]): (Int, Set[Char]) =\n if (chars(tlx) == chars(leadx)) (tlx + 1, cs)\n else tailForward(tlx + 1, cs - chars(tlx))\n\n if (leadx >= chars.length) best max leadx-rearx\n else if (cSet(chars(leadx))) {\n val (newTail, newSet) = tailForward(rearx, cSet)\n headForward(leadx+1, newTail, newSet, best max leadx-rearx)\n } else\n headForward(leadx+1, rearx, cSet + chars(leadx), best)\n }\n headForward(0, 0, Set(), 0)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T05:05:53.517",
"Id": "208912",
"ParentId": "208785",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T19:30:03.873",
"Id": "208785",
"Score": "3",
"Tags": [
"strings",
"array",
"interview-questions",
"functional-programming",
"scala"
],
"Title": "Longest Substring Without Repeating Characters in Scala"
} | 208785 |
<p>I don't know anything about parsers but I had to write something to read COBOL for a work project. What are some things that I could improve with my Python coding and parser design?</p>
<p>Note: This isn't COBOL feature complete yet, just the things I need for the project.</p>
<pre><code>"""
Parse COBOL copybook files to a Python list for EBCDIC reading
"""
#! /usr/bin/env python
import re
from os import path
# Only the handful I care about really
COBOL_KEYWORDS = {"COMP-3", "PIC", "REDEFINES", "OCCURS", "TIMES", "SIGN", "IS"}
class COBOLParser:
"""
Takes a file path as an argument. Run the parse method on returned object
to convert to a python readable format.
"""
def __init__(self, file: str):
if not path.isfile(file):
raise FileNotFoundError
self.file = file
# This here object keeps track of what level ID groups are in in. This
# is not needed in the final data, but is nescessary for determining
# what level to place a new item on after leaving a group so it is
# stored seperately
self.group_levels = []
def parse(self) -> list:
"""
Parse and return self.file as a list of python dictionaries
"""
parse_out = []
with open(self.file, "rt") as cobol_file:
line_number = 0
previous_field_level = 0
previous_group_level = 0
unfinished_item = {}
for line in cobol_file:
line_number += 1
# skip comment lines and empty lines
if not line.strip() or line.strip()[0] == "*":
continue
parse_out = self.parse_line(parse_out, line, line_number)
# Check for duplicate names
group = (
self._item_level(parse_out, self.group_levels[-1][1])
if self.group_levels
else parse_out
)
if (
group
and not unfinished_item
and group[-1:][0]["Name"] != "FILLER"
and group[-1:][0]["Name"]
in [item["Name"] for item in group[:-1]]
):
raise InvalidCOBOLError(
line_number, "Duplicate names in a group."
)
# Check for proper line ending
if (
unfinished_item
and unfinished_item["Name"]
!= self._lowest_dict(parse_out)["Name"]
):
raise InvalidCOBOLError(
line_number - 1, "Unended line was not continued."
)
# Make sure that the level is lesser than or equal to the last
# field level if previous level is a field. Then set a new
# value for previous_line_level.
if (
not unfinished_item
and previous_field_level
and int(line.strip()[:2]) > previous_field_level
):
raise InvalidCOBOLError(
line_number, "Field has sub entries at line {}"
)
# If a group was created the item after the group needs to be a
# member of said group, otherwise, raise error
if (
not unfinished_item
and previous_group_level
and int(line.strip()[:2]) <= previous_group_level
):
raise InvalidCOBOLError(
line_number - 1, "Group has no sub elements at line {}."
)
# Save information about last read line for easier error
# checking.
if (
not unfinished_item
and self._lowest_dict(parse_out)["Type"] == "Field"
):
previous_field_level = int(line.strip()[:2])
previous_group_level = 0
elif not unfinished_item:
previous_group_level = int(line.strip()[:2])
previous_field_level = 0
# Check for EOL character in string
line_ended_check = r"(\w|\d|\))+\.(\s|$)"
if not re.search(line_ended_check, line):
unfinished_item = self._lowest_dict(parse_out)
else:
unfinished_item = {}
return parse_out
def parse_line(
self, out_builder: list, line: str, line_number: int
) -> list:
"""
Parses a COBOL line and creates a new item in the output builder. If
the line is a continuation of a previous line, just add the new info to
the previously added entry.
"""
if out_builder:
last_element = self._lowest_dict(out_builder)
else:
last_element = {}
items = [x for x in line.strip().split()]
# Strip out closing periods from items, then strip out items that come
# after the period
for item in items:
if item[-1:] == ".":
line_ended = True
last_item = items.index(item)
items = items[: last_item + 1]
items[last_item] = items[last_item][:-1]
else:
line_ended = False
try:
# Check first item (should be level if not a line continuation)
# Level should be two digits, representing a number between 01 and
# 49. COBOL standards also allow 66 and 88 as levels with specific
# rules. These are not supported yet but if they are in the future
# replace below regex with the following: (?!00)(66|88|[0-4][[0-9])
if re.match(r"(?!00)[0-4][0-9]", items[0]):
current_level = items[0]
# Check whether line is a continuation of previous line
# As of right now, only PIC and Usage are allowed to continue
# onto another line, (both only existing on fields
elif (
items[0] == "PIC"
and last_element
and "Format" not in last_element.keys()
):
last_element["Format"] = self._clause_value(items, "PIC")
last_element["Type"] = "Field"
# Check if continued line also has usage clause
# PIC is always two items long, check after
if len(items) == 3 and self._valid_usage(items[2]):
last_element["Usage"] = items[2]
return out_builder
elif (
last_element
and last_element["Type"] == "Field"
and self._valid_usage(items[0])
and "Usage" not in last_element.keys()
):
last_element["Usage"] = items[0]
return out_builder
else:
raise InvalidCOBOLError(
line_number, "Input does not resemble COBOL at line {}"
)
# At this point we know this is a new field or group. Get the group
# name and save it in a dictionary representing the new item. Also
# check for invalid names
new_item = {"Name": items[1]}
# Get the list of fields for the group the current item belongs to
current_group = self._item_level(out_builder, int(current_level))
if new_item["Name"] in COBOL_KEYWORDS:
raise InvalidCOBOLError(
line_number,
"Field or group name at line {} matches a COBOL keyword",
)
try:
clause_error = InvalidCOBOLError(
line_number,
"A clause was declared but no definition was given.",
)
if "REDEFINES" in items:
new_item["Redefines"] = self._clause_value(
items, "REDEFINES"
)
if new_item["Redefines"] in COBOL_KEYWORDS:
raise clause_error
if "OCCURS" in items:
if items[items.index("OCCURS") + 2] != "TIMES":
raise clause_error
try:
new_item["Occurs"] = int(
self._clause_value(items, "OCCURS")
)
except ValueError:
raise InvalidCOBOLError(
line_number,
"Occurs clause must specify an integer value at line {}.",
)
if "PIC" not in items and line_ended:
# Append the newly added group to group_levels
self.group_levels.append(
(new_item["Name"], int(current_level))
)
new_item["Type"] = "Group"
new_item["Fields"] = []
current_group.append(new_item)
return out_builder
# Item is field
new_item["Type"] = "Field"
if "PIC" in items:
new_item["Format"] = self._clause_value(items, "PIC")
if new_item["Format"] in COBOL_KEYWORDS:
raise clause_error
# Check for usage clause.
usage_index = items.index("PIC") + 2
if len(items) > usage_index:
if self._valid_usage(items[usage_index]):
new_item["Usage"] = items[usage_index]
else:
raise InvalidCOBOLError(
line_number,
(
"Usage clause does not match an existing "
"definition at line {}"
),
)
except IndexError:
raise clause_error
current_group = self._item_level(out_builder, int(current_level))
current_group.append(new_item)
return out_builder
except IndexError:
raise InvalidCOBOLError(
line_number, "Input does not resemble COBOL at line {}"
)
def _item_level(self, struct: list, current_level: int) -> list:
"""
Returns a list corresponding what group an item should belong to.
"""
if not struct or not self.group_levels:
return struct
# We only care about the last level of a matching group. Check groups
# in reverse.
if current_level > self.group_levels[-1][1]:
return self._lowest_list(struct)
for group in self.group_levels[::-1]:
# Return the fields of the first group that has a lower level than
# the current item's level.
if group[1] < current_level:
return self._lowest_list(struct, group[0])
return struct
def _lowest_dict(self, struct: list) -> dict:
"""
Returns the deepest dictionary at the bottom of provided structure.
"""
last_element = struct[-1:][0]
if "Fields" in last_element.keys() and last_element["Fields"]:
return self._lowest_dict(last_element["Fields"])
return last_element
def _lowest_list(self, struct: list, name: str = None) -> list:
"""
Returns the deepest list at the bottom of provided stucture. If a name
parameter is provided, stop searching and return list with matching
name.
"""
if not struct:
return struct
last_element = struct[-1]
if (
name
and last_element["Name"] == name
and "Fields" in last_element.keys()
):
return last_element["Fields"]
if "Fields" in last_element.keys():
return self._lowest_list(last_element["Fields"])
return struct
@staticmethod
def _clause_value(items: list, clause: str) -> str:
"""
Returns the item from a list of items following the provided clause.
"""
value = items[items.index(clause) + 1]
return value
@staticmethod
def _valid_usage(usage: str) -> bool:
"""
Returns bool indicating whether provided usage is valid or not.
"""
# Not really an indication of valid usages as much as a list of what
# usages the EBCDIC reader we use supports.
valid_usages = ["COMP-3"]
return usage in valid_usages
class InvalidCOBOLError(Exception):
"""
Produces an error message with a line number showing which line of code
contains the Invalid COBOL. msg parameter should contain a set of empty
square brackets, although if not, a set will be appended to the end of the
message.
"""
def __init__(self, line, msg=None):
if msg is None:
# Try to not let this happen
msg = (
"There was an unspecified error while parsing the COBOL at "
"line {}. Please contact a developer for assistance."
)
elif not "{}" in msg:
msg = msg + " (Line {})."
msg = msg.format(line)
super(InvalidCOBOLError, self).__init__(msg)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T23:17:13.893",
"Id": "403369",
"Score": "2",
"body": "An alternative approach is to look at **cb2xml** https://sourceforge.net/projects/cb2xml/) it will convert the Cobol to Xml. cb2xml is written java but there is an example of reading the Xml in python. cb2xml. Alternative cb2xml is written using sablecc; sablecc can generate pyhtonas well as java."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T23:17:32.370",
"Id": "403370",
"Score": "0",
"body": "there is also stingray https://sourceforge.net/projects/stingrayreader/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T23:41:08.740",
"Id": "403371",
"Score": "1",
"body": "There are a lot of quirks in `COBOL`, the existing parsers will deal with many of them. Take `comp-3` it can also be written as `computational-3`, it can be specified with/without usage and at either field or group level."
}
] | [
{
"body": "<p><code>group[-1:][0][\"Name\"]</code></p>\n\n<p>This expression is reused, so assign it to a variable name.</p>\n\n<p><code>in [item[\"Name\"] for item in group[:-1]]</code></p>\n\n<p>For a membership test, a set is a better idea than a list.</p>\n\n<p><code>int(line.strip()[:2])</code></p>\n\n<p>This is reused a bunch of times, so make a variable.</p>\n\n<p><code>line_ended_check = r\"(\\w|\\d|\\))+\\.(\\s|$)\"</code></p>\n\n<p>You shouldn't initialize this regex where it is. It needs to be compiled once, outside of all of your parsing loops, using <code>re.compile</code>.</p>\n\n<p><code>elif not \"{}\" in msg:</code></p>\n\n<p>You should probably use <code>elif \"{}\" not in msg:</code> .</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T06:10:25.183",
"Id": "208808",
"ParentId": "208789",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208808",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-30T20:25:25.710",
"Id": "208789",
"Score": "4",
"Tags": [
"python",
"parsing",
"cobol"
],
"Title": "COBOL layout parser in Python"
} | 208789 |
<p>Question is taken from leet code.</p>
<p><strong>Problem</strong></p>
<p>Given two strings s and t , write a function to determine if t is an anagram of s.</p>
<p><strong>Examples</strong></p>
<pre><code>Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
</code></pre>
<p>Here is my implementation in scala</p>
<pre><code>import scala.collection.immutable.HashMap
object ValidAnagram extends App {
def validAnagram(s1: String, s2: String): Boolean = {
if (s1 == s2) true
else if (s1.length != s2.length) false
else {
val lookupTable = s1.foldLeft(HashMap[Char,Int]()) ((m,c) => m ++ HashMap(c -> (if (m contains c) m(c) + 1 else 1)))
println(lookupTable)
(s2.foldLeft(lookupTable) {(m,c) =>
if (m contains c) {
val count = m(c)
if (count > 1) {m + (c -> (count-1))} else m - c
} else m // we can return here if not functional
}).isEmpty
}
}
println(validAnagram(args(0), args(1)))
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T21:50:09.500",
"Id": "403466",
"Score": "0",
"body": "I don't know Scala, so cannot provide a code review. But something seems complicated (creating hashmaps and then cycling through the maps). The easy way to determine if anagram - order `s` and order `t` (by whatever efficient way possible). If the `s'` and `t'` are the same, then is an anagram."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T08:34:22.313",
"Id": "403599",
"Score": "1",
"body": "This is way too much code for such a basic task. If, for some reason, you don't want to sort the input before doing an equality check, you could build a `Map` equivalent of each input, i.e. `val m1 = s1.groupBy(identity)`, and do the equality check on that: `m1 == m2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T05:10:09.803",
"Id": "403708",
"Score": "0",
"body": "Thanks for the comments. Problem is taken from an interview question site.. where you are supposed to touch upon time and space complexity of solutions for worst cases and then provide the optimal solution.\n\n Yes sorting is the easiest way of checking this. And I would use the same in production code if my input strings are not very very long.\n\nBut as sorting may become expensive for larger string.. I chose going for populating a map."
}
] | [
{
"body": "<h2>Short circuit!</h2>\n\n<p>Check the lengths first. In the case that they aren't the same, you don't need to incur a linear pass for an equality check.</p>\n\n<h2>Don't check the hashmap for an entry!</h2>\n\n<p>It's good that you know <code>m(c)</code> can throw if there's a missing key; luckily, \n you can use <code>Map#getOrElse</code> and provide a default -- in this case, it makes sense to provide a 0 default since you haven't seen the character.</p>\n\n<h2>Compare the counts from each string directly!</h2>\n\n<p>I find the subtracting of the counts to be very confusing. You'll need to remove keys from the counter if any of the values go to 0, which lowers the signal to noise ratio of the code. It's better to just build a second counter.</p>\n\n<hr>\n\n<p>If you decide to build two counters and compare them, you'll need to do the same fold logic twice. This is really messy to write, so you won't want to do this twice. You may want to <a href=\"https://danielasfregola.com/2015/06/08/pimp-my-library/\" rel=\"nofollow noreferrer\">pimp out the String class</a>. You can do this in the following way:</p>\n\n<pre><code>implicit class Counter(s: String) {\n def countCharacters: Map[Char, Int] = \n s.foldLeft(Map.empty[Char, Int])({ case (acc, c) =>\n acc + (c -> (acc.getOrElse(c, 0) + 1))\n })\n}\n</code></pre>\n\n<p>You can see it in action here:</p>\n\n<pre><code>scala> \"hello\".countCharacters\nres0: Map[Char,Int] = Map(h -> 1, e -> 1, l -> 2, o -> 1)\n</code></pre>\n\n<p>So now you can compare the counts with a clean, non-repeated API.</p>\n\n<p>Pulling this all together, you can write:</p>\n\n<pre><code>object ValidAnagram extends App {\n\n // when I see a string, implicitly construct a `Counter` instance\n implicit class Counter(s: String) {\n // this will be \"added\" to the String API via an implicit class construction\n def countCharacters: Map[Char, Int] = \n s.foldLeft(Map.empty[Char, Int])({ case (acc, c) =>\n acc + (c -> (acc.getOrElse(c, 0) + 1))\n })\n }\n\n def validAnagram(s1: String, s2: String): Boolean =\n if (s1.length != s2.length) false\n else if (s1 == s2) true\n else s1.countCharacters == s2.countCharacters\n\n\n println(validAnagram(args(0), args(1)))\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T05:15:17.530",
"Id": "403710",
"Score": "0",
"body": "I really liked the ides of having an implicit for counter, it makes code very readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T02:56:23.800",
"Id": "208903",
"ParentId": "208799",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208903",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T00:26:29.593",
"Id": "208799",
"Score": "0",
"Tags": [
"strings",
"interview-questions",
"functional-programming",
"scala"
],
"Title": "find if one string is a valid anagram of another , in scala"
} | 208799 |
<p>I have this code to display a counter on the side of <code><i class="fas fa-bell mr-3"></i></code>. I want to know if this code is good on security and perfomance.</p>
<p>I just started using jquery and ajax, i had heard people saying that someone could disable the javascript and do bad things. What you guys think about my code?</p>
<pre><code> <div>
<ul class="navbar-nav textoPerfilDesk dropMenuHoverColor">
<li class="nav-item dropdown pr-2 dropleft navbarItem ">
<a class="nav-link dropdown-toggle-fk" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-bell mr-3"></i>
</a>
<div class="dropdown-menu dropdown-menu-fk py-3" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item dropMNitemNT" href="um-link">
<span class="d-flex">
<img class="imgNT" src="img/1.jpg">
<span class="pl-2 pt-1">
titutlo
</span>
</span>
</a>
</div>
</li>
</ul>
<span class="text-white divCountNT" id="datacount"></span>
</div>
</code></pre>
<p>script:</p>
<pre><code><script>
$(document).ready(function(){
var intervalo, carregaDiv;
(carregaDiv = function(){
$("#datacount").load('select.php', function(){
intervalo = setTimeout(carregaDiv, 1000);
});
})();
$('.fa-bell').on('click', function (){
clearTimeout(intervalo);
$.ajax({
url: "update.php",
complete: function(){
setTimeout(carregaDiv, 1000);
}
});
});
});
</script>
</code></pre>
<p>select.php</p>
<pre><code><?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['userid'])) {
$userid = $_SESSION['userid'];
}
$status = 'unread';
$sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND
userid = :userid");
$sql->bindParam(':userid', $userid, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
$conn = null;
?>
</code></pre>
<p>update.php</p>
<pre><code><?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['userid'])) {
$userid = $_SESSION['userid'];
}
$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE userid = :userid");
$sql->bindParam(':user_id', $userid, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
$conn = null;
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T15:24:57.773",
"Id": "403430",
"Score": "0",
"body": "(I'd be more inclined to delve into the code if comments, the introduction and, to the extent feasible, the title of this post told *who or what* is notified *how* about *what*.)"
}
] | [
{
"body": "<h3>JAVASCRIPT SECURITY</h3>\n<p>Javascript is running on the client, and is therefore under full control of the user. It can be disabled, inspected, manipulated, and everything else that can done in a programming language. You knew this, didn't you?</p>\n<p>Javascript is, almost by definition, insecure. Things that have to do with the security of your site, like validating passwords, should not be done in Javascript. And in your code you don't do anything security related in Javascript. All you do is set a timer running and call two PHP scripts. No risks there.</p>\n<br>\n<h3>PHP SECURITY</h3>\n<p>The PHP scripts are another matter. Here is where things really happen, and you should implement your security measures here. Even though these scripts implement AJAX calls, they can be executed by anybody.</p>\n<p>You seem to have users, that can log in. Their user ID is stored in <code>$_SESSION['userid']</code>. I notice that you don't do anything, in your PHP scripts, when this ID is absent. You still execute the database queries. That is a bad idea.</p>\n<p>When the two current PHP scripts are called, without an user ID, they will probably just perform database queries that are invalid. No real harm done. But you shouldn't rely on just pure luck. Good security should leave no doubts about what will happen.</p>\n<p>I therefore propose I slight change to your code. Instead of writing this:</p>\n<pre><code>if (isset($_SESSION['userid'])) {\n $userid = $_SESSION['userid'];\n}\n</code></pre>\n<p>you could write this:</p>\n<pre><code>if (!isset($_SESSION['userid'])) die('Not logged in.');\n$userid = $_SESSION['userid'];\n</code></pre>\n<p>this means that the PHP scripts will halt execution when there's no user, as they should.</p>\n<br>\n<h3>PERFORMANCE</h3>\n<p>You code is evidently not very efficient. Polling the database every second does not scale very well. There are other ways to do this. For instance with web sockets: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Websockets_API\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Websockets_API</a> ( you would use a combination of the tools mentioned there). Updates will be quicker, without polling.</p>\n<p>For now polling will probably be fine for you, after all you're still learning Jquery and that is a challenge in itself. It takes time to understand how everything hangs together.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T17:23:54.253",
"Id": "403799",
"Score": "0",
"body": "Lets talk about this paragraph `PHP SECURITY`. I use `echo` to print out on the screen the HTML code for this notification, and it's all inside a `if (!empty($user_id)) {` example: https://pastebin.com/wmty3PKd is it enough? This way i will not execute the queries if the user is not logged in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T17:25:54.833",
"Id": "403800",
"Score": "0",
"body": "And i changed `intervalo = setTimeout(carregaDiv, 1000);` to `intervalo = setTimeout(carregaDiv, 60000);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-05T08:34:02.337",
"Id": "403902",
"Score": "1",
"body": "Yes, as long as you check that there is a valid user, before you do user-related things, it should be fine. Raising the interval of the timer to 60 seconds will certainly help, but the principle won't change. I also noted that you 'chain' your timers, instead of having one timer created with `setInterval()`. Your counter will stop whenever a single connection problem is encountered. In other words: It's not robust."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T09:19:19.597",
"Id": "208990",
"ParentId": "208803",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "208990",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T03:18:28.497",
"Id": "208803",
"Score": "2",
"Tags": [
"php",
"jquery",
"security",
"ajax"
],
"Title": "Notification system using PHP+jQuery+Ajax"
} | 208803 |
<p>I would like to optimize this layout to improve rendering speed. How can I remove so many unnecessary components from the layout file?</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/ingameFrameLayout"
android:visibility="visible">
<com.kyunggi.sanggeoltopia2.InGameSurfaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/ingameSurfaceView"/>
<com.kyunggi.sanggeoltopia2.InGameViewOGL
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/ingameViewOGL"/>
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
android:visibility="visible">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_gravity="bottom|center_horizontal"
android:gravity="bottom|center_horizontal">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal">
<ImageButton
android:layout_height="50dp"
android:layout_width="50dp"
android:src="@android:drawable/ic_menu_sort_by_size"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#000000"
android:id="@+id/ingameIBMenu"/>
<ImageButton
android:layout_height="50dp"
android:layout_width="50dp"
android:src="@drawable/tbxinxi"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:scaleType="fitXY"
android:background="#ED6FD7"
android:id="@+id/ingameIBStat"/>
<ImageButton
android:layout_height="50dp"
android:layout_width="50dp"
android:src="@android:drawable/ic_search_category_default"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#0E5DEE"
android:scaleType="fitXY"
android:id="@+id/ingameIBTech"/>
<ImageButton
android:layout_height="50dp"
android:layout_width="50dp"
android:src="@drawable/nextturn_btn"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#2AF4D8"
android:id="@+id/ingameIBNextTurn"
android:scaleType="fitXY"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:id="@+id/ingameLLCapture">
<ImageView
style="?android:attr/buttonBarButtonStyle"
android:layout_height="50dp"
android:layout_width="50dp"
android:src="@drawable/capture"/>
</LinearLayout>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_gravity="bottom|center_horizontal"
android:gravity="bottom|center_horizontal"
android:id="@+id/ingameLLDesc"
android:visibility="invisible">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_gravity="bottom|center_horizontal"
android:gravity="center_horizontal"
android:background="#000000"
android:id="@+id/ingameLLDescIn">
<ImageView
android:layout_height="52dp"
android:layout_width="50dp"
android:src="@drawable/burning"
android:id="@+id/ingameDescIvImg"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_weight="1.0">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Forest,Game"
android:id="@+id/ingameDescTvTitle"
android:layout_gravity="center"
android:textColor="#FFFFFF"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Tap here to extract"
android:id="@+id/ingameDescTvDetail"
android:layout_gravity="center"
android:textColor="#FFFFFF"/>
</LinearLayout>
<ImageButton
android:layout_height="52dp"
android:layout_width="52dp"
android:src="@drawable/x_btn"
android:id="@+id/ingameDescIbBack"
android:background="#000000"
android:scaleType="fitXY"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_gravity="bottom|center_horizontal"
android:gravity="center_horizontal"
android:background="#000000"
android:id="@+id/ingameLLDescInBtns">
<ImageView
android:layout_height="52dp"
android:layout_width="50dp"
android:src="@drawable/burning"
android:id="@+id/ingameDescBtnsIvImg"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Forest,Game"
android:id="@+id/ingameDescBtnsTvTitle"
android:layout_gravity="center"
android:textColor="#FFFFFF"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Tap here to extract"
android:id="@+id/ingameDescBtnsTvDetail"
android:layout_gravity="center"
android:textColor="#FFFFFF"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_weight="1.0">
<HorizontalScrollView
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:id="@+id/ingameDescBtnsLL"/>
</HorizontalScrollView>
</LinearLayout>
</LinearLayout>
<ImageButton
android:layout_height="52dp"
android:layout_width="52dp"
android:src="@drawable/x_btn"
android:id="@+id/ingameDescBtnsIbBack"
android:background="#000000"
android:scaleType="fitXY"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/ingameFrameLayoutMenu"
android:visibility="invisible"
android:elevation="10dp">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#000000"
android:alpha="0.6">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Menu"
android:layout_marginTop="80dp"
android:textSize="26sp"
android:textColor="#FFFFFF"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Exit"
android:id="@+id/ingameBtExit"
android:elevation="11dp"
android:alpha="1.0"/>
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/ingameFrameLayoutStat"
android:visibility="invisible">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#000000">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Game mode"
android:layout_marginTop="80dp"
android:id="@+id/ingameStatTVTitle"
android:textColor="#FFFFFF"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Text"
android:id="@+id/ingameStatTVContent"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Back"
android:layout_margin="10dp"
android:id="@+id/ingameBtStatBack"/>
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/ingameFrameLayoutTech"
android:visibility="invisible"
android:background="#FFFFFF">
<ScrollView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#FFFFFF"
android:layout_marginTop="40dp">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="@+id/ingameLLTechContainer"/>
</ScrollView>
</FrameLayout>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="@+id/ingamellVictory"
android:gravity="top|center"
android:background="#000000">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="VICTORY!!!"
android:textSize="40sp"
android:textColor="#FFFFFF"
android:layout_marginTop="87dp"/>
<ImageView
android:layout_height="100dp"
android:layout_width="100dp"
android:src="@drawable/capture"
android:scaleType="fitXY"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="DONE"
android:background="#83DBFF"
android:textColor="#FFFFFF"
android:layout_marginTop="100dp"
android:id="@+id/ingameBtDone"/>
</LinearLayout>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="top">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_weight="1.0"
android:layout_marginRight="28dp"
android:layout_marginLeft="26dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Score"
android:textColor="#FFFFFF"
android:shadowColor="#000000"
android:shadowRadius="40"
android:background="#000000"/>
<ImageView
android:layout_height="35dp"
android:layout_width="35dp"
android:src="@android:drawable/ic_menu_myplaces"
android:background="#F1F137"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="500"
android:textColor="#FFFFFF"
android:gravity="center"
android:id="@+id/ingameTvScore"
android:shadowColor="#000000"
android:shadowRadius="1.0"
android:background="#000000"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_weight="1.0"
android:layout_marginRight="28dp"
android:layout_marginLeft="26dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Stars"
android:gravity="center"
android:textColor="#FFFFFF"
android:shadowColor="#000000"
android:shadowRadius="2"
android:background="#000000"/>
<ImageView
android:layout_height="35dp"
android:layout_width="35dp"
android:src="@android:drawable/star_on"
android:scaleType="fitXY"
android:background="#F00808"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="5"
android:textColor="#FFFFFF"
android:gravity="center"
android:id="@+id/ingameTvStars"
android:shadowColor="#000000"
android:shadowRadius="2"
android:background="#000000"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_weight="1.0"
android:layout_marginRight="28dp"
android:layout_marginLeft="26dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Turn"
android:gravity="center"
android:textColor="#FFFFFF"
android:shadowColor="#000000"
android:shadowRadius="2"
android:background="#000000"/>
<ImageView
android:layout_height="35dp"
android:layout_width="35dp"
android:src="@android:drawable/ic_menu_recent_history"
android:background="#55F80C"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="0"
android:textColor="#FFFFFF"
android:gravity="center"
android:id="@+id/ingameTvTurns"
android:shadowColor="#000000"
android:shadowRadius="2"
android:background="#000000"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="@+id/ingameLLToast"/>
</FrameLayout>
</code></pre>
<p><strong>Screenshots</strong></p>
<ol>
<li><p>Nothing shown on the screen</p>
<p><a href="https://i.stack.imgur.com/c0J0I.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c0J0I.jpg" alt="enter image description here"></a></p></li>
<li><p>Menu shown</p>
<p><a href="https://i.stack.imgur.com/kCA2X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kCA2X.jpg" alt="enter image description here"></a></p></li>
<li><p>Stat shown</p>
<p><a href="https://i.stack.imgur.com/3YFyR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3YFyR.jpg" alt="enter image description here"></a></p></li>
<li><p>TechTree shown</p>
<p><a href="https://i.stack.imgur.com/qrL1t.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qrL1t.jpg" alt="enter image description here"></a></p></li>
</ol>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T04:04:51.927",
"Id": "208804",
"Score": "1",
"Tags": [
"android",
"xml",
"layout"
],
"Title": "Reduce components in an android layout with GLSurfaceView"
} | 208804 |
<p>This is a typical <code>C</code> implementation of a (doubly) linked-list.</p>
<p><a href="https://i.stack.imgur.com/sjgSD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sjgSD.png" alt="Normal C implementation of a linked-list with two elements."></a></p>
<p>I want to avoid passing the element and the list itself to functions which operate on and possibly modify the list; the element alone should be all I need. I separated the <code>prev</code> and <code>next</code> into it's own <code>struct</code>.</p>
<p><a href="https://i.stack.imgur.com/RKzyU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RKzyU.png" alt="Still has problems."></a></p>
<p>This is not closed; <code>start</code> has nothing pointing to it, so I still need to pass <code>List</code>.</p>
<p><a href="https://i.stack.imgur.com/teSBp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/teSBp.png" alt="Circular linked list with undefined behaviour waiting to happen."></a></p>
<p>This is closed, but it has no way to differentiate the <code>struct List</code> from the <code>struct Link</code>; not only will this go round-and-round, it will crash when I upcast <code>start</code> and expect <code>Link</code>.</p>
<p><a href="https://i.stack.imgur.com/w8V1B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w8V1B.png" alt="Good."></a></p>
<p>This works. <code>head</code> and <code>tail</code> have a distinctive property that one of their pointers is null. I can test for this.</p>
<p><code>List.h</code>, (<code>C89/90</code>,)</p>
<pre><code>typedef void (*Action)(int *const);
struct X { struct X *prev, *next; };
struct Link { struct X x; int data; };
struct List { struct X head, tail; };
void ListClear(struct List *const list);
void ListPush(struct List *const list, int *const add);
void ListAddBefore(int *const data, int *const add);
void ListForEach(struct List *const list, const Action action);
</code></pre>
<p><code>List.c</code>,</p>
<pre><code>#include <stddef.h> /* offset_of */
#include "List.h"
/* Minimal example without checks. */
static struct Link *x_upcast(struct X *const x) {
return (struct Link *)(void *)((char *)x - offsetof(struct Link, x));
}
static struct Link *data_upcast(int *const data) {
return (struct Link *)(void *)((char *)data - offsetof(struct Link, data));
}
static void add_before(struct X *const x, struct X *const add) {
add->prev = x->prev;
add->next = x;
x->prev->next = add;
x->prev = add;
}
static void clear(struct List *const list) {
list->head.prev = list->tail.next = 0;
list->head.next = &list->tail;
list->tail.prev = &list->head;
}
/** Clears and removes all values from {list}, thereby initialising the {List}.
All previous values are un-associated. */
void ListClear(struct List *const list) {
if(!list) return;
clear(list);
}
/** Initialises the contents of the node which contains {add} to add it to the
end of {list}. */
void ListPush(struct List *const list, int *const add) {
if(!list || !add) return;
add_before(&list->tail, &(data_upcast)(add)->x);
}
/** Initialises the contents of the node which contains {add} to add it
immediately before {data}. */
void ListAddBefore(int *const data, int *const add) {
if(!data || !add) return;
add_before(&data_upcast(data)->x, &data_upcast(add)->x);
}
/** Performs {action} for each element in {list} in the order specified. */
void ListForEach(struct List *const list, const Action action) {
struct X *x, *next_x;
if(!list || !action) return;
for(x = list->head.next; (next_x = x->next); x = next_x)
action(&(x_upcast)(x)->data);
}
</code></pre>
<p>Use this as,</p>
<pre><code>#include <stdio.h> /* printf */
#include <stdlib.h> /* EXIT_ */
#include <errno.h>
#include "List.h"
/* Very basic fixed capacity; returns null after full. */
static struct Link links[20];
static const size_t links_no = sizeof links / sizeof *links;
static size_t links_used;
static int *get_link(const int data) {
struct Link *link;
if(links_used >= links_no) { errno = ERANGE; return 0; }
link = links + links_used++;
link->data = data;
return &link->data;
}
static void sub_ten(int *const i) { ListAddBefore(i, get_link(*i - 10)); }
static void show(int *const i) { printf("%d.\n", *i); }
static struct List list;
int main(void) {
size_t i;
ListClear(&list);
/* Create 10 nodes, [1, 10]. */
for(i = 0; i < 10; i++) ListPush(&list, get_link(links_used + 1));
/* Creates a copy of all the data minus ten. */
ListForEach(&list, &sub_ten);
/* Prints. */
ListForEach(&list, &show);
return errno ? perror("ints"), EXIT_FAILURE : EXIT_SUCCESS;
}
</code></pre>
<p>Prints,</p>
<pre><code>-9.
1.
-8.
2.
-7.
3.
-6.
4.
-5.
5.
-4.
6.
-3.
7.
-2.
8.
-1.
9.
0.
10.
</code></pre>
<p>(If you go above the fixed number of elements, it will print an error.)</p>
<p>Do I really need four pointers in <code>List</code> to call it on <code>Link</code> alone? If I wanted to add the valid <code>static</code> initial state, I would have to branch each time I iterate on null/not-null. Further, how would I deal with two equivalent states, that is, <code>head.next = tail.prev = null</code> and <code>head.next = tail; tail.prev = head</code>, in the most robust way possible? Is it possible to initialise <code>List</code> statically?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T10:59:57.240",
"Id": "403405",
"Score": "0",
"body": "I don't know what is wrong with the 3rd option you presented. You can prevent the list from \"going round and round\" by simply stopping when you reach the head of the list (which is passed in as an argument)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T17:47:56.503",
"Id": "403446",
"Score": "0",
"body": "Good point; it doesn't matter in `ListForEach` because it has access to the list, but in general, I don't want to have the list as a separate argument. I want a closed solution that has access to every `Link` and `List` with a single pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T19:38:44.747",
"Id": "403656",
"Score": "0",
"body": "Edited to show more of what's wrong with the 3rd option."
}
] | [
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Use <code>NULL</code> instead of <code>0</code> for pointers</h2>\n\n<p>The value <code>0</code> is an integer, but the value <code>NULL</code> is an <a href=\"http://en.cppreference.com/w/c/types/NULL\" rel=\"nofollow noreferrer\">implementation-defined null-pointer constant</a>. In a pointer context, they're equivalent, but <code>NULL</code> is a cue to the reader of the code that a pointer is involved.</p>\n\n<h2>Use include guards</h2>\n\n<p>There should be an include guard in the <code>.h</code> file. That is, start the file with:</p>\n\n<pre><code>#ifndef LIST_H\n#define LIST_H\n// file contents go here\n#endif // LIST_H\n</code></pre>\n\n<h2>Simplify your code</h2>\n\n<p>I'm not sure why the <code>x_upcast</code> and <code>data_upcast</code> code exists. Maybe the intent was to more cleanly separate the <code>data</code> type (an <code>int</code> here) from the rest of the code. However, consider that it could instead be written like this: </p>\n\n<pre><code>static struct Link *x_upcast(struct X *const x) {\n return (struct Link *)x;\n}\n</code></pre>\n\n<p>Better though, in my opinion, would be to eliminate it entirely. The single place it's used is in <code>ListForEach</code>:</p>\n\n<pre><code>for(x = list->head.next; (next_x = x->next); x = next_x)\n action(&(x_upcast)(x)->data);\n</code></pre>\n\n<p>This could be more clearly written as:</p>\n\n<pre><code>for(x = list->head.next; (next_x = x->next); x = next_x)\n action(&((struct Link *)x)->data);\n</code></pre>\n\n<p>This also brings us to the next suggestion.</p>\n\n<h2>Use the appropriate data type</h2>\n\n<p>The code, as posted, appears to treat pointers to the data value and pointers to a <code>Link</code> identically. This is a problem because it misleads the reader. For example, the <code>get_link</code> code creates and partially initializes a <code>Link</code> but claims to be returning an <code>int *</code>. This would be much more clear if, instead, the code were to actually return a <code>struct Link *</code>. In other words, the interface should <em>guide correct usage</em> rather than <em>encourage incorrect usage</em>. As an example, this code compiles just fine:</p>\n\n<pre><code>int n = 99;\nListPush(&list, &n);\n</code></pre>\n\n<p>However this is a runtime disaster waiting to happen. We would probably prefer that it not even compile because what <code>ListPush</code> actually requires is a pointer to the data member of an already created <code>struct Link</code>. The next suggestion addresses this problem.</p>\n\n<h2>Rethink your interface</h2>\n\n<p>If <code>LinkPush</code> really requires a <code>List</code> and a <code>Link</code>, let's declare it that way. Instead of this:</p>\n\n<pre><code>void ListPush(struct List *const list, int *const add);\n</code></pre>\n\n<p>use this:</p>\n\n<pre><code>void ListPush(struct List *const list, struct Link *const newnode);\n</code></pre>\n\n<p>Now compiler will actually assist and point out bad usage like the code mentioned previously. This eliminates the type name <code>X</code> and also requires some redefinitions of other things such as <code>List</code> and <code>Action</code> which now look like this:</p>\n\n<pre><code>struct List { struct Link head, tail; };\ntypedef void (*Action)(struct Link *const);\n</code></pre>\n\n<h2>Use better names</h2>\n\n<p>The type name <code>List</code> is good, but the type name <code>X</code> is not. The first name explains something about what the variable means within the context of the code, but the latter is opaque and non-descriptive.</p>\n\n<h2>Better describe the responsibilities of the data structure</h2>\n\n<p>It is quite important to note that this implementation of a linked list assumes that some other entity is creating (and presumably deleting) its nodes. It gives the user some flexibility, as it would allow the use of statically or dynamically allocated memory, but it's worth explicitly mentioning to the user of the code in a comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T22:04:10.050",
"Id": "403468",
"Score": "0",
"body": "Yes, it's **a possibility** but not guaranteed by the standard: https://stackoverflow.com/questions/9894013/is-null-always-zero-in-c"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T22:17:00.413",
"Id": "403471",
"Score": "0",
"body": "Further background for the curious: http://c-faq.com/null/machexamp.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T22:37:11.193",
"Id": "403570",
"Score": "0",
"body": "Thanks! Comment on your 1st point: I agree that the address 0 is not always a null pointer, and `memset(pointer, 0, sizeof pointer)` (ie, `int 0`) is not a way to get a null pointer. However, in pointer contexts, 0 is a null pointer, \"The macro NULL is an implementation-defined null pointer constant, which may be an integer constant expression with the value 0.\" http://c-faq.com/null/null2.html. (Although stylistically, it may be better to use `NULL`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T22:56:11.073",
"Id": "403572",
"Score": "1",
"body": "Fair enough -- I've updated my answer to be more technically correct. Also see http://c-faq.com/null/nullor0.html"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T20:45:20.773",
"Id": "208836",
"ParentId": "208807",
"Score": "4"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/208836/29485\">@Edward</a> good answer.</p>\n\n<p><strong>Information hiding</strong></p>\n\n<p>I'd expect the calling code of <code>List...()</code> functions to not need to know nor be aware the inner structure of <code>struct List</code> in <code>\"List.h\"</code>.</p>\n\n<pre><code>//struct X { struct X *prev, *next; };\n//struct Link { struct X x; int data; };\n//struct List { struct X head, tail; };\nstruct List; // Just declare its existence.\n</code></pre>\n\n<p><strong>Surprising name</strong></p>\n\n<p>I would not expect a type named <code>Action()</code> in <code>List.h</code>. Consider <code>ListAction</code>.</p>\n\n<pre><code>// typedef void (*Action)(int *const);\ntypedef void (*ListAction)(int *const);\n</code></pre>\n\n<p><strong>Entire List Function</strong></p>\n\n<p>Instead of simply calling a function to apply to each element of the list, pass in a <em>state</em> variable and return value of <code>int</code> to allow for preemptive return should it be non-zero.</p>\n\n<pre><code>// typedef void (*Action)(int *const);\ntypedef int (*ListAction)(void *state, int *data);\n\n// void ListForEach(struct List *const list, const Action action);\nint ListForEach(struct List *const list, const ListAction action, void *state);\n</code></pre>\n\n<p><strong>Inefficient design</strong></p>\n\n<p>Given the 4 function set, a double-linked list is not needed. A single linked list will do. e.g. <a href=\"https://en.wikipedia.org/wiki/Linked_list#Circular_linked_list\" rel=\"nofollow noreferrer\">Circular linked list</a> </p>\n\n<p>A double-linked list is only needed if code needs to <em>walk</em> the list in either order - which is not the case here.</p>\n\n<p>This space savings is important when the link-list type is widely deployed. In such cases <em>many</em> lists are empty.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T23:12:09.693",
"Id": "403575",
"Score": "1",
"body": "Or `ListPredicate` for `ListShortCircuit`. A hash table with separate chain linked lists is an example I was thinking of before, and a very good point."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T22:47:42.360",
"Id": "208841",
"ParentId": "208807",
"Score": "4"
}
},
{
"body": "<p>With regard to initialising <code>list</code> statically, <em>ISO/IEC 9899 6.6.9</em> says that an <em>address constant</em>:</p>\n\n<blockquote>\n <p>The array-subscript [] and member-access .\n and -> operators, the address & and indirection * unary operators, and pointer casts may\n be used in the creation of an address constant, but the value of an object shall not be\n accessed by use of these operators.</p>\n</blockquote>\n\n<p>I didn't think this would work, but it does because it doesn't access the value,</p>\n\n<pre><code>static struct List list = { { 0, &list.tail }, { &list.head, 0 } };\n</code></pre>\n\n<p>This eliminates the need to call <code>ListClear</code>. It is much easier then having two cases, empty and a non-empty list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T04:12:42.547",
"Id": "208910",
"ParentId": "208807",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "208836",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T06:08:43.827",
"Id": "208807",
"Score": "4",
"Tags": [
"c",
"linked-list"
],
"Title": "Closed linked-list which uses sentinels to avoid passing itself"
} | 208807 |
<p>I would like to know if there is a more efficient way to speed up below code. This function is meant to fill in a set of poker hand with the remaining
cards using Mersenne Twister for a Monte Carlo simulation.</p>
<pre><code>void HandEvaluator::RandomFill(std::vector<std::shared_ptr<Card>>& _Set, std::vector<std::shared_ptr<Card>>& _Dead, unsigned int _Target){
//Add the cards that are currently in Set as dead cards
for (auto const& CardInSet : _Set)
{
if (CardInSet == nullptr)
break;
_Dead.push_back(CardInSet);
}
bool IsDead;
unsigned int RequiredAmt = _Target - _Set.size();
unsigned int CardIndex = 0;
std::uniform_int_distribution<unsigned int> CardsDistribution(0, 51);
for (unsigned int Index = 0; Index < RequiredAmt; Index++)
{
while (true)
{
IsDead = false;
CardIndex = CardsDistribution(MTGenerator);
for (auto const& Dead : _Dead)
{
if (ReferenceDeck[CardIndex]->GetRank() == Dead->GetRank() && ReferenceDeck[CardIndex]->GetSuit() == Dead->GetSuit())
{
IsDead = true;
break;
}
}
if (!IsDead)
{
_Set.push_back(ReferenceDeck[CardIndex]);
break;
}
}
}
}
</code></pre>
<p>The Visual Studio Profiler had identified that this line</p>
<pre><code> CardIndex = CardsDistribution(MTGenerator);
</code></pre>
<p>is the main culprit behind the high compute time. Is Mersenne Twister itself not meant for a Monte Carlo Simulation and another PRNG should be used instead ? Or there are some inefficient lines that I had missed out ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T09:55:56.637",
"Id": "403402",
"Score": "0",
"body": "Hi, and welcome to CodeReview! I reformatted your code section. Next time, please just paste the code, select it, then press Ctrl + K."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T10:59:55.737",
"Id": "403404",
"Score": "0",
"body": "Could you please also post other parts of the code used in the post? A little example program which can be compiled and run would be awesome! Don't be concerned with size of the program, 100-200 lines of code is common for a CR question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T12:57:35.270",
"Id": "403411",
"Score": "0",
"body": "Thanks for the help ! I've done up a sample project that can be compiled and run. However, my sample project relies on a relatively large .dat file (~126mb) to perform the simulation. Should I include the .dat file into the project and upload them into a file storage site like Google Drive or include another project that generate .dat file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T13:13:32.077",
"Id": "403413",
"Score": "0",
"body": "Whichever is more convenient for you. People might want to check their modifications, like comparing the output of your version and their version. I believe the code you've shown here just generates the deck of cards. Maybe you could include all of the code used for it and create a small main function which generates one deck and prints it? For example, at the moment I don't know what `Card` is (I can guess that it is either an integer or pair which represents a card) and what is `ReferenceDeck` (vector of cards?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T13:52:36.433",
"Id": "403420",
"Score": "0",
"body": "Ah sorry for the confusion, this function is meant to generate a hand, `_Target` amt of cards, based on the remaining cards in a deck. The generation of ReferenceDeck is in another part of the `HandEvaluator` class and `Card` is a class that contains the `Suit` and `Rank` with functions to compare with other `Card`s. Here's the link to the sample project: https://drive.google.com/file/d/1U3d8ZuS_wzkq4RVIj2RV6gj1zyv_yrco/view?usp=sharing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-07T12:52:39.370",
"Id": "404327",
"Score": "0",
"body": "Hi! On attempt to run the code, I get segfault where the code tries to generate score for opponents, specifically in the line with many nested `HR` accesses. Upon further investigation, I found that the value yielded by `HR[53 + CardInts[0]]` is very large and thus outside of bounds. I've rewritten most of the code without changing the logic (at least I hope so), could you please help me out with getting it to run? Here is the link for [my version](https://github.com/simmplecoder/cards-monte-carlo.git). Sorry for taking so long, dates of my finals were quite spread out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T04:17:03.493",
"Id": "404427",
"Score": "0",
"body": "Thanks for taking the time to answer, really appreciate the optimizations you made. It seems that your version returns a different result from mine. After some digging, it seems that you had changed `HR` to a `std::vector`. I tried to change it back to an array but a 'Stack Overflow' exception was thrown which had never happen in my main project. I assume that's the reason for your change to `std::vector`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T04:19:02.773",
"Id": "404428",
"Score": "0",
"body": "you can allocate the object on the heap, as you did previosly, using unique pointer. Did it get faster? Is my version worth fixing? May I also ask how I can generate input data myself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T04:23:28.867",
"Id": "404429",
"Score": "0",
"body": "I tried to test the `DetermineValue_7Card` function from your version with a sample hand of `4c, Ah, 4h, 3h, Kd, Qh, Js`, the last access to `HR`, specifically `HR[HR[HR[HR[HR[HR[.....] + CardInts[5]]`, returns a `0` while mine returns a value of `24727680`. I believe this is the cause for our different results but I not sure about the reason for its occurrence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T04:50:30.367",
"Id": "404430",
"Score": "0",
"body": "Your version does get significantly faster than mine, at least 40% ! I will implement your optimization into my main project. To generate the input data, download this [library](http://web.archive.org/web/20130315225827/http://www.codingthewheel.com/archives/poker-hand-evaluator-roundup#xpokereval) . Within it, there is a table generation code in XPokerEval.TwoPlusTwo project. Build and run that project will produce the .DAT file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T04:30:52.673",
"Id": "404548",
"Score": "0",
"body": "Hey, I managed to implement the changes into my main project. The cause of the weird behavior of `DetermineValue_7Card` is due to `RandomFill` generating invalid cards. Instead of using `std::find` in `RandomFill`, `std::find_if` should be used as the `std::find` compared the `Card` using the default `==` operator that does not perform the actual comparison of the `Suit` and `Rank`. Once I fixed that, I can see a significant improvement in performance. I can't really upvote or tick your comment but I appreciate your help !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T10:40:32.927",
"Id": "404558",
"Score": "0",
"body": "I'm a bit unsure what you mean. I had some other optimizations which I'd like to perform, but cannot get it to run due to the error you described. Implementation of `operator==` looks correct to me. What comparison you had in mind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-09T11:28:40.860",
"Id": "404563",
"Score": "0",
"body": "The implementation is correct. The issue is that `std::find` is not using the`operator==` from `Card` class but is instead using the default `operator==` from `std` namespace. There is an explanation [here](https://stackoverflow.com/questions/7287224/why-isnt-stdfind-using-my-operator). Since the default `operator==` cannot compare the `Suit` and `Rank` between 2 `Card`, this results in `std::find` returning invalid `Card`"
}
] | [
{
"body": "<p>In the end, I opt to replace Mersenne Twister with another PRNG, <a href=\"http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c\" rel=\"nofollow noreferrer\">xoroshiro128+</a>, it managed to cut the compute time by around 15%. I also did some minor optimization on the for-loop but the improvement is minuscule. Anyway, here is the same function but with new PRNG:</p>\n\n<p>Seeding in <code>HandEvaluator</code>'s constructor:</p>\n\n<pre><code>HandEvaluator::HandEvaluator()\n{\n Initialize();\n MTGenerator.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n\n s[0] = std::chrono::high_resolution_clock::now().time_since_epoch().count();\n std::cout << \"Seed 1: \" << s[0] << \"\\n\";\n\n s[1] = std::chrono::high_resolution_clock::now().time_since_epoch().count();\n std::cout << \"Seed 2: \" << s[1] << \"\\n\";\n}\n</code></pre>\n\n<p><code>HandEvaluator</code>'s RandomFill function:</p>\n\n<pre><code>void HandEvaluator::RandomFill(std::vector<std::shared_ptr<Card>>& _Set, std::vector<std::shared_ptr<Card>>& _Dead, unsigned int _Target)\n{\n //Add the cards that are currently in Set as dead cards\n for (auto const& CardInSet : _Set)\n {\n if (CardInSet == nullptr)\n break;\n\n _Dead.push_back(CardInSet);\n }\n\n bool IsDead;\n unsigned int RequiredAmt = _Target - _Set.size();\n\n for (unsigned int Index = 0; Index < RequiredAmt; Index++)\n {\n while (true)\n {\n _Set.push_back(ReferenceDeck[next() % 52]);\n\n IsDead = false;\n\n for (auto const& Dead : _Dead)\n {\n if (Dead->IsEqualTo(_Set[_Set.size() - 1]))\n {\n IsDead = true;\n break;\n }\n }\n\n if (IsDead)\n _Set.pop_back();\n else\n break;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T15:54:12.797",
"Id": "403531",
"Score": "0",
"body": "If you got rid of the Mersenne Twister you should probably rename `MTGenerator`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T23:27:42.397",
"Id": "403576",
"Score": "0",
"body": "Thanks for the heads-up, I had removed `MTGenerator` from `HandEvaluator` class as its no longer necessary"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T07:41:45.647",
"Id": "208860",
"ParentId": "208814",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T09:24:48.243",
"Id": "208814",
"Score": "3",
"Tags": [
"c++",
"random",
"simulation",
"ai"
],
"Title": "Filling up a hand with random cards that are not yet drawn - Monte Carlo"
} | 208814 |
<p>I am working on multi-threading application to learn multithreading better.<br>
My application has a queue with 400 unique links, 4 threads and each thread is pulling link from the queue and sending a Get request to this queue. </p>
<p>My application seems to run, and it takes 18 - 22 seconds for it to finish on 400 links.<br>
I am using <code>ThreadPool.QueueUserWorkItem</code> to do the multithreading. </p>
<p>I wanted someone to review my code and tell me if I use <code>ThreadPool</code> in the correct way.<br>
I need it to be efficient as it can be. </p>
<p>I created a similar application in Python and it takes 12 seconds to run 400 requests. Therefore, I think I am not using the multithreading ability of C# correctly. </p>
<p>The code: </p>
<pre><code>using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace PlayGround
{
class Program
{
static void Main(string[] args)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
RunThreadPool();
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine("[*] Elapsed time: {0}", elapsedMs / 1000);
Console.ReadLine();
}
static BlockingCollection<string> inputQueue = new BlockingCollection<string>();
// https://stackoverflow.com/questions/6529659/wait-for-queueuserworkitem-to-complete
private static ManualResetEvent resetEvent = new ManualResetEvent(false);
private static void RunThreadPool()
{
string url = @"https://google.com";
for (int i = 0; i < 4; i++)
{
var tempWorkerId = i;
ThreadPool.QueueUserWorkItem(state => Worker(tempWorkerId));
}
for (int i = 0; i < 400; ++i)
{
//Console.WriteLine("Queueing work item {0}", url + "/" + i);
inputQueue.Add(url + "/" + i);
//Thread.Sleep(50);
}
Console.WriteLine("Stopping adding.");
inputQueue.CompleteAdding();
resetEvent.WaitOne();
Console.WriteLine("Done.");
}
// https://stackoverflow.com/a/22689821/2153777
static void Worker(int workerId)
{
Console.WriteLine("Worker {0} is starting.", workerId);
foreach (var workItem in inputQueue.GetConsumingEnumerable())
{
string res = "";
//Console.WriteLine("Worker {0} is processing item {1}", workerId, workItem);
try
{
res = Get(workItem);
}
catch (Exception)
{
res = "404";
}
//Console.WriteLine("Worker {0} is processing item {1} with result {2}", workerId, workItem, res);
//Thread.Sleep(100); // Simulate work.
}
resetEvent.Set();
Console.WriteLine("Worker {0} is stopping.", workerId);
}
// https://stackoverflow.com/a/27108442/2153777
public static string Get(string uri)
{
HttpStatusCode status;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
status = response.StatusCode;
}
//Thread.Sleep(2000);
return status.ToString() + "; Thread: " + Thread.CurrentThread.ManagedThreadId.ToString();
}
}
}
</code></pre>
<p><strong>EDIT: Using <code>async\await</code> was very slow (44 seconds) (4.12.2018)</strong><br>
Following the comments about using <code>async\await</code>, I used the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall#example" rel="nofollow noreferrer">link</a> from Microsoft to create a version with <code>async\await</code> and it seems to work faster than anything else I tried. </p>
<p>Here is the code: </p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncAwait
{
class Program
{
static void Main(string[] args)
{
SumPageSizesAsync();
Console.ReadLine();
}
private static async Task SumPageSizesAsync()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
// Make a list of web addresses.
List<string> urlList = SetUpURLList();
// Create a query.
IEnumerable<Task<HttpStatusCode>> downloadTasksQuery =
from url in urlList select GetURLStatusCodeAsync(url);
// Use ToArray to execute the query and start the download tasks.
Task<HttpStatusCode>[] downloadTasks = downloadTasksQuery.ToArray();
// You can do other work here before awaiting.
// Await the completion of all the running tasks.
HttpStatusCode[] lengths = await Task.WhenAll(downloadTasks);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine("[*] Elapsed time: {0}", elapsedMs / 1000);
}
private static async Task<HttpStatusCode> GetURLStatusCodeAsync(string url)
{
HttpStatusCode status;
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
// Send the request to the Internet resource and wait for
// the response.
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
status = response.StatusCode;
}
}
catch (Exception)
{
status = HttpStatusCode.NotFound;
}
//Console.WriteLine("[*] Status code: {0}, Thread: {1}, Url: {2}", status, Thread.CurrentThread.ManagedThreadId, url);
return status;
}
private static List<string> SetUpURLList()
{
string url = @"https://google.com";
List<string> urls = new List<string>();
for (int i = 0; i < 400; ++i)
{
urls.Add(url + "/" + i);
}
return urls;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T11:43:52.517",
"Id": "403407",
"Score": "1",
"body": "Have you tried the same with `async/await` or do just want to use threads?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T12:24:41.950",
"Id": "403408",
"Score": "0",
"body": "I didn't try it. I don't care too much. I am trying to find the fastest and correct way to use multithreading. You think it should improve the performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T21:28:45.427",
"Id": "403463",
"Score": "0",
"body": "async-await example https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T07:38:06.833",
"Id": "403716",
"Score": "0",
"body": "@t3chb0t @Nkosi, I used `async\\await` (see my last edit from 4.12.2018) and it took between 36 - 44 seconds. Very slow compared to my first method."
}
] | [
{
"body": "<p>I think your use of <code>ManualResetEvent</code> is incorrect in this scenario, because as I read it, you intend to wait for all threads to complete here:</p>\n\n<blockquote>\n<pre><code> resetEvent.WaitOne();\n Console.WriteLine(\"Done.\");\n</code></pre>\n</blockquote>\n\n<p>But you actually only wait for the first thread to call <code>resetEvent.Set()</code>.</p>\n\n<p>Instead you'll have to provide a <code>ManualResetEvent</code> (or another waithandle type - for instance <code>ManualResetEventSlim</code>) for each thread in order to wait for them all to end. This could be done like this:</p>\n\n<pre><code>private static void RunThreadPool()\n{\n string url = @\"https://google.com\";\n List<ManualResetEvent> waitHandles = new List<ManualResetEvent>();\n\n for (int i = 0; i < 4; i++)\n {\n ManualResetEvent waitHandle = new ManualResetEvent(false);\n waitHandles.Add(waitHandle);\n int workerId = i;\n ThreadPool.QueueUserWorkItem(state => Worker(workerId, waitHandle));\n }\n\n Console.WriteLine(\"Starting adding.\");\n for (int i = 0; i < 400; ++i)\n {\n inputQueue.Add(url); // + \"/\" + i);\n }\n\n Console.WriteLine(\"Stopping adding.\");\n inputQueue.CompleteAdding();\n\n WaitHandle.WaitAll(waitHandles.ToArray());\n\n waitHandles.ForEach(wh => wh.Dispose());\n //resetEvent.WaitOne();\n Console.WriteLine(\"Done.\");\n}\n\nstatic void Worker(int workerId, ManualResetEvent waitHandle)\n{\n Console.WriteLine(\"Worker {0} is starting.\", workerId);\n\n foreach (var workItem in inputQueue.GetConsumingEnumerable())\n {\n string res = \"\";\n try\n {\n res = Get(workItem);\n Console.WriteLine($\"{res} - {workerId}\");\n }\n catch (Exception)\n {\n res = \"404\";\n }\n }\n waitHandle.Set();\n Console.WriteLine(\"Worker {0} is stopping.\", workerId);\n}\n</code></pre>\n\n<p>Besides that I think your use of <code>ThreadPool.QueueUserWorkItem()</code> is OK.</p>\n\n<hr>\n\n<p>It is not quite clear what kind of concurrency you are exercising but if it's just about executing an action on each element in an existing collection in a multi threaded/parallel manner then, you can experiment with <code>Parallel.ForEach(..)</code>:</p>\n\n<pre><code>private static void RunParallel()\n{\n string url = @\"https://google.com\";\n\n List<string> inputQueue = new List<string>();\n\n for (int i = 0; i < 400; ++i)\n {\n inputQueue.Add(url); // + \"/\" + i);\n }\n\n int workerId = 0;\n ParallelOptions options = new ParallelOptions();\n options.MaxDegreeOfParallelism = 8;\n Parallel.ForEach(inputQueue, options, (uri) =>\n {\n Worker(workerId++, uri);\n });\n\n Console.WriteLine(\"Done.\");\n}\n\nstatic void Worker(int workerId, string uri)\n{\n Console.WriteLine(\"Worker {0} is starting.\", workerId);\n\n string res = \"\";\n try\n {\n res = Get(uri);\n Console.WriteLine(res);\n }\n catch (Exception)\n {\n res = \"404\";\n }\n\n Console.WriteLine(\"Worker {0} is stopping.\", workerId);\n}\n</code></pre>\n\n<p>If you experiment with different values of <code>options.MaxDegreeOfParallelism</code> you can investigate how the <code>Parallel</code> react to that in the use of threads and how it may influence on performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T16:17:05.750",
"Id": "403538",
"Score": "0",
"body": "I'd use [semaphore](https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphore) instead (workers call Release, main calls WaitOne four times). +1 Anyway"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T07:41:09.317",
"Id": "403717",
"Score": "0",
"body": "@Henrik Hansen, thanks. The last method with the `Parallel.ForEach(..)` was the fastet (14 seconds). Btw, I also tried `async\\await` (my last edit from 4.12.2018) but it was much slower compared to your suggestions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T08:27:36.290",
"Id": "208861",
"ParentId": "208815",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "208861",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T11:23:52.623",
"Id": "208815",
"Score": "5",
"Tags": [
"c#",
"performance",
"multithreading",
"console"
],
"Title": "Requesting 400 links with multithreading and ThreadPool"
} | 208815 |
<p>I'm working on R and using regex to keep only numeric figures in a column (I need to keep digits, negative and decimal sign).</p>
<p>Suppose I've a value</p>
<pre><code>t = "$%-123,()@5./6 5ABC"
</code></pre>
<p>My expression</p>
<pre><code>t1 = gsub("[^0-9+-.]", "", t )
</code></pre>
<p>returns</p>
<pre><code>"-123,5.65"
</code></pre>
<p>Now to remove the comma (<code>,</code>) from the result I've to write another line of code</p>
<pre><code>t1 = gsub(",", "", t1)
</code></pre>
<p>Need help to simplify this so that this can be achieved in a single line of code.</p>
<p>Thanks.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T13:05:44.903",
"Id": "403412",
"Score": "0",
"body": "To the down votes and close votes, I read all the requirements at https://codereview.stackexchange.com/help/on-topic and there is only the *does the code work as intended* that could be debated. Here the OP deals with an unexpected result by writing more code to address the problem. So as a whole, I'd say his/her two lines of codes are working code achieving what's intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T15:42:40.233",
"Id": "403435",
"Score": "0",
"body": "(@flodel: voting hints stress usefulness and clarity; one point to question is whether this post invites *insightful observation about the code* rather than tools used.) I think this question better fits the [topics of SO](https://stackoverflow.com/help/on-topic)."
}
] | [
{
"body": "<p>Let's look at your regex <code>[^0-9+-.]</code> in details and see why it does not replace commas:</p>\n\n<ul>\n<li><code>[]</code> is for matching a character set</li>\n<li><code>[^]</code> is to negate a character set, where you intend to match anything that is not one of the following characters (then replace with <code>\"\"</code>):</li>\n<li><code>0-9</code> defines a range of characters from <code>0</code> to <code>9</code> in the ascii table (char codes 48 to 57): <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, <code>5</code>, <code>6</code>, <code>7</code>, <code>8</code>, <code>9</code></li>\n<li><code>+-.</code> defines a range of characters from <code>+</code> to <code>.</code> in the ascii table (char codes 43 to 46): <code>+</code>, <code>,</code>, <code>-</code>, <code>.</code></li>\n</ul>\n\n<p>It's this last item <code>+-.</code> that you did not mean to be interpreted as a range. Instead you wanted <code>+</code>, <code>-</code>, and <code>.</code> to be interpreted as three separate characters. One solution is to switch their order so that <code>-</code> is not between two other characters and the regex engine won't see it as a range of characters: <code>+.-</code> should work.</p>\n\n<pre><code>gsub(\"[^0-9+.-]\",\"\", t )\n[1] \"-1235.65\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T13:28:13.310",
"Id": "403416",
"Score": "0",
"body": "This works well. Thanks for detailed explanation on why it was not working my way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T12:48:22.227",
"Id": "208819",
"ParentId": "208816",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "208819",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T11:25:58.417",
"Id": "208816",
"Score": "-1",
"Tags": [
"regex",
"r"
],
"Title": "R Regex : Need only numeric figures"
} | 208816 |
<p>I have a dataset composed of ~700k samples. Each sample is composed of n_features features. Each feature is a word. Each feature has his own vocabulary. The size of the vocabularies range from 18 to 32000.</p>
<blockquote>
<p>np.shape(x) -> (n_samples, n_features)</p>
</blockquote>
<p>Instead of having lists of features I would like to have lists of indexes corresponding to the indexes in vocabularies. This is my code:</p>
<pre><code>vocs = [np.array(list(set(x[:,i]))) for i in range(np.shape(x)[1])]
x_new = [[np.argwhere(vocs[j]==x[i,j]) for j,feature in enumerate(features)] for i,features in enumerate(x)]
</code></pre>
<p>This code works but I wonder if there is a way to improve the performances. These 2 lines take 10min to run on my i7-7700HQ @ 2.8GHz.</p>
<p>Edit:</p>
<p>For more context, what I'm working on is natural language processing. I want to train a classifier to predict relations between words in a sentence. For this I have a <a href="http://universaldependencies.org/format.html" rel="nofollow noreferrer">conllu file</a> which give sentences and for each word of each sentence a list of features and with which word it's related and how. These features may be the word itself, its lemma, its position in the sentence etc... I'm trying a different set of features and type of embedding and I want to test the embedding described above.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T18:23:55.347",
"Id": "403826",
"Score": "1",
"body": "Hi! I'm not sure this question is super clear to some readers. Could you maybe give a small example of the expected behavior of your code?"
}
] | [
{
"body": "<ol>\n<li><p>When using NumPy, stick to NumPy functions where possible instead of going via pure Python and back again (which is usually slower). So instead of getting the unique elements of an array by writing <code>np.array(list(set(...)))</code>, call <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html\" rel=\"noreferrer\"><code>numpy.unique</code></a>.</p></li>\n<li><p>The expression <code>np.argwhere(vocs[j]==x[i,j])</code> has to search the whole vocabulary for the word <code>x[i,j]</code>, and this has to be done for every feature in every sample. This means that if there are <span class=\"math-container\">\\$s\\$</span> samples and <span class=\"math-container\">\\$f\\$</span> features, and each feature has <span class=\"math-container\">\\$w = O(s)\\$</span> words, the overall runtime is proportional to <span class=\"math-container\">\\$sfw = O(s^2f)\\$</span>. That is, it's quadratic in the number of samples. This is why it takes so long.</p>\n\n<p>To avoid this, we need to construct, for each feature, an inverse mapping from words in the samples to their indexes in the vocabulary. How do we construct such inverse mappings? Well, looking at the <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html\" rel=\"noreferrer\"><code>numpy.unique</code></a> documentation, we find that it takes a keyword argument:</p>\n\n<blockquote>\n <p>return_inverse : <em>bool, optional</em></p>\n \n <p>If <code>True</code>, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct <em>ar</em>.</p>\n</blockquote>\n\n<p>These inverse arrays are exactly what you need, and so your code becomes:</p>\n\n<pre><code>vocs, inverses = zip(*(np.unique(feature, return_inverse=True) for feature in x.T))\nx_new = np.vstack(inverses).T\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T18:36:56.567",
"Id": "403552",
"Score": "0",
"body": "Thank you! I was looking for a numpy function to convert a list of values to a list of indexes giving a vocabulary but I didn't find it and I was sure I was missing something. With your code it takes less than 10s."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T17:14:59.783",
"Id": "208887",
"ParentId": "208820",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "208887",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T13:21:47.033",
"Id": "208820",
"Score": "3",
"Tags": [
"python",
"performance",
"array",
"numpy"
],
"Title": "List of word to list of index in a vocabulary"
} | 208820 |
<p>From a data frame <code>d</code> I have to select the longest possible sequences of <code>x.</code> variables. </p>
<p><em>Example:</em></p>
<pre class="lang-none prettyprint-override"><code>> d
id X1 X2 X3 X4 X5
1 A 1 11 21 31 41
2 B 2 12 22 32 42
3 C 3 13 23 33 NA
4 D 4 14 24 34 NA
5 E 5 15 25 NA NA
6 F 6 16 26 NA NA
7 G 7 17 NA NA NA
8 H 8 18 NA NA NA
9 I 9 NA NA NA NA
10 J 10 NA NA NA NA
</code></pre>
<p>Since all observations with missings have to be neglected, there is a tradeoff between sequence length and number of observations. I have to minimize this tradeoff. </p>
<p>For this purpose I have written this function:</p>
<pre><code>seqRank <- function(d, id="id") {
# generate power subsets of rows and columns
psr <- HapEstXXR::powerset(as.character(d[[id]]))
pssr <- lapply(psr, function(x)
d[which(d[[id]] %in% x), ])
psc <- HapEstXXR::powerset(names(d)[-which(names(d) == id)])
pssc <- lapply(psc, function(x)
d[, c(id, x)])
# generate all combinations of subsets
sss <- lapply(psr, function(x)
lapply(pssc, function(y) y[which(y$id %in% x), ]))
# clean subsets from NAs
cn <- sapply(sss, function(x)
lapply(x, function(y) {
y0 <- y[, which(names(y) == id)]
y1 <- y[, -which(names(y) == id)]
if (is.null((dim(y1))) & any(is.na(y1)))
NULL
else if (is.null((dim(y1))) & any(!is.na(y1)))
setNames(data.frame(as.factor(as.character(y0)), y1),
names(y))
else if (all(apply(is.na(y1), 2, any)))
NULL
else {
na <- which(apply(is.na(y1), 2, any))
if (length(na) == 0)
NA
else
setNames(data.frame(as.factor(as.character(y0)),
y1[, -na]),
c(id, names(y1[-na])))
}
}))
# count rows and columns of subsets
scr <- unlist(setNames(sapply(cn, nrow),
sapply(cn, function(x)
paste0(names(x)[-which(names(x) == id)],
collapse=", "))))
scc <- unlist(setNames(sapply(cn, ncol),
sapply(cn, function(x)
paste0(names(x)[-which(names(x) == id)],
collapse=", ")))) - 1
# bind to a matrix
m <- t(rbind(n.obs=scr, sq.len=scc))
# aggregate matrix by sequences and return maximum sequence lengths
ag <- aggregate(m, by=list(sequence=rownames(m)), max)
return("rownames<-"(with(ag, ag[order(-sq.len, -n.obs), ]), NULL))
}
</code></pre>
<p>It gives me the desired result, </p>
<pre class="lang-none prettyprint-override"><code>> seqRank(d)
1024 sets to create.
32 sets to create.
sequence n.obs sq.len
1 X1, X2, X3, X4 4 4
2 X1, X2, X3 6 3
3 X1, X2, X4 4 3
4 X1, X3, X4 4 3
5 X2, X3, X4 4 3
6 X1, X2 8 2
7 X1, X3 6 2
8 X2, X3 6 2
9 X1, X4 4 2
10 X2, X4 4 2
11 X3, X4 4 2
12 X1 10 1
13 X2 8 1
14 X3 6 1
15 X4 4 1
16 X5 2 1
</code></pre>
<p>but it works quite slowly, even with this small 10x6 data frame, and I have to apply the function to larger data frames that have considerably more rows.</p>
<p>Note that, while working through this <a href="https://stackoverflow.com/a/18719385/6574038">answer on Stack Overflow</a>, I noticed that <code>HapEstXXR::powerset</code> is the fastest way to calculate the powersets, however it only calculates up to a maximum of 15 rows, which is why in lines 3 and 6 I probably have to do this:</p>
<pre><code>psr <- do.call(c, lapply(seq_along(d[[id]]), combn, x=d[[id]], simplify=FALSE))
psc <- do.call(c, lapply(seq_along(names(d)[-which(names(d) == id)]),
combn, x=names(d)[-which(names(d) == id)], simplify=FALSE))
</code></pre>
<p>I'm not sure now whether the complexity of the calculation itself or my code is slowing down the function. Probably there's a much easier way that I didn't come up with.</p>
<p>I am grateful for all suggestions for improvement.</p>
<p><em>Data:</em></p>
<pre><code>d <- structure(list(id = structure(1:10, .Label = c("A", "B", "C",
"D", "E", "F", "G", "H", "I", "J"), class = "factor"), X1 = 1:10,
X2 = c(11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, NA, NA), X3 = c(21L,
22L, 23L, 24L, 25L, 26L, NA, NA, NA, NA), X4 = c(31L, 32L,
33L, 34L, NA, NA, NA, NA, NA, NA), X5 = c(41L, 42L, NA, NA,
NA, NA, NA, NA, NA, NA)), row.names = c(NA, -10L), class = "data.frame")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T00:51:15.000",
"Id": "403473",
"Score": "0",
"body": "In your output, where it says `X5`, should it not say `X1` since that's the name of the column in you input that has 10 non-NA observations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T08:18:49.820",
"Id": "403502",
"Score": "0",
"body": "@flodel Thanks, fixed! I missed it because I had been messing with `aggregate()` just before the post."
}
] | [
{
"body": "<p>I do not get what are you trying to calculate, but this should work much faster:\n(because of using matrices not data.frames and retaining the structure, it takes a lot of time to create new data.frames inside loops)</p>\n\n<pre><code>seqRank2 <- function(d, id = \"id\") {\n require(matrixStats)\n\n # change structure, convert to matrix\n ii <- as.character(d[, id])\n dm <- d\n dm[[id]] <- NULL\n dm <- as.matrix(dm)\n rownames(dm) <- ii\n\n your.powerset = function(s){\n l = vector(mode = \"list\", length = 2^length(s))\n l[[1]] = numeric()\n counter = 1L\n for (x in 1L:length(s)) {\n for (subset in 1L:counter) {\n counter = counter + 1L\n l[[counter]] = c(l[[subset]], s[x])\n }\n }\n return(l[-1])\n }\n\n psr <- your.powerset(ii)\n psc <- your.powerset(colnames(dm))\n\n sss <- lapply(psr, function(x) {\n i <- ii %in% x\n lapply(psc, function(y) dm[i, y, drop = F])\n })\n\n cn <- sapply(sss, function(x)\n lapply(x, function(y) {\n\n if (ncol(y) == 1) {\n if (any(is.na(y))) return(NULL)\n return(y)\n }\n\n isna2 <- matrixStats::colAnyNAs(y)\n if (all(isna2)) return(NULL)\n if (sum(isna2) == 0) return(NA)\n r <- y[, !isna2, drop = F]\n return(r)\n }))\n\n scr <- sapply(cn, nrow)\n scc <- sapply(cn, ncol)\n\n namesCN <- sapply(cn, function(x) paste0(colnames(x), collapse = \", \"))\n names(scr) <- namesCN\n scr <- unlist(scr)\n\n names(scc) <- namesCN\n scc <- unlist(scc)\n\n m <- t(rbind(n.obs = scr, sq.len = scc))\n ag <- aggregate(m, by = list(sequence = rownames(m)), max)\n ag <- ag[order(-ag$sq.len, -ag$n.obs), ]\n rownames(ag) <- NULL\n return(ag)\n}\nx2 <- seqRank2(d)\n\nall.equal(x, x2)\n# TRUE\n</code></pre>\n\n<p>P.S. I do not like using <code>setNames</code>, it makes code harder to read, so I rewrote those parts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T09:29:49.020",
"Id": "403723",
"Score": "0",
"body": "I need it for time sequence analysis of survey data with package `TraMineR`, which doesn't accept any `NA` in data. So this program helps me to select appropriate time periods (in wide format) without losing too many observations. It's now 15 times faster, thanks! I'll see how it will cope with the big data with a 34235 x 56 matrix, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T10:57:55.443",
"Id": "403734",
"Score": "0",
"body": "As expected it didn't work with this huge matrix, getting error `vector size cannot be infinite`. A smaller 35x17 matrix throws `Error: cannot allocate vector of size 256.0 Gb`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T11:09:42.390",
"Id": "403737",
"Score": "0",
"body": "In my code I replaced the `HapEstXXR::...` lines with the `do.call()`s as described in the question and tested the function with big data. It consumed all of my 32GB RAM and ran forever, but at least it run. So probably the error is related to the `matrixStats` package you used? I know I'm planning a huge calculation and I don't know if that's even possible with my tiny machine, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T11:10:37.427",
"Id": "403738",
"Score": "0",
"body": "It's actually a 34235 x 17 matrix, not a 34235 x 56."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T11:52:29.263",
"Id": "403746",
"Score": "0",
"body": "@jay.sf try doing `psr <- do.call(c, lapply(seq_along(1:25), combn, x = 1:25, simplify = FALSE))` and you will see that it is hard to create even all combinations of 25 elements. So I would suggest that you rethink what you are doing and why. And maybe create new question with your initial problem (what you are trying to resolve with this approach) on stackoverflow, because you will not manage to solve it like this. Better description of your problem may help, because I did not get what are you trying to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T11:59:51.053",
"Id": "403747",
"Score": "0",
"body": "Thanks, that's exactly what I had in mind, and you're right maybe there's a simpler solution to get what I want. I'll open something at Stack Overflow and link to here. Thanks for your time by all means!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-04T13:25:55.787",
"Id": "403761",
"Score": "0",
"body": "*Note:* I've asked a new question on [Stack Overflow](https://stackoverflow.com/q/53613882/6574038) case you want to follow the issue further."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-03T13:28:20.917",
"Id": "208928",
"ParentId": "208826",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "208928",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T16:57:58.027",
"Id": "208826",
"Score": "1",
"Tags": [
"performance",
"r"
],
"Title": "Get maximum sequence lengths taking into account the tradeoff of omitted observations"
} | 208826 |
<p>I made a basic cube that can move around of container and jump too. It's basic but I want to know if I can use better methods, better formatting, or shorten the code.</p>
<p>This my HTML:</p>
<pre><code><div class="container">
<div class="cube">
<div class="box">
</div>
</div>
</code></pre>
<p>and this is my Javascript code with a little jQuery:</p>
<pre><code>var velocity = 2;
var acceleration = 0.002;
var gravity = 2;
var key_left = false;
var key_right = false;
var key_up = false;
window.addEventListener('keydown', handleKeyDown)
window.addEventListener('keyup', handleKeyUp)
function handleKeyDown(event) {
if (event.keyCode == 65) {
key_left = true;
} else if (event.keyCode == 68) {
key_right = true;
} else if (event.keyCode == 87) {
key_up = true;
}
};
function handleKeyUp(event) {
if (event.keyCode == 65) {
key_left = false;
velocity = 2;
acceleration = 0.002;
} else if (event.keyCode == 68) {
key_right = false;
velocity = 2;
acceleration = 0.002;
} else if (event.keyCode == 87) {
key_up = false;
}
};
setInterval(function () {
var move = parseFloat($(".box").css("marginRight"));
var moveLimt = (parseFloat($(".cube").css("width")) - 100)
if (key_left === true && move < moveLimt) {
$(".box").css("marginRight", function () {
move += (velocity += acceleration);
return move.toString() + "px";
});
} else if (key_right === true && move > 0) {
$(".box").css("marginRight", function () {
move -= (velocity += acceleration);
return move.toString() + "px";
});
}
var jump = parseFloat($(".cube").css("height"));
if (key_up === true) {
$(".cube").css("height", function () {
jump += (gravity);
if (jump < 402) {
return jump.toString() + "px";
}
});
} else if (key_up === false) {
$(".cube").css("height", function () {
jump -= (gravity);
if (jump > 98) {
return jump.toString() + "px";
}
});
}
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T19:27:59.373",
"Id": "403457",
"Score": "0",
"body": "Welcome to Code Review! You can make this a better question if you make a live demo, including CSS: [edit] the question, and press Ctrl-M in the editor."
}
] | [
{
"body": "<p>It looks not bad at all. However, it could look more professional, and to my not very picky eye there seem to be errors. </p>\n\n<h3>HTML</h3>\n\n<ul>\n<li>There are no html-head-body tags, but every HTML document should have them. Nothing bad will happen, as modern browsers are really smart and will render your code correctly. These tags can be omitted by the HTML standards (e.g. <a href=\"https://html.spec.whatwg.org/multipage/semantics.html#the-html-element\" rel=\"nofollow noreferrer\">WHATWG</a>), but it is sort of a good style to have them always included. It will help whoever reads your code understand, that it is a document, not a part or template to be included somewhere else (if you didn't mean exactly this, of course).</li>\n<li>The third DIV element is not closed, this is an error that will cause your HTML render not correctly. Use traditional <code><div class=\"box\"></div></code> or one-tag self-closing syntax: <code><div class=\"box\"/></code></li>\n</ul>\n\n<h3>Javascript</h3>\n\n<p>At the first glance, it is nice, but it doesn't look like Javascript. To look like Javascript, it should follow, or at least visually be close to one of coding conventions. Just a couple of things to be mentioned, that come to my mind:</p>\n\n<ul>\n<li>No header. A header really helps you (some time later), or another person, to understand what it is, what it does, who and when wrote it, what language it is written in, and many other things you may want to let the future generations know. This is just a /**/-comment block on the top of the script.</li>\n<li><p>Var-group. There are two main trends with defining the variables in JS - in the header / top of the script / block / function, or right before the place they are used. I personally prefer the first approach as more traditional, and besides that you assign initial values in your script, which makes it logic to do it as you did it. Var block can be grouped under the same var expression for better readability and more laconic and easier to transfer code. E.g. </p>\n\n<p><code>var velocity = 2,\n acceleration = 0.002,\n //...\n key_up = false;\n</code></p></li>\n<li><p>Separate the next logical paragraph (add listeners) with a blank line, don't keep it in the same paragraph with the \"var\" paragraph;</p></li>\n<li><p>Function body is not indented well. The indentation should start with the first line of the function body. The rest is fine. E.g.</p>\n\n<p><code>function example() {\n //first line indented\n //block opens: {\n //block indented\n //}\n}</code></p></li>\n<li><p>Good style is to put a block comment descriptor in front of every function to describe it.</p></li>\n<li>Use strict comparison, instead of type-independent (e.g. <code>a === b</code> instead of <code>a == b</code>). This will help you avoid some issues later.</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"nofollow noreferrer\">setInterval</a> is missing the second argument - interval.</li>\n<li><p>Defining function for a callback argument in the function call expression is not really a good practice, as it decreases readability and mantainability of your code and may lead to a \"Callback hell\", so I would recommend first define a named function and then specify it is an argument for the setInterval method. E.g. </p>\n\n<p><code>function example() {\n //function body\n}\nsetInterval(example, 1000);\n</code></p></li>\n</ul>\n\n<p>And, in case if there are things that you don't know and which I mentined, but didn't reference here, you know how to search the web, right? =) Reading about coding conventions and a couple of articles about the good JS coding style may defenetely help.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T18:57:48.900",
"Id": "208830",
"ParentId": "208828",
"Score": "2"
}
},
{
"body": "<h2>Review and alternative approaches</h2>\n<p>Micheal Zelensky has already provided a great review (Though I do not agree with all his points, no two coders ever will)</p>\n<p>This review is to focus more on what your code does and how it does it. And some points the other answer missed.</p>\n<h2>Style</h2>\n<ul>\n<li><p>Be consistent in your naming. You use snake_case for some variable names and camelCase for others. The JavaScript convention is camelCase. Swapping styles means you will be forever needing to remember what style you used for each variable name and this is how bugs creep in.</p>\n</li>\n<li><p>JavaScript also uses UPPER_CASE_SNAKE when defining constants, mostly to define the many magic numbers and values your code needs. However it is not for all constants.</p>\n</li>\n<li><p>You have lots of magic numbers in your code. Many are repeated, so if you wish to change a value you would have to find each one. It is both tedious, prone to error, and disincentivizes your will to tune your app to be just right.</p>\n<p>Using a set of constants defined in one place in the code makes changing values easy, reduces errors, and give semantic meaning in situation where all you have is a number.</p>\n</li>\n</ul>\n<h2>JavaScript</h2>\n<ul>\n<li><p><code>window</code> is the default object, it is also the global scope. You don't need to use it. thus <code>window.addEventListener('keydown', handleKeyDown)</code> is the same as <code>addEventListener('keydown', handleKeyDown)</code></p>\n</li>\n<li><p>JavaScript has 3 types of variables. <code>var</code> scoped to the function, <code>let</code> scoped to a block <code>{ /*everything between the curlies is a block*/ }</code>, and <code>const</code> also block scoped but can not be changed, a constant. It is important to learn which to use and when.</p>\n</li>\n<li><p>Avoid repeated DOM queries for the same object, DOM queries are slow and as the code gets more complicated they will become a major bottleneck if you miss use DOM queries. Use query the DOM for <code>.box</code> and <code>.cube</code> each time you need them, this is bad.</p>\n<p>Locate the elements at the start of the program and assign it to a variables to be used when needed. It is much quicker and makes the code more readable.</p>\n</li>\n<li><p>Also on the queries you should not be using class names to identify individual elements. Many elements can have the same class names. Use the element's Id which must be unique for each element on the page to locate and get a reference to the element.</p>\n</li>\n<li><p>The <code>keyboardEvent</code> properties <code>keyCode</code> and <code>charCode</code> are depreciated properties and may disappear at any time (don't hold your breath though). Use <code>keyboardEvent.code</code> and/or <code>keyboardEvent.key</code> as they replace the depreciated properties and define the characters as named strings.</p>\n<p>Thus if q is pressed keyboardEvent.code === "KeyQ" and keyboardEvent.key === "q" See MDN <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent</a> for more information</p>\n<p>See example of how to read keyboard states.</p>\n</li>\n<li><p>When animating any DOM content don't use <code>setInterval</code> or <code>setTimeout</code>. Thay have a long list of problems in terms of creating good quality animation.</p>\n<p>Use <code>requestAnimationFrame</code> as it is synced to the display hardware and will ensure the best possible frame rate 60fps and will always be in perfect sync with the display refresh. (see example code for how to use)</p>\n</li>\n</ul>\n<h2>Objects</h2>\n<p>Use objects to encapsulate related data and behaviours. Your code is animating a box and you have a variety of variable that are all related to the box in some way. As your code grows so will the number of variables and things will start to get very messy.</p>\n<p>The best way to handle this is to put all related variables in a single object so that you can access them easily and dont end up with clashing variable names.</p>\n<p>Objects can also define behaviours via function calls. Objects can serve as a template to make copies, define one and then create 1000's</p>\n<h2>JQuery</h2>\n<p>You don't need it, and the more you use the less you learn how the browser does it. I added two helper functions to the example. <code>query</code> takes a standard query string and return the first matching element. <code>bounds</code> takes a query string, or empty string and an element and returns the elements bounds object. <code>top</code>, <code>left</code>, <code>right</code>, <code>bottom</code>, <code>width</code> and <code>height</code> as numbers</p>\n<h2>Example</h2>\n<p>The example is quick rewrite and offered as a set of suggestions you may wish to familiarize yourself with.</p>\n<p>I only made a close approximation of what your code did. If you have question use the comment and feel free to ask.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>requestAnimationFrame(animationLoop); // start the main animation loop\nfunction animationLoop(){\n box.update(); \n box.render();\n requestAnimationFrame(animationLoop); // request the next frame\n}\n\n// Helper functions to query the DOM qStr is standard query string\nconst query = qStr => document.querySelector(qStr); \nconst bounds = (qStr, el = query(qStr)) => el.getBoundingClientRect(); \n\n\n\n// Set up all the magic numbers in one place as constants. Add comments to describe what the values mean, units, and safe ranges.\nconst MOVE_VELOCITY = 2; // in pixels per frame (@60fps 2 pixel per frame is 120 pixels per second \n // At 120 pixels per second you can cross a HD 1920 screen in 16 seconds.\nconst GROUND_FRICTION = 0.1; // fraction of x speed lost to friction per fame \n // Must be less than 1 and greater than 0\nconst BOUNCE = 1 / 2; // fraction of speed that box will bounce when it hits the ground.\nconst GRAVITY = 2; // in pixels \nconst BOX_ACCELERATION = 0.5; // in pixels per frame per frame x directions\nconst JUMP_POWER = -60; // as a speed in pixels per frame\nconst ON_GROUND_SPEED = 0.1; // below this speed box is on ground. In pixels per frame\n\n// Keys are named keyboardEvent.code values REF https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code\nconst keys = { // maps keyboard keys to box object control states\n KeyA(state) { box.controls.left = state },\n KeyD(state) { box.controls.right = state },\n KeyW(state) { box.controls.up = state },\n ArrowUp(state) { box.controls.up = state },\n ArrowLeft(state) { box.controls.left = state },\n ArrowRight(state) { box.controls.right = state },\n}\nfunction handleKeyEvents(event) {\n if(keys[event.code]) {\n keys[event.code](event.type === \"keydown\"); \n event.preventDefault(); \n }\n}\naddEventListener('keydown', handleKeyEvents);\naddEventListener('keyup', handleKeyEvents);\nfocus(); // get the keyboard events.\n\n\nvar boxBounds = bounds(\"#box\"); \nconst box = {\n element : query(\"#box\"),\n bounds : bounds(\"#cube\"), \n canJump : false, \n x : boxBounds.left, \n y : boxBounds.top, \n width : boxBounds.width,\n height : boxBounds.height,\n dx : 0, // the box delta (AKA velocity)\n dy : 0,\n update() {\n if (box.controls.left) { box.dx -= BOX_ACCELERATION }\n if (box.controls.right) { box.dx += BOX_ACCELERATION }\n box.dy += GRAVITY; \n if (box.controls.up && box.canJump) {\n box.dy -= JUMP_POWER;\n box.controls.up = false; \n }\n box.x += box.dx;\n box.y += box.dy;\n if (box.x < box.bounds.left) {\n box.x = box.bounds.left;\n box.dx = 0;\n }\n if (box.x + box.width > box.bounds.right) {\n box.x = box.bounds.right - box.width;\n box.dx = 0;\n }\n if (box.y + box.height > box.bounds.bottom) {\n box.y = box.bounds.bottom - box.height;\n if (Math.abs(box.dy) < ON_GROUND_SPEED) {\n box.dy = 0; \n } else { \n box.dy = -Math.abs(box.dy) * BOUNCE; \n }\n box.dx *= 1 - GROUND_FRICTION;\n box.canJump = true;\n } else {\n box.canJump = false;\n }\n },\n render() {\n box.element.style.top = box.y + \"px\";\n box.element.style.left = box.x + \"px\";\n },\n controls : {\n up : false,\n left : false,\n right : false,\n },\n}\nboxBounds = undefined; // no longer needed so dump it</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#box {\n position : absolute;\n top : 40px;\n left : 40px;\n width : 60px;\n height : 60px;\n border: 4px solid #5D4;\n border-radius: 5px;\n background : #485;\n}\n\n#cube {\n position : absolute;\n top : 10px;\n left : 10px;\n bottom : 10px;\n right : 10px;\n border: 2px solid black;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code>...Move A, W, D, or Up, Left, Right, arrows.</code>\n<div id=\"cube\"></div>\n<div id=\"box\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T14:32:30.153",
"Id": "403520",
"Score": "0",
"body": "I know I should not thank you in comments but i don't expect have someone that give me so much good information and rewrite my worthless code. Thank you and this showed me that website have such good community."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-02T02:55:33.237",
"Id": "208852",
"ParentId": "208828",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "208852",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T17:06:46.487",
"Id": "208828",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"animation"
],
"Title": "Simple cube that moves around the container with keys"
} | 208828 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.