body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I came across a problem that needs to reverse each word in a string without affecting space in it. For example, if a string has two spaces between the word, the answer needs to have space between two words. These are example test cases, I have been given<br>
<strong>/This is a sentence/</strong><br>
<strong>/ This is a Sentence /</strong><br>
My approach is: </p>
<pre><code>string oreverse(string s){
for(int i=0,n=s.size();i<n/2;++i)
swap(s[i],s[n-i-1]);
return s;
}
string reverseWords(string s) {
string re;
for(auto i=0;i<s.size();){
if(s[i]!=' '||s[i]=='/0'){
int _t = s.find_first_of(' ',i);
re+=oreverse(s.substr(i,_t-i));
i=_t;
}else{
re+=s[i];
i++;
}
}
return re;
}
</code></pre>
<p>I like to know, is there any further optimisation can be done or any other approaches with increased efficiency.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T10:28:41.550",
"Id": "380533",
"Score": "1",
"body": "Welcome to Code Review! Could you please provide an example main and provide all of the includes? Also, did you test this? The compiler should complain about `'/0'`, as it should... | [
{
"body": "<h1>Use compiler warnings</h1>\n\n<p>You should always enable compilers warning in c++. For your code, clang & g++ gives the following warnings (<a href=\"https://wandbox.org/permlink/qswjiVNP5oPyGqzq\" rel=\"nofollow noreferrer\">live demo</a>):</p>\n\n<pre><code>prog.cc:14:29: warning: multi-ch... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T07:12:54.010",
"Id": "197400",
"Score": "1",
"Tags": [
"c++",
"strings"
],
"Title": "Reverse words in a string without affecting space"
} | 197400 |
<p>My first (real?) program.</p>
<p>The client connects to a Django restframework API by sending user credentials to obtain a token for headers. Then the user can drag and drop an image from a OS folder into the terminal and press enter, then write a title for it to upload.</p>
<p>The image(s) URL is obtained from the server and then turned into markdown that are listed in a bytearray. This byte array gets loaded into a tempfile that can be edited with the system's default editor or Vim. When this is saved and closed, it's converted to html and the article is published.</p>
<h3>api_client.py</h3>
<pre><code>import requests
import tempfile
import os
import pypandoc
import json
from getpass import getpass
from subprocess import call
EDITOR = os.environ.get('EDITOR', 'vim')
ARTICLE_URL = 'http://127.0.0.1:8000/api/articles/'
IMAGE_URL = 'http://127.0.0.1:8000/api/media/images/'
TOKEN_URL = 'http://127.0.0.1:8000/api-auth-token/'
def obtain_token(username, password):
"""Authenticate and obtain token"""
data = {'username': username, 'password': password}
req = requests.post(TOKEN_URL, data=data)
res = req.json()
token = res['token']
headers = {'Authorization': 'Token {}'.format(token)}
return headers
"""
Ask for user credentials to set header, not sure how to
place this code in a functional way
"""
username = input("Username: ")
password = getpass()
headers = obtain_token(username=username, password=password)
def image_upload(img_file, img_title):
"""Upload image with title"""
files = {'image': img_file}
payload = {'title': img_title}
upload = requests.post(IMAGE_URL, files=files, data=payload,
headers=headers)
return upload
md_urls = bytearray()
def img_docload():
"""
Get the latest uploaded image and convert it
to a html string so that pypandoc again can make
it into markdown, then extend each to the bytearray.
"""
get_url = requests.get(IMAGE_URL)
get_json = json.loads(get_url.content)
clean = get_json[-1]['image']
md_html = "<img src='"+clean+"'>"
md = pypandoc.convert_text(md_html, 'md', format='html')
md_urls.extend(md.encode())
def article(headline, summary):
"""
Make a tempfile and write the list of markdown inserts,
then open it in Vim or any default editor. Save and quit
to convert from markdown to html and upload the article.
"""
with tempfile.NamedTemporaryFile(suffix='.md') as tmp:
tmp.write(md_urls)
tmp.flush()
call([EDITOR, tmp.name])
tmp.seek(0)
edited = tmp.read()
article = edited.decode('utf-8')
content = pypandoc.convert_text(article, 'html', format='md')
payload = {
'headline': headline,
'summary': summary,
'content': content,
}
upload = requests.post(ARTICLE_URL, json=payload, headers=headers)
return upload
def main():
while True:
action = input("Upload image? (k): ")
if action == 'k':
img_file = open(input("Image - Filename: ").strip('\''), 'rb')
img_title = input("Image - Title: ")
image_upload(img_file=img_file, img_title=img_title)
img_docload()
continue
else:
headline = input("Article - Headline: ")
summary = input("Article - Summary: ")
article(headline=headline, summary=summary)
print("Article is published")
break
main()
</code></pre>
<h3>Questions:</h3>
<ul>
<li>I wrote the program without a single function to begin with. Then I tried to follow the functional design to learn more about functions and how to structure programs. What could be done better? </li>
<li>How would you place the <code>obtain_token</code> function and its I/O?</li>
<li>My next goal is to learn about classes and OOP; is there a place for classes in this program or is it unnecessary?</li>
<li>What do you think about the way it first upload an image and then gets the URL, then puts it into a HTML <code>img</code> element, and then converts it to md (pypandoc needs it to make the markdown, and I wanted the links to be "dynamic")? This can't be the best approach; would you do it server-side? Or is it best to do as much as possible on the client-side?</li>
</ul>
<p>In general I would like to know about all the mistakes I have made - what could be done better - especially regarding structure, before I move on to learn more.</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>ARTICLE_URL = 'http://127.0.0.1:8000/api/articles/'\nIMAGE_URL = 'http://127.0.0.1:8000/api/media/images/'\nTOKEN_URL = 'http://127.0.0.1:8000/api-auth-token/'\n</code></pre>\n</blockquote>\n\n<p>The repetition here could be harmful. If you move the server, then there's thre... | {
"AcceptedAnswerId": "226899",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T09:37:06.260",
"Id": "197406",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Python API article/image client using requests, pypandoc and os editor"
} | 197406 |
<p>Python3's <code>async</code>/<code>await</code> syntax is great, but it does create a divide between libraries which are async-based and those which are not. For example, <a href="https://github.com/boto/boto3" rel="noreferrer">boto3</a> (AWS API library) currently doesn't work with async. There is a separate project, <a href="https://github.com/aio-libs/aiobotocore" rel="noreferrer">aiobotocore</a>, attempts to recreate some of this functionality in an async context.</p>
<p>I have been thinking for a while about how to create HTTP API clients which can be run async and sync contexts. I have come up with a strategy that involves creating a separation between the logic (preparation of requests, interpretation of responses), and the sending. The logic is implemented as a generator function, which yields out an object which represents the request, and receives back an object representing the response. This generator is "run" by a runner function, which does the actual sending, and may be sync or async.</p>
<p>You can imagine that if, for example, <code>boto3</code> had been written this way, it would be easy to re-use the bulk of the code to make an async version, rather than having to do an async rewrite.</p>
<p>I have included a toy example below. I would welcome comments.</p>
<pre><code>from typing import Iterable, NamedTuple, Dict, Any, Optional
import requests
from aiohttp import ClientSession
URL_TEMPLATE = "https://api.icndb.com/jokes/{id}/"
class Request(NamedTuple):
method: str
url: str
json: Optional[Dict[str, Any]] = None
class Response(NamedTuple):
status: int
json: Optional[Dict[str, Any]] = None
def get_joke(id: int) -> Iterable[Request]:
response = yield Request("GET", URL_TEMPLATE.format(id=id))
try:
if response.status != 200:
raise JokeApiError("API request failed")
data = response.json
if data.get("type") == 'NoSuchQuoteException':
raise NoSuchJoke(data.get("value", ""))
if data.get("type") != "success":
raise JokeApiError("API request failed")
raise Return(data["value"]["joke"])
except (JokeApiError, Return, StopIteration):
raise
except Exception as e:
raise JokeApiError() from e
def call_api_sync(it):
try:
for req in it:
response = requests.request(req.method, req.url, json=req.json)
it.send(
Response(status=response.status_code, json=response.json())
)
except Return as e:
return e.value
async def call_api_async(it):
async with ClientSession() as session:
try:
for req in it:
async with session.request(
method=req.method,
url=req.url,
json=req.json) as res:
json = await res.json()
response = Response(status=res.status, json=json)
it.send(response)
except Return as e:
return e.value
class JokeApiError(Exception):
pass
class NoSuchJoke(JokeApiError):
pass
class Return(Exception):
def __init__(self, value):
self.value = value
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T17:23:09.423",
"Id": "380596",
"Score": "0",
"body": "I'd suggest adding a`if name...` section as well"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T18:13:17.057",
"Id": "380602",
"Score": "... | [
{
"body": "<p>The code is admirably clear.\nNice annotations.\nWith these classes,\nChuck Norris wouldn't need a debugger,\nhe could just stare down the bug until the code confesses.</p>\n\n<pre><code>class Request(NamedTuple):\n method: str\n</code></pre>\n\n<p>Maybe list <code>method</code> 2nd, and allow ... | {
"AcceptedAnswerId": "216602",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T11:48:22.063",
"Id": "197425",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"async-await"
],
"Title": "Creating API clients that are \"async agnostic\""
} | 197425 |
<p>I'm writing my own MVC framework for learning purposes. Usually in my projects I like to use <code>AJAX</code> to send requests and retrive data. Now my doubt is if this can be a best approach to make a one page dashboard. </p>
<p>I've created an <code>.htaccess</code> who will display only folders that have an index file inside, the dashboard will be loaded only after user login, the login form is on the index file who is inside a folder named user. On the root of the project there is another index file who will be publicy available.</p>
<p>Assuming I've this code in the user dashboard file:</p>
<p><code>HTML</code></p>
<pre><code><div class="container-fluid" id="app">
<div class="row">
<div class="col-sm-12 col-lg-4">
<a href="#" id="open-settings">
<div class="card">
<div class="card-body">
<div class="card-img-top text-center">
<i class="fas fa-cog fa-3x"></i>
</div>
<h5 class="card-title text-uppercase text-center">settings</h5>
</div>
</div>
</a>
</div>
<div class="col-sm-12 col-lg-4">
<a href="#">
<div class="card">
<div class="card-body">
<div class="card-img-top text-center">
<i class="fas fa-database fa-3x"></i>
</div>
<h5 class="card-title text-uppercase text-center">show database entry</h5>
</div>
</div>
</a>
</div>
<div class="col-sm-12 col-lg-4">
<a href="#">
<div class="card">
<div class="card-body">
<div class="card-img-top text-center">
<i class="fas fa-plus fa-3x"></i>
</div>
<h5 class="card-title text-uppercase text-center">new insert</h5>
</div>
</div>
</a>
</div>
</div>
<div class="row" id="display-view"></div>
</div> <!-- container end -->
</code></pre>
<p>What is the best approach to load the requested view for the user selected action?
I want to avoid duplication of the jquery code who now is something like this</p>
<pre><code>$('#open-settings').on('click',function(e){
e.preventDefault();
preloader.modal('show');
$.ajax({
type: 'GET',
url: 'view/settings.php',
cache: false,
beforeSend: function(){
preloader.modal('show');
},
success: function(response){
$('#display-view').html(response)
}
});
</code></pre>
| [] | [
{
"body": "<p>Without really knowing a great deal about how your code is structured and basing it purely on your ajax function you could so somethhing like this; </p>\n\n<pre><code>function loadView(url, beforeSend, callback) {\n $.ajax({\n type: 'GET',\n url: url,\n cache: false,\n ... | {
"AcceptedAnswerId": "197434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T12:10:46.287",
"Id": "197427",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "Simple AJAX view loading approach"
} | 197427 |
<p>The story here is about a console application that replays to a test system string clauses already imported in the production system.</p>
<p>Looking forward to your comments.</p>
<pre><code>namespace MyCompany.Department.ProjectXYZ;
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using MyCompany.XYZ;
/// <summary>
/// Books message clauses to staging Diamant via web service.<para/>
/// If no arguments are provided, the program reads from the production database log table (<see cref="ImportJobData"/>)
/// all clauses that were imported in the last 24 hours.<para/>
/// If a single filename argument is provided, the program reads clauses from that file.<para/>
/// The program writes clauses that encounter an error on booking to Diamant in a text file in the FailedClauses directory.
/// </summary>
public class Program
{
/// <summary>
/// Client to the staging web service.
/// </summary>
private static ImportVSMessageClient _client;
/// <summary>
/// Error messages for all processed clauses.
/// </summary>
private static readonly List<string> _errorMessages = new List<String>();
private static readonly IApplicationLogger _logger = ApplicationMonitoring.GetLogger(typeof(Program));
private static readonly Lazy<ErrorService> _errorService = new Lazy<ErrorService>(() => new ErrorService());
internal static void Main(string[] args)
{
WebServiceClientApplication.Initialize();
_client = new ImportVSMessageClient();
try
{
var clauses = GetClausesToImport(args);
DoImport(clauses);
}
catch (Exception ex)
{
_errorMessages.Add(ex.Message);
}
finally
{
if (_errorMessages.Any())
{
_errorService.Value.ProcessError(
"WebService.Client - Error",
string.Join(Environment.NewLine, _errorMessages));
}
_client.Close();
}
}
#region Private methods
private static IEnumerable<string> GetClausesToImport(string[] args)
{
if (!args.Any())
{
return GetImportedClausesOnPreviousDay();
}
string filename = args[0];
return File.ReadAllLines(filename);
}
private static IEnumerable<string> GetImportedClausesOnPreviousDay()
{
IImportJobsService importJobsService = new ImportJobsService();
return importJobsService.Load(DiamantSystem.Produktion, DateTime.Now.AddDays(-1), DateTime.Now)
.Where(IsValid).OrderBy(ijd => ijd.Erstelldatum)
.Select(ijd => ijd.Eingangswerte);
}
private static Boolean IsValid(ImportJobData ijd)
{
return ijd.Status == VerarbeitungsStatus.ImportErfolgreich && ijd.Satzart != Satzart.LOGOUT;
}
private static void DoImport(IEnumerable<string> clauses)
{
var clausesList = clauses.ToList();
if (clausesList.Any())
{
_logger.Info("Importing {0} messages.", clausesList.Count);
ImportClauses(clausesList);
_logger.Info("Closing connection.");
ImportClause(Satzart.LOGOUT);
_logger.Info("Finished importing.");
}
else
{
_logger.Info("Nothing to import.");
}
}
private static void ImportClauses(IEnumerable<string> clauses)
{
var failedClauses = new List<String>();
foreach (var clause in clauses)
{
var success = ImportClause(clause);
if (!success)
{
failedClauses.Add(clause);
}
}
if (failedClauses.Any())
{
WriteFailedClauses(failedClauses);
}
}
// Returns true when successful.
private static bool ImportClause(String clause)
{
var errorMessage = RunImportAction(() => _client.ImportMessage(clause));
if (string.IsNullOrEmpty(errorMessage))
{
return true;
}
LogError(string.Format("Clause: {0}", clause));
LogError(string.Format("Error: {0}", errorMessage));
return false;
}
private static void LogError(string errorMsg)
{
_errorMessages.Add(errorMsg);
_logger.Error(errorMsg);
}
// Returns empty string when successful, otherwise the error message.
private static String RunImportAction(Action action)
{
try
{
action();
return string.Empty;
}
catch (FaultException<DiamantWarningFaultContract> faultException)
{
return faultException.Detail.ErrorMessage.Aggregate((a, b) => a + Environment.NewLine + b);
}
catch (FaultException<DiamantFatalFaultContract> faultException)
{
return faultException.Detail.ErrorMessage.Aggregate((a, b) => a + Environment.NewLine + b);
}
catch (FaultException exception)
{
return string.Format("Code: {0}, Message: {1}", exception.Code.Name, exception.Message);
}
catch (Exception exception)
{
return exception.Message;
}
}
private static void WriteFailedClauses(IEnumerable<string> failedClauses)
{
string filename = String.Format("FailedClauses_{0}.txt", DateTime.Now.ToString("yyyy-MM-dd-HHmmss"));
filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FailedClauses", filename);
File.WriteAllLines(filename, failedClauses);
}
#endregion
}
}
</code></pre>
| [] | [
{
"body": "<p>Few small observaions.</p>\n\n<ol>\n<li><p>Good use of <code>readonly</code> </p></li>\n<li><p>Might want to declare your <code>_errorMessages</code> as a more generic type, e.g.:</p>\n\n<p><code>private static readonly ICollection<string> _errorMessages = new List<String>();</code></p... | {
"AcceptedAnswerId": "197431",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T13:19:49.843",
"Id": "197430",
"Score": "4",
"Tags": [
"c#",
".net"
],
"Title": "From production to staging"
} | 197430 |
<p>I've written a perl script that creates a csv file consolidated of values from multiple files. This file that I've created is then used to update certain rows in a main excel spreadsheet my company uses. I've created a VBA script that scans the main file for values that match up with those from my perl generate file and it all works fine. </p>
<p>The problem is that it takes about four minutes to run. The main file is only about 1000 or so rows long, and the file I'm generating only comes out to about 100 rows top. My logic in my script is to scan through every row in the main file for each row in the generated file:</p>
<pre><code>Sub TransferDataToForecast()
Dim strPath As String 'File path
Dim foreb As Workbook 'Workbook that the file path points to
Dim copys As Worksheet 'Worksheet that contains the data to be copied
Dim dests As Worksheet 'Worksheet that is being copied to
Dim copysLastRow As Long 'Last row of data worksheet
Dim copysLastCol As Long 'Last column of data worksheet
Dim destsLastRow As Long 'Last row of target worksheet
Dim counter As Long 'Counter for loop control
Application.ScreenUpdating = False
Set copys = ActiveWorkbook.ActiveSheet
'Get user to select target workbook
strPath = BrowseForFile("Select the DM Forecast file you want to update")
If strPath = vbNullString Then Exit Sub
'Debug.Print strPath
Set foreb = Workbooks.Open(strPath)
Set dests = foreb.Worksheets("Material_Usage_Prim")
'Get last row of each worksheet and last column of data sheet in order to help with loop control
copysLastRow = copys.Cells(Rows.Count, 3).End(xlUp).Row
copysLastCol = copys.Cells(2, Columns.Count).End(xlToLeft).Column
destsLastRow = dests.Cells(Rows.Count, 1).End(xlUp).Row
counter = 0
'Loop through each row of the data sheet
For i = 2 To copysLastRow
Debug.Print "i is "; i
'For each row in the data sheet, loop through every row in the destination sheet in order
'to find matching id's between each sheet
For j = 2 To destsLastRow
Debug.Print "j is "; j
If Trim(copys.Cells(i, 3).Value2) = vbNullString Then Exit For 'This exits the loop if the data sheet has a blank row
If dests.Cells(j, 4) <> copys.Cells(i, 4) Then GoTo NextDestLoop 'This skips the rest of the current j if values in col4 of each sheet don't match up
'Have to use replace due to differing naming conventins among people i.e. _ vs - (this row can be changed for specific peoples needs)
'This checks that columns 3 and 4 of each sheet match
If Replace(copys.Cells(i, 3).Value2, "_", "") = Replace(dests.Cells(j, 3).Value2, "_", "") And copys.Cells(i, 4).Value2 = dests.Cells(j, 4).Value2 Then
counter = 0
For k = 5 To copysLastCol
Debug.Print "k is "; k
'Go to 14, because we want to keep the first 14 weeks (columns)
If counter < 14 Then
counter = counter + 1
GoTo NextIteration
End If
counter = counter + 1
dests.Cells(j, k).Value2 = copys.Cells(i, k).Value2
NextIteration:
Next k
End If
If counter = copysLastRow Then GoTo NextLoop
NextDestLoop:
Next j
NextLoop:
Next i
Application.ScreenUpdating = True
MsgBox ("Data has been transferred.")
End Sub
'This function brings up a window for the user to pick an excel file they want to update
Private Function BrowseForFile(Optional strTitle As String) As String
Dim fDialog As FileDialog
On Error GoTo Err_handler
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.Title = strTitle
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
.AllowMultiSelect = False
.InitialView = msoFileDialogViewList
If .Show <> -1 Then GoTo Err_handler:
BrowseForFile = fDialog.SelectedItems.Item(1)
End With
lbl_Exit:
Exit Function
Err_handler:
BrowseForFile = vbNullString
Resume lbl_Exit
End Function
</code></pre>
<p>If anyone can help me to make this more efficient I would be grateful! </p>
| [] | [
{
"body": "<p>I found something a little awkward that I would do differently</p>\n\n<p>your code </p>\n\n<blockquote>\n<pre><code> If Replace(copys.Cells(i, 3).Value2, \"_\", \"\") = Replace(dests.Cells(j, 3).Value2, \"_\", \"\") And copys.Cells(i, 4).Value2 = dests.Cells(j, 4).Value2 Then\n counter = 0\n ... | {
"AcceptedAnswerId": "197445",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T15:33:01.883",
"Id": "197435",
"Score": "5",
"Tags": [
"performance",
"vba"
],
"Title": "VBA script that copies data from one workbook to another"
} | 197435 |
<h2>Program purpose</h2>
<p>The purpose for the program is to create a file containing the effective inventory for each stocked item stored in a collection of shops. </p>
<h2>Input and algorithm details</h2>
<p>For clarity, in the descriptions below, variables in the C++ program use this style: <code>nShopID</code>, while fields in CSV files are shown like this: <em>shop_id</em>. </p>
<h3>Shops and groups</h3>
<p>The problem domain is a collection of <strong>shops</strong> (identified by an <code>int</code> shop ID number) each of which is assigned to a <strong>group</strong> (also identified by an <code>int</code>). The association between <code>nShopID</code> and <code>nGroupID</code> is contained in a text file <code>shopgroups.csv</code>, which is a tab-delimited file with a header with two fields: <em>shop_id</em> and <em>shopgroup_id</em>. </p>
<h3>Simple inventory</h3>
<p>The <strong>simple inventory</strong> is in a file named <code>shopstock_all.csv</code>. That file is also a tab-delimited file with header containing three fields: <em>item_idx</em>, <em>shop_id</em>, and <em>amount</em>. The <em>item_idx</em> field is a string containing the item identifier, and the <em>shop_id</em> represents the shop that has the item and <em>amount</em> is an integer representing the quantity of the item at that shop. </p>
<h3>Effective inventory</h3>
<p>The <em>simple inventory</em> is simply the number of items at each shop, as described above, but the desired <strong>effective inventory</strong> takes into account the fact that the inventory of nearby shops could, if needed, be quickly moved to one particular shop. Thus, the <em>effective inventory</em> of a particular shop represents the <em>simple inventory</em> of that shop plus that of nearby stores. Nearby stores and the direction of possible movement of inventory is represented in a third tab-delimited file called <code>sgm.csv</code> which contains a header and two fields: <em>shop_group_from</em> and <em>shop_group_to</em>. For example, a line in the file might say <code>8 15</code> which means that any inventory in group 8 can be counted in the effective inventory of all shops in group 15. These associations are many-to-many (that is group 8 might feed multiple groups and group 15 might be fed from multiple other groups) and not necessarily reciprocal. That is, group 8 inventory may be moved to group 15 shops but not necessarily the other direction unless explicitly stated in the file.</p>
<p>Additionally, all shops within the same group also share their effective inventory without needing a special line in the <code>sgm.csv</code> file.</p>
<p>Finally, some warehouse shops (those with <code>nShopID > 10000</code>) have extra storage available and goods are only transferred <em>from</em> and never <em>to</em> such shops. To differentiate, the program actually calculates two effective inventory quantities for each store; <code>nTotalAmount</code> which is the effective inventory from all stores including these warehouse shops and <code>nTotalAmount10k</code> which is the effective inventory excluding these warehouse shops.</p>
<h2>Output file</h2>
<p>The output file is a tab-delimited file with no header with each record (line) containing four fields: <em>itemID</em>, <em>shopID</em>, <em>totalAmount</em>, <em>totalAmount10k</em> each of which has been described above. The order of the records within the file does not matter.</p>
<h2>The code</h2>
<p>The code and sample files are all on <a href="https://gitlab.com/pk72/shop-stock-total" rel="nofollow noreferrer">on GitLab</a></p>
<h2>Questions</h2>
<p>Since I rarely write C++ code, I've got a mix of C++ and C code. Could it be fixed without hurting performance?</p>
<p>What should be fixed to improve readability, naming of variables and code styling?</p>
<p>Could makefile be less "bloated"? (This is the 2nd one I've ever written.)</p>
<p>P.S. I'm using vim, so there are</p>
<pre><code>// {{{ manual-style folding comments
// ...
// }}}
</code></pre>
<p>and I would prefer to leave those as is.</p>
<h2>shop_stock_total.h</h2>
<pre><code>// {{{ Structures and typedefs
// {{{ ShopGroupMove
typedef list<int> GroupsFromList;
struct ShopGroupMoveStruct {
int nGroupTo;
GroupsFromList *lstGroupsFrom;
};
typedef unordered_map<int, struct ShopGroupMoveStruct> ShopGroupMovesMap;
// }}}
// {{{ ShopGroup
typedef list<int> ShopsList;
struct ShopGroupStruct {
int nGroupID;
ShopsList *lstShops; // all shops with the same group
};
typedef unordered_map<int, struct ShopGroupStruct> ShopGroupsMap;
// }}}
// {{{ Shop
struct ShopStruct {
int nShopID;
int nGroupID;
ShopsList *lstFromAll;
ShopsList *lstFrom10k;
};
typedef unordered_map<int, struct ShopStruct> ShopsMap;
// }}}
// {{{ Availability
struct AvailabilityStruct {
int nShopID;
int nAmount;
int nTotalAmount;
int nTotalAmount10k;
};
typedef unordered_map<int, struct AvailabilityStruct> AvailabilitiesMap;
// }}}
// {{{ ShopStock
struct ShopStockStruct {
char *sItemID;
AvailabilitiesMap *mapAv;
};
typedef unordered_map<std::string, struct ShopStockStruct> ShopStocksMap;
// }}}
// }}}
// {{{ Functions
// {{{ APP specific
void ProcessShopGroupMoves(ShopGroupMovesMap *mapSGM);
void DebugPrintSGM(ShopGroupMovesMap *mapSGM);
void ProcessShopGroups(ShopGroupsMap *mapSG, ShopsMap *mapS);
void DebugPrintSG(ShopGroupsMap *mapSG, ShopsMap *mapS);
void Fill_FromShopAll(ShopGroupMovesMap *mapSGM, ShopGroupsMap *mapSG, ShopsMap *mapS);
void DebugPrintS(ShopsMap *mapS);
void ProcessShopStocks(ShopStocksMap *mapSS, ShopsMap *mapS, FILE *out);
void PostProcessItem(ShopStockStruct *pstSS, ShopsMap *mapS, FILE *out);
void DebugPrintSS(ShopStockStruct *pstSS);
void WriteResult(ShopStockStruct *pstSS, FILE *out);
// }}}
// {{{ generic
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems);
std::vector<std::string> split(const std::string &s, char delim);
// }}}
// }}}
</code></pre>
<hr>
<h2>shop_stock_total.cpp</h2>
<pre><code>// {{{ standard and other includes
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <locale>
#include <fstream>
#include <string>
#include <string.h>
#include <sstream>
#include <assert.h>
#include <ctype.h>
#include <algorithm>
#include <unordered_map>
#include <vector>
#include <list>
// }}}
// {{{ filenames
const char *SHOP_GROUP_MOVES_FILE = "sgm.csv";
const char *SHOP_GROUPS_FILE = "shopgroups.csv";
const char *SHOP_STOCKS_FILE = "shopstock_all.csv";
const char *SHOP_STOCK_TOTALS_FILE = "shop_stock_total.csv";
// }}}
using namespace std;
#include "shop-stock-total.h"
// {{{ main
int main() {
// ShopGroupMoves
ShopGroupMovesMap *mapSGM;
mapSGM = new ShopGroupMovesMap();
ProcessShopGroupMoves(mapSGM);
DebugPrintSGM(mapSGM);
// ShopGroups and Shops
ShopGroupsMap *mapSG;
mapSG = new ShopGroupsMap();
ShopsMap *mapS;
mapS = new ShopsMap();
ProcessShopGroups(mapSG, mapS);
DebugPrintSG(mapSG, mapS);
Fill_FromShopAll(mapSGM, mapSG, mapS);
DebugPrintS(mapS);
// ShopStock
ShopStocksMap *mapSS;
mapSS = new ShopStocksMap();
FILE* fileSST = fopen (SHOP_STOCK_TOTALS_FILE, "w+");
ProcessShopStocks(mapSS, mapS, fileSST);
fclose(fileSST);
return 0;
}
// }}}
// {{{ ProcessShopGroupMoves
void ProcessShopGroupMoves(ShopGroupMovesMap *mapSGM) {
std::ifstream file(SHOP_GROUP_MOVES_FILE);
std::string l;
ShopGroupMoveStruct *pstSGM;
int nKey = -1;
int nSGMs = 0;
int nGroupFrom;
int nGroupTo;
std::vector<std::string> vsItems;
while (std::getline(file, l)) {
// skip first line
if (nKey < 0) {
nKey = 0;
continue;
}
vsItems = split(l, (char) '\t');
if (vsItems.size() < 2)
continue;
nGroupFrom = atoi(vsItems[0].c_str());
nGroupTo = atoi(vsItems[1].c_str());
auto sgm = mapSGM->find(nGroupTo);
if (sgm == mapSGM->end()) {
// not found, so we need to create a new one
pstSGM = new ShopGroupMoveStruct();
pstSGM->nGroupTo = nGroupTo;
pstSGM->lstGroupsFrom = new GroupsFromList();
// and store it, we'll add from value a bit later
(* mapSGM)[nGroupTo] = *pstSGM;
}
else {
// found group already, get a pointer to it for adding nGroupFrom
// value later
pstSGM = &(sgm->second);
}
// in any case (found or not), we've to add GroupFrom value
pstSGM->lstGroupsFrom->push_back(nGroupFrom);
nSGMs++;
}
printf("Total %d ShopGroupMoves loaded.\n", nSGMs);
}
// }}}
// {{{ DebugPrintSGM
void DebugPrintSGM(ShopGroupMovesMap *mapSGM) {
for (auto sgm=mapSGM->begin(); sgm != mapSGM->end(); sgm++) {
printf("%d:\t", sgm->second.nGroupTo);
for (auto f=sgm->second.lstGroupsFrom->begin();
f!=sgm->second.lstGroupsFrom->end();
f++) {
printf("%d ", *f);
}
printf("\n");
}
}
// }}}
// {{{ ProcessShopGroups
void ProcessShopGroups(ShopGroupsMap *mapSG, ShopsMap *mapS) {
std::ifstream file(SHOP_GROUPS_FILE);
std::string l;
int nSGs = 0;
int nKey = -1;
int nShopID;
int nGroupID;
ShopStruct *pstShop;
ShopGroupStruct *pstSG;
std::vector<std::string> vsItems;
while (std::getline(file, l)) {
// skip first line
if (nKey < 0) {
nKey = 0;
continue;
}
vsItems = split(l, (char) '\t');
if (vsItems.size() < 2)
continue;
nShopID = atoi(vsItems[0].c_str());
nGroupID = atoi(vsItems[1].c_str());
// skip zero ID shop
if (nShopID == 0)
continue;
// create new Shop and save it
pstShop = new ShopStruct();
pstShop->nShopID = nShopID;
pstShop->nGroupID = nGroupID;
pstShop->lstFromAll = new ShopsList();
pstShop->lstFrom10k = new ShopsList();
(* mapS)[nShopID] = *pstShop;
// do we need to save ShopGroup
if (nGroupID == 0)
continue;
auto sg = mapSG->find(nGroupID);
if (sg == mapSG->end()) {
// not found, so we need to create a new one
pstSG = new ShopGroupStruct();
pstSG->nGroupID = nGroupID;
pstSG->lstShops = new ShopsList();
// and store it, we'll add from value a bit later
(* mapSG)[nGroupID] = *pstSG;
}
else {
// found group already, get a pointer to it for adding shop
// value later
pstSG = &(sg->second);
}
// in any case (found or not), we've to add GroupFrom value
pstSG->lstShops->push_back(nShopID);
nSGs++;
}
printf("Total %d ShopGroups loaded.\n", nSGs);
}
// }}}
// {{{ Fill_FromShopAll
void Fill_FromShopAll(ShopGroupMovesMap *mapSGM, ShopGroupsMap *mapSG, ShopsMap *mapS) {
for (auto s = mapS->begin(); s != mapS->end(); s++) {
// fill shops from the same group
auto sg = mapSG->find(s->second.nGroupID);
if (sg != mapSG->end()) {
for (auto s_ = sg->second.lstShops->begin();
s_ != sg->second.lstShops->end();
s_++) {
s->second.lstFromAll->push_back(*s_);
}
}
// fill shops from movement groups
auto sgm = mapSGM->find(s->second.nGroupID);
if (sgm != mapSGM->end()) {
for (auto sg = sgm->second.lstGroupsFrom->begin();
sg != sgm->second.lstGroupsFrom->end();
sg++) {
auto sg_ = mapSG->find(*sg);
if (sg_ != mapSG->end()) {
for (auto s_ = sg_->second.lstShops->begin();
s_ != sg_->second.lstShops->end();
s_++) {
s->second.lstFromAll->push_back(*s_);
}
}
}
}
// de duping
s->second.lstFromAll->sort();
s->second.lstFromAll->unique();
// remove shop itself
s->second.lstFromAll->remove(s->second.nShopID);
// copy to 10k
/* auto n = std::copy_if( */
/* s->second.lstFromAll->begin(), */
/* s->second.lstFromAll->end(), */
/* s->second.lstFrom10k->begin(), */
/* [](int i){return (i < 10000);}); */
/* s->second.lstFrom10k->size( */
/* auto n = std::copy( */
/* s->second.lstFromAll->begin(), */
/* s->second.lstFromAll->end(), */
/* s->second.lstFrom10k->begin() */
/* ); */
/* s->second.lstFrom10k->resize( */
/* std::distance(s->second.lstFrom10k->begin(), n)); */
for (auto s_ = s->second.lstFromAll->begin();
s_ != s->second.lstFromAll->end();
s_++) {
if (*s_ < 10000) {
s->second.lstFrom10k->push_back(*s_);
}
}
}
}
// }}}
// {{{ DebugPrintS
void DebugPrintS(ShopsMap *mapS) {
for (auto s = mapS->begin(); s != mapS->end(); s++) {
printf("%d:\t", s->second.nShopID);
for (auto s_ = s->second.lstFrom10k->begin();
s_ != s->second.lstFrom10k->end();
s_++) {
printf("%d, ", *s_);
}
printf("\n");
}
}
// }}}
// {{{ DebugPrintSG
void DebugPrintSG(ShopGroupsMap *mapSG, ShopsMap *mapS) {
// print shop groups
for (auto sg=mapSG->begin(); sg != mapSG->end(); sg++) {
printf("%d:\t", sg->second.nGroupID);
for (auto s = sg->second.lstShops->begin();
s != sg->second.lstShops->end();
s++) {
printf("%d ", *s);
}
printf("\n");
}
// print shops
for ( auto s = mapS->begin(); s != mapS->end(); s++) {
printf("%d : %d\n", s->second.nShopID, s->second.nGroupID);
}
}
// }}}
// {{{ PostProcessItem
void PostProcessItem(ShopStockStruct *pstSS, ShopsMap *mapS, FILE *out) {
AvailabilityStruct *pstAV;
for (auto s = mapS->begin();
s != mapS->end();
s++) {
// if shop is not present in current item Availability
// add it with 0 amounts,
// coz we could still move goods there from others shops
auto s_ = pstSS->mapAv->find(s->second.nShopID);
if (s_ == pstSS->mapAv->end()) {
pstAV = new AvailabilityStruct();
pstAV->nShopID = s->second.nShopID;
pstAV->nAmount = 0;
pstAV->nTotalAmount = 0;
pstAV->nTotalAmount10k = 0;
(*(pstSS->mapAv))[s->second.nShopID] = *pstAV;
}
}
// summing up total availability
for (auto av = pstSS->mapAv->begin();
av != pstSS->mapAv->end();
av++) {
// add amounts from shop itself
av->second.nTotalAmount = av->second.nAmount;
av->second.nTotalAmount10k = av->second.nAmount;
// add amount from other shops which could move goods into this one
auto s_ = mapS->find(av->second.nShopID);
if (s_ == mapS->end()) continue;
for (auto s__ = s_->second.lstFromAll->begin();
s__ != s_->second.lstFromAll->end();
s__++) {
auto av_ = pstSS->mapAv->find(*s__);
if (av_ == pstSS->mapAv->end()) continue;
av->second.nTotalAmount += av_->second.nAmount;
if (*s__ < 10000) {
av->second.nTotalAmount10k += av_->second.nAmount;
}
}
}
//DebugPrintSS(pstSS);
WriteResult(pstSS, out);
}
// }}}
// {{{ DebugPrintSS
void DebugPrintSS(ShopStockStruct *pstSS) {
printf("%s:\t", pstSS->sItemID);
for (auto av = pstSS->mapAv->begin();
av != pstSS->mapAv->end();
av++) {
printf("%d - %d - %d;", av->second.nShopID, av->second.nTotalAmount,
av->second.nTotalAmount10k);
}
printf("\n");
}
// }}}
// {{{ WriteResult
void WriteResult(ShopStockStruct *pstSS, FILE *out) {
for (auto av = pstSS->mapAv->begin();
av != pstSS->mapAv->end();
av++) {
if (av->second.nTotalAmount + av->second.nTotalAmount10k == 0) {
continue;
}
fprintf(out, "%s\t%d\t%d\t%d\n",
pstSS->sItemID,
av->second.nShopID,
av->second.nTotalAmount,
av->second.nTotalAmount10k
);
}
}
// }}}
// {{{ ProcessShopStocks
void ProcessShopStocks(ShopStocksMap *mapSS, ShopsMap *mapS, FILE *out) {
std::ifstream file(SHOP_STOCKS_FILE);
std::string l;
ShopStockStruct *pstSS = NULL;
AvailabilityStruct *pstAV;
int nKey = -1;
int nSSs = 0;
char *sItemID;
char *sItemIDprev = (char *)"";
int nShopID;
int nAmount;
std::vector<std::string> vsItems;
while (std::getline(file, l)) {
// skip first line
if (nKey < 0) {
nKey = 0;
continue;
}
vsItems = split(l, (char) '\t');
if (vsItems.size() < 3)
continue;
sItemID = strdup(vsItems[0].c_str());
if (strcmp(sItemIDprev, sItemID) != 0) {
// item changed - post process previous item
if (pstSS != NULL)
PostProcessItem(pstSS, mapS, out);
}
nShopID = atoi(vsItems[1].c_str());
nAmount = atoi(vsItems[2].c_str());
auto ss = mapSS->find(sItemID);
if (ss == mapSS->end()) {
// not found, so we need to create a new one
pstSS = new ShopStockStruct();
pstSS->sItemID = sItemID;
pstSS->mapAv = new AvailabilitiesMap();
// and store it, we'll add from value a bit later
(* mapSS)[sItemID] = *pstSS;
}
else {
// found group already, get a pointer to it for adding nGroupFrom
// value later
pstSS = &(ss->second);
}
// in any case (found or not), we've to add GroupFrom value
// to do: create struct, and store it in map
pstAV = new AvailabilityStruct();
pstAV->nShopID = nShopID;
pstAV->nAmount = nAmount;
pstAV->nTotalAmount = 0;
pstAV->nTotalAmount10k = 0;
(*(pstSS->mapAv))[nShopID] = *pstAV;
nSSs++;
}
// process the last item if exists
if (pstSS != NULL)
PostProcessItem(pstSS, mapS, out);
printf("Total %d ShopStocks loaded.\n", nSSs);
}
// }}}
// {{{ Generic split to vector function
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
// printf("\t%s\n", item.c_str());
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
// }}}
</code></pre>
<hr>
<h2>Makefile:</h2>
<pre><code>PROGRAM = shop-stock-total
CXX=g++
CXXFLAGS := -g -std=c++11 -Wall -O3 -march=native -mtune=native
LDFLAGS := -g -L /usr/lib:/usr/lib/x86_64-linux-gnu
all: $(PROGRAM)
$(PROGRAM): $(PROGRAM).gcda $(PROGRAM).o
$(CXX) $(CXXFLAGS) -fprofile-use -o $@ $(PROGRAM).o $(LDFLAGS)
$(PROGRAM).gcda: profile/$(PROGRAM)
./profile/$(PROGRAM) >/dev/null
cp profile/$(PROGRAM).gcda ./
profile/$(PROGRAM): $(PROGRAM).cpp $(PROGRAM).h
[[ -d profile ]] || mkdir profile
cp $(PROGRAM).cpp profile/
cp $(PROGRAM).h profile/
cd profile && $(CXX) -c $(CXXFLAGS) -fprofile-generate $(PROGRAM).cpp
cd profile && $(CXX) $(CXXFLAFS) -fprofile-generate -o $(PROGRAM) $(PROGRAM).o $(LDFLAGS)
shop-stock-total.o: $(PROGRAM).cpp $(PROGRAM).h
$(CXX) -c $(CXXFLAGS) -fprofile-use $(PROGRAM).cpp
clean:
@rm -rf *.o $(PROGRAM) ./profile *.gcda
</code></pre>
<hr>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T16:16:53.860",
"Id": "380581",
"Score": "0",
"body": "For better performance, try to 1) replace all uses of `std::list` with `std::vector` 2) reduce pointer usage the items pointed to can often be stored by value instead."
},
{
... | [
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad... | {
"AcceptedAnswerId": "197999",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T15:42:18.153",
"Id": "197436",
"Score": "8",
"Tags": [
"c++",
"c++11",
"csv",
"hash-map",
"makefile"
],
"Title": "Calculating effective shop inventories from CSV files"
} | 197436 |
<p>This is a follow my rock-paper-scissors program, original post here:
<a href="https://codereview.stackexchange.com/questions/195912/simple-rock-paper-scissors-game">Simple rock-paper-scissors game</a></p>
<p>Looking for any feedback and recommendations on ways to keep improving.</p>
<p>Quick notes on changes:</p>
<ul>
<li>Removed the use of using namespace std;</li>
<li>Added inheritance structure.</li>
<li>Added the use of enum variables to replace strings to ease computational
expense while still maintaining code readability.</li>
<li>Simplified the logic of the whoWon function.</li>
<li>Changed the scope whoWon function to deal with a singular task</li>
<li>Removed the use of rand and replaced it with a normal distribution from
the random library.</li>
<li>Added the option of choosing from three types of play:
Player vs Computer, Player vs Player(Local), and Computer vs Computer. </li>
<li>Move choices given by Human players will no longer be echoed onto the
application window to ensure player's do not unfairly see each-other's
choices.</li>
<li>Added a moveToString function so that each player's move choice can be
displayed after the winner is determined.</li>
<li>Changed main.cpp loop structure to be do-while, so it will run atleast
once.</li>
</ul>
<p>Code:</p>
<p>rock-paper-scissors_v2.h:</p>
<pre><code>#ifndef ROCK_PAPER_SCISSORS_V2_H
#define ROCK_PAPER_SCISSORS_V2_H
#include <iostream>
#include <random>
#include <string>
#include <unordered_map>
#include <termios.h>
#include <unistd.h>
enum rock_paper_scissors{
rock = 0,
paper = 1,
scissors = 2
};
class Player{
protected:
rock_paper_scissors move_choice;
public:
virtual void setMoveChoice() = 0;
virtual rock_paper_scissors getMoveChoice() = 0;
std::string moveToString(rock_paper_scissors);
};
class ComputerPlayer : public Player{
public:
void setMoveChoice();
rock_paper_scissors getMoveChoice();
};
class HumanPlayer : public Player{
private:
std::string player_name;
public:
HumanPlayer();
void setMoveChoice();
rock_paper_scissors getMoveChoice();
};
#endif /* ROCK_PAPER_SCISSORSS_H */
</code></pre>
<p>rock-paper-scissors_v2.cpp:</p>
<pre><code>#include "rock-paper-scissors_v2.h"
using std::cin;
using std::cout;
std::string Player:: moveToString(rock_paper_scissors move){
std::string move_as_string;
if(move == rock)
move_as_string = "rock";
else if(move == paper)
move_as_string = "paper";
else
move_as_string = "scissors";
return move_as_string;
}
void ComputerPlayer :: setMoveChoice(){
//Simulate the computer randomly choosing a move
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> distribution(0,2);
int num_generated = distribution(gen);
move_choice= (rock_paper_scissors)num_generated;
}
rock_paper_scissors ComputerPlayer :: getMoveChoice(){
return move_choice;
}
HumanPlayer :: HumanPlayer(){
cout<<"Please enter your name: ";
cin>>player_name;
cout<<"Hello "<<player_name<<", welcome to Rock-Paper-Scissors! \n";
}
void HumanPlayer :: setMoveChoice(){
cout<<player_name<<", please enter the move you wish to make: \n";
termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
std::string move;
cin>>move;
//Use a hashmap to map user string input to enum
std::unordered_map<std::string,rock_paper_scissors> valid_moves = {
{"rock",rock},{"paper",paper},{"scissors",scissors}
};
//Check for valid user input
while(valid_moves.find(move) == valid_moves.end()){
cout<<"Error, invalid move! Please enter rock, paper, or scissors \n";
getline(cin,move);
}
move_choice = valid_moves[move];
}
rock_paper_scissors HumanPlayer :: getMoveChoice(){
return move_choice;
}
</code></pre>
<p>main.cpp:</p>
<pre><code>#include "rock-paper-scissors_v2.h"
using std::cin;
using std::cout;
int whoWon(rock_paper_scissors &p1_move, rock_paper_scissors &p2_move){
// Function will return 1 if player 1 wins, 2 if player 2 wins, and 3 for a tie
//Both players making the same move results in a tie
if(p1_move == p2_move){
return 3;
}
//If not a tie, check for player 1 being the winner
else if((p1_move == rock && p2_move == scissors) || (p1_move == paper && p2_move == rock) || (p1_move == scissors && p2_move == paper)){
return 1;
}
// If none of the above are true, player 2 wins
else{
return 2;
}
}
int main(int argc, char** argv) {
char play_again;
do{
//Initiate the Title Screen
cout<<"Rock-Paper-Scissors \n";
cout<<"-------------------\n";
cout<<"Enter the number of the mode you wish to play: \n";
cout<<"1.) Player vs Computer \n2.) Player vs Player(Local Only) \n3.) Computer vs Computer(Simulation) \n";
int mode_selected;
cin>>mode_selected;
Player *player_1;
Player *player_2;
switch(mode_selected){
case 1:{
ComputerPlayer com;
HumanPlayer hum;
player_1 = &hum;
player_2 = &com;
break;
}
case 2:{
HumanPlayer hum_1;
HumanPlayer hum_2;
player_1 = &hum_1;
player_2 = &hum_2;
break;
}
case 3:{
ComputerPlayer com_1;
ComputerPlayer com_2;
player_1 = &com_1;
player_2 = &com_2;
break;
}
}
player_1->setMoveChoice();
rock_paper_scissors p1_move = player_1->getMoveChoice();
player_2->setMoveChoice();
rock_paper_scissors p2_move = player_2->getMoveChoice();
int winner = whoWon(p1_move,p2_move);
if(winner == 1){
cout<<"Player one chose "<<player_1->moveToString(p1_move)<<" and Player 2 chose "<<player_1->moveToString(p2_move)<< ". Player 1 wins! \n";
}
else if(winner == 2){
cout<<"Player one chose "<<player_1->moveToString(p1_move)<<" and Player 2 chose "<<player_1->moveToString(p2_move)<< ". Player 2 wins! \n";
}
else{
cout<<"Player one chose "<<player_1->moveToString(p1_move)<<" and Player 2 chose "<<player_1->moveToString(p2_move)<< ". It's a tie! \n";
}
cout<<"Would you like to play again?(y/n) \n";
cin>>play_again;
} while(play_again == 'y');
return 0;
}
</code></pre>
<p>Additional Questions:</p>
<ul>
<li>What are some good sources to look at for adding simple PvP online play?</li>
<li>Any tips/ resource recommendations for improving the current "menu" UI?</li>
</ul>
| [] | [
{
"body": "<p>Visually, your indentation and spacing are a little inconsistent, making parts of the code harder to read.</p>\n\n<p>You should include the <code>override</code> keyword in your <code>ComputerPlayer</code> and <code>HumanPlayer</code> classes if your compiler supports it.</p>\n\n<p>The <code>getMo... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T16:07:38.633",
"Id": "197438",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"rock-paper-scissors"
],
"Title": "Simple rock-paper-scissors game [Follow Up 1]"
} | 197438 |
<p>My idea was to take in the function and perform a self cross product so that I could check every pair against every other pair. I'm new to Haskell so this solution is probably rough.</p>
<p>My question is, is there a better way to emulate a nested for loop rather than a cross product? Also, is there any way to collapse my ugly <code>valid</code> and <code>valid'</code> into one clean function?</p>
<pre><code>valid :: [(Int, Int)] -> Bool
valid f = valid' $ [(x,y) | x <- f, y <- f]
valid' :: [((Int,Int),(Int,Int))] -> Bool
valid' [] = True
valid' (((x,y),(x1,y1)):xs) = valid' xs && if x == x1 then (if y == y1 then True else False) else True
</code></pre>
| [] | [
{
"body": "<p>To start, <code>if y == y1 then True else False</code> can be simplified to <code>y == y1</code>:</p>\n\n<pre><code>valid' (((x,y),(x1,y1)):xs) = valid' xs && if x == x1 then y == y1 else True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"Conte... | {
"AcceptedAnswerId": "197526",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T16:48:18.337",
"Id": "197441",
"Score": "5",
"Tags": [
"haskell"
],
"Title": "Determining if a set of 2d vectors is a valid function"
} | 197441 |
<p>Please provide general and any specific criticism of the following which is intended to provide a map of SF transit cars.
The code can be viewed in <a href="https://www.jimmont.com/sfmuni/" rel="nofollow noreferrer">the working version</a> and also <a href="https://gist.github.com/jimmont/2b8c21b9b3810b3662f8f6a63fccc59f" rel="nofollow noreferrer">in a group of gists</a>.</p>
<p>If this isn't the appropriate place or way to request a review please let me know. Feedback received so far indicates the solution is amateurish and I would like to better understand the better/preferred solutions--specifically what and where to focus. Overall this was a first-pass at a solution intended to reflect a productive day's work. </p>
<pre><code>import './the-controls.js';
class TheMap extends HTMLElement{
constructor(){
super();
this.attachShadow({mode:'open'}).innerHTML = `
<style>
:host{display:block;width:100%;height:100%;}
svg{border:1px dotted #555;background:#0df;height:100%;width:100%;position:fixed;}
g[src*='neighborhoods']{fill:green;stroke:#ccff0033;stroke-width:4px;}
g[src*='arteries']{display:none;fill:none;stroke:#000;stroke-width:0.5;}
g[src*='freeways']{display:none;fill:none;stroke:#fff;stroke-opacity:0.7;stroke-width:0.5;}
g[src*='streets']{display:none;stroke:#fff;fill:none;stroke-opacity:0.8;stroke-width:0.2px;}
.show-freeways g[src*='freeways'],
.show-streets g[src*='streets'],
.show-arteries g[src*='arteries']{display:inline;}
.vehicles circle{fill:red;fill-opacity:0.7;}
.vehicles circle:hover{fill:#cf0;fill-opacity:1;stroke:#555;stroke-width:0.1;}
.vehicles text{display:none;fill:var(--dark);font-size:1rem;pointer-events:none;}
.vehicles g:active text,
.vehicles g:hover text{display:block;}
button{font-weight:bold;}
button.active{background-color:var(--dark);color:white;}
/*.vehicles g{transition:all 500ms;}*/
</style>
<svg>
<g class=layers></g>
<g class=overlay>
<foreignobject class="filter" x="2.5rem" y="2rem" width="150" height="100%">
<the-controls></the-controls>
</foreignobject>
</g>
</svg>
`;
this._setup = false;
this.map = d3.select(this.shadowRoot.querySelector('svg'))
this.layers = d3.select(this.shadowRoot.querySelector('.layers'))
this.controls = this.shadowRoot.querySelector('the-controls')
this.data = {
time: 0
//'http://webservices.nextbus.com/service/publicJSONFeed?command=vehicleLocations&a=sf-muni&t=0'
,tags: {}
,taglist: []
,vehicles: []
,timer: 0
,interval: 30
,scale: 100000
// San Francisco
,lon: -122.4, lat: 37.76
,projection: null
,pathprojector: null
//
,content: './sfmaps/neighborhoods.json ./sfmaps/arteries.json ./sfmaps/freeways.json ./sfmaps/streets.json'
}
this.addEventListener('change-active', this.vehicleDrawer)
}
tagisactive(active, tag){
if(tag.active) active[ tag.name ] = tag;
return active;
}
vehicleisactive(item){
return this[ item.routeTag ] ? true : false;
}
vehicleDrawer(){
// show the active-tag vehicles
var data = this.data, $, vehicleList = data.vehicles.filter(this.vehicleisactive,
data.taglist.reduce(this.tagisactive, {}) );
requestAnimationFrame(()=>{
// update
$ = this.layers
.select('g.vehicles')
.selectAll("g")
.data(vehicleList)
.each(this.vehicleDetails)
;
// enter
$.enter()
.append("g")
.each(this.vehicleDetails)
;
// exit
$.exit().remove();
})
}
//item = {dirTag:"7____O_F00", heading:"225", id:"6719", lat:"37.784794", lon:"-122.403969", predictable:"true", routeTag:"7", secsSinceReport:"17", speedKmHr:"19"}
vehicleDetails(item, i, vehicleList){
var $;
this.setAttribute('transform', `translate(${item.position[0]}, ${item.position[1]}) scale(0.5)`);
$ = this.querySelector('text');
if($){
$.textContent = item.routeTag;
}else{
this.innerHTML = `<circle cx=0 cy=0 r=5 /><text>${ item.routeTag }</text>`;
};
}
vehiclePostion(item){
item.position = this.projection([+item.lon, +item.lat]);
}
tagSorter(a,b){
return a.name < b.name ? -1 :(a.name > b.name ? 1 : 0);
}
updateFinish(res){
this.data.timer = setTimeout(()=>{ this.update(); }, 1000 * this.data.interval);
console.log('updated',res);
return res;
}
update(){
clearTimeout(this.data.timer);
d3.json(`http://webservices.nextbus.com/service/publicJSONFeed?command=vehicleLocations&a=sf-muni&t=${this.data.time}`)
.then((json)=>{
var taglist, data = this.data;
// get all the unique routeTags as a sorted list
taglist = json.vehicle.reduce(this.vehiclehash, data).taglist;
data.taglist = taglist = Array.from(new Set(taglist)).sort(this.tagSorter);
data.vehicles = json.vehicle;
// easier to interpret the position here than passing the pieces and parts around
data.vehicles.forEach(this.vehiclePostion, data)
this.vehicleDrawer();
this.controls.model = data;
return this.updateFinish(json);
}).catch((res)=>{
return this.updateFinish(json);
});
}
vehiclehash(data, item){
var name = item.routeTag, tag = data.tags[ name ];
if(!tag){
tag = data.tags[ name ] = {name:name, active:true};
};
data.taglist.push( tag );
item.tag = tag;
return data;
}
layerDrawer(json){
requestAnimationFrame(()=>{
var data = this.data, $;
$ = this.layers
.select(`g[src="${json.path}"]`)
.selectAll("path")
.data(json.features)
.attr("d", data.pathprojector)
;
$.enter()
.append("path")
.attr("d", data.pathprojector)
;
$.exit().remove();
});
}
// zooming adjusts transform and visible layers/detail
mapView(position={}){
cancelAnimationFrame(this._rafmap);
this._rafmap = requestAnimationFrame(()=>{
var z = position.k, view, layer, layers = this.layers;
// I don't know d3
view = layers._groups[0][0].classList;
layer = 'show-streets';
if(view.contains(layer)){
if(z <= 6) view.remove(layer);
}else if(z > 6){
view.add(layer);
};
layer = 'show-arteries';
if(view.contains(layer)){
if(z <= 3) view.remove(layer);
}else if(z > 3){
view.add(layer);
};
layer = 'show-freeways';
if(view.contains(layer)){
if(z <= 1.5) view.remove(layer);
}else if(z > 1.5){
view.add(layer);
};
layers.attr("transform", position);
});
}
connectedCallback(){
var data;
if(!this._setup){
// initial setup: projection, load and draw layers, start updating
data = this.data;
data.projection = d3.geoMercator().scale(data.scale).center([+data.lon, +data.lat]);
data.pathprojector = d3.geoPath().projection(data.projection);
this.map.call(
d3.zoom()
.scaleExtent([1,30])
.on('zoom', ()=>{ this.mapView(d3.event.transform) })
)
data.content.trim().split(/\s+/).map((path, i) => {
this.layers.append('g').attr('src', path)
d3.json(path)
.then((json)=>{
json.path = path;
this.layerDrawer(json);
return json;
})
.catch((err)=>{
console.warn('problem layer',path,err);
return err;
})
return path;
});
this.layers.append('g').attr('class','vehicles');
}
this.update();
}
disconnectedCallback(){
// stop updating
clearTimeout(this.data.timer);
}
}
window.customElements.define('the-map', TheMap);
class TheControls extends HTMLElement{
constructor(){
super();
this.attachShadow({mode:'open'});
// {tags: {N: {}...}, taglist: []}
this.data = {};
this.addEventListener('click', this.clicked);
}
clicked(e){
var $ = e.composedPath()[0], tags = this.data.tags, prev;
e.stopPropagation();
switch($.nodeName){
case 'INPUT':
switch($.value){
case 'all':
Array.from(this.shadowRoot.querySelectorAll('button')).forEach(($)=>{
tags[$.value].active = true;
$.classList.add('active');
});
break;
case 'clear':
Array.from(this.shadowRoot.querySelectorAll('button')).forEach(($)=>{
tags[$.value].active = false;
$.classList.remove('active');
});
break;
};
this._previous = '';
this.dispatchEvent(new CustomEvent('change-active', {detail: this.data, cancelable: true, composed: true, bubbles: true}));
break;
case 'BUTTON':
if(e.metaKey || e.ctrlKey){
prev = this.shadowRoot.querySelector(`button[value="${this._previous}"]`);
if(prev && prev !== $){
tags[prev.value].active = prev.classList.toggle('active');
}
};
this._previous = $.value;
tags[$.value].active = $.classList.toggle('active');
this.dispatchEvent(new CustomEvent('change-active', {detail: this.data, cancelable: true, composed: true, bubbles: true}));
break;
};
}
//<button value="10" class="active">10</button>
tagHTML(item){
return `<button value="${ item.name }" class="${ item.active ? 'active':'' }">${ item.name }</button>`
}
render(){
this.shadowRoot.innerHTML = `
<style>
button{font-weight:bold;}
button.active{background-color:var(--dark);color:white;}
</style>
<input type=button value=all>
<input type=button value=clear>
<br>
${ this.data.taglist.map(this.tagHTML).join(' ') }
`;
}
get model(){
return this.data;
}
set model(data){
this.data = data;
this.render();
return true;
}
}
window.customElements.define('the-controls', TheControls);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T05:41:35.020",
"Id": "380661",
"Score": "1",
"body": "Welcome to Code Review: this is indeed the appropriate SE place to ask your question. Well, I'm pretty much the only D3 answerer around here these days, so here is my 2 cents: yo... | [
{
"body": "<p>Just as <a href=\"https://codereview.stackexchange.com/questions/197446/map-of-sf-transit-cars/201904#comment380661_197446\">Gerardo hinted at in comments</a>, I admit that I am not well-versed with d3 and at most can offer general JavaScript feedback. Nonetheless here is what I came up with:</p>\... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T19:04:26.913",
"Id": "197446",
"Score": "6",
"Tags": [
"javascript",
"ecmascript-6",
"html5",
"dom",
"d3.js"
],
"Title": "map of SF transit cars"
} | 197446 |
<p>I have written this code in C# to connect to an Oracle Database, omitting the tnsnames.ora file, then place results from a query into a CSV File.</p>
<p>Is there more efficient way to do this? (Such as reading in the data into a DataReader rather than a DataTable)</p>
<p>Please review and tell me what you would change.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
using System.Configuration;
using System.Data;
using FileHelpers;
using System.IO;
namespace oracle_test
{
class Program
{
static void Main(string[] args)
{
OraTest ot = new OraTest();
ot.Connect();
}
class OraTest
{
public void Connect()
{
var constr = new OracleConnectionStringBuilder()
{
DataSource = @"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 10.100.100.10)(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = ONE10)))",
UserID = "100",
Password = "100",
}.ConnectionString;
using (var con = new OracleConnection(constr))
{
string prfbalqry = "select * from ati where be = 0";
OracleCommand cmd = new OracleCommand(prfbalqry, con);
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
DataTable pbResults = new DataTable();
OracleDataAdapter oda = new OracleDataAdapter(cmd);
oda.Fill(pbResults);
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = pbResults.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in pbResults.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(@"C:\Financial Reporting\Output Path\pbresults.csv", sb.ToString());
}
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p><code>OraTest</code> is not a useful name. Call it <code>OracleToCSVWriter</code> or something like that.</p>\n\n<hr>\n\n<p>Mind the naming of variables etc: <code>oda</code> is not very descriptive - <code>adapter</code> would maybe be better.</p>\n\n<hr>\n\n<p>Hardcoded username/password is rare... | {
"AcceptedAnswerId": "197470",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T20:33:40.037",
"Id": "197447",
"Score": "0",
"Tags": [
"c#",
".net",
"csv",
".net-datatable"
],
"Title": "Pull From Oracle into CSV File"
} | 197447 |
<p>I have the following code that causes my excel to 'not respond' however if I step through put a breakpoint at the loop <code>For thisScen = 1 To UBound(stressScenMapping, 1)</code> to <code>Next thisScen</code> and run it next by next it works but takes long. When running at once it takes so long. It slows down at this For triple loop.</p>
<p>It does run fast in excel 2010 (3 seconds).
I currently run excel 2013.</p>
<p>Why does it run fast in excel 2010, but 2013 is giving me big issues?</p>
<p>The code does some mapping between sheets and writes to database.</p>
<pre><code>Public Sub calc()
Application.ScreenUpdating = False
Dim i As Long, thisScen As Long, nRows As Long, nCols As Long
Dim stressWS As Worksheet
Set stressWS = Worksheets("EQ_Shocks")
Unprotect_Tab ("EQ_Shocks")
nRows = lastWSrow(stressWS)
nCols = lastWScol(stressWS)
Dim readcols() As Long
ReDim readcols(1 To nCols)
For i = 1 To nCols
readcols(i) = i
Next i
Dim eqShocks() As Variant
eqShocks = colsFromWStoArr(stressWS, readcols, False)
'read in database columns
Dim dataWs As Worksheet
Set dataWs = Worksheets("database")
nRows = lastrow(dataWs)
nCols = lastCol(dataWs)
Dim dataCols() As Variant
Dim riskSourceCol As Long
riskSourceCol = getWScolNum("header1", dataWs)
ReDim readcols(1 To 4)
readcols(1) = getWScolNum("header2", dataWs)
readcols(2) = getWScolNum("header3", dataWs)
readcols(3) = getWScolNum("header4", dataWs)
readcols(4) = riskSourceCol
dataCols = colsFromWStoArr(dataWs, readcols, True)
'read in scenario mappings
Dim mappingWS As Worksheet
Set mappingWS = Worksheets("mapping_ScenNames")
Dim stressScenMapping() As Variant
ReDim readcols(1 To 2): readcols(1) = 1: readcols(2) = 2
stressScenMapping = colsFromWStoArr(mappingWS, readcols, False, 2) 'include two extra columns to hold column number for IR and CR shocks
For i = 1 To UBound(stressScenMapping, 1)
stressScenMapping(i, 3) = getWScolNum(stressScenMapping(i, 2), dataWs)
If stressScenMapping(i, 2) <> "NA" And stressScenMapping(i, 3) = 0 Then
MsgBox ("Could not find " & stressScenMapping(i, 2) & " column in database")
Exit Sub
End If
Next i
ReDim readcols(1 To 4): readcols(1) = 1: readcols(2) = 2: readcols(3) = 3: readcols(4) = 4
stressScenMapping = filterOut(stressScenMapping, 2, "NA", readcols)
'calculate stress and write to database
Dim thisEqShocks() As Variant
Dim keepcols() As Long
ReDim keepcols(1 To UBound(eqShocks, 2))
For i = 1 To UBound(keepcols)
keepcols(i) = i
Next i
Dim thisCurrRow As Long
For thisScen = 1 To UBound(stressScenMapping, 1)
thisEqShocks = filterIn(eqShocks, 2, stressScenMapping(thisScen, 1), keepcols)
If thisEqShocks(1, 1) = "#EMPTY" Then
For i = 2 To nRows
If dataCols(i, 4) <> "stack" And dataCols(i, 4) <> "overflow" And (dataCols(i, 1) = "Equity|Public" Or dataCols(i, 1) = "Equity|Private") Then
dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = "No shock found"
End If
Next i
Else 'calculate shocks
Call quicksort(thisEqShocks, 3, 1, UBound(thisEqShocks, 1))
For i = 2 To nRows
If dataCols(i, 4) <> "stack" And dataCols(i, 4) <> "ITS" And (dataCols(i, 1) = "Equity|Public" Or dataCols(i, 1) = "Equity|Private" Or dataCols(i, 1) = "Pref Shares") Then
thisCurrRow = findInArrCol(dataCols(i, 3), 3, thisEqShocks)
If thisCurrRow = 0 Then 'could not find currency so use generic shock
thisCurrRow = findInArrCol("OTHERS", 3, thisEqShocks)
End If
If thisCurrRow = 0 Then
dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = "No shock found"
Else
dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = Replace(dataCols(i, 2), "-", 0) * (thisEqShocks(thisCurrRow, 4) - 1)
End If
End If
Next i
End If
Next thisScen
Application.ScreenUpdating = True
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T21:23:25.420",
"Id": "380616",
"Score": "0",
"body": "@Close-Voter(s): the code *does* work as intended, just too slow. Nothing in the OP suggests anything is broken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate... | [
{
"body": "<p>This is essentially what you're doing <em>on a sheet</em></p>\n\n<pre><code>FOR every item in stressScenMapping\n Make thisEqShocks\n IF thisEqShocks(1,1) = empty then\n FOR EVERY ROW\n if EACH ROW IS THESE THEN\n WRITE ON THAT ROW\n END IF\n ... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T21:08:43.550",
"Id": "197450",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Mapping between 3 sheets, write to final sheet"
} | 197450 |
<p>I am attempting to make an eCommerce site from scratch. Right now I have the following code that gets all the items from a Firebase Firestore database and then adds HTML into an items div element based on the item's info.</p>
<pre><code>var items = [];
var itemsDiv = document.getElementsByClassName("items")[0];
db.collection("items").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
var docData = doc.data();
items.push(docData);
});
renderItems();
});
function renderItems() {
console.log(items);
items.forEach(function(item) {
itemsDiv.innerHTML += `
<div class="item">
<img class="itemImgBackground" src="assets/${item.name.replace(" ", "")}.png">
<img class="itemImg" src="assets/${item.name.replace(" ", "")}.png">
<span class="itemName">${item.name}</span>
<span class="itemCondition">${item.condition}</span>
<span class="itemPrice">${item.price}</span>
</div>
`
});
}
</code></pre>
<p>What can I do to make my code better?</p>
| [] | [
{
"body": "<p>Here are a few things:</p>\n\n<ul>\n<li><p>good you're using <code>`</code> (template literals) to format your HTML inside the JavaScript code</p></li>\n<li><p>don't use <code>innerHTML +=</code> as it forces the browser to re-render the DOM when called. Read more here: <a href=\"https://stackover... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T22:29:25.970",
"Id": "197453",
"Score": "4",
"Tags": [
"javascript",
"functional-programming",
"ecmascript-6",
"iterator",
"firebase"
],
"Title": "Loading items for an eCommerce site"
} | 197453 |
<p>I am implementing a program to draw a box of text next to some other drawn object (that can have any position and dimensions) and the text box should always be visible, even if the drawn object's width is of the entire screen and vice versa.
They should simply not overlap.</p>
<p>This is a code to position the text on some relatively good coordinates.</p>
<pre><code>if(x > (box_w + 20)) box_x = x - (box_w + 20);
else box_x = w + 20;
if(y > (box_h + 20)) box_y = y - (box_h + 20);
else box_y = h + 20;
if(w > width - (box_h + 20) || x + w + box_w + 20 > width)
{
box_x = 20;
if(y < box_h + 20)
{
box_y = h + 20;
}
else box_y = y - (box_h + 20);
}
</code></pre>
<p><code>x</code>, <code>y</code>, <code>w</code>, <code>h</code> are the coords and dimensions for the object; <code>box_x</code>, <code>box_y</code>, <code>box_w</code> and <code>box_y</code> are for the text box and width/height is the dimension of the area.</p>
<p>Here is schematically how this code positions text (darker blue) near the object (lighter blue)
<a href="https://i.stack.imgur.com/uNYNs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uNYNs.png" alt="box positioning examples"></a></p>
<p>It is quite obvious that it could have been written much better.
To target performance, but more importantly - code space.</p>
<p>Can anyone suggest a better way to find good coordinates for the text box?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T23:49:51.573",
"Id": "380633",
"Score": "1",
"body": "Could you add more of your code for context? This is not much to go on, just a series of conditionals, seeing the code that makes the box and draws it would help clarify."
},
... | [
{
"body": "<p>This is a definite candidate for using rect / point structures, but I don't know what the rest of your code-base looks like, so just talking about the algorithm alone, one approach would be:</p>\n\n<pre><code>void FindNonOverlappingPosition(\n uint canvasWidth, uint canvasHeight,\n uint x1, ... | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T23:26:52.813",
"Id": "197457",
"Score": "2",
"Tags": [
"performance",
"c",
"coordinate-system"
],
"Title": "Calculations to position a text box next to another object"
} | 197457 |
<p>This is a form that I want to use to enter users into a database. I used MySQLi with prepared statements. I want to make sure that I sanitized my data well.</p>
<pre><code><?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once './db_con.php';
$id = '';
$firstname = trim(filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
$lastname = trim(filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
//$val_email = trim(filter_var($email, FILTER_VALIDATE_EMAIL));
$password = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
$password2 = trim(filter_input(INPUT_POST, 'password2', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
$errs = array();
#firstname
if ( empty($firstname) ) {
$errs[] = "Please enter your first name.";
}
#lastname
if ( empty($lastname) ) {
$errs[] = "Please enter your last name.";
}
#email
if ( empty($email) ) {
$errs[] = "Please enter your E-mail.";
}
#email validation
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
$errs[] = "Please enter a valid E-mail.";
}
#check if email exist
if ( email_exists($email,$connection) ) {
$errs[] = "Your E-mail already exists.";
}
#password
if ( empty($password) ) {
$errs[] = "Please enter your password.";
} elseif (strlen($password) < 6) {
$errs[] = "Your password must have at least 6 characters.";
}
#confirm-password
if ( empty($password2) ) {
$errs[] = "Please confirm your password.";
} else {
#matching-passwords
if ( $password !== $password2 ) {
$errs[] = "Password didn't match.";
}
}
if ( !empty( $errs ) ) {
foreach ($errs as $err) {
echo $err.'</br >';
}
} else {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `password`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $id, $firstname, $lastname, $email, $hashed_password);
if ( !($stmt->execute()) ) {
echo "There was a problem, Try again.";
} else {
echo "You are registered now.";
}
$stmt->close();
}
#functions
function email_exists($email,$connection) {
$stmt = $connection->prepare("SELECT * FROM `users` WHERE `email` = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$rows_count = $result->num_rows;
if ( $rows_count >= 1 ) {
return TRUE;
}
$stmt->close();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T11:12:41.750",
"Id": "380699",
"Score": "1",
"body": "This question [is being discussed on meta](https://codereview.meta.stackexchange.com/q/8895/31503)"
}
] | [
{
"body": "<p>This code is perfectly safe. The only issue with sanitization in this code is that it makes the data, so to say, <em>overly-sanitized</em>.</p>\n\n<p>The way you are getting your input variables, makes them suitable for the HTML output. But there is no HTML output in the code present. Which makes ... | {
"AcceptedAnswerId": "197493",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T23:33:48.860",
"Id": "197458",
"Score": "1",
"Tags": [
"php",
"mysqli"
],
"Title": "Entering users into a MySQLi database"
} | 197458 |
<p>I have a contact form that will perform validation on the server. Right now the form checks if the fields are empty or not. My goal is to expand it following:</p>
<p>Check the fields for particular format, if it is a proper email format, phone number format, etc
Set the field as required or not</p>
<p>My form is as below, I appreciate any suggestions on how to clean it up and make it easier to adjust and overall cleaner.</p>
<pre><code><?php
ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");
error_log( "Errors" );
include "recaptcha.php";
include 'email.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['firstName']))
$errors['firstName'] = 'First Name is required.';
if (empty($_POST['lastName']))
$errors['lastName'] = 'Last Name is required.';
if (empty($_POST['companyName']))
$errors['companyName'] = 'Company Name is required.';
if (empty($_POST['companyAddress']))
$errors['companyAddress'] = 'Company Address is required.';
if (empty($_POST['city']))
$errors['city'] = 'City is required.';
if (empty($_POST['state']))
$errors['state'] = 'State is required.';
if (empty($_POST['emailAddress']))
$errors['emailAddress'] = 'Email Address is required.';
if (empty($_POST['comment']))
$errors['comment'] = 'Comment is required.';
if (empty($_POST['g-recaptcha-response']))
$errors['recaptcha'] = 'Captcha is required.';
// return a response ===========================================================
// Check ReCaptcha Validation
if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
$errors['recaptcha'] = 'Captcha is required.';
}
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
//Begin of send email
$mail = new PHPMailer;
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.server.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "user@server.com";
$mail->Password = "super_secret_password";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->From = $emailAddress;
$mail->addAddress("name@server.com", "Recepient Name");
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = $emailBody;
if(!$mail->send())
{
$data['success'] = false;
$data['errors'] = "Mailer Error: " . $mail->ErrorInfo;
}
else
{
$data['message'] = 'Success!';
}
?>
</code></pre>
| [] | [
{
"body": "<h3>General inconsistency</h3>\n<p>Basically your code is borderline off topic. Although it could work, it is not a working code in the sense a programmer could take it; but rather a set of copy-pasted code blocks loosely (and wrongly) connected to each other.</p>\n<p>The main problem is inconsistent... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-28T23:35:21.243",
"Id": "197459",
"Score": "0",
"Tags": [
"php",
"form",
"ajax"
],
"Title": "Writing cleaner PHP code to add additional options"
} | 197459 |
<p>I want to substring a String from given start index and given substring length.</p>
<ol>
<li>if the string is empty then returns String.Empty </li>
<li>if the string length is greater than start index then it substrings from given start index to given length...</li>
<li>if the string length is less than start index then it returns from start index to last index</li>
</ol>
<p>I just want to know if it can be improved and shorter with all these checks.</p>
<ol>
<li>if the string is null or empty</li>
<li>if the start index is not less than zero </li>
<li>if the start index is less than the length of given input string.</li>
<li>if the given input string length is less than the desired substring length. </li>
<li>if the given input string length is greater than the desired substring length. </li>
</ol>
<p><strong>Sample Input and Ouput for my program:</strong></p>
<pre><code>SplitEntity("", 1, 15) => ""
SplitEntity("abcdef", 0, 3) => "abc"
SplitEntity("abcdef", 3, 100) => "def"
SplitEntity("abcdef", 0, 100) => "abcdef"
SplitEntity("abcdef", -1, 100) => ""
</code></pre>
<p><strong>My function is below:</strong></p>
<pre><code>Public Function SplitEntity(entity As String, startIndex As Integer,
subStringLength As Integer) As String
Dim spilttedString As String = String.Empty
If (Not String.IsNullOrEmpty(entity) AndAlso startIndex >=0 ) Then
If (entity.Length > startIndex) Then
If entity.Length >= (startIndex + subStringLength) Then
spilttedString = entity.Substring(startIndex, subStringLength)
ElseIf entity.Length < (startIndex + subStringLength) Then
spilttedString = entity.Substring(startIndex, (entity.Length - startIndex))
End If
End If
End If
Return spilttedString
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T01:20:15.943",
"Id": "380643",
"Score": "0",
"body": "Welcome to Code Review! I hope you get some good answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T01:42:22.280",
"Id": "380647",
"... | [
{
"body": "<p>for something like this I would suggest making it an <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/how-to-write-an-extension-method\" rel=\"nofollow noreferrer\">Extension Method</a>.</p>\n\n<p>To that end I would suggest a name chang... | {
"AcceptedAnswerId": "197469",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T01:01:44.673",
"Id": "197460",
"Score": "2",
"Tags": [
".net",
"vb.net"
],
"Title": "Substring a String from given start index and given substring length"
} | 197460 |
<p>To learn network programming in Python, I have written a small piece of code which is constituted of 2 modules, a client and a server. The server listens to a specific port provided on command line, then the client connects to the server, and send a file to it.</p>
<p>The client sends the size of file at first, then the content of file. During data transmission, both side of socket update a SHA256 object, and when transmission is completed, they calculate the hash digests and print them on screen.</p>
<p>I know my code is still far from being a robust implementation, so I am looking for your opinions. Any criticism is welcome. Thank you.</p>
<p>Module <code>bigfile_server.py</code>:</p>
<pre><code># -*- encoding: utf-8 -*-
import sys
import struct
import getopt
import socket
import hashlib
from datetime import datetime
FILE_BUFFER_SIZE = 524288
def usage():
print('Usage: bigfile_server.py <SERVER_PORT>')
print('SERVER_PORT: Port to which server will listen.')
def random_filename():
dt_now = datetime.now()
return dt_now.strftime('%Y%m%d%H%M%S%f')
def readn(sock, count):
data = b''
while len(data) < count:
packet = sock.recv(count - len(data))
if packet == '':
return ''
data += packet
return data
if __name__ == '__main__':
server_port = ''
opts, args = getopt.gnu_getopt(sys.argv[1:], 'p:', ['port='])
for opt, arg in opts:
if opt in ('-p', '--port'):
server_port = arg
if server_port == '':
print('Server port missing.', file=sys.stderr)
usage()
sys.exit(1)
if not server_port.isdecimal():
print('Server port contains invalid characters.', file=sys.stderr)
sys.exit(2)
print('Launching bigfile server.')
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serv_sock.bind(('', int(server_port)))
serv_sock.listen(5)
except socket.error as e:
print('Failed to launch server:', e)
sys.exit(3)
else:
print('Server launched, waiting for new connection.')
try:
clnt_sock, clnt_addr = serv_sock.accept()
except socket.error as e:
print ('Failed to accept new connection:', e)
sys.exit(3)
else:
print('New connection from:', clnt_sock)
size_buff = readn(clnt_sock, 4)
if size_buff == '':
print('Failed to receive file size.', file=sys.stderr)
clnt_sock.close()
serv_sock.close()
sys.exit(3)
size_unpacked = struct.unpack('!I', size_buff)
file_size = size_unpacked[0]
print('Will receive file of size', file_size, 'bytes.')
hash_algo = hashlib.sha256()
filename = random_filename()
try:
with open(filename, 'wb') as file_handle:
while file_size > 0:
buffer = clnt_sock.recv(FILE_BUFFER_SIZE)
print(len(buffer), 'bytes received.')
if buffer == '':
print('End of transmission.')
break
hash_algo.update(buffer)
file_handle.write(buffer)
file_size -= len(buffer)
if file_size > 0:
print('Failed to receive file,', file_size, 'more bytes to go.')
except socket.error as e:
print('Failed to receive data:', e, file=sys.stderr)
clnt_sock.close()
serv_sock.close()
sys.exit(3)
except IOError as e:
print('Failed to write file:', e, file=sys.stderr)
clnt_sock.close()
serv_sock.close()
sys.exit(3)
else:
print('File transmission completed.')
clnt_sock.shutdown(socket.SHUT_RD)
clnt_sock.close()
serv_sock.close()
print('Server shutdown.')
print('SHA256 digest:', hash_algo.hexdigest())
sys.exit(0)
</code></pre>
<p>Module <code>bigfile_client.py</code>:</p>
<pre><code># -*- encoding: utf-8 -*-
import os
import sys
import struct
import getopt
import socket
import hashlib
FILE_BUFFER_SIZE = 524288
def usage():
print('Usage: bigfile_client.py <ARGUMENTS>')
print('ARGUMENTS:')
print('[-f|--file]: Source file to send.')
print('[-h|--host]: Server address.')
print('[-p|--port]: Server port number.')
if __name__ == '__main__':
source_file, server_addr, server_port = '', '', ''
opts, args = getopt.gnu_getopt(sys.argv[1:], 'f:h:p:', ['file=', 'host=', 'port='])
for opt, arg in opts:
if opt in ('-f', '--file'):
source_file = arg
elif opt in ('-h', '--host'):
server_addr = arg
elif opt in ('-p', '--port'):
server_port = arg
if source_file == '':
print('Source file missing.', file=sys.stderr)
usage()
sys.exit(1)
elif server_addr == '':
print('Server address missing.', file=sys.stderr)
usage()
sys.exit(1)
elif server_port == '':
print('Server port number missing.', file=sys.stderr)
usage()
sys.exit(1)
if not os.path.isfile(source_file):
print('Source file cannot be found.', file=sys.stderr)
sys.exit(2)
elif not server_port.isdecimal():
print('Server port number contains invalid characters.', file=sys.stderr)
sys.exit(2)
file_size = os.path.getsize(source_file)
print('Sending file {0} to {1}:{2}.'.format(source_file, server_addr, server_port))
print('Source file size:', file_size, 'bytes.')
print('Connecting to remote server.')
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
conn.connect((server_addr, int(server_port)))
except socket.error as e:
print('Failed to connect to server:', e)
sys.exit(3)
else:
print('Connection established.')
print('Sending file size to remote server.')
buffer = b''
buffer = struct.pack('!I', file_size)
print('File size packed into binary format:', buffer)
try:
conn.sendall(buffer)
except socket.error as e:
print('Failed to send file size:', e)
sys.exit(3)
else:
print('File size sent.')
hash_algo = hashlib.sha256()
print('Start to send file content.')
try:
with open(source_file, 'rb') as file_handle:
buffer = file_handle.read(FILE_BUFFER_SIZE)
while len(buffer) > 0:
conn.sendall(buffer)
hash_algo.update(buffer)
buffer = file_handle.read(FILE_BUFFER_SIZE)
except IOError as e:
print('Failed to open source file', source_file, ':', e, file=sys.stderr)
sys.exit(3)
conn.shutdown(socket.SHUT_WR)
conn.close()
print('File sent, connection closed.')
print('SHA256 digest:', hash_algo.hexdigest())
sys.exit(0)
</code></pre>
| [] | [
{
"body": "<p>If I’m reading this correctly - I did not test it, the file cannot be larger than a 4 byte integer of bytes which is only a 4gb file, which in 2018 I wouldn’t have considered large since it fits in memory for most laptops.</p>\n<p>I love that you are using getopts!</p>\n<p>What I’m not loving is t... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T01:59:26.243",
"Id": "197462",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"socket"
],
"Title": "Large file transmission over socket in Python"
} | 197462 |
<p>I have two lists of numbers:</p>
<p>$$\{i_1, i_2, i_3,i_4\}$$ and $$\{j_1,j_2,j_3,j_4\}$$</p>
<p>The problem I want to solve is: Inside a loop, if the following two conditions are satisfied, then it will do something I want, otherwise it just cycle the loop. The conditions are:</p>
<ol>
<li>Both lists contain four different numbers;</li>
<li>If ignoring the ordering, in other words, we view these two lists as two set, then they are the same.</li>
</ol>
<p>I want to find a very fast way to get the answer to the problem. I have very slow Fortran code as follows:</p>
<pre><code>if (i2==i1) cycle
if (i3==i1) cycle
if (i3==i2) cycle
if (i4==i1) cycle
if (i4==i2) cycle
if (i4==i3) cycle
if (j2==j1) cycle
if (j3==j1) cycle
if (j3==j2) cycle
if (j4==j1) cycle
if (j4==j2) cycle
if (j4==j3) cycle
q1=0
q2=0
q3=0
q4=0
if (i1==j1)q1=1
if (i1==j2)q1=2
if (i1==j3)q1=3
if (i1==j4)q1=4
if (i2==j1)q2=1
if (i2==j2)q2=2
if (i2==j3)q2=3
if (i2==j4)q2=4
if (i3==j1)q3=1
if (i3==j2)q3=2
if (i3==j3)q3=3
if (i3==j4)q3=4
if (i4==j1)q4=1
if (i4==j2)q4=2
if (i4==j3)q4=3
if (i4==j4)q4=4
if (q1*q2*q3*q4==24)then
Something I want to do
endif
</code></pre>
<p>I think to find a good program, the following should also be considered as well as cutting down the number of instructions:</p>
<ol>
<li>The probability to have four different numbers in both lists are about
1/10;</li>
<li>The probability to have for these two lists containing two same set
of numbers are very small, about 10^(-11); </li>
<li>I really have to do many loops.</li>
</ol>
<p>Could someone help me out? I think a good idea can really boost the code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T14:12:00.880",
"Id": "380721",
"Score": "0",
"body": "What are the ranges of the loops? Are those if statements at the inner-most loop, or are they located at the top level of the loop(s)?"
},
{
"ContentLicense": "CC BY-SA 4... | [
{
"body": "<p>The only way to reduce the number of operations is to sort one of the arrays. But 4 elements is hardly worth it. </p>\n\n<p>Perhaps when adding the numbers to the array then add them in a sorted order, otherwise quicksort is good for arrays under 10 elements in size.</p>\n\n<p>Performing a binary ... | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T03:45:43.047",
"Id": "197465",
"Score": "1",
"Tags": [
"sorting",
"complexity",
"fortran"
],
"Title": "Checking whether two lists contain the same elements"
} | 197465 |
<p>I have a list of 2D arrays which comes from a time evolution PDE (in \$(x, y, t)\$) that I solved numerically. There are \$k\$ arrays, which all have the same dimensions, and the arrays correspond to a solution field of the PDE at times \$t = 0, 0.1, \dots, 0.1k\$. I wrote a program that takes in this list and computes the autocorrelation between the arrays for varying lag times. </p>
<p>From the <a href="https://en.wikipedia.org/wiki/Autocorrelation#Statistics" rel="nofollow noreferrer">definition of the autocorrelation function for wide-sense stationary processes</a>, we have </p>
<p>$$R(\tau) = \frac{\mathbb{E}[(X_{t} - \mu)(X_{t + \tau} - \mu)]}{\sigma^{2}} = \frac{1}{\sigma^{2}} \sum_{t = 0}^{k-\tau} (X_{t} - \mu)(X_{t + \tau} - \mu)$$</p>
<p>Here, \$X_{t}\$ represents our 2D array at time \$t\$ and \$\mu\$, \$\sigma\$ the average and standard deviation, respectively, of the entire list of 2D arrays. My code for this is as follows</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
### Data
# List of data arrays called 'Data'.
### Expectation
New_Data = []
O = np.ones((len(Data[0][0]),len(Data[0][1]))) # Resolution of data arrays.
A = sum(Data)/len(Data) # Average 2D array
M = np.mean(A) # Average of average 2D array
S = np.std(A) # Standard deviation of average 2D array
for i in range(len(Data)):
New_Data.append((Data[i]-M*O)/S) # (X_t-mu)/sigma
### Autocorrelation for varying lags.
Count = 1
R = []
while Count < len(New_Data)//2: # Arbitrary choice for max lag time.
Matrix_Multiply = []
for j in range(len(New_Data)-Count):
Matrix_Multiply.append(np.multiply(New_Data[j],New_Data[j+Count]))
R.append(sum(Matrix_Multiply))
Count = Count+1
Solution = []
for k in range(len(R)):
Solution.append(np.mean(R[k]))
t = [0.1*k for k in range(1,len(Solution)+1)]
### Plotting
plt.xlabel('Lag time')
plt.ylabel('Matrix sum')
plt.title('Field autocorrelation over time')
plt.semilogy(t, Solution)
plt.savefig('I_hope_this_works.png')
</code></pre>
<p>I'm sure there are some redundant steps in there, so I was wondering if anyone can see how I could make the code cleaner? Also, if anyone knows how to apply <a href="http://numba.pydata.org/numba-doc/0.33.0/index.html" rel="nofollow noreferrer">pythons numba package</a> to make the code faster, it would be greatly appreciated, as I haven't been able to figure it out from the documentation in the hyperlink. </p>
<p><strong>EDIT</strong></p>
<p>In response to the comment below, here is some arbitrary data to use</p>
<pre><code>Data = []
n = 20
for k in range(n):
Data.append(np.random.randint(n, size=(n,n)))
</code></pre>
<p>For my data, I have ~800 arrays of size 256x256. I don't think I'm able to upload that for anyone to use.</p>
<p><strong>EDIT 2</strong></p>
<p>I just realised that we don't need to keep the data in the R list, so we can remove it as well as the lines</p>
<pre><code>Solution = []
for k in range(len(R)):
Solution.append(np.mean(R[k]))
</code></pre>
<p>and edit the while loop to</p>
<pre><code>### Autocorrelation for varying lags.
Count = 1
Solution = []
while Count < len(New_Data)//2: # Arbitrary choice for max lag time.
Matrix_Multiply = []
for j in range(len(New_Data)-Count):
Matrix_Multiply.append(np.multiply(New_Data[j],New_Data[j+Count]))
R = sum(Matrix_Multiply)
Solution.append(np.mean(R))
Count = Count+1
</code></pre>
<p>though it doesn't provide much of a markup in terms of speed.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T12:44:30.607",
"Id": "380710",
"Score": "0",
"body": "It would help if you could provide some example data. Right now it is very hard to test any alternative approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDat... | [
{
"body": "<p>So here is a slightly simplified version that uses more <code>numpy</code> functionalities, where your solution manually iterates over the outer lists:</p>\n\n<pre><code>def autocorrelate_graipher(Data):\n Data = np.array(Data)\n A = Data.mean(axis=0) # Average 2D arra... | {
"AcceptedAnswerId": "197500",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T05:48:40.303",
"Id": "197467",
"Score": "6",
"Tags": [
"python",
"numpy",
"statistics",
"matplotlib"
],
"Title": "Computing the autocorrelation between 2D time series arrays in python"
} | 197467 |
<p>Could I please have some ideas how to improve this conversion calculator I have made. I am currently not looking to add any more quantities, but rather trying to enhance the usability and add some quality of life changes to it. </p>
<p>If there are any major ways I could make the program more efficient that would be helpful as well.</p>
<p>Here is my <a href="https://github.com/APOCHA/Conversion-Calculator/blob/master/calc%20shortening.py" rel="nofollow noreferrer">code</a>:</p>
<pre><code># Conversion Calculator #
#rid input unit
from tkinter import *
from tkinter import ttk
class GUI():
def __init__(self, master):
self.master = master
master.resizable(False, False)
master.title('Conversion Calculator')
self.tabControl = ttk.Notebook(master) # Tab Formatting
self.tab1 = ttk.Frame(self.tabControl)
self.tabControl.add(self.tab1, text='Weight')
self.tab2 = ttk.Frame(self.tabControl)
self.tabControl.add(self.tab2, text='Length')
self.tab3 = ttk.Frame(self.tabControl)
self.tabControl.add(self.tab3, text='Tempurature')
self.tabControl.pack(expand=1, fill="both")
self.intial_wording11 = StringVar(self.tab1) # Tab 1 Formatting
self.intial_wording11.set('Unit')
self.intial_wording12 = StringVar(self.tab1)
self.intial_wording12.set('Unit')
self.entrybox1 = ttk.Entry(self.tab1, width=12)
self.entrybox1.grid(column=0, row=1)
self.entrybox1.focus_set()
self.Iunit1 = StringVar()
self.input_unit1 = ttk.Combobox(self.tab1, width=12, textvariable=self.Iunit1, state="readonly", values = ['Unit', 'Grams', 'Kilograms', 'Tons', 'Ounces', 'Pounds'])
self.input_unit1.grid(column=1, row=1)
self.input_unit1.current(0)
self.convert_bttn1 = ttk.Button(self.tab1, text='Convert', command=self.weight)
self.convert_bttn1.grid(column=0, row=3)
self.outputbox1 = ttk.Entry(self.tab1, width=12, state="readonly")
self.outputbox1.grid(column=0, row=4)
self.Ounit1 = StringVar()
self.output_unit1 = ttk.Combobox(self.tab1, width=12, textvariable=self.Ounit1, state="readonly", values = ['Unit', 'Grams', 'Kilograms', 'Tons', 'Ounces', 'Pounds'])
self.output_unit1.grid(column=1, row=4)
self.output_unit1.current(0)
self.intial_wording21 = StringVar(self.tab2) # self.tab 2 Formatting #
self.intial_wording21.set('Unit')
self.intial_wording22 = StringVar(self.tab2)
self.intial_wording22.set('Unit')
self.entrybox2 = ttk.Entry(self.tab2, width=12)
self.entrybox2.grid(column=0, row=1)
self.entrybox2.focus_set()
self.Iunit2 = StringVar()
self.input_unit2 = ttk.Combobox(self.tab2, width=12, textvariable=self.Iunit2, state="readonly", values = ['Unit', 'Millimeters', 'Centimeters', 'Meters', 'Kilometers', 'Miles', 'Feet', 'Inches', 'Yards'])
self.input_unit2.grid(column=1, row=1)
self.input_unit2.current(0)
self.convert_bttn2 = ttk.Button(self.tab2, text='Convert', command=self.length)
self.convert_bttn2.grid(column=0, row=3)
self.outputbox2 = ttk.Entry(self.tab2, width=12, state="readonly")
self.outputbox2.grid(column=0, row=4)
self.Ounit2 = StringVar()
self.output_unit2 = ttk.Combobox(self.tab2, width=12, textvariable=self.Ounit2, state="readonly", values = ['Unit', 'Millimeters', 'Centimeters', 'Meters', 'Kilometers', 'Miles', 'Feet', 'Inches', 'Yards'])
self.output_unit2.grid(column=1, row=4)
self.output_unit2.current(0)
self.intial_wording31 = StringVar(self.tab3) # self.tab 3 Formatting #
self.intial_wording31.set('Unit')
self.intial_wording32 = StringVar(self.tab3)
self.intial_wording32.set('Unit')
self.entrybox3 = ttk.Entry(self.tab3, width=12)
self.entrybox3.grid(column=0, row=1)
self.entrybox1.focus_set()
self.Iunit3 = StringVar()
self.input_unit3 = ttk.Combobox(self.tab3, width=12, textvariable=self.Iunit3, state="readonly", values = ['Unit', 'Celcius', 'Farenheit', 'Kelvin']) # self.intial_wording
self.input_unit3.grid(column=1, row=1)
self.input_unit3.current(0)
self.convert_bttn3 = ttk.Button(self.tab3, text='Convert', command=self.tempurature)
self.convert_bttn3.grid(column=0, row=3)
self.outputbox3 = ttk.Entry(self.tab3, width=12, state="readonly")
self.outputbox3.grid(column=0, row=4)
self.Ounit3 = StringVar()
self.output_unit3 = ttk.Combobox(self.tab3, width=12, textvariable=self.Ounit3, state="readonly", values = ['Unit', 'Celcius', 'Farenheit', 'Kelvin'])#self.intial_wording2,
self.output_unit3.grid(column=1, row=4)
self.output_unit3.current(0)
self.master.bind('<Return>', self.keybind)
class Logic(GUI):
def keybind (self, event):
self.convert_bttn1.invoke()
self.convert_bttn2.invoke()
self.convert_bttn3.invoke()
def weight(self):
Weight_Conversion_Values = {'Grams': 1,
'Kilograms': 1000,
'Tons': 1000000,
'Ounces': 28.3495,
'Pounds': 453.592}
self.outputbox1.delete(0, END)
if self.Iunit1.get() != '':
if self.Ounit1.get() != '':
try:
self.outputbox1.config(state='NORMAL')
self.outputbox1.delete(0, 'end')
self.outputbox1.config(state='readonly')
text = float(self.entrybox1.get())
newtext = text*(Weight_Conversion_Values[self.Iunit1.get()])*(int(1)/(Weight_Conversion_Values[self.Ounit1.get()]))
self.outputbox1.config(state='NORMAL')
self.outputbox1.insert(0, newtext)
self.outputbox1.config(state='readonly')
except ValueError:
error_message = 'non-int error'
self.outputbox1.config(state='NORMAL')
self.outputbox1.insert(0, error_message)
self.outputbox1.config(state='readonly')
def length(self):
Length_Conversion_Values = {'Meters': 1,
'Kilometers': 1000,
'Centimeters': 0.01,
'Millimeters': 0.001,
'Miles': 1609.344498,
'Feet': 0.304799999,
'Inches': 0.02539998,
'Yards': 0.9144027578}
self.outputbox2.delete(0, END)
if self.Iunit2.get() != '':
if self.Ounit2.get() != '':
try:
self.outputbox2.config(state='NORMAL')
self.outputbox2.delete(0, 'end')
self.outputbox2.config(state='readonly')
text = float(self.entrybox2.get())
newtext = text*(Length_Conversion_Values[self.Iunit2.get()])*(int(1)/(Length_Conversion_Values[self.Ounit2.get()]))
self.outputbox2.config(state='NORMAL')
self.outputbox2.insert(0, newtext)
self.outputbox2.config(state='readonly')
except ValueError:
error_message = 'non-int error'
self.outputbox2.config(state='NORMAL')
self.outputbox2.insert(0, error_message)
self.outputbox2.config(state='readonly')
def tempurature(self):
self.outputbox3.delete(0, END)
if self.Iunit3.get() == 'Celcius':
self.outputbox3.config(state='NORMAL')
self.outputbox3.delete(0, 'end')
self.outputbox3.config(state='readonly')
try:
if self.Ounit3.get() == 'Kelvin':
if float(self.entrybox3.get()) >= -273.15:
text = float(self.entrybox3.get())
newtext = text + 273.15
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, newtext)
self.outputbox3.config(state='readonly')
else:
error_message = 'X ≥ -273.15'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
if self.Ounit3.get() == 'Farenheit':
if float(self.entrybox3.get()) >= -273.15:
text = float(self.entrybox3.get())
newtext = text*9/5 + 32
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, newtext)
self.outputbox3.config(state='readonly')
else:
error_message = 'X ≥ -273.15'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
except ValueError:
error_message = 'non-int error'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
if self.Iunit3.get() == 'Farenheit':
self.outputbox3.config(state='NORMAL')
self.outputbox3.delete(0, 'end')
self.outputbox3.config(state='readonly')
try:
if self.Ounit3.get() == 'Kelvin':
if float(self.entrybox3.get()) >= -459.67:
text = float(self.entrybox3.get())
newtext = (text+459.67)*5/9
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, newtext)
self.outputbox3.config(state='readonly')
else:
error_message = 'X ≥ -459.67'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
if self.Ounit3.get() == 'Celcius':
if float(self.entrybox3.get()) >= -459.67:
text = float(self.entrybox3.get())
newtext = text*5/9 - 32
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, newtext)
self.outputbox3.config(state='readonly')
else:
error_message = 'X ≥ -459.67'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
except ValueError:
error_message = 'non-int error'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
if self.Iunit3.get() == 'Kelvin':
self.outputbox3.config(state='NORMAL')
self.outputbox3.delete(0, 'end')
self.outputbox3.config(state='readonly')
try:
if self.Ounit3.get() == 'Celcius':
if float(self.entrybox3.get()) >= 0:
text = float(self.entrybox3.get())
newtext = text - 273.15
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, newtext)
self.outputbox3.config(state='readonly')
else:
error_message = 'X ≥ 0'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
if self.Ounit3.get() == 'Farenheit':
if float(self.entrybox3.get()) >= 0:
text = float(self.entrybox3.get())
newtext = text*9/5 - 459.67
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, newtext)
self.outputbox3.config(state='readonly')
else:
error_message = 'X ≥ 0'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
except ValueError:
error_message = 'non-int error'
self.outputbox3.config(state='NORMAL')
self.outputbox3.insert(0, error_message)
self.outputbox3.config(state='readonly')
if __name__ == "__main__":
root = Tk()
test = Logic(root)
</code></pre>
| [] | [
{
"body": "<p>One of the smartest programmer's I've ever known once told me that code is read way more often than it is written, so optimize for the reader<sup>1</sup></p>\n\n<p>While it's true that code should be efficient, it also needs to be understandable and maintainable. Also, efficiency is relative. If y... | {
"AcceptedAnswerId": "197491",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T07:35:38.443",
"Id": "197473",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"gui",
"tkinter",
"unit-conversion"
],
"Title": "Enhancing a Conversion calculator"
} | 197473 |
<p>Yesterday someone guided me through this <a href="https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/" rel="nofollow noreferrer">article</a> and I'm wondering whether I should use try-catch implementation or not? I have the following code below which is actually a RESTful service and I have implemented the try-catch pattern. I'm throwing errors only in debug mode just for testing purpose and during the release mode, I'm catching errors and returning the meaningful error messages such as Http Status Codes.</p>
<p>After reading this article, I'm confused whether I'm on the right track and if not, do I need to remove try-catch and throw errors instead of such meaningful messages to the end user? </p>
<p>Any code review/feedback is appreciated. </p>
<pre><code>namespace NewEmployeeBuddy.Facade.Controllers.Employee
{
[RoutePrefix("api/employee")]
[RequireHttps]
[BasicAuthorization]
public class EmployeeController : ApiController
{
#region Properties
private IEmployeeService _employeeService { get; set; }
#endregion
#region Constructor
public EmployeeController()
{
//_employeeService = new EmployeeService();
}
public EmployeeController(IEmployeeService employeeService)
{
_employeeService = employeeService;
}
#endregion
#region Actions
[HttpPost, Route("add")]
[ValidateRequest]
public IHttpActionResult AddEmployee(AddEmployeeRequestDTO request)
{
try
{
if (request == null)
return Content(HttpStatusCode.BadRequest, ErrorCodes.E002);
var response = _employeeService.AddEmployee(request);
if (response.OperationResult)
return Content(HttpStatusCode.Created, response);
return Content(HttpStatusCode.InternalServerError, ErrorCodes.E001);
}
catch (Exception ex)
{
#if (DEBUG)
Logger.Instance.Error(ex);
throw ex;
#endif
//Logger.Instance.Error(ex);
//return Content(HttpStatusCode.InternalServerError, ErrorCodes.E001);
}
}
#endregion
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T09:04:29.940",
"Id": "380685",
"Score": "1",
"body": "_`//No need to create the concrete instance. Autofac takes care of it.`_ - this is not true if you use this constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Crea... | [
{
"body": "<blockquote>\n<pre><code>throw ex;\n</code></pre>\n</blockquote>\n\n<p>This is a fatal mistake. It'll create a new stack-trace and you won't be able to tell where the actual exception occured. If you want to rethrow it then use just</p>\n\n<pre><code>throw;\n</code></pre>\n\n<p>without <code>ex</cod... | {
"AcceptedAnswerId": "197477",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T09:02:07.363",
"Id": "197476",
"Score": "6",
"Tags": [
"c#",
"error-handling",
"rest",
"controller",
"asp.net-web-api"
],
"Title": "ASP.NET REST controller with try-catch error handling"
} | 197476 |
<p>This code needs to get two inputs: </p>
<ul>
<li>one is the full address of a directory</li>
<li>and another the file extension that it will be changed. </li>
</ul>
<p>These inputs cab be added in the default section of <code>parser.add_argument</code> as in the example. It will overwrite the files with the new copyright:</p>
<pre><code>import csv
import argparse
import os
class change_logo(object):
def __init__(self, key):
self.keyword = key
self.case = 1
self.counter1 = 0
self.counter2 = 0
self.counter3 = 0
def read_line(self, key):
with open(key, 'rb') as f:
reader = csv.reader(f, delimiter=',')
lista = []
s_index = -2
for row in reader:
lista.append(row)
for index in range(0, len(lista)):
if any("# Copyright: (c) 2011 Comp1 Ltd. All Rights Reserved" in s for s in lista[index]):
s_index = index
self.counter1 = self.counter1+ 1
if any("# Copyright: (c) 2018 Comp2 Ltd. All Rights Reserved" in s for
s in lista[index]):
print("COPYRIGHT ALREADY EXISTS")
self.case = 2
self.counter2 = self.counter2 + 1
return s_index
if s_index == -2:
self.counter3 = self.counter3 + 1
print("NO COPYRIGHT IN THIS FILE")
else:
print(s_index + 1)
return s_index
def replace_copyright(self, key):
s_index = self.read_line(key)
if self.case == 2:
self.case = 1
return 0
if s_index != -2:
s = open(key).read()
s = s.replace('# Copyright: (c) 2011 Comp1 Ltd. All Rights Reserved',
'# Copyright: (c) 2018 Comp2 Ltd. All Rights Reserved')
f = open(key, 'w')
f.write(s)
f.close()
print("COPYRIGHT ADDED IN LINE %d OF THE FILE" % (s_index + 1))
else:
s = open(key).read()
f = open(key, 'w')
f.write('# Copyright: (c) 2018 Comp2 Ltd. All Rights Reserved' + '\n' + s)
f.close()
print("COPYRIGHT ADDED IN THE BEGINNING OF THE FILE")
# This class returns a list of addresses
class file_traverser(object):
# The user sends the path address and file extension that wants changed
def __init__(self, key):
self.path = key[0]
self.file_extension = key[1]
def file_walker(self):
directory = []
# Iterate through all file paths and append the list
for root, dirs, files in os.walk(self.path):
for file_ in files:
if self.file_extension in os.path.join(root, file_):
directory.append(os.path.join(root, file_))
return directory
# This method parses user's arguments from cmd prompt
def parser_arg():
parser = argparse.ArgumentParser('--help')
parser.add_argument(
"--path", nargs="+",
help="Give a valid directory path and a fileextension to be scanned and changed",
default=['C:\Users', ".py"] # put a directory path and also you can change the extension to .csv or anything else
)
args = parser.parse_args()
path = args.path
return path
if __name__ == '__main__':
counter = 0
counter1, counter2, counter3 = 0, 0, 0
test1 = file_traverser(parser_arg())
files = test1.file_walker()
for index in range(0, len(files)):
try:
print(files[index])
test = change_logo(files[index])
test.replace_copyright(files[index])
counter = counter + 1
counter1 = counter1 + test.counter1
counter2 = counter2 + test.counter2
counter3 = counter3 + test.counter3
except Exception:
index = index + 1
print ("number of files read : %d" % counter)
print ("number of files replaced with the new COPYRIGHT : %d" % counter1)
print ("number of files that COPYRIGHT ALREADY EXISTS : %d" % counter2)
print ("number of files that NO COPYRIGHT EXISTS : %d" % counter3)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T09:58:11.430",
"Id": "197480",
"Score": "3",
"Tags": [
"python",
"python-2.x",
"text-editor"
],
"Title": "code for changing from old copyright to a new one in python"
} | 197480 |
<p>I am relatively new to redux - I wanted to keep the actions in the same detectJsCamera function which is why I decided to resolve a promise to detectCamera - hence the set timeout.</p>
<p>I am not sure how I would go about testing this.</p>
<pre><code>xport function detectJsCamera() {
return async(dispatch) => {
dispatch({type: types.JS_DETECTING_CAMERA});
try {
await detectCamera();
await dispatch({type: types.JS_CAMERA_DETECTED});
} catch (error) {
throw error;
// this.props.history.push('/setup/positioning')
};
}
}
const detectCamera = () => new Promise((resolve, reject) => {
const checkIfReady = () => {
if (webgazer.isReady()) {
resolve('success');
} else {
setTimeout(checkIfReady, 100);
}
}
setTimeout(checkIfReady,100);
});
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T10:57:44.353",
"Id": "197484",
"Score": "1",
"Tags": [
"javascript",
"redux"
],
"Title": "Dispatches an event to detect a camera - Once the camera has initialised resolve a promise to say the camera is detected"
} | 197484 |
<p>I'm currently trying to implement the singleton pattern in C++. After reading about it for a while now, it seems like there are a really large amount of different ways to do this. </p>
<p>Is the way I ended up doing it correct or did I miss out on something important here? Is this implementation thread safe in modern C++ (I read there were some changes to that in particular with C++11)? In addition I am not sure at all about the way I am accessing the class within <code>MyFunction()</code>. </p>
<p>Is it really necessary to use a raw pointer there? Does this code contain any memory leaks?</p>
<pre><code>#include <iostream>
class Singleton
{
private:
Singleton();
~Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
void Test();
};
void Singleton::Test()
{
std::cout << "Test() called" << std::endl;
}
Singleton::Singleton()
{
std::cout << "CONSTRUCTOR CALLED" << std::endl;
}
Singleton::~Singleton()
{
std::cout << "DESTRUCTOR CALLED" << std::endl;
}
void MyFunction()
{
// use the singleton class
Singleton * MySingleton = &Singleton::instance();
MySingleton->Test();
}
int main()
{
MyFunction();
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T12:40:33.973",
"Id": "380708",
"Score": "2",
"body": "I'd disable copyctor and `=` so that you won't accidentally copy the object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T12:41:42.030",
"I... | [
{
"body": "<h1>Thread safety</h1>\n<p>Accessing the singleton is thread-safe. The change in C++11 has forced compilers to implement the construction of local <code>static</code> variables (like <code>INSTANCE</code>) in a thread-safe manner.</p>\n<p>Note, however, that this doesn't make <code>Singleton</code> t... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T11:12:58.887",
"Id": "197486",
"Score": "5",
"Tags": [
"c++",
"c++11",
"singleton"
],
"Title": "Singleton class and correct way to access it in C++"
} | 197486 |
<p>Yesterday, I very quickly, in an hour, wrote the very first version of my long-term archiving + encrypting shell script.</p>
<p>I am aware it may have too many flaws, but none of them really prevent it from normal operation, so before I take another step and restructure it with <code>printf</code> and better error reporting, structure, exit codes, etc. I would like you to have a look first.</p>
<p>What it does:</p>
<ol>
<li>It archives a given directory into a tarball.</li>
<li>It compresses (with maximum effort) that tarball using <code>xz</code>.</li>
<li>It encrypts that <code>xz</code> archive using <code>openssl</code> and AES-256.</li>
<li>It creates and checks the created SHA-512 sum file.</li>
<li>It then decrypts the created file to a temporary file.</li>
<li>Finally, it compares the decrypted file with the original <code>xz</code> archive.</li>
</ol>
<p>I am prepared to waste time and effort in order to be 100% sure before burning my precious data to Blu-ray M-disc.</p>
<p>I know I should not have to do steps 5 and 6 just because there is almost a 0% chance for the data to get corrupted in the process. But since I have a rather large NVMe SSD drive, and relatively fast CPU, it should not be so shocking that I wrote it with motto <em>better safe than sorry</em>.</p>
<pre><code>#!/bin/sh
[ -z "$1" ] && echo "You need to give me one directory!" && exit 1
[ ! -d "$1" ] && echo "This is not a directory!" && exit 1
[ ! -w "$PWD" ] && echo "The current directory is not writable by you!" && exit 1
dir=$(basename "$1")
today=$(date +%Y-%m-%d)
backupdir="${dir}_${today}"
# backupdir="${dir}"
backupfile="${backupdir}.tar"
bold=$(tput bold)
red=$(tput setaf 1)
yellow=$(tput setaf 3)
nocolor=$(tput sgr0)
bold_red="$bold$red"
bold_yellow="$bold$yellow"
echo
echo "${bold_yellow}1/6: TAR is archiving your directory '${bold_red}$dir${bold_yellow}' into '${bold_red}$backupfile${bold_yellow}'${nocolor}"
echo
if ! tar -cf "$backupfile" "$1" --totals
then
echo "TAR failed to archive your directory"
exit 1
fi
echo
echo "${bold_yellow}2/6: XZ is compressing your '${bold_red}$backupfile${bold_yellow}' into '${bold_red}$backupfile.xz${bold_yellow}'${nocolor}"
echo
if ! xz --format=xz --check=sha256 -9 --threads=8 --keep --verbose --verbose --extreme "$backupfile"
then
echo "XZ failed to compress your backup file"
exit 1
fi
echo
echo "${bold_yellow}3/6: OpenSSL is encrypting your '${bold_red}$backupfile.xz${bold_yellow}' into '${bold_red}$backupfile.xz.enc${bold_yellow}'${nocolor}"
echo
if ! pv -W "$backupfile.xz" | openssl enc -aes-256-cbc -md sha256 -salt -out "$backupfile.xz.enc" -pass file:/home/vlastimil/.blablablabla 2> /dev/null
then
echo "OpenSSL failed to encrypt your compressed file"
exit 1
fi
echo
echo "${bold_yellow}4/6: sha512sum is creating hash file '${bold_red}$backupfile.xz.enc.SHA512SUM${bold_yellow}'${nocolor}"
echo
if ! sha512sum -b "$backupfile.xz.enc" > "$backupfile.xz.enc.SHA512SUM"
then
echo "sha512sum failed to compute hashsum file"
exit 1
fi
sha512sum -c "$backupfile.xz.enc.SHA512SUM"
echo
echo "${bold_yellow}5/6: Decrypting your '${bold_red}$backupfile.xz.enc${bold_yellow}' into a temporary file '${bold_red}$backupfile.xz.dec${bold_yellow}'${nocolor}"
echo
if ! pv -W "$backupfile.xz.enc" | openssl enc -aes-256-cbc -md sha256 -salt -out "$backupfile.xz.dec" -d -pass file:/home/vlastimil/.blablablabla 2> /dev/null
then
echo "OpenSSL failed to decrypt your encrypted file"
exit 1
fi
echo
echo "${bold_yellow}6/6: Comparing your un-encrypted, compressed, archived, directory file '${bold_red}$backupfile.xz${bold_yellow}' with a temporary file '${bold_red}$backupfile.xz.dec${bold_yellow}'${nocolor}"
echo
if ! cmp "$backupfile.xz" "$backupfile.xz.dec"
then
echo "Failed to compare files"
exit 1
else
echo "Your directory '${bold_red}$dir${nocolor}' has been successfully stored as '${bold_red}$backupfile.xz.enc${nocolor}'"
rm "$backupfile.xz.dec"
rm "$backupfile.xz"
rm "$backupfile"
fi
</code></pre>
| [] | [
{
"body": "<p>It's a fine script. Even <a href=\"https://www.shellcheck.net/#\" rel=\"nofollow noreferrer\">shellcheck</a> doesn't find anything in it. Well done!</p>\n\n<p>I only have minor comments.</p>\n\n<p>You can safely omit the <code>sha512sum -c</code>.\nIt would only fail if the previous command failed... | {
"AcceptedAnswerId": "197516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T13:10:30.137",
"Id": "197490",
"Score": "1",
"Tags": [
"linux",
"aes",
"sh",
"posix",
"openssl"
],
"Title": "Long-term archiving + encrypting shell script"
} | 197490 |
<p>Here I have implemented code for Round Robin CPU Scheduling Algorithm. scheduling.h header file is also used in Shortest Job First Scheduling Algorithm and Priority Scheduling Algorithm, so it contains common data members and member functions.</p>
<p>First I have calculated end time in <code>calcEndTime()</code> then using formula <code>turnAroundTime = endTime - arrivalTime</code> calculated Turnaround time and using <code>waitingTime = turnAroundTime - burstTime</code> calculated Waiting time.</p>
<p>Please help me to improve and optimize this code using more C++11 and C++14 features.</p>
<p>scheduling.h</p>
<pre><code>#ifndef SCHEDULING_H_
#define SCHEDULING_H_
#include <vector>
class Scheduling
{
uint currActiveProcessID;
uint timeCounter = 0;
double avgWaitingTime;
double avgTurnAroundTime;
std::vector<unsigned> arrivalTime;
//When process start to execute
std::vector<unsigned> burstTime;
//process wait to execute after they have arrived
std::vector<unsigned> waitingTime;
//total time taken by processes
std::vector<unsigned> turnAroundTime;
//time when a process end
std::vector<unsigned> endTime;
public:
Scheduling(unsigned num = 0);
Scheduling(const Scheduling&) = delete;
Scheduling &operator=(const Scheduling&) = delete;
Scheduling(Scheduling&&) = delete;
Scheduling &operator=(Scheduling&&) = delete;
~Scheduling() = default;
void calcWaitingTime();
void calcTurnAroundTime();
void calcEndTime();
void printInfo();
private:
void sortAccordingArrivalTime();
};
#endif
</code></pre>
<p>roundrobin.cpp</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm> // std::find
#include <iterator> // std::begin, std::end
#include <limits> //std::numeric_limits
#include "scheduling.h"
unsigned timeQuantum = 0;
Scheduling::Scheduling(unsigned num)
{
unsigned arrivalVal, burstVal;
currActiveProcessID = 0;
timeCounter = 0;
std::cout << "\nEnter time quantum : ";
std::cin >> timeQuantum;
arrivalTime.reserve(num);
burstTime.reserve(num);
endTime.reserve(num);
std::cout << "\nEnter arrival time and burst time eg(5 18)\n";
for (unsigned i = 0; i < num; i++)
{
std::cout << "\nProcess" << i+1 << ": ";
std::cin >> arrivalVal >> burstVal;
arrivalTime.push_back(arrivalVal);
burstTime.push_back(burstVal);
}
}
void Scheduling::sortAccordingArrivalTime()
{
for (std::size_t i = 0; i < arrivalTime.size(); i++)
{
for (std::size_t j = i+1; j < arrivalTime.size(); j++)
{
if (arrivalTime[i] > arrivalTime[j])
{
std::swap(arrivalTime[i], arrivalTime[j]);
std::swap(burstTime[i], burstTime[j]);
}
}
}
}
void Scheduling::calcEndTime()
{
//If arrival time is not sorted
//sort burst time according to arrival time
sortAccordingArrivalTime();
//copy values of burst time in new vector
std::vector<unsigned> burstTimeCopy;
std::copy(burstTime.begin(), burstTime.end(),
std::back_inserter(burstTimeCopy));
while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(),
[] (unsigned e) { return e == 0; })))
{
currActiveProcessID = 0;
auto it = burstTimeCopy.begin();
while (it != burstTimeCopy.end())
{
if (burstTimeCopy[currActiveProcessID] > timeQuantum)
{
burstTimeCopy[currActiveProcessID] -= timeQuantum;
timeCounter += timeQuantum;
}
else if (burstTimeCopy[currActiveProcessID] > 0)
{
timeCounter += burstTimeCopy[currActiveProcessID];
burstTimeCopy[currActiveProcessID] = 0;
endTime[currActiveProcessID] = timeCounter;
}
currActiveProcessID++;
it++;
}
}
}
void Scheduling::calcTurnAroundTime()
{
double sum = 0.00;
for (std::size_t i = 0; i < arrivalTime.size(); i++)
{
unsigned val = endTime[i] - arrivalTime[i];
turnAroundTime.push_back(val);
sum += (double)val;
}
avgTurnAroundTime = sum / turnAroundTime.size();
}
void Scheduling::calcWaitingTime()
{
double sum = 0.00;
for (std::size_t i = 0; i < burstTime.size(); i++)
{
unsigned val = turnAroundTime[i] - burstTime[i];
waitingTime.push_back(val);
sum += (double)val;
}
avgWaitingTime = sum / waitingTime.size();
}
void Scheduling::printInfo()
{
std::cout << "ProcessID\tArrival Time\tBurst Time\tEnd Time\tWaiting Time";
std::cout << "\tTurnaround Time\n";
for (std::size_t i = 0; i < arrivalTime.size(); i++)
{
std::cout << i+1 << "\t\t" << arrivalTime[i] << "\t\t" << burstTime[i];
std::cout << "\t\t"<<endTime[i] << "\t\t" << waitingTime[i] <<"\t\t";
std::cout << turnAroundTime[i] <<'\n';
}
std::cout << "Average Waiting Time : " << avgWaitingTime << '\n';
std::cout << "Average Turn Around Time : " << avgTurnAroundTime << '\n';
}
int main()
{
int num;
std::cout << "Enter number of process: ";
std::cin >> num;
Scheduling roundRobin(num);
roundRobin.calcEndTime();
roundRobin.calcTurnAroundTime();
roundRobin.calcWaitingTime();
roundRobin.printInfo();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T16:47:54.403",
"Id": "380739",
"Score": "0",
"body": "There's no definition for `uint`. Was this intended to be `unsigned`, or is the definition missing entirely (e.g. by missing an `#include`)?"
},
{
"ContentLicense": "CC B... | [
{
"body": "<p>Where does the <code>uint</code> type come from?</p>\n\n<p>The <code>currActiveProcessID</code> member of <code>Scheduling</code> can be removed from the class, as it is only used internally to <code>calcEndTime()</code>.</p>\n\n<p><code>timeQuantum</code> should be entered in <code>main</code> (o... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T15:52:32.487",
"Id": "197498",
"Score": "1",
"Tags": [
"c++",
"c++11"
],
"Title": "Round Robin Scheduling Algorithm"
} | 197498 |
<p>I've just started with Java. The code below calculates Body Mass Index (BMI).</p>
<p>Could someone look for my code and assess it? Maybe I should write something more? All advice will be very helpful.</p>
<pre><code>import java.util.Scanner;
public class BMI {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double weight = 0;
double height = 0;
double bmi = 0;
System.out.println("Please enter your details to calculate your Body Mass Index.");
System.out.println("Enter your weight in kilograms:");
weight = scanner.nextDouble();
System.out.println("Enter your height in metres:");
height = scanner.nextDouble();
bmi = (weight / (height * height));
System.out.println("Your BMI is: " + bmi);
if (bmi >= 40) {
System.out.println("Serious obesity");
} else if (bmi >= 30) {
System.out.println("Obesity");
} else if (bmi >= 25) {
System.out.println("Overweight");
} else if (bmi >= 18) {
System.out.println("Standard");
} else {
System.out.println("Underweight");
}
scanner.close();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T16:44:00.343",
"Id": "380734",
"Score": "1",
"body": "You definitely should write more. Please [edit] your question and tell us what this assesment is about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-... | [
{
"body": "<p>Because this is such a simple program, there are really only a few basic things that can make it good or bad (beyond the fact that it actually works). </p>\n\n<p>The good:</p>\n\n<ul>\n<li><strong>Formatting</strong> - this is all consistent, and matches the standard Java formatting</li>\n<li><str... | {
"AcceptedAnswerId": "197506",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T16:32:25.600",
"Id": "197501",
"Score": "1",
"Tags": [
"java",
"beginner",
"calculator"
],
"Title": "BMI calculator/assessor"
} | 197501 |
<p>For a project, I need to write a basic template manager who will be responsible to load the requested HTML or PHP template when the user clicks on a menù link. It's like a page loader since that all the loaded templates are static HTML pages. I want to improve it if is it possible. Here is the code.</p>
<p>on the main index of the project I have a jQuery code like this:</p>
<pre><code><script>
$(document).ready(function(){
$('.contents').load('templates/home.php');
$(document).on('click','a',function(e){
e.preventDefault();
$('#nav-modal').modal('hide');
var url = $(this).attr('href');
if(url == 'booking/'){
window.location.href= 'booking/';
} else {
$.ajax({
type: 'GET',
url: 'templates/TemplateController.php'+url,
cache: false,
dataType: 'html',
success: function(response){
$('.contents').empty()
.html(response);
}
});
}
});
});
</script>
</code></pre>
<p>on the PHP 'controller' side I have this code who will only call a class to obtain the needed files. The URL passed from <code>AJAX</code> to the controller is something like this: <code>?tpl=atemplate</code></p>
<pre><code><?php
require_once 'Autoloader.php';
if(isset($_GET['tpl'])){
$tpl = new TemplateLoader;
echo $tpl->render($_GET['tpl']);
}
?>
</code></pre>
<p>And then in the simple class, I have only a <code>switch</code> control that will select what is the requested template to load on the index</p>
<pre><code><?php
class TemplateLoader{
public function __construct(){
#$this->path = $path;
}
public function render($tpl){
switch($tpl){
case 'home':
echo file_get_contents('home.php');
break;
case 'about':
echo file_get_contents('about.php');
break;
case 'services':
echo file_get_contents('services.php');
break;
case 'contacts':
echo file_get_contents('contacts.php');
break;
case 'prices':
echo file_get_contents('prices.php');
break;
}
}
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T04:37:54.697",
"Id": "380803",
"Score": "0",
"body": "Instead of using `jQuery.ajax()` for your requests, you should consider the benefits of the fetch API. Importantly, fetch works asynchronously and it also won't reject on HTTP er... | [
{
"body": "<h1>Technical mistakes</h1>\n\n<h3>echo void</h3>\n\n<pre><code>echo $tpl->render($_GET['tpl']);\n</code></pre>\n\n<p>This echo will display empty string (null), because you've already output a string with echo within method and have void return type (implicit <code>return null</code>). Make <code... | {
"AcceptedAnswerId": "197533",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T16:36:22.610",
"Id": "197502",
"Score": "2",
"Tags": [
"php",
"template",
"ajax"
],
"Title": "Basic PHP template loader"
} | 197502 |
<p>I'm relatively new to Go, which is why I decided to post some code here. My goal is to en-/decode a TCP stream. The individual data packets length-based. The first two bytes are the unsigned size in little-endian byte order. The size includes the size field itself. The methods I wrote seem to en-/decode the packets as expected.</p>
<p>Is there a more efficient way to achieve this?
Does Go perhaps already implement such methods somewhere.</p>
<hr>
<pre><code>func GetPacketByLength(source io.Reader) ([]byte, error) {
s := make([]byte, 2)
if _, err := io.ReadFull(source, s); err != nil {
return nil, err
}
// Little-endian uint16
size := uint16(s[0]) | uint16(s[1])<<8 - 2
p := make([]byte, size)
if _, err := io.ReadFull(source, p); err != nil {
return nil, err
}
return p, nil
}
func PutPacketByLength(target io.Writer, p []byte) error {
s := make([]byte, 2)
// Little-endian uint16
s[0] = byte((len(p) + 2))
s[1] = byte((len(p) + 2) >> 8)
if _, err := target.Write(s); err != nil {
return err
}
if _, err := target.Write(p); err != nil {
return err
}
return nil
}
</code></pre>
| [] | [
{
"body": "<p>You may consider to use <a href=\"https://golang.org/pkg/encoding/binary/#Read\" rel=\"nofollow noreferrer\"><code>binary.Read</code></a>. I find this more readable and self documented. See <a href=\"https://play.golang.org/p/6v_sjL4M6-h\" rel=\"nofollow noreferrer\">this example</a>.</p>\n\n<pre>... | {
"AcceptedAnswerId": "197507",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T17:25:42.017",
"Id": "197504",
"Score": "4",
"Tags": [
"performance",
"io",
"go"
],
"Title": "Length-Based Frame Stream En-/Decoding in Go"
} | 197504 |
<p>Using Qt, I've got this code in order to protect access to some shared data between threads. I'm pretty sure the idea is correct, but I don't know if RVO and/or RAII could potentially screw the <code>get</code> function. I'm much more used to C and while I understand the idea, I'm not totally familiar with all the "gotchas" for these two concepts.</p>
<pre><code>class DataManager {
Q_OBJECT
private:
QVector<DataType> data;
QReadWriteLock* rwLock;
public:
DataManager() {
rwLock = new QReadWriteLock();
}
~DataManager() {
delete rwLock;
}
Q_DISABLE_COPY(DataManager)
QVector<DataType> getData() {
QReadWriteLocker lock(rwLock);
return data;
}
QVector<DataType>* beginModifyData() {
rwLock->lockForWrite();
return &data;
}
void endModifyData() {
rwLock->unlock();
emit dataChanged();
}
signals:
void dataChanged();
};
</code></pre>
<p>In the <code>get</code> function, is it possible that the RAII-type class <code>QReadWriteLocker</code> unlocks the lock before the return copy is made? Thus allowing some thread, that was waiting to write, to overwrite the data being returned.</p>
<p>Also, if somebody writes</p>
<pre><code>QVector<DataType>& myData = dataManager->getData();
</code></pre>
<p>Is it possible, due to RVO, that they get a reference to the <em>actual</em> data?</p>
<p>Also, I'd like to receive comments on the code and idea itself. Below I've outlined the reasons why I chose this approach.</p>
<ol>
<li>Simple to use. Since one can only read a copy of the data, they don't have to worry about synchronization and locking.</li>
<li>Taking advantage of the implicit sharing of Qt containers, no <em>actual</em> copies will ever be made when using <code>getData()</code>, thus making read-only access very fast.</li>
<li>Since, when modifying the data, one gets a pointer to the actual data, again, in most cases, no copies will be made, unless some thread is caching the data (or one of the copies has not yet gone out of scope of whatever got it).</li>
<li>Looking at the documentation and code, a non-recursive QReadWriteLock is ultra fast in the non-contended case, not doing any waiting or context-switching (uses atomic operations on an integer).</li>
<li>I could potentially do some data validation/fixup in the <code>endModifyData</code> function if needed.</li>
</ol>
<p>Thanks.</p>
| [] | [
{
"body": "<h1>Locking</h1>\n<p>Let's see what these member functions actually do, and what can go wrong:</p>\n<h3><code>getData</code></h3>\n<p>The lock acquired in <code>getData</code> basically only ensures that nobody is currently modifying <code>data</code> while inside. As soon as the caller gets the retu... | {
"AcceptedAnswerId": "197519",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T19:05:25.430",
"Id": "197511",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"concurrency",
"qt"
],
"Title": "Concurrent access to data with QReadWriteLock"
} | 197511 |
<p>Here is my code:</p>
<pre><code>import sys
import math
def dist(a,b):
return math.hypot((b[0]-a[0]),(b[1]-a[1]))
def minimum_distance(x, y):
points = list(zip(x,y))
points_y = sorted(points, key= lambda z:z[1])
points.sort(key=lambda g:g[0])
return min_dist(points,points_y)
def min_dist(points,points_y):
if len(points)==2: return dist(points[0],points[1])
elif len(points)==3: return min(dist(points[0],points[1]),dist(points[0],points[2]),dist(points[1],points[2]))
ave = (len(points)+1)//2
yleft = [t for t in points_y if t[0]<=points[ave-1][0]]
yright = [q for q in points_y if q[0]>=points[ave][0]]
d1 = min_dist(points[0:ave],yleft)
d2 = min_dist(points[ave:len(points)],yright)
d = min(d1,d2)
arr_split = [point for point in points_y if abs(point[0]- points[ave][0]) <= d]
d_=2*(10**18)
for i in range(len(arr_split)-1):
for j in range(i+1,min(len(arr_split),i+7)):
temp = dist(arr_split[i],arr_split[j])
if temp<d_:d_=temp
return min(d,d_)
</code></pre>
<p>Example input:([2,5,1],[3,6,2]) and output is \$ \sqrt 2 \$ since (2,3) and (1,2) are the closest points. The input arrays to minimum_distance are the x and y values of each point respectively and the inputs to min_dist are the points sorted based on their x values and y values respectively. </p>
<p>I have implemented pre-sort and have used computational geometric theory (comparison between 7 points only in the strip) to make the time complexity \$ O(n \log n) \$ and my code works swiftly and correctly for most test cases. However, for some hidden test cases generated by Coursera, my code is taking more than 20 seconds. Any optimisations/ corrections?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T19:43:42.953",
"Id": "380767",
"Score": "0",
"body": "Can you provide an example input and output -- from my understanding of the problem you could easily come up with an O(n) solution."
},
{
"ContentLicense": "CC BY-SA 4.0"... | [
{
"body": "<h3>Coding style</h3>\n\n<p>Your code is difficult to read because it is written very condensed.</p>\n\n<p>There is a well-established coding style for Python, the \n<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 coding style</a>,\nand conformance to that style... | {
"AcceptedAnswerId": "197560",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T19:10:00.560",
"Id": "197512",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"computational-geometry",
"clustering"
],
"Title": "Finding the distance between the two closest points in a 2-D plane"
} | 197512 |
<p>Since the previous question I posted here was not found as interesting as I expected, I decided to post a new one. I made a function solely for the purpose of having fun. That is, a function that checks if two strings are similar with a given %.</p>
<pre><code>int case_insensitive_chrcmp (int ch1, int ch2)
{
return ch1 == ch2 || ch1 + ' ' == ch2 || ch1 - ' ' == ch2;
}
int strpcmp (char* str1, char* str2, unsigned setting)
{
int szStr1 = strlen(str1);
int szStr2 = strlen(str2);
int szMax = max(szStr1, szStr2);
int szMin = 0;
int chars = 0;
if(setting > 100)
setting = 100;
if(szStr1 == szMax)
szMin = szStr2;
else szMin = szStr1;
chars = szMax * setting / 100;
int cur = 0;
for(int i = 0; i < szMin; i++)
{
if(case_insensitive_chrcmp(str1[i], str2[i]))
cur++;
else cur = 0;
if(cur >= chars)
return 1;
}
return 0;
}
</code></pre>
<p>(you may need to provide your own definition for <code>min</code> and <code>max</code> since I think they are not supported by all compilers)</p>
<hr>
<p>Example usage:</p>
<pre><code>char* str1 = "Hello";
char* str2 = "Hey";
int percentage = 50%101; // or just 50 or w/e
printf("%s %i%% %s - %s\n", str1, percentage, str2, strpcmp(str1, str2, percentage) ? "true" : "false");
</code></pre>
<p>Output:</p>
<blockquote>
<p>Hello 50% Hey - true</p>
<hr>
</blockquote>
<h2>More info on what the function is supposed to do:</h2>
<p>It calculates how many characters must match consecutively based on percentage in order to return true. The comparison between characters is also done in case insensitive manner.</p>
<h2>More info on how the function is required to work:</h2>
<p>Regarding safety, this function can do much more, check
against null pointers, re-entrancy guarding, MT-safety and that shouldn't really damage the performance level.
Speaking of performance, I am a performancecholic and the first thing I can see that is bothering me here is the two <code>strlens</code> - the size of the two strings can be obtained within a single loop. Otherwise there are redundant iterations.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T12:53:09.470",
"Id": "380835",
"Score": "1",
"body": "You probably want to use [edit distance](https://en.wikipedia.org/wiki/Edit_distance) instead."
}
] | [
{
"body": "<p>Alright I have a hole in my schedule, so I will give it a review myself.</p>\n\n<hr>\n\n<h2>Let's start with the function <code>case_insensitive_chrcmp</code></h2>\n\n<ol>\n<li><p>The name mixes two standards for function name, the well-descriptive, but long snake_case and the less descriptive but... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T20:05:37.783",
"Id": "197517",
"Score": "4",
"Tags": [
"c",
"strings",
"edit-distance"
],
"Title": "Function to check whether two strings are similar at given %"
} | 197517 |
<p>I've written a script in scrapy to grab different <code>names</code> and <code>links</code> from different pages of a website and write those parsed items in a csv file. When I run my script, I get the results accordingly and find a data filled in csv file. I'm using python 3.5, so when I use scrapy's built-in command to write data in a csv file, I do get a csv file with blank lines in every alternate row. Eventually, I tried the below way to achieve the flawless output (with no blank lines in between). Now, It produces a csv file fixing blank line issues. I hope I did it in the right way. However, if there is anything I can/should do to make it more robust, I'm happy to cope with.</p>
<p>This is my script which provides me with a flawless output in a csv file:</p>
<pre><code>import scrapy ,csv
from scrapy.crawler import CrawlerProcess
class GetInfoSpider(scrapy.Spider):
name = "infrarail"
start_urls= ['http://www.infrarail.com/2018/exhibitor-profile/?e={}'.format(page) for page in range(65,70)]
def __init__(self):
self.infile = open("output.csv","w",newline="")
def parse(self, response):
for q in response.css("article.contentslim"):
name = q.css("h1::text").extract_first()
link = q.css("p a::attr(href)").extract_first()
yield {'Name':name,'Link':link}
writer = csv.writer(self.infile)
writer.writerow([name,link])
c = CrawlerProcess({
'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(GetInfoSpider)
c.start()
</code></pre>
<p>Btw, I used <code>.CrawlerProcess()</code> to be able to run my spider from sublime text editor.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T08:00:43.543",
"Id": "380810",
"Score": "0",
"body": "Welcome to Code Review! That's quite a well-written question, especially for a new user. Well done."
}
] | [
{
"body": "<p>I'd like to mention, that there is a special way of making output files in scrapy - <a href=\"https://doc.scrapy.org/en/latest/topics/item-pipeline.html\" rel=\"nofollow noreferrer\">item pipelines</a>. So, in order to make it right, you should write your own pipeline (or modify standard one via s... | {
"AcceptedAnswerId": "197546",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T20:06:31.387",
"Id": "197518",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"csv",
"web-scraping",
"scrapy"
],
"Title": "Writing to a csv file in a customized way using scrapy"
} | 197518 |
<p>I just started coding programs with python. As a challenge I wanted to program something to print out the Fibonacci Numbers. It looks like I've done what I wanted to do (I checked the first few numbers) and because I just started coding, I obviously don't know if this is a legitimate code and somebody would code it like that. Keep in mind that I have only done some basic lessons in python so I just want to get some feedback and advice for better code. </p>
<pre><code>def spiral(sequence):
numbers = []
for i in sequence:
numbers.append(0)
if i == 0 or i == 1:
numbers[i] = 1
continue
numbers[i] = numbers[i-1] + numbers[i-2]
return numbers
times = range(int(input("How many times do you want to go through? ")))
fibonacci = spiral(times)
print(fibonacci)
</code></pre>
| [] | [
{
"body": "<p>The way <code>sequence</code> is used guarantees that the results will be wrong for the majority of inputs. It's clearly intended that <code>sequence</code> should be a continuous range starting at <code>0</code>. So rather than require the range as input, it would make more sense to require the l... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T20:37:20.523",
"Id": "197522",
"Score": "1",
"Tags": [
"python",
"beginner",
"fibonacci-sequence"
],
"Title": "Display Fibonacci numbers"
} | 197522 |
<p>This is short Angular 5 code which works as intended: check boxes behave like radio buttons - only one can be selected at a time.</p>
<p>Both versions of 'toggleCheckbox' works but I am interested is if there is better, more elegant way to set 'checkbox1' and 'checkbox2'?</p>
<p>template-driven-form.component.ts</p>
<pre><code>import {Component, OnInit} from '@angular/core';
import {User} from './domain/user';
@Component({
selector: 'app-template',
templateUrl: './template-driven-form.component.html',
styleUrls: ['./style.css']
})
export class TemplateDrivenFormComponent implements OnInit {
user = new User();
ngOnInit() {
this.setDefaultValues();
}
constructor() {
}
// toggleCheckbox(event) {
// if (event.target.id === 'checkbox1') {
// this.user.checkbox1 = true;
// this.user.checkbox2 = false;
// } else {
// this.user.checkbox1 = false;
// this.user.checkbox2 = true;
// }
// }
toggleCheckbox(event) {
event.target.id === 'checkbox1' ? (this.user.checkbox1 = true, this.user.checkbox2 = false)
: (this.user.checkbox2 = true, this.user.checkbox1 = false);
}
setDefaultValues() {
this.user.checkbox1 = true;
this.user.checkbox2 = false;
}
}
</code></pre>
<p>template-driven-form.component.html</p>
<pre><code><h3>Template Driven Form</h3>
<table>
<tr>
<td>
<label for="checkbox1">Label 1</label><input type="checkbox" id="checkbox1" name="checkbox1" [ngModel]="user.checkbox1" (change)="toggleCheckbox($event)" [checked]="user.checkbox1">
</td>
</tr>
<tr>
<td>
<label for="checkbox2">Label 2</label><input type="checkbox" id="checkbox2" name="checkbox2" [ngModel]="user.checkbox2" (change)="toggleCheckbox($event)" [checked]="user.checkbox2">
</td>
</tr>
</table>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T21:26:53.750",
"Id": "197523",
"Score": "1",
"Tags": [
"form",
"typescript",
"angular-2+"
],
"Title": "Checkboxes behave like radio buttons with angular"
} | 197523 |
<p>I am using Java to create an Android app. I have the main activity read a CSV file, create objects, and then save them into a singleton class so the rest of the activities in the app can access them easily.</p>
<p>This is working perfectly fine but I am not sure if there are some other ways to achieve the same result that are considered better practice, or if perhaps my solution could cause issues down the line that I am not aware of.</p>
<p>MainActivity extends AppCompatActivity </p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createItemObjects();
}
public void createItemObjects(){
InputStream is = getResources().openRawResource(R.raw.items_csv);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
ArrayList<Item> items = new ArrayList<Item>();
String line = "";
try {
while((line = reader.readLine())!=null) {
String[] values = line.split(",");
String img = values[0];
int imgID = getResources().getIdentifier(img , "drawable", getPackageName());
items.add(new Item(imgID, values[1], values[2]));
}
} catch (IOException e) {
Log.v("Main Activity", "Error Reading File on Line " + line, e);
e.printStackTrace();
}
ItemListHolder.getInstance().setItemsArrayList(items);
}
</code></pre>
<p>So as you can see, when the app launches it reads the CSV file, creates <code>Item</code> objects, creates an <code>ArrayList</code> to store those <code>Item</code> objects, then sends it into the <code>ItemListHolder</code> singleton, so that all the Activities in the app can use <code>ItemListHolder.getInstance().getItemsArrayList()</code> to retrieve the <code>ArrayList</code> of <code>Item</code>. Each <code>Item</code> is constructed with an image ID, name, and description from a line in the CSV file.</p>
<p>This works without any issues, but my question is: Is having your Android app create objects from a CSV file everytime it restarts considered good practice/safe to use/efficient ect, or should you be storing your objects in some other way, such as shared preferences, so that they are actually saved in memory and do not need to be created everytime the app launches and then held inside a class.</p>
<p>I am familiar with Java but am very new to Android so I really have no idea what other ways of saving objects may or may not exist, or what is considered good to use. Is it better to save them to the fileOutputStream? Is it better to save them to sharedPreferences? Is there some other storage method that is better?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T00:07:57.933",
"Id": "380794",
"Score": "0",
"body": "Just changes the title so it clearly state what this code accomplishes. For the Item class, the second argument is a string that gets assigned to an instance variable called name... | [
{
"body": "<p>People from Android have a really comprehensive documentation about it at <a href=\"https://developer.android.com/guide/topics/data/data-storage\" rel=\"nofollow noreferrer\">https://developer.android.com/guide/topics/data/data-storage</a>.</p>\n\n<p>Short answer: yes, there are better ways: Share... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T21:39:22.867",
"Id": "197525",
"Score": "4",
"Tags": [
"java",
"android",
"csv"
],
"Title": "Initializing an Android activity by reading a CSV file with image IDs, names, and descriptions"
} | 197525 |
<p>For a Seesaw (Swing) app I'm writing, I need to be able to flash a component for a certain duration. Here's the basic function I came up with that accomplishes this:</p>
<pre><code>; Note, this isn't what I want reviewed. See below.
(defn flash-property [component prop-key flash-value duration]
(let [old-value (sc/config component prop-key)]
(sc/config! component prop-key flash-value)
(sc/timer (fn [_]
(sc/config! component prop-key old-value))
:initial-delay duration, :repeats? false)))
</code></pre>
<p>It reads the current property value into <code>old-value</code>, sets the new value, then in a timer reverts the old value after <code>duration</code> many milliseconds. If I wanted to create a button that flashes for half a second when pressed, I could write:</p>
<pre><code>(let [btn (sc/button :text "Button")]
(sc/listen btn
:action (fn [_] (flash-property btn :background :red 500)))
btn)
</code></pre>
<p>I had a problem that if you start a new flash before the old one has finished, <code>old-value</code> becomes the flash color from the previous flash, and the component gets stuck as the flash color.</p>
<p>To get around this, I had to rely on a "static variable" that keeps track of what is currently being flashed. I tried to extract as much as I could out of the decider function, but I'm still unhappy with it. The atom, while in a restricted scope, still feels like a hack to cover up a bad design. I've never used a <code>let</code> at the top level before, and it feels kind of dirty.</p>
<p>Of course, I could create some kind of a "flash handler" that gets passed back and forth and keeps track of what's being flashed, but that would be it's own flavour of mess. Then the caller would need to maintain it somehow. Considering the flash gets triggered in a button handler, I'd probably have to maintain an atom there anyways.</p>
<p>Can anyone see how to cleanly avoid the "static variable" <code>flashing?-atom</code>?</p>
<pre><code>(ns pet-redo.full-ui.helpers
(:require [seesaw.core :as sc]))
(defn flash-property
"Alters the property at prop-key to flash-value for duration-many milliseconds,
then reverts the property back to the original value.
Will break if a new flash is started before a previous one ends."
[component prop-key flash-value duration component-done-callback]
(let [old-value (sc/config component prop-key)]
(sc/config! component prop-key flash-value)
(sc/timer (fn [_]
(sc/config! component prop-key old-value)
(component-done-callback))
:initial-delay duration, :repeats? false)))
(let [flashing?-atom (atom #{})]
(defn maybe-flash-background!
"Alters the property at prop-key to flash-value for duration-many milliseconds,
then reverts the property back to the original value.
Does nothing if the element is already being flashed.
Returns whether or not a flash was triggered."
[component flash-color duration]
(when-not (@flashing?-atom component)
(swap! flashing?-atom conj component)
(flash-property component :background flash-color duration
#(swap! flashing?-atom disj component))
true)))
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T23:29:55.807",
"Id": "197528",
"Score": "1",
"Tags": [
"swing",
"animation",
"clojure"
],
"Title": "Cleanly preventing flashing an element from corrupting future flashes"
} | 197528 |
<p>Essentially the AJAX component of <a href="https://codereview.stackexchange.com/q/152699/127828">this question</a>, reimplemented in ES2017 style async/await. The code connects to a remote JSON API and scrapes it using a limited number of streams to avoid triggering rate limiting when the number of pages is large. Each stream retries on server-side errors and when rate limiting kicks in, up to 3 times by default. A rate limiting 429 response also results in a 5-second wait before further requests, increasing 50% each time up to 30 seconds. Other network errors result in a thrown error with a custom message.</p>
<pre><code>const Module = {};
Module.HttpError = class HttpError extends TypeError {
constructor(result = "Network Error", ...args) {
super(result, ...args);
this.message =
"Network access failed with status code " +
result.status + ": " + result.statusText +
" at " + result.url + ". Check your network connection.";
}
};
/**
* Local copy of a remote API endpoint.
*/
Module.Remote = class Remote {
constructor(path, query = {}) {
this.remote = new URL(path, "https://online-go.com/api/v1/");
this.remote.searchParams.set("format", "json");
for (let i of Object.keys(query))
this.remote.searchParams.set(i, query[i]);
this.meta = fetch(new URL("?page_size=1", this.remote))
.then(r=>{
if(r.ok) {
r.json();
} else {
throw new Module.HttpError(r);
}
});
}
/**
* Fetches everything from the API path specified, using a number of streams.
*
* @param {number=} maxStreams - number of simultaneous streams.
* @param {number=} pageSize - size of pages to fetch.
*
* @return {(Array<Object>|Object)} An array of pages
*/
async scrape(maxStreams = 5, pageSize = 100) {
const meta = await this.meta;
if ("count" in meta) { // Check number of pages from API metadata.
let target = this.remote;
target.searchParams.set("page_size", pageSize);
const numP = Math.ceil((meta.count)/pageSize);
let q = Array.from({length: numP}, (v, i) => i+1);
let pages = [];
let wait = 0;
/**
* Creates a stream that fetches pages from the shared queue,
* then saves the result to the array pages.
*
* @param {!URL} target - the URL and path of the remote.
* @param {number} page - the page number to fetch.
* @param {number=} retries - maximum number of retries before error.
* @return {number} zero on sucessful completion.
*/
async function stream (target, page, retries=3) {
if(wait) await sleep(5000*1.5**wait);
target.searchParams.set("page", page);
let result = await fetch(target);
if(result.ok) {
pages[page-1] = result.json();
// When queue is empty, return 0.
return q.length?stream(target, q.shift()):0;
} else if(result.status === 429 && retries) {
wait>4||(wait+=1/maxStreams); // Max wait = 5 or ~ 30 secs
console.warn("Too many requests! Backing off.");
return stream(target, page, retries-1);
} else if(500<=result.status && retries) {
console.warn("Server error, retrying");
return stream(target, page, retries-1);
} else {
throw new dvt.HttpError(result);
}
}
await Promise.all(Array.from({length: maxStreams}, v => stream(target, q.shift())));
console.info("Final wait level: " + wait);
this.pages = pages;
return this.pages;
} else {
return this.meta;
}
}
};
export default Module;
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T09:20:00.853",
"Id": "197543",
"Score": "1",
"Tags": [
"javascript",
"performance",
"web-scraping",
"concurrency",
"ajax"
],
"Title": "JSON API Scraper v2: Limited concurrency AJAX from a shared queue (ES2017)"
} | 197543 |
<p>This is a solution for the Day 8 hackerrank.com challenge. The basic idea of the challenge is to create a mapping of names to phone numbers based on the the given input, and later look up the phone numbers for certain names. If the entry exists, print it and its number. If it doesn't, print out "Not found".</p>
<p>Here's my solution in C++:</p>
<pre><code>#include<iostream>
#include<map>
using namespace std;
int main()
{
int i, n;
cin>>n;
string name, number, key;
map<string, string> phone_dir;
for(i=0; i<n; i++)
{
cin>>name>>number;
phone_dir.insert(pair <string, string> (name, number));
}
while(cin>>key)
{
if (phone_dir.find(key) != phone_dir.end())
{
cout<<key<<"="<<phone_dir.find(key)->second<< endl;
}
else cout<< "Not found"<<endl;
}
return 0;
}
</code></pre>
<p>Is there a more efficient solution in C++ for this problem?</p>
| [] | [
{
"body": "<ol>\n<li><p>You should not use <code>using namespace std;</code> This is bad practice that will get you into trouble once you want to use a function that has the same name.</p></li>\n<li><p>You can use descriptive names. So instead of \"n\" use \"numEntries\" or whatever.</p></li>\n<li><p>You should... | {
"AcceptedAnswerId": "197545",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T11:44:19.937",
"Id": "197544",
"Score": "4",
"Tags": [
"c++",
"programming-challenge",
"hash-map"
],
"Title": "Hackerrank Day 8: Dictionaries and Maps solution in C++"
} | 197544 |
<p>The following code is my solution to a code challenge I submitted a few days ago. I got rejected straight away with no feedback and I've wondered why.</p>
<p><a href="https://github.com/AyaAzzam/toy-robot-puzzle" rel="nofollow noreferrer">Here</a> is the full code repo.</p>
<blockquote>
<p><strong>Requirements</strong></p>
<p>The application is a simulation of a toy robot moving on a square
tabletop, of dimensions 5 x 5 units. There are no other obstructions
on the table surface. The robot is free to roam around the surface of
the table, but must be prevented from falling to destruction. Any
movement that would result in the robot falling from the table must be
prevented, however further valid movement commands must still be
allowed. Create an application that can read in commands of the
following form:</p>
<p>PLACE X,Y,F</p>
<p>MOVE</p>
<p>LEFT</p>
<p>RIGHT</p>
<p>REPORT</p>
<p>PLACE will put the toy robot on the table in position X,Y and facing
NORTH, SOUTH, EAST or WEST.</p>
<p>The origin (0,0) can be considered to be the SOUTH WEST most corner.</p>
<p>MOVE will move the toy robot one unit forward in the direction it is
currently facing.</p>
<p>LEFT and RIGHT will rotate the robot 90 degrees in the specified
direction without changing the position of the robot.</p>
<p>REPORT will announce the X,Y and F of the robot.</p>
<p>Constraints:</p>
<ul>
<li>The application must be a Spring-Boot-Application</li>
<li>Input must be realised over the REST-API, take care when designing the REST-API</li>
<li>The robot that is not on the table can choose the ignore the MOVE, LEFT, RIGHT and REPORT commands.</li>
<li>The robot must not fall off the table during movement. This also includes the initial placement of the toy robot.</li>
<li>Any move that would cause the robot to fall must be ignored.</li>
<li>It is not required to provide any graphical output showing the movement of the toy robot.</li>
</ul>
<p>Plain input Examples:</p>
<p>PLACE 0,0,NORTH MOVE REPORT</p>
<p>Output: 0,1,NORTH</p>
<p>PLACE 0,0,NORTH LEFT REPORT</p>
<p>Output: 0,0,WEST</p>
<p>PLACE 1,2,EAST MOVE MOVE LEFT MOVE REPORT</p>
<p>Output: 3,3,NORTH</p>
<p>MOVE REPORT</p>
<p>Output: ROBOT MISSING</p>
</blockquote>
<p><strong>Solution</strong></p>
<p><strong>ToyRobotApplication.java</strong> </p>
<pre><code>package com.puzzle.toyrobot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ToyRobotApplication {
public static void main(String[] args) {
SpringApplication.run(ToyRobotApplication.class, args);
}
}
</code></pre>
<p><strong>RobotSimulationController.java</strong></p>
<pre><code>package com.puzzle.toyrobot.controller;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.SimulationRound;
import com.puzzle.toyrobot.service.RobotSimulationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RobotSimulationController {
private RobotSimulationService simulationService;
@Autowired
public RobotSimulationController(RobotSimulationService simulationService) {
this.simulationService = simulationService;
}
@PostMapping
@RequestMapping("/robot/simulation")
public ResponseEntity<Report> newSimulationRound(@RequestBody SimulationRound simulationRound) {
Report report = simulationService.start(simulationRound);
return ResponseEntity.ok(report);
}
}
</code></pre>
<p><strong>RobotSimulationService.java</strong></p>
<pre><code>package com.puzzle.toyrobot.service;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.Robot;
import com.puzzle.toyrobot.model.SimulationRound;
import com.puzzle.toyrobot.model.command.Command;
import com.puzzle.toyrobot.model.command.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class RobotSimulationService {
private final Logger log = LoggerFactory.getLogger(RobotSimulationService.class);
public Report start(SimulationRound simulationRound) {
Robot robot = new Robot();
Report report = new Report();
for (String commandString : simulationRound.getCommands()) {
Command command = CommandFactory.getCommand(commandString);
if (command != null) {
command.execute(robot, report);
} else {
log.debug("Wrong command: " + commandString);
}
}
return report;
}
}
</code></pre>
<p><strong>SimulationRound.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model;
import java.util.ArrayList;
import java.util.List;
public class SimulationRound {
private List<String> commands = new ArrayList<>();
public List<String> getCommands() {
return commands;
}
public void setCommands(List<String> commands) {
this.commands = commands;
}
public void addCommand(String command) {
commands.add(command);
}
}
</code></pre>
<p><strong>Robot.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model;
public class Robot {
public static final Integer MAX_POSITION = 4;
public static final Integer MIN_POSITION = 0;
private Integer xPosition;
private Integer yPosition;
private CardinalDirection cardinalDirection;
public Robot() {
}
public Robot(Integer xPosition, Integer yPosition, CardinalDirection cardinalDirection) {
this.xPosition = xPosition;
this.yPosition = yPosition;
this.cardinalDirection = cardinalDirection;
}
public Integer getXPosition() {
return xPosition;
}
public void setXPosition(Integer xPosition) {
this.xPosition = xPosition;
}
public Integer getYPosition() {
return yPosition;
}
public void setYPosition(Integer yPosition) {
this.yPosition = yPosition;
}
public CardinalDirection getCardinalDirection() {
return cardinalDirection;
}
public void setCardinalDirection(CardinalDirection cardinalDirection) {
this.cardinalDirection = cardinalDirection;
}
public boolean isOnTable() {
return xPosition != null && yPosition != null && cardinalDirection != null;
}
public String getCurrentStatus() {
return String.join(",", xPosition.toString(), yPosition.toString(), cardinalDirection.toString());
}
public void increaseYPosition() {
yPosition++;
}
public void decreaseYPosition() {
yPosition--;
}
public void increaseXPosition() {
xPosition++;
}
public void decreaseXPosition() {
yPosition++;
}
}
</code></pre>
<p><strong>Report.java</strong>
package com.puzzle.toyrobot.model;</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Report {
private List<String> output = new ArrayList<>();
public List<String> getOutput() {
return output;
}
public void setOutput(List<String> output) {
this.output = output;
}
public void addOutput(String outupt) {
this.output.add(outupt);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Report report = (Report) o;
return Objects.equals(output, report.output);
}
@Override
public int hashCode() {
return Objects.hash(output);
}
}
</code></pre>
<p><strong>CardinalDirection.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model;
public enum CardinalDirection {
EAST, WEST, SOUTH, NORTH
}
</code></pre>
<p><strong>Command.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model.command;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.Robot;
public abstract class Command {
public abstract void execute(Robot robot, Report report);
}
</code></pre>
<p><strong>CommandFactory.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model.command;
public class CommandFactory {
private static final String PLACE_COMMAND_REGEX = "^(PLACE)\\s\\d+,\\d+,(NORTH|WEST|EAST|SOUTH)$";
public static Command getCommand(String commandString) {
if (commandString.matches(PLACE_COMMAND_REGEX)) {
return new PlaceCommand(commandString);
} else if (commandString.equals(CommandType.LEFT.name())) {
return new LeftCommand();
} else if (commandString.equals(CommandType.RIGHT.name())) {
return new RightCommand();
} else if (commandString.equals(CommandType.REPORT.name())) {
return new ReportCommand();
} else if (commandString.equals(CommandType.MOVE.name())) {
return new MoveCommand();
}
return null;
}
}
</code></pre>
<p><strong>CommandType,java</strong> </p>
<pre><code>package com.puzzle.toyrobot.model.command;
public enum CommandType {
PLACE, MOVE, LEFT, RIGHT, REPORT
}
</code></pre>
<p><strong>LeftCommand.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model.command;
import com.puzzle.toyrobot.model.CardinalDirection;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.Robot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LeftCommand extends Command {
private final Logger log = LoggerFactory.getLogger(LeftCommand.class);
public void execute(Robot robot, Report report) {
if (!robot.isOnTable()) {
log.debug("Left command ignored");
} else {
switch (robot.getCardinalDirection()) {
case NORTH:
robot.setCardinalDirection(CardinalDirection.WEST);
break;
case SOUTH:
robot.setCardinalDirection(CardinalDirection.EAST);
break;
case EAST:
robot.setCardinalDirection(CardinalDirection.NORTH);
break;
case WEST:
robot.setCardinalDirection(CardinalDirection.SOUTH);
break;
}
log.debug("The robot is rotating 90 degree to " + robot.getCardinalDirection());
}
}
}
</code></pre>
<p><strong>MoveCommand.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model.command;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.Robot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MoveCommand extends Command {
private final Logger log = LoggerFactory.getLogger(MoveCommand.class);
@Override
public void execute(Robot robot, Report report) {
if (!robot.isOnTable()) {
log.debug("Move command ignored");
} else {
switch (robot.getCardinalDirection()) {
case NORTH:
if (robot.getYPosition() < Robot.MAX_POSITION) {
robot.increaseYPosition();
log.debug("The robot is moving");
} else {
log.debug("Move command ignored");
}
break;
case SOUTH:
if (robot.getYPosition() > Robot.MIN_POSITION) {
robot.decreaseYPosition();
log.debug("The robot is moving");
} else {
log.debug("Move command ignored");
}
break;
case EAST:
if (robot.getXPosition() < Robot.MAX_POSITION) {
robot.increaseXPosition();
log.debug("The robot is moving");
} else {
log.debug("Move command ignored");
}
break;
case WEST:
if (robot.getXPosition() > Robot.MIN_POSITION) {
robot.decreaseXPosition();
log.debug("The robot is moving");
} else {
log.debug("Move command ignored");
}
break;
}
}
}
}
</code></pre>
<p><strong>PlaceCommand.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model.command;
import com.puzzle.toyrobot.model.CardinalDirection;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.Robot;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceCommand extends Command {
private final Logger log = LoggerFactory.getLogger(PlaceCommand.class);
private String commandString;
PlaceCommand(String commandString) {
this.commandString = commandString;
}
@Override
public void execute(Robot robot, Report report) {
String placementArgs = StringUtils.substringAfter(commandString, CommandType.PLACE.name());
String[] args = StringUtils.split(placementArgs, ",");
Integer initialX = Integer.parseInt(args[0].trim());
Integer initialY = Integer.parseInt(args[1].trim());
if (initialX <= Robot.MAX_POSITION && initialX >= Robot.MIN_POSITION
&& initialY <= Robot.MAX_POSITION && initialY >= Robot.MIN_POSITION) {
robot.setXPosition(initialX);
robot.setYPosition(initialY);
robot.setCardinalDirection(CardinalDirection.valueOf(args[2].trim()));
log.debug("Robot is placed at " + robot.getCurrentStatus());
} else {
log.debug("Place command ignored");
}
}
}
</code></pre>
<p><strong>ReportCommand.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model.command;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.Robot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReportCommand extends Command {
private final Logger log = LoggerFactory.getLogger(ReportCommand.class);
@Override
public void execute(Robot robot, Report report) {
if (!robot.isOnTable()) {
log.debug("Missing Robot");
report.addOutput("ROBOT MISSING");
} else {
report.addOutput(robot.getCurrentStatus());
}
}
}
</code></pre>
<p><strong>RightCommand.java</strong></p>
<pre><code>package com.puzzle.toyrobot.model.command;
import com.puzzle.toyrobot.model.CardinalDirection;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.Robot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RightCommand extends Command {
private final Logger log = LoggerFactory.getLogger(RightCommand.class);
@Override
public void execute(Robot robot, Report report) {
if (!robot.isOnTable()) {
log.debug("Right command ignored");
} else {
switch (robot.getCardinalDirection()) {
case NORTH:
robot.setCardinalDirection(CardinalDirection.EAST);
break;
case SOUTH:
robot.setCardinalDirection(CardinalDirection.WEST);
break;
case EAST:
robot.setCardinalDirection(CardinalDirection.SOUTH);
break;
case WEST:
robot.setCardinalDirection(CardinalDirection.NORTH);
break;
}
log.debug("The robot is rotating 90 degree to " + robot.getCardinalDirection());
}
}
}
</code></pre>
<p><strong>pom.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.puzzle</groupId>
<artifactId>toy-robot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>toy-robot</name>
<description>Toy Robot coding puzzle</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>and Finally a controller test </p>
<pre><code>package com.puzzle.toyrobot.controller;
import com.puzzle.toyrobot.model.Report;
import com.puzzle.toyrobot.model.SimulationRound;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RobotSimulationControllerTest {
@Autowired
private TestRestTemplate template;
@Test
public void simulationReportAsExpectedTest() {
Report report = new Report();
report.addOutput("0,1,NORTH");
SimulationRound round = new SimulationRound();
round.addCommand("PLACE 0,0,NORTH");
round.addCommand("LEFT");
round.addCommand("RIGHT");
round.addCommand("MOVE");
round.addCommand("REPORT");
HttpEntity<Object> simulationRound = getHttpEntity(round);
ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class);
Assert.assertEquals(resultAsset.getBody(), report);
}
@Test
public void missingRobotTest() {
Report report = new Report();
report.addOutput("ROBOT MISSING");
SimulationRound round = new SimulationRound();
round.addCommand("MOVE");
round.addCommand("REPORT");
HttpEntity<Object> simulationRound = getHttpEntity(round);
ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class);
Assert.assertEquals(resultAsset.getBody(), report);
}
@Test
public void ignoringWrongCommandTest() {
Report report = new Report();
report.addOutput("0,0,WEST");
SimulationRound round = new SimulationRound();
round.addCommand("PLACE 0,0,WEST");
round.addCommand("MOVEEEE");
round.addCommand("REPORT");
HttpEntity<Object> simulationRound = getHttpEntity(round);
ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class);
Assert.assertEquals(resultAsset.getBody(), report);
}
@Test
public void ignoringCommandThatCausesFailTest() {
Report report = new Report();
report.addOutput("0,0,SOUTH");
SimulationRound round = new SimulationRound();
round.addCommand("PLACE 0,0,SOUTH");
round.addCommand("MOVE");
round.addCommand("REPORT");
HttpEntity<Object> simulationRound = getHttpEntity(round);
ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class);
Assert.assertEquals(resultAsset.getBody(), report);
}
@Test
public void simulationRoundWithoutReportTest() {
Report report = new Report();
SimulationRound round = new SimulationRound();
round.addCommand("PLACE 1,2,EAST");
round.addCommand("MOVE");
round.addCommand("MOVE");
round.addCommand("LEFT");
HttpEntity<Object> simulationRound = getHttpEntity(round);
ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class);
Assert.assertEquals(resultAsset.getBody(), report);
}
private HttpEntity<Object> getHttpEntity(Object body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(body, headers);
}
}
</code></pre>
<p><strong>Notes on solution:</strong></p>
<ul>
<li>All commands will be ignored until a valid PLACE command.</li>
<li>The robot can be re-PLACEd at any time.</li>
<li>Any number of REPORT commands are allowed.</li>
<li>The REST-API request body is a Simulation Round object that contains a list of commands.</li>
<li>The REST-API response object is a Report object that contains a list of reports, which is the output of the REPORT command if any.</li>
<li>Many Integration tests are added.</li>
</ul>
| [] | [
{
"body": "<p>I didn't examine all the classes. Here is my (partial) analysis:</p>\n\n<h2>REST API</h2>\n\n<p>Your API consists of one call. This is clearly not what was intended by the question (they did state that they regard the design of the API as important...) </p>\n\n<p>First thing when designing a RE... | {
"AcceptedAnswerId": "197598",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T13:43:42.630",
"Id": "197547",
"Score": "1",
"Tags": [
"java",
"api",
"rest",
"spring"
],
"Title": "Toy Robot coding puzzle with Java"
} | 197547 |
<p>I'm doing some recreational programming in C (after spending some time in C++, but professionally using only PHP/JavaScript).</p>
<p>I wrote a UTF8 to UTF32 converter and just wanted to know if I made some obvious mistakes. (For example, is it a big no-no to <code>malloc</code> inside a function (because of possible memory leaks) – and if yes – how would you rather do it?)</p>
<pre><code>#include <stdlib.h>
#include <stdint.h>
size_t utf8_strlen(uint8_t* text) {
size_t i = 0;
size_t num_chars = 0;
while (text[i] != 0) {
num_chars++;
if ((text[i] & 0b10000000) == 0) {
// 1 byte code point, ASCII
i += 1;
}
else if ((text[i] & 0b11100000) == 0b11000000) {
// 2 byte code point
i += 2;
}
else if ((text[i] & 0b11110000) == 0b11100000) {
// 3 byte code point
i += 3;
}
else {
// 4 byte code point
i += 4;
}
}
return num_chars;
}
uint32_t* utf8_to_utf32(uint8_t* text) {
size_t num_chars = utf8_strlen(text);
uint32_t* c = malloc(sizeof(uint32_t) * num_chars);
size_t i = 0;
for (size_t n = 0; n < num_chars; n++) {
if ((text[i] & 0b10000000) == 0) {
// 1 byte code point, ASCII
c[n] = (text[i] & 0b01111111);
i += 1;
}
else if ((text[i] & 0b11100000) == 0b11000000) {
// 2 byte code point
c[n] = (text[i] & 0b00011111) << 6 | (text[i + 1] & 0b00111111);
i += 2;
}
else if ((text[i] & 0b11110000) == 0b11100000) {
// 3 byte code point
c[n] = (text[i] & 0b00001111) << 12 | (text[i + 1] & 0b00111111) << 6 | (text[i + 2] & 0b00111111);
i += 3;
}
else {
// 4 byte code point
c[n] = (text[i] & 0b00000111) << 18 | (text[i + 1] & 0b00111111) << 12 | (text[i + 2] & 0b00111111) << 6 | (text[i + 3] & 0b00111111);
i += 4;
}
}
return c;
}
</code></pre>
<h2>Edit:</h2>
<p>I've posted an updated version of the code to GitHub for anyone that is interested: <a href="https://github.com/s22h/cutils/blob/master/src/unicode.h" rel="nofollow noreferrer">https://github.com/s22h/cutils/blob/master/src/unicode.h</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T16:24:54.000",
"Id": "380858",
"Score": "1",
"body": "I just realised that I'm missing the null terminator at the end of the UTF32 string."
}
] | [
{
"body": "<h1>Magic numbers</h1>\n\n<p>The implementation uses them a lot. While the bit-notation helps with indicating what is happening, it doesn't show the intention. What reads clearer:</p>\n\n<pre><code>if((text[i] & 0b1000000) == 0)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if((text[i] & UTF8_ONE... | {
"AcceptedAnswerId": "197564",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T15:39:04.857",
"Id": "197548",
"Score": "8",
"Tags": [
"c",
"unicode",
"utf-8",
"c11"
],
"Title": "Convert UTF8 string to UTF32 string in C"
} | 197548 |
<p>I am trying to implement a controlled job with java that initiates a new thread and provides a method to stop the execution of the thread without having to maintain the context.</p>
<p>The interface looks like:</p>
<pre><code>public interface ControlledJob {
void stop();
void start();
boolean isJobRunning();
}
</code></pre>
<p>And the implementation looks like:</p>
<pre><code>import com.google.common.base.Preconditions;
public class SampleControlledJob implements ControlledJob {
private static final String JOB_ALREADY_RUNNING_EXCEPTION_MESSAGE = "Job is already running.";
private static final String JOB_ALREADY_STOPPED_EXCEPTION_MESSAGE = "Job is already stopped.";
private final static SampleControlledJob SAMPLE_CONTROLLED_JOB = new SampleControlledJob();
private final Process process;
private boolean isJobRunning = false;
private boolean toContinue = false;
private Thread thread;
private String threadName;
private SampleControlledJob() {
this.process = new Process();
}
public static ControlledJob getInstance() {
return SAMPLE_CONTROLLED_JOB;
}
@Override
public void start() {
Preconditions.checkArgument(!this.isJobRunning, JOB_ALREADY_RUNNING_EXCEPTION_MESSAGE);
this.threadName = "Thread:" + System.currentTimeMillis();
this.thread = new Thread(this.process, threadName);
this.toContinue = true;
this.isJobRunning = true;
this.thread.start();
}
@Override
public void stop() {
Preconditions.checkArgument(this.isJobRunning, JOB_ALREADY_STOPPED_EXCEPTION_MESSAGE);
this.toContinue = false;
}
@Override
public boolean isJobRunning() {
return isJobRunning;
}
private class Process implements Runnable {
public void run() {
while (toContinue) {
System.out.println(threadName + ", prints hello::" + System.currentTimeMillis());
}
isJobRunning = false;
}
}
}
</code></pre>
<p>The client can use the API like:</p>
<pre><code>SampleControlledJob.getInstance().start();
SampleControlledJob.getInstance().stop();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-10T12:21:57.727",
"Id": "382223",
"Score": "1",
"body": "Smaller things: when multithreading like this, use volatile keyword. The Thread will be instantiated every time you call start (that might be okay). Thread name is based on times... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T16:48:37.213",
"Id": "197550",
"Score": "1",
"Tags": [
"java",
"multithreading"
],
"Title": "Implementation of a controlled job with Java"
} | 197550 |
<p>So I am working on writing a discord bot with <a href="https://github.com/Rapptz/discord.py" rel="noreferrer">discord.py</a>.</p>
<p>I decided, rather than making a serie of if/elif, to map the messages to the functions in a dictionnary, like so:</p>
<p><code>my_dict = { "!trigger": func }</code></p>
<p>I then wanted to parse this dictionnary into an <code>async for</code> loop, but ran into some problems. To face those problems, I decided to write a <code>dict()</code> subclass, which I called <code>AsyncDict</code>. I just want to know if this is safe to work like this, or not? The main purpose of this little class is to avoid errors like "an async for loop needs an item that defines the function <code>__aiter__</code>" </p>
<p><strong>AsyncDict class:</strong></p>
<pre><code>class AsyncDict(dict):
def __init__(self, *args, **kwargs):
super(AsyncDict, self).__init__(*args, **kwargs)
async def items(self):
items = super().items()
for item in items:
yield item
async def keys(self):
keys = super().keys()
for key in keys:
yield key
async def values(self):
values = super().values()
for value in values:
yield
</code></pre>
<p>Once this is done, I just create my dictionary "as usual":
<code>calls = AsyncDict([("!ping", ping)])</code></p>
<p>Here is the relevant code in my <strong>main.py:</strong></p>
<pre><code>import discord
import asyncio
async def ping(message):
await client.send_message(message.channel, 'pong')
calls = AsyncDict([("!ping", ping)])
@client.event
async def on_message(message):
async for k, v in calls.items():
if message.content.startswith(k):
await v(message)
</code></pre>
<p>I just want to know if it's "safe" to work like this (cf.: AsyncDict)? I'm quite new to asynchronous development and I don't know if I'm missing something.</p>
| [] | [
{
"body": "<p>I saw your post on python-ideas. I think you have a misconception about native coroutines (i.e. <code>async def</code>). For example, this method in <code>AsyncDict</code>:</p>\n\n<pre><code>async def items(self):\n items = super().items()\n for item in items:\n yield item\n</code></p... | {
"AcceptedAnswerId": "202067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T16:51:16.353",
"Id": "197551",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"hash-map",
"async-await"
],
"Title": "Asynchronous dictionary in Python"
} | 197551 |
<p>A few notes:</p>
<ul>
<li><p>There is currently no non exception-based way of knowing whether a key is present in the table or not. This is intentional for my use case.</p></li>
<li><p>Unlike the lookup process, the baking process is definitely not appropriate for a real-time application. That's ok as it's meant to be run offline.</p></li>
<li><p>Obviously, this is only appropriate for storing trivial types.</p></li>
</ul>
<p>What I'm particularly interested in is:</p>
<ol>
<li><p>I "think" I managed to pull this off without any Undefined Behavior, but I'd really want some other pairs of eyes checking for this, as I'm in dodgy territory on that front.</p></li>
<li><p>As usual, any and all criticism on general code quality.</p></li>
</ol>
<p>Thanks!</p>
<pre><code>#include <cassert>
#include <cstdint>
#include <cstring>
#include <functional>
#include <type_traits>
#include <unordered_set>
#include <utility>
// The flat hash table is meant to be used when a hash table is baked once,
// typically during a build process, and then used repeatadly. It can be
// initialized by simply pointing it at a memory location containing the
// raw data.
// The table does NOT maintain ownership over the data.
template <typename ValT, typename HashT = std::uint64_t>
class flat_hash_table {
static_assert(std::is_trivial_v<ValT>);
static_assert(std::is_trivial_v<HashT>);
public:
flat_hash_table(char const* mem_loc, std::size_t mem_len)
: mem_loc_(mem_loc) {
if (mem_len < sizeof(bucket_count_)) {
throw std::invalid_argument("invalid flat hash data");
}
char const* read_ptr = mem_loc;
std::memcpy(&bucket_count_, read_ptr, sizeof(bucket_count_));
read_ptr += sizeof(bucket_count_);
if (mem_len < sizeof(bucket_count_) + bucket_count_ * sizeof(bucket_t)) {
throw std::invalid_argument("invalid flat hash data");
}
if (std::uintptr_t(read_ptr) % alignof(bucket_t) != 0) {
throw std::invalid_argument("flat hash data appears to be misaligned");
}
static_assert(std::is_trivially_constructible_v<bucket_t>);
buckets_ = new (const_cast<char*>(read_ptr)) bucket_t[bucket_count_];
for (std::uint32_t i = 0; i < bucket_count_; ++i) {
if (buckets_[i].offset + buckets_[i].count * sizeof(elem_t) > mem_len) {
throw std::invalid_argument("invalid flat hash data");
}
auto bucket_loc = mem_loc_ + buckets_[i].offset;
if (std::uintptr_t(bucket_loc) % alignof(elem_t) != 0) {
throw std::invalid_argument("flat hash data appears to be misaligned");
}
static_assert(std::is_trivially_constructible_v<elem_t>);
new (const_cast<char*>(bucket_loc)) elem_t[buckets_[i].count];
}
}
// Lookup a value from the hash table, throws if the value is not
// present.
template <typename KeyT>
ValT const& at(KeyT const& key) {
HashT key_hash = std::hash<KeyT>{}(key);
auto const& bucket = buckets_[key_hash % bucket_count_];
if (bucket.count > 0) {
elem_t const* elem_table =
reinterpret_cast<elem_t const*>(mem_loc_ + bucket.offset);
auto end = elem_table + bucket.count;
// Elements within a bucket are stored as a sorted vector, so we
// can do a binary search.
auto found = std::lower_bound(
elem_table, end, key_hash,
[](elem_t const& lhs, HashT const& rhs) { return lhs.key < rhs; });
if (found != end && found->key == key_hash) {
return found->val;
}
}
throw std::out_of_range("element not present in flat hash table");
}
private:
char const* mem_loc_;
struct bucket_t {
std::uint32_t count;
std::uint32_t offset;
};
// This cannot be a std::pair<> because the default constructor is not trivial
struct elem_t {
HashT key;
ValT val;
};
std::uint32_t bucket_count_;
bucket_t const* buckets_;
template <typename K, typename V, typename H>
friend std::vector<char> bake_flat_hash_table(
std::vector<std::pair<K, V>> const&);
};
// Bakes a dataset into a flat_has_table raw data chunk.
template <typename KeyT, typename ValT, typename HashT = std::uint64_t>
std::vector<char> bake_flat_hash_table(
std::vector<std::pair<KeyT, ValT>> const& data) {
using table_t = flat_hash_table<ValT, HashT>;
using elem_t = typename table_t::elem_t;
using bucket_t = typename table_t::bucket_t;
static_assert(std::is_trivial_v<ValT>);
static_assert(std::is_trivial_v<HashT>);
// TODO: Better process to determine optimal bucket count.
std::uint32_t bucket_count = data.size() / 2 + 1;
std::vector<std::vector<elem_t>> buckets(bucket_count);
{
// Keep track of seen hashes since we do not tolerate true collisions.
std::unordered_set<HashT> hash_values_set;
for (auto const& d : data) {
HashT hash_val = HashT(std::hash<KeyT>{}(d.first));
if (hash_values_set.count(hash_val) != 0) {
throw std::runtime_error(
"True hash collision in dataset, cannot make a flat hash table out "
"of it.");
}
hash_values_set.insert(hash_val);
buckets[hash_val % bucket_count].emplace_back(elem_t{hash_val, d.second});
}
}
std::size_t header_mem_size = 0;
header_mem_size += sizeof(std::uint32_t); // for bucket_count
header_mem_size += sizeof(bucket_t) * bucket_count; // bucket table
// Make sure the actual value payloads is correctly aligned
constexpr auto elem_align = alignof(elem_t);
static_assert((elem_align & (elem_align - 1)) == 0);
header_mem_size = (header_mem_size + (elem_align - 1)) & ~(elem_align - 1);
auto mem_size = header_mem_size + sizeof(elem_t) * data.size();
std::vector<char> result(mem_size);
char* header_w_ptr = result.data();
char* data_w_ptr = result.data() + header_mem_size;
auto write = [&](char*& dst, auto const& v) {
assert(dst + sizeof(v) <= result.data() + result.size());
std::memcpy(dst, &v, sizeof(v));
dst += sizeof(v);
};
write(header_w_ptr, bucket_count);
for (auto& b : buckets) {
std::sort(b.begin(), b.end(), [](auto const& lhs, auto const& rhs) {
return lhs.key < rhs.key;
});
auto offset = data_w_ptr - result.data();
bucket_t bucket_header{std::uint32_t(b.size()), std::uint32_t(offset)};
write(header_w_ptr, bucket_header);
for (auto const& e : b) {
write(data_w_ptr, e);
}
}
return result;
}
#include <iostream>
#include <string_view>
#include <vector>
int main() {
std::vector<std::pair<std::string, float>> raw_values = {
{"hi", 12.0f}, {"yo", 10.0f}, {"sup", 3.0f},
};
std::vector<char> raw_data = bake_flat_hash_table(raw_values);
flat_hash_table<float> values(raw_data.data(), raw_data.size());
std::cout << values.at(std::string_view("yo")) << "\n";
std::cout << values.at(std::string_view("sup")) << "\n";
std::cout << values.at(std::string_view("hi")) << "\n";
return 0;
}
</code></pre>
<p>Obvious next steps / stuff I'm already aware of:</p>
<ul>
<li>Endianness handling</li>
<li>Proper iterator-based lookup interface</li>
<li>Better bucket counting</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T21:46:24.950",
"Id": "380881",
"Score": "0",
"body": "Is internal layout of hashmap part of public interface? Code says yes, but I just wanted to be sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-... | [
{
"body": "<p>I'm no expert, but it seems like the code doesn't invoke UB. It is already great, but there are some small issues here and there.</p>\n\n<h2>Missing header</h2>\n\n<p><code>std::sort()</code> is used in <code>bake_flat_hash_table()</code>, but <code><algorithm></code> is not added.</p>\n\n<h... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T17:00:13.537",
"Id": "197552",
"Score": "3",
"Tags": [
"c++",
"memory-management",
"hash-map",
"c++17"
],
"Title": "Pre-baked Hash table with a flat memory layout"
} | 197552 |
<p>This function <code>word_break(s, dictionary)</code> receives a string <code>s</code> and a set of all valid words <code>dictionary</code>, and must return all possible ways the string <code>s</code> can be split into valid words, if any. </p>
<p>For example, a string <code>catsanddog</code> with dictionary <code>{'cat', 'cats', 'sand', 'and', 'dog'}</code> can be broken in two ways: <code>cats and dog</code> and <code>cat sand dog</code>.</p>
<p>My solution to this recursively breaks the input string at various index (offset), and uses memoization as I realized we may be breaking at the same offset multiple times.</p>
<p>Here is the full code along with a test case, in Python 2.x:</p>
<pre><code>def memoize(fn):
memo = {}
def wrapped_fn(*args):
if args not in memo:
memo[args] = fn(*args)
return memo[args]
return wrapped_fn
def word_break(s, dictionary):
@memoize
def _word_break(offset):
if offset == len(s):
return []
breaks_from_offset = []
if s[offset:] in dictionary:
breaks_from_offset.append([s[offset:]])
for i in range(offset+1, len(s)):
if s[offset:i] in dictionary:
for break_from_i in _word_break(i):
breaks_from_offset.append([s[offset:i]] + break_from_i)
return breaks_from_offset
return [' '.join(words) for words in _word_break(0)]
# print word_break('catsanddog', {'cat', 'cats', 'sand', 'and', 'dog'})
# -> [cat sand dog', 'cats and dog']
</code></pre>
<p>Based on LeetCode question Word Break II: <a href="https://leetcode.com/problems/word-break-ii/description/" rel="nofollow noreferrer">https://leetcode.com/problems/word-break-ii/description/</a></p>
<p>As this is an "interview" algorithm question, I would love feedback that keeps that setting in mind. That said, I also appreciate any feedback to help me write more production-ready Python code :) </p>
| [] | [
{
"body": "<p>Honestly it looks like you're doing this wrong. Currently you're splitting the word into \\$n^2\\$ words and checking if they are in the dictionary. Rather than doing this you can traverse a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">Trie</a> and loop through the in... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T18:34:42.003",
"Id": "197558",
"Score": "2",
"Tags": [
"python",
"algorithm",
"recursion",
"memoization"
],
"Title": "Determine all ways a string can be split into valid words, given a dictionary of all words"
} | 197558 |
<p>This is a very simple ball game in which we have to avoid projectiles falling from the sky. This is my second project and first game. Please review and tell where I can improve.</p>
<pre><code>import time
import random
import pygame
pygame.init()
#colors
black=(0,0,0)
white=(255,255,255)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
darkViolet=(148,0,211)
#display
displayWidth=1024
displayHeight=600
display=pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('PHY')
heart=pygame.image.load('heart.png')
myfont=pygame.font.SysFont('Terminal', 18)
clock=pygame.time.Clock()
endTime=time.time()
#physics
x,y=displayWidth/2,displayHeight/2
ux, uy, ax, ay= 0, 0, 0, 0 # u means velocity, a means acceleration
yp1, up1, ap = 0, 50, 50 #p for projectile
xp1,yp1,up1,ap1=[],0,50,50 #projectile variables. xp1 list coz multiple projectiles
uc, ac = 20, 5 # c stands for the amount of change on key press
score, lives=0,3
touching=False
running=True
#misc
projectile=pygame.Surface((10,20))
projectile.fill(darkViolet)
#adding random locations for projectiles to spawn in
for _ in range(20):
xp1.append(random.randint(0,displayWidth))
while running:
#taking dt to be a small value which will depend on the processing power
startTime=time.time()
t=startTime-endTime
#changing the postions and velocities with time
ux+=ax*t
uy+=ay*t
x+=ux*t
y+=uy*t
up1+=ap*t
yp1+=up1*t
endTime=time.time()
#checking for collision of ball with boundaries
if x<0:
x=0
ux=-ux/3
if x>displayWidth:
x=displayWidth
ux=-ux/3
if y<0:
y=0
uy=-uy/3
if y>displayHeight:
y=displayHeight
uy=-uy/3
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
running=False
elif ev.type == pygame.KEYDOWN: #acts on pressing and not on holding key
if ev.key == pygame.K_UP:
ay-=ac
uy-=uc
if ev.key == pygame.K_DOWN:
ay+=ac
uy+=uc
if ev.key == pygame.K_LEFT:
ax-=ac
ux-=uc
if ev.key == pygame.K_RIGHT:
ax+=ac
ux+=uc
elif ev.type == pygame.KEYUP:
if ev.key == pygame.K_UP:
ay=0
if ev.key == pygame.K_DOWN:
ay=0
if ev.key == pygame.K_LEFT:
ax=0
if ev.key == pygame.K_RIGHT:
ax=0
#condition for when the projectile crosses the screen
if yp1>displayHeight:
yp1=0
up1=3*up1/5
ap+=5
xp1=[]
score+=1
for _ in range(20):
xp1.append(random.randint(0,displayWidth))
#checking for collision between ball and projectile
for g in range(20):
if x>xp1[g]-10 and x<10+xp1[g] and y>yp1-15 and y<yp1+15:
touching=True
xp1[g]=1050
if touching:
if lives>1:
lives-=1
touching=False
else:
running=False
#displaying
display.fill(black)
for g in range(lives): #displaying the lives as hearts
display.blit(heart, (950+g*25,25))
for g in range(20): #displaying the same projectile at 20 places
display.blit(projectile, (xp1[g], yp1))
textDisp=myfont.render('SCORE: %s'%(score),False,white)
pygame.draw.circle(display, red, (int(x),int(y)), 10, 0) #displaying the ball
display.blit(textDisp,(950,50)) #displaying the score
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
</code></pre>
| [] | [
{
"body": "<p>Follow standard identifier conventions. Variable are <code>lower_case</code>, class names should be <code>CamelCase</code>, and constants should be <code>UPPER_CASE</code>. With this in mind, your block of colours at the start should be altered:</p>\n\n<pre><code># Colours\nBLACK = (0, 0, 0)\nWH... | {
"AcceptedAnswerId": "197587",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T18:49:39.243",
"Id": "197559",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"pygame"
],
"Title": "ball-game created in Python 3"
} | 197559 |
<p>This is a school project I've written. It works, but I feel it could be done better. </p>
<p>The program generate an array of 1'000 random numbers, and searches for a number typed into console, and displays the index if found.</p>
<pre><code>int inp, zuf, i, num, trig=0;
const int amount = 1000;
int arr[amount];
cout << "Numbers" << endl << "======" << endl << endl;
cout << "Please type in a nuber between 1 and 1000: " << endl;
cin >> inp;
srand(time(NULL));
for (int i = 1; i < amount + 1; i++) {
zuf = rand();
zuf = (zuf % amount) + 1;
arr[i] = zuf;
num = i;
if (inp== arr[num] && trig == 0) {
cout << "The number exists at the position: ";
trig++;
}
if (inp== arr[num]) {
cout << num << ", ";
num++;
trig++;
}
}
if (trig == 0) cout << "This number doesn't exist." << endl;
else cout << "\b\b." << endl;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T19:42:48.263",
"Id": "380870",
"Score": "0",
"body": "Are you intentionally writing pre-C++11 code? This would change the nature of the feedback quite a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-... | [
{
"body": "<h2>Do not using <code>using namespace std</code></h2>\n\n<p>bringing in entire namespaces can be convenient, but in the long run, it's a really bad habit.</p>\n\n<p>You should explicitly use <code>std::cout</code> and the like instead. </p>\n\n<h2>Declare variables as close as possible to their firs... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T18:59:43.057",
"Id": "197561",
"Score": "6",
"Tags": [
"c++",
"homework"
],
"Title": "Generate array with random numbers and search for an element in it"
} | 197561 |
<p>Its meant to password protect python scripts by using encryption
It should use <code>os.urandom(40)</code>'s output in hex as the salt. The <a href="https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/?highlight=kdf" rel="nofollow noreferrer">kdf (cryptography.io)</a> is using <a href="https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/?highlight=Scrypt" rel="nofollow noreferrer">Scrypt (cryptography.io)</a> password input is using <code>getpass.getpass</code>. It's on my GitHub: <a href="https://github.com/OfficialNoob/Python-Script-Locker/tree/2ed5d8cd6ba250767b41356f1adb9d37733aa002" rel="nofollow noreferrer">Python Script Locker (GitHub)</a>, and is required to work with both Python 2 and 3.</p>
<pre><code>#!/usr/bin/env python
import sys
def exitmsg(msg):
print(msg)
input("Press ENTER to exit the script")
sys.exit()
if sys.version_info<(3,0,0):
def input(string):
return raw_input(string)
import base64
import binascii
import os
import getpass
try:
from cryptography.fernet import Fernet
except ImportError:
exitmsg("cryptography not installed install it with pip install cryptography via cmd or powershell (On Windows)")
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
print("PyLock beta v1.0.3 https://github.com/OfficialNoob/Python-Script-Locker")
salt = binascii.hexlify(os.urandom(40))
kdf = Scrypt(salt=salt,length=32,n=2**14,r=8,p=1,backend=default_backend())
loc = input("Script to use: ")
try:
fscript = open(loc)
except IOError:
exitmsg("Unable to read file")
script = fscript.read()
fscript.close
print("Can be used to overwrite your script")
sloc = input("Save as: ")
nc = '''#!/usr/bin/env python
#Made using PyLock https://github.com/OfficialNoob/Python-Script-Locker
import sys
def exitmsg(msg):
print(msg)
input("Press ENTER to exit")
sys.exit()
if sys.version_info<(3,0,0):
def input(string):
return raw_input(string)
import getpass
import base64
try:
from cryptography.fernet import Fernet
except ImportError:
exitmsg("cryptography not installed install it with pip install cryptography via cmd or powershell (On Windows)")
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
kdf = Scrypt(salt=%s,length=32,n=2**14,r=8,p=1,backend=default_backend())
try:
exec(Fernet(base64.urlsafe_b64encode(kdf.derive(getpass.getpass("Password to use: ").encode()))).decrypt(%s))
except Exception as ex:
if(type(ex).__name__ == "InvalidToken"):
exitmsg("Wrong password (-:")
print(ex)''' % (salt, Fernet(base64.urlsafe_b64encode(kdf.derive(getpass.getpass("Password to use: ").encode()))).encrypt(script.encode()))
try:
f = open(sloc,"w+")
f.write(nc)
except IOError:
exitmsg("Unable to write to file")
f.close
exitmsg("Your file has been created")
</code></pre>
| [] | [
{
"body": "<p>The good news is that as far as I can tell, the cryptography is correct (password-based key derivation function, random salt). The bad news is that your code is hard to read, and so it's hard to make sure that it's correct.</p>\n\n<p>Please read <a href=\"https://www.python.org/dev/peps/pep-0008/\... | {
"AcceptedAnswerId": "197616",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T19:13:20.833",
"Id": "197563",
"Score": "1",
"Tags": [
"python",
"security",
"cryptography",
"meta-programming"
],
"Title": "Encryption scripts using the module cryptography"
} | 197563 |
<p>Here is a class I wrote to provide a user a way to have a callback function executed at some defined frequency:</p>
<p><strong>Task.hpp</strong></p>
<pre><code>#pragma once
#include <memory>
#include <functional>
class Task
{
public:
Task(const double& _hertz, const std::function<void()>& _callback);
~Task();
void SetCallback(const std::function<void()>& _callback);
void Start();
void Pause();
void Exit();
void SetFrequency(const double& _hertz);
bool IsRunning() const;
unsigned long GetOverrunCount() const;
private:
struct Internal;
std::unique_ptr<Internal> impl;
};
</code></pre>
<p><strong>Task.cpp</strong></p>
<pre><code>#include "Task.hpp"
// misc
#include "Chrono.hpp"
// std
#include <thread>
#include <mutex>
#include <atomic>
struct Task::Internal
{
public:
Internal(const double& _m_freq, const std::function<void()>& _callback):
m_frequency(_m_freq),
m_callback(_callback)
{
}
~Internal()
{
Exit();
}
void SetCallback(const std::function<void()>& _callback)
{
std::lock_guard<std::mutex> _lock(m_thread_mutex);
m_callback = _callback;
}
void SetFrequency(const double& _hertz)
{
m_frequency = _hertz;
}
void Start()
{
std::lock_guard<std::mutex> _lock(m_thread_mutex);
// Already have a thread
if (m_thread != nullptr)
{
return;
}
m_thread = std::make_unique<std::thread>(&Internal::Task, this);
m_pause = false;
m_run = true;
}
void Pause()
{
m_run = false;
m_pause = true;
}
void Exit()
{
std::lock_guard<std::mutex> _lock(m_thread_mutex);
// We don't have a thread
if (m_thread == nullptr)
{
return;
}
m_run = false;
m_exit = true;
// wait for exit
m_thread->join();
// Destory thread object
m_thread.reset(nullptr);
}
bool IsRunning() const
{
return m_run;
}
unsigned long GetOverrunCount() const
{
return m_overrun_count;
}
protected:
private:
std::atomic<double> m_frequency;
std::atomic<bool> m_exit{ false };
std::atomic<bool> m_pause{ true };
std::atomic<bool> m_run{ false };
std::atomic<unsigned long> m_overrun_count{ 0 };
std::unique_ptr<std::thread> m_thread{ nullptr };
std::function<void()> m_callback;
std::mutex m_thread_mutex;
void Task()
{
// run until told to m_exit
while (m_exit == false)
{
// Calculate the period from freq
long long periodInUs = (long long)((1.0 / m_frequency) * 1000.0 * 1000.0);
// start time of the task
auto start = ChronoHelper::GetTimeNow();
// we are not paused
if (m_pause == false)
{
std::lock_guard<std::mutex> _lock(m_thread_mutex);
// the callback has been set
if (m_callback != nullptr)
{
m_callback();
}
}
// get the amount of time left needed to sleep
TimeVar end = ChronoHelper::GetTimeNow();
long long executionTime = ChronoHelper::DurationInMicroSeconds(start, end);
long long toSleep = periodInUs - executionTime;
if (toSleep > 0)
{
std::this_thread::sleep_for(std::chrono::microseconds(toSleep));
}
else
{
m_overrun_count++;
}
}
};
};
Task::Task(const double& _m_freq, const std::function<void()>& _callback):
impl(new Internal(_m_freq, _callback))
{
}
Task::~Task()
{
}
void Task::Start()
{
impl->Start();
}
void Task::Pause()
{
impl->Pause();
}
void Task::Exit()
{
impl->Exit();
}
bool Task::IsRunning() const
{
return impl->IsRunning();
}
void Task::SetFrequency(const double& _hertz)
{
impl->SetFrequency(_hertz);
}
void Task::SetCallback(const std::function<void()>& _callback)
{
impl->SetCallback(_callback);
}
unsigned long Task::GetOverrunCount() const
{
return impl->GetOverrunCount();
}
</code></pre>
<p>I made <code>std::thread</code> dynamically allocated because I did not like that I can't control when <code>std::thread</code> starts executing. This way, I limit the thread from running unnecessarily until the user calls <code>Start()</code>. It will, however, still be ticking when the user calls <code>Pause()</code>, which is a little jarring.</p>
<p>I was also considering having this class maintain a list of callbacks rather than a single callback.</p>
| [] | [
{
"body": "<p>Really nice use of an opaque type! (though I personally think it's overkill in this particular instance, but that's a matter of opinion).</p>\n\n<blockquote>\n <p>I made std::thread dynamically allocated because I did not like that I can't control when std::thread starts executing.</p>\n</blockqu... | {
"AcceptedAnswerId": "197571",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T21:12:57.583",
"Id": "197570",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"callback"
],
"Title": "Class that provides callback execution at a specified rate"
} | 197570 |
<p>I wrote a program that, given a string of text, converts it to Title Case based on certain criteria. I would mainly like to know how I could improve readability and expressiveness, make a more clear API, and improve the efficiency of the algorithms, but any other feedback would also be appreciated. Here is an excerpt of the requirements from </p>
<p><a href="https://www.fluentcpp.com/2018/06/29/7-more-ways-to-get-better-at-c-this-summer-2018-edition/" rel="noreferrer">https://www.fluentcpp.com/2018/06/29/7-more-ways-to-get-better-at-c-this-summer-2018-edition/</a> : </p>
<blockquote>
<p>Step 1: Basic Title Case For each word in a sentence, make all of its
letters lower case, except the first one that would be in upper case.</p>
<p>There is a list of “exceptions” words that need to be entirely in
lower case, including their first letter. This lists includes “at” and
“to”, along with another dozen words. For the sake of this project
let’s say that the list of exceptions is: a, an, the, at, by, for, in,
of, on, to, and, as and or.</p>
<p>Note that in all cases, the first word of the string must start with a
capital letter.</p>
<p>Step 2: Title Case with customizations Make the list of exceptions
customizable: the library user can add new exceptions, replace the
list with their own, or add words that should not be changed by the
library.</p>
<p>An additional requirement is that words in all caps should be left as
is (“STL” must remain “STL”, and not be changed into “Stl”), but the
library user should be able to opt-out of this feature.</p>
</blockquote>
<h2>TitleCase.h</h2>
<pre><code>#pragma once
#include <algorithm>
#include <string>
#include <string_view>
#include <vector>
class TitleCase
{
//title case will not be applied to these words
std::vector<std::string> m_exceptions = { "a", "an", "the", "at", "by", "for", "in", "of", "on", "to", "and", "as", "or" };
//acronyms like "STL" will optionally be ignored when applying title case
bool m_ignore_acronyms = true;
void apply_title_case(std::string::iterator begin_word, std::string::iterator end_word);
std::string_view get_word(std::string::iterator begin_word, std::string::iterator end_word);
template<typename Pred>
void apply_case_if_pred_met(std::string::iterator begin_word, std::string::iterator end_word, Pred pred)
{
if (pred(get_word(begin_word, end_word)))
{
apply_title_case(begin_word, end_word);
}
}
template<typename Pred>
void convert_impl(std::string& text, Pred pred)
{
auto begin_word = text.begin();
auto end_word = std::find(begin_word, text.end(), ' ');
if (end_word == text.end()) //check if there's only one word in string or string is empty
{
if (text.empty()) return;
apply_case_if_pred_met(begin_word, end_word, pred);
return;
}
while (end_word != text.end())
{
apply_case_if_pred_met(begin_word, end_word, pred);
begin_word = end_word + 1;
end_word = std::find(begin_word, text.end(), ' ');
}
}
public:
TitleCase() = default;
TitleCase(bool ignore_acronyms) : m_ignore_acronyms{ ignore_acronyms } {}
TitleCase(const std::vector<std::string>& exceptions, bool ignore_acronyms = true) : m_exceptions(exceptions), m_ignore_acronyms(ignore_acronyms) {}
void convert(std::string& text);
std::string converted_copy(const std::string& text);
bool is_exception(std::string_view str);
bool is_acronym(std::string_view word);
void ignore_acronyms(bool b) { m_ignore_acronyms = b; }
template<typename T>
void add_exception(T&& exception) { m_exceptions.emplace_back(std::forward<T>(exception)); }
template<typename T>
void remove_exception(T&& exception)
{
m_exceptions.erase(std::remove(m_exceptions.begin(), m_exceptions.end(), std::forward<T>(exception)), m_exceptions.end());
}
void replace_exceptions(const std::vector<std::string>& exceptions)
{
m_exceptions = exceptions;
}
const auto& exceptions()
{
return m_exceptions;
}
};
</code></pre>
<h2>TitleCase.cpp</h2>
<pre><code>#include "TitleCase.h"
#include <algorithm>
#include <cctype>
void TitleCase::apply_title_case(std::string::iterator begin_word, std::string::iterator end_word)
{
*begin_word = std::toupper(*begin_word);
std::for_each(++begin_word, end_word, [](char& c) { c = std::tolower(c); });
}
void TitleCase::convert(std::string & text)
{
if (m_ignore_acronyms)
{
convert_impl(text, [this](std::string_view word) { return !is_exception(word) && !is_acronym(word); });
}
else
{
convert_impl(text, [this](std::string_view word) { return !is_exception(word); });
}
}
std::string TitleCase::converted_copy(const std::string& text)
{
auto text_copy = text;
convert(text_copy);
return text_copy;
}
bool TitleCase::is_exception(std::string_view word)
{
return std::find(m_exceptions.begin(), m_exceptions.end(), word) != m_exceptions.end();
}
bool TitleCase::is_acronym(std::string_view word)
{
return std::all_of(word.begin(), word.end(), [](char c) { return std::isupper(c); });
}
std::string_view TitleCase::get_word(std::string::iterator begin_word, std::string::iterator end_word)
{
const char* begin_word_ptr = &(*begin_word);
std::string_view::size_type word_size = std::distance(begin_word, end_word);
auto word = std::string_view{ begin_word_ptr, word_size };
return word;
}
</code></pre>
| [] | [
{
"body": "<p>First, call it “English Title Case” so it is clear that it is hard-coded for this rule set. A function named <code>TitleCase</code> ought to use the current locale and/or have parameters specifying the language and culture.</p>\n\n<pre><code>void convert(std::string& text);\n</code></pre>\n\n... | {
"AcceptedAnswerId": "197577",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T21:58:27.527",
"Id": "197572",
"Score": "10",
"Tags": [
"c++",
"strings"
],
"Title": "Title Case Converter"
} | 197572 |
<p>I'm writing a simple wrapper for <code>std::unique_ptr</code>, which copies the pointed object when copied.</p>
<p>Unlike <a href="https://codereview.stackexchange.com/questions/103744/deepptr-a-deep-copying-unique-ptr-wrapper-in-c">this wrapper</a>, it properly copies derived classes if
<code>unique_ptr</code> points to a base class.</p>
<p>Also it supports a feature similar to <code>std::visit</code>, which is described below.</p>
<p><sub>(As noted by @Quuxplusone, deep-copying feature resembles that of <code>std::any</code>.)</sub></p>
<hr>
<p>Here's a short description of my class.<br>
<strong>(The implementation is at the bottom of the question.)</strong></p>
<ul>
<li>It supports conventional <code>operator*</code>, <code>operator-></code>, <code>T* get()</code>, and <code>operator bool</code>.</li>
<li>It doesn't have <code>.reset()</code>, but <code>my_obj = {};</code> can be used instead.</li>
<li>Can be copy constructed/assigned. When copied, copies the underlying object.</li>
<li>Can't aquire ownership of an external pointer, and can't release ownership of stored pointer.</li>
<li><p><code>std::make_unique</code>-esque construction: <code>DynStorage<T> my_obj = DynStorage<T>::make(…);</code>.<br>
Can be written as <code>DynStorage<T> my_obj(…);</code> if argument list is not empty.<br>
Example usage:</p>
<pre><code>auto x = DynStorage<int>::make(42);
std::cout << x.get() << '\n'; // Prints 42
</code></pre></li>
<li><p><code>DynStorage<Derived></code> <em>can't</em> be converted to <code>DynStorage<Base></code> (to simplify the implementation).<br>
The only way to make a <code>DynStorage<Base></code> that points to a derived class is to use <code>DynStorage<Base> my_obj = DynStorage<Base>::make<Derived>(…);</code></p></li>
<li><code>const DynStorage<T></code> doesn't allow you to modify the pointed object (unlike <code>unique_ptr</code>).</li>
<li>Pointers to arrays aren't supported.</li>
<li><p>Supports a feature similar to <code>std::visit</code>, but you have to specify every possible visitor function in advance in an (optional) template parameter of <code>DynStorage</code>:</p>
<pre><code>// Assume we have some classes:
struct A {virtual ~A() {}};
struct B : A {};
// Some overloaded (or template) function:
void foo(A) {std::cout << "foo(A)\n";}
void foo(B) {std::cout << "foo(B)\n";}
// And we want to call a correct overload on a pointed object:
int main()
{
auto x = DynStorage<A>::make(); // Makes an instance of A
auto y = DynStorage<A>::make<B>(); // Makes an instance of B
foo(*x); // Prints foo(A)
foo(*y); // Prints foo(A), but we want foo(B)
}
// Here is how we do that:
template <typename BaseT>
struct MyFuncsBase : DynamicStorage::func_base<BaseT>
{
virtual void call_foo(BaseT *) = 0;
using Base = MyFuncsBase;
};
template <typename BaseT, typename DerivedT>
struct MyFuncs : MyFuncsBase<BaseT>
{
void call_foo(BaseT *base) override
{
foo(*DynamicStorage::derived<DerivedT>(base));
}
};
int main()
{
auto x = DynStorage<A,MyFuncs>::make();
auto y = DynStorage<A,MyFuncs>::make<B>();
x.functions().call_foo(x.get()); // prints foo(A)
y.functions().call_foo(y.get()); // prints foo(B)
}
</code></pre></li>
</ul>
<hr>
<h3>The implementation</h3>
<p><strong><code>dynamic_storage.h</code></strong></p>
<pre><code>#ifndef DYN_STORAGE_H_INCLUDED
#define DYN_STORAGE_H_INCLUDED
#include <memory>
#include <type_traits>
#include <utility>
namespace DynamicStorage
{
namespace impl
{
// Type trait to check if A is static_cast'able to B.
template <typename A, typename B, typename = void> struct can_static_cast_impl
: std::false_type {};
template <typename A, typename B> struct can_static_cast_impl<A, B,
std::void_t<decltype(static_cast<B>(std::declval<A>()))>> : std::true_type {};
template <typename A, typename B> inline constexpr bool can_static_cast_v =
can_static_cast_impl<A,B>::value;
// Type trait to check if A is dynamic_cast'able to B.
template <typename A, typename B, typename = void> struct can_dynamic_cast_impl
: std::false_type {};
template <typename A, typename B> struct can_dynamic_cast_impl<A, B,
std::void_t<decltype(dynamic_cast<B>(std::declval<A>()))>> : std::true_type {};
template <typename A, typename B> inline constexpr bool can_dynamic_cast_v =
can_dynamic_cast_impl<A,B>::value;
template <typename A, typename B>
inline constexpr bool can_static_or_dynamic_cast_v =
can_static_cast_v<A,B> || can_dynamic_cast_v<A,B>;
template <typename T> T *get_instance()
{
static T ret;
return &ret;
}
}
// Downcasts a pointer. Attempts to use static_cast, falls back
// to dynamic_cast. If none of them work, fails with a static_assert.
template <typename Derived, typename Base> Derived *derived(Base *ptr)
{
static_assert(impl::can_static_or_dynamic_cast_v<Base*, Derived*>,
"Pointer to derived can't be obtained from pointer to base.");
if constexpr (impl::can_static_cast_v<Base*, Derived*>)
return static_cast<Derived *>(ptr); // This doesn't work if base is virtual.
else
return dynamic_cast<Derived *>(ptr);
}
template <typename B> struct func_base
{
using Base = func_base;
virtual std::unique_ptr<B> copy_(const B *) = 0;
};
template <typename B, typename D> struct default_func_impl : func_base<B> {};
template
<
typename T,
template <typename,typename> typename Functions = default_func_impl
>
class DynStorage
{
static_assert(!std::is_const_v<T>, "Template parameter can't be const.");
static_assert(!std::is_array_v<T>, "Template parameter can't be an array.");
template <typename D> struct Implementation : Functions<T,D>
{
static_assert(impl::can_static_or_dynamic_cast_v<T*, D*>,
"Pointer to derived can't be obtained from pointer to base.");
std::unique_ptr<T> copy_(const T *ptr) override
{
return ptr ? std::make_unique<D>(*derived<const D>(ptr))
: std::unique_ptr<T>();
}
};
using Pointer = std::unique_ptr<T>;
using FuncBase = typename Implementation<T>::Base;
FuncBase *funcs = impl::get_instance<Implementation<T>>();
Pointer ptr;
public:
// Makes a null pointer.
DynStorage() noexcept {}
// Constructs an object of type T from a parameter pack.
template <typename ...P, typename = std::void_t<decltype(T(std::declval<P>()...))>>
DynStorage(P &&... p) : ptr(std::make_unique<T>(std::forward<P>(p)...)) {}
DynStorage(const DynStorage &other)
: funcs(other.funcs), ptr(funcs->copy_(other.ptr.get())) {}
DynStorage(DynStorage &&other) noexcept
: funcs(other.funcs), ptr(std::move(other.ptr)) {}
DynStorage &operator=(const DynStorage &other)
{
ptr = other.funcs->copy_(other.ptr.get());
funcs = other.funcs;
return *this;
}
DynStorage &operator=(DynStorage &&other) noexcept
{
ptr = std::move(other.ptr);
funcs = other.funcs;
return *this;
}
// Constructs an object of type T (by default)
// or a derived type from a parameter pack.
template <typename D = T, typename ...P,
typename = std::void_t<decltype(D(std::declval<P>()...))>>
[[nodiscard]] static DynStorage make(P &&... p)
{
static_assert(!std::is_const_v<D>, "Template parameter can't be const.");
static_assert(!std::is_array_v<D>, "Template parameter can't be an array.");
static_assert(std::is_same_v<D,T> || std::has_virtual_destructor_v<T>,
"Base has to have a virtual destructor.");
DynStorage ret;
ret.ptr = std::make_unique<D>(std::forward<P>(p)...);
ret.funcs = impl::get_instance<Implementation<D>>();
return ret;
}
[[nodiscard]] explicit operator bool() const {return bool(ptr);}
[[nodiscard]] T *get() {return ptr.get();}
[[nodiscard]] const T *get() const {return ptr.get();}
[[nodiscard]] T &operator*() {return *ptr;}
[[nodiscard]] const T &operator*() const {return *ptr;}
[[nodiscard]] T *operator->() {return *ptr;}
[[nodiscard]] const T *operator->() const {return *ptr;}
FuncBase &functions() const {return *funcs;}
};
}
using DynamicStorage::DynStorage;
#endif
</code></pre>
<hr>
<p>Some thoughts:</p>
<ul>
<li>It seems to work, but I'm not sure if I handle all possible exceptions correctly.</li>
<li>I don't like the visiting syntax (especially visitor definitions), but I'm not sure how to improve it.</li>
<li>It seems that copying (and visiting) could be optimized a bit by using function pointers instead of virtual functions, but I'm not sure how to do it elegantly.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T00:03:04.270",
"Id": "380900",
"Score": "0",
"body": "⟪It seems to work, but I'm not sure if I handle all possible exceptions correctly.⟫ Try multiple base classes and virtual base classes. Try non-public base classes, and multipl... | [
{
"body": "<p>That's really neat! I really like the idea of provoking the on-demand instantiation of the polymorphic dispatcher by passing it as a template template parameter.</p>\n\n<p>That being said, I agree with you that the dispatching syntax can be improved quite a bit. </p>\n\n<pre><code>x.functions().ca... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T23:28:52.770",
"Id": "197579",
"Score": "2",
"Tags": [
"c++",
"memory-management",
"c++17"
],
"Title": "Deep-copyable unique_ptr wrapper with std::visit-like feature"
} | 197579 |
<p>I wrote an algorithm that solves this problem but I would love to get some feedback on it (especially since I'm not so confident in my Big \$O\$ skills).</p>
<p>Do you think this is a good quality algorithm? Is it efficient? What would be your impression if you were an interviewer? I really want to improve as a programmer so any help is appreciated!</p>
<pre><code>def lengthOfLongestSubstring(self, word):
longest =0
currentLength = 0
if(len(word) > 0):
currentLength = 1
longest = 1
dict = {word[0] : 0}
i = 1
while i < len(word):
if (dict.has_key(word[i])):
i = dict[word[i]]+1
dict.clear()
if (longest < currentLength):
longest= currentLength
currentLength = 0
else:
dict[word[i]] = i
currentLength = currentLength + 1
i = i + 1
if (longest < currentLength):
longest= currentLength
return longest
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T08:14:10.620",
"Id": "380927",
"Score": "0",
"body": "Welcome to Code Review! What Python version is this written for?"
}
] | [
{
"body": "<p>The algorithmic complexity of your solution is \\$O(N*C)\\$ where \\$N\\$ is the number of characters in the string and \\$C\\$ is the size of the alphabet. Assuming lowercase ASCII characters, that's a linear algorithm and will probably be good enough for most things. That being said, it is possi... | {
"AcceptedAnswerId": "197594",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T07:11:47.050",
"Id": "197589",
"Score": "10",
"Tags": [
"python",
"strings",
"programming-challenge",
"python-2.x"
],
"Title": "Given a string, find the length of the longest substring without repeating characters"
} | 197589 |
<p>I have a table with OHLCV values stored per symbol and I am trying to compute various technical indicators for the same. I am a newbie to Python and this type of application in general.</p>
<p>There are 2 types of indicators from what I have worked on so far:</p>
<ol>
<li>The indicators that only require last N values to get an accurate result such as simple moving average</li>
<li>The indicators that require all the values to get an accurate result such as exponential moving average</li>
</ol>
<p>I want to compute indicators on the symbols only if N values are present. For example a 20 period SMA has a valid value only if you have 20 values for that asset. Here's my attempt which is a lot of spaghetti code in my opinion. How do I structure this to make it better. Thanks</p>
<pre><code>def refresh_indicators(table_name, indicator_key):
"""Compute indicators from the table"""
hmset = {}
#Connect to the database specified by file path
with sqlite3.connect(file_path_15m) as conn:
#Loop through each asset's symbol and internal id for 999 items
for symbol, internal_id in zip(redis_connection.zrange('e3:symbols', 0, 999), redis_connection.zrange('e3:ids', 0, 999)):
#Convert string integer id to integer id
internal_id = int(internal_id)
s = io.StringIO()
#Fetch h,l,c for the current symbol using its internal id
cur = conn.execute('select h,l,c from {} where symbol = ? order by ts'.format(table_name), (internal_id,))
#Convert the cursor into a structured np array
ohlc = np.array(list(cur), dtype=dtype)
h,l,c = ohlc['h'], ohlc['l'], ohlc['c']
#Add a check to exclude any symbol with nan values for its h,l,c
missing = np.isnan(h).all() or np.isnan(l).all() or np.isnan(c).all()
#This dict will store all the indicators for the current symbol
indicators = {}
if not missing:
#Take the last 10 close values and compute the 10 period SMA if the current symbol has atleast 10 values
indicators['sma10'] = func.SMA(c[-10:], 10)[-1] if len(c) >= 10 else None
#Take the last 20 close values and compute the 20 period SMA if the current symbol has atleast 20 values
indicators['sma20'] = func.SMA(c[-20:], 20)[-1] if len(c) >= 20 else None
indicators['sma50'] = func.SMA(c[-50:], 50)[-1] if len(c) >= 50 else None
indicators['sma100'] = func.SMA(c[-100:], 100)[-1] if len(c) >= 100 else None
indicators['sma200'] = func.SMA(c[-200:], 200)[-1] if len(c) >= 200 else None
upper, middle, lower = func.BBANDS(c[-20:], 20, 2)
indicators['lower'] = lower[-1] if len(lower) >=20 else None
indicators['middle'] = middle[-1] if len(middle) >=20 else None
indicators['upper'] = upper[-1] if len(upper) >=20 else None
indicators['trima'] = func.TRIMA(c[-20:], 20)[-1] if len(c) >= 20 else None
indicators['wma'] = func.WMA(c[-10:], 10)[-1] if len(c) >= 10 else None
aroonup, aroondown = func.AROON(h[-15:], l[-15:], 14)
indicators['aroonup'] = aroonup[-1] if len(aroonup) >= 15 else None
indicators['aroondown'] = aroondown[-1] if len(aroondown) >= 15 else None
indicators['aroonosc'] = func.AROONOSC(h[-15:], l[-15:], 14)[-1] if len(h) >= 15 and len(l) >= 15 else None
indicators['cci'] = func.CCI(h[-14:], l[-14:], c[-14:], 14)[-1] if len(h) >= 14 and len(l) >= 14 and len(c) >=14 else None
indicators['mom'] = func.MOM(c[-15:], 14)[-1] if len(c) >= 14 else None
indicators['roc'] = func.ROC(c[-11:], 10)[-1] if len(c) >= 10 else None
indicators['rocr'] = func.ROCR100(c[-11:], 10)[-1] if len(c) >= 10 else None
indicators['ultosc'] = func.ULTOSC(h[-29:], l[-29:], c[-29:], 7, 14, 28)[-1] if len(h) >= 29 and len(l) >= 29 and len(c) >= 29 else None
indicators['willr'] = func.WILLR(h[-14:], l[-14:], c[-14:], 14)[-1] if len(h) >= 14 and len(l) >= 14 and len(c) >= 14 else None
indicators['ema9'] = func.EMA(c, 9)[-1] if len(c) >= 9 else None
indicators['ema10'] = func.EMA(c, 10)[-1] if len(c) >= 10 else None
indicators['ema20'] = func.EMA(c, 20)[-1] if len(c) >= 20 else None
indicators['ema50'] = func.EMA(c, 50)[-1] if len(c) >= 50 else None
indicators['ema100'] = func.EMA(c, 100)[-1] if len(c) >= 100 else None
indicators['ema200'] = func.EMA(c, 200)[-1] if len(c) >= 200 else None
#minimum length needed 2 * period - 1
indicators['dema'] = func.DEMA(c, 9)[-1] if len(c) >= 17 else None
#minimum length needed 3 * period - 2
indicators['tema'] = func.TEMA(c, 9)[-1] if len(c) >= 25 else None
indicators['sar'] = func.SAR(h, l, 0.02, 0.2)[-1]
indicators['kama'] = func.KAMA(c, 20)[-1] if len(c) >= 21 else None
#minimum length needed 2 * period
indicators['adx'] = func.ADX(h, l, c, 14)[-1] if len(h) >= 28 else None
indicators['apo'] = func.APO(c, 10, 20, 1)[-1] if len(c) >= 20 else None
#Take all the values and compute 14 period RSI if the current symbol has atleast 15 values
indicators['rsi'] = func.RSI(c, 14)[-1] if len(c) >= 15 else None
#Round all the computations to 8 digits
indicators = {k:round(v,8) for k,v in indicators.items() if v is not None}
#Convert the indicators from dict to csv format
csv_writer = csv.DictWriter(s, fieldnames = fields, delimiter=',', lineterminator=':')
csv_writer.writerow(indicators)
hmset[symbol] = s.getvalue()
return redis_connection.hmset(indicator_key, hmset) if hmset else None
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T11:51:27.237",
"Id": "380937",
"Score": "2",
"body": "You can use a lamba to *hide* the condition, and add the required length parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T11:53:31.940",... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T08:35:23.013",
"Id": "197591",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"design-patterns"
],
"Title": "Design code to compute technical indicators"
} | 197591 |
<p>I'm trying to learn Functional Programming and I picked <a href="https://www.erlang.org/" rel="nofollow noreferrer">Erlang</a> because I will have to use it eventually. In the meantime, I'm trying to build a simple lexer to stumble upon problems and solve them along the way.</p>
<p>I'm aware that Erlang has <a href="http://erlang.org/doc/man/leex.html" rel="nofollow noreferrer">leex</a> and <a href="http://erlang.org/doc/man/yecc.html" rel="nofollow noreferrer">yeec</a> but this code is just for illustration purposes and teach me the "FP way".</p>
<p>So I would appreciate if someone would give a cursory glance at my initial attempt and tell me their suggestions.</p>
<p>The code below is a simple tokenizer that splits expressions in the form
"<code><number> + <number></code>" into a list of tokens. The general direction I took to solve this problem is as follows:</p>
<p>The <code>tokenize/2</code> funtion is called recursively on a successively shrinking portion of text. When the text is empty, it returns the <em>lexed</em> tokens.</p>
<p>The <code>tokenize/2</code> function first builds a list of functions, each of which, when applied to a portion of text, returns an <code>{ok, {Type, Token}, Text}</code> tuple representing the outcome of the match, the token and the remaining, non matched, portion of the input string.</p>
<p>The <code>tokenize/2</code> function then maps the list of functions, with the expectations that, at each stage, only one match will occur. A <code>HasMatched</code> predicate is built to extract the single match from the list, if any. If a match has indeed been found, the recursive call is made to the function, with arguments being the remaining potion of the text and the new token appended to the list of resulting tokens.</p>
<pre><code>-module(tokenizer).
-export([tokenize/1]).
-include_lib("eunit/include/eunit.hrl").
% tokenize an input string
tokenize(String) -> tokenize_ignore_ws(String).
tokenize_ignore_ws(String) ->
{R, Tokens} = tokenize(String, []),
{R, lists:filter(
fun
({ws, _}) -> false
; (_) -> true
end
, Tokens
)}
.
tokenize([], Tokens) -> {ok, Tokens};
tokenize(String, Tokens) ->
Patterns = [
fun(S) -> match(number, "[0-9]+", S) end,
fun(S) -> match(op, "\\+", S) end,
fun(S) -> match(ws, "\\s+", S) end
],
Matches = lists:map(fun(P) -> P(String) end, Patterns),
HasMatched = fun({error, _, _}) -> false; (_) -> true end,
Match = lists_single_or_default(HasMatched, Matches),
case Match of
{ok, Token, Text} ->
tokenize(Text, Tokens ++ [Token]);
null ->
{error, Tokens}
end
.
% The match/3 function applies the specified Regex to the input String.
% If the match is successful, the function returns the tuple:
% {ok, {Type, Token}, Text} where
% - Token is the matched portion of the input String and
% - Text is the remaining portion of the input String.
%
% If the match fails, the function returns the tuple:
% {error, null, String}
%
match(Type, Regex, String) ->
case re:run(String, Regex, [anchored]) of
{match, Captures} ->
{0, Length } = lists:last(Captures),
Token = string:left(String, Length),
Text = string:substr(String, Length + 1),
{ok, {Type, Token}, Text}
; nomatch -> {error, null, String}
end
.
%% Lists Helper Functions
lists_single(Pred, L) ->
case lists_single_or_default(Pred, L) of
null -> error;
X -> X
end
.
lists_single_or_default(Pred, L) ->
R = lists:filter(Pred, L),
case length(R) of
0 -> null;
1 -> lists:nth(1, R);
_ -> error
end
.
% EUnit
tokenize_number_test() ->
{ok, [{Type, Token}]} = tokenize("123"),
?assert(Type =:= number),
?assert(Token =:= "123")
.
tokenize_op_plus_test() ->
{ok, [{Type, Token}]} = tokenize("+"),
?assert(Type =:= op),
?assert(Token =:= "+")
.
tokenize_empty_expression_test() ->
{ok, []} = tokenize("")
.
tokenize_expression_test() ->
{ok, Tokens} = tokenize("123+456"),
[
{number, "123"},
{op, "+"},
{number, "456"}
] = Tokens
</code></pre>
<p>For instance, in the code above, I felt the need to declare a <code>lists_single_or_default/2</code> function. That's because I'm coming from a C# background. Is there some proper FP way to make the calling code more maintainable/readable with an alternative way?</p>
<p>Another thing I'm interested about is to add <code>{Row, Column}</code> information to each token so as to give more meaningful error messages while tokenizing and, eventually, while parsing later on. For this, I think I will need to carry this information in the <code>{Type, Token, {Row, Column}}</code> <em>tuple</em> that represents a token. But I feel that adding more and more <em>state</em> to the Token will make the code more and more difficult to read and maintain.</p>
<p>I'm aware that FP makes extensive use of recursion. For instance, the canonical way to implement the Fibbonacci suite is as follows:</p>
<pre><code>fac(0) -> 1;
fac(1) -> 1;
fac(N) -> N * fac(N - 1).
</code></pre>
<p>However, I have searched about potential for <em>stack overflows</em> while running recursive functions and I found that most functional programming languages make use of <em>Tail Call Optimization</em> in order to reuse the last stack frame while possible.</p>
<p>It seems, unfortunately, that the canonical implementation of the Fibonaci suite shown above does not lend itself to being optimized that way. Is there a way to inspect the stack in Erlang and, in the context of my <code>tokenize/2</code> method, is is possible to use another algorithm that does not involve recursion ? Is there a way to adapt my algorithm so that is lends itself to being optimized ?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T10:34:39.273",
"Id": "197592",
"Score": "2",
"Tags": [
"parsing",
"functional-programming",
"reinventing-the-wheel",
"erlang"
],
"Title": "A simple tokenizer in Erlang"
} | 197592 |
<p>This is a followup to a previous <a href="https://codereview.stackexchange.com/q/196628/146901">question</a> of mine on same subject.</p>
<h3>Context</h3>
<p>I want to have a tool that allows to simulate as much as possible a C++ standard container for a multidimensional contiguous array whose sizes are only known at run time. That immediately means that <code>std::arrays</code> are off (compile time sizes), as are vectors of vectors (not contiguous data). That also means that the common solution multi_array(i, j, k) is also off because of no natural iterators and direct members.</p>
<p>Previous review have shown that is is impossible to build conformant containers and iterators over <em>views</em> of data (Refs: <a href="http://www.gotw.ca/publications/mill09.htm" rel="nofollow noreferrer">When Is a Container Not a Container?</a> and <a href="http://ericniebler.com/2015/01/28/to-be-or-not-to-be-an-iterator/" rel="nofollow noreferrer">To Be or Not to Be (an Iterator)</a>), so I have followed the given advice and tried to follow the proxy pattern. I have also tried to better explain in comments how the different classes are supposed to be used.</p>
<h3>Code:</h3>
<pre><code>#pragma once
#include <type_traits>
#include <algorithm>
#include <exception>
#include <stdexcept>
#include <memory>
#include <utility>
#include <iterator>
#include <array>
#include <vector>
/********************************
This intends to provide a general use multi dimensional view over a
1-D array. Public API classes:
template <class T, int dims, class Allocator = allocator<T> >
class Array: public ArrayBase<T, dims,
typename allocator_traits<Allocator>::size_type,
typename allocator_traits<Allocator>::difference_type>
This is a quasi container in the sense that it holds the internal array in
a member vector. But it is only a proxy container because it pretends that
its elements are Row objects
Array can be initialized from a raw array along with its dimensions, and
it will hold a copy of the original data. It supports copy/move/swap semantics
from another Array or copy semantics from any ArrayBase
template <class T, int dims, class size_type = size_t,
class difference_type = ptrdiff_t>
class View : public ArrayBase<T, dims, size_type, difference_type> {
This a a View over an external raw array which is expected to have a lifetime
at least as long as the view. It will also pretends that its elements are Row
objects.
View can be initialized from a raw array and its dimensions, and will only
keep a raw pointer over the original array. It supports copy semantics from
any ArrayBase. Views are swappable, but this only change where each view
points to
template <class T, int dims, class size_type, class difference_type>
class Row : public ArrayBase<T, dims, size_type, difference_type>
This class represents a subarray of an Array, a View or another Row. It can
only be created as an element of its parent. Rows can be copied, or moved
from any ArrayBase. Rows are swappable. Operator & on a row returns an iterator.
template <class T, int dims, class size_type, class difference_type>
class ArrayBase: ElementAccessor<T, size_type, difference_type,
size_type, dims>
ArrayBase is the base class of Array, View and ArrayBase. It contains all
the logic of element access and iteration. Its iterators pretend to be
random access iterators, but are only proxy iterators. That is quite enough
for for loops with container syntax, and iterator arithmetics, but usage with
standard algorithms (sort, shuffle, etc.) cannot be guaranteed
template <class T, class Allocator = std::allocator<T> >
class ArrayBuilder;
This is only a utility class that knows how to build Array of View objects.
It can save some boiler plate template declaration by declaring the types
once at builder initialization, mainly when using not default allocators,
size_type or difference_type.
********************************/
namespace DynArray {
using std::allocator;
using std::allocator_traits;
//Forward declarations
template <class T, int dims, class size_type, class difference_type,
bool cnst = false, bool rev=false> class Iterator;
template <class T, int dims, class size_type, class difference_type>
class Row;
namespace {
/* private utility class to allow specialization of element access
through operator[] or operator *
*/
template <class T, class size_type, class difference_type,
class index_type, int dims> class ElementAccessor {
protected:
Row<T, dims - 1, size_type, difference_type> getElt(T* arr,
size_type *sizes, size_type rowsize, index_type i) {
Row<T, dims - 1, size_type, difference_type> child(
arr + rowsize * i,
sizes + 1, rowsize / sizes[1]);
return child;
}
const Row<T, dims - 1, size_type, difference_type> getConstElt(T* arr,
size_type *sizes, size_type rowsize, index_type i) {
Row<T, dims - 1, size_type, difference_type> child(
arr + rowsize * i,
sizes + 1, rowsize / sizes[1]);
return child;
}
};
// specialization for dims == 1: elements are actual T
template <class T, class size_type, class difference_type,
class index_type> class ElementAccessor<T, size_type,
difference_type, index_type, 1> {
protected:
T& getElt(T* arr, size_type *sizes, size_type rowsize,
index_type i) {
return arr[i];
}
const T& getConstElt(T* arr, size_type *sizes,
size_type rowsize, index_type i) {
return arr[i];
}
};
}
// Base: contains the data and types and manages access to elements
// and sub arrays
template <class T, int dims, class size_type, class difference_type>
class ArrayBase: ElementAccessor<T, size_type, difference_type,
size_type, dims> {
public:
using iterator = typename Iterator<T, dims, size_type,
difference_type, 0, 0>;
using const_iterator = typename Iterator<T, dims, size_type,
difference_type, 1, 0>;
typedef typename std::conditional<dims == 1, T,
Row<T, dims - 1, size_type, difference_type>>::type value_type;
typedef typename std::conditional<dims == 1, T&,
value_type>::type reference;
// reference is indeed a proxy to real data when dims != 1
using reverse_iterator = typename Iterator<T, dims, size_type,
difference_type, 0, 1>;
using const_reverse_iterator = typename Iterator<T, dims, size_type,
difference_type, 1, 1>;
protected:
T* arr; // underlying array for the data
size_type *sizes; // array of dimensions of the nD array
size_type rowsize; // cached size of a top level row
// protected ctor called from subclasses
ArrayBase(T* arr, size_type* sizes, size_type rowsize)
: arr(arr), sizes(sizes), rowsize(rowsize) {}
// pseudo-assignment from subclasses
void load(T* arr, size_type *sizes, size_type rowsize) {
this->arr = arr;
this->sizes = sizes;
this->rowsize = rowsize;
}
public:
virtual ~ArrayBase() = default;
// access to member
reference operator[] (size_type i) noexcept {
return getElt(arr, sizes, rowsize, i);
}
const reference operator[] (size_type i) const noexcept {
return getConstElt(arr, sizes, rowsize, i);
}
// access to internal data, arr and sizes and number of dimensions
size_type size(size_type i) const {
if (i >= dims) {
throw std::out_of_range("Illegal dimension");
}
return sizes[i];
}
size_type size() const noexcept {
return sizes[0];
}
size_type tot_size() const noexcept {
return sizes[0] * rowsize;
}
T* data() noexcept {
return arr;
}
const T* data() const noexcept {
return arr;
}
constexpr int getdims() const noexcept {
return dims;
}
// iterators
iterator begin() {
return iterator(arr, sizes, rowsize);
}
iterator end() {
iterator tmp = begin();
tmp += sizes[0];
return tmp;
}
const_iterator begin() const {
return cbegin();
}
const_iterator end() const {
return cend();
}
const_iterator cbegin() const {
return const_iterator(arr, sizes, rowsize);
}
const_iterator cend() const {
const_iterator tmp = cbegin();
tmp += sizes[0];
return tmp;
}
reverse_iterator rbegin() {
reverse_iterator tmp = rend();
tmp -= sizes[0];
return tmp;
}
reverse_iterator rend() {
return reverse_iterator(arr, sizes, rowsize);
}
const_reverse_iterator rbegin() const {
return rcbegin();
}
const_reverse_iterator rend() const {
return rcend();
}
const_reverse_iterator rcbegin() const {
const_reverse_iterator tmp = rend();
tmp -= sizes[0];
return tmp;
}
const_reverse_iterator rcend() const {
return const_reverse_iterator(arr, sizes, rowsize);
}
};
// Row represents a sub-array. Handles copying, moving and swapping rows
// can only be created by an ElementAccessor
template <class T, int dims, class size_type, class difference_type>
class Row : public ArrayBase<T, dims, size_type, difference_type> {
protected:
using ArrayBase::arr;
using ArrayBase::sizes;
using ArrayBase::rowsize;
Row(T* arr, size_type* sizes, size_type rowsize)
: ArrayBase<T, dims, size_type, difference_type>(arr,
sizes, rowsize) {}
public:
using base = ArrayBase<T, dims, size_type, difference_type>;
/* copy/move assignment (construction can only be from an ElementAccessor)
Programmers must use a view or a reference to point to a row, or an
Array to get a copy.
Swap operation is also possible */
Row& operator = (const base& src) {
if (tot_size() != src.tot_size()) {
throw std::logic_error("Wrong sizes");
}
for (size_type i = 0; i < tot_size(); i++) {
arr[i] = src.data()[i];
}
return *this;
}
Row& operator = (base&& src) {
if (tot_size() != src.tot_size()) {
throw std::logic_error("Wrong sizes");
}
for (size_type i = 0; i < tot_size(); i++) {
arr[i] = std::move(src.data()[i]);
}
return *this;
}
Iterator<T, dims + 1, size_type, difference_type, 0, 0> operator & () {
return Iterator<T, dims + 1, size_type,difference_type,
0, 0>(arr, sizes - 1, sizes[0] * rowsize);
}
Iterator<T, dims + 1, size_type, difference_type, 1, 0> operator & () const {
return Iterator<T, dims + 1, size_type, difference_type,
1, 0>(arr, sizes - 1, sizes[0] * rowsize);
}
// 1 argument swap allows the other member to be any ArrayBase
void swap(ArrayBase& other) {
using std::swap;
if (tot_size() != other.tot_size()) {
throw std::logic_error("Wrong sizes");
}
for (size_type i = 0; i < tot_size(); i++) {
swap(arr[i], other.data()[i]);
}
}
friend class ElementAccessor<T, size_type, difference_type,
size_type, dims + 1>;
friend class ElementAccessor<T, size_type, difference_type,
difference_type, dims + 1>;
};
// 2 arguments swap between Rows
template <class T, int dims, class size_type, class difference_type>
void swap(Row<T, dims, size_type, difference_type>& first,
Row<T, dims, size_type, difference_type>& second) {
first.swap(second);
}
namespace {
/* private auxilliary functions to build a sizes array and
compute total sizes when given the dimensions */
template <class size_type, class...U>
size_type calc_size(size_type *sizes, size_type first,
U...others) {
if (sizes != nullptr) *sizes = first;
return first * calc_size<size_type>(sizes + 1, others...);
}
template<class size_type>
size_type calc_size(size_type *sizes, size_type first) {
if (sizes != nullptr) *sizes = first;
return first;
}
}
// View is a top-level nD array over an existing raw array - no ownership
template <class T, int dims, class size_type = size_t,
class difference_type = ptrdiff_t>
class View : public ArrayBase<T, dims, size_type, difference_type> {
public:
using base = ArrayBase<T, dims, size_type, difference_type>;
private:
using ArrayBase::arr;
using ArrayBase::sizes;
using ArrayBase::rowsize;
// private array to hold the actual dimensions
// constraint: sizes shall point to _sizes
size_type _sizes[dims];
public:
/* public ctors, assignment operators and swap.
Only copy semantics, because assignment only changes where the
view points to, not the underlying data */
template <class...U,
typename = std::enable_if<dims == sizeof...(U)>::type>
View(T* arr, U...sz): base(arr, _sizes, 0) {
size_t tot = calc_size<size_type>(sizes, sz...);
rowsize = tot / sizes[0];
}
View(const base& other) :
ArrayBase<T, dims, size_type, difference_type>(other) {
std::copy(sizes, sizes + dims, _sizes);
sizes = _sizes;
}
View(const View& other) :
ArrayBase<T, dims, size_type, difference_type>(other) {
std::copy(sizes, sizes + dims, _sizes);
sizes = _sizes;
}
View& operator = (const base& other) {
ArrayBase.operator = (other);
std::copy(sizes, sizes + dims, _sizes);
sizes = _sizes;
}
void swap(View& other) {
using std::swap;
swap(_sizes, other._sizes);
T *tmparr = arr;
size_type tmprs = rowsize;
ArrayBase::operator = (other);
other.load(tmparr, sizes, tmprs);
sizes = _sizes;
}
};
template <class T, int dims, class size_type = size_t,
class difference_type = ptrdiff_t>
void swap(View<T, dims, size_type, difference_type>& first,
View<T, dims, size_type, difference_type>& second) {
first.swap(second);
}
// Full array, holds (a copy of) the underlying data
template <class T, int dims, class Allocator = allocator<T> >
class Array : public ArrayBase<T, dims,
typename allocator_traits<Allocator>::size_type,
typename allocator_traits<Allocator>::difference_type> {
public:
using size_type = typename allocator_traits<Allocator>::size_type;
using difference_type =
typename allocator_traits<Allocator>::difference_type;
private:
using base = ArrayBase<T, dims,
typename allocator_traits<Allocator>::size_type,
typename allocator_traits<Allocator>::difference_type>;
using ArrayBase::arr;
using ArrayBase::sizes;
using ArrayBase::rowsize;
Allocator alloc; // internal allocator
size_type _sizes[dims];
std::vector<T, Allocator> _arr;
template<class...U>
void init(size_type first, U... others) {
sizes = _sizes;
size_t tot = calc_size<size_type>(sizes, first, others...);
rowsize = tot / sizes[0];
if (arr == nullptr) {
_arr.assign(tot, T());
}
else {
_arr.assign(arr, arr + tot);
}
this->arr = _arr.data();
}
public:
template<class...U,
typename = std::enable_if<sizeof...(U)+1 == dims>::type>
Array(T* arr, Allocator alloc, size_type first, U... others)
: base(arr, nullptr, 0), alloc(alloc), _arr(this->alloc) {
init(first, others...);
}
template<class...U,
typename = std::enable_if<sizeof...(U)+1 == dims>::type>
Array(T* arr, size_type first, U... others)
: base(arr, nullptr, 0), _arr(this->alloc) {
init(first, others...);
}
template<class...U,
typename = std::enable_if<sizeof...(U)+1 == dims>::type>
Array(Allocator alloc, size_type first, U... others)
: base(nullptr, nullptr, 0), alloc(alloc), _arr(this->alloc) {
init(first, others...);
}
template<class...U,
typename = std::enable_if<sizeof...(U)+1 == dims>::type>
Array(size_type first, U... others)
: base(nullptr, nullptr, 0), _arr(this->alloc) {
init(first, others...);
}
// copy/move ctors and assignment from another array
// TODO: implement move semantics from an ArrayBase
Array(const Array& other)
: ArrayBase(other), alloc(other.alloc),
_arr(other._arr) {
std::copy(sizes, sizes + dims, _sizes);
arr = _arr.data();
sizes = _sizes;
}
Array(Array&& other) : ArrayBase(other), alloc(other.alloc),
_arr(std::move(other._arr)) {
std::copy(sizes, sizes + dims, _sizes);
arr = _arr.data();
sizes = _sizes;
}
Array(const ArrayBase& other) : ArrayBase(other), alloc(),
_arr(arr, arr + rowsize * sizes[0]) {
std::copy(sizes, sizes + dims, _sizes);
arr = _arr.data();
sizes = _sizes;
}
Array& operator = (const Array& other) {
load(other);
if (std::allocator_traits(
Allocator)::propagate_on_container_copy_assignment) {
alloc = other.alloc;
}
std::copy(sizes, sizes + dims, _sizes);
_arr.assign(other._arr);
arr = _arr.data();
sizes = _sizes;
return *this;
}
Array& operator = (Array&& other) {
ArrayBase::operator = (other);
if (std::allocator_traits<
Allocator>::propagate_on_container_move_assignment::value) {
alloc = other.alloc;
}
std::copy(sizes, sizes + dims, _sizes);
_arr = std::move(other._arr);
arr = _arr.data();
sizes = _sizes;
return *this;
}
Array& operator = (const ArrayBase& other) {
ArrayBase::operator = (other);
std::copy(sizes, sizes + dims, _sizes);
_arr.assign(arr, arr + sizes[0] * rowsize);
arr = _arr.data();
sizes = _sizes;
return *this;
}
};
/* syntactic sugar to help template deduction and avoid some (re-)typing
mainly usefull for non default allocators */
template <class T, class Allocator = std::allocator<T> >
class ArrayBuilder {
public:
using size_type = typename allocator_traits<Allocator>::size_type;
using difference_type
= typename allocator_traits<Allocator>::difference_type;
private:
Allocator alloc;
public:
ArrayBuilder(const Allocator& alloc = Allocator()) : alloc(alloc) {}
template <class ...U, int dims = sizeof...(U)+1>
View<T, dims, size_type, difference_type> dynUseArray(T* arr,
size_type first, U...others) {
return View<T, dims, size_type, difference_type>(arr, first,
others...);
}
template <class ...U, int dims = sizeof...(U)+1>
Array<T, dims, Allocator> dynCopyArray(T* arr,
size_type first, U...others) {
return Array<T, dims, Allocator>(arr, alloc,
first, others...);
}
template <class ...U, int dims = sizeof...(U)+1>
Array<T, dims, Allocator> dynBuildArray(size_type first, U...others) {
return Array<T, dims, Allocator>(alloc, first, others...);
}
};
// iterator if cnst == 0 or const_iterator if cnst == 1, U is the value_type
template <class T, int dims, class size_type,
class difference_type, bool cnst, bool rev>
class Iterator: public ElementAccessor<T, size_type, difference_type,
difference_type, dims>{
public:
using value_type = typename std::conditional<cnst,
typename std::conditional<dims == 1, const T,
const Row<T, dims-1, size_type, difference_type>>::type,
typename std::conditional<dims == 1, T, Row<T, dims - 1, size_type,
difference_type>>::type>::type;
using reference = typename std::conditional < dims == 1,
value_type&, value_type>::type;
using iterator_category = typename std::random_access_iterator_tag;
private:
struct Proxy {
value_type elt;
Proxy(value_type&& elt) : elt(elt) {}
value_type* operator ->() {
return std::addressof(elt);
}
};
T* arr;
size_type *sizes;
size_type rowsize;
Iterator(T* arr, size_type *sizes, size_type rowsize) :
arr(arr), sizes(sizes), rowsize(rowsize) {}
template<bool x=false>
reference getXElt(difference_type i) {
return getElt(arr - rowsize * (rev ? 1 : 0), sizes, rowsize, i);
}
template<>
reference getXElt<true>(difference_type i) {
return getConstElt(arr - rowsize * (rev ? 1 : 0), sizes, rowsize, i);
}
void add(difference_type i) {
arr += (rev ? -i : i) * rowsize ;
}
using iterator = Iterator<T, dims, size_type, difference_type, cnst, rev>;
public:
using pointer = Proxy;
// a default ctor (to mimic standard iterators)
Iterator(): arr(nullptr), sizes(nullptr), rowsize(0) {}
//convert an (non const) iterator to a const_iterator
template <class X = T, typename = std::enable_if<cnst == 1>::type>
Iterator(const Iterator<T, dims, size_type, difference_type,
1 - cnst, rev>& other)
: arr(other.arr), sizes(other.sizes), rowsize(other.rowsize) {}
// all operations of an iterator
reference operator * () {
return getXElt(0) ;
}
pointer operator -> () {
return Proxy(getXElt(0));
}
const reference operator * () const {
return getConstElt(arr - rowsize * (rev ? 1 : 0), sizes, rowsize, 0);
}
const pointer operator -> () const {
return Proxy(getXElt(0));
}
iterator& operator ++() {
this->add(1);
return *this;
}
iterator& operator --() {
this->add(-1);
return *this;
}
iterator operator ++(int) {
iterator tmp = *this;
this->add(1);
return tmp;
}
iterator operator --(int) {
iterator tmp = *this;
this->add(-1);
return tmp;
}
iterator& operator += (difference_type i) {
this->add(i);
return *this;
}
iterator operator + (difference_type i) {
iterator tmp = *this;
tmp.add(i);
return tmp;
}
iterator operator -= (difference_type i) {
return operator += (-i);
}
iterator operator - (difference_type i) {
return operator + (-i);
}
value_type operator [] (difference_type i) {
return *(*this + i);
}
const value_type operator [] (difference_type i) const {
return *(*this + i);
}
// comparisons are allowed between const and non const iterators
template <bool c>
bool operator ==(const Iterator<T, dims, size_type,
difference_type, c, rev>& other) const {
return (arr == other.arr) && (sizes == other.sizes)
&& (rowsize == other.rowsize);
}
template <bool c>
bool operator != (const Iterator<T, dims, size_type,
difference_type, c, rev>& other) const {
return !operator ==(other);
}
template <bool c>
bool operator <(const Iterator<T, dims, size_type,
difference_type, rev, c>& other) const {
return arr < other.arr;
}
template <bool c>
bool operator >(const Iterator<T, dims, size_type,
difference_type, c, rev>& other) const {
return arr > other.arr;
}
template <bool c>
bool operator <=(const Iterator<T, dims, size_type,
difference_type, c, rev>& other) const {
return !operator >(other);
}
template <bool c>
bool operator >=(const Iterator<T, dims, size_type,
difference_type, c, rev>& other) const {
return !operator <(other);
}
friend class ArrayBase<T, dims, size_type, difference_type>;
friend class Iterator<T, dims, size_type,
difference_type, !cnst, rev>;
friend class Row<T, dims - 1, size_type, difference_type>;
};
}
</code></pre>
<p>For reference here are the unit test classes for MSCV 2017 test framework</p>
<pre><code>#include "stdafx.h"
#include "CppUnitTest.h"
#include "../mdynarray/mdynarray.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
using namespace DynArray;
TEST_CLASS(UnitTest1)
{
public:
/* creation of a view shall point to original raw array */
TEST_METHOD(useArr)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
l = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
Assert::AreSame(dynarray[i][j][k], arr[l++]);
}
}
}
}
/* Assignment of a row from a second view */
TEST_METHOD(rowAssign) {
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
View<int, 3> array {arr, 3, 4, 5};
int arr2[20];
l = 64;
for (int&i : arr) {
i = l++;
}
View<int, 2> array2{ arr2, 4, 5 };
array[1] = array2;
/* controls that:
- values have been copied
- indices still point to original raw array
*/
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
Assert::AreNotSame(array[1][i][j], array2[i][j]);
Assert::AreEqual(array[1][i][j], array2[i][j]);
Assert::AreSame(arr[20 + 5 * i + j], array[1][i][j]);
}
}
}
// swap Rows
TEST_METHOD(rowSwap) {
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
View<int, 3> array {arr, 3, 4, 5};
swap(array[0], array[2]);
l = 40;
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
Assert::AreSame(arr[k++], array[0][i][j]);
Assert::AreEqual(l++, array[0][i][j]);
}
}
}
//Assignement of a view from a Row or another View
TEST_METHOD(viewAssign) {
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
View<int, 3> array {arr, 3, 4, 5};
View<int, 2> arr0{ array[0] };
l = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
Assert::AreSame(arr[l++], arr0[i][j]);
}
}
View<int, 2> arr2 = array[2];
arr0 = arr2;
l = 40;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
Assert::AreSame(arr[l++], arr0[i][j]);
}
}
}
// swap views
TEST_METHOD(viewSwap) {
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
View<int, 3> array {arr, 3, 4, 5};
View<int, 2> arr0{ array[0] };
View<int, 2> arr2 = array[2];
swap(arr0, arr2);
l = 40;
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
Assert::AreSame(arr[l++], arr0[i][j]);
Assert::AreSame(arr[k++], arr2[i][j]);
}
}
}
TEST_METHOD(copyArr)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynCopyArray(arr, 3, 4, 5);
l = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
Assert::AreEqual(dynarray[i][j][k], arr[l]);
Assert::AreNotSame(dynarray[i][j][k], arr[l]);
l++;
}
}
}
}
TEST_METHOD(buildArr)
{
ArrayBuilder<int> builder;
auto dynarray = builder.dynBuildArray(3, 4, 5);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
Assert::AreEqual(dynarray[i][j][k], 0);
}
}
}
}
TEST_METHOD(copyCtor)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
Array<int, 3> dyn2{ dynarray };
l = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
Assert::AreEqual(dyn2[i][j][k], arr[l]);
Assert::AreNotSame(dyn2[i][j][k], arr[l]);
l++;
}
}
}
}
TEST_METHOD(moveCtor)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynCopyArray(arr, 3, 4, 5);
int *ix = dynarray.data();
auto dyn2 = std::move(dynarray);
Assert::AreEqual(ix, dyn2.data());
l = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
Assert::AreEqual(dyn2[i][j][k], arr[l]);
l++;
}
}
}
}
TEST_METHOD(copyAssign)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
auto dyn2 = builder.dynBuildArray(3, 4, 5);
dyn2 = dynarray;
l = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
Assert::AreEqual(dyn2[i][j][k], arr[l]);
Assert::AreNotSame(dyn2[i][j][k], arr[l]);
l++;
}
}
}
}
TEST_METHOD(moveAssign)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynCopyArray(arr, 3, 4, 5);
int *ix = dynarray.data();
auto dyn2 = builder.dynBuildArray(3, 4, 5);
dyn2 = std::move(dynarray);
l = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
Assert::AreEqual(dyn2[i][j][k], arr[l]);
l++;
}
}
}
Assert::AreEqual(ix, dyn2.data());
}
TEST_METHOD(nonConstIter)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
l = 0;
for (auto& it1 : dynarray) {
for (auto& it2 : it1) {
for (auto& it3 : it2) {
Assert::AreSame(it3, arr[l]);
l++;
it3 = l; // control it is not const...
}
}
}
}
TEST_METHOD(constIter)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
l = 0;
for (auto it1 = dynarray.cbegin(); it1 != dynarray.cend(); it1++) {
for (auto it2 = it1->cbegin(); it2 != it1->cend(); it2++) {
for (auto it3 = it2->cbegin(); it3 != it2->cend(); it3++) {
Assert::AreSame(*it3, arr[l]);
l++;
// *it3 = l; // does not compile
}
}
}
}
TEST_METHOD(convConstIterator)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
auto it = dynarray.begin();
Array<int, 3>::const_iterator cit = it;
//it = (MDynArray<int, 3>::iterator) cit; // does not compile
it += 1;
cit += 1;
Assert::IsTrue(it > dynarray.begin());
Assert::IsTrue(it == cit);
Assert::IsTrue(cit == it);
}
TEST_METHOD(revIterator)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
l = 0;
for (auto it1 = dynarray.rbegin(); it1 != dynarray.rend(); it1++) {
for (auto it2 = it1->rbegin(); it2 != it1->rend(); it2++) {
for (auto it3 = it2->rbegin(); it3 != it2->rend(); it3++) {
Assert::AreSame(*it3, arr[59 - l]);
l++;
*it3 = l; // control non constness
}
}
}
}
TEST_METHOD(rowToIter)
{
ArrayBuilder<int> builder;
int arr[60];
int l = 0;
for (int& i : arr) {
i = l++;
}
auto dynarray = builder.dynUseArray(arr, 3, 4, 5);
l = 0;
auto row = dynarray[1];
auto it = &row - 1;
Assert::AreSame(arr[0], it[0][0][0]);
}
};
}
</code></pre>
<p>I admit it is a rather large piece of code...</p>
| [] | [
{
"body": "<p>I found a number of compilation issues using GCC 8 (with <code>-std=c++2a</code>). I'm guessing you're using an older or less-conformant compiler. Here's what I had to change.</p>\n\n<hr>\n\n<p>The <code>typename</code> keyword isn't wanted here (where it knows that <code>Iterator<></code>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T11:18:54.707",
"Id": "197595",
"Score": "4",
"Tags": [
"c++",
"array",
"iterator",
"collections"
],
"Title": "General use multi-dimensional container using operator[]"
} | 197595 |
<p>The McCabe code complexity of the following function is 19 as found by <code>pytest --mccabe test.py</code> (from my toy-project <a href="https://github.com/MartinThoma/mpu/tree/15e749184605f6235ed772453bdfb717e87bb1f2" rel="nofollow noreferrer"><code>mpu</code></a>). While I agree that this function is length and likely will become longer in future, I don't know how to improve the situation.</p>
<h2>What it does</h2>
<p>The code <code>mpu.io.write(filepath)</code> is a convenience function for writing a few common file formats.</p>
<h2>Code</h2>
<p>This code should work in Python 2 and 3.</p>
<pre><code>def write(filepath, data, **kwargs):
"""
Write a file.
Supported formats:
* CSV
* JSON, JSONL
* pickle
Parameters
----------
filepath : str
Path to the file that should be read. This methods action depends
mainly on the file extension.
data : dict or list
Content that should be written
kwargs : dict
Any keywords for the specific file format.
Returns
-------
data : str or bytes
"""
if filepath.lower().endswith('.csv'):
kwargs_open = {'newline': ''}
mode = 'w'
if sys.version_info < (3, 0):
kwargs_open.pop('newline', None)
mode = 'wb'
with open(filepath, mode, **kwargs_open) as fp:
if 'delimiter' not in kwargs:
kwargs['delimiter'] = ','
if 'quotechar' not in kwargs:
kwargs['quotechar'] = '"'
with open(filepath, 'w') as fp:
writer = csv.writer(fp, **kwargs)
writer.writerows(data)
return data
elif filepath.lower().endswith('.json'):
with io_stl.open(filepath, 'w', encoding='utf8') as outfile:
if 'indent' not in kwargs:
kwargs['indent'] = 4
if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = True
if 'separators' not in kwargs:
kwargs['separators'] = (',', ': ')
if 'ensure_ascii' not in kwargs:
kwargs['ensure_ascii'] = False
str_ = json.dumps(data, **kwargs)
outfile.write(to_unicode(str_))
elif filepath.lower().endswith('.jsonl'):
print(filepath)
with io_stl.open(filepath, 'w', encoding='utf8') as outfile:
kwargs['indent'] = None # JSON has to be on one line!
if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = True
if 'separators' not in kwargs:
kwargs['separators'] = (',', ': ')
if 'ensure_ascii' not in kwargs:
kwargs['ensure_ascii'] = False
for line in data:
str_ = json.dumps(line, **kwargs)
outfile.write(to_unicode(str_))
outfile.write(u'\n')
elif filepath.lower().endswith('.pickle'):
if 'protocol' not in kwargs:
kwargs['protocol'] = pickle.HIGHEST_PROTOCOL
with open(filepath, 'wb') as handle:
pickle.dump(data, handle, **kwargs)
elif (filepath.lower().endswith('.yml') or
filepath.lower().endswith('.yaml')):
raise NotImplementedError('YAML is not supported, because you need '
'PyYAML in Python3. '
'See '
'https://stackoverflow.com/a/42054860/562769'
' as a guide how to use it.')
elif (filepath.lower().endswith('.h5') or
filepath.lower().endswith('.hdf5')):
raise NotImplementedError('HDF5 is not supported. See '
'https://stackoverflow.com/a/41586571/562769'
' as a guide how to use it.')
else:
raise NotImplementedError('File \'{}\' is not known.'.format(filepath))
</code></pre>
| [] | [
{
"body": "<p>You’ve got your code split into various sections; why not make the sections their own methods?</p>\n\n<pre><code>if filepath.lower().endswith('.csv'):\n return _write_csv(filepath, data, kwargs)\nelif filepath.lower().endswith('.json'):\n return _write_json(filepath, data, kwargs)\nelif filepa... | {
"AcceptedAnswerId": "197632",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T11:47:37.170",
"Id": "197597",
"Score": "2",
"Tags": [
"python",
"json",
"file",
"csv",
"cyclomatic-complexity"
],
"Title": "Convenience function for writing files in CSV, JSON, etc"
} | 197597 |
<p>I'm visiting a functional programming course at my university which has a small project for examination. The language we are using is clojure and the contents of the lecture have mostly been about it's syntax, rather than the benefits and paradigms of functional programming. Our lecturer doesn't seem to be too harsh when it comes to grading but we are still very unsure if our program fully matches the requirements of functional programming. Here are some of our questions:</p>
<ol>
<li>Can you mess up that badly when it comes to functional programming or are some things already ensured when using clojure?</li>
<li>We have some functions with random numbers to randomize the output (e.g. "create-star"). This makes them "unpure" because output with the same input is different every time. If we would pass the random numbers via the parameters instead it would make the code much less readable and clear. Is sticking to the parameters of functional programming more important than visibility? <em>(If we would follow that train of thought we would even have to create and pass all random values in the "update-state" functions parameters as it is the outer-most function to be called and would be unpure aswell if it contained randomness.)</em></li>
<li>The framework internally uses an atom for the state variable which we modify in some methods. But we always pass it as parameter and return it, so we don't use global variables. Does this violate the principle of immutable objects?</li>
<li>Is there anything else in our code below that violates functional programming principles?</li>
</ol>
<p>Below is the main part of our code. The full project can be found at <a href="https://github.com/Niggls/rocket_game/tree/3efd103c924aa544cbd577d7d568bf6888912b7b" rel="noreferrer">https://github.com/Niggls/rocket_game</a>. It's a small game where you have to control a rocket to avoid incoming meteors. We are using the "quil" library to draw the contents of the game screen. It works with a "state" variable that handles all data of objects on the screen. The main parts are the "draw" function which creates the output and the "update-state" function which evaluates all of our functions for every frame. Both of these are at the bottom.</p>
<pre><code>(ns rocket-game.core
(:require [quil.core :as q]
[quil.middleware :as m]))
(defn star-color-index [x]
(if (< x 12)
0
(if (< x 15)
2
3)))
(defn create-star [y]
{:x (rand-int (q/width))
:y (rand-int y)
:size (+ (rand-int 5) 1)
:speed (+ (rand-int 3) 1)
:color (star-color-index (rand-int 20))})
;; function for reset state
(defn reset-state-variable [state]
{:rocket {:image (q/load-image "images/rocket.png")
:x 260
:y 340
:dir 0}
:background (q/load-image "images/stars.jpg")
:fires []
:smoke []
:score 0
:stars (:stars state)
:highscore (if ( > (:score state) (:highscore state))
(:score state)
(:highscore state))
:gameOver true
:meteors []
:bonus []})
;; setup: here we define our global state variable
;; # --> anonymous function
(defn setup []
;; these two lines, a map (data structure) is added in step 1-6
{:rocket {:image (q/load-image "images/rocket.png")
:x 260
:y 340
:dir -1}
:background (q/load-image "images/stars.jpg")
:fires []
:score 0
:smoke []
:highscore 0
:stars (take 150 (repeatedly #(create-star (q/height))))
:gameOver false
:meteors []
:bonus []})
;;;; helper methods;;;;;;;;;;;;;;;;;;;;;;;;
(defn inside? [x y]
(or
(< x -12)
(> (+ x 33) (q/width))
(< y 0)
(> (+ y 40) (q/height))))
(defn item-inside? [item]
(let [x (:x item)
y (:y item)]
(> y (q/height))))
(defn remove-stars [stars]
(remove item-inside? stars))
(defn meteor-out [state]
(let [old (-> state :meteors (count))
new-meteor (remove item-inside? (:meteors state))
new (count new-meteor)]
{:rocket (:rocket state)
:background (q/load-image "images/stars.jpg")
:fires (:fires state)
:score (+ (:score state) (- old new))
:highscore (:highscore state)
:gameOver false
:smoke (:smoke state)
:stars (:stars state)
:meteors new-meteor
:bonus (:bonus state)}))
(defn meteor-hit [state]
(let [rocket-x (-> state :rocket :x)
rocket-y (-> state :rocket :y)
meteors (:meteors state)]
(if (empty? meteors)
state
(if (loop [[m1 & rest] meteors]
(if (or (and
(<= (:x m1) rocket-x (+ (:x m1) 45))
(<= (:y m1) rocket-y (+ (:y m1) 45)))
(and
(<= (:x m1) (+ rocket-x 45) (+ (:x m1) 45))
(<= (:y m1) (+ rocket-y 45) (+ (:y m1) 45))))
true
(if (empty? rest)
false
(recur rest))))
(reset-state-variable state)
state))))
(defn bonus-out [state]
(if (item-inside? (:bonus state))
state
{:rocket (:rocket state)
:background (q/load-image "images/stars.jpg")
:fires (:fires state)
:score (:score state)
:highscore (:highscore state)
:gameOver false
:smoke (:smoke state)
:stars (:stars state)
:meteors (:meteors state)
:bonus []}))
(defn bonus-hit [state]
(let [rocket-x (-> state :rocket :x)
rocket-y (-> state :rocket :y)
bonus (get (:bonus state) 0)]
(if (empty? bonus)
state
(if (or (and
(<= (:x bonus) rocket-x (+ (:x bonus) 40))
(<= (:y bonus) rocket-y (+ (:y bonus) 40)))
(and
(<= (:x bonus) rocket-x (+ (:x bonus) 40))
(<= (:y bonus) (+ rocket-y 45) (+ (:y bonus) 40)))
(and
(<= (:x bonus) (+ rocket-x 45) (+ (:x bonus) 40))
(<= (:y bonus) rocket-y (+ (:y bonus) 40)))
(and
(<= (:x bonus) (+ rocket-x 45) (+ (:x bonus) 40))
(<= (:y bonus) (+ rocket-y 45) (+ (:y bonus) 40))))
{:rocket (:rocket state)
:background (q/load-image "images/stars.jpg")
:fires (:fires state)
:score (+ (:score state) (:points bonus))
:highscore (:highscore state)
:gameOver false
:smoke (:smoke state)
:stars (:stars state)
:meteors (:meteors state)
:bonus []}
state))))
;; # defines a function --> (fn [oldAge] (+ oldAge 0.3))
(defn age-smoke [smoke]
(update-in smoke [:age] #(+ % 0.3)))
(defn old? [smoke]
(< 2.0 (:age smoke)))
(defn remove-old-smokes [smokes]
(remove old? smokes))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; creation methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn create-meteor [state]
(if (= (rand-int 10) 1)
(if-not (or
(-> state :rocket :dir (= 0))
(-> state :rocket :dir (= -1)))
(update-in state [:meteors] conj {:x (rand-int (+ (q/width) -40)) :y -40 :speed (+ (rand-int 30) 5)})
;(update-in state [:meteors] conj {:x (rand-int (+ (q/width) -40)) :y -40 :speed 1})
state)
state))
(defn create-smoke [x y]
{:pos [(+ x 25 (- (rand-int 10) 5))
(+ y 50 (- (rand-int 10) 5))]
:dir 0.0
:age 0.0
:col [(+ (rand-int 105) 150)
(+ (rand-int 100) 100)
(rand-int 100)]})
(defn emit-smoke [state]
(let [x (-> state :rocket :x)
y (-> state :rocket :y)]
(update-in state [:smoke] conj (create-smoke x y))))
(defn create-new-star [state]
(if(= (rand-int 7) 1)
(if-not (or
(-> state :rocket :dir (= 0))
(-> state :rocket :dir (= -1)))
{:rocket (:rocket state)
:background (q/load-image "images/stars.jpg")
:fires (:fires state)
:score (:score state)
:highscore (:highscore state)
:gameOver true
:smoke (:smoke state)
:stars (conj (:stars state) (create-star 1))
:meteors (:meteors state)
:bonus (:bonus state)}
state)
state))
(defn create-bonus [state]
(if (and (empty? (:bonus state)) (= (rand-int 100) 1))
(if-not (or
(-> state :rocket :dir (= 0))
(-> state :rocket :dir (= -1)))
(if (= (rand-int 5) 1)
(update-in state [:bonus] conj {:x (rand-int (+ (q/width) -40)) :y (rand-int (+ (q/height) -40)) :points 25 :speed 3 :image "images/bonus2.png"})
(update-in state [:bonus] conj {:x (rand-int (+ (q/width) -40)) :y (rand-int (+ (q/height) -40)) :points 10 :speed 2 :image "images/bonus.png"}))
state)
state))
(defn fly-backwards [smoke state]
(if (-> state :rocket :dir (= 2))
[]
smoke))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;; reset methods;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn reset-game [state]
(if
(inside? (:x (:rocket state )) (:y (:rocket state)))
(reset-state-variable state)
state))
(defn reset-game-over [gameOver state]
(if (-> state :rocket :dir (not= 0))
false
true))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,
;;;;;;;; move methods;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn move [state event]
(case (:key event)
(:w :up) (assoc-in state [:rocket :dir] 1)
(:s :down) (assoc-in state [:rocket :dir] 2)
(:a :left) (assoc-in state [:rocket :dir] 3)
(:d :right) (assoc-in state [:rocket :dir] 4)
state))
(defn move-meteors [meteor]
(let [speed (:speed meteor)]
(update-in meteor [:y] #(+ % speed))))
(defn move-star [star]
(update-in star [:y] #(+ % (:speed star))))
(defn move-stars [state]
(if-not (or
(= (:dir (:rocket state)) 0)
(= (:dir (:rocket state)) -1))
{:rocket (:rocket state)
:background (q/load-image "images/stars.jpg")
:fires (:fires state)
:score (:score state)
:highscore (:highscore state)
:gameOver true
:smoke (:smoke state)
:stars (doall (map move-star (:stars state)))
:meteors (:meteors state)
:bonus (:bonus state)}
state))
(defn move-bonus [state]
(if (empty? (:bonus state))
state
(update-in (:bonus state) [:y] + 4)))
(defn move-rocket [rocket]
(case (:dir rocket)
(1) (update-in rocket [:y] - 10)
(2) (update-in rocket [:y] + 10)
(3) (update-in rocket [:x] - 10)
(4) (update-in rocket [:x] + 10)
(0) (update-in rocket [:x] + 0)
(-1) (update-in rocket [:x] + 0)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; draw method
(defn draw [state]
;; q/background-image and q/image functions are added in step 1-6
;(q/background-image (:background state))
(q/background 0)
(q/fill 250 250 250)
(q/stroke 250 250 250)
(doseq [star (:stars state)]
(if (= (:color star) 0)
(do
(q/fill 250 250 250)
(q/stroke 250 250 250)
(q/ellipse (:x star) (:y star) (:size star) (:size star)))
(if (= (:color star) 1)
(do
(q/fill 255 255 26)
(q/stroke 255 255 26)
(q/ellipse (:x star) (:y star) (:size star) (:size star)))
(do
(q/fill 255 77 77)
(q/stroke 255 77 77)
(q/ellipse (:x star) (:y star) (:size star) (:size star))))))
(doseq [bonus (:bonus state)]
(q/image (q/load-image (:image bonus))
(:x bonus)
(:y bonus)
45 45))
(q/image (:image (:rocket state))
(:x (:rocket state))
(:y (:rocket state)))
(q/fill 0 0 255)
(q/text-align :left)
(q/stroke 0 0 255)
(doseq [meteor (:meteors state)]
(q/image (q/load-image "images/meteor.png")
(:x meteor)
(:y meteor)))
(doseq [smoke (:smoke state)]
(let [age (:age smoke)
size (max 0.0 (- 10.0 (* 5.0 age)))
[r g b] (:col smoke)
[x y] (:pos smoke)]
(q/fill 0 0 250 150)
(q/stroke 0 0 250 150)
(q/ellipse x y size size)))
(q/fill 255 255 255)
(q/text-size 20)
(q/text (str "Score: " (:score state)) 10 30)
(q/text (str "Highscore: " (:highscore state)) (- (q/width) 140) 30)
(q/fill 200 0 0)
(q/text-font (q/create-font "DejaVu Sans" 40 true))
(q/text-align :center)
(when (:gameOver state)
(q/text (str "Game Over...\nMove to try again") (/ (q/width) 2) 500)))
; update method
(defn update-state [state]
(-> state
(update-in [:meteors] (fn [meteors] (doall (map move-meteors meteors))))
(update-in [:rocket] move-rocket)
; (update-in [:bonus] (fn [bonus] (doall (map move-bonus bonus))))
move-stars
create-new-star
(update-in [:stars] remove-stars)
emit-smoke
(update-in [:smoke] (fn [smokes] (map age-smoke smokes)))
(update-in [:smoke] remove-old-smokes)
meteor-out
create-meteor
; bonus-out
create-bonus
bonus-hit
meteor-hit
reset-game
(update-in [:smoke] fly-backwards state)
(update-in [:gameOver] reset-game-over state)))
;; defsketch
(q/defsketch rocket_game
:host "host"
:title "rocket game"
:size [600 700]
:setup setup
:draw draw
:key-pressed move
:update update-state
:middleware [m/fun-mode])
</code></pre>
| [] | [
{
"body": "<p>For code written by students new to the language, this is quite good. You haven't made any of the major mistakes that most newbies to the language make, like abuse of <code>def</code>, or use of unnecessary side effects.</p>\n\n<p>For your main questions:</p>\n\n<ol>\n<li><p>It's very possible to ... | {
"AcceptedAnswerId": "197619",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T13:39:30.400",
"Id": "197600",
"Score": "7",
"Tags": [
"game",
"functional-programming",
"homework",
"clojure"
],
"Title": "Avoid incoming meteors"
} | 197600 |
<p>As a C programming exercise, I implemented a minimal <code>tac</code> program that prints the input line by line starting from the last line.</p>
<p>I'm looking for feedback on my code. Did I overlook anything? Can the style be improved? Did I miss a major issue?</p>
<p>The code is available here or on <a href="https://github.com/thk2b/ex/tree/master/c" rel="nofollow noreferrer">GitHub</a>.</p>
<pre><code>/*
** tac [ infd [ outfd ]]
**
** output each line from infd to oufile, starting from the last line.
** infd and outfd default to stdin and stdout, respectively.
**
*/
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
void
err_exit(char *msg)
{
perror(msg);
exit(errno);
}
/*
** write each line starting from the end of the buffer.
**
** if flush is falsy, don't output characters unless they are preceded by a newline.
** if flush is truthy, write all characters to the output.
**
** return the number of charaters not outputed.
*/
int
rev_write_lines(int outfd, const char *buf, size_t len, int flush)
{
int i, prev_eol;
size_t line_len;
for(i = prev_eol = len; i >= 0; i--)
if(buf[i] == '\n') {
line_len = prev_eol - i;
if(write(outfd, buf+i+1, line_len) != line_len)
err_exit("write");
prev_eol = i;
}
if(flush) {
if(write(outfd, buf, prev_eol+1) != prev_eol+1)
err_exit("write");
return 0;
}
return prev_eol+1;
}
#define BUF_SIZE 512
/*
** read size characters from stdin into buffer.
** return the number of characters read.
** stop reading when buffer is full or when EOF is encountered.
*/
size_t
read_in_buf(char *buf, size_t size)
{
char *p = buf;
size_t num_read;
int c;
if(size == 0)
return 0;
while((c = getchar()) != EOF) {
*p++ = c;
if(++num_read == size)
break;
}
return num_read;
}
int
stdin_tac(int outfd)
{
size_t buf_size = BUF_SIZE;
char *buf;
ssize_t num_read;
size_t total_read, read_n;
if((buf = (char *) malloc(buf_size)) == NULL)
err_exit("malloc");
total_read = 0;
read_n = buf_size;
while((total_read += num_read = read_in_buf(buf+total_read, read_n))
, num_read == read_n) {
if((buf = (char *) realloc(buf, buf_size *= 2)) == NULL)
err_exit("realloc");
read_n = buf_size - total_read;
}
if(num_read == -1)
err_exit("read(stdin)");
return rev_write_lines(outfd, buf, total_read, 1);
}
int
tac(int infd, int outfd)
{
char *buf;
size_t buf_size = BUF_SIZE, bytes_left;
off_t offset, seek_by;
ssize_t num_read = 0;
int chars_left_in_line = 0;
if((buf = (char *) malloc(buf_size)) == NULL)
err_exit("malloc");
offset = lseek(infd, 0, SEEK_END);
seek_by = -buf_size;
/* loop until we try to seek before the start of file */
while(offset + seek_by >= 0) {
if((offset = lseek(infd, seek_by, SEEK_CUR)) == -1)
err_exit("lseek(SEEK_CUR)");
if((num_read = read(infd, buf, buf_size)) != buf_size)
if(num_read == -1)
err_exit("read(infd)");
chars_left_in_line = rev_write_lines(
outfd, buf, num_read, 0);
if( chars_left_in_line == num_read) {
/*
** buffer is too small to hold this entire line.
** realloc a larger buffer, and (inneficiently) re-read
** the current chunk that we just read in the next iteration.
*/
if((buf = (char *) realloc(buf, buf_size *= 2 )) == NULL)
err_exit("realloc");
seek_by = -buf_size;
} else
seek_by = -2*buf_size + chars_left_in_line;
}
bytes_left = offset + chars_left_in_line;
if((offset = lseek(infd, 0, SEEK_SET)) == -1)
err_exit("lseek(SEEK_START)");
if((num_read = read(infd, buf, bytes_left)) != bytes_left)
err_exit("read");
return rev_write_lines(
outfd, buf, num_read, 1);
}
int
main(int argc, char **argv)
{
int infd, outfd;
if(argc == 1)
return stdin_tac(STDOUT_FILENO);
if((infd = open(argv[1], O_RDONLY)) == -1)
err_exit("open infd");
if(argc == 2)
return tac(infd, STDOUT_FILENO);
if((outfd = open(argv[2], O_CREAT | O_WRONLY, S_IRWXU)) == -1)
err_exit("open outfd");
return tac(infd, outfd);
}
</code></pre>
<p>A concession I made is that, on occasion, it is acceptable (though inefficient) to re-read characters that have already been read. For instance, when the buffer overflows in the middle of a line, we re-read the end of the line into a larger buffer as we attempt to read the rest of the line. An alternative would be to copy the incomplete line to the end of the buffer, and read this many less characters. I found that this solution was significantly more complicated to implement, for a negligible performance gain.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T16:12:14.430",
"Id": "380959",
"Score": "2",
"body": "You are forcing the read of the whole file into memory. You could quite easily get the size of the whole file and pre-allocate the buffer. Or you can use some of the file system ... | [
{
"body": "<p>Well, let's make a start with reviewing:</p>\n\n<ol>\n<li><p>You are assuming that all files the user might name are seekable, even though he might name the console, a socket, a pipe or just about anything else. Also, you assume <code>STDIN</code> is never a normal file.<br>\nSo, open files as req... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T14:13:26.750",
"Id": "197601",
"Score": "5",
"Tags": [
"c",
"file",
"io"
],
"Title": "Implementation of the `tac` command"
} | 197601 |
<p>Simple game where you control space shuttle with mouse click and try to avoid meteors moving in random speed toward you. There are some things I am still developing like rotation and menus, but wanted to get some tips/recommendations on what I have so far. </p>
<p>Thank you in advance! </p>
<pre><code># Import pygame and random
import pygame
import random
# Initialize the game engine
pygame.init()
#Define colors
WHITE = (255, 255, 255)
# Define done
done = False
# Define function to create new meteor
def create_meteor():
meteor = Meteor(WHITE, width, height)
meteor_sprites_list.add(meteor)
# Define player class
class Player(pygame.sprite.Sprite):
def __init__(self, filename, color, HW, HH):
super().__init__()
# Set height, width
self.image = pygame.image.load("player.png").convert_alpha()
# Set background color to transparent
self.image.set_colorkey(color)
# Make top-left corner the passed in locatin
self.rect = pygame.rect.Rect((HW, HH), self.image.get_size())
# Gravity
self.dy = 0
def ignite(self):
self.dy = -400
def update(self, dt, screen):
# Apply gravity
self.dy = min(400, self.dy + 40)
self.rect.y += self.dy * dt
# What happens if go to border of screen
if(self.rect.top <= 0): #top
self.rect.y = 0
self.dy = -4
elif(self.rect.bottom >= height): #ground
self.rect.y = (526-self.rect.height)
#blit image to screen
screen.blit(self.image, self.rect)
# Define new clas for meteor
class Meteor(pygame.sprite.Sprite):
def __init__(self, color, width, height):
# Takes in parameters for color, width (x position) , and height (y postion)
# Call the parent class
super().__init__()
# Make list of image file location
self.meteor_list = ["meteors/meteor1.png"]
# Randomly select meteor from above list
self.new_meteor = random.choice(self.meteor_list)
# Load graphic that is in file folder
self.image = pygame.image.load(self.new_meteor).convert_alpha()
# Set background to transparent
self.image.set_colorkey(color)
# Fetch the rectangle object that has the dimensions of the image
self.rect = self.image.get_rect()
# Random starting location
self.rect.x = random.randrange(width, (width + 300))
self.rect.y = random.randrange(0, height)
# Random movement to the left
self.change_x = random.randrange(-10,-5)
self.change_y = random.randrange(-4,3)
# Set angle for rotate attribute
# ---- Attributes
def reset_pos(self, screen):
# List of meteors
self.meteor_list = ["meteors/meteor1.png"]
# Pick random meteor from above list
self.new_meteor = random.choice(self.meteor_list)
# Load graphic that is in file folder
self.image = pygame.image.load(self.new_meteor).convert_alpha()
# Set background to transparent
self.image.set_colorkey(WHITE)
# Fetch the rectangle object that has the dimensions of the image
self.rect = self.image.get_rect()
# Reset postion of bad block when they reach the bottom of the screen
self.rect.x = random.randrange(width, (width +100))
self.rect.y = random.randrange(0, height)
# Random movement to the left
self.change_x = random.randrange(-10,-5)
self.change_y = random.randrange(-4,3)
# What meteor does each cycle through
def update(self):
# Add rotation
#pygame.transform.rotate(self.image, 115)
# Move bad block down 3 at a time
self.rect.x += self.change_x
self.rect.y += self.change_y
#blit image to screen
screen.blit(self.image, self.rect)
# Reset if falls off screen
if self.rect.right < 0:
self.reset_pos(screen)
if self.rect.top > height:
self.reset_pos(screen)
if self.rect.bottom < 0:
self.reset_pos(screen)
# Class to show the how far rocketship has travelled
class Distance(pygame.sprite.Sprite):
def __init__(self):
# Call the parent class
super().__init__()
# Get time since init was called
time = pygame.time.get_ticks()
# Convert milliseconds to seconds, 1 second = 1 km
travel_distance = round(time/1000, 2)
# Format the font to be used
font = pygame.font.SysFont ("transistor", 25, True, False)
# Create text to be displayed
text = font.render("You've travelled " + str(travel_distance) + " kms", True, WHITE)
# Center text
text_rect = text.get_rect(center=(HW, HH))
# Blit text to the screen
screen.blit(text, text_rect)
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
background_size = pygame.image.load("background.png")
# Get dimensions of background
width = background_size.get_width()
height = background_size.get_height()
HW, HH = width/2, height/2
size = (width, height)
screen = pygame.display.set_mode(size)
x = 0
# Load image for star background
background = pygame.image.load("background.png").convert()
# Seperate becuase error when placed before screen
#Set caption
pygame.display.set_caption("")
# Creates a list of sprites. Each object in program is added to list. Managed by a class called "group"
meteor_sprites_list = pygame.sprite.Group()
# Create spaceship
player = Player("player.png", WHITE, HW, HH)
# Create meteor sprites on the screen
for i in range(4):
create_meteor()
#-----Main Program Loop
while not done:
dt = clock.tick(30)
# Main event Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
player.ignite()
#-----Game Logic
# Draw background and move to the left
rel_x = x % width
screen.blit(background, (rel_x - width, 0))
if rel_x < width:
screen.blit(background, (rel_x, 0))
x -= 2
# Display text on screen
Distance()
# Update Sprites
# Update meteor sprite
meteor_sprites_list.update()
# Update player sprite
player.update(dt/1000. , screen)
# Check to see if player has collided with meteor
meteor_hit_list = pygame.sprite.spritecollide(player, meteor_sprites_list, True, pygame.sprite.collide_circle)
# Event if player collides with meteor
for item in meteor_hit_list:
print("Shuttle hit")
create_meteor()
meteor_hit_list.remove(item)
# Make into game over screen and display distance
# Update the screen with what we've drawn.
pygame.display.flip()
# Make sure to quit
pygame.quit()
</code></pre>
| [] | [
{
"body": "<p>Good job! Here are my suggestions (roughly ordered from important to less important):</p>\n\n<p>Separate the game logic from the drawing/blitting code. That will make your main loop cleaner and the code will probably be easier to extend. So don't blit the sprite images in their <code>update</code>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T15:27:09.867",
"Id": "197603",
"Score": "6",
"Tags": [
"python",
"pygame"
],
"Title": "Flappy Bird Style Game in Space Setting"
} | 197603 |
<p>I tried to literally convert recursive algorithm taught <a href="https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/" rel="nofollow noreferrer">here</a> to iterative, by simulating the recursive stack exactly as much as possible.</p>
<p>I have tested my code and it passed all test cases. </p>
<p>Please let me know if any more improvements are possible.</p>
<p>Here is my code:</p>
<pre><code>public class Graph
{
private int tv; //total vertices
private int te; //total edges
private ArrayList<ArrayList<Integer>> adjacencyList;
public Graph(int tv)
{
this.tv = tv;
adjacencyList = new ArrayList<ArrayList<Integer>>(tv);
for (int i = 0; i < tv; i++)
{
adjacencyList.add(i, new ArrayList<Integer>());
}
}
//adds edge for undirected graph
//s - source, d - destination
public void addEdge(int s, int d)
{
//need to check s & d are with in bounds
adjacencyList.get(s).add(d);
adjacencyList.get(d).add(s);
te++;
}
public void dfsIterative()
{
boolean[] isVisited = new boolean[tv];
for (int v = 0; v < tv; v++)
{
if (!isVisited[v])
{
dfsIterativeUtil(v, isVisited);
}
}
}
//sv - start vertex
private void dfsIterativeUtil(int sv, boolean[] isVisited)
{
class Node
{
int v; //vertex in a graph
int i; //current index of v's adjacency list
Node(int v, int i)
{
this.v = v;
this.i = i;
}
}
Deque<Node> stack = new LinkedList<>();
stack.push(new Node(sv, -1));
while (!stack.isEmpty())
{
int cv = stack.peek().v; //cv - current vertex
if (!isVisited[cv])
{
System.out.print(cv + " ");
isVisited[cv] = true;
}
ArrayList<Integer> cvAdjList = adjacencyList.get(cv);
int ci = ++stack.peek().i; //ci - current index in cvAdjList
if (ci>=cvAdjList.size())
{
stack.pop();
}
else
{
int vtx = cvAdjList.get(ci);
if (!isVisited[vtx])
{
stack.push(new Node(vtx, -1));
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T18:16:56.487",
"Id": "380976",
"Score": "0",
"body": "\"I tried few test cases and they passed. But I am unsure whether my algorithm is correct.\" Why? And what test cases did you try?"
},
{
"ContentLicense": "CC BY-SA 4.0",... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T17:07:51.907",
"Id": "197605",
"Score": "2",
"Tags": [
"java",
"graph",
"depth-first-search"
],
"Title": "DFS logic to traverse a graph"
} | 197605 |
<p>I am a mathematician attempting to become proficient with C++. At the moment I am learning about data structures. I am now writing a queue data structure using linked list from scratch.</p>
<p>I have tested my class that I wrote and everything seems to be working fine but I want to see if there are any bugs or some areas of the code I could improve on.</p>
<p>Here is the class:</p>
<pre><code>#ifndef Queue_h
#define Queue_h
template <class T>
class Queue {
private:
struct Node {
T data;
Node* next = nullptr;
};
Node* first = nullptr;
Node* last = nullptr;
// Used for destructor to delete elements
void do_unchecked_pop();
// Use for debugging purposes and for overloading the << operator
void show(std::ostream &str) const;
public:
// Constructors
Queue() = default; // empty constructor
Queue(Queue const& value); // copy constructor
// Rule of 5
Queue(Queue&& move) noexcept; // move constuctor
Queue& operator=(Queue&& move) noexcept; // move assignment operator
~Queue(); // destructor
// Overload operators
Queue& operator=(Queue const& rhs);
friend std::ostream& operator<<(std::ostream& str, Queue<T> const& data) {
data.show(str);
return str;
}
// Member functions
bool empty() const {return first == nullptr;}
int size() const;
T& front() const;
T& back() const;
void push(const T& theData);
void push(T&& theData);
void pop();
void swap(Queue& other) noexcept;
};
template <class T>
Queue<T>::Queue(Queue<T> const& value) {
try {
for(auto loop = value.first; loop != nullptr; loop = loop->next)
push(loop->data);
}
catch (...) {
while(first != nullptr)
do_unchecked_pop();
throw;
}
}
template <class T>
Queue<T>::Queue(Queue&& move) noexcept {
move.swap(*this);
}
template <class T>
Queue<T>& Queue<T>::operator=(Queue<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
Queue<T>::~Queue() {
while(first != nullptr) {
do_unchecked_pop();
}
}
template <class T>
int Queue<T>::size() const {
int size = 0;
for (auto current = first; current != nullptr; current = current->next)
size++;
return size;
}
template <class T>
T& Queue<T>::front() const {
if(first == nullptr) {
throw std::out_of_range("the Queue is empty!");
}
return first->data;
}
template <class T>
T& Queue<T>::back() const {
return last->data;
}
template <class T>
void Queue<T>::push(const T& theData) {
Node* newNode = new Node;
newNode->data = theData;
newNode->next = nullptr;
if(first == nullptr) {
first = last = newNode;
}
else {
last->next = newNode;
last = newNode;
}
}
template <class T>
void Queue<T>::push(T&& theData) {
Node* newNode = new Node;
newNode->data = std::move(theData);
newNode->next = nullptr;
if(first == nullptr) {
first = last = newNode;
}
else {
last->next = newNode;
last = newNode;
}
}
template <class T>
void Queue<T>::pop() {
if(first == nullptr) {
throw std::invalid_argument("the Queue is empty!");
}
do_unchecked_pop();
}
template <class T>
void Queue<T>::do_unchecked_pop() {
Node* tmp = first->next;
delete tmp;
first = tmp;
}
template <class T>
void Queue<T>::show(std::ostream &str) const {
for(Node* loop = first; loop != nullptr; loop = loop->next) {
str << loop->data << "\t";
}
str << "\n";
}
template <class T>
void Queue<T>::swap(Queue<T> &other) noexcept {
using std::swap;
swap(first, other.first);
swap(last, other.last);
}
// Free function
template <typename T>
void swap(Queue<T>& a, Queue<T>& b) noexcept {
a.swap(b);
}
#endif /* Queue_h */
</code></pre>
<p>Here is the main.cpp that tests the latter class:</p>
<pre><code>#include <algorithm>
#include <cassert>
#include <iostream>
#include <ostream>
#include <iosfwd>
#include "Queue.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Queue Using Linked List //////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
Queue<int> obj;
obj.push(2);
obj.push(4);
obj.push(6);
obj.push(8);
obj.push(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------Displaying Queue Contents---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------Pop Queue Element -------------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop();
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------Get the size of Queue -------------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj.size() << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------Print top element --------------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj.front() << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------Print last element --------------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj.back() << std::endl;
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>There is a check missing in your <code>back()</code> function (If the queue is empty you have an error). </p>\n\n<p>It would increase readability if you would use <code>empty()</code> instead of repeated <code>top == nullptr</code> checks. The intent is more obvious that way.</p>\n\n<p>Your <code... | {
"AcceptedAnswerId": "197615",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T18:07:39.017",
"Id": "197607",
"Score": "1",
"Tags": [
"c++",
"queue"
],
"Title": "Generic Queue data structure in C++"
} | 197607 |
<p>I made a simple Hearthstone fatigue calculator. For those who don't know, <a href="https://en.wikipedia.org/wiki/Hearthstone" rel="nofollow noreferrer">Hearthstone</a> is a card game in which every turn you draw a card from your deck. Once you're out of cards, you start taking <em>fatigue damage</em>, getting 1 more damage each turn. The total damage dealt in X turns is known as the Triangular Number Sequence: 1 (1), 3 (1+2), 6 (1+2+3), 10 (1+2+3+4). For example, at turn 4 the fatigue damage has already dealt 10 dmg (1+2+3+4). This could be used for some decks that make you run out of cards, to calculate how much damage they need to kill the opponent or to just calculate how much damage X fatigue turns will do.</p>
<p>I just wanted to know how my code looks. I know it's a very simple program but I might be doing something wrong and I guess it's better to know as early as possible. Besides, code reviewing a long project is just too boring for everyone. I've been learning by myself and as nobody ever reads my code I might be doing terrible things without knowing it haha</p>
<pre><code>def error():
print("Whoops, something went wrong. Please try again.")
def calc_mode(t, s):
d = 0
for i in range(s, t+s):
d = d + i
return d
def lethal_mode(d_input, s):
d_calc = 0
i = 1
t = 0
while d_calc < d_input:
d_calc = d_calc + i
i += 1
t += 1
return t
while True: # Checks if the mode input is valid
try:
mode = int(input("\nMODES: "
"\n* '1' to get the turns needed for X damage "
"\n* '2' to get the damage dealt in X turns "
"\nPlease type to select your mode: "))
except ValueError:
error()
continue
else:
while True:
if mode == 1: # Checks if the input after the mode is valid
while True:
try:
damageInput = int(input("\nPlease input the damage needed for lethal: "))
startInput = int(input("Starting at how much damage? (default is 1): "))
except ValueError:
error()
continue
else:
print("\n>> You will need %d fatigue turns for that sweet lethal"
% lethal_mode(damageInput, startInput))
continue
if mode == 2:
while True:
try:
turnsInput = int(input("\nPlease input how many fatigue turns: "))
startInput = int(input("Starting at how much damage? (default is 1): "))
except ValueError:
error()
continue
else:
print("\n>> It will deal %d damage" % calc_mode(turnsInput, startInput))
continue
else:
error()
break
</code></pre>
<p>What do you think overall? Thanks!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T20:14:04.973",
"Id": "380983",
"Score": "2",
"body": "What's your Python version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T21:33:03.700",
"Id": "380987",
"Score": "1",
"body": "It's... | [
{
"body": "<h1>The math</h1>\n\n<p>There is a useful formula for <a href=\"https://en.wikipedia.org/wiki/Triangular_number\" rel=\"nofollow noreferrer\">triangle numbers</a> that vastly simplifies a lot of the code here:</p>\n\n<p>$$\\sum_{k=1}^n k = \\frac{n(n+1)}{2}$$</p>\n\n<p>So for instance, the first tria... | {
"AcceptedAnswerId": "197618",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T18:20:35.727",
"Id": "197608",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Hearthstone fatigue calculator"
} | 197608 |
<p>In my Spring MVC app I have <code>User</code> and <code>Role</code> entities.</p>
<p><code>User</code>:</p>
<pre><code>public class User {
private Long id;
private Set<Role> roles;
// other fields, getters and setters
}
</code></pre>
<p><code>Role</code>:</p>
<pre><code>public class Role {
private Long id;
// other fields, getters and setters
}
</code></pre>
<p>I have a service method with the following signature:</p>
<pre><code>@Transactional
void setRolesByUserId(Map<Long, Set<Long>> rolesByUserId)
</code></pre>
<p>The key of the <code>Map</code> is a <code>User</code> ID and the corresponding value is a <code>Set</code> of <code>Role</code> IDs that needs to be assigned to the user.</p>
<p>My implementation:</p>
<pre><code>public void setRolesByUserId(Map<Long, Set<Long>> rolesByUserId) {
// 1.
Map<Long, Role> roles = roleRepository.findAll()
.stream().collect(Collectors.toMap(Role::getId, Function.identity()));
// 2.
userRepository.findAllById(rolesByUserId.keySet())
// 3.
.forEach(user -> user.setRoles(rolesByUserId.get(user.getId())
.stream().map(roles::get).collect(Collectors.toSet())));
}
</code></pre>
<p>So basically the flow is the following:</p>
<ol>
<li>fetch all the <code>Role</code> entities from the DB into a <code>Map<Long, Role></code> (where the key is the <code>Role</code> ID and the value is the <code>Role</code> entity itself)</li>
<li>fetch the <code>User</code> entities from the DB that needs to be modified</li>
<li>for each <code>User</code>, iterate through the <code>Role</code> IDs to be assigned, fetch the corresponding <code>Role</code> entities from the <code>Map</code>, collect them into a <code>Set</code> and assign it to the <code>User</code></li>
</ol>
<p>Can this method be optimized?</p>
| [] | [
{
"body": "<p>Well, you created a good code so far. Your lamda is OK. But there are some things about naming which could be improved</p>\n\n<ol>\n<li>About the API <code>setRolesByUserId</code>, it is OK to accept userId as long. But about role, it could be better to change the Set to Set, and i think you're ab... | {
"AcceptedAnswerId": "197633",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T19:05:42.047",
"Id": "197610",
"Score": "2",
"Tags": [
"java",
"hibernate",
"authorization",
"jpa"
],
"Title": "JPA method to update roles for users"
} | 197610 |
<p>I am trying to solve a puzzle in a performant way. This is <a href="https://www.codewars.com/kata/insane-coloured-triangles" rel="nofollow noreferrer">the puzzle</a>.</p>
<p>Simply explained: you have a String and you must reduce it to one character with the given rules. This is the solution to the <a href="https://www.codewars.com/kata/coloured-triangles" rel="nofollow noreferrer">simple</a> variant. </p>
<pre><code>COLORS = set("RGB")
def triangle(row):
while len(row) > 1:
row = ''.join(a if a == b else (COLORS-{a, b}).pop() for a, b in zip(row, row[1:]))
return row
</code></pre>
<p>In the harder variant the task is to do the same, but performance is asked.
I thought adding a dictionary and "remembering" already solved words would boost the performance. But actualy it is not performing faster than the simple variation. Is there a way to boost one of my codes? Do I have an efficiency lack in my code? Is there maybe a efficiency lack in the algorithm?</p>
<pre><code>COLORS = set("RGB")
mapping_simple = {}
def triangle_simple(row):
result = ['']
while True:
if len(row) == 1:
result[0] = row
return result[0]
if row in mapping_simple:
result[0] = mapping_simple[row][0]
return result[0]
mapping_simple[row] = result
row = ''.join(a if a == b else (COLORS-{a, b}).pop() for a, b in zip(row, row[1:]))
return result[0]
</code></pre>
| [] | [
{
"body": "<h1>string conversion</h1>\n\n<p>You convert the row to a string at each iteration, there is no need for that. You can shave off a few µs by using a tuple</p>\n\n<pre><code>def triangle_tuple(row):\n while len(row) > 1:\n row = tuple(a if a == b else (COLORS-{a, b}).pop() for a, b in zip... | {
"AcceptedAnswerId": "197642",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T20:58:51.683",
"Id": "197612",
"Score": "12",
"Tags": [
"python",
"performance",
"strings",
"programming-challenge",
"hash-map"
],
"Title": "Codewars: Reduce strings to one character"
} | 197612 |
<p>I was told my QT Project file is a hot mess. I'm returning to C++ after many years of doing Java and I'm really new to QT. I would like someone familiar with QT Project files to give my code a once over and provide a critique with suggestions for improvement. I have to use <code>install_name_tool</code> to set <code>@rpath</code> after I build in QT Creator. That was not fun finding a solution there but that's when I was told my project file is a mess. I started modifying a file from another altcoin to be by own new coin. It seems that no one has kept up with the os-x builds, core or QT (GUI). Please do a code review of my project file.</p>
<pre><code># QT Project File
TEMPLATE = app
TARGET = cybill-wallet
macx:TARGET = "cybill-wallet"
VERSION = 0.1.0
INCLUDEPATH += src src/json src/qt
DEFINES += QT_GUI BOOST_THREAD_USE_LIB BOOST_SPIRIT_THREADSAFE
CONFIG += no_include_pwd
CONFIG += thread
CONFIG += static
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4) {
QT += widgets
}
# for boost > 1.37, add -mt to the boost libraries
# use: qmake BOOST_LIB_SUFFIX=-mt
# for boost thread win32 with _win32 sufix
# use: BOOST_THREAD_LIB_SUFFIX=_win32-...
# when linking against a specific BerkelyDB version: BDB_LIB_SUFFIX=-4.8
# Dependency library locations can be customized using following settings
# winbuild dependencies
win32 {
# BOOST_LIB_SUFFIX=-mgw49-mt-s-1_58
BOOST_INCLUDE_PATH=$$DEPSDIR/boost_1_58_0
BOOST_LIB_PATH=$$DEPSDIR/boost_1_58_0/stage/lib
BDB_INCLUDE_PATH=$$DEPSDIR/db-4.8.30.NC/build_unix
BDB_LIB_PATH=$$DEPSDIR/db-4.8.30.NC/build_unix
OPENSSL_INCLUDE_PATH=$$DEPSDIR/openssl-1.0.2j/include
OPENSSL_LIB_PATH=$$DEPSDIR/openssl-1.0.2j
MINIUPNPC_INCLUDE_PATH=$$DEPSDIR/miniupnpc
MINIUPNPC_LIB_PATH=$$DEPSDIR/miniupnpc
QRENCODE_INCLUDE_PATH=$$DEPSDIR/qrencode-3.4.3
QRENCODE_LIB_PATH=$$DEPSDIR/qrencode-3.4.3/.libs
GMP_INCLUDE_PATH=$$DEPSDIR/gmp-6.0.0
GMP_LIB_PATH=$$DEPSDIR/gmp-6.0.0/.libs
}
OBJECTS_DIR = build
MOC_DIR = build
UI_DIR = build
# use: qmake "RELEASE=1"
contains(RELEASE, 1) {
# Mac: compile for maximum compatibility (10.5, 64-bit)
macx:QMAKE_CXXFLAGS += -mmacosx-version-min=10.5 -arch x86_64 - isysroot $(xcode-select --print-path)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.5.sdk
!windows:!macx {
# Linux: static link
LIBS += -Wl,-Bstatic
}
}
!win32 {
# for extra security against potential buffer overflows: enable GCCs Stack Smashing Protection
QMAKE_CXXFLAGS *= -fstack-protector-all --param ssp-buffer-size=1
QMAKE_LFLAGS *= -fstack-protector-all --param ssp-buffer-size=1
# We need to exclude this for Windows cross compile with MinGW 4.2.x, as it will result in a non-working executable!
# This can be enabled for Windows, when we switch to MinGW >= 4.4.x.
}
# for extra security on Windows: enable ASLR and DEP via GCC linker flags
#win32:QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat -Wl,--large- address-aware -static
win32:QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat -static
win32:QMAKE_LFLAGS += -static-libgcc -static-libstdc++
# use: qmake "USE_QRCODE=1"
# libqrencode (http://fukuchi.org/works/qrencode/index.en.html) must be installed for support
contains(USE_QRCODE, 1) {
message(Building with QRCode support)
DEFINES += USE_QRCODE
LIBS += -lqrencode
}
# use: qmake "USE_UPNP=1" ( enabled by default; default)
# or: qmake "USE_UPNP=0" (disabled by default)
# or: qmake "USE_UPNP=-" (not supported)
# miniupnpc (http://miniupnp.free.fr/files/) must be installed for support
contains(USE_UPNP, -) {
message(Building without UPNP support)
} else {
message(Building with UPNP support)
count(USE_UPNP, 0) {
USE_UPNP=1
}
DEFINES += USE_UPNP=$$USE_UPNP STATICLIB
INCLUDEPATH += $$MINIUPNPC_INCLUDE_PATH
LIBS += $$join(MINIUPNPC_LIB_PATH,,-L,) -lminiupnpc
win32:LIBS += -liphlpapi
}
# use: qmake "USE_DBUS=1"
contains(USE_DBUS, 1) {
message(Building with DBUS (Freedesktop notifications) support)
DEFINES += USE_DBUS
QT += dbus
}
# use: qmake "USE_IPV6=1" ( enabled by default; default)
# or: qmake "USE_IPV6=0" (disabled by default)
# or: qmake "USE_IPV6=-" (not supported)
contains(USE_IPV6, -) {
message(Building without IPv6 support)
} else {
message(Building with IPv6 support)
count(USE_IPV6, 0) {
USE_IPV6=1
}
DEFINES += USE_IPV6=$$USE_IPV6
}
contains(BITCOIN_NEED_QT_PLUGINS, 1) {
DEFINES += BITCOIN_NEED_QT_PLUGINS
QTPLUGIN += qcncodecs qjpcodecs qtwcodecs qkrcodecs qtaccessiblewidgets
}
INCLUDEPATH += src/leveldb/include src/leveldb/helpers
LIBS += $$PWD/src/leveldb/libleveldb.a $$PWD/src/leveldb/libmemenv.a
SOURCES += src/txdb.cpp \
src/qt/magi.cpp \
src/qt/magiaddressvalidator.cpp \
src/qt/magiamountfield.cpp \
src/qt/magigui.cpp \
src/qt/magistrings.cpp \
src/qt/magiunits.cpp \
src/magirpc.cpp \
src/clientversion.cpp \
src/qt/utilitydialog.cpp
!win32 {
# we use QMAKE_CXXFLAGS_RELEASE even without RELEASE=1 because we use RELEASE to indicate linking preferences not -O preferences
genleveldb.commands = cd $$PWD/src/leveldb && CC=$$QMAKE_CC CXX=$$QMAKE_CXX $(MAKE) OPT=\"$$QMAKE_CXXFLAGS $$QMAKE_CXXFLAGS_RELEASE\" libleveldb.a libmemenv.a
} else {
# make an educated guess about what the ranlib command is called
isEmpty(QMAKE_RANLIB) {
QMAKE_RANLIB = $$replace(QMAKE_STRIP, strip, ranlib)
}
LIBS += -lshlwapi
genleveldb.commands = cd $$PWD/src/leveldb && CC=$$QMAKE_CC CXX=$$QMAKE_CXX TARGET_OS=OS_WINDOWS_CROSSCOMPILE $(MAKE) OPT=\"$$QMAKE_CXXFLAGS $$QMAKE_CXXFLAGS_RELEASE\" libleveldb.a libmemenv.a && $$QMAKE_RANLIB $$PWD/src/leveldb/libleveldb.a && $$QMAKE_RANLIB $$PWD/src/leveldb/libmemenv.a
}
genleveldb.target = $$PWD/src/leveldb/libleveldb.a
genleveldb.depends = FORCE
PRE_TARGETDEPS += $$PWD/src/leveldb/libleveldb.a
QMAKE_EXTRA_TARGETS += genleveldb
# Gross ugly hack that depends on qmake internals, unfortunately there is no other way to do it.
QMAKE_CLEAN += $$PWD/src/leveldb/libleveldb.a; cd $$PWD/src/leveldb ; $(MAKE) clean
# regenerate src/build.h
!windows|contains(USE_BUILD_INFO, 1) {
genbuild.depends = FORCE
genbuild.commands = cd $$PWD; /bin/sh share/genbuild.sh $$OUT_PWD/build/build.h
genbuild.target = $$OUT_PWD/build/build.h
PRE_TARGETDEPS += $$OUT_PWD/build/build.h
QMAKE_EXTRA_TARGETS += genbuild
DEFINES += HAVE_BUILD_INFO
}
# If we have an ARM device, we can't use SSE2 instructions, so don't try to use them
QMAKE_XCPUARCH = $$QMAKE_HOST.arch
equals(QMAKE_XCPUARCH, armv7l) {
message(Building without SSE2 support)
}
else:equals(QMAKE_XCPUARCH, armv6l) {
message(Building without SSE2 support)
}
else {
message(Building with SSE2 support)
QMAKE_CXXFLAGS += -msse2
QMAKE_CFLAGS += -msse2
}
#endif
QMAKE_CXXFLAGS_WARN_ON = -fdiagnostics-show-option -Wall -Wextra - Wformat -Wformat-security -Wno-unused-parameter -Wstack-protector
# Input
DEPENDPATH += src src/json src/qt
HEADERS += \
src/qt/transactiontablemodel.h \
src/qt/addresstablemodel.h \
src/qt/optionsdialog.h \
src/qt/coincontroldialog.h \
src/qt/coincontroltreewidget.h \
src/qt/sendcoinsdialog.h \
src/qt/addressbookpage.h \
src/qt/signverifymessagedialog.h \
src/qt/editaddressdialog.h \
src/alert.h \
src/addrman.h \
src/base58.h \
src/bignum.h \
src/checkpoints.h \
src/compat.h \
src/coincontrol.h \
src/sync.h \
src/util.h \
src/hash.h \
src/uint256.h \
src/kernel.h \
src/scrypt_mine.h \
src/pbkdf2.h \
src/serialize.h \
src/strlcpy.h \
src/main.h \
src/net.h \
src/key.h \
src/db.h \
src/txdb.h \
src/walletdb.h \
src/script.h \
src/init.h \
src/mruset.h \
src/magimath.h \
src/json/json_spirit_writer_template.h \
src/json/json_spirit_writer.h \
src/json/json_spirit_value.h \
src/json/json_spirit_utils.h \
src/json/json_spirit_stream_reader.h \
src/json/json_spirit_reader_template.h \
src/json/json_spirit_reader.h \
src/json/json_spirit_error_position.h \
src/json/json_spirit.h \
src/qt/clientmodel.h \
src/qt/guiutil.h \
src/qt/transactionrecord.h \
src/qt/guiconstants.h \
src/qt/optionsmodel.h \
src/qt/monitoreddatamapper.h \
src/qt/transactiondesc.h \
src/qt/transactiondescdialog.h \
src/qt/updatecheck.h \
src/wallet.h \
src/keystore.h \
src/qt/transactionfilterproxy.h \
src/qt/transactionview.h \
src/qt/walletmodel.h \
src/qt/overviewpage.h \
src/qt/csvmodelwriter.h \
src/crypter.h \
src/qt/sendcoinsentry.h \
src/qt/qvalidatedlineedit.h \
src/qt/qvaluecombobox.h \
src/qt/askpassphrasedialog.h \
src/protocol.h \
src/qt/notificator.h \
src/qt/qtipcserver.h \
src/allocators.h \
src/ui_interface.h \
src/qt/console.h \
src/qt/rpcconsole.h \
src/version.h \
src/netbase.h \
src/clientversion.h \
src/hash_magi.h \
src/hash/sph_types.h \
src/hash/sph_keccak.h \
src/hash/sph_haval.h \
src/hash/sph_ripemd.h \
src/hash/sph_sha2.h \
src/hash/sph_tiger.h \
src/hash/sph_whirlpool.h \
src/qt/magiaddressvalidator.h \
src/qt/magiamountfield.h \
src/qt/magigui.h \
src/qt/magiunits.h \
src/magirpc.h \
src/qt/utilitydialog.h
SOURCES += \
src/qt/transactiontablemodel.cpp \
src/qt/addresstablemodel.cpp \
src/qt/optionsdialog.cpp \
src/qt/sendcoinsdialog.cpp \
src/qt/coincontroldialog.cpp \
src/qt/coincontroltreewidget.cpp \
src/qt/addressbookpage.cpp \
src/qt/signverifymessagedialog.cpp \
src/qt/editaddressdialog.cpp \
src/alert.cpp \
src/sync.cpp \
src/util.cpp \
src/hash.cpp \
src/netbase.cpp \
src/key.cpp \
src/script.cpp \
src/main.cpp \
src/init.cpp \
src/net.cpp \
src/checkpoints.cpp \
src/addrman.cpp \
src/db.cpp \
src/walletdb.cpp \
src/magimath.cpp \
src/qt/clientmodel.cpp \
src/qt/guiutil.cpp \
src/qt/transactionrecord.cpp \
src/qt/optionsmodel.cpp \
src/qt/monitoreddatamapper.cpp \
src/qt/transactiondesc.cpp \
src/qt/transactiondescdialog.cpp \
src/qt/updatecheck.cpp \
src/wallet.cpp \
src/keystore.cpp \
src/qt/transactionfilterproxy.cpp \
src/qt/transactionview.cpp \
src/qt/walletmodel.cpp \
src/rpcdump.cpp \
src/rpcnet.cpp \
src/rpcmining.cpp \
src/rpcwallet.cpp \
src/rpcblockchain.cpp \
src/rpcrawtransaction.cpp \
src/qt/overviewpage.cpp \
src/qt/csvmodelwriter.cpp \
src/crypter.cpp \
src/qt/sendcoinsentry.cpp \
src/qt/qvalidatedlineedit.cpp \
src/qt/qvaluecombobox.cpp \
src/qt/askpassphrasedialog.cpp \
src/protocol.cpp \
src/qt/notificator.cpp \
src/qt/qtipcserver.cpp \
src/qt/console.cpp \
src/qt/rpcconsole.cpp \
src/noui.cpp \
src/kernel.cpp \
src/pbkdf2.cpp \
src/hash/keccak.cpp \
src/hash/haval.cpp \
src/hash/ripemd.cpp \
src/hash/sha2.cpp \
src/hash/sha2big.cpp \
src/hash/tiger.cpp \
src/hash/whirlpool.cpp
RESOURCES += \
src/qt/magi.qrc
FORMS += \
src/qt/forms/coincontroldialog.ui \
src/qt/forms/sendcoinsdialog.ui \
src/qt/forms/addressbookpage.ui \
src/qt/forms/signverifymessagedialog.ui \
src/qt/forms/editaddressdialog.ui \
src/qt/forms/transactiondescdialog.ui \
src/qt/forms/overviewpage.ui \
src/qt/forms/sendcoinsentry.ui \
src/qt/forms/askpassphrasedialog.ui \
src/qt/forms/rpcconsole.ui \
src/qt/forms/optionsdialog.ui \
src/qt/forms/console.ui \
src/qt/forms/helpmessagedialog.ui
contains(USE_QRCODE, 1) {
HEADERS += src/qt/qrcodedialog.h
SOURCES += src/qt/qrcodedialog.cpp
FORMS += src/qt/forms/qrcodedialog.ui
}
contains(BITCOIN_QT_TEST, 1) {
SOURCES += src/qt/test/test_main.cpp \
src/qt/test/uritests.cpp
HEADERS += src/qt/test/uritests.h
DEPENDPATH += src/qt/test
QT += testlib
TARGET = m-wallet_test
DEFINES += BITCOIN_QT_TEST
}
CODECFORTR = UTF-8
# for lrelease/lupdate
# also add new translations to src/qt/magi.qrc under translations/
TRANSLATIONS = $$files(src/qt/locale/bitcoin_*.ts)
isEmpty(QMAKE_LRELEASE) {
win32:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]\\lrelease.exe
else:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]/lrelease
}
isEmpty(QM_DIR):QM_DIR = $$PWD/src/qt/locale
# automatically build translations, so they can be included in resource file
TSQM.name = lrelease ${QMAKE_FILE_IN}
TSQM.input = TRANSLATIONS
TSQM.output = $$QM_DIR/${QMAKE_FILE_BASE}.qm
TSQM.commands = $$QMAKE_LRELEASE ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_OUT}
TSQM.CONFIG = no_link
QMAKE_EXTRA_COMPILERS += TSQM
# "Other files" to show in Qt Creator
OTHER_FILES += README.md \
doc/*.rst \
doc/*.txt doc/README \
src/qt/res/magi-qt.rc \
src/test/*.cpp \
src/test/*.h \
src/qt/test/*.cpp \
src/qt/test/*.h
# platform specific defaults, if not overridden on command line
isEmpty(BOOST_LIB_SUFFIX) {
macx:BOOST_LIB_SUFFIX = -mt
windows:BOOST_LIB_SUFFIX = -mgw49-mt-s-1_58
}
isEmpty(BOOST_THREAD_LIB_SUFFIX) {
BOOST_THREAD_LIB_SUFFIX = $$BOOST_LIB_SUFFIX
}
isEmpty(BDB_LIB_PATH) {
macx:BDB_LIB_PATH = /opt/local/lib/db48
}
isEmpty(BDB_LIB_SUFFIX) {
macx:BDB_LIB_SUFFIX = -4.8
}
isEmpty(BDB_INCLUDE_PATH) {
macx:BDB_INCLUDE_PATH = /opt/local/include/db48
}
isEmpty(BOOST_LIB_PATH) {
macx:BOOST_LIB_PATH = /usr/local/Cellar/boost@1.57/1.57.0/lib
}
isEmpty(BOOST_INCLUDE_PATH) {
macx:BOOST_INCLUDE_PATH = /opt/local/include
}
windows:DEFINES += WIN32
windows:RC_FILE = src/qt/res/magi-qt.rc
windows:!contains(MINGW_THREAD_BUGFIX, 0) {
# At least qmake's win32-g++-cross profile is missing the -lmingwthrd
# thread-safety flag. GCC has -mthreads to enable this, but it doesn't
# work with static linking. -lmingwthrd must come BEFORE -lmingw, so
# it is prepended to QMAKE_LIBS_QT_ENTRY.
# It can be turned off with MINGW_THREAD_BUGFIX=0, just in case it causes
# any problems on some untested qmake profile now or in the future.
DEFINES += _MT
QMAKE_LIBS_QT_ENTRY = -lmingwthrd $$QMAKE_LIBS_QT_ENTRY
}
!windows:!macx {
DEFINES += LINUX
LIBS += -lrt
}
############################################
# MAC OS-X Specific
############################################
macx:CFLAGS += -stdlib=libc++ - rpath=/usr/local/Cellar/qt/5.11.1/lib/QtWidgets.framework/Versions/5/QtWidgets
macx:INCLUDEPATH += /usr/local/Cellar/miniupnpc/2.1/include /usr/local/Cellar/boost@1.57/1.57.0/include /usr/local/Cellar/openssl/1.0.2o_2/include /usr/local/Cellar/gmp/6.1.2_2/include /usr/local/Cellar/leveldb/1.20_2/include /usr/local/Cellar/berkeley- db@4/4.8.30/include
macx:HEADERS += src/qt/macdockiconhandler.h src/qt/macnotificationhandler.h
macx:OBJECTIVE_SOURCES += src/qt/macdockiconhandler.mm src/qt/macnotificationhandler.mm
macx:LIBS += -framework Foundation -framework ApplicationServices -framework AppKit -framework CoreServices
macx:DEFINES += MAC_OSX MSG_NOSIGNAL=0
macx:ICON = src/qt/res/icons/cybill.icns
macx:CONFIG += -std=c++11
macx:QMAKE_CFLAGS_THREAD += -pthread -stdlib=libc++
macx:QMAKE_LFLAGS_THREAD += -pthread
macx:QMAKE_CXXFLAGS_THREAD += -pthread -stdlib=libc++ -std=c++11
macx:MINIUPNPC_LIB_PATH = /usr/local/Cellar/miniupnpc/2.1/lib
macx:LIBS += $$join(MINIUPNPC_LIB_PATH,,-L,) -lminiupnpc
macx:GMP_LIB_PATH = /usr/local/Cellar/gmp/6.1.2_2/lib
macx:LIBS += $$join(GMP_LIB_PATH,,-L,) -lgmp
macx:OPENSSL_LIB_PATH = /usr/local/Cellar/openssl/1.0.2o_2/lib
macx:LIBS += $$join(OPENSSL_LIB_PATH,,-L,) -lssl
macx:BOOST_LIB_PATH = /usr/local/Cellar/boost@1.57/1.57.0/lib
macx:LIBS += $$join(BOOST_LIB_PATH,,-L,) -lboost_system-mt
macx:LIBS += $$join(BOOST_LIB_PATH,,-L,) -lboost_thread-mt
# Set libraries and includes at end, to use platform-defined defaults if not overridden
INCLUDEPATH += $$OPT_INCLUDE_PATH $$BOOST_INCLUDE_PATH $$BDB_INCLUDE_PATH $$OPENSSL_INCLUDE_PATH $$QRENCODE_INCLUDE_PATH $$GMP_INCLUDE_PATH
LIBS += $$join(OPT_LIB_PATH,,-L,) $$join(BOOST_LIB_PATH,,-L,) $$join(BDB_LIB_PATH,,-L,) $$join(OPENSSL_LIB_PATH,,-L,) $$join(QRENCODE_LIB_PATH,,-L,) $$join(GMP_LIB_PATH,,-L,)
LIBS += -lssl -lgmp -lcrypto -ldb_cxx$$BDB_LIB_SUFFIX
LIBS += $$OPT_LIBS
# -lgdi32 has to happen after -lcrypto (see #681)
windows:LIBS += -lws2_32 -lshlwapi -lmswsock -lole32 -loleaut32 -luuid - lgdi32
LIBS += -lboost_system$$BOOST_LIB_SUFFIX - lboost_filesystem$$BOOST_LIB_SUFFIX - lboost_program_options$$BOOST_LIB_SUFFIX - lboost_thread$$BOOST_THREAD_LIB_SUFFIX
windows:LIBS += -lboost_chrono$$BOOST_LIB_SUFFIX
contains(RELEASE, 1) {
!windows:!macx {
# Linux: turn dynamic linking back on for c/c++ runtime libraries
LIBS += -Wl,-Bdynamic
}
}
system($$QMAKE_LRELEASE -silent $$TRANSLATIONS)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-04T14:11:00.090",
"Id": "385007",
"Score": "0",
"body": "Since no one has attempted to do a code review, I'll do a quick review. The project file is messy, however it's because the focus has been to build the application for Mac OS-X. ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T20:59:22.560",
"Id": "197613",
"Score": "1",
"Tags": [
"qt",
"makefile",
"macos"
],
"Title": "Alt-Coin Wallet QT Project for Mac OS-X"
} | 197613 |
<blockquote>
<p>Write a factorial function that takes a positive integer, N as a parameter and prints the result of N! (N factorial).</p>
<p>Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0 .</p>
</blockquote>
<p>Here's my solution in C++:</p>
<pre><code>#include <iostream>
int factorial( int n ) {
if(n<=1)
return 1 ;
else{
return n * factorial (n-1) ;
}
}
int main() {
int n;
std::cin >> n;
std::cout << factorial (n) ;
}
</code></pre>
<p>Is there a more efficient solution to this problem?</p>
| [] | [
{
"body": "<p>Yes, there is a more efficient solution that still uses recursion; specifically, using <a href=\"https://en.m.wikipedia.org/wiki/Tail_call\" rel=\"nofollow noreferrer\">Tail Recursion</a>.</p>\n\n<p>When you <code>return n * factorial(n-1);</code>, the compiler can’t optimize the call away because... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T23:12:36.687",
"Id": "197621",
"Score": "1",
"Tags": [
"c++",
"programming-challenge",
"recursion",
"functional-programming"
],
"Title": "Hackerrank Day 9: Recursion"
} | 197621 |
<p>I wrote an algorithm to solve this challenge but would love some feedback on its efficiency and, if you were an interviewer, what your opinion would be on my solution. I believe my time complexity is \$O(N)\$. Is this correct?</p>
<p><strong>The Task:</strong></p>
<blockquote>
<p>Given a sorted array <em>nums</em>, remove the duplicates in-place such that
each element appear only once and return the new length.</p>
<p>Do not allocate extra space for another array, you must do this by
modifying the input array in-place with O(1) extra memory.</p>
<blockquote>
<p><strong>Example:</strong>
Given <em>nums</em> = [0,0,1,1,1,2,2,3,3,4]</p>
<p>Your function should return length = 5, with the first five elements of <em>nums</em> being modified to 0, 1, 2, 3, and 4 respectively.</p>
<p>It doesn't matter what values are set in the array beyond the returned length.</p>
</blockquote>
</blockquote>
<p><strong>My Solution:</strong></p>
<pre><code>def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if(nums):
IndFirstKind = IndCompare = 0
lengthArray = len(nums)
while(IndCompare < lengthArray):
if nums[IndFirstKind] == nums[IndCompare]:
IndCompare = IndCompare + 1
else:
if(IndFirstKind + 1 != IndCompare):
temp = nums[IndCompare]
nums[IndCompare] = nums[IndFirstKind + 1]
nums[IndFirstKind + 1]= temp
IndFirstKind = IndFirstKind +1
IndCompare = IndCompare + 1
return IndFirstKind + 1
return 0
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Flat is better than nested. Consider reverting the first <code>if</code> condition:</p>\n\n<pre><code>if not nums:\n return 0\n\n# main logic goes here, less one indentation level\n</code></pre></li>\n<li><p>An <code>if-else</code> as a body of the loop is always a red flag. In this c... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T23:17:54.380",
"Id": "197622",
"Score": "2",
"Tags": [
"python",
"performance",
"programming-challenge",
"python-2.x",
"interview-questions"
],
"Title": "Given a sorted array nums, remove the duplicates in-place"
} | 197622 |
<p>I had written code in C++ to create transformation filters to get input, sort (custom_sorting and existing sorting routine) and write the output to stdin and file. When I presented it to my teacher, he ran it on a considerably huge file and observed that my custom sorting routine took over 5 minutes to complete. He mentioned that instead of using hash maps to store the input and do the sorting, if I re-wrote the entire code using structs/classes in a more structured oriented way, I could get it to finish sorting within 10 seconds instead of 5 minutes. I am rusty when it comes to following a structured oriented approach. Can anyone help with re-writing the following code in a more structured oriented way using objects and classes/structs in C++?</p>
<pre><code>#include <sstream>
#include <iostream>
#include <algorithm>
#include <string>
#include <unistd.h>
#include <sys/time.h>
#include <getopt.h>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <vector>
#include <fstream>
#include <map>
#include <iterator>
#include <tr1/unordered_map>
using namespace std::tr1;
using namespace std;
vector <string> str;
void
custom_sort (vector <string> str, int num)
{
int round, r, i;
for (round = 0; round < num; round++) {
for (i = 0; i < num-1; i++) {
r = str[i].compare(str[i+1]);
if (r > 0) {
string s = "";
s = str[i];
str[i] = str[i+1];
str[i+1] = s;
}
}
}
}
string
getField (string input_str, char ch, int fieldNum)
{
istringstream ss(input_str);
string temp;
string field;
int count = 0;
vector <string> input;
while(getline(ss,temp,ch)) {
if(count < fieldNum) {
input.push_back(temp);
count++;
}
}
field = input.back();
//cout << "Hey this is the field : " << field << endl;
return field;
}
int
main(int argc, char** argv)
{
int c;
int items = 0;
unordered_map<string, vector<string> > output;
unordered_map<string, vector<string> > custom_output;
string action_variable = "";
string input_variable = "";
string output_variable = "";
string separation_variable = "";
int field_variable = 0;
while(1) {
int option_index = 0;
struct option long_options[] = {
{"action", required_argument, 0, 'a'},
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{"separator", required_argument, 0, 's'},
{"field", required_argument, 0, 'f'},
};
c = getopt_long(argc, argv, "a:i:o:s:f:",long_options, &option_index);
if (c == -1) {
break;
}
switch (c) {
case 'a':
action_variable = optarg;
cout << "action :" << action_variable << endl;
break;
case 'i':
input_variable = optarg;
cout << "input :" << input_variable << endl;
break;
case 'o':
output_variable = optarg;
cout << "output :" << output_variable << endl;
break;
case 's':
separation_variable = optarg;
cout << "Separation variable :" << separation_variable << endl;
break;
case 'f':
field_variable = atoi(optarg);
cout << "Field variable :" << field_variable << endl;
break;
default:
cout << "Usage: myfilter --input arg --action arg --output arg" << action_variable << endl;
exit(0);
}
}
string name = "";
char ch = separation_variable[0];
ifstream myfile;
myfile.open (input_variable.c_str());
if (myfile.is_open()) {
while(getline(myfile,name)) {
string field = getField(name,ch,field_variable);
output[field].push_back(name);
custom_output[field].push_back(name);
str.push_back(field);
items++;
}
myfile.close();
}
else {
cout << "Unable to open file. Enter values in the standard input" << endl;
while (getline(cin,name)) {
string field = getField(name,ch,field_variable);
output[field].push_back(name);
custom_output[field].push_back(name);
str.push_back(field);
items++;
}
}
struct timeval tv1, tv2;
struct timeval qtv1, qtv2;
double start_time = gettimeofday(&tv1, NULL);
vector <string> custom_sort_output;
//sorting = custom sorting routine
custom_sort(str,items);
int strLength = str.size();
for(int i = 0; i < strLength; i++) {
if(output.find(str[i]) != output.end()) {
vector <string> temp = output[str[i]];
int sz = temp.size();
for(int j = 0; j < sz; j++) {
custom_sort_output.push_back(temp[j]);
}
}
}
double end_time = gettimeofday(&tv2, NULL);
double q_start_time = gettimeofday(&qtv1, NULL);
//sorting using an ordered_map
map <string,vector<string> > sorted_output(output.begin(), output.end());
double q_end_time = gettimeofday(&qtv2, NULL);
printf ("Total time to read, sort and display from standard input using my sorting routine = %f seconds\n",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
printf ("Total time to read, sort and display from standard input using my sorting routine = %f seconds\n",(double) (qtv2.tv_usec - qtv1.tv_usec) / 1000000 + (double) (qtv2.tv_sec - qtv1.tv_sec));
//printing the output
ofstream outputfile;
outputfile.open(output_variable.c_str());
if (outputfile.is_open()) {
for( map<string, vector<string> >::iterator it = sorted_output.begin(); it != sorted_output.end(); ++it) {
int length = it->second.size();
for(int i = 0; i < length; i++) {
outputfile << it->second[i] << endl;
}
}
outputfile.close();
}
else {
for( map<string,vector<string> >::iterator it = sorted_output.begin(); it != sorted_output.end(); ++it) {
int length = it->second.size();
for(int i = 0; i < length; i++) {
outputfile << it->second[i] << endl;
}
}
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T13:01:57.650",
"Id": "381051",
"Score": "0",
"body": "What is `getopt.h`? it seems instrumental, but I don't get where it comes from. More generally, could you explain us how the input data is structured, and what you need to do wit... | [
{
"body": "<p>Your code doesn't seem to work. However, let's break down just the sort routine, since that's what you seem to think is the bottleneck.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Get in the habit of <strong>not</strong> <code>using namespace</code> anything. Then you won't have to... | {
"AcceptedAnswerId": "197628",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-01T23:48:58.500",
"Id": "197625",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"sorting",
"time-limit-exceeded",
"homework"
],
"Title": "C++ code to read, sort, and write data"
} | 197625 |
<p>I created an MVC router based on knowledge of an MVC design pattern.</p>
<p>It will simply take a URL as a string (class/method/params...), then it will instantiate a requested class controller and call its method.</p>
<p>In my class, I call a controller method and then include the view at the same time to display data.</p>
<p>My questions are:</p>
<ul>
<li>Is this a valid MVC router?</li>
<li>Is it good practice to make this class call include views for our application?</li>
</ul>
<p></p>
<pre><code>class FrontController {
//default view
private $view = 'index';
//default methode
private $method = 'indexMethode';
//default controller
private $controller = 'Page';
//this attribute to store data returned
private $data;
//to store methode parameters from url.
private $param;
public function __construct() {
//getting user url request
$url = $this->getUrl();
//checking user input
if (isset($url[0])) {
//getting class name from user input
$this->controller = ucwords($url[0]);
unset($url[0]);
}
//checking if class file exsiste if yes we include it
if(file_exists('controllers/'.$this->controller.'.php')){
require 'controllers/'.$this->controller.'.php';
}
//instantiating the demanded class
$this->controller = new $this->controller;
//getting demanded class method if it is demanded by user
if (isset($url[1])) {
if(method_exists($this->controller, $url[1]))
$this->method = $url[1];
}
//checking if there is a view for our request
if(file_exists('view/'.$url[1].'.php')){
//setting the sutable template for the methode
$this->view = $url[1];
unset($url[1]);
}
//Getting methode parameters from user input if exsist
$this->param = $url ? array_values($url) : [];
//Calling the methode and getting the result
$this->data = call_user_func_array([$this->controller,
$this->method], $this->param);
//Getting the sutable page for the responde to display it.
include 'view/' . $this->view . '.php';
}
//To get any private var in our class
public function __get($name) {
return $this->$name;
}
//Here we are gona take user input and devide it as array element
public function getUrl() {
//checking user input and filtring it for unwanted charecters
if (!empty($_GET['url'])) {
// remove / char from url
$url = rtrim($_GET['url'], '/');
//Checking url for unwanted chars
$url = filter_var($url, FILTER_SANITIZE_URL);
//forming array from url
$url = explode('/', $url);
//Sending back url array
return $url;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T08:09:48.903",
"Id": "381020",
"Score": "0",
"body": "One problem I can see is that of security. Given this code anybody can call any of your public controller methods with any arguments. You will have to be very dissiplined and pro... | [
{
"body": "<h2>Dependency Injection</h2>\n\n<p>You instantiate all the controllers with <code>new $this->controller</code> what if my controller has dependencies ? Instead of your controllers looking like this; </p>\n\n<pre><code>public function __construct() {\n $this->xyz = new xyz();\n}\n</code></pre... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T00:49:35.597",
"Id": "197627",
"Score": "1",
"Tags": [
"php",
"mvc"
],
"Title": "Creating an MVC router"
} | 197627 |
<p>I have to convert a JsonArray to an ArrayList but unfortunately the code below is used very often during the execution of the program! How can I speed it up?</p>
<p><strong>Java:</strong></p>
<pre><code>public static ArrayList CastJsonObject(JSONArray object) {
ArrayList<Cantiere> tm = new ArrayList<Cantiere>();
Cantiere cant;
Cliente c;
try {
for (int i = 0; i < object.length(); i++) {
JSONObject value = object.getJSONObject(i);
int IdCantiere = Integer.parseInt(value.getString("IdCantiere").toString());
int IdCliente = Integer.parseInt(value.getString("IdCliente").toString());
String Filiale = value.getString("Filiale").toString();
String RagioneSociale = value.getString("RagioneSociale").toString();
String NomeCantiere = value.getString("NomeCantiere").toString();
String DataCreazioneCantiere = value.getString("DataCreazioneCantiere").toString();
String Tipologia = value.getString("Tipologia").toString();
String StatoCantiere = value.getString("StatoCantiere").toString();
int StatoFatturazione = Integer.parseInt(value.getString("StatoFatturazione").toString());
c = new Cliente(IdCliente, RagioneSociale, Filiale);
cant = new Cantiere(c, IdCantiere, NomeCantiere, DataCreazioneCantiere, Tipologia, StatoCantiere, StatoFatturazione);
tm.add(cant);
}
} catch (Exception ex) {
System.out.println("\n Error: " + ex);
}
return tm;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T07:04:12.983",
"Id": "381012",
"Score": "0",
"body": "It would help us a lot if you added an example of the data you're parsing. `JSONObject` also looks like this is about adroid..."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<p>If there really is a performance problem with that code, please back this up with some measurements. Otherwise, read some articles concerning premature optimization and don't bother.</p>\n\n<p>Nevertheless, on micro-level there are a few calls that you don't need:</p>\n\n<p>Get rid of superfluous ... | {
"AcceptedAnswerId": "197645",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T06:55:03.803",
"Id": "197635",
"Score": "1",
"Tags": [
"java",
"performance",
"json"
],
"Title": "Slow Converting from JsonArray to ArrayList"
} | 197635 |
<p>I have a class that handles interactions with a custom rest/json webserver, for the purposes of handling online game matchmaking etc. I want the class to have very simple public functions like <code>Server.Login()</code> and <code>Server.JoinMatch()</code>, so they can be connected up at the UI layer easily. As you will see from the code fairly quickly, there is a lot of repeated code in each function, which I want to refactor out.</p>
<p>The first part of each function ensures only one operation at once. The next bit defines a callback delegate for when the request is finished (async). And the last part starts the actual request operation.</p>
<pre class="lang-cs prettyprint-override"><code>public class Server
{
#region Fields
public string playerName { get; private set; }
public string playerID { get; private set; }
public string playerToken { get; private set; }
public string currentMatchID { get; private set; }
private Patterns.State<ServerState> state = new Patterns.State<ServerState>();
#endregion
public Server()
{
state.Add(ServerState.Idle);
}
public void Login(string playerName, Action<TcpRequest> onSuccess = null, Action<TcpRequest> onError = null)
{
// Throw exception already busy with an operation
if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); }
// Define login callback action
Action<TcpRequest> loginCallback = delegate (TcpRequest request)
{
// Add idle state back in
state.Add(ServerState.Idle);
// Check if the request succeeded
if (request.OK)
{
// Store player data in class
playerName = (string)request.requestJson["player_name"];
playerID = (string)request.responseJson["player_id"];
playerToken = (string)request.responseJson["player_token"];
// Add the logged in state
state.Add(ServerState.LoggedIn);
// Call the onSuccess callback if provided
onSuccess?.Invoke(request);
}
// Login failed, call the onError callback if provided
else { onError?.Invoke(request); }
};
// Remove idle state
state.Remove(ServerState.Idle);
// Perform request
Request("login", callback: loginCallback, requestJson: new Dictionary<string, object> { { "player_name", playerName }, { "client_version", "test1" } });
}
public void CreateMatch(string matchName, Action<TcpRequest> onSuccess = null, Action<TcpRequest> onError = null)
{
// Throw exception already busy with an operation
if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); }
// Define callback action
Action<TcpRequest> callback = delegate (TcpRequest request)
{
// Add idle state back in
state.Add(ServerState.Idle);
// Check if the request succeeded
if (request.OK)
{
// Add the inLobby state
state.Add(ServerState.InLobby);
// Call the onSuccess callback if provided
onSuccess?.Invoke(request);
}
// Request failed. Call the onError callback if provided
else { onError?.Invoke(request); }
};
// Remove idle state
state.Remove(ServerState.Idle);
// Perform request
AuthenticatedRequest("match/create", callback: callback, requestJson: new Dictionary<string, object> { { "match_name", matchName } });
}
public void JoinMatch(string matchID, Action<TcpRequest> onSuccess = null, Action<TcpRequest> onError = null)
{
// Throw exception already busy with an operation
if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); }
// Define callback action
Action<TcpRequest> callback = delegate (TcpRequest request)
{
// Add idle state back in
state.Add(ServerState.Idle);
// Check if the request succeeded
if (request.OK)
{
// Add the inLobby state
state.Add(ServerState.InLobby);
// Set currentMatchID in class
currentMatchID = (string)request.responseJson["match_id"];
// Call the onSuccess callback if provided
onSuccess?.Invoke(request);
}
// Request failed. Call the onError callback if provided
else { onError?.Invoke(request); }
};
// Perform request
AuthenticatedRequest("match/join", callback: callback, requestJson: new Dictionary<string, object> { { "match_id", matchID } });
}
private void Request(string resource, Action<TcpRequest> callback = null, Dictionary<string, object> requestJson = null)
{
// Start async request, invoke callback when done
}
private void AuthenticatedRequest(string resource, Action<TcpRequest> callback = null, Dictionary<string, object> requestJson = null)
{
// Add login auth data into the requestJson dict or throw exception if we aren't logged in
// Call Request()
}
}
</code></pre>
<p>Notes:</p>
<ul>
<li>Patterns.State class is basically a hashset that keeps track of what states an object has. When a server transaction is in progress, I remove the Idle state, and add it back in when its done. To prevent concurrent transactions, I check for the presence of the Idle state.</li>
<li>I am restricted to c#6, .net 4.7 (Unity)</li>
</ul>
<p>EDIT1: I tweaked the callbacks, so that instead of having one callback in the TcpRequest and having it call other things, I added a callback list for onSuccess and onError. This means I just add extra callbacks as required, instead of redefining a master one each time.</p>
<pre><code>public void Login(string playerName, Action<TcpRequest> onSuccess=null, Action<TcpRequest> onError=null)
{
// Throw exception already busy with an operation
if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); }
// Prepare callback lists
List<Action<TcpRequest>> onSuccessCallbacks = new List<Action<TcpRequest>>();
List<Action<TcpRequest>> onErrorCallbacks = new List<Action<TcpRequest>>();
// Add login callback action
onSuccessCallbacks.Add(delegate (TcpRequest request)
{
// Add idle state back in
state.Add(MakoState.Idle);
// Store player data in class
playerName = (string)request.requestJson["player_name"];
playerID = (string)request.responseJson["player_id"];
playerToken = (string)request.responseJson["player_token"];
// Add the logged in state
state.Add(MakoState.LoggedIn);
});
// Add onSuccess/onError callback args if not null
if (onSuccess != null) { onSuccessCallbacks.Add(onSuccess); }
if (onError != null) { onErrorCallbacks.Add(onError); }
// Remove idle state
state.Remove(MakoState.Idle);
// Perform request (using NoAuth method as we aren't logged in yet)
Request("login", onSuccess=onSuccessCallbacks, onError=onErrorCallbacks, requestJson: new Dictionary<string, object>{ {"player_name", playerName }, {"client_version", "test1" } });
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T08:41:05.050",
"Id": "381022",
"Score": "0",
"body": "Is the class itself meant to be thread-safe, or are you just worried about asynchronous call-backs? (i.e. are you intending to address the concern of these methods being called c... | [
{
"body": "<p>I'm answering instead of just editing the original with updates, as these changes solve my initial problem. I'm still interested to see if anyone comes up with anything else or has any other feedback. </p>\n\n<ul>\n<li>Moved the idle state check <code>if(!state.Has(ServerState.Idle))</code> into <... | {
"AcceptedAnswerId": "197654",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T07:28:22.897",
"Id": "197638",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Server Request Class, Async Callbacks"
} | 197638 |
<p>I have written a simple JavaScript function to make an array reactive (i.e. observable). Is there anything I could improve? What the code does is take an array, a callback and a <code>this</code> value as arguments, then whenever the array gets updated or a value gets added to it, it runs the callback with the specified <code>this</code> value. It works similar to the obsolete <code>Array.observe()</code>.</p>
<pre><code>function arrayObserve(array, callback, thisArg){
var result = [];
result.push.apply(result, array);
function getterAndSetter() {
if (Array.isArray(array))
var currentArray = result;
else
var currentArray = Object.keys(result);
console.log(result);
currentArray.forEach( function(prop){
if (Array.isArray(result))
var currentProp = result.lastIndexOf(prop);
else
var currentProp = prop;
Object.defineProperty(array, currentProp, {
configurable: true,
enumerable: true,
set: function(val) {
result[currentProp] = val;
callback.call(thisArg, result);
},
get: function() {
return result[currentProp];
}
});
//}
if (typeof result[currentProp] == 'object') {
arrayObserve(result[currentProp], callback, result);
}
});
}
getterAndSetter();
['pop','push','reverse','shift','unshift','splice','sort','map','filter'].forEach( function(method){
Object.defineProperty(array, method, {
configurable: false,
enumerable: false,
writable: true,
value: function () {
var noReturnMethods = ['push', 'pop', 'reverse', 'shift', 'unshift'];
if (noReturnMethods.indexOf(method) > -1) {
Array.prototype[method].apply(result, arguments);
} else {
var results = Array.prototype[method].apply(result, arguments);
result = results;
}
callback.call(thisArg, result);
getterAndSetter();
return result;
}
});
});
return result;
}
</code></pre>
| [] | [
{
"body": "<p>Some minor nit-picks about your code.</p>\n\n<blockquote>\n<pre><code>Object.defineProperty(array, method, {\n configurable: false,\n enumerable: false,\n writable: true,\n value: function () {\n // ...\n</code></pre>\n</blockquote>\n\n<p>Here, <code>configurable</code> and <cod... | {
"AcceptedAnswerId": "198178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T09:32:39.773",
"Id": "197647",
"Score": "4",
"Tags": [
"javascript",
"array",
"observer-pattern"
],
"Title": "Make an Array Reactive (Observable)"
} | 197647 |
<p>My new mobile phone is capable of importing contact information from a renamed *.VCF file stored on an SD memory card (<a href="https://www.quora.com/How-do-I-sync-contacts-on-Nokia-130" rel="nofollow noreferrer">https://www.quora.com/How-do-I-sync-contacts-on-Nokia-130</a>). Annoyingly, it does not work very well for contacts with multiple phone numbers or anything not tagged as <code>TEL:</code> or <code>TEL;TYPE=CELL:</code>.</p>
<p>The following script takes an *.vcf file, parses the stored contact information as needed - first name, last name and phone numbers - and outputs the information in a way that the phone imports it correctly. Therefore, each contact may only contain one number. For multiple numbers, a contact will be duplicated for each phone number. The resulting string is simply printet out.</p>
<pre><code>#!/usr/bin/python
import re
class Contact(object):
"""
Contains the contact infromation,
including a list of phone numbers.
Arguments:
object {[type]} -- [description]
"""
def __init__(self):
self.FirstName = ""
self.LastName = ""
self.Phonenumbers = []
def extract_number(line):
"""
Extracts the phone number from a vCard-file line,
by removing everything but numbers and '+'
Arguments:
line {string} -- the line to extract the phone number from
Returns:
string -- the phone number
"""
line = line[line.index(":")+1:].rstrip()
line = re.sub('[^0-9+]', '', line)
return line
def generate_vcard_contact_string(contact):
"""
Generates the vCard string for this contact.
Will generate a sperate vCard for each phone number of the contact.
Arguments:
contact {Contact} -- the contact to generate the vCard string from
Returns:
string -- the generated vCard string
"""
base = f"BEGIN:VCARD\n"
base += f"N:{contact.LastName};{contact.FirstName}\n"
base += f"TEL:{{phone_number}}\n" # use '{phone_number}' as a placeholder.
# Will be replaced by actual number.
base += f"END:VCARD\n"
result = ""
for number in contact.Phonenumbers:
# Add the base string for this contact,
# replace {phone_number} with actual number
result += base.replace("{phone_number}", number)
return result
contacts = []
with open(r'contacts.vcf') as f:
current_contact = Contact()
for line in f:
# Some lines are build like "item1.TEL;...",
# remove "item1.", "item2.", to ease parsing
if line.startswith("item"):
line = line[line.index(".")+1:]
if "BEGIN:VCARD" in line:
# Marks the start of a vCard,
# create a blank contact to work with
current_contact = Contact()
elif line.startswith("N:"):
# Line contains a name in the format N:LastName;FirstName;...;...;
# Only LastName and FirstName will be used
line = line.replace("N:", "") # remove "N:" from line
chunks = line.split(';')
current_contact.LastName = chunks[0].strip()
current_contact.FirstName = chunks[1].strip()
elif line.startswith("TEL"):
# Line contains a phone number
# phone number type may be specified by "TYPE=...",
# currently, TYPE will ne omitted
# One contact may contain multiple phone numbers.
number = extract_number(line)
current_contact.Phonenumbers.append(number)
elif "END:VCARD" in line:
# Marks the end of a vCard,
# append contact to list
contacts.append(current_contact)
result = ""
for contact in contacts:
# Generate a string containing a vCard for each of the contacts phone
# numbers, append those string to create one big text containing everything
result += generate_vcard_contact_string(contact)
print(result)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T08:34:54.780",
"Id": "381140",
"Score": "1",
"body": "Did you consider using one of the [Python packages handling the VCF format](https://pypi.org/search/?q=vcf)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "... | [
{
"body": "<p>Your function <code>generate_vcard_contact_string</code> obviously belongs to the <code>Contact</code> class. It even takes a <code>Contact</code> instance as the first argument.</p>\n\n<p>I would actually elevate this to be the magic <code>__str__</code> method, which is for example called when y... | {
"AcceptedAnswerId": "197865",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T11:19:41.437",
"Id": "197652",
"Score": "3",
"Tags": [
"python",
"parsing",
"reinventing-the-wheel",
"converting"
],
"Title": "Convert *.VCF contact file for cellphone import"
} | 197652 |
<p>Could you please correct me if I'm not following best practices or code optimizations? It is working fine in test environment planning to deploy.</p>
<p>Trigger does two tasks:</p>
<ol>
<li><p>Gives an error when trying to change case owner from</p>
<ol>
<li>DS Service Queue</li>
<li>Data Services</li>
<li>RFP, Data Services and Case fields <code>Categiry__c</code> or <code>Sub_Department__c</code> is null (should not allow to change case owner if Category and Sub Department is null on queues mentioned)</li>
</ol></li>
<li><p>When case owner changes to Queues</p>
<ol>
<li>Marketing Queue</li>
<li>G&T Service Queue</li>
<li>CCSC Queue</li>
<li>E-Commerce</li>
<li>Guest Assistance Queue respective case fields <code>RecordTypeId</code>, <code>Department__c</code>, <code>Sub_Department__c</code>, <code>Category__c</code> should update with respective values</li>
</ol></li>
</ol>
<p></p>
<pre><code>trigger updateCase on Case (before update) {
Set<Id> QIds = new Set<Id>();
list<RecordType> rc= new list<RecordType>();
list <Group> gc=new list<group>();
list <id> caseid=new list<id>();
list <Group> g=new list<group>();
//Get the Ids of the different Queues
Id MarkeRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('Marketing').getRecordTypeId();
Id GTGrLRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('G&T Group Leads').getRecordTypeId();
Id CCSCRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('CCSC').getRecordTypeId();
Id EcomRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('E-Commerce').getRecordTypeId();
Case oldC = new Case();
for (Case c:trigger.new)
{
oldC = trigger.oldMap.get(c.Id);
}
rc=[Select ID, Name From RecordType Where sObjectType = 'case' and id=:oldc.RecordTypeId limit 1 ];
gc=[select id, Name from Group where id =:Trigger.new[0].ownerid and Type = 'Queue'];
g=[select Id, Name from Group where Type = 'Queue'];
for( Group qu :g){
if(qu.Name == 'DS Service Queue' || qu.Name == 'Data Services RFP' || qu.Name == 'Data Services')
QIds.add(qu.Id);
}
//Loop through all Cases and check owner change
system.debug('oldrecord type==>+' + oldc.RecordTypeId );
for (Case c:trigger.new)
{
oldC = trigger.oldMap.get(c.Id);
System.debug('Oldc'+ oldc);
System.debug('RecordTypename' + oldc.RecordType.name);
// Guest Assistance Project Requirments - Auto stamp Department and Sub-Department when a GA case is re-assigned to other Queues
if (oldC.OwnerId != c.OwnerId && QIds.contains(oldC.OwnerId))
{
c.Status = 'Open';
if (c.Category__c == null || c.Sub_Department__c == null)
c.addError('You must provide a value for Category and Sub Department before changing the Case Owner');
}
for(RecordType rt : rc) {
system.debug('Record Type name ==>' + rt.Name);
if(rt.Name == 'Guest Assistance') {
System.debug('RecordTypeIds ==>'+ 'Marketing==>' + MarkeRecoTyId + ' ' + 'G&T Group Leads==>'+ GTGrLRecoTyId + ' ' + 'CCSC==>' + CCSCRecoTyId + ' ' + 'E-Commerce ==>' + EcomRecoTyId );
for( Group qu :gc){
if (qu.name == 'Marketing Queue') {
c.RecordTypeId = MarkeRecoTyId;
c.Department__c = 'Marketing';
c.Sub_Department__c = 'Marketing';
c.Category__c = 'Website Feature';
}
if (qu.name == 'G&T Service Queue' || Test.isRunningTest() ) {
c.RecordTypeId = GTGrLRecoTyId;
c.Department__c = 'Group & Tour';
c.Sub_Department__c = 'Group & Tour';
c.Category__c = 'Group Event';
}
if (qu.name == 'CCSC Queue'||Test.isRunningTest()) {
c.RecordTypeId = CCSCRecoTyId;
c.Department__c = 'Guest Assistance';
c.Sub_Department__c = 'Guest Assistance';
c.Category__c = null ;
}
if (qu.name == 'E-Commerce'||Test.isRunningTest()) {
c.RecordTypeId = EcomRecoTyId;
c.Department__c = 'E-Commerce';
c.Sub_Department__c = 'E-Commerce';
c.Category__c = 'Other';
}
}
}
else if ((rt.Name == 'Marketing') || (rt.Name == 'G&T Group Leads') || (rt.Name == 'CCSC') || (rt.Name == 'E-Commerce'|| Test.isRunningTest())) {
Id GuesRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('Guest Assistance').getRecordTypeId();
for( Group qu :gc){
if (qu.name == 'Guest Assistance Queue') {
c.RecordTypeId = GuesRecoTyId;
c.Department__c = 'Guest Assistance';
c.Sub_Department__c = 'Guest Assistance';
c.Category__c = null;
}
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T15:17:12.053",
"Id": "381068",
"Score": "0",
"body": "Hey welcome to Code Review! So, what does your code actually do, besides being a trigger? Some explanation goes a long way for reviewers to understand your code."
},
{
"C... | [
{
"body": "<p>I'm no Apex expert, nor coding expert in general. I do deal with Apex triggers quite a bit, both my own and those written by others.</p>\n\n<p>Ultimately, I don't see any practices which break any of the <a href=\"https://developer.salesforce.com/blogs/developer-relations/2015/01/apex-best-practic... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T11:58:56.437",
"Id": "197655",
"Score": "1",
"Tags": [
"salesforce-apex"
],
"Title": "Trigger corrections"
} | 197655 |
<p>The question is from <a href="https://www.hackerearth.com/zh/practice/data-structures/linked-list/singly-linked-list/practice-problems/algorithm/remove-friends-5/" rel="nofollow noreferrer">here</a>.</p>
<blockquote>
<p>Given two numbers N and K where N is the number of nodes and K is the number of nodes to be deleted, delete K nodes whose data is less than their next node's data. If no such nodes exist, delete the last node.</p>
</blockquote>
<p>But it is still giving me TLE. I tried all the optimisations that could occur to me. I know this can be done with stacks but I would like to know if it can't done in the allocated time with linked lists.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
struct Node
{
int value;
struct Node *next;
};
void addnode(struct Node** head, struct Node** tail, int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->value = data;
temp->next = nullptr;
if( *head == nullptr)
{
*head = temp;
*tail = *head;
return;
}
(*tail)->next = temp;
*tail = temp;
}
void deleteNode(struct Node** head, struct Node** prev, struct Node** temp)
{
if( (*prev)->next == *head)
{
*head = (*prev)->next->next;
return;
}
(*prev)->next = (*temp)->next;
}
void deletenodeatlast(struct Node** prev)
{
(*prev)->next = (*prev)->next->next;
}
void display(struct Node* head)
{
struct Node* p = head;
while(p != nullptr)
{
printf("%d ", p->value);
p = p->next;
}
printf("\n");
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
struct Node* head = nullptr;
struct Node* tail = head;
int N, K;
scanf("%d %d", &N, &K);
for(int i = 0; i < N; i++)
{
int data;
scanf("%d", &data);
addnode(&head, &tail, data);
}
for(int i = 0; i < K; i++)
{
bool isGreater = false;
struct Node* p = head;
struct Node* prev = (struct Node*)malloc(sizeof(struct Node));
prev->value = 1000000;
prev->next = p;
while( p->next != nullptr)
{
if( p->value < p->next->value)
{
deleteNode(&head, &prev, &p);
isGreater = true;
}
else
{
prev = p;
p = p->next;
}
if( isGreater )
{
break;
}
}
if( !isGreater)
{
deletenodeatlast(&prev);
}
}
display(head);
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T13:50:51.047",
"Id": "381057",
"Score": "0",
"body": "Do you want this reviewed as pure C (which is how you wrote the code), or C++ (which is how you tagged it)? Because, as C++, a review amounts to a full re-write."
},
{
"C... | [
{
"body": "<h2>Initialize your variables:</h2>\n\n<p>Leaving variables in uninitialized states is generally a bad idea, get into the habit of always giving them a value:</p>\n\n<pre><code>int T = 0;\n</code></pre>\n\n<p>The small additional amount of work required will soon become second nature, and in the long... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T13:06:34.063",
"Id": "197656",
"Score": "0",
"Tags": [
"c++",
"linked-list"
],
"Title": "Delete K nodes in a linked list having their data less than the next node's"
} | 197656 |
<p>After implementing suggestions from my previous questions about <a href="https://codereview.stackexchange.com/questions/197076/shortest-job-first-preemptive/197177#197177">SJF</a>, <a href="https://codereview.stackexchange.com/questions/197269/priority-scheduling-algorithm-preemptive/197325?noredirect=1#comment380390_197325">priority</a> and <a href="https://codereview.stackexchange.com/questions/197498/round-robin-scheduling-algorithm/197554?noredirect=1#comment380947_197554">round robin</a>.</p>
<p>Here I have <code>scheduling.h</code> which contains a struct <code>Data</code> and <code>virtual</code> member functions. Then I have derived class for each scheduling algorithm. Only <code>calcEndTime()</code> is defined for each scheduling algorithm. I have asked to enter priority in each algortihm because it must be in <code>Data</code> so it is bounded to <code>arrivalTime</code> and <code>burstTime</code>. This is first time I have written program related to inheritance. Suggest me improvements.</p>
<p>scheduling.h</p>
<pre><code>#ifndef SCHEDULING_H_
#define SCHEDULING_H_
#include <vector>
class Scheduler
{
public:
double avgWaitingTime;
double avgTurnAroundTime;
struct Data
{
unsigned arrivalTime;
//When process start to execute
unsigned burstTime;
//only for priority Scheduling
unsigned priority;
Data(unsigned arrivalTime, unsigned burstTime, unsigned priority):
arrivalTime(std::move(arrivalTime)),
burstTime(std::move(burstTime)),
priority(std::move(priority))
{}
Data() = default;
};
std::vector<Data> data;
//process wait to execute after they have arrived
std::vector<unsigned> waitingTime;
//total time taken by processes
std::vector<unsigned> turnAroundTime;
//time when a process end
std::vector<unsigned> endTime;
Scheduler(unsigned num = 0);
Scheduler(const Scheduler&) = delete;
Scheduler &operator=(const Scheduler&) = delete;
Scheduler(Scheduler&&) = delete;
Scheduler &operator=(Scheduler&&) = delete;
~Scheduler() = default;
void calcWaitingTime();
void calcTurnAroundTime();
virtual void calcEndTime() = 0;
void printInfo() const;
};
#endif
</code></pre>
<p>scheduling.cpp</p>
<pre><code>#include <iostream>
#include <vector>
#include "scheduling.h"
Scheduler::Scheduler(unsigned num): endTime(num, 0)
{
unsigned arrivalVal, burstVal, priorityVal;
data.reserve(num);
endTime.reserve(num);
waitingTime.reserve(num);
turnAroundTime.reserve(num);
std::cout << "\nEnter arrival time and burst time and priority eg(5 18 2)\n";
std::cout << "If it is not priority scheduling enter 0 for priority\n";
std::cout << "Lower integer has higher priority\n";
for (unsigned i = 0; i < num; i++)
{
std::cout << "\nProcess" << i+1 << ": ";
std::cin >> arrivalVal >> burstVal >> priorityVal;
data.push_back( Data(arrivalVal, burstVal, priorityVal) );
}
}
void Scheduler::calcTurnAroundTime()
{
double sum = 0.00;
for (std::size_t i = 0; i < data.size(); i++)
{
unsigned val = endTime[i] - data[i].arrivalTime;
turnAroundTime.push_back(val);
sum += (double)val;
}
avgTurnAroundTime = sum / turnAroundTime.size();
}
void Scheduler::calcWaitingTime()
{
double sum = 0.00;
for (std::size_t i = 0; i < data.size(); i++)
{
unsigned val = turnAroundTime[i] - data[i].burstTime;
waitingTime.push_back(val);
sum += (double)val;
}
avgWaitingTime = sum / waitingTime.size();
}
void Scheduler::printInfo() const
{
std::cout << "ProcessID\tArrival Time\tBurst Time\tPriority\tEnd Time\tWaiting Time";
std::cout << "\tTurnaround Time\n";
for (std::size_t i = 0; i < data.size(); i++)
{
std::cout << i+1 << "\t\t" << data[i].arrivalTime << "\t\t";
std::cout << data[i].burstTime << "\t\t" <<data[i].priority << "\t\t";
std::cout << endTime[i] << "\t\t";
std::cout << waitingTime[i] <<"\t\t" << turnAroundTime[i] <<'\n';
}
std::cout << "Average Waiting Time : " << avgWaitingTime << '\n';
std::cout << "Average Turn Around Time : " << avgTurnAroundTime << '\n';
}
</code></pre>
<p>shortestjobfirst.h</p>
<pre><code>#ifndef SHORTESTJOBFIRST_H_
#define SHORTESTJOBFIRST_H_
#include "scheduling.h"
class ShortestJobFirst : public Scheduler
{
public:
ShortestJobFirst(unsigned num);
ShortestJobFirst() = default;
ShortestJobFirst(const ShortestJobFirst&) = delete;
ShortestJobFirst &operator=(const ShortestJobFirst&) = delete;
ShortestJobFirst(ShortestJobFirst&&) = delete;
ShortestJobFirst &operator=(ShortestJobFirst&&) = delete;
~ShortestJobFirst() = default;
void calcEndTime();
};
#endif
</code></pre>
<p>shortestjobfirst.cpp</p>
<pre><code>#include <iostream>
#include <array>
#include <vector>
#include <algorithm> // std::find
#include <iterator> // std::begin, std::end
#include <limits> //std::numeric_limits
#include "scheduling.h"
#include "shortestjobfirst.h"
ShortestJobFirst::ShortestJobFirst(unsigned num) :Scheduler(num)
{}
void ShortestJobFirst::calcEndTime()
{
//If arrival time is not sorted
//sort burst time according to arrival time
static const auto byArrival = [](const Data &a, const Data &b)
{
return a.arrivalTime < b.arrivalTime;
};
std::sort(data.begin(), data.end(), byArrival);
//copy values of burst time in new vector
std::vector<unsigned> burstTimeCopy;
for (auto it = data.begin(); it != data.end(); ++it)
{
unsigned val = (*it).burstTime;
burstTimeCopy.push_back(val);
}
unsigned timeCounter = 0;
unsigned currActiveProcessID = 0;
while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(),
[] (unsigned e) { return e == 0; })))
{
std::size_t dataSize = data.size();
//All processes are not arrived
if (timeCounter <= data[dataSize -1].arrivalTime)
{
unsigned minBurstTime = std::numeric_limits<uint>::max();
//Find index with minimum burst Time remaining
for (std::size_t i = 0; i < burstTimeCopy.size(); i++)
{
if (burstTimeCopy[i] != 0 && burstTimeCopy[i] < minBurstTime
&& data[i].arrivalTime <= timeCounter)
{
minBurstTime = burstTimeCopy[i];
currActiveProcessID = i;
}
}
burstTimeCopy[currActiveProcessID] -= 1;
timeCounter++;
if (burstTimeCopy[currActiveProcessID] == 0)
{
endTime[currActiveProcessID] = timeCounter;
}
}
else //When all processes are arrived
{
unsigned minBurstTime = std::numeric_limits<uint>::max();
//Find index with minimum burst Time remaining
for (std::size_t i = 0; i < burstTimeCopy.size(); i++)
{
if (burstTimeCopy[i] != 0 && burstTimeCopy[i] < minBurstTime)
{
minBurstTime = burstTimeCopy[i];
currActiveProcessID = i;
}
}
timeCounter += minBurstTime;
endTime[currActiveProcessID] = timeCounter;
burstTimeCopy[currActiveProcessID] = 0;
}
}
}
int main()
{
int num;
std::cout << "Enter the number of processes\n";
std::cin >> num;
ShortestJobFirst batch(num);
batch.calcEndTime();
batch.calcTurnAroundTime();
batch.calcWaitingTime();
batch.printInfo();
}
</code></pre>
<p><code>Priority</code>, <code>ShortestJobFirst</code> are nearly smae and in <code>RoundRobin</code> we have member function <code>timeQuantum</code> which is entered through constructor.</p>
<p>priorit.cpp</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm> // std::find
#include <iterator> // std::begin, std::end
#include <limits> //std::numeric_limits
#include "scheduling.h"
#include "priority.h"
Priority::Priority(unsigned num): Scheduler(num)
{}
void Priority::calcEndTime()
{
//If arrival time is not sorted
//sort burst time according to arrival time
static const auto byArrival = [](const Data &a, const Data &b)
{
return a.arrivalTime < b.arrivalTime;
};
std::sort(data.begin(), data.end(), byArrival);
//copy values of burst time in new vector
std::vector<unsigned> burstTimeCopy;
for (auto it = data.begin(); it != data.end(); ++it)
{
unsigned val = (*it).burstTime;
burstTimeCopy.push_back(val);
}
unsigned timeCounter = 0;
unsigned currActiveProcessID = 0;
while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(),
[] (unsigned e) { return e == 0; })))
{
std::size_t dataSize = data.size();
//All processes are not arrived
if (timeCounter <= data[dataSize - 1].arrivalTime)
{
unsigned maxPriority = std::numeric_limits<uint>::max();
for (std::size_t i = 0; i < burstTimeCopy.size(); i++)
{
if (burstTimeCopy[i] != 0 && data[i].priority < maxPriority
&& data[i].arrivalTime <= timeCounter)
{
maxPriority = data[i].priority;
currActiveProcessID = i;
}
}
burstTimeCopy[currActiveProcessID] -= 1;
timeCounter++;
if (burstTimeCopy[currActiveProcessID] == 0)
{
endTime[currActiveProcessID] = timeCounter;
}
}
else //When all processes are arrived
{
unsigned maxPriority = std::numeric_limits<uint>::max();
for (std::size_t i = 0 ; i < burstTimeCopy.size(); i++)
{
if (burstTimeCopy[i] != 0 && data[i].priority < maxPriority)
{
maxPriority = data[i].priority;
currActiveProcessID = i;
}
}
timeCounter += burstTimeCopy[currActiveProcessID];
burstTimeCopy[currActiveProcessID] = 0;
endTime[currActiveProcessID] = timeCounter;
}
}
}
int main()
{
int num;
std::cout << "Enter the number of processes\n";
std::cin >> num;
Priority prioritySchedule(num);
prioritySchedule.calcEndTime();
prioritySchedule.calcTurnAroundTime();
prioritySchedule.calcWaitingTime();
prioritySchedule.printInfo();
}
</code></pre>
<p>roundrobin.cpp</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm> // std::find
#include <iterator> // std::begin, std::end
#include <limits> //std::numeric_limits
#include "scheduling.h"
#include "roundrobin.h"
RoundRobin::RoundRobin(unsigned num, unsigned quantum): Scheduler(num)
{
timeQuantum = quantum;
}
void RoundRobin::calcEndTime()
{
//If arrival time is not sorted
//sort burst time according to arrival time
static const auto byArrival = [](const Data &a, const Data &b)
{
return a.arrivalTime < b.arrivalTime;
};
std::sort(data.begin(), data.end(), byArrival);
//copy values of burst time in new vector
std::vector<unsigned> burstTimeCopy;
for (auto it = data.begin(); it != data.end(); ++it)
{
unsigned val = (*it).burstTime;
burstTimeCopy.push_back(val);
}
unsigned timeCounter = 0;
while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(),
[] (unsigned e) { return e == 0; })))
{
unsigned currActiveProcessID = 0;
auto it = burstTimeCopy.begin();
while (it != burstTimeCopy.end())
{
if (burstTimeCopy[currActiveProcessID] > timeQuantum)
{
burstTimeCopy[currActiveProcessID] -= timeQuantum;
timeCounter += timeQuantum;
}
else if (burstTimeCopy[currActiveProcessID] > 0)
{
timeCounter += burstTimeCopy[currActiveProcessID];
burstTimeCopy[currActiveProcessID] = 0;
endTime[currActiveProcessID] = timeCounter;
}
currActiveProcessID++;
it++;
}
}
}
int main()
{
unsigned num, timeQuantum;
std::cout << "Enter number of process: ";
std::cin >> num;
std::cout << "\nEnter time quantum : ";
std::cin >> timeQuantum;
RoundRobin roundRobin(num, timeQuantum);
roundRobin.calcEndTime();
roundRobin.calcTurnAroundTime();
roundRobin.calcWaitingTime();
roundRobin.printInfo();
}
</code></pre>
| [] | [
{
"body": "<p>At first glance, in <code>Scheduler</code>, I would replace</p>\n\n<pre><code>std::vector<Data> data;\nstd::vector<unsigned> waitingTime;\nstd::vector<unsigned> turnAroundTime;\nstd::vector<unsigned> endTime;\n</code></pre>\n\n<p>by</p>\n\n<pre><code>struct Process {\n D... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T13:36:38.350",
"Id": "197659",
"Score": "5",
"Tags": [
"c++",
"c++11"
],
"Title": "Follow up: CPU Scheduling Algorithm (SJF, priority & Round Robin)"
} | 197659 |
<p>I apologize for that title, lol.</p>
<p>I have a Java method that I'm writing where I want to be able to pass in an array of Objects and two interfaces that will be used for lambda expressions that specify a particular value to use for calculation.</p>
<p>It's part of a larger class that I want to use for all kinds of Statistics calculations, but I started with calculating correlation because it's most relevant to the specific problem I want to solve.</p>
<pre><code>import java.lang.IllegalArgumentException;
import java.util.Arrays;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.List;
public class Statistics
{
//1. This method is really unreadable
public static <O> double getCorrelation(O[] a, Fetchable<O, Double> dataPointA, Fetchable<O, Double> dataPointB)
{
Double[] temp = Arrays.stream(a).map(x -> dataPointA.fetch(x)).collect(Collectors.toList()).toArray(new Double[0]);
Double[] temp2 = Arrays.stream(a).map(x -> dataPointB.fetch(x)).collect(Collectors.toList()).toArray(new Double[0]);
return getCorrelation(temp, temp2);
}
public static double getCorrelation(double[] a, double[] b)
{
if (a.length != b.length)
{
//2. Is this the best Exception for this case?
throw new IllegalArgumentException();
}
double sumA = 0.0;
double sumB = 0.0;
double sumSquareA = 0.0;
double sumSquareB = 0.0;
double sumAB = 0.0;
for(int i = 0; i < a.length; i++)
{
sumA += a[i];
sumB += b[i];
sumSquareA += a[i] * a[i];
sumSquareB += b[i] * b[i];
sumAB += a[i] * b[i];
}
int n = a.length;
return (n * sumAB - sumA * sumB) / (Math.sqrt(n * sumSquareA - sumA * sumA) * Math.sqrt(n * sumSquareB - sumB * sumB));
}
private static double getCorrelation(Double[] a, Double[] b)
{
if (a.length != b.length)
{
//2. Is this the best Exception for this case?
throw new IllegalArgumentException();
}
//3. Is there a better way to do this conversion from Double[] to double[]?
double doubleArrA[] = new double[a.length];
double doubleArrB[] = new double[a.length];
for (int i = 0; i < a.length; i++)
{
doubleArrA[i] = (double)a[i];
doubleArrB[i] = (double)b[i];
}
return getCorrelation(doubleArrA, doubleArrB);
}
interface Fetchable<T1, T2>
{
public T2 fetch(T1 a);
}
//main function for testing
public static void main(String[] args)
{
//this class is defined in another file; it's a simple class with four public doubles I made just to test
TestDataPoint a[] = new TestDataPoint[5];
a[0] = new TestDataPoint();
a[0].w = 3;
a[0].x = 0;
a[0].y = 4;
a[0].z = 9;
a[1] = new TestDataPoint();
a[1].w = 1;
a[1].x = 8;
a[1].y = 3;
a[1].z = 2;
a[2] = new TestDataPoint();
a[2].w = 7;
a[2].x = 4;
a[2].y = 4;
a[2].z = 0;
a[3] = new TestDataPoint();
a[3].w = 3;
a[3].x = 1;
a[3].y = 0;
a[3].z = 1;
a[4] = new TestDataPoint();
a[4].w = 6;
a[4].x = 3;
a[4].y = 9;
a[4].z = 8;
a[1] = new TestDataPoint();
System.out.println(getCorrelation(a, p -> p.w, q -> q.z));
System.out.println(getCorrelation(a, p -> p.x, q -> q.z));
System.out.println(getCorrelation(a, p -> p.y, q -> q.z));
System.out.println(getCorrelation(a, p -> p.z, q -> q.z));
}
}
</code></pre>
<p>It works pretty well; I've tried it and it seems to do exactly what I want. There are a few things I want to look at, though:</p>
<ol>
<li>That crazy method is absurdly unreadable.</li>
<li>Is IllegalArgumentException the best Exception for the case where the method cannot execute properly because arrays of differing lengths are provided?</li>
<li>Is there any easily readable way to convert Double[] to double[] without the loop I used in getCorrelation(Double[] a, Double[] b)?</li>
</ol>
<p>Thanks in advance.</p>
| [] | [
{
"body": "<p><strong>To focus on your initial questions</strong></p>\n\n<blockquote>\n <p>1) That crazy method is absurdly unreadable.</p>\n</blockquote>\n\n<p>I don't think it's too bad. You can improve it by using method references rather than lambdas and the <a href=\"https://docs.oracle.com/javase/8/docs/... | {
"AcceptedAnswerId": "197669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T13:57:40.333",
"Id": "197660",
"Score": "0",
"Tags": [
"java",
"generics",
"interface",
"lambda",
"exception"
],
"Title": "Using a wrapper on a primitive as a generic for an interface used for Java lambda"
} | 197660 |
<p>I was recently playing around with some code, and someone mentioned that my code uses too many classes. I didn't realize I've been doing ES6 incorrectly for so long. </p>
<p>I'm having a hard time finding a way to organize my code in a way that reads nicely. I say this coming from a C# background. </p>
<p>Thanks for your time, everyone.</p>
<pre><code>class Producer {
constructor(starterString) {
this.rules = [];
this.createRules();
this.producedString = starterString;
}
createRules() {
this.rules.add(new RuleAddE());
this.rules.add(new RuleAddNumberOne());
}
produce() {
for(var i = 0, len = this.rules.length; i < len; i++) {
this.producedString = this.rules[i].run(this.producedString);
}
return this.producedString;
}
}
class Rule {
constructor() {
this.applied = false;
}
run() {
}
}
class RuleAddE extends Rule {
constructor() {
super();
}
run(stringToChange) {
this.applied = true;
return stringToChange + "e";
}
}
class RuleAddNumberOne extends Rule {
constructor() {
super();
}
run(stringToChange) {
this.applied = true;
return stringToChange + "1";
}
}
var producer = new Producer("aa 1hdheb");
console.log(producer.produce());
</code></pre>
<p>How could I improve this code with more proper structure?</p>
| [] | [
{
"body": "<p><strong>1</strong>. You have classes but you do not effectively <em>need</em> them because they do not keep any state (even the <code>applied</code> field is actually unused). In C# you do not have much options (unless they're local) but in JavaScript you can use functions anywhere:</p>\n\n<pre><c... | {
"AcceptedAnswerId": "197670",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T14:07:13.427",
"Id": "197664",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Produces a string based on rules"
} | 197664 |
<p>Please help me improving this existing, working code. I am not asking you to change what it does, as it handles connections already perfectly as designed by my own specs. I just want the code to be reviewed to be sure.</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, ssl
from socketserver import ThreadingMixIn
from http.server import SimpleHTTPRequestHandler, HTTPServer
global sslcontext
sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
sslcontext.options |= ssl.OP_NO_TLSv1
sslcontext.options |= ssl.OP_NO_TLSv1_1
sslcontext.protocol = ssl.PROTOCOL_TLSv1_2
sslcontext.set_ciphers("ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305")
sslcontext.set_ecdh_curve("secp384r1")
sslcontext.load_cert_chain("/home/pi/keys/fullchain.pem", "/home/pi/keys/privkey.pem")
class HSTSHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
SimpleHTTPRequestHandler.end_headers(self)
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
def main():
try:
os.chdir("/media/external")#auto-change working directory
SimpleHTTPRequestHandler.sys_version = "0.1"#display custom Python system version
SimpleHTTPRequestHandler.server_version = "0.2"#display custom server software version
my_server = ThreadedHTTPServer(('', 443), HSTSHandler)
my_server.socket = sslcontext.wrap_socket(my_server.socket, server_side=True)
print('Starting server, use <Ctrl-C> to stop')
my_server.serve_forever()
except KeyboardInterrupt:
print(' received, shutting down server')
my_server.shutdown()
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T15:00:47.713",
"Id": "381067",
"Score": "1",
"body": "What does this *actually* do? How is /media/external significant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T11:03:19.143",
"Id": "381163... | [
{
"body": "<ol>\n<li><p>When importing names from a location (module, package, dynamic library, ...), don't mix multiple locations on a single line. That is, this:</p>\n\n<pre><code>import os, ssl\n</code></pre>\n\n<p>... should be:</p>\n\n<pre><code>import os\nimport ssl\n</code></pre>\n\n<p>This is purely a s... | {
"AcceptedAnswerId": "197961",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T14:46:09.820",
"Id": "197666",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"socket",
"https"
],
"Title": "Actively writing an HTTPS webserver in Python 3"
} | 197666 |
<p>I have a dict with a series of <code>bools</code> to specify if a particular aspect of my program will be run (e.g. <code>settings['A']</code> and <code>settings['B']</code>). </p>
<p>If they are run the results need to go into an aptly named directory. The directory names (not the entire path) are also stored in the dict (e.g. <code>settings['outputDirNameOut1']</code> and <code>settings['outputDirNameA']</code>) </p>
<p>In order to create the directories I'm using the following code.</p>
<pre><code>for each in filePathList:
path = os.path.dirname(each)
if not os.path.exists(os.path.join(path, settings['outputDirNameOut1'])):
os.makedirs(os.path.join(path, settings['outputDirNameOut1']))
if settings['A'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameA'])):
os.makedirs(os.path.join(path, settings['outputDirNameA']))
if settings['B'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameB'])):
os.makedirs(os.path.join(path, settings['outputDirNameThreshold']))
if settings['C'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameC'])):
os.makedirs(os.path.join(path, settings['outputDirNameC']))
os.makedirs(os.path.join(path, settings['outputDirNameOut2']))
if settings['D'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameOut2'])):
os.makedirs(os.path.join(path, settings['outputDirNameOut2']))
</code></pre>
<p>I'm wondering if there's a simpler, easier to read way to accomplish this.</p>
| [] | [
{
"body": "<p>Any time there's a repeating pattern that's very obvious like this you\nmight consider using another loop, or a function, or some other\nabstraction mechanism available. To me this also looks like example\ncode - please post the actual code you're using!</p>\n\n<p>So first a few comments:</p>\n\n... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T17:54:44.387",
"Id": "197673",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"file-system"
],
"Title": "Create directories for outputs based on setting"
} | 197673 |
<p>I am trying to make a stored procedure and pass some parameters for filtering. As soon as filtering is in horizon, code has to be as generic as possible with as few as possible <code>if</code>, <code>else</code>, etc.</p>
<p>How could I make this more readable? Can I use functions for this?</p>
<pre><code>ALTER PROCEDURE [dbo].[Stats] @network VARCHAR(9) = NULL,
@name VARCHAR(100) = NULL,
@version VARCHAR(15) = NULL,
@year INT = NULL,
@month INT = NULL,
@day INT = NULL,
@from DATE = null,
@to DATE = null
AS
BEGIN
SET nocount ON;
DECLARE @fromYear INT = NULL;
SET @fromYear = CASE WHEN @from IS NOT NULL THEN Datepart(year, @from) END
DECLARE @fromMonth INT = NULL;
SET @fromMonth = CASE WHEN @from IS NOT NULL THEN Datepart(month, @from) END
DECLARE @fromDay INT = NULL;
SET @fromDay = CASE WHEN @from IS NOT NULL THEN Datepart(day, @from) END
DECLARE @toYear INT = NULL;
SET @toYear = CASE WHEN @to IS NOT NULL THEN Datepart(year, @to) ELSE @fromYear END
DECLARE @toMonth INT = NULL;
SET @toMonth = CASE WHEN @to IS NOT NULL THEN Datepart(month, @to) ELSE @fromMonth END
DECLARE @toDay INT = NULL;
SET @toDay = CASE WHEN @to IS NOT NULL THEN Datepart(day, @to) ELSE @fromDay END
SELECT GS.[contractaddress],
GS.[network],
GS.[rounds],
GS.[sessions],
GS.[handle],
GS.[hold],
GS.[year],
GS.[month],
GS.[day],
G.[name],
G.[version],
DATEFROMPARTS(GS.[Year], GS.[Month], GS.[Day]) as [Date]
FROM [dbo].[gamestatsdaily] AS GS
INNER JOIN [dbo].[game] AS G
ON GS.contractaddress = G.[contractaddress]
WHERE ( @network IS NULL
OR ( GS.network = Upper(@network) ) )
AND ( @name IS NULL
OR ( GS.[contractaddress] IN (SELECT [contractaddress]
FROM [dbo].[game]
WHERE [name] = @name
AND [version] =
@version
AND [network] =
@network)
) )
AND ( @year IS NULL OR GS.[Year] = @year )
AND ( @month IS NULL OR GS.[Month] = @month )
AND ( @day IS NULL OR GS.[Day] = @day )
AND ( @from IS NULL OR ( GS.[Year] <= @fromYear AND @toYear >= GS.[Year] AND GS.[Month] <= @fromMonth AND @toMonth >= GS.[Month] AND GS.[Day] <= @fromMonth AND @toMonth >= GS.[Day]))
ORDER BY GS.[year] ASC,
GS.[month] ASC,
GS.[day] ASC
END
</code></pre>
| [] | [
{
"body": "<h3>Here is the revised SQL I came up with</h3>\n\n<p>Below this code is a list of tips for writing better SQL. </p>\n\n<hr>\n\n<pre><code>ALTER PROCEDURE [dbo].[Stats] \n @network VARCHAR(9) = NULL\n , @name VARCHAR(100) = NULL\n , @version VARCHAR(15) = NULL\n , @year INT = NULL\n ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T18:01:32.850",
"Id": "197674",
"Score": "0",
"Tags": [
"sql",
"t-sql",
"stored-procedure"
],
"Title": "Filtering query by date built from integers"
} | 197674 |
<p>I've implemented a card game called Macau. This is a follow-up from this <a href="https://softwareengineering.stackexchange.com/questions/373133/designing-a-card-game">topic</a>, where I tried to get the game's design right before actually implementing it. </p>
<p>Even if the game is presented on that topic, I will give a brief explanation as it follows. The game consists of a standard-deck that contains 52 cards. At the very beginning, every player receives 5 cards from the deck. (The first player that runs out of cards is the winner). Then, a card is put on the top of the pile. A player can put on the pile any card that is compatible with the top one. Two cards are compatible if they have the same suit or the same rank. There also exist several special cards:</p>
<ul>
<li>Rank: 2 or 3. This will require the next player to receive 2/3 cards from the deck if he doesn't have a 4 card with the same suit.</li>
<li>Rank: A (Ace). This will simply skip the next player's turn.</li>
</ul>
<p>Please note that, even if I mentioned 7 and the Joker as special cards in that topic, in the current state of the game they are not implemented. More precisely, the Jokers are disabled and the 7 is considered a normal card.</p>
<p>Here is the diagram of my classes.
<a href="https://i.stack.imgur.com/NMbJo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NMbJo.png" alt="diagram"></a></p>
<p>And here is the code:</p>
<p><strong>CardProperties.hpp</strong></p>
<pre><code>#pragma once
#include <array>
#include <string>
constexpr unsigned int numberOfSuits{ 6 };
constexpr unsigned int numberOfRanks{ 14 };
const std::array<std::string, numberOfSuits> suits{"Diamonds","Clubs"
, "Hearts","Spades" , "Red", "Black"};
const std::array<std::string, numberOfRanks> ranks{ "A", "2","3","4","5","6","7","8","9","10", "J","Q","K","Joker" };
enum class Suit
{
Diamonds,
Clubs,
Hearts,
Spades,
Red,
Black,
};
enum class Rank
{
Ace = 0,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Joker,
};
</code></pre>
<p><strong>Card.hpp</strong></p>
<pre><code>#pragma once
#include <ostream>
#include "CardProperties.hpp"
class Game;
class Card
{
public:
Card(const Suit& suit, const Rank& rank);
Card(const Rank& rank, const Suit& suit);
bool isCompatibleWith(const Card& other) const;
bool operator != (const Card& other) const;
friend std::ostream& operator<<(std::ostream& os, const Card& card);
//needed for std::set
bool operator == (const Card& other) const;
bool operator < (const Card& other) const;
friend class Game;
private:
bool invalidCardProperties(const Suit& suit, const Rank& rank) const;
Suit _suit;
Rank _rank;
};
</code></pre>
<p><strong>Exceptions.hpp</strong></p>
<pre><code>#pragma once
#include <exception>
#include <string>
class InvalidCardException : public std::exception
{
public:
InvalidCardException(const std::string& errorMessage);
const char* what() const override;
private:
std::string _errorMessage;
};
class EmptyDeckException : public std::exception
{
public:
EmptyDeckException(const std::string& errorMessage);
const char* what() const override;
private:
std::string _errorMessage;
};
class NotEnoughCardsException : public std::exception
{
public:
NotEnoughCardsException(const std::string& errorMessage);
const char* what() const override;
private:
std::string _errorMessage;
};
class InvalidNumberOfPlayersException : public std::exception
{
public:
InvalidNumberOfPlayersException(const std::string& errorMessage);
const char* what() const override;
private:
std::string _errorMessage;
};
</code></pre>
<p><strong>Card.cpp</strong></p>
<pre><code>#include "Card.hpp"
#include "Exceptions.hpp"
bool Card::invalidCardProperties(const Suit& suit, const Rank& rank) const
{
if (rank == Rank::Joker && (suit != Suit::Black && suit != Suit::Red))
return true;
if (rank != Rank::Joker && (suit == Suit::Black || suit == Suit::Red))
return true;
return false;
}
Card::Card(const Suit& suit, const Rank& rank)
: _suit(suit),
_rank(rank)
{
if (invalidCardProperties(suit, rank))
throw InvalidCardException("The Joker can only be red or black.\n");
}
Card::Card(const Rank& rank, const Suit& suit)
: Card(suit,rank)
{}
bool Card::isCompatibleWith(const Card& other) const
{
return _suit == other._suit || _rank == other._rank;
}
bool Card::operator< (const Card& other) const
{
return (static_cast<int>(_rank) < static_cast<int>(other._rank));
}
bool Card::operator == (const Card& other) const
{
return _rank == other._rank && _suit == other._suit;
}
bool Card::operator!= (const Card& other) const
{
return !((*this) == other);
}
std::ostream& operator << (std::ostream& os, const Card& card)
{
return os << '[' << suits[static_cast<int>(card._suit)] << " " << ranks[static_cast<int>(card._rank)] << ']';
}
</code></pre>
<p><strong>Deck.hpp</strong></p>
<pre><code>#pragma once
#include <vector>
#include "Card.hpp"
class Deck
{
public:
Deck();
const Card& dealCard();
std::vector<Card> dealCards(const unsigned int& numberOfCards);
void refill(const std::vector<Card>& cards);
void refill(const Card& card);
private:
void fill();
void shuffle();
std::vector<Card> _cards;
};
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include "Deck.hpp"
#include "Exceptions.hpp"
#include <random>
Deck::Deck()
{
fill();
shuffle();
}
const Card& Deck::dealCard()
{
if (_cards.empty())
throw EmptyDeckException("");
Card& topCard(_cards.back());
_cards.pop_back();
return topCard;
}
std::vector<Card> Deck::dealCards(const unsigned int& numberOfCards)
{
if (_cards.size() < numberOfCards)
throw NotEnoughCardsException("");
std::vector<Card> requestedCards;
auto it{ std::prev(_cards.end(), numberOfCards) };
std::move(it, _cards.end(), std::back_inserter(requestedCards));
_cards.erase(it, _cards.end());
return requestedCards;
}
void Deck::fill()
{
constexpr unsigned int numberOfSuitsWithoutJokerSpecificOnes{ 4 };
constexpr unsigned int numberOfRanksWithoutJokers{ 13 };
for (unsigned int index1 = 0; index1 < numberOfRanksWithoutJokers; ++index1)
{
for (unsigned int index2 = 0; index2 < numberOfSuitsWithoutJokerSpecificOnes; ++index2)
{
Card card(static_cast<Suit>(index2), static_cast<Rank>(index1));
_cards.push_back(card);
}
}
/*Card redJoker(Suit::Red, Rank::Joker);
_cards.push_back(redJoker);
Card blackJoker(Suit::Black, Rank::Joker);
_cards.push_back(blackJoker);*/
}
void Deck::shuffle()
{
std::mt19937 randomNumberGenerator{ std::random_device{}() };
std::shuffle(_cards.begin(), _cards.end(), randomNumberGenerator);
}
void Deck::refill(const std::vector<Card>& cards)
{
_cards.insert(_cards.end(), cards.begin(), cards.end());
shuffle();
}
void Deck::refill(const Card& card)
{
_cards.push_back(card);
shuffle();
}
</code></pre>
<p><strong>Pile.hpp</strong></p>
<pre><code>#pragma once
#include "Card.hpp"
#include <vector>
class Pile
{
public:
void addCard(const Card& card);
const Card& eraseTopCard();
const Card& getTopCard();
friend std::ostream& operator << (std::ostream& os, const Pile& pile);
std::vector<Card> releaseAllCardsButFirst();
private:
std::vector<Card> _alreadyPlayedCards;
};
</code></pre>
<p><strong>Pile.cpp</strong></p>
<pre><code>#include "Pile.hpp"
#include "Exceptions.hpp"
#include <algorithm>
constexpr unsigned int minimumValueOfPlayedCards{ 1 };
constexpr unsigned int lastElementOffset{ 1 };
void Pile::addCard(const Card& card)
{
_alreadyPlayedCards.push_back(card);
}
std::vector<Card> Pile::releaseAllCardsButFirst()
{
std::vector<Card> releasedCards;
auto it{ std::next(_alreadyPlayedCards.begin(), _alreadyPlayedCards.size() - lastElementOffset) };
std::move(_alreadyPlayedCards.begin(), it, std::back_inserter(releasedCards));
_alreadyPlayedCards.erase(_alreadyPlayedCards.begin(), it);
return releasedCards;
}
const Card& Pile::getTopCard()
{
return _alreadyPlayedCards.back();
}
const Card& Pile::eraseTopCard()
{
const Card& requestedCard{ _alreadyPlayedCards.back() };
_alreadyPlayedCards.pop_back();
return requestedCard;
}
std::ostream & operator<<(std::ostream & os, const Pile & pile)
{
return os << pile._alreadyPlayedCards.back();
}
</code></pre>
<p><strong>Hand.hpp</strong></p>
<pre><code>#pragma once
#include <vector>
#include "Card.hpp"
class Hand
{
public:
void addCard(const Card& card);
void addCards(const std::vector<Card>& cards);
void removeCard(const Card& card);
void removeCard(const unsigned int& cardNumber);
std::vector<Card>::iterator findCard(const Card& card);
const Card& getCard(const Card& card);
const Card& getCard(const unsigned int& cardNumber);
const unsigned int numberOfCards() const;
friend std::ostream& operator << (std::ostream& os, const Hand& hand);
private:
std::vector<Card> _cards;
};
</code></pre>
<p><strong>Hand.cpp</strong></p>
<pre><code>#include "Hand.hpp"
#include <algorithm>
constexpr unsigned int indexOffset{ 1 };
void Hand::addCard(const Card& card)
{
_cards.push_back(card);
}
void Hand::removeCard(const Card& card)
{
auto it{ findCard(card) };
_cards.erase(it);
}
void Hand::addCards(const std::vector<Card>& cards)
{
_cards.insert(_cards.end(), cards.begin(), cards.end());
}
void Hand::removeCard(const unsigned int& cardNumber)
{
_cards.erase(std::next(_cards.begin(), cardNumber - indexOffset));
}
std::vector<Card>::iterator Hand::findCard(const Card& card)
{
return std::find(_cards.begin(), _cards.end(), card);
}
const Card& Hand::getCard(const Card& card)
{
auto it{ findCard(card) };
return *it;
}
const Card& Hand::getCard(const unsigned int& cardNumber)
{
return _cards[cardNumber - indexOffset];
}
const unsigned int Hand::numberOfCards() const
{
return _cards.size();
}
std::ostream& operator << (std::ostream& os, const Hand& hand)
{
for (unsigned int index = 0; index < hand._cards.size(); ++index)
os << "Card number: " << index + indexOffset <<" "<< hand._cards[index] << '\n';
return os << '\n';
}
</code></pre>
<p><strong>Player.hpp</strong></p>
<pre><code>#pragma once
#include "Hand.hpp"
#include <vector>
class Player
{
public:
Player(const std::string& name = "undefined_name");
const Card& putCard(const Card& card);
Card putCard(const unsigned int& cardNumber);
const Card& getCard(const unsigned int& cardNumber);
void receive(const Card& card);
void receive(const std::vector<Card>& cards);
const unsigned int numberOfCards() const;
friend std::ostream& operator << (std::ostream& os, const Player& player);
const std::string name() const;
private:
Hand _handOfCards;
std::string _name;
};
</code></pre>
<p><strong>Player.cpp</strong></p>
<pre><code>#include "Player.hpp"
Player::Player(const std::string& name)
: _name(name)
{}
const Card& Player::putCard(const Card& card)
{
const Card& requestedCard{ _handOfCards.getCard(card) };
_handOfCards.removeCard(card);
return requestedCard;
}
Card Player::putCard(const unsigned int& cardNumber)
{
Card requestedCard{ _handOfCards.getCard(cardNumber) };
_handOfCards.removeCard(cardNumber);
return requestedCard;
}
const Card& Player::getCard(const unsigned int& cardNumber)
{
return _handOfCards.getCard(cardNumber);
}
void Player::receive(const Card& card)
{
_handOfCards.addCard(card);
}
void Player::receive(const std::vector<Card>& cards)
{
_handOfCards.addCards(cards);
}
std::ostream& operator << (std::ostream& os, const Player& player)
{
return os << player._name << "'s cards.\n" << player._handOfCards;
}
const unsigned int Player::numberOfCards() const
{
return _handOfCards.numberOfCards();
}
const std::string Player::name() const
{
return _name;
}
</code></pre>
<p><strong>Game.hpp</strong></p>
<pre><code>#pragma once
#include "Deck.hpp"
#include "Pile.hpp"
#include "Exceptions.hpp"
#include "Player.hpp"
#include <set>
class Game
{
public:
Game(const unsigned int& numberOfPlayers = 2);
void run();
private:
void dealInitialCardsToEachPlayer();
void initializePlayerNames();
void receiveCardsFromDeck(Player& player, const unsigned int& numberOfCards);
void putCardToPile(Player& player, unsigned int& cardNumber);
void normalCardPlayerTurn(Player& player);
void specialCardPlayerTurn(Player& player);
void printInformationAboutThePlayerAndTheTopCardFromPile(const Player& player) const;
void printInformationAboutThePlayerAndTheTopCardFromPile(const Player& player, const Rank& rank) const;
const Player& findWinner();
bool isSpecialCard(const Card& card) const;
void validatePlayerCardCompatibilityWithPileTopCard(Player& player, unsigned int& cardNumber);
std::vector<Player> _players;
unsigned int _numberOfPlayers;
Deck _deck;
Pile _pile;
bool _isRunning;
const std::set<Card> _specialCards{ { Suit::Clubs, Rank::Two },{ Suit::Diamonds, Rank::Two },{ Suit::Hearts, Rank::Two },{ Suit::Spades, Rank::Two }
,{ Suit::Clubs, Rank::Three },{ Suit::Diamonds, Rank::Three },{ Suit::Hearts, Rank::Three },{ Suit::Spades, Rank::Three },
/*,{ Suit::Clubs, Rank::Seven },{ Suit::Diamonds, Rank::Seven },{ Suit::Hearts, Rank::Seven },{ Suit::Spades, Rank::Seven },*/
{ Suit::Clubs, Rank::Ace },{ Suit::Diamonds, Rank::Ace },{ Suit::Hearts, Rank::Ace },{ Suit::Spades, Rank::Ace } };
};
</code></pre>
<p><strong>Game.cpp</strong></p>
<pre><code>#include "Game.hpp"
#include "GameConstants.hpp"
#include <set>
#include <iostream>
#include <algorithm>
void Game::initializePlayerNames()
{
std::string currentPlayerName;
for (unsigned int index = 0; index < _numberOfPlayers; ++index)
{
std::cout << "Name: ";
std::getline(std::cin, currentPlayerName);
Player player(currentPlayerName);
_players.push_back(player);
}
}
Game::Game(const unsigned int& numberOfPlayers)
: _numberOfPlayers(numberOfPlayers),
_isRunning(true)
{
if (numberOfPlayers > maximumNumberOfPlayers || numberOfPlayers < minimumNumberOfPlayers)
throw InvalidNumberOfPlayersException("The minimum number of players is 2, while the maximum number of players is 9.");
initializePlayerNames();
}
void Game::printInformationAboutThePlayerAndTheTopCardFromPile(const Player& player) const
{
std::cout << "\nTop card from pile: " << _pile << "\n";
std::cout << player << "\n";
std::cout << "What card would you like to put? If you don't have any compatible card or you wish to skip the turn, enter 0.\n";
}
void Game::printInformationAboutThePlayerAndTheTopCardFromPile(const Player& player, const Rank& rank) const
{
switch (rank)
{
case Rank::Two:
{
std::cout << "\nTop card from pile: " << _pile << "\nThis is 2 card and you will need to receive 2 cards from the deck.\n"
<< "If you have a 4 card that has the same suit, then you can stop it.\n";
std::cout << "What card would you like to put? If don't have a compatible 4 card, then enter 0.\n" << player << "\n";
break;
}
case Rank::Three:
{
std::cout << "\nTop card from pile: " << _pile << "\nThis is 3 card and you will need to receive 3 cards from the deck.\n"
<< "If you have a 4 card that has the same suit, then you can stop it.\n";
std::cout << "What card would you like to put? If don't have a compatible 4 card, then enter 0.\n" << player << "\n";
break;
}
case Rank::Seven:
{
std::cout << "\nTop card from pile: " << _pile << "\nThis is a 7 card and you will need to put down a card that has the specified suit. If you have a Joker, then"
<< " you can put it. Enter 0 if you don't have such a compatible card.\n" << player << "\n";
break;
}
case Rank::Ace:
{
std::cout << "\nTop card from pile: " << _pile << "\nThis is an A card."<< player.name() <<"'s turn was skipped.\n";
break;
}
}
}
void Game::receiveCardsFromDeck(Player& player, const unsigned int& numberOfCards)
{
try
{
player.receive(_deck.dealCards(numberOfCards));
}
catch (const NotEnoughCardsException& error)
{
_deck.refill(_pile.releaseAllCardsButFirst());
player.receive(_deck.dealCards(numberOfCards));
}
catch (const EmptyDeckException& error)
{
_deck.refill(_pile.releaseAllCardsButFirst());
player.receive(_deck.dealCards(numberOfCards));
}
}
void Game::putCardToPile(Player& player, unsigned int& cardNumber)
{
_pile.addCard(player.putCard(cardNumber));
}
bool Game::isSpecialCard(const Card& card) const
{
return (_specialCards.find(card) != _specialCards.end());
}
const Player& Game::findWinner()
{
auto it{ std::find_if(_players.begin(), _players.end(),
[&](const Player& player) { return !player.numberOfCards(); }) };
return *it;
}
void Game::dealInitialCardsToEachPlayer()
{
std::for_each(_players.begin(), _players.end(),
[this](Player& player) {player.receive(_deck.dealCards(initialNumberOfCardsPerPlayer)); });
}
void Game::validatePlayerCardCompatibilityWithPileTopCard(Player& player, unsigned int& cardNumber)
{
while (!player.getCard(cardNumber).isCompatibleWith(_pile.getTopCard()))
{
std::cout << "This card is incompatible.\nEnter another card or enter 0 to skip your turn.\n";
std::cin >> cardNumber;
if (!cardNumber)
break;
}
}
void Game::normalCardPlayerTurn(Player& player)
{
unsigned int cardNumber{ 0 };
printInformationAboutThePlayerAndTheTopCardFromPile(player);
std::cin >> cardNumber;
if (!cardNumber)
receiveCardsFromDeck(player, defaultNumberOfCardsToPick);
else
{
validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber);
if (!cardNumber)
receiveCardsFromDeck(player, defaultNumberOfCardsToPick);
else
putCardToPile(player, cardNumber);
}
if (!player.numberOfCards())
_isRunning = false;
}
void Game::specialCardPlayerTurn(Player& player)
{
unsigned int cardNumber{ 0 };
switch (_pile.getTopCard()._rank)
{
case Rank::Two:
{
printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Two);
std::cin >> cardNumber;
if (!cardNumber)
receiveCardsFromDeck(player, neededCardsToPickForTwo);
else if (player.getCard(cardNumber)._rank == Rank::Four && player.getCard(cardNumber).isCompatibleWith(_pile.getTopCard()))
putCardToPile(player, cardNumber);
else
{
validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber);
if (!cardNumber)
receiveCardsFromDeck(player, neededCardsToPickForTwo);
else
putCardToPile(player, cardNumber);
}
break;
}
case Rank::Three:
{
printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Three);
std::cin >> cardNumber;
if (!cardNumber)
receiveCardsFromDeck(player, neededCardsToPickForThree);
else if (player.getCard(cardNumber)._rank == Rank::Four && player.getCard(cardNumber).isCompatibleWith(_pile.getTopCard()))
putCardToPile(player, cardNumber);
else
{
validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber);
if (!cardNumber)
receiveCardsFromDeck(player, neededCardsToPickForThree);
else
putCardToPile(player, cardNumber);
}
break;
}
case Rank::Ace:
{
printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Ace);
break;
}
}
if (!player.numberOfCards())
_isRunning = false;
}
void Game::run()
{
dealInitialCardsToEachPlayer();
_pile.addCard(_deck.dealCard());
while (isSpecialCard(_pile.getTopCard()))
{
_deck.refill(_pile.eraseTopCard());
_pile.addCard(_deck.dealCard());
}
Card lastCard{ _pile.getTopCard() };
bool specialCardHadEffect{ false };
while (_isRunning)
{
for (auto& currentPlayer : _players)
{
if (!isSpecialCard(_pile.getTopCard()))
normalCardPlayerTurn(currentPlayer);
else
{
if (isSpecialCard(_pile.getTopCard()) && !specialCardHadEffect)
{
specialCardPlayerTurn(currentPlayer);
specialCardHadEffect = true;
}
else
normalCardPlayerTurn(currentPlayer);
}
if (_pile.getTopCard() != lastCard)
{
specialCardHadEffect = false;
lastCard = _pile.getTopCard();
}
if (!_isRunning)
break;
}
}
std::cout << "\tThe winner is " << findWinner().name() << ".\n";
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "Game.hpp"
#include <iostream>
int main()
{
unsigned int numberOfPlayers{ 0 };
std::cout << "Number of players.\n";
std::cin >> numberOfPlayers;
std::cin.ignore();
try
{
Game game(numberOfPlayers);
game.run();
}
catch (const InvalidNumberOfPlayersException& error)
{
std::cerr << error.what() << "\n";
std::cin >> numberOfPlayers;
Game game(numberOfPlayers);
game.run();
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T19:44:04.010",
"Id": "381097",
"Score": "0",
"body": "BTW, what are you using to draw your class diagrams?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T07:49:35.000",
"Id": "381134",
"Score... | [
{
"body": "<p>Writing identifiers with a leading underscore is a bad idea, and is generally dissuaded as a style. Note that it is legal for member names if (and only if) the next character is not a capital letter or another underscore. </p>\n\n<hr>\n\n<p>You used old-style syntax for some member initializers. ... | {
"AcceptedAnswerId": "197688",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T18:21:39.377",
"Id": "197675",
"Score": "8",
"Tags": [
"c++",
"object-oriented",
"game",
"playing-cards"
],
"Title": "Macau Card Game"
} | 197675 |
<p>Finished my first lone project and I'm wondering if the execution is passable. This is a basic lbs to tons converter. The customer drives on the scale loaded, then dumps the load and returns unloaded to the scale again. We need to convert the leftover lbs to tons. I am wondering if this is a concise way to perform this task.</p>
<p>loaded weight - unloaded weight = Total lbs in scrap</p>
<p>total lbs * 0.0005 = weight in tons</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function calc() {
let loadedAmount = document.getElementById("loaded").value;
let unloadedAmount = document.getElementById("unloaded").value;
let final = document.getElementById("result").value =
Math.round(`${(loadedAmount - unloadedAmount) * 0.0005}` * 100)/100;
let resultInPounds = document.getElementById("result").value =
Math.round(`${(loadedAmount - unloadedAmount)}`);
if (!loadedAmount) {
document.getElementById("loaded").value=alert("waiting for an initial value for loaded");
} else {
loadedAmount = parseInt(loadedAmount);
}
if (!unloadedAmount) {
document.getElementById("unloaded").value = alert("waiting for an initial value for unloaded");
} else {
unloadedAmount = parseInt(unloadedAmount);
}
if (loadedAmount < unloadedAmount) {
alert("loaded amount must be greater than unloaded amount");
}
console.log(`loadedAmount: ${loadedAmount}`);
console.log(`unloadedAmount: ${unloadedAmount}`);
document.getElementById("result").innerHTML=final + " Tons or " +
resultInPounds + " lbs";
console.log(result);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
<header>Negaunee Iron and Metal</header>
<script src="app.js"></script>
<div >input loaded pounds
<input type="number" id="loaded" placeholder="Loaded...">
</div>
<div > input unloaded pounds
<input type="number" id="unloaded" placeholder="Unloaded" >
</div>
<div><label type="number" id="result" ></label></div>
<button type="submit" id="button" onclick="calc()">Click To
Convert</button>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T21:21:25.377",
"Id": "381105",
"Score": "1",
"body": "\"total lbs * 0.0005 = weight in tons\" That's quite a rounding error you produce there, almost 10% just with one action. Are you sure you want to do this?"
},
{
"Content... | [
{
"body": "<p>The <a href=\"https://www.w3.org/TR/2017/REC-html52-20171214/sec-forms.html#the-label-element\" rel=\"nofollow noreferrer\"><code>label</code> element</a> can be used for the labels of the <code>input</code> fields.</p>\n\n<p>The <a href=\"https://www.w3.org/TR/2017/REC-html52-20171214/sec-forms.h... | {
"AcceptedAnswerId": "197737",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T19:47:15.293",
"Id": "197681",
"Score": "2",
"Tags": [
"javascript",
"html",
"unit-conversion"
],
"Title": "Pounds-to-tons converter"
} | 197681 |
<p>Test data passes the test, so why does Codility keep failing it? Am I perhaps misunderstanding the requirement?</p>
<pre><code>using System;
class Solution {
public int solution(int[] A) {
int max = 0;
for (var i = 0; i < A.Length; i++) {
for (var j = i + 1; j < A.Length; j++) {
for (var k = j + 1; k < A.Length; k++) {
var product = A[i] * A[j] * A[k];
var zeros = trailingZeros(product);
//Console.WriteLine($"{product} - {zeros}");
if (zeros > max) {
max = zeros;
}
}
}
}
return max;
}
private int trailingZeros(int N) {
if (N == 0) {
return 0;
}
int count = 0;
while (!(N <= 0 || N % 10 != 0)) {
count++;
N /= 10;
}
return count;
}
}
</code></pre>
<p>Test data:</p>
<pre><code>A = [7, 15, 6, 20, 5, 10]
A = [25, 10, 25, 10, 32]
A = [1, 1, 110]
A = [90, 76, 300, 10, 3, 5, 9, 1000000000]
A = [100090, 10030, 1000, 90, 87655, 676345]
A = [85, 65, 20, 50, 1, 0]
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
A = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 3, 90]
A = [101, 307, 890, 208, 406, 701, 222, 445, 5432]
A = [7, 15, 6, 20, 5, 10]
A = [90, 70, 80]
A = [900, 800, 700, 600, 500, 551, 662, 773, 884, 995]
</code></pre>
<p>Full description of the problem:</p>
<blockquote>
<p>Write a function:</p>
<p>class Solution { public int solution(int[] A); }</p>
<p>that, given an array of N positive integers, returns the maximum
number of trailing zeros of the number obtained by multiplying three
<strong>different</strong> elements from the array. Numbers are considered different if they are at different positions in the array.</p>
<p>For example, given A = [7, 15, 6, 20, 5, 10], the function should
return 3 (you can obtain three trailing zeros by taking the product of
numbers 15, 20 and 10 or 20, 5 and 10).</p>
<p>For another example, given A = [25, 10, 25, 10, 32], the function
should return 4 (you can obtain four trailing zeros by taking the
product of numbers 25, 25 and 32).</p>
<p>Assume that:</p>
<p>N is an integer within the range [3..100,000]; each element of array A
is an integer within the range [1..1,000,000,000]. Complexity:</p>
<p>expected worst-case time complexity is O(N*log(max(A)))
expected worst-case space complexity is O(N) (not counting the storage required
for input arguments).</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T15:05:12.227",
"Id": "381193",
"Score": "0",
"body": "_so why does Codility keep failing it_ - I don't think Code Review is the right place for this question. We're reviewing code and not explain requirements."
},
{
"Content... | [
{
"body": "<p>You must consider domain boundaries: <code>A</code> can contain integers in the range <code>[1..1,000,000,000]</code> so the largest possible product would be <code>1,000,000,000^3</code> which is way beyond <code>int.MaxValue</code> (and even <code>ulong.MaxValue</code>). One way to overcome this... | {
"AcceptedAnswerId": "197714",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T21:14:59.300",
"Id": "197686",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Codility: MaxZeroProduct challenge and solution"
} | 197686 |
<p>This is a <strong>follow-up post of my previous question: <a href="https://codereview.stackexchange.com/questions/197135/displaying-javascript-objects-structure-on-page-with-html#">Displaying JavaScript object's structure on page with HTML</a></strong> which looked at how to display all properties of a JavaScript object on a page similar to how the console behaves in browsers. In this first question, I had figured out how to render object that had cycles.</p>
<p>Receiving valuable advice from <a href="https://codereview.stackexchange.com/users/142650/gerrit0">Gerrit0</a>, I changed a couple of things:</p>
<ul>
<li><p>used <code>template</code> to prepare the HTML elements with JavaScript this allows to safely parse string as strings, not HTML (using <code>textContent</code> instead of <code>innerHTML</code>)</p></li>
<li><p>used the <code>details</code> element to make the foldable containers</p></li>
<li><p>added some CSS styling</p></li>
</ul>
<p>Here's how it looks like:</p>
<p><a href="https://i.stack.imgur.com/Bww1i.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bww1i.gif" alt="enter image description here"></a></p>
<hr>
<p><strong>HTML templates</strong></p>
<pre><code><template id="keyValue">
<div class="csle-property">
<span class="csle-key"></span>:
<span class="csle-value"></span>
</div>
</template>
<template id="folder">
<summary>
<div>
<div class="csle-key"></div>:
<div class="csle-preview"></div>
</div>
</summary>
</template>
</code></pre>
<p><strong>JavaScript code:</strong></p>
<pre><code>/**
* Shows all the object's properties with a depth of 1
* @params {Object} object, its first level properties are shown
* {HTMLElement} parent the element in which are displayed the properties
* @return {undefined}
*/
const showObject = (object, parent = document.body) => {
const template = {
keyValue: document.querySelector('template#keyValue'),
folder: document.querySelector('template#folder')
}
Object.entries(object).forEach(([key, value]) => {
const objectClass = (value && value.constructor) ? value.constructor : undefined;
const isContainer = (objectClass == Object) || (objectClass == Array);
if (isContainer) { // !better naming for (objects, arrays, maps, sets)?
const element = document.importNode(template.folder.content, true);
const children = {
key: element.querySelector('.csle-key'),
preview: element.querySelector('.csle-preview')
}
children.key.textContent = key;
children.preview.classList.add('csle-' + objectClass.name);
// show four properties maximum per preview
Object.entries(value).some(([k, v], i) => {
type = (v && v.constructor) ? v.constructor : undefined;
const keyValue = document.importNode(template.keyValue.content, true);
const keyValueElement = {
key: keyValue.querySelector('.csle-key'),
value: keyValue.querySelector('.csle-value')
}
// all types need different formatting
switch (type) {
case Object:
keyValueElement.value.textContent = `{...}`;
break;
case Array:
keyValueElement.value.textContent = `Array(${v.length})`;
break
default:
keyValueElement.value.textContent = `${v}`;
}
keyValueElement.key.textContent = k;
keyValueElement.value.setAttribute('class', 'csle-' + typeof v);
children.preview.appendChild(keyValue);
return i == 4;
});
const wrapper = document.createElement('details'); // !couldn't add event listener on <details>
wrapper.appendChild(element)
wrapper.addEventListener('toggle', () => {
showObject(value, wrapper)
}, { once: true });
parent.appendChild(wrapper);
} else {
const element = document.importNode(template.keyValue.content, true);
const children = {
key: element.querySelector('.csle-key'),
value: element.querySelector('.csle-value')
}
children.key.textContent = key;
children.value.textContent = value; // !undefined and null won't be parsed
children.value.setAttribute('class', 'csle-' + typeof value);
parent.appendChild(element);
}
});
};
</code></pre>
<hr>
<p><strong>Full code:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
* Shows all the object's properties with a depth of 1
* @params {Object} object, its first level properties are shown
* {HTMLElement} parent the element in which are displayed the properties
* @return {undefined}
*/
const showObject = (object, parent = document.body) => {
const template = {
keyValue: document.querySelector('template#keyValue'),
folder: document.querySelector('template#folder')
}
Object.entries(object).forEach(([key, value]) => {
const objectClass = (value && value.constructor) ? value.constructor : undefined;
const isContainer = (objectClass == Object) || (objectClass == Array);
if (isContainer) { // !better naming for (objects, arrays, maps, sets)?
const element = document.importNode(template.folder.content, true);
const children = {
key: element.querySelector('.csle-key'),
preview: element.querySelector('.csle-preview')
}
children.key.textContent = key;
children.preview.classList.add('csle-' + objectClass.name);
// show four properties maximum per preview
Object.entries(value).some(([k, v], i) => {
type = (v && v.constructor) ? v.constructor : undefined;
const keyValue = document.importNode(template.keyValue.content, true);
const keyValueElement = {
key: keyValue.querySelector('.csle-key'),
value: keyValue.querySelector('.csle-value')
}
switch (type) {
case Object:
keyValueElement.value.textContent = `{...}`;
break;
case Array:
keyValueElement.value.textContent = `Array(${v.length})`;
break
default:
keyValueElement.value.textContent = `${v}`;
}
keyValueElement.key.textContent = k;
keyValueElement.value.setAttribute('class', 'csle-' + typeof v);
children.preview.appendChild(keyValue);
return i == 4;
});
const wrapper = document.createElement('details'); // !couldn't add event listener on <details>
wrapper.appendChild(element)
wrapper.addEventListener('toggle', () => {
showObject(value, wrapper)
}, {
once: true
});
parent.appendChild(wrapper);
} else {
const element = document.importNode(template.keyValue.content, true);
const children = {
key: element.querySelector('.csle-key'),
value: element.querySelector('.csle-value')
}
children.key.textContent = key;
children.value.textContent = value; // !undefined and null won't be parsed
children.value.setAttribute('class', 'csle-' + typeof value);
parent.appendChild(element);
}
});
};
/**
* For demonstration purposes
*/
const obj = {
integer: 12,
string: 'Hello World',
boolean: true,
htmlString: '<b>Nope, not bold</b>',
object: {
innerArray: ['first', 'second'],
innerString: 'yes',
innerInteger: 12,
innerObject: {
first: 1,
second: 2
}
},
array: ['<b>bold text</b>', 'two'],
function: function() {}
};
obj['cycle'] = obj;
showObject(obj, document.querySelector('.container'))</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/**
* // all properties for the console get the prefix "csle-"
*/
/**
* Console frame
*/
.container {
background: #242424;
padding: 8px 15px;
}
/**
* Property value's styling
* csle-{boolean, undefined, string, Array, Object}
*/
.csle-boolean,
.csle-undefined {
color: #9283d1;
}
.csle-string {
color: #ca3b38; /*#e93f3b;*/
}
.csle-string:before,
.csle-string:after { content: '"'; }
.csle-Array:before { content: '['; }
.csle-Array:after { content: ']'; }
.csle-Object:before { content: '{'; }
.csle-Object:after { content: '}'; }
/**
* <summary> styling
*/
summary {
margin-left: 18px;
padding-left: 0px;
font-size: 20px;
display: flex;
align-items: center;
margin-bottom: 2px;
}
summary::-webkit-details-marker {
color: #8d8d8d;
text-shadow: 1em 0.1em #242424;
}
/**
* properties styling
*/
details > *:not(:first-child) {
margin-left: 22px;
}
summary > div {
display: inline-block;
width: 100%;
}
.csle-property, summary {
font-family: "Lucida Grande", sans-serif;
font-size: 17px;
padding: 1px;
overflow: hidden;
padding-left: 17px;
color: #acabab;
}
.csle-property {
line-height: 23px;
margin-bottom: 2px;
font-size: 18px;
}
.csle-property > span {
font-size: 17px;
}
.csle-preview > .csle-property {
display: inline;
margin: 0px;
padding: 0px;
margin: -2px;
color: #acabab;
font-size: 18px;
}
.csle-preview > .csle-property > span {
font-size: 17px;
}
.csle-preview > .csle-property:not(:first-child) > .csle-key:before {
content: ', ';
}
.csle-key, summary {
color: #a545ac;
font-size: 17px
}
.csle-key, .csle-preview {
display: inline;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container"></div>
<template id="keyValue">
<div class="csle-property">
<span class="csle-key"></span>:
<span class="csle-value"></span>
</div>
</template>
<template id="folder">
<summary>
<div>
<div class="csle-key"></div>:
<div class="csle-preview"></div>
</div>
</summary>
</template></code></pre>
</div>
</div>
</p>
<hr>
<p><strong>Issues:</strong></p>
<ul>
<li><p>my function <code>showObject</code> seems to big.</p></li>
<li><p>Unsure if I'm using ECMAScript 6 properly</p></li>
<li><p>some of the variable names bother me (<code>element</code>, <code>childrenPreview</code>, <code>isContainer</code>) as they aren't very clear.</p></li>
<li><p>I can't attach an event listener on the imported template <code><details></code> because it is a <code>DocumentFragment</code>. To fix that I had to (<code>line 62</code> of the snippet):</p>
<ol>
<li>only import <code><summary></code> as a <code>template</code></li>
<li>create the <code><details></code> element manually</li>
<li>append <code><summary></code> inside <code><details></code></li>
<li>attach the event listener to <code><details></code></li>
</ol>
<p><br /> Any workaround?</p></li>
</ul>
<p><strong>I'm looking forward to reading your comments.</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T11:29:28.620",
"Id": "381167",
"Score": "0",
"body": "Very nice! I see a few small things, but I'll hold off on reviewing as I believe it would be more valuable for you to receive a review from someone with a slightly different pers... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-02T22:07:22.543",
"Id": "197690",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Replicating Chrome console's JavaScript object explorer"
} | 197690 |
<p>This is my second attempt after I started to learn about STL. I am oblivious and need suggestions/advices on if there can be improvements made on this code.</p>
<pre><code>#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
string LongestWord(string sen) {
vector<string> coll; //initialize vector
istringstream iss(sen); //read the string "sen"
copy(istream_iterator<string>(iss), //copy from beginning of iss
istream_iterator<string>(), //to the end of iss
back_inserter(coll)); //and insert string to vector
//istream_iterator by default separates word by whitespace
string longestWord = coll.at(0);
int longestCount = longestWord.length();
for(auto element : coll)
{
if(element.length() > longestCount)
{
longestWord = element;
}
}
return longestWord;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T03:37:24.063",
"Id": "381117",
"Score": "1",
"body": "This doesn't appear to work. When I run it, it always returns the last word rather than the longest word. I'm passing it a sentence like \"This is a sentence with a long word\" a... | [
{
"body": "<p>As @user1118321 points out: just using your implementation, I believe you're missing a crucial line (inside your for loop and if-statement):</p>\n\n<pre><code>longestCount = element.length();\n</code></pre>\n\n<p>Which becomes:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n... | {
"AcceptedAnswerId": "197696",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T02:59:57.343",
"Id": "197694",
"Score": "0",
"Tags": [
"c++",
"algorithm",
"strings"
],
"Title": "Find the longest word in a sentence"
} | 197694 |
<p>I have this kind of instance method:</p>
<pre><code>def list_records(self,race_type,year=0):
yearnow= datetime.now().year
yearlist = [yearnow - i for i in range(4)]
if not year:
for y in yearlist:
if self.records:
yield self.records[utils.dateracetype_to_DBcolumn(y,str(race_type))]
else:
yield None
else:
if self.records:
yield self.records[utils.dateracetype_to_DBcolumn(year,str(race_type))]
else:
yield None
</code></pre>
<ol>
<li>I am calling it mainly through list comprehension,
but I could return it simply as a list, what is the most pythonic
way to do this? What would be the reasons to chose one method or the
other? </li>
<li>let's say I'll go with a generator, should I
turn the 2 last 'yield' into return values as there will be only one
value to be returned?</li>
<li>Is there a more optimized way to code this method, as I have the
feeling there's too much nested conditions/loop in there?</li>
<li>Is there a Python convention to name generators? something like
'gen...'</li>
</ol>
<p>Thanks</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T07:50:50.357",
"Id": "381135",
"Score": "2",
"body": "1) Depends on the context, which is missing in this question. Please take a look at the [help/on-topic]. 3) I've seen much worse. I'd probably create 2 sub-functions for `list_re... | [
{
"body": "<ol>\n<li><p>If you are going to need the whole list for some reason, then make a list. But if you only need one item at a time, use a generator. The reasons for preferring generators are (i) you only need the memory for one item at a time; (ii) if the items are coming from a file or network connecti... | {
"AcceptedAnswerId": "197701",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T06:30:48.523",
"Id": "197698",
"Score": "-1",
"Tags": [
"python",
"generator"
],
"Title": "When to create a generator or return simply a list in Python?"
} | 197698 |
<p>I have a table in Lua, which contains two 1-dimensional arrays in which each array contains approximately 800,000 elements. I want to serialize this Lua table to file efficiently. Hence, I planned to use Lua C bindings.</p>
<pre><code>#include "lua.h"
#include "lauxlib.h"
#include <stdio.h>
#include <assert.h>
static int do_it(lua_State *L) {
assert(L && lua_type(L, -1) == LUA_TTABLE);
int len, idx;
void *ptr;
FILE *f;
size_t r;
lua_pushstring(L, "p");
lua_gettable(L, -2);
len = lua_objlen(L, -1);
// instead of using lua_rawlen, i used lua_objlen. see below
// len = lua_rawlen(L, -1); // it throws the following error
// lua: error loading module 'savetable' from file './savetable.so':
// ./savetable.so: undefined symbol: lua_rawlen
int p_values[len];
for (idx = 1; idx <= len; idx++) {
lua_rawgeti(L, -1, idx);
p_values[idx - 1] = (int)lua_tonumber(L, -1);
lua_pop(L, 1);
}
f = fopen("p.bin", "wb");
assert(f);
r = fwrite(p_values, sizeof(int), len, f);
printf("[p] wrote %zu elements out of %d requested\n", r, len);
fclose(f);
lua_pop(L, 1);
lua_pushstring(L, "q");
lua_gettable(L, -2);
len = lua_objlen(L, -1);
double q_values[len];
for (idx = 1; idx <= len; idx++) {
lua_rawgeti(L, -1, idx);
q_values[idx - 1] = (double)lua_tonumber(L, -1);
lua_pop(L, 1);
}
f = fopen("q.bin", "wb");
assert(f);
r = fwrite(q_values, sizeof(double), len, f);
printf("[q] wrote %zu elements out of %d requested\n", r, len);
fclose(f);
lua_pop(L, 1);
return 1;
}
int luaopen_savetable(lua_State *L) {
static const luaL_reg Map[] = {{"do_it", do_it}, {NULL, NULL}};
luaL_register(L, "mytask", Map);
return 1;
}
</code></pre>
<p>Please note that for debugging purpose, I have defined two very small 1-dimensional arrays:</p>
<pre><code>my_table = {p = {11, 22, 33, 44}, q = {0.12, 0.23, 0.34, 0.45, 0.56}}
require "savetable"
mytask.do_it(my_table)
</code></pre>
<p>I used the following commands to compile and run it:</p>
<pre><code>> gcc -I/usr/include/lua5.1 -o savetable.so -shared savetable.c -fPIC
> lua wrapper.lua
</code></pre>
<p>The code works, however, I am looking for suggestions to make table serialization to file much faster than current.</p>
<p>Please note that I am using Lua 5.1 on a 64-bit Ubuntu PC.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T09:54:59.143",
"Id": "381156",
"Score": "0",
"body": "Tip: you may write your array implementation in C and push it into Lua as a light userdata with custom metatable (with insert/remove methods). If you make your array continuous y... | [
{
"body": "<pre><code>// undefined symbol: lua_rawlen\n</code></pre>\n\n<p>This happens because there is no such function in Lua 5.1 C API. As stated by documentation <code>lua_objlen</code> is preffered way to get table length.</p>\n\n<p>FYI <code>lua_rawlen</code> function first appeared in Lua 5.2.</p>\n\n<p... | {
"AcceptedAnswerId": "197754",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T07:44:21.117",
"Id": "197700",
"Score": "3",
"Tags": [
"performance",
"c",
"serialization",
"lua",
"lua-table"
],
"Title": "Serializing a table for filing"
} | 197700 |
<p>In order to learn haskell, I wrote a solver for the <a href="https://code.google.com/codejam/contest/6224486/dashboard#s=p1" rel="nofollow noreferrer">Infinite House of Pancakes</a> problem. </p>
<pre><code>-- Solve the 'Infinite House of Pancakes' problem.
-- https://code.google.com/codejam/contest/6224486/dashboard#s=p1
import Text.Printf
import Control.Monad
-- Generic solver code
readInt :: IO Int
readInt = readLn
readIntList :: IO [Int]
readIntList = getLine >>= return . map read . words
main :: IO [()]
main = do
n <- readInt
forM [1..n] (\i ->
parse >>= putStr . printf "Case #%d: %d\n" i . solve)
-- Problem-specific code
parse :: IO [Int]
parse = getLine >> readIntList
cost :: Int -> Int -> Int
cost l n = if r == 0 then q - 1 else q where (q, r) = n `quotRem` l
test :: Int -> [Int] -> Int
test l = (+l) . sum . map (cost l)
solve :: [Int] -> Int
solve s = minimum . map (\l -> test l s) $ [1 .. maximum s]
</code></pre>
<p>I used <a href="https://github.com/vxgmichel/codejam-solver/blob/master/example/pancake.py" rel="nofollow noreferrer">this python solution</a> as a reference, which is based on the <a href="https://code.google.com/codejam/contest/6224486/dashboard#s=a&a=1" rel="nofollow noreferrer">following problem analysis</a>. I tested my program using those <a href="https://github.com/vxgmichel/codejam-solver/blob/master/example/B-large-practice.in" rel="nofollow noreferrer">input</a> and <a href="https://github.com/vxgmichel/codejam-solver/blob/master/example/B-large-practice.out.expected" rel="nofollow noreferrer">output</a> files, and it seems to work fine:</p>
<pre><code>$ stack ghc pancake.hs -- -O2
$ \time -f "%e s" ./pancake < B-large-practice.in | diff - B-large-practice.out
0.28 s
</code></pre>
<p>I'm looking for comments about the following points:</p>
<ul>
<li>coding style</li>
<li>performance (currently runs in 0.28 seconds using <code>-O2</code>, against 5.5 seconds for python 3)</li>
<li>bind operators vs do syntax (I used both here, but it was mostly for educational purposes)</li>
<li>tools and ecosystem (code analysis, better compilation flags, etc.)</li>
</ul>
<hr>
<p><strong>EDIT -</strong> Thanks to @Gurkenglas answer, I've been able to improve this program quite a lot. Here's a <a href="https://gist.github.com/vxgmichel/5f3cfc69e06dd149d6bc188a58f949cd" rel="nofollow noreferrer">link to the corresponding gist</a>.</p>
| [] | [
{
"body": "<p>I'll refactor so every line tells the reader something about the program.</p>\n\n<pre><code>{-# LANGUAGE ScopedTypeVariables #-}\nimport Text.Printf\nimport Control.Monad\nimport Data.List.Split (splitPlaces)\nimport Safe (headNote)\n\nmain :: IO ()\nmain = interact ... | {
"AcceptedAnswerId": "197864",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T08:47:52.913",
"Id": "197703",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Infinite House of Pancakes in Haskell"
} | 197703 |
<p>I tried implementing a queue using <code>std::vector</code>, using some properties of vector class. Is there scope for further improvement in my code, to make it more efficient?</p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
vector<int> q;
void push(int d){
q.insert(q.end(),d);
}
void pop(){
q.erase(q.begin());
}
int front(){
return *q.begin();
}
int main(){
push(1);
push(2);
push(3);
push(4);
pop();
cout<<front()<<endl;
for(int i=0;i<q.size();i++) cout<<q[i]<<" ";
}
</code></pre>
| [] | [
{
"body": "<p>There are a number of things that could be improved here, and none of them have to do with the efficiency of the program. The problems with this code are more fundamental.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of eve... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T08:55:42.213",
"Id": "197706",
"Score": "3",
"Tags": [
"c++",
"beginner",
"reinventing-the-wheel",
"queue"
],
"Title": "implementing a queue using std::vector"
} | 197706 |
<p>I write this session helper class to use it inside my projects for managing the <code>$_SESSION</code> variables setup after an user login or logout. It's very simple and after some tests it seems to work smoothly and fine. </p>
<p>The class doesn't have a constructor, this because the needed parameters that are the username and the user id are passed directly to the <code>setSession</code> method. </p>
<p>The <code>sessionCode</code> method is instead only a code who is used to check if the user is logged in or not, this to limit the access to certain pages if needed. </p>
<pre><code><?php
namespace library;
class SessionHelper{
private $username;
private $id;
private $ip;
public function setSession(string $email,int $id){
session_regenerate_id();
$_SESSION['session_code'] = $this->sessionCode();
$_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $email;
return true;
}
public function sessionStatus(){
if(isset($_SESSION['session_code'])){
if(hash_equals($_SESSION['session_code'], $this->sessionCode())){
return true;
} else {
return false;
}
}
}
public function unsetSession(){
session_unset();
session_destroy();
return true;
}
private function sessionCode(){
return hash('sha256', session_id());
}
}
?>
</code></pre>
<p>USAGE EXAMPLE AFTER A LOGIN SCRIPT:</p>
<pre><code><?php
require_once 'SessionHelper.php';
use library\SessionHelper as SessionHelper;
$session = new SessionHelper;
$session->setSession('user1', '4');
?>
</code></pre>
<p>USAGE ON RESTRICTED ACCESS PAGES</p>
<pre><code><?php
session_start();
require_once 'library/Autoloader.php';
use library\SessionHelper as SessionHelper;
$session = new SessionHelper;
if($session->sessionStatus() != true){
header('Location: index');
die();
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T12:28:11.193",
"Id": "381172",
"Score": "1",
"body": "What's the point of `session_regenerate_id()` here? I also can't see how you're using the session code in a safe manner. You must be accessing `$_SESSION` outside this helper cla... | [
{
"body": "<p>This is not a SessionHelper but a UserSessionHelper in the first place. A session is a container that could contain anything, not only user credentials. A shopping cart items for example. Therefore you have to either extend its functionality or at least rename a class. </p>\n\n<p>In 2018 you are o... | {
"AcceptedAnswerId": "197713",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T10:46:23.707",
"Id": "197711",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"session"
],
"Title": "User session helper class"
} | 197711 |
<p>I've built a VBA Excel macro that works on a spreadsheet of duplicated files, and displays only groups in which at least one duplication is owned by the current user.</p>
<p>The spreadsheet lists file metadata, one file per row, grouped with other files whose content is identical, i.e. "duplicated". Each such duplication group is preceded by a title row in bold.</p>
<p>The macro uses text boldness to determine duplication groups, and checks within each group whether any file's owner (represented in column 7) is the currently logged user.
All groups with no file owned by the user get hidden.
(auto-filtering would not solve this problem because I want the user to see the other files in the duplication group, i.e. see files from other owners with the same content as theirs) </p>
<p>It works exactly as intended, but too slowly. It takes one or two minutes to run through a spreadsheet about 80 thousand lines long. Anyone can see a way to speed it up?</p>
<p>I had the idea of maybe hiding every row first (which I assume can be done much faster) and then de-hide what should be shown. But I couldn't find a command to mass-hide.</p>
<p>Also, since we're here, what best practices am I missing? I'm a complete novice to VBA, though I'm an experienced programmer in other languages.</p>
<p>Grateful for any help.</p>
<pre><code>'Operates on .xslx report of network file duplication, as output by TreeSize tool.
'Hides all Duplication Groups not involving the currently logged user as a file Owner
'(regular filtering does not work because it hides the other duplicates which have a different owner)
'TODO: speed it up. It currently takes ~1min to run. Probably hide-all then unhide-selected will be faster.
Private Sub My_duplicates_Click()
Dim hidIt As Boolean
Dim foundInGroup As Boolean
Application.ScreenUpdating = False
Application.EnableEvents = False
login = Environ("Username")
ownerCol = 7
rowNum = 3 'skip header
Do While Not IsEmpty(Cells(rowNum, 1))
If Cells(rowNum, ownerCol).Font.Bold = True Then 'bold text indicates the beginning of a duplication group
foundInGroup = False
groupMemberRow = rowNum + 1
Do While Not IsEmpty(Cells(groupMemberRow, 1)) And Not Cells(groupMemberRow, ownerCol).Font.Bold = True
If Cells(groupMemberRow, ownerCol).Value2 = login Then
foundInGroup = True
End If
groupMemberRow = groupMemberRow + 1
Loop
If foundInGroup = False Then
hidIt = True
Else
hidIt = False
End If
Cells(rowNum, ownerCol).EntireRow.Hidden = hidIt
groupMemberRow = rowNum + 1
Do While Not IsEmpty(Cells(groupMemberRow, 1)) And Not Cells(groupMemberRow, ownerCol).Font.Bold = True
Cells(groupMemberRow, ownerCol).EntireRow.Hidden = hidIt
groupMemberRow = groupMemberRow + 1
Loop
rowNum = groupMemberRow - 1 'counting on next increment to place it back on the next group header
End If
rowNum = rowNum + 1
Loop
End Sub
</code></pre>
| [] | [
{
"body": "<p>First off, regarding </p>\n\n<blockquote>\n <p>But I couldn't find a command to mass-hide.</p>\n</blockquote>\n\n<p>For me, the snippet <code>WhateverSheet.Range(\"A3:A80000\").Rows.Hidden = True</code> seems to do the trick.</p>\n\n<hr>\n\n<p>I see a lot of not fully qualified <code>Range()</cod... | {
"AcceptedAnswerId": "197728",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T11:17:24.603",
"Id": "197712",
"Score": "5",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Hide Excel Rows faster"
} | 197712 |
<p>I used an opportunity to learn about Dependency Injection and DDD, therefore, althought any feedback is welcome, I am interested in feedback about those software design principles.</p>
<p>I have a small project where I have to display some information queried from several similar databases (= DB that have the same purpose, but are assigned to different plants).</p>
<p>The back-end is coding using C#/Web API 2.</p>
<p>I have organized it in 3 projects (plus one test project per actual project), organized as follows (Only showing the file I believe are relevant to the review).</p>
<p>I am submitting for review the very first step of the program, reading the different servers that exist from configuration, and serve them to the front-end.</p>
<pre><code>Backend.sln
|-> Backend.API (WebApi2 project)
|-> Controllers/ServersController.cs
|-> App_Start/UnityConfig.cs
|-> Settings/Servers (a string, JSON-formatted)
|-> Backend.Domain (Class Library)
|-> Server/AServer.cs
|-> Server/SettingsServerRepository.cs
|-> Backend.Infra (Class Library)
|-> Server/IServer.cs
|-> Server/IServerRepository.cs
</code></pre>
<p><strong>Backend.API</strong></p>
<p><em>Controllers/ServersController.cs</em></p>
<pre><code>namespace Backend.API.Controllers
{
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*", SupportsCredentials = true)]
public class ServersController : ApiController
{
Infra.Server.IServerRepository serverRepository;
public ServersController(Infra.Server.IServerRepository serverRepo)
{
serverRepository = serverRepo;
}
public HttpResponseMessage Get()
{
IEnumerable<Infra.Server.IServer> servers = serverRepository.Servers;
return Request.CreateResponse(HttpStatusCode.OK, servers);
}
}
}
</code></pre>
<p><em>App_Start/UnityConfig.cs</em></p>
<pre><code>namespace Backend.API
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var servers = Properties.Settings.Default.Servers;
var container = new UnityContainer();
container.RegisterType<Infra.Server.IServerRepository,
Domain.Server.SettingsServerRepository>(new InjectionConstructor(servers));
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
}
</code></pre>
<p><em>Settings/Servers</em></p>
<pre><code>[
{
"$type": "Backend.Domain.Server.AServer, Backend.Domain",
"HostName": "foo",
},
{
"$type": "Backend.Domain.Server.AServer, Backend.Domain",
"HostName": "bar",
}
]
</code></pre>
<p><strong>Backend.Domain</strong></p>
<p><em>Server/AServer.cs</em></p>
<pre><code>namespace Backend.Domain.Server
{
public class AServer: Infra.Server.IServer
{
public string HostName { get; }
public AServer (string HostName)
{
this.HostName = HostName;
}
}
}
</code></pre>
<p><em>Server/SettingsServerRepository.cs</em></p>
<pre><code>namespace Backend.Domain.Server
{
public class SettingsServerRepository : Infra.Server.IServerRepository
{
public IEnumerable<Infra.Server.IServer> Servers {get;}
public SettingsServerRepository(string jsonSettings)
{
Servers = JsonConvert.DeserializeObject<IEnumerable<Infra.Server.IServer>>(
jsonSettings,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
});
}
}
}
</code></pre>
<p><strong>Backend.Infra</strong></p>
<p><em>Server/IServer.cs</em></p>
<pre><code>namespace Backend.Infra.Server
{
public interface IServer
{
string HostName { get; }
}
}
</code></pre>
<p><em>Server/IServerRepository.cs</em></p>
<pre><code>namespace Backend.Infra.Server
{
public interface IServerRepository
{
IEnumerable<IServer> Servers { get; }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T14:57:56.667",
"Id": "381191",
"Score": "0",
"body": "Please post your real code, do not edit it for the sake of the question. Some variables in your question don't match. Either this is not working or you have edited it."
},
{
... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T11:41:56.213",
"Id": "197716",
"Score": "0",
"Tags": [
"c#",
"dependency-injection",
"asp.net-web-api",
"ddd"
],
"Title": "Inject settings as a dependency, and serve them using a Web API"
} | 197716 |
<p>The small bit of code below blits and image to the screen within a class. I call this 4 times to display the image 4 times, each image has a different y coordinate and doesn't need different x but when they are blitted they make the code MUCH slower. I know it is the blitting as well due to the fact that if i just draw rects instead, the program moves smoothly.</p>
<pre><code>tableTex = pygame.transform.scale(pygame.image.load('./Sources/Table.png'), (270, 240))
def display(self):
if not self.occupied:
screen.blit(tableTex, (self.x, self.y))
else:
pygame.draw.rect(screen, (127, 0, 0), self.rect, 0)
</code></pre>
<p>A link to the full code can be found <a href="https://github.com/tomayling7/restaurant-game/" rel="nofollow noreferrer">here</a> if needed.
I just want to know if there is any reason this is so slow and if there are any other methods I could use that are faster?</p>
<p>Thanks</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T15:49:53.690",
"Id": "381213",
"Score": "0",
"body": "You should add the definition of `tableTex` to the code, since it is actually quite relevant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T15:5... | [
{
"body": "<p>As noted in the <a href=\"https://www.pygame.org/docs/tut/newbieguide.html\" rel=\"nofollow noreferrer\">beginners guide</a>, you should convert your image right after loading it. So instead of</p>\n\n<pre><code>tableTex = pygame.transform.scale(pygame.image.load('./Sources/Table.png'), (270, 240)... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T12:08:36.690",
"Id": "197718",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"pygame"
],
"Title": "The start of a game in pygame, blitting images to the screen"
} | 197718 |
<p>I have the following code I'm using to show/hide multiple shape groups in Excel 2016 using VBA and macros:</p>
<pre><code> Sub Pic_1_SA_click()
ActiveSheet.Shapes("Group 23").Visible = True
ActiveSheet.Shapes("Group 71").Visible = False
ActiveSheet.Shapes("Group 19").Visible = False
ActiveSheet.Shapes("Group 20").Visible = False
End Sub
Sub Pic_1_SB_click()
ActiveSheet.Shapes("Group 23").Visible = False
ActiveSheet.Shapes("Group 71").Visible = True
ActiveSheet.Shapes("Group 19").Visible = False
ActiveSheet.Shapes("Group 20").Visible = False
End Sub
Sub Pic_2_SA_click()
ActiveSheet.Shapes("Group 23").Visible = False
ActiveSheet.Shapes("Group 71").Visible = False
ActiveSheet.Shapes("Group 19").Visible = True
ActiveSheet.Shapes("Group 20").Visible = False
End Sub
Sub Pic_2_SB_click()
ActiveSheet.Shapes("Group 23").Visible = False
ActiveSheet.Shapes("Group 71").Visible = False
ActiveSheet.Shapes("Group 19").Visible = False
ActiveSheet.Shapes("Group 20").Visible = True
End Sub
</code></pre>
<p>Now the above is somewhat tedious if I plan to add more buttons. Is there any way to do this more efficiently? </p>
| [] | [
{
"body": "<p>The simple answer is to use pass an array of names to the <code>Shapes.Range</code>, hide all 4 Groups, and then make the one Group visible. </p>\n\n<blockquote>\n<pre><code>ActiveSheet.Shapes.Range(Array(\"Group 19\", \"Group 20\", \"Group 23\", \"Group 71\")).Visible = msoTrue\nActiveSheet.Shap... | {
"AcceptedAnswerId": "197727",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T13:05:33.823",
"Id": "197721",
"Score": "4",
"Tags": [
"vba",
"excel"
],
"Title": "Excel 2016 VBA - Show/Hide multiple shape groups"
} | 197721 |
<p>This is a functional component that I have developed in React Native for creating a circular progress view.</p>
<p>The code does not use any external libraries, just pure CSS. Article that I wrote while creating this code is <a href="https://medium.com/@0saurabhgour/react-native-percentage-based-progress-circle-no-external-library-e25b43e83888" rel="nofollow noreferrer">here</a>. <a href="https://github.com/saurabhgour/react-native-progress-circle-without-library/tree/5bd395eae76f42cf9fa184816555401895de9ebc" rel="nofollow noreferrer">Github repo</a>. <a href="https://www.npmjs.com/package/react-native-circular-progress-no-ext-library" rel="nofollow noreferrer">npm package</a>.</p>
<pre><code>import React from 'react';
import {Text, View, StyleSheet} from 'react-native';
/**
* Function that calculates rotation of the semicircle for firstProgressLayer
* ( when percent is less than equal to 50 ) or for the secondProgressLayer
* when percent is greater than 50.
**/
rotateByStyle = (percent, base_degrees, clockwise) => {
let rotateBy = base_degrees;
if(clockwise){
rotateBy = base_degrees + (percent * 3.6);
}else{
//anti clockwise progress
rotateBy = base_degrees - (percent * 3.6);
}
return {
transform:[{rotateZ: `${rotateBy}deg`}]
};
}
renderThirdLayer = (percent, commonStyles, ringColorStyle, ringBgColorStyle, clockwise,
bgRingWidth, progressRingWidth, innerRingStyle, startDegrees) => {
let rotation = 45 + startDegrees;
let offsetLayerRotation = -135 + startDegrees;
if(!clockwise){
rotation += 180;
offsetLayerRotation += 180;
}
if(percent > 50){
/**
* Third layer circles default rotation is kept 45 degrees for clockwise rotation, so by default it occupies the right half semicircle.
* Since first 50 percent is already taken care by second layer circle, hence we subtract it
* before passing to the rotateByStyle function
**/
return <View style={[styles.secondProgressLayer,rotateByStyle((percent - 50), rotation, clockwise),
commonStyles, ringColorStyle, {borderWidth: progressRingWidth} ]}></View>
}else{
return <View style={[styles.offsetLayer, innerRingStyle, ringBgColorStyle,
{transform:[{rotateZ: `${offsetLayerRotation}deg`}], borderWidth: bgRingWidth}]}></View>
}
}
const CircularProgress = ({percent, radius, bgRingWidth, progressRingWidth, ringColor, ringBgColor,
textFontSize, textFontWeight, clockwise, bgColor, startDegrees}) => {
const commonStyles = {
width: radius * 2,
height: radius * 2,
borderRadius: radius
};
/**
* Calculate radius for base layer and offset layer.
* If progressRingWidth == bgRingWidth, innerRadius is equal to radius
**/
const widthDiff = progressRingWidth - bgRingWidth;
const innerRadius = (radius - progressRingWidth) + bgRingWidth + widthDiff/2;
const innerRingStyle = {
width: innerRadius * 2,
height: innerRadius * 2,
borderRadius: innerRadius
};
const ringColorStyle = {
borderRightColor: ringColor,
borderTopColor: ringColor,
};
const ringBgColorStyle = {
borderRightColor: ringBgColor,
borderTopColor: ringBgColor,
};
const thickOffsetRingStyle = {
borderRightColor: bgColor,
borderTopColor: bgColor,
};
let rotation = -135 + startDegrees;
/**
* If we want our ring progress to be displayed in anti-clockwise direction
**/
if(!clockwise){
rotation += 180;
}
let firstProgressLayerStyle;
/* when ther ring's border widths are different and percent is less than 50, then we need an offsetLayer
* before the original offser layer to avoid ring color of the thick portion to be visible in the background.
*/
let displayThickOffsetLayer = false;
if(percent > 50){
firstProgressLayerStyle = rotateByStyle(50, rotation, clockwise);
}else {
firstProgressLayerStyle = rotateByStyle(percent, rotation, clockwise);
if(progressRingWidth > bgRingWidth){
displayThickOffsetLayer = true;
}
}
let offsetLayerRotation = -135 + startDegrees;
if(!clockwise){
offsetLayerRotation += 180;
}
return(
<View style={[styles.container, {width: radius * 2, height: radius * 2}]}>
<View style={[styles.baselayer, innerRingStyle, {borderColor: ringBgColor, borderWidth: bgRingWidth}]}>
</View>
<View style={[styles.firstProgressLayer, firstProgressLayerStyle,
commonStyles, ringColorStyle, {borderWidth: progressRingWidth}]}>
</View>
{
displayThickOffsetLayer && <View style={[styles.offsetLayer, commonStyles, thickOffsetRingStyle,
{transform:[{rotateZ: `${offsetLayerRotation}deg`}], borderWidth: progressRingWidth}]}></View>
}
{
renderThirdLayer(percent, commonStyles, ringColorStyle, ringBgColorStyle, clockwise,
bgRingWidth, progressRingWidth, innerRingStyle, startDegrees)
}
<Text style={[styles.display, {fontSize: textFontSize,fontWeight: textFontWeight}]}>{percent}%</Text>
</View>
);
}
// default values for props
CircularProgress.defaultProps = {
percent: 0,
radius: 100,
bgRingWidth: 10,
progressRingWidth: 20,
ringColor: '#3498db',
ringBgColor: 'grey',
textFontSize: 40,
textFontWeight: 'bold',
clockwise: true,
bgColor: 'white',
startDegrees: 0
}
/**
* offsetLayer has transform:[{rotateZ: '-135deg'}] since
* the offsetLayer rotation is fixed by us.
**/
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center'
},
baselayer: {
position: 'absolute'
},
firstProgressLayer: {
position: 'absolute',
borderLeftColor: 'transparent',
borderBottomColor: 'transparent'
},
secondProgressLayer:{
position: 'absolute',
borderLeftColor: 'transparent',
borderBottomColor: 'transparent'
},
offsetLayer: {
position: 'absolute',
borderLeftColor: 'transparent',
borderBottomColor: 'transparent'
},
display: {
position: 'absolute'
}
});
export default CircularProgress;
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T13:36:58.480",
"Id": "197723",
"Score": "3",
"Tags": [
"css",
"animation",
"react.js",
"jsx",
"react-native"
],
"Title": "React native circular progress view"
} | 197723 |
<p>Merged cells are a PITA in Excel. They prevent doing a lot of actions and make copying columns impossible. So I wrote this little code to change all the merged cells in a given sheet into 'Center across selection'.<br>
I did NOT test against vertically merged cells, but it should not trigger an error (just unmerge them).</p>
<pre><code>Sub fixMergedCells(sh As Worksheet)
'replace merged cells by Center Acroos Selection
'high perf version using a hack: https://stackoverflow.com/a/9452164/78522
Dim c As Range, used As Range
Dim m As Range, i As Long
Dim constFla: constFla = Array(xlConstants, xlFormulas)
Set used = sh.UsedRange
For i = 0 To 1 '1 run for constants, 1 for formulas
Err.Clear
On Error Resume Next
Set m = Intersect(used.Cells.SpecialCells(constFla(i)), used.Cells.SpecialCells(xlBlanks))
On Error GoTo 0
If Not m Is Nothing Then
For Each c In m.Cells
If c.MergeCells Then
With c.MergeArea
'Debug.Print .Address
.UnMerge
.HorizontalAlignment = xlCenterAcrossSelection
End With
End If
Next c
End If
Next i
End Sub
Sub test_fixMergedCells()
fixMergedCells ActiveSheet
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T16:46:11.747",
"Id": "381232",
"Score": "0",
"body": "Nice work. I am sure that there are a lot of people search for code to get rid of the PITA Merged Cells. Thank you for sharing."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<h2>Vertically Merged Cells</h2>\n<blockquote>\n<p>I did NOT test against vertically merged cells, but it should not trigger an error (just unmerge them).</p>\n</blockquote>\n<p>You code will unmerge the cells and set each cells <code>.HorizontalAlignment = xlCenterAcrossSelection</code>.</p>\n<h2>Ta... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T14:02:40.723",
"Id": "197726",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Getting rid of Merged cells"
} | 197726 |
<p>I have written low quality php code, I'm not a good coder ;) Help me, please, to optimise it ;)</p>
<p>This simple code check bitstamp.net exchange rate, compare it with previous rate and print the result.</p>
<pre><code><?php
function getPrice($url) {
$decode = @file_get_contents($url);
return json_decode($decode, true);
}
$btc = getPrice('https://api.binance.com/api/v1/ticker/24hr?symbol=BTCUSDT');
$btcusdlast = round($btc["lastPrice"], 1);
$rbtc = ($btc["priceChange"]>0) ? 'up' : ' down';
$ltc = getPrice('https://api.binance.com/api/v1/ticker/24hr?symbol=LTCUSDT');
$ltcusdlast = round($ltc["lastPrice"], 1);
$rltc = ($ltc["priceChange"]>0) ? 'up' : ' down';
?>
<h2>BTC
$ <?=$btcusdlast, ' ', $rbtc;?></h2>
<h2>LTC
$ <?=$ltcusdlast, ' ', $rltc;?></h2>
</code></pre>
<p>But it's low quality and work <strong>very slowly</strong>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T14:45:36.673",
"Id": "381189",
"Score": "1",
"body": "_\"and work very slowly.\"_ Since you’re calling an external site, it can't work faster than your internet connection speed…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"... | [
{
"body": "<p>Id make your code more functional (if your not going to use OOP) the fact that this code is slow is probably your internet connection (as mentioned in the comments) </p>\n\n<p>First as the api is returning common keys I would just make the rounding & ternary operator as one function you can pa... | {
"AcceptedAnswerId": "197740",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T14:39:36.397",
"Id": "197729",
"Score": "2",
"Tags": [
"php"
],
"Title": "Check bitstamp.net exchange rate, compare it with previous rate"
} | 197729 |
<p>I come from a C background and am trying to learn Rust. I wrote my first Rust program, to check the battery level on my laptop and warn me if it's low/critical. </p>
<p>It works fine, but I wrote it in a way I'm familiar with and was wondering if I'm missing out on some features of the Rust language that could make this more portable, more optimal, or safer.</p>
<pre><code>extern crate notify_rust;
use notify_rust::Notification;
use notify_rust::NotificationUrgency;
use std::fs::File;
use std::io::prelude::*;
static CHARGE_NOW: &str = "/sys/class/power_supply/BAT0/charge_now";
static CHARGE_FULL: &str = "/sys/class/power_supply/BAT0/charge_full";
static STATUS: &str = "/sys/class/power_supply/BAT0/status";
static CHARGING_STR: &str = "Charging";
const CHARGE_WARN: f32 = 15.0;
const CHARGE_CRIT: f32 = 5.0;
const NOTIFICATION_TIMEOUT: i32 = 4000;
fn main() {
/* If we're charging, just exit */
if get_str_from_file(STATUS).trim() == CHARGING_STR {
std::process::exit(0);
}
let charge_level: f32 = (get_float_from_file(CHARGE_NOW) /
get_float_from_file(CHARGE_FULL)) * 100.0;
if charge_level < CHARGE_WARN {
Notification::new()
.summary("Battery level low!")
.body(&format!("Battery level: {0:.1$}%", charge_level, 2))
.icon("dialog-information")
.urgency(
if charge_level < CHARGE_CRIT {
NotificationUrgency::Critical
} else {
NotificationUrgency::Normal
}
)
.timeout(NOTIFICATION_TIMEOUT)
.show().unwrap();
}
}
fn get_str_from_file(file_path: &str) -> String {
let mut file = File::open(file_path)
.expect("file not found");
let mut ret = String::new();
file.read_to_string(&mut ret)
.expect("failed to read file");
ret
}
fn get_float_from_file(file_path: &str) -> f32 {
get_str_from_file(file_path).trim().parse::<f32>().unwrap()
}
</code></pre>
<p>Used crate: <a href="https://docs.rs/notify-rust/3.4.2/x86_64-unknown-linux-gnu/notify_rust/" rel="nofollow noreferrer">notify_rust</a>.</p>
| [] | [
{
"body": "<p>Unwrapping options is probably fine for this simple little app that only you’re using, but it dumps out a panic if the result is <code>None</code>. I like your use of <code>expect</code> better. That can give a nicer error message to the user. Either way, it’d be good to learn the more idiomatic w... | {
"AcceptedAnswerId": "197771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-03T16:41:08.617",
"Id": "197742",
"Score": "10",
"Tags": [
"beginner",
"linux",
"rust",
"status-monitoring"
],
"Title": "Laptop battery level monitor for Linux"
} | 197742 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.