body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>Much to my chagrin, neither STL nor Boost has a cartesian product. Namely, given as arguments one or more iterables, create an iterator producing <code>std::tuple</code>s of every combination of elements (with one drawn from each iterator in the order of the arguments).</p>
<p>My goal here was to make <code>cartesian_product</code> to behave exactly like python's <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="noreferrer"><code>itertools.product</code></a> (with the exception of the optional <code>repeat</code> kwarg). Ideally, it would be a zero cost abstraction (when compared to using nested for loops).</p>
<p>As an example:</p>
<pre><code>#include <vector>
std::vector<int> as = {1, 2};
std::vector<char> bs = {'a', 'b'};
std::vector<float> cs = {1.5, 2.5};
for (auto [a, b, c] : cartesian_product(as, bs, cs)) {
std::cout << "(a = " << a << ", b = " << b << ", c = " << c << ")" << std::endl;
}
</code></pre>
<p>Should produce:</p>
<pre><code>(a = 1, b = a, c = 1.5)
(a = 1, b = a, c = 2.5)
(a = 1, b = b, c = 1.5)
(a = 1, b = b, c = 2.5)
(a = 2, b = a, c = 1.5)
(a = 2, b = a, c = 2.5)
(a = 2, b = b, c = 1.5)
(a = 2, b = b, c = 2.5)
</code></pre>
<p>To make it general and support an arbitrary number of args, I had to use parameter packs and do some template pattern matching.</p>
<p>Here's what I arrived at:</p>
<pre><code>#pragma once
#include <tuple>
template<typename... Ts>
class product_iterator;
template<typename... Ts>
class product;
template<typename T>
class product<T> {
public:
explicit product(const T &x) : m_x(x) {}
product_iterator<T> begin() const;
product_iterator<T> end() const;
protected:
const T &m_x;
};
template<typename T, typename... Ts>
class product<T, Ts...> {
public:
product(const T &x, const Ts&... xs) : m_x(x), m_xs(product<Ts...>(xs...)) {}
product_iterator<T, Ts...> begin() const;
product_iterator<T, Ts...> end() const;
protected:
const T &m_x;
product<Ts...> m_xs;
};
template<typename T>
class product_iterator<T> {
friend class product<T>;
public:
std::tuple<typename T::value_type> operator*() const {
return std::make_tuple(*m_it);
}
const product_iterator<T> &operator++() {
m_it++;
return *this;
}
bool operator==(const product_iterator &other) const {
return m_it == other.m_it;
}
bool operator!=(const product_iterator &other) const {
return !(*this == other);
}
protected:
typedef typename T::const_iterator t_iterator;
product_iterator(t_iterator it, t_iterator end) : m_it(it), m_end(end) {}
t_iterator m_it;
t_iterator m_end;
};
template<typename T, typename... Ts>
class product_iterator<T, Ts...> {
friend class product<T, Ts...>;
public:
decltype(auto) operator*() const {
return std::tuple_cat(std::make_tuple(*m_x), *m_xs);
}
const product_iterator<T, Ts...> &operator++() {
if (++m_xs == m_xs_end && ++m_x != m_x_end) {
m_xs = m_xs_begin;
}
return *this;
}
bool operator==(const product_iterator &other) const {
return m_x == other.m_x && m_xs == other.m_xs;
}
bool operator!=(const product_iterator &other) const {
return !(*this == other);
}
protected:
typedef typename T::const_iterator t_iterator;
typedef product_iterator<Ts...> ts_iterator;
product_iterator(t_iterator x, t_iterator x_end, ts_iterator xs,
ts_iterator xs_begin, ts_iterator xs_end)
: m_x(x), m_x_end(x_end), m_xs(xs), m_xs_begin(xs_begin), m_xs_end(xs_end) {}
t_iterator m_x;
t_iterator m_x_end;
ts_iterator m_xs;
ts_iterator m_xs_begin;
ts_iterator m_xs_end;
};
template<typename T>
product_iterator<T> product<T>::begin() const {
return product_iterator<T>(m_x.begin(), m_x.end());
}
template<typename T>
product_iterator<T> product<T>::end() const {
return product_iterator<T>(m_x.end(), m_x.end());
}
template<typename T, typename... Ts>
product_iterator<T, Ts...> product<T, Ts...>::begin() const {
return product_iterator<T, Ts...>(m_x.begin(), m_x.end(), m_xs.begin(),
m_xs.begin(), m_xs.end());
}
template<typename T, typename... Ts>
product_iterator<T, Ts...> product<T, Ts...>::end() const {
return product_iterator<T, Ts...>(m_x.end(), m_x.end(), m_xs.end(), m_xs.begin(),
m_xs.end());
}
template<typename... Ts>
product<Ts...> cartesian_product(Ts&... xs) {
return product<Ts...>(xs...);
}
</code></pre>
<p>I've tested for correctness and also for speed. Both clang 6 and gcc 8 struggle to optimize this to be equivalent to nested for loops. For empirical results, see <a href="https://gist.github.com/baileyparker/cc4211a06235ae719591f6c04ed7eb7c" rel="noreferrer">this gist with a reproducible benchmark</a>. On my machine, I consistently get around the following:</p>
<pre><code>$ g++-8 --version
g++-8 (Homebrew GCC 8.1.0) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ clang++-6 --version
clang version 6.0.1 (tags/RELEASE_601/final)
Target: x86_64-apple-darwin17.7.0
Thread model: posix
InstalledDir: /usr/local/opt/llvm/bin
$ make clean && CXX=g++-8 make benchmark
# ... snip ...
time ./run_cartesian
32.53 real 32.42 user 0.03 sys
time ./run_loop
32.39 real 32.29 user 0.03 sys
$ make clean && CXX=clang++-6 make benchmark
# ... snip ...
time ./run_cartesian
30.31 real 30.24 user 0.02 sys
time ./run_loop
27.30 real 27.24 user 0.02 sys
</code></pre>
<p>Not sure what's going on with gcc's timings here (hopefully this benchmark isn't borked!), but there's a noticeable difference with clang. Furthermore, looking at <a href="https://godbolt.org/g/iEZqU3" rel="noreferrer">godbolt</a> for both gcc-8 and clang-6 shows both appear to be unable to optimize away some of the abstraction from <code>product_iterator</code>.</p>
<p>Furthermore, if you replace <code>dummy</code> with an accumulator and do an actual dot product like:</p>
<pre><code>uint32_t dot(const std::vector<uint32_t> &as, const std::vector<uint32_t> &bs) {
uint32_t acc = 0;
for (auto [a, b] : cartesian_product(as, bs)) {
acc += a * b;
}
return acc;
}
</code></pre>
<p>And:</p>
<pre><code>uint32_t dot(const std::vector<uint32_t> &as, const std::vector<uint32_t> &bs) {
uint32_t acc = 0;
for (auto a : as) {
for (auto b : bs) {
acc += a * b;
}
}
return acc;
}
</code></pre>
<p>The different becomes incredibly noticeable. The loop version runtime drops to about 1 second and the cartesian product remains at 30s on my machine. <a href="https://godbolt.org/g/h1HwHU" rel="noreferrer">Looking at godbolt for this</a> you can see very clearly that both gcc and clang are able to vectorize the nested loop version but not the cartesian version.</p>
<p>I'm curious about the following things:</p>
<ul>
<li>How idomatic is this code?</li>
<li>How pluggable is this code? (ie. is it compatible with all of the contexts that it should be valid in?)
<ul>
<li>Have I implemented everything that I should for this iterator?</li>
</ul></li>
<li>Is there a better way to express this such that gcc and clang can better optimize loops using <code>cartesian_product</code>? Ideally, <code>cartesian_product</code> should be a zero cost abstraction (compared to nested for loops).</li>
</ul>
| [] | [
{
"body": "<h1>Naming</h1>\n\n<p>Using <code>m_x</code> for the container (in <code>product</code>) as well as the iterator (in <code>product_iterator</code>) gets confusing. Similar for <code>m_xs</code>.</p>\n\n<h1>Performance / Optimization</h1>\n\n<p>The compiler relies on the \"nestedness\" of loops to opt... | {
"AcceptedAnswerId": "198478",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T04:28:19.717",
"Id": "198475",
"Score": "10",
"Tags": [
"c++",
"combinatorics",
"template-meta-programming",
"c++17"
],
"Title": "Generalized Cartesian Product"
} | 198475 |
<p>I am attempting to write up a program in Python that will find the shortest path between two nodes in 3D space. The actual domain is the EVE-Online Universe, which is composed of systems connected by stargates.</p>
<p>The input to my program is a list of systems, represented as Python dicts (JSON). I am trying to use the physical 3D distance as well as an incrementing step-cost as my two heuristics.</p>
<pre><code>from math import sqrt
from Queue import PriorityQueue
class Universe(object):
def __init__(self, systems):
self._id_to_system = {system["system_id"]: system for system in systems}
self._name_to_system = {system["name"]: system for system in systems}
@property
def num_systems(self):
return len(self._id_to_system)
def __getitem__(self, key):
if key in self._id_to_system:
return self._id_to_system[key]
elif key in self._name_to_system:
return self._name_to_system[key]
else:
raise KeyError("No system with a name or id equal to {}".format(key))
def distance(a, b):
""" Returns straight-line distance in AUs between two systems """
a_pos = a["position"]
b_pos = b["position"]
x_dist = b_pos["x"] - a_pos["x"]
y_dist = b_pos["y"] - b_pos["y"]
z_dist = b_pos["z"] - b_pos["z"]
distance = sqrt((x_dist)*(x_dist) + (y_dist)*(y_dist) + (z_dist)*(z_dist))
# Convert from meters to AUs before returning - helps keep this number reasonable
return distance / 1.496e+11
class SystemNode(object):
""" Used to represent a system inside the open and closed sets """
def __init__(self, system, parent, step_cost):
self.system = system
self.parent = parent
self.step_cost = step_cost
def find_stargate_route(universe, start_system, end_system, step_cost=10):
# Create open and closed sets
frontier_nodes = PriorityQueue(universe.num_systems)
closed_system_ids = {}
# Add starting system to frontier
start_node = SystemNode(start_system, None, 0)
frontier_nodes.put((0, start_node))
while not frontier_nodes.empty():
# Grab the node with the lowest cost
current_node = frontier_nodes.get(False)[1]
# Check if we have found our goal
if current_node.system == end_system:
print("Found Route to {}".format(end_system["name"]))
break
# Calculate next node step cost
next_step_cost = current_node.step_cost + step_cost
# Add each output system if we haven't seen it yet
for system_id in (
stargate["destination"]["system_id"] for stargate in current_node.system["stargates"]
):
system = universe[system_id]
system_node = SystemNode(system, current_node, next_step_cost)
# Check if system is in our closed list
if system_id in closed_system_ids:
continue
# Add to our frontier with priority=step_cost + distance
total_cost = distance(system, end_system) + next_step_cost
frontier_nodes.put((total_cost, system_node))
# Add the current node to the closed set
closed_system_ids[current_node.system["system_id"]] = current_node
if current_node.system != end_system:
return None
else:
# Return a list of systems from start to end
route = []
while current_node != None:
route.insert(0, current_node.system)
current_node = current_node.parent
return route
</code></pre>
<p>And then a little program to run it...</p>
<p>A jsonl.gz file with all of the systems is available in <a href="https://gitlab.com/snippets/1733170" rel="nofollow noreferrer">this gitlab snippet</a> (see the attached file - "combined_systems.jsonl.gz")</p>
<pre><code>import gzip
import json
with gzip.open("combined_systems.jsonl.gz", 'rb') as gzfp:
systems = [json.loads(line) for line in gzfp]
start_name = "Amarr"
end_name = "Jita"
universe = Universe(systems)
route = find_stargate_route(
universe, universe[start_name], universe[end_name]
)
print(len(route))
</code></pre>
<p>Any suggestions? This was meant more as a coding exercise to help me grasp the A-star algorithm, so any pointers are much appreciated :)</p>
<p><strong>EDIT:</strong> Removed the dependency on <code>PrioritySet</code> - it works the same with <code>Queue.PriorityQueue</code>. Also added my Universe class (basically just getters for the different systems). Also added a link to the <code>jsonl.gz</code> file containing all of the systems, see the gitlab link.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T08:09:52.530",
"Id": "382802",
"Score": "0",
"body": "Welcome to Code Review! For what Python version did you write this and does it work correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T08:... | [
{
"body": "<p>Let's start with the <code>distance</code> function.</p>\n\n<p><code>distance = sqrt((x_dist)*(x_dist) + (y_dist)*(y_dist) + (z_dist)*(z_dist))</code> is how you would probably write it in C++, in Python there exists a more readable way using the <code>**</code> operator:</p>\n\n<p><code>distance ... | {
"AcceptedAnswerId": "199496",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T06:06:50.070",
"Id": "198476",
"Score": "4",
"Tags": [
"python",
"python-2.x",
"graph",
"search",
"a-star"
],
"Title": "A-Star Search with 3D Universe"
} | 198476 |
<p>Here I uploaded a very basic Barabasi-Albert network generator and then a percolator which conducts percolation over the network following some rules. I have used openmp to parallelize the loops.</p>
<p>Here 3 arrays, <code>maxclus</code>,<code>delmx</code> and <code>entropycalc</code> are shared between the parallel threads and <code>netmap1</code>,<code>netmap2</code>,<code>ptr</code> and <code>random</code> are made private to the threads. What it basically does is that, suppose you have a vector, and two arrays, then, </p>
<pre><code>int* arrayresult = new int [N];
int* array;
#pragma omp parallel shared(arrayresult) private(array)
{
vector<int> someVec;
array = new int [N]
for(int k=0;k<somenum;k++) array[k] = 0;
#pragma omp for
for(int i=0;i<somenum;i++)
{
// do something with someVec;
// do something with array;
for(int j=0;j<somenum1;j++)
#pragma omp atomic
arrayresult[j] += someResult;
}
delete [] array;
}
</code></pre>
<p>Now this snippet describes the main gist of the code I am posting here. This shows a performance degradation proportional to the number of cores or threads being used. I am providing both the linear code and the parallel code.</p>
<p>How can I make the parallel one more efficient?</p>
<p><a href="https://pastebin.com/i9smRx5M" rel="nofollow noreferrer">Parallel Code with OpenMP</a></p>
<pre><code>//compile with icpc filename.cpp -o executable -O3 -std=c++14 -qopenmp
#include<iostream>
#include<vector>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<ctime>
#include<cmath>
#include<random>
#include<fstream>
#include<algorithm>
#include<omp.h>
//#include "openacc_curand.h"
using namespace std;
int EMPTY = 0;
int connectionNumber = 0; // it indexes the connection between different nodes of the network
// this function does the union find work for the percolation
//#pragma acc routine seq
int findroot(int ptr[],int i)
{
if(ptr[i]<0) return i;
return ptr[i]=findroot(ptr,ptr[i]);
}
int main()
{
int seed,vertices,m,run,filenum,M;
//I am just going to set the initial value for your need
/*
cout<<"enter seed size: ";
cin>>seed;
cout<<endl;
cout<<"enter vertice number: ";
cin>>vertices;
cout<<endl;
cout<<"order number: ";
cin>>m;
cout<<endl;
cout<<"order of Explosive Percolation: ";
cin>>M;
cout<<endl;
cout<<"enter ensemble number: ";
cin>>run;
cout<<endl;
cout<<"enter filenumber: ";
cin>>filenum;
cout<<endl;
*/
seed = 6;
vertices = 500000;
m = 5;
M = 12;
run = 50;
filenum = 1;
//this sets up the connection and initializes the array;
int con = 0;
for(int i=1;i<seed;i++)
{
con = con + i;
}
con = con + (vertices-seed)*m;
//int* netmap1 = new int[con+1]; //node 1 that is connected to a certain connectionNumber
//int* netmap2 = new int[con+1]; //node 2 that is connected to a certain connectionNumber
//for(int i=1;i<=con;i++)
//{
// netmap1[i] = 0;
// netmap2[i] = 0;
//}
connectionNumber = con;
srand(time(NULL));
int A,B,C;
A = vertices;
B = run;
C = filenum;
//saved filename
string filename1;
filename1 = "maxclus_";
string filename2;
filename2 = "delmx_";
string filename3;
filename3 = "entropy_";
filename1 = filename1+to_string(A)+"node_"+to_string(m)+"m_"+to_string(M)+"M_"+to_string(B)+"ens"+to_string(C)+".dat";
filename2 = filename2+to_string(vertices)+"node_"+to_string(m)+"m_"+to_string(M)+"M_"+to_string(run)+"ens"+to_string(filenum)+".dat";
filename3 = filename3+to_string(vertices)+"node_"+to_string(m)+"m_"+to_string(M)+"M_"+to_string(run)+"ens"+to_string(filenum)+".dat";
ofstream fout1,fout2,fout3;//,fout3;
//int* random = NULL;
//random = new int[connectionNumber+1];
double* maxclus = NULL;
maxclus = new double[vertices+1];
double* delmx = NULL;
delmx = new double[connectionNumber+1];
double* entropycalc = NULL;
entropycalc = new double[connectionNumber+1];
for(int i=0;i<=vertices;i++)
{
maxclus[i]=0;
delmx[i]=0;
entropycalc[i]=0;
}
//for(int i=0;i<=connectionNumber;i++)
//{
// random[i] = i;
//}
//this is the pointer that needs to be made private for all the parallel loops
//int* ptr = new int[vertices+1];
//for(int i=0;i<vertices+1;i++) ptr[i]=0;
//the main program starts here
int* ptr; int* netmap1; int* netmap2; int* random;
int runcounter = 0;
#pragma omp parallel shared(con,runcounter,maxclus,delmx,entropycalc) private(ptr,netmap1,netmap2,random) firstprivate(connectionNumber)
{
ptr = new int[vertices+1];
netmap1 = new int[connectionNumber+1];
netmap2 = new int[connectionNumber+1];
random = new int[connectionNumber+1];
for(int l=0;l<=con;l++)
{
netmap1[l] = 0;
netmap2[l] = 0;
random[l] = l;
}
for(int l=0;l<=vertices;l++)
ptr[l] = EMPTY;
#pragma omp for schedule(static)
for(int i=1;i<=run;i++)
{
//#pragma omp critical
//cout<<"run : "<<i<<endl;
//vector<size_t> network;
vector<int> network;
/*for(int l=0;l<=con;l++)
{
netmap1[l] = 0;
netmap2[l] = 0;
random[l] = l;
}
for(int l=0;l<=vertices;l++)
ptr[l] = EMPTY;*/
connectionNumber = 0;
//cout<<network.capacity()<<endl;
//seeds are connected to the network
for(int i=1;i<=seed;i++)
{
for(int j=1;j<=seed;j++)
{
if(j>i)
{
connectionNumber=connectionNumber + 1;
netmap1[connectionNumber]=i; //connections are addressed
netmap2[connectionNumber]=j;
network.push_back(i); // the vector is updated for making connection
network.push_back(j);
}
}
}
int concheck = 0;
int ab[m]; //this array checks if a node is chosen twice
int countm = 0;
for(int i = seed+1;i<=vertices; i++)
{
countm = 0;
for(int k=0;k<m;k++) ab[k] = 0;
for(int j = 1; ;j++)
{
concheck = 0;
int N1=network.size() ;
int M1=0;
int u = M1 + rand()/(RAND_MAX/(N1-M1+1) + 1);
for(int n=0;n<m;n++)
{
if(ab[n] == network[u]) concheck = 1;
}
//if condition is fulfilled the connection are given to the nodes
//the data is saved in the arrays of the connection
if(concheck == 0 && network[u]!=i)
{
ab[countm] = network[u];
countm=countm+1;
connectionNumber=connectionNumber+1;
netmap1[connectionNumber] = i;
netmap2[connectionNumber] = network[u];
network.push_back(i);
network.push_back(network[u]);
}
if(countm==m) break;
}
}
//the random list of connection are shuffled
random_shuffle(&random[1],&random[con]);
for(int rx=1;rx<=1;rx++)
{
int index=0,big=0,bigtemp=0,jump=0,en1=0,en2=0;
int nodeA=0,nodeB=0;
int indx1=0;
int node[2*M+1];// = {0};
int clus[2*M+1];// = {0};
double entropy = log(vertices);
for(int i=0;i<=vertices;i++) ptr[i] = EMPTY;
for(int i=1;i<=vertices;i++)
{
if(i!=connectionNumber)
{
int algaRandomIndex = 0;
for(int nodeindex = 0; nodeindex<2*M; nodeindex+=2)
{
node[nodeindex] = netmap1[random[i + algaRandomIndex]];
node[nodeindex + 1] = netmap2[random[i + algaRandomIndex]];
algaRandomIndex++;
}
for(int nodeindex = 0; nodeindex<2*M; nodeindex++)
{
if(ptr[node[nodeindex]]==EMPTY) clus[nodeindex] = 1;
else
{
int x = findroot(ptr,node[nodeindex]);
clus[nodeindex] = -ptr[x];
}
}
int clusmul[M];
int clusindex1 = 0;
for(int clusindex = 0; clusindex<M; clusindex++)
{
clusmul[clusindex] = clus[clusindex1]*clus[clusindex1+1];
clusindex1 += 2;
}
bool clusmulCheck = true;
for(int ase = 0; ase < M; ase++)
{
bool clusmulCheck1 = true;
if(clusmul[ase] == 1) clusmulCheck1 = true;
else clusmulCheck1 = false;
clusmulCheck = clusmulCheck && clusmulCheck1;
}
if(clusmulCheck)
{
nodeA = node[0];
nodeB = node[1];
for(int someK = 1; someK < M; someK++)
{
int N1=connectionNumber;
int M1=i+M;
int u = M1 + rand()/(RAND_MAX/(N1-M1+1) + 1);
int temp = random[u];
random[u] = random[i+someK];
random[i+someK] = temp;
}
}
else
{
int low = clusmul[0];
indx1 = 1;
for(int as=0;as<11;as++)
{
if(clusmul[as]<low)
{
low = clusmul[as];
indx1 = as+1;
}
}
nodeA = node[2*indx1 - 2];
nodeB = node[2*indx1 - 1];
int temp = random[i+(indx1-1)];
random[i+(indx1-1)] = random[i];
random[i] = temp;
for(int ase = 1; ase < M; ase++)
{
int N1=connectionNumber;
int M1=i+M;
int u = M1 + rand()/(RAND_MAX/(N1-M1+1) + 1);
int temp = random[u];
random[u] = random[i+ ase];
random[i+ ase] = temp;
}
}
}
if(ptr[nodeA]==EMPTY && ptr[nodeB]==EMPTY)
{
en1=1;
en2=1;
ptr[nodeA] = -2;
ptr[nodeB] = nodeA;
index = nodeA;
entropy = (double)(entropy-(-2.0/vertices*log(1.0/vertices))+(-2.0/vertices*log(2.0/vertices)));
if(entropy<0) entropy = 0;
}
else if(ptr[nodeA]==EMPTY && ptr[nodeB]!=EMPTY)
{
en1=1;
int e = findroot(ptr,nodeB);
en2 = -(ptr[e]);
ptr[nodeA] = e;
ptr[e] += -1;
index = e;
entropy = entropy-(-(double)1.0/vertices*log(1.0/(double)vertices))-(-(double)en2/vertices*log((double)en2/vertices))+(-( double)(-ptr[index])/vertices*log((-ptr[index])/(double)vertices));
if(entropy<0) entropy = 0;
}
else if(ptr[nodeA]!=EMPTY && ptr[nodeB]==EMPTY)
{
en2 = 1;
int f = findroot(ptr,nodeA);
en1 = -(ptr[f]);
ptr[nodeB] = f;
ptr[f] += -1;
index = f;
entropy = entropy-(-(double)1.0/(double)vertices*log(1.0/(double)vertices))-(-(double)en1/(double)vertices*log((double)en1/vertices))+(-(double)(-ptr[index])/vertices*log((-ptr[index])/(double)vertices));
if(entropy<0) entropy = 0;
}
else if(ptr[nodeA]!=EMPTY && ptr[nodeB]!=EMPTY)
{
int g,h;
g = findroot(ptr,nodeA);
en1 = -(ptr[g]);
h = findroot(ptr,nodeB);
en2 = -(ptr[h]);
if(g!=h)
{
if(ptr[g]<ptr[h])
{
ptr[g] += ptr[h];
ptr[h] = g;
index = g;
}
else
{
ptr[h] += ptr[g];
ptr[g] = h;
index = h;
}
entropy = entropy-(-(double)en1/(double)vertices*log((double)en1/(double)vertices))-(-(double)en2/vertices*log((double)en2/(double)vertices))+(-(double)(-ptr[index])/vertices*log((double)(-ptr[index])/(double)vertices));
if(entropy<0) entropy = 0;
}
else
{
jump=big-bigtemp;
#pragma omp atomic
maxclus[i] += big;
#pragma omp atomic
delmx[i] += jump;
if(entropy<0) entropy = 0;
#pragma omp atomic
entropycalc[i] += entropy;
bigtemp = big;
continue;
}
}
if(-ptr[index]>big) big = -ptr[index];
jump = big - bigtemp;
#pragma omp atomic
maxclus[i] += big;
#pragma omp atomic
delmx[i] += jump;
if(entropy<0) entropy = 0;
#pragma omp atomic
entropycalc[i] += entropy;
bigtemp = big;
}
}
network.clear();
#pragma omp atomic
runcounter++;
int rem = (runcounter * 100/run) % 5;
if(rem == 0)
cout<<"Progress: "<<(double)runcounter*100/run<<"%"<<endl;
}
delete [] ptr;
delete [] netmap1;
delete [] netmap2;
delete [] random;
}
//fout1.open(filename1.c_str());
//fout2.open(filename2.c_str());
//fout3.open(filename3.c_str());
connectionNumber = con;
for(int i=1;i<=vertices;i++)
{
//fout1<<(double)i/vertices<<'\t'<<(double)maxclus[i]/vertices/run<<endl;
//fout2<<(double)i/vertices<<'\t'<<(double)delmx[i]/run<<endl;
//fout3<<(double)i/vertices<<'\t'<<(double)entropycalc[i]/run<<endl;
}
//fout1.close();
//fout2.close();
//fout3.close();
//delete[] random;
//random = NULL;
//delete [] netmap1;
//netmap1 = NULL;
//delete [] netmap2;
//netmap2 = NULL;
//delete [] ptr;
//ptr = NULL;
delete[] maxclus;
maxclus = NULL;
delete[] delmx;
delmx = NULL;
delete[] entropycalc;
entropycalc = NULL;
return 0;
}
</code></pre>
<p><a href="https://pastebin.com/St97Z8HN" rel="nofollow noreferrer">Linear Code</a></p>
<pre><code>#include<iostream>
#include<vector>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<ctime>
#include<cmath>
#include<random>
#include<fstream>
#include<algorithm>
//#include<bits/stdc++.h>
//#include "openacc_curand.h"
using namespace std;
//vector<int> network;
int EMPTY = 0;
int connectionNumber = 0; // it indexes the connection between different nodes of the network
// this function does the union find work for the percolation
//#pragma acc routine seq
int findroot(int ptr[],int i)
{
if(ptr[i]<0) return i;
return ptr[i]=findroot(ptr,ptr[i]);
}
/*#pragma acc routine seq
int findroot(int ptr[],int i)
{
//cao = 1;
int r,s;
r = s = i;
while (ptr[r]>=0)
{
ptr[s] = ptr[r];
s = r;
r = ptr[r];
}
return r;
}*/
int main()
{
int seed,vertices,m,run,filenum,M;
//I am just going to set the initial value for your need
/* cout<<"enter seed size: ";
cin>>seed;
cout<<endl;
cout<<"enter vertice number: ";
cin>>vertices;
cout<<endl;
cout<<"order number: ";
cin>>m;
cout<<endl;
cout<<"order of Explosive Percolation: ";
cin>>M;
cout<<endl;
cout<<"enter ensemble number: ";
cin>>run;
cout<<endl;
cout<<"enter filenumber: ";
cin>>filenum;
cout<<endl;
*/
seed = 6;
vertices = 500000;
m = 5;
M = 12;
run = 50;
filenum = 10;
//this sets up the connection and initializes the array;
int con = 0;
for(int i=1;i<seed;i++)
{
con = con + i;
}
con = con + (vertices-seed)*m;
int* netmap1 = new int[con+1]; //node 1 that is connected to a certain connectionNumber
int* netmap2 = new int[con+1]; //node 2 that is connected to a certain connectionNumber
for(int i=1;i<=con;i++)
{
netmap1[i] = 0;
netmap2[i] = 0;
}
connectionNumber = con;
srand(time(NULL));
int A,B,C;
A = vertices;
B = run;
C = filenum;
//saved filename
string filename1;
filename1 = "maxclus_";
string filename2;
filename2 = "delmx_";
string filename3;
filename3 = "entropy_";
filename1 = filename1+to_string(A)+"node_"+to_string(m)+"m_"+to_string(M)+"M_"+to_string(B)+"ens"+to_string(C)+".dat";
filename2 = filename2+to_string(vertices)+"node_"+to_string(m)+"m_"+to_string(M)+"M_"+to_string(run)+"ens"+to_string(filenum)+".dat";
filename3 = filename3+to_string(vertices)+"node_"+to_string(m)+"m_"+to_string(M)+"M_"+to_string(run)+"ens"+to_string(filenum)+".dat";
ofstream fout1,fout2,fout3;//,fout3;
int* random = NULL;
random = new int[connectionNumber+1];
double* maxclus = NULL;
maxclus = new double[vertices+1];
double* delmx = NULL;
delmx = new double[connectionNumber+1];
double* entropycalc = NULL;
entropycalc = new double[connectionNumber+1];
for(int i=0;i<=vertices;i++)
{
maxclus[i]=0;
delmx[i]=0;
entropycalc[i]=0;
}
for(int i=0;i<=connectionNumber;i++)
{
random[i] = i;
}
//this is the pointer that needs to be made private for all the parallel loops
int* ptr = new int[vertices+1];
for(int i=0;i<vertices+1;i++) ptr[i]=0;
//the main program starts here
//#pragma acc data copy(maxclus[0:connectionNumber],delmx[0:connectionNumber],entropycalc[0:connectionNumber]), copyin(netmap1[0:connectionNumber],netmap2[0:connectionNumber])
for(int i=1;i<=run;i++)
{
cout<<"run : "<<i<<endl;
//vector<size_t> network;
vector<int> network;
connectionNumber = 0;
//cout<<network.capacity()<<endl;
//seeds are connected to the network
for(int i=1;i<=seed;i++)
{
for(int j=1;j<=seed;j++)
{
if(j>i)
{
connectionNumber=connectionNumber + 1;
netmap1[connectionNumber]=i; //connections are addressed
netmap2[connectionNumber]=j;
network.push_back(i); // the vector is updated for making connection
network.push_back(j);
}
}
}
int concheck = 0;
int ab[m]; //this array checks if a node is chosen twice
int countm = 0;
for(int i = seed+1;i<=vertices; i++)
{
countm = 0;
for(int k=0;k<m;k++) ab[k] = 0;
for(int j = 1; ;j++)
{
concheck = 0;
int N1=network.size() ;
int M1=0;
int u = M1 + rand()/(RAND_MAX/(N1-M1+1) + 1);
for(int n=0;n<m;n++)
{
if(ab[n] == network[u]) concheck = 1;
}
//if condition is fulfilled the connection are given to the nodes
//the data is saved in the arrays of the connection
if(concheck == 0 && network[u]!=i)
{
ab[countm] = network[u];
countm=countm+1;
connectionNumber=connectionNumber+1;
netmap1[connectionNumber] = i;
netmap2[connectionNumber] = network[u];
network.push_back(i);
network.push_back(network[u]);
}
if(countm==m) break;
}
}
//the random list of connection are shuffled
random_shuffle(&random[1],&random[connectionNumber]);
double rand_seed = time(NULL);
//this is where the problem lies
//basically i want to make all the rx loops parallel in such a way that every parallel loop will have their own copy of ptr[ ] and random[ ] which they can modify themselves
// this whole part does the 'explosive percolation' and saves the data in maxclus, delmx, entropycalc array of different runs
//#pragma acc update device(maxclus,delmx,entropycalc,netmap1,netmap2)
//#pragma acc data copy(maxclus[0:connectionNumber],delmx[0:connectionNumber],entropycalc[0:connectionNumber]), copyin(netmap1[0:connectionNumber],netmap2[0:connectionNumber])
//#pragma acc parallel loop private(ptr[0:vertices+1]) firstprivate(random[0:connectionNumber])
for(int rx=1;rx<=1;rx++)
{
int index=0,big=0,bigtemp=0,jump=0,en1=0,en2=0;
int nodeA=0,nodeB=0;
int indx1=0;
int node[2*M+1];// = {0};
int clus[2*M+1];// = {0};
double entropy = log(vertices);
//curandState_t state;
//curand_init(rand_seed*rx,0,0,&state);
for(int i=0;i<=vertices;i++) ptr[i] = EMPTY;
//#pragma acc loop seq
for(int i=1;i<=vertices;i++)
{
if(i!=connectionNumber)
{
int algaRandomIndex = 0;
for(int nodeindex = 0; nodeindex<2*M; nodeindex+=2)
{
node[nodeindex] = netmap1[random[i + algaRandomIndex]];
node[nodeindex + 1] = netmap2[random[i + algaRandomIndex]];
algaRandomIndex++;
}
for(int nodeindex = 0; nodeindex<2*M; nodeindex++)
{
if(ptr[node[nodeindex]]==EMPTY) clus[nodeindex] = 1;
else
{
int x = findroot(ptr,node[nodeindex]);
clus[nodeindex] = -ptr[x];
}
}
int clusmul[M];
int clusindex1 = 0;
for(int clusindex = 0; clusindex<M; clusindex++)
{
clusmul[clusindex] = clus[clusindex1]*clus[clusindex1+1];
clusindex1 += 2;
}
bool clusmulCheck = true;
for(int ase = 0; ase < M; ase++)
{
bool clusmulCheck1 = true;
if(clusmul[ase] == 1) clusmulCheck1 = true;
else clusmulCheck1 = false;
clusmulCheck = clusmulCheck && clusmulCheck1;
}
if(clusmulCheck)
{
nodeA = node[0];
nodeB = node[1];
for(int someK = 1; someK < M; someK++)
{
int N1=connectionNumber;
int M1=i+M;
int u = M1 + rand()/(RAND_MAX/(N1-M1+1) + 1);
int temp = random[u];
random[u] = random[i+someK];
random[i+someK] = temp;
}
}
else
{
int low = clusmul[0];
indx1 = 1;
for(int as=0;as<11;as++)
{
if(clusmul[as]<low)
{
low = clusmul[as];
indx1 = as+1;
}
}
nodeA = node[2*indx1 - 2];
nodeB = node[2*indx1 - 1];
int temp = random[i+(indx1-1)];
random[i+(indx1-1)] = random[i];
random[i] = temp;
for(int ase = 1; ase < M; ase++)
{
int N1=connectionNumber;
int M1=i+M;
int u = M1 + rand()/(RAND_MAX/(N1-M1+1) + 1);
int temp = random[u];
random[u] = random[i+ ase];
random[i+ ase] = temp;
}
}
}
if(ptr[nodeA]==EMPTY && ptr[nodeB]==EMPTY)
{
en1=1;
en2=1;
ptr[nodeA] = -2;
ptr[nodeB] = nodeA;
index = nodeA;
entropy = (double)(entropy-(-2.0/vertices*log(1.0/vertices))+(-2.0/vertices*log(2.0/vertices)));
if(entropy<0) entropy = 0;
}
else if(ptr[nodeA]==EMPTY && ptr[nodeB]!=EMPTY)
{
en1=1;
int e = findroot(ptr,nodeB);
en2 = -(ptr[e]);
ptr[nodeA] = e;
ptr[e] += -1;
index = e;
entropy = entropy-(-(double)1.0/vertices*log(1.0/(double)vertices))-(-(double)en2/vertices*log((double)en2/vertices))+(-( double)(-ptr[index])/vertices*log((-ptr[index])/(double)vertices));
if(entropy<0) entropy = 0;
}
else if(ptr[nodeA]!=EMPTY && ptr[nodeB]==EMPTY)
{
en2 = 1;
int f = findroot(ptr,nodeA);
en1 = -(ptr[f]);
ptr[nodeB] = f;
ptr[f] += -1;
index = f;
entropy = entropy-(-(double)1.0/(double)vertices*log(1.0/(double)vertices))-(-(double)en1/(double)vertices*log((double)en1/vertices))+(-(double)(-ptr[index])/vertices*log((-ptr[index])/(double)vertices));
if(entropy<0) entropy = 0;
}
else if(ptr[nodeA]!=EMPTY && ptr[nodeB]!=EMPTY)
{
int g,h;
g = findroot(ptr,nodeA);
en1 = -(ptr[g]);
h = findroot(ptr,nodeB);
en2 = -(ptr[h]);
if(g!=h)
{
if(ptr[g]<ptr[h])
{
ptr[g] += ptr[h];
ptr[h] = g;
index = g;
}
else
{
ptr[h] += ptr[g];
ptr[g] = h;
index = h;
}
entropy = entropy-(-(double)en1/(double)vertices*log((double)en1/(double)vertices))-(-(double)en2/vertices*log((double)en2/(double)vertices))+(-(double)(-ptr[index])/vertices*log((double)(-ptr[index])/(double)vertices));
if(entropy<0) entropy = 0;
}
else
{
jump=big-bigtemp;
//#pragma acc atomic
maxclus[i] += big;
//#pragma acc atomic
delmx[i] += jump;
if(entropy<0) entropy = 0;
//#pragma acc atomic
entropycalc[i] += entropy;
bigtemp = big;
continue;
}
}
if(-ptr[index]>big) big = -ptr[index];
jump = big - bigtemp;
//#pragma acc atomic
maxclus[i] += big;
//#pragma acc atomic
delmx[i] += jump;
//#pragma acc atomic
if(entropy<0) entropy = 0;
entropycalc[i] += entropy;
bigtemp = big;
}
}
//vector<size_t>().swap(network);
//vector<int>().swap(network);
//network.clear();
//network.erase(network.begin(),network.end());
//cout<<network.capacity()<<endl;
network.shrink_to_fit();
//cout<<network.capacity()<<endl;
/*for(int i=0;i<connectionNumber;i++)
{
cout<<"maxclus: "<<maxclus[i]<<'\t'<<"delmx: "<<delmx[i]<<'\t'<<"entropy: "<<entropycalc[i]<<'\t'<<endl;
}*/
}
//fout1.open(filename1.c_str());
//fout2.open(filename2.c_str());
//fout3.open(filename3.c_str());
connectionNumber = con;
for(int i=1;i<=vertices;i++)
{
//fout1<<(double)i/vertices<<'\t'<<(double)maxclus[i]/vertices/run<<endl;
//fout2<<(double)i/vertices<<'\t'<<(double)delmx[i]/run<<endl;
//fout3<<(double)i/vertices<<'\t'<<(double)entropycalc[i]/run<<endl;
}
//fout1.close();
//fout2.close();
//fout3.close();
delete[] random;
random = NULL;
delete[] maxclus;
maxclus = NULL;
delete[] delmx;
delmx = NULL;
delete[] entropycalc;
entropycalc = NULL;
delete [] netmap1;
netmap1 = NULL;
delete [] netmap2;
netmap2 = NULL;
delete [] ptr;
ptr = NULL;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T14:36:30.000",
"Id": "383832",
"Score": "3",
"body": "With a nearly 500 lines long `main()` function this code is hard to reason about. Maybe split it into multiple function? I've been staring at it for like 15 minutes, and still ca... | [
{
"body": "<p>I haven't examined the code in great detail yet, but the first point that nearly jumped out was the use of <code>rand()</code> inside the parallelized loop.</p>\n\n<p>Each call to <code>rand()</code> not only retrieves data, but also modifies a seed that's normally shared between all threads, so a... | {
"AcceptedAnswerId": "199528",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T07:57:10.977",
"Id": "198479",
"Score": "1",
"Tags": [
"c++",
"openmp"
],
"Title": "BA network generator and Percolator with OpenMP and also Linear code"
} | 198479 |
<p>I've recently solved Project Euler's 15th problem stating:</p>
<blockquote>
<p>Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.</p>
<p>How many such routes are there through a 20×20 grid?</p>
</blockquote>
<p>This is my dynamic approach in C++</p>
<pre><code>#include <cstdio>
const unsigned short n = 20;
int main() {
unsigned long long p[n][n];
for (unsigned short i = 2; i <= n; i++)
p[n - i][n - 1] = i + 1;
for (unsigned short i = n - 2; i >= 1; i--) {
p[i][i] = 2 * p[i][i + 1];
for (unsigned short k = i; k >= 1; k--)
p[k - 1][i] = p[k][i] + p[k - 1][i + 1];
}
printf("%llu", 2 * p[0][1]);
}
</code></pre>
<p>I am aware that this problem could be solved way more efficiently and faster by simply calculating \${(2n)!}/{(n!)^2}\$, however I decided to look at this problem from a programmer's point of view, rather than a mathematician's.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T15:53:04.183",
"Id": "383847",
"Score": "8",
"body": "It's worth mentioning that the \"programmer's point of view\" should include mathematical simplification of algorithms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creat... | [
{
"body": "<pre><code>#include <cstdio>\n</code></pre>\n\n<p>If your goal is to write C++, you're really off to a bad start using the C standard I/O library.</p>\n\n<pre><code>const unsigned short n = 20;\n</code></pre>\n\n<p>The modern way to do compile time constants is with <code>constexpr</code>.</p>\... | {
"AcceptedAnswerId": "199487",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T12:30:49.513",
"Id": "198485",
"Score": "8",
"Tags": [
"c++",
"programming-challenge",
"combinatorics",
"dynamic-programming"
],
"Title": "Project Euler #15: counting paths through a 20 × 20 grid"
} | 198485 |
<p>First time around Code Review so please be gentle (and I am happy for comments on which angles of this post are a good fit and which less so). I'm not pretty much used to software engineering in Python, and so I figured this might be a match:</p>
<pre><code>import pickle
class Lexicon:
'a lexicon holding each term and providing some lexicon services like term frequency, and term ids'
def __init__(self):
self.dictt = {}
def size(self):
return len(self.dictt)
def add(self, token):
if token in self.dictt:
self.dictt[token] = self.dictt[token] + 1
else:
self.dictt[token] = 1
return token # for traceability by the caller
def remove_low_frequency(self, min_frequency):
'removes low frequency tokens'
self.dictt = dict(filter(lambda kv: kv[1] >= min_frequency, self.dictt.items()))
def pickle(self, output_file_name):
with open(output_file_name, 'wb') as handle:
pickle.dump(self.dictt, handle, protocol=pickle.HIGHEST_PROTOCOL)
@staticmethod
def unpickle(input_file_name):
with open(input_file_name, 'rb') as handle:
new_lexicon = Lexicon()
new_lexicon.dictt = pickle.load(handle)
return new_lexicon
def equals(self, other):
return self.dictt == other.dictt
</code></pre>
<ol>
<li>Am I being non-idiomatic above, or, just cumbersome anywhere? </li>
<li>Does my <code>unpickle</code> method actually represent potential for a huge memory leak as I'm reusing the name but putting a different dictionary into it? </li>
<li>What might be the Pythonic idiom for a correct implementation in these cases?</li>
<li>And what is the Pythonic way of making this class safe for concurrent usage? (thread-safe)</li>
</ol>
| [] | [
{
"body": "<p>First of all, the <code>Lexicon</code> class reinvents <a href=\"https://docs.python.org/2.7/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>Counter</code> from <code>collections</code></a>. Maybe subclassing can help.</p>\n\n<p>Second, I'd separate persistence fro... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T14:44:53.140",
"Id": "199489",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"python-2.x",
"memory-management"
],
"Title": "Python lexicon class"
} | 199489 |
<p>I am working on the following assignment and I am a bit lost:</p>
<blockquote>
<p>Build a regression model that will predict the rating score of each
product based on attributes which correspond to some very common words
used in the reviews (selection of how many words is left to you as a
decision). So, for each product you will have a long(ish) vector of
attributes based on how many times each word appears in reviews of
this product. Your target variable is the rating. You will be judged
on the process of building the model (regularization, subset
selection, validation set, etc.) and not so much on the accuracy of
the results.</p>
</blockquote>
<p>This is what I currently have as code (I use <code>mord</code>'s API for the regression model since <code>Rating</code> is categorical):</p>
<pre><code># Create word matrix
bow = df.Review2.str.split().apply(pd.Series.value_counts)
rating = df['Rating']
df_rating = pd.DataFrame([rating])
df_rating = df_rating.transpose()
bow = bow.join(df_rating)
# Remove some columns and rows
bow = bow.loc[(bow['Rating'].notna()), ~(bow.sum(0) < 80)]
# Divide into train - validation - test
bow.fillna(0, inplace=True)
rating = bow['Rating']
bow = bow.drop('Rating', 1)
x_train, x_test, y_train, y_test = train_test_split(bow, rating, test_size=0.4, random_state=0)
# Run regression
regr = m.OrdinalRidge()
regr.fit(x_train, y_train)
scores = cross_val_score(regr, bow, rating, cv=5, scoring='accuracy')
# scores -> array([0.75438596, 0.73684211, 0.66071429, 0.53571429, 0.60714286])
# avg_score -> Accuracy: 0.66 (+/- 0.16)
</code></pre>
<p>Could I have some constructive criticism on the above code please (regarding what I am missing from the posed task)?</p>
<hr>
<p>This is what <code>bow</code> looks like:</p>
<p><a href="https://i.stack.imgur.com/QGGnW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QGGnW.png" alt="enter image description here"></a></p>
<p>If you need any other information just comment I will happily edit it in.</p>
<p>P.S: I've been working on this the past few days, this is my first regression model I code. I'll be honest, I didn't find it easy. So if someone could lend a helping hand I would be so ever grateful. Lastly, I want to be clear that I don't post to get a complete answer, code-wise (even if I would not say no to that). I am merely hoping in some guidance. My deadline approaches fast :P</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T10:26:46.740",
"Id": "383923",
"Score": "0",
"body": "The wording of the question feels like the code does not work as expected and you're asking about implementing missing features. Do I understand correctly?"
},
{
"Content... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T15:15:19.000",
"Id": "199491",
"Score": "2",
"Tags": [
"python",
"homework",
"statistics",
"pandas",
"clustering"
],
"Title": "Regression on Pandas DataFrame"
} | 199491 |
<p>I wrote this function that, given an array, calculates the closest number to zero. The conditions are the following:</p>
<ul>
<li>if the array is empty, return 0</li>
<li>if the array has two values share the "closeness" to zero, return the positive (for example if -1 and 1)</li>
</ul>
<p><a href="https://repl.it/@ChrisPanayotova/Find-closest-to-zero" rel="nofollow noreferrer">Here</a> is my code and link to it.</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>// Write a function that takes an array an finds the closes number to 0.
// Disregard all 0s
// If the array is empty return 0
const tempArray = [-1, 0, 0, 5, -5, 6, -3, 2, 10, 13, 8, 70, -36, 36];
function calculateClosestTo0 (tempArray) {
let minusTemps = [];
let plusTemps = [];
if (!tempArray.length) {
return 0;
}
for (let i = 0; i < tempArray.length - 1; i++) {
if (tempArray[i] < 0) {
minusTemps.push(tempArray[i]);
} else if (tempArray[i] > 0) {
plusTemps.push(tempArray[i]);
}
}
minusTemps.sort((a, b) => b - a)
plusTemps.sort((a, b) => a - b)
if (plusTemps[0] === Math.abs(minusTemps[0])) {
return(plusTemps[0])
}
if (plusTemps[0] < Math.abs(minusTemps[0])) {
return(plusTemps[0])
}
if (plusTemps[0] > Math.abs(minusTemps[0])) {
return(minusTemps[0])
}
}
calculateClosestTo0(tempArray)</code></pre>
</div>
</div>
</p>
<p>What I intended to do is separate the array into minus values and positive values. The minus values I ordered by descending (cause I want the first item to be the "biggest" in minus numbers perspective) and the positive in ascending. After that, I compare the first number.</p>
<p>What worries me most is the I try to remove the "0" like that:</p>
<pre><code>for (let i = 0; i < tempArray.length - 1; i++) {
if (tempArray[i] < 0) {
minusTemps.push(tempArray[i]);
} else if (tempArray[i] > 0) {
plusTemps.push(tempArray[i]);
}
}
</code></pre>
<p>My colleagues usually frowned upon having a condition that has "else if" and nothing else. Why, I don't know.</p>
<p>Another thing that worries me is that ending part, where I have 3 conditions to return the correct value. Is there a smarter way to do that?</p>
<p>And generally: do you think that there is a better approach to such a problem?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T15:23:58.157",
"Id": "383839",
"Score": "0",
"body": "_\"My collgues usually froun upon having a condition that has \"else if\" and no else. Why: I don't know.\"_ Because you leave conditional cases uncovered from your code."
},
... | [
{
"body": "<ol>\n<li>I suggest to use functional approach, which makes code more readable and concise.</li>\n<li>I suggest to write functions that solve some generic problem, not particular one.</li>\n<li>I think using word \"temp\" in variable names is redundant.</li>\n</ol>\n\n<p>My suggested solution:</p>\n\... | {
"AcceptedAnswerId": "199518",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T15:19:51.423",
"Id": "199492",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "A function to find temperatures closest to zero"
} | 199492 |
<p>I am developing scikit-learn like implementation for C++ it is in the initial stage while developing I've started doubt myself that is this the correct implementation, since here <em>accuracy is more important than robustness</em>. I am still learning C++ and I would like an expert consultation since the development is at beginning stage I could fix and prevent future errors. Thank you</p>
<pre><code>#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<typeinfo>
#include<cmath>
//===================================================================
// FOR COMPUTING MEAN
//===================================================================
template<typename T>
class mean
{
public:
T get_mean(std::vector<T> vec)
{
T total = 0;
for (auto i : vec) total += i;
auto average = total / vec.size();
return average;
}
};
//===================================================================
// FOR COMPUTING MEDIAN
//===================================================================
template<typename T>
class median
{
public:
T get_median(std::vector<T> vec, bool sorted = false)
{
if (sorted == false)std::sort(vec.begin(), vec.end());
auto vector_size = vec.size();
if (vector_size == 1) return vec[0];
// If the elements are odd return the middle element
if (vector_size % 2 != 0) return vec[vector_size / 2];
// If the elements count are even return the average of middle elements
auto middle_element_one = vector_size / 2;
auto middle_element_two = middle_element_one - 1;
auto result = (vec[middle_element_one] + vec[middle_element_two]) / 2;
return result;
}
};
//====================================================================
// FOR COMPUTING THE MODE
//====================================================================
template<typename T>
class mode
{
public:
T get_mode(std::vector<T> vec)
{
std::sort(vec.begin(), vec.end());
std::map<T, unsigned long int> number_count_table;
std::vector<T> elements_with_max_occurences;
unsigned long int bigger_no = 1;
for (auto i : vec)
{
if (number_count_table.find(i) == number_count_table.end()) number_count_table[i] = 1;
else {
auto current_count = number_count_table[i];
current_count++;
if (current_count>bigger_no) bigger_no = current_count;
number_count_table[i] = current_count;
}
}
if (bigger_no == 1) {
return vec[0];
}
else
{
for (auto itr : number_count_table)
{
if (itr.second == bigger_no) elements_with_max_occurences.push_back(itr.first);
}
std::sort(elements_with_max_occurences.begin(), elements_with_max_occurences.end());
return elements_with_max_occurences[0];
}
}
};
//========================================================================================
// FOR COMPUTING WEIGHTED MEAN
//========================================================================================
template <typename T>
class weighted_mean
{
private:
unsigned long int vector_size;
public:
T get_weighted_mean(std::vector<T> vec, std::vector<T> weights)
{
this->vector_size = vec.size();
T numerator = 0;
T total_weight = 0;
for (unsigned long int i = 0; i<vector_size; i++)
{
T current_value = vec[i] * weights[i];
numerator += current_value;
total_weight += weights[i];
}
//std::cout << "NUMERATOR: " << numerator << "\n";
//std::cout << "DENOMINATOR: " << summation_of_weights << "\n";
return numerator / total_weight;
}
};
//==========================================================================================
// FOR COMPUTING STANDARD DEVIATION
//==========================================================================================
template <typename T>
class standard_deviation : public mean<T>
{
private:
T mean_value;
T standard_deviation_value;
public:
T get_standard_deviation(std::vector<T> vec)
{
this->mean_value = this->get_mean(vec);
this->standard_deviation_value = 0;
for (unsigned long int i = 0; i<vec.size(); ++i)
{
T powered_value = (vec[i] - this->mean_value) * (vec[i] - this->mean_value);
this->standard_deviation_value += powered_value;
}
this->standard_deviation_value = sqrt(this->standard_deviation_value / vec.size());
return this->standard_deviation_value;
}
};
//==========================================================================================
// FOR COMPUTING INTERQUARTILE RANGE
//==========================================================================================
/*
CALCULATING INTERQUARTILE RANGE FOR ODD NO OF ELEMENTS:
-------------------------------------------------------
Given Elements(E) = { 3,5,5,7,8,8,9,10,13,13,14,15,16,22,23}
Step 1: Sort it! Here we already have an sorted values
E = { 3, 5, 5, 7, 8, 8, 9, 10, 13, 13, 14, 15, 16, 22, 23 }
Step 2: Get the median for the values
Median (M) = 10
Step 3: The lower and the upper half
Elements which are left to the median are called left half and
to the right is right half
3 5 5 7 8 8 9 10 13 13 14 15 16 22 23
|___________| | |__________________|
LOWER HALF MEDIAN UPPER HALF
Step 4:
Q1 = median of left half
Q3 = median of right half
interquartile_range = Q3 - Q1
CALCULATING INTERQUARTILE RANGE FOR EVEN NO OF ELEMENTS:
--------------------------------------------------------
Step 1: Sort the array
Step 2: Get the median of the array
Step 3: Insert the median back to the array
Step 4: Follow odd no procedure since we have an array
of odd size.
*/
template <typename T>
class interquartile_range : public median<T>
{
private:
bool is_odd_vector;
public:
T get_interquartile_range(std::vector<T> vec, bool sorted = false)
{
if (sorted == false) std::sort(vec.begin(), vec.end());
if (vec.size() % 2 != 0) is_odd_vector = true;
else is_odd_vector = false;
if (is_odd_vector)
{
return compute(vec);
}
else
{
unsigned long int middle_index = vec.size() / 2;
T median_for_vector = this->get_median(vec);
vec.insert(vec.begin() + middle_index, median_for_vector);
return compute(vec);
}
}
private:
T compute(std::vector<T> vec)
{
unsigned long int middle_element_index = vec.size() / 2;
std::vector<T> lower_half;
for (unsigned long int i = 0; i < middle_element_index; i++)
{
lower_half.push_back(vec[i]);
}
std::vector<T> upper_half;
for (unsigned long int i = middle_element_index + 1; i<vec.size(); i++)
{
upper_half.push_back(vec[i]);
}
T q1 = this->get_median(lower_half);
T q3 = this->get_median(upper_half);
return q3 - q1;
}
};
//================================================================================
// FREQUENCY MAP TO VECTOR CONVERTER
//================================================================================
template <typename T>
class frequency_map_converter
{
public:
void to_vector(std::map<T, unsigned long int> frequency_map, std::vector<T> &target_vector)
{
for (auto element : frequency_map)
{
for (unsigned long int i = 0; i < element.second; i++) target_vector.push_back(element.first);
}
}
};
//================================================================================
// FOR CALCULATING THE RANGE
//================================================================================
/*
HOW TO CALCULATE THE RANGE
--------------------------
sorted input vector = { 1, 2, 3, 4}
greatest_value = 4
least_value = 1
range = greatest_value - least_value
i.e range = 3
*/
template <typename T>
class range
{
public:
T get_range(std::vector<T> vec, bool sorted = false)
{
if (sorted == false) std::sort(vec.begin(), vec.end());
T greatest_value = vec[vec.size() - 1];
T least_value = vec[0];
return greatest_value - least_value;
}
};
//===============================================================================
// FOR CALCULATING THE QUARTILE
//===============================================================================
template <typename T>
class quartile : public median<T>
{
public:
std::map<std::string, T> get_quartile(std::vector<T> vec, bool sorted = false)
{
if (sorted == false) std::sort(vec.begin(), vec.end());
std::map<std::string, T> result;
result["q2"] = this->get_median(vec, sorted = true);
unsigned long int middle_index = vec.size() / 2;
std::vector<T> lower_half;
for (unsigned long int i = 0; i<middle_index; i++)
{
lower_half.push_back(vec[i]);
}
result["q1"] = this->get_median(lower_half, sorted = true);
// free the memory by clearning the lower half
lower_half.clear();
std::vector<T> upper_half;
if (vec.size() % 2 != 0) middle_index++;
for (unsigned long int i = middle_index; i<vec.size(); i++)
{
upper_half.push_back(vec[i]);
}
result["q3"] = this->get_median(upper_half, sorted = true);
return result;
}
};
// ====================== TEXT TO NUMERICAL DATA CONVERTERS ===================
template <typename T>
class LabelEncoder
{
private:
long int current_encoded_value = -1;
std::vector<T> array;
std::map < T, long int> encoded_values;
public:
void fit(std::vector<T> array)
{
this->array = array;
std::sort(array.begin(), array.end());
std::vector<T> sorted_array = array;
for (auto i : sorted_array)
{
if (encoded_values.find(i) == encoded_values.end()) {
current_encoded_value++;
encoded_values[i] = current_encoded_value;
}
}
}
std::vector<long int> transform(std::vector<T> array)
{
std::vector<long int> transformed_array;
for (auto i : array)
{
transformed_array.push_back(encoded_values[i]);
}
return transformed_array;
}
std::vector<long int> transform()
{
return transform(this->array);
}
};
/*
Future Milestones - To implement mostlty used vectorizers from scikit-learn:
1. Implement CountVectorizer
2. Implement TfidfVectorizer
*/
// ============================ END OF TEXT TO NUMERICAL ENCODERS ==============================
// ============================ ACTIVATION FUNCTIONS ============================
template <typename T>
class activation_function
{
public:
T identity(T value)
{
return value;
}
long double sigmoid(T value)
{
T negative_value = -1 * value;
long double exponential = exp(negative_value);
long double result = 1 / (1 + exponential);
return result;
}
long double tan_h(T value)
{
long double pos_exp = exp(value);
long double neg_exp = exp(-1 * value);
return (pos_exp - neg_exp) / (pos_exp + neg_exp);
}
int threshold(T value)
{
if (value < 0) return 0;
else return 1;
}
};
</code></pre>
<p>This code passed all the unit-tests from the Hacker-rank for some of the statistics exercises. </p>
<p>Most of the ML libraries available in C++ are without documentation so it is hard to understand and implement. So I took this initiative. The main aim is to make is very easy for the end user like scikit-learn does. It is single header so it is easier to be Incorporated in existing projects.</p>
<p>License: Apache 2.0
Documentation: <a href="https://github.com/VISWESWARAN1998/statx" rel="nofollow noreferrer">https://github.com/VISWESWARAN1998/statx</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T17:15:29.157",
"Id": "383854",
"Score": "3",
"body": "you are aware that even with the last sentence in the question, this is licensed under CC-BY-SA-3.0 right?"
}
] | [
{
"body": "<h1>Wrapper classes</h1>\n\n<p>I don't get why many algorithms (like <code>get_mean</code>, <code>get_median</code>, ...) are wrapped inside a class that is basically just a fancy <code>namespace</code>.</p>\n\n<p>Why force the user to write <code>mean{}.get_mean(...)</code> if <code>mean(...)</code>... | {
"AcceptedAnswerId": "199498",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T15:56:17.560",
"Id": "199493",
"Score": "2",
"Tags": [
"c++",
"statistics",
"machine-learning"
],
"Title": "Basic Single Header statistics and ml libray for C++ - Scikit-Learn like implementation"
} | 199493 |
<p>This code is my first implementation of <a href="http://www.cubetimer.com/" rel="nofollow noreferrer">this</a> style of application in the console. In essence a stopwatch with some added functionality. I was interested in getting some feedback before I refactor and begin adding more features. I'm fairly new to programming and I specifically have concerns about my design pattern.</p>
<p>Known issues: </p>
<ol>
<li><p>When the program saves a "session" (a json file) a directory is hard coded into the program. If this directory does not already exist an error occurs. I plan to fix this in the future.</p></li>
<li><p>Size. The entire application is in one file, which is already causing me readability problems. All of my function definitions should be in a separate file at the very least.</p></li>
<li><p>When I grab user input to change menus, I do not always check if it's valid input and notify the user when it isn't. Example: line 138 I do not have a case if the input is not a valid command. As opposed to something like line 110.</p></li>
</ol>
<p>Concerns:</p>
<ol>
<li><p>Using <code>while</code> loops to change between "menus" or "states" has so far worked well, but I'm uncertain if my implementation is a good idea.</p></li>
<li><p>Variable shadowing. For a single example, I use the variable <code>command</code> 5 times in this program, but the value of command is defined by user input and hence almost always different. There are numerous other examples in the code of similar or identical variable names. However, these usages are in separate <code>while</code> loops, so should I be concerned? If I do need to change my variable names, how do I do it and not be verbose/unclear?</p></li>
<li><p>General code quality. Since I haven't been programming long I do not expect to have written stellar code. What are things I could do to improve the overall quality of this program?</p></li>
</ol>
<p>Code:</p>
<pre><code>import keyboard
import time
import json
import os
from fuzzywuzzy import process
def createSessionStructure():
'''Creates a data structure for a session and adds a timestamp'''
timestamp = time.ctime(time.time())
return {"session": {
"timestamp": timestamp,
"times": []
}
}
def cubeTime():
'''Returns (and prints) floating point number under normal circumstance. Returns None if timer operation is aborted.'''
print("Press space to begin timing, backspace to abort.")
trigger = keyboard.read_event()
if trigger.name == "backspace":
print("Cancelled")
return None
else:
start = time.perf_counter()
keyboard.wait("space")
end = time.perf_counter()
keyboard.press_and_release("backspace") # These lines fix a bug where space characters would end up littering the menu after the timer closed
keyboard.press_and_release("backspace") # By pressing backspace it clears any characters in the terminal to ensure a better user experience
print(round((end - start), 4))
return round((end - start), 4)
def storeSession(timeList):
'''Writes list of times into a nested python dictionary structure'''
session = createSessionStructure()
for time in timeList:
session["session"]["times"].append(time)
return session
def writeSession(session, directory):
'''Writes session data at filepath: directory. writeSession(exampleSession, "C:/foo/bar/") will create a json file inside /bar/ with the data from exampleSession'''
command = input("Do you want to name this file (yes/no)? ")
if command.lower() == "yes":
customName = input("Name: ")
outputFile = open(f"{directory}{customName}.json", "w+")
json.dump(session, outputFile, indent=4)
outputFile.close()
elif command.lower() == "no":
timeStamp = session["session"]["timestamp"].replace(" ", "-").replace(":",".")
outputFile = open(f"{directory}{timeStamp}.json", "w+")
json.dump(session, outputFile, indent=4) #outputFile.write(jsonString) <- old method replaced with json.dump
outputFile.close()
def appendSession(timeList, filepath):
'''Grabs old session data as a python object, appends new data to it, and overwrites the file with this new data'''
with open(filepath, "r+") as JSONfile:
sessionData = json.load(JSONfile)
for time in timeList:
sessionData["session"]["times"].append(time)
JSONfile.seek(0)
json.dump(sessionData, JSONfile, indent=4)
def fuzzyMatch(string, options):
'''returns the best match from a list of options'''
return process.extractOne(string, options)[0]
destination = "C:/Coding/cube-timer/times/"
PROGRAM_LOOP = True
mainMenu = True
dataMenu = False
cubeTimer = False
print("Welcome to Cube Timer!")
print("======================")
while PROGRAM_LOOP == True:
while mainMenu == True:
print("Main Menu")
print("Commands: times, timer, or quit")
command = input("Where would you like to go: ")
if command.lower() == "times":
mainMenu = False
cubeTimer = False
dataMenu = True
elif command.lower() == "timer":
mainMenu = False
cubeTimer = True
dataMenu = False
elif command.lower() == "quit":
PROGRAM_LOOP = False
mainMenu = False
dataMenu = False
cubeTimer = False
else:
print("I don't understand that.")
while dataMenu == True:
globaltimes = False
sessiontimes = False
command = input("Would you like to view global (gl), session (ses) times, or go back (back)? ")
if command.lower() == "gl":
globaltimes = True
sessiontimes = False
elif command.lower() == "ses":
sessiontimes = True
globaltimes = False
elif command.lower() == "back":
dataMenu = False
cubeTimer = False
mainMenu = True
else:
print("I don't understand that.")
while sessiontimes == True:
viewSession = False
print("Which session would you like to view?\n")
print(("-" * 20) + "\n")
sessionFileNames = os.listdir("times/")
for session in sessionFileNames:
print(session)
print(("-" * 20) + "\n")
sessionFileChoice = input("filename: ")
fuzzyFileName = fuzzyMatch(sessionFileChoice, sessionFileNames)
sessionFilePath = 'times/' + fuzzyFileName
with open(sessionFilePath, "r+") as JSONfile:
viewSession = True
sessionData = json.load(JSONfile)
timestamp = sessionData["session"]["timestamp"]
print(f"Session {fuzzyFileName} created at {timestamp}:\n")
for time in sessionData["session"]["times"]:
print(time)
print("\n")
while viewSession == True:
command = input("Display average (av), or quit (quit): ")
if command.lower() == "quit":
viewSession = False
sessiontimes = False
elif command.lower() == "av":
print(sum(sessionData["session"]["times"]) / len(sessionData["session"]["times"]))
while globaltimes == True:
print("This area has not been implimented yet, returning to data menu.")
globaltimes = False
sessiontimes = False
while cubeTimer == True:
session = False
command = input("Start a new session (new) or continue (cont) an old session? ")
if command.lower() == "new":
session = True
updateSession = False
sessionTimes = []
elif command.lower() == "cont":
print("Which session would you like to continue? ")
stringFileNames = os.listdir("times/")
for JSONfile in stringFileNames:
print(JSONfile)
fileChoice = input("filename: ")
fuzzyPath = 'times/' + fuzzyMatch(fileChoice, stringFileNames)
session = True
updateSession = True
sessionTimes = []
else:
command = input("Return to main menu? ")
if command.lower() == "yes":
mainMenu = True
cubeTimer = False
dataMenu = False
else:
pass
while session == True:
time.sleep(.1)
result = cubeTime()
time.sleep(.1)
if result == None:
command = input("You have paused the timer, would you like to save (save) or return to the main menu (menu)? ")
if command.lower() == "save":
if updateSession == True:
appendSession(sessionTimes, fuzzyPath)
sessionTimes = []
else:
savedData = storeSession(sessionTimes)
print(json.dumps(savedData, indent=2))
writeSession(savedData, destination)
sessionTimes = []
elif command.lower() == "menu":
mainMenu = True
session = False
cubeTimer = False
dataMenu = False
elif type(result) == float:
sessionTimes.append(result)
print(sessionTimes)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T19:43:15.307",
"Id": "383880",
"Score": "1",
"body": "@Daniel I have put the code directly in the post and would be happy to explain my reasoning behind any portion of the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<p>You currently have <code>createSessionStructure</code>, <code>storeSession</code>, <code>writeSession</code> and <code>appendSession</code>. These all create or manipulate a <code>Session</code> object and therefore I would make them members of a class:</p>\n\n<pre><code>class Session:\n def __... | {
"AcceptedAnswerId": "199536",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T18:44:34.510",
"Id": "199506",
"Score": "4",
"Tags": [
"python",
"beginner",
"console",
"timer"
],
"Title": "Speed-cubing timer console application"
} | 199506 |
<p>I am trying to implement a stack with Java:</p>
<pre><code>public class Stack<E> {
Node top = null;
public void push(E data) {
Node node = new Node(data);
if (null != top) {
node.next = top;
}
top = node;
}
public E pop() {
if (null == top) {
throw new IllegalStateException("Stack is empty");
} else {
E data = top.data;
top = top.next;
return data;
}
}
public E peek() {
if (null == top) {
throw new IllegalStateException("Stack is empty");
} else {
E data = top.data;
return data;
}
}
public void print() {
if (null == top) {
throw new IllegalStateException("Stack is empty");
} else {
Node node = top;
while(null != node) {
System.out.println(node.data);
node = node.next;
}
}
}
private class Node {
Node next;
E data;
Node(E data) {
this.data = data;
}
}
}
</code></pre>
<p>I am looking for feedback for the implementation. Also, I wanted to know if the <code>pop()</code> implementation can cause a memory leak?</p>
| [] | [
{
"body": "<blockquote>\n <p>I wanted to know if the pop() implementation can cause a memory leak?</p>\n</blockquote>\n\n<p>It will not cause a memory leak, because java is a garbage collected language. When top is no longer accessible the garbale collecter will free top if it sees fit.</p>\n\n<h3>feedback:</h... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T18:48:26.283",
"Id": "199507",
"Score": "3",
"Tags": [
"java",
"stack"
],
"Title": "Implementing a stack with Java"
} | 199507 |
<p>I'm learning Rust by learning the Rust programming language book. I'm now implementing the solution for the third challenge.</p>
<blockquote>
<p>Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, "Add Sally to Engineering" or "Add Amir to Sales." Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.</p>
</blockquote>
<p>I decided to do a simple UI to enter commands, but the implementation is very naive overall.</p>
<p>Rust is my first systems language. My background is in Ruby and Javascript.</p>
<pre><code>use std::collections::HashMap;
use std::io::{self, Write};
use std::str::SplitWhitespace;
fn main() {
println!("Welcome to the department interface. Please run a command:");
help();
let mut departments: HashMap<String, Vec<String>> = HashMap::new();
loop {
print_promt();
let command = get_command();
let mut command_iter = command.split_whitespace();
match command_iter.next() {
Some("add") => match process_add(&mut command_iter) {
Ok((employee, department)) => {
let mut employees = departments.entry(department).or_insert(Vec::new());
employees.push(employee);
}
Err(err) => println!("Error: {}", err),
},
Some("help") => help(),
Some("list") => println!("{:#?}", &departments),
Some("exit") => break,
Some(_) => println!("{}: Command unknown. Try `help`", command),
None => panic!("We shouldn't be here"),
}
}
}
fn help() {
println!("help: show this help.");
println!("exit: exits this program.");
println!("show: shows the deparment structure.");
println!("add: adds an employee to a department");
println!(" - usage: `add <employee name> to <department_name>`");
}
fn print_promt() {
print!("> ");
io::stdout().flush().ok().expect("Couldn't flush stdout!");
}
// I think this can be made better returning an Enum/Struct with a parsed command.
fn get_command() -> String {
let mut command = String::new();
io::stdin()
.read_line(&mut command)
.expect("Couldn't read command!");
command
}
// The compiler told me to add the lifetime, but I don't understand why (I haven't reached that
// part of the book yet.)
// FIXME `SplitWhitespace` is too specific.
fn process_add<'a>(command: &mut SplitWhitespace) -> Result<(String, String), &'a str> {
let mut employee = String::new();
let mut department = String::new();
// For a command "add Ronald Reagan to Old Presidents"
// - Consume the iterator onto `employee` until you find "to""
// - Consume the rest of the iterator onto `department`
// Using two loops feels naive though. I don't like the duplication inside them.
//
// Maybe `String` can be extended and I could add a `push_str_with_separator` method that does
// the extra check.
//
// employee.push_str_with_separator(word);
//
while let Some(word) = command.next() {
if word == "to" {
break;
}
if employee.len() > 0 {
employee.push_str(" ");
}
employee.push_str(word)
}
for word in command {
if department.len() > 0 {
department.push_str(" ");
}
department.push_str(word);
}
if employee.len() > 0 && department.len() > 0 {
Ok((employee, department))
} else {
Err("Could not parse command. Try `add <employee name> to <department name>")
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T20:57:35.203",
"Id": "199513",
"Score": "5",
"Tags": [
"beginner",
"rust",
"hash-map"
],
"Title": "HashMap exercise, Rust book Ch.8"
} | 199513 |
<p>This is a version of my skip-list implementation. In my project I store my custom class that is similar to a pair of blobs. I replaced my custom class with <code>int</code>. At the end of skiplist.cc, I also added the <code>main()</code> function with some test usage. I want to know if there are some mistakes or performance improvements I missed.</p>
<pre><code>#skiplist.h
#ifndef _SKIP_LIST_LIST_H
#define _SKIP_LIST_LIST_H
#include <cstdint>
#include <array>
using size_t = std::size_t;
using V = int;
using K = int;
constexpr int compare(V const a, K const b){
return a - b;
}
class SkipList {
public:
using size_type = size_t;
using height_type = uint8_t;
public:
static constexpr height_type MAX_HEIGHT = 64;
static constexpr height_type DEFAULT_HEIGHT = 32;
class Iterator;
public:
explicit
SkipList(height_type height = DEFAULT_HEIGHT);
SkipList(SkipList &&other);
~SkipList();
public:
bool clear();
const K *operator[](const K &key) const;
bool erase(const V &key);
bool insert(V &&data);
size_type size(bool const = false) const noexcept{
return dataCount_;
}
public:
Iterator lowerBound(const V &key) const;
Iterator begin() const;
static constexpr Iterator end();
private:
struct Node;
template<typename T>
using HeightArray = std::array<T, MAX_HEIGHT>;
height_type height_;
HeightArray<Node *>
heads_;
size_type dataCount_;
private:
void zeroing_();
struct NodeLocator;
NodeLocator locate_(const K &key, bool shortcut_evaluation);
const Node *locateNode_(const K &key, bool const exact) const;
height_type getRandomHeight_();
private:
class RandomGenerator;
static RandomGenerator rand_;
};
// ==============================
class SkipList::Iterator{
private:
friend class SkipList;
constexpr Iterator(const Node *node) : node_(node){}
public:
Iterator &operator++();
const V &operator*() const;
public:
bool operator==(const Iterator &other) const{
return node_ == other.node_;
}
bool operator!=(const Iterator &other) const{
return ! operator==(other);
}
const V *operator ->() const{
return & operator*();
}
private:
const Node *node_;
};
// ==============================
inline auto SkipList::lowerBound(const K &key) const -> Iterator{
return locateNode_(key, false);
}
inline auto SkipList::begin() const -> Iterator{
return heads_[0];
}
inline constexpr auto SkipList::end() -> Iterator{
return nullptr;
}
#endif
</code></pre>
<h1>skiplist.cc</h1>
<pre><code>#include "skiplist.h"
#include <stdexcept>
#include <algorithm> // fill
#include <random> // mt19937, bernoulli_distribution
#include <cassert>
class SkipList::RandomGenerator{
public:
bool operator()(){
return distr_(gen_);
}
private:
std::mt19937 gen_{ (uint32_t) time(nullptr) };
std::bernoulli_distribution distr_{ 0.5 };
};
SkipList::RandomGenerator SkipList::rand_;
// ==============================
/*
We do ***NOT*** store next[] array size,
***NOR*** we store NULL after last next node.
It turn out it does not need, because NULL lanes are already NULL.
Disadvantage is once allocated, no one knows the size,
except probably with malloc_usable_size();
[2]------------------------------->NULL
[1]------>[1]------>[1]----------->NULL
[0]->[0]->[0]->[0]->[0]->[0]->[0]->NULL
*/
struct SkipList::Node{
V data;
Node *next[1]; // system dependent, dynamic, at least 1
public:
// no need universal ref
Node(V &&data) : data(std::move(data)){}
private:
static size_t calcNewSize__(size_t const size, height_type const height){
return size + (height - 1) * sizeof(Node *);
}
public:
static void *operator new(size_t const size, height_type const height) {
return ::operator new(calcNewSize__(size, height));
}
static void *operator new(size_t const size, height_type const height, std::nothrow_t ) {
return ::operator new(calcNewSize__(size, height), std::nothrow);
}
};
// ==============================
struct SkipList::NodeLocator{
HeightArray<Node **> prev;
Node *node = nullptr;
};
// ==============================
SkipList::SkipList(height_type const height) :
height_(height){
assert( height > 0 && height <= MAX_HEIGHT );
zeroing_();
}
SkipList::SkipList(SkipList &&other):
height_ (std::move(other.height_ )),
heads_ (std::move(other.heads_ )),
dataCount_ (std::move(other.dataCount_ )){
other.zeroing_();
}
SkipList::~SkipList(){
clear();
}
bool SkipList::clear(){
for(const Node *node = heads_[0]; node; ){
const Node *copy = node;
node = node->next[0];
delete copy;
}
zeroing_();
return true;
}
bool SkipList::insert(V && newdata){
const auto &key = newdata;
const auto nl = locate_(key, true);
if (nl.node){
// update in place.
V & olddata = nl.node->data;
// copy assignment
olddata = std::move(newdata);
return true;
}
// create new node
height_type const height = getRandomHeight_();
Node *newnode = new(height, std::nothrow) Node(std::move(newdata));
if (newnode == nullptr){
// newdata will be magically destroyed.
return false;
}
/* SEE REMARK ABOUT NEXT[] SIZE AT THE TOP */
// newnode->height = height
// place new node where it belongs
for(height_type i = 0; i < height; ++i){
newnode->next[i] = *nl.prev[i];
*nl.prev[i] = newnode;
}
#ifdef DEBUG_PRINT_LANES
printf("%3u Lanes-> ", height);
for(height_type i = 0; i < height; ++i)
printf("%p ", (void *) newnode->next[i]);
printf("\n");
#endif
/* SEE REMARK ABOUT NEXT[] SIZE AT THE TOP */
// newnode->next[i] = NULL;
++dataCount_;
return true;
}
const V *SkipList::operator[](const K &key) const{
const Node *node = locateNode_(key, true);
return node ? & node->data : nullptr;
}
bool SkipList::erase(const K &key){
const auto nl = locate_(key, false);
if (nl.node == nullptr)
return true;
for(height_type h = 0; h < height_; ++h){
if (*nl.prev[h] == nl.node)
*nl.prev[h] = nl.node->next[h];
else
break;
}
const V & data = nl.node->data;
dataCount_--;
delete nl.node;
return true;
}
// ==============================
void SkipList::zeroing_(){
dataCount_ = 0;
std::fill(heads_.begin(), heads_.end(), nullptr);
}
auto SkipList::locate_(const K &key, bool const shortcut_evaluation) -> NodeLocator{
NodeLocator nl;
Node **jtable = heads_.data();
for(height_type h = height_; h --> 0;){
for(Node *node = jtable[h]; node; node = node->next[h]){
const V & data = node->data;
int const cmp = compare(data, key);
if (cmp >= 0){
if (cmp == 0 && (shortcut_evaluation || h == 0) ){
// found
nl.node = node;
if (shortcut_evaluation){
// at this point, we do not really care,
// if nl.prev is setup correctly.
return nl;
}
}
break;
}
jtable = node->next;
}
nl.prev[h] = & jtable[h];
}
return nl;
}
auto SkipList::locateNode_(const K &key, bool const exact) const -> const Node *{
const Node * const *jtable = heads_.data();
const Node *node = nullptr;
for(height_type h = height_; h --> 0;){
for(node = jtable[h]; node; node = node->next[h]){
const V & data = node->data;
int const cmp = compare(data, key);
if (cmp >= 0){
if (cmp == 0){
// found
return node;
}
break;
}
jtable = node->next;
}
}
return exact ? nullptr : node;
}
auto SkipList::getRandomHeight_() -> height_type{
// This gives slightly better performance,
// than divide by 3 or multply by 0.33
// We execute rand() inside the loop,
// but performance is fast enought.
height_type h = 1;
while( h < height_ && rand_() )
h++;
return h;
}
// ==============================
SkipList::Iterator &SkipList::Iterator::operator++(){
node_ = node_->next[0];
return *this;
}
const V &SkipList::Iterator::operator*() const{
assert(node_);
return node_->data;
}
// ==============================
// ==============================
// ==============================
#include <iostream>
inline void print(const char *val){
std::cout << val << '\n';
}
inline void println(){
print("-------------------");
}
inline void print(const V val){
std::cout << val << '\n';
}
inline void print(const V *val){
if (val)
print(*val);
else
print("_none_");
}
inline void print(const SkipList &list){
for(auto x : list)
print(x);
println();
}
constexpr V samples[] = { 100, 5, 22, 59, 35, 25, 8, 3 };
int main(){
SkipList list;
for(auto x : samples)
list.insert(std::move(x));
print(list);
print(list[22]);
print(list[999]);
println();
list.erase(22);
print(list[22]);
println();
print(list);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T05:39:31.797",
"Id": "383906",
"Score": "0",
"body": "Was this written by more than one person? `const` placement style seems very inconsistent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T07:41:2... | [
{
"body": "<p>Are you aware, that if you define the move constructor (as you did) that move-assignment is not default generated and copy assignment and copy construction are deleted, aka will give a compiler error?</p>\n\n<p>Also constexpr implies inline so you can skip that.</p>\n",
"comments": [
{
... | {
"AcceptedAnswerId": "199987",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-14T21:26:44.823",
"Id": "199515",
"Score": "3",
"Tags": [
"c++",
"c++11",
"skip-list"
],
"Title": "Skiplist implementation"
} | 199515 |
<p>I wrote a Network... thing (not really telnet); and it's pretty simple. No options, just straight I/O. It seems programs get so bloated easily.</p>
<pre><code>#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define BUFLEN 1024
sig_atomic_t run = 1;
sig_atomic_t sd = 1;
char e_socket_msg[] = "socket creation failed\n";
char e_sockopt_msg[] = "set socket non-block failed\n";
char e_parse_msg[] = "address parsing failed\n";
char e_timeout_msg[] = "connection attempt timed out\n";
char e_io_msg[] = "i/o error\n";
char e_generic_msg[] = "unknown or unexpected error\n";
char e_resolve_msg[] = "unable to resolve address\n";
typedef enum {
e_resolve = -1,
e_socket = -2,
e_sockopt = -3,
e_parse = -4,
e_timeout = -5,
e_io = -6
} Error;
void input(char *input, char *output, int len);
int resolve(char *host);
void sig_handler(int sig);
int connect_to(char *host, int port);
int transfer(int fd_in, char *buf, int buf_len, int fd_out);
int print_error(Error e);
int main(void) {
fd_set fds;
struct timeval tv;
int rv;
char buffer[BUFLEN];
char host[64], port[16];
char host_msg[] = "host:\t";
char port_msg[] = "port:\t";
input(host_msg, host, 64);
input(port_msg, port, 16);
sd = connect_to(host, atoi(port));
if (sd < 0) {
rv = resolve(host);
if (rv < 0) return print_error(rv);
sd = connect_to(host, atoi(port));
if (sd < 0) return print_error(sd);
}
signal(SIGINT, sig_handler);
signal(SIGPIPE, sig_handler);
FD_ZERO(&fds);
tv.tv_sec = 0;
tv.tv_usec = 300000;
while (run) {
FD_SET(sd, &fds);
FD_SET(STDIN_FILENO, &fds);
rv = select(sd + 1, &fds, NULL, NULL, &tv);
if (FD_ISSET(STDIN_FILENO, &fds))
rv = transfer(STDIN_FILENO, buffer, BUFLEN, sd);
else if (FD_ISSET(sd, &fds))
rv = transfer(sd, buffer, BUFLEN, STDOUT_FILENO);
if (rv != 0) {
run = 0;
if (rv > 0) print_error(e_io);
}
}
close(sd);
return 0;
}
void input(char *input, char *output, int len) {
int rv;
(void) write(STDOUT_FILENO, input, strlen(input));
rv = read(STDIN_FILENO, output, len - 1);
output[rv - 1] = '\0';
}
void sig_handler(int sig) {
run = 0;
close(sd);
}
int resolve(char *host) {
struct addrinfo hints, *servinfo;
struct in_addr addr;
char *addr_tmp;
int rv = 0;
memset(&hints, 0, sizeof hints);
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
rv = getaddrinfo(host, NULL, &hints, &servinfo);
if (rv) return print_error(e_resolve);
addr.s_addr = ((struct sockaddr_in*)servinfo->ai_addr)->sin_addr.s_addr;
addr_tmp = inet_ntoa(addr);
memset(host, 0, 64);
memcpy(host, addr_tmp, strlen(addr_tmp));
freeaddrinfo(servinfo);
return rv;
}
int connect_to(char *host, int port) {
int sd;
struct sockaddr_in addr;
fd_set sfds;
struct timeval tv;
sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd == -1) return e_socket;
if (fcntl(sd, F_SETFL, O_NONBLOCK) == -1) return e_sockopt;
memset(&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
if (inet_pton(AF_INET, host, &addr.sin_addr) != 1)
return e_parse;
addr.sin_port = htons(port);
connect(sd, (struct sockaddr *) &addr, sizeof (addr));
FD_ZERO(&sfds);
FD_SET(sd, &sfds);
tv.tv_sec = 4;
tv.tv_usec = 0;
if (select(sd + 1, NULL, &sfds, NULL, &tv)) return sd;
return e_timeout;
}
int transfer(int fd_in, char *buf, int buf_len, int fd_out) {
int len = read(fd_in, buf, buf_len);
return len > 0? len - write(fd_out, buf, len) : -1;
}
int print_error(Error e) {
char *msg;
switch (e) {
case e_socket:
msg = e_socket_msg;
break;
case e_sockopt:
msg = e_sockopt_msg;
break;
case e_parse:
msg = e_parse_msg;
break;
case e_timeout:
msg = e_timeout_msg;
break;
case e_io:
msg = e_io_msg;
break;
case e_resolve:
msg = e_resolve_msg;
break;
default:
msg = e_generic_msg;
break;
}
(void) write(STDERR_FILENO, msg, strlen(msg));
return -e;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T11:05:24.897",
"Id": "383926",
"Score": "1",
"body": "FWIW, some nitpicks: 1. using FULL_CAPS for C constant values (most people include enums here) seems to be the norm for readability, 2. prefer `e_socket_msg*` to `e_socket_msg[]`... | [
{
"body": "<ul>\n<li><p>There is no guarantee that <code>write</code> writes out the entire <code>buffer</code>. This means that</p>\n\n<pre><code>if (FD_ISSET(STDIN_FILENO, &fds))\n rv = transfer(STDIN_FILENO, buffer, BUFLEN, sd);\n</code></pre>\n\n<p>may lose data. Consider looping until all data gone ... | {
"AcceptedAnswerId": "199527",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T02:42:19.023",
"Id": "199524",
"Score": "7",
"Tags": [
"c",
"io",
"networking",
"socket",
"web-services"
],
"Title": "Network Interface Object"
} | 199524 |
<p><strong>Problem</strong></p>
<blockquote>
<p>Have the function <code>ChessboardTraveling(str)</code> read <code>str</code> which will be a
string consisting of the location of a space on a standard 8x8 chessboard with no pieces on the board along with another space on the
chessboard.</p>
<p>The structure of <code>str</code> will be the following:</p>
<p>\$(x,y)(a,b)\$ where \$(x, y)\$ represents the position you are
currently on with \$x\$ and \$y\$ ranging from 1 to 8 and \$(a, b)\$
represents some other space on the chessboard with \$a\$ and \$b\$
also ranging from 1 to 8 where \$a > x\$ and \$b > y\$. Your program
should determine how many ways there are of traveling from \$(x, y)\$
on the board to \$(a, b)\$ moving only up and to the right. </p>
<p><strong>Example</strong>: if <code>str</code> is \$(1,1)(2, 2)\$ then your program should output <code>2</code> because there are only two possible ways to travel from space
\$(1, 1)\$ on a chessboard to space \$(2, 2)\$ while making only moves
up and to the right.</p>
</blockquote>
<p>Are there any improvements I can make?</p>
<pre><code>#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
std::string delete_Punctuation(std::string& str)
{
std::string noPunctString = "";
str.insert(str.length()/2," ");
for (auto character : str)
{
if (!ispunct(character))
{
noPunctString.push_back(character);
}
}
return str = noPunctString;
}
bool check_If_PointXY_Is_Less_Than_PointAB(std::vector<int> v)
{
return (v.at(2) > v.at(0) && v.at(3) > v.at(1));
}
long long int find_Factorial(unsigned int n)
{
if (n == 0)
{
return 1;
}
return n * find_Factorial(n - 1);
}
int number_Of_Steps(std::string& str)
{
str = delete_Punctuation( str );
std::istringstream iss( str );
std::vector<int> coll((std::istream_iterator<int>( iss )),std::istream_iterator<int>());
int steps = 0;
if (check_If_PointXY_Is_Less_Than_PointAB(coll))
{
int xDistance = coll.at(2) - coll.at(0);
int yDistance = coll.at(3) - coll.at(1);
int totalDistance = xDistance + yDistance;
//combination formula
steps = find_Factorial(totalDistance)/(find_Factorial(xDistance) * (find_Factorial(totalDistance - xDistance)));
}
return steps;
}
</code></pre>
| [] | [
{
"body": "<h1>My Test Setup:</h1>\n\n<ul>\n<li>Microsoft Visual Studio 2017</li>\n<li>C++17</li>\n<li>Optimizations disabled</li>\n</ul>\n\n<h1>At a Glance</h1>\n\n<ol>\n<li><p><code>number_Of_Steps</code> should take a <strong><code>const</code></strong> <code>std::string&</code>. It is best practice to o... | {
"AcceptedAnswerId": "199563",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T06:17:51.517",
"Id": "199532",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"chess"
],
"Title": "Demonstration of ChessBoard Traveling (CoderByte)"
} | 199532 |
<p>GitLab saves files with the pattern <code>1530410429_2018_07_01_11.0.1_gitlab_backup.tar</code> (epoch, date, version, fixed string) to an S3 container.</p>
<p>I wanted to create a Python module to manage those backups, particularly to delete old backups, but preserving a specified number of files for each version).</p>
<p>To this end I:</p>
<ul>
<li>read S3 bucket contents and populate a list of dictionaries containing file name and an extracted version</li>
<li>extract a set of versions from the above list</li>
<li>iterate over each version and create a list of files to delete</li>
<li>iterate over the above result and delete the files from the bucket</li>
</ul>
<p>It works, but I feel the data structures I used are not appropriate and not pythonic.</p>
<p>How could I simplify the data structures and possibly minimize the number of function calls.</p>
<pre><code>import boto3
def get_set_of_versions(table_of_backups):
set_of_versions = set()
for backup in table_of_backups:
set_of_versions.add(backup['gitlab_version'])
return set_of_versions
def create_table_of_backups(list_of_backup_files):
table_of_backups = [
{
"s3_object_name": filename,
"gitlab_version": filename.split('_')[4]
} for filename in list_of_backup_files
]
return table_of_backups
def extract_list_of_backups(list_of_objects):
list_of_backups = [s3_object.key for s3_object in list_of_objects if 'gitlab_backup' in s3_object.key]
return list_of_backups
class GitlabBackups:
def __init__(self, bucket_name):
self.bucket_name = bucket_name
self.s3 = boto3.resource('s3')
self.bucket = self.s3.Bucket(bucket_name)
self.list_of_backup_files = extract_list_of_backups(self.bucket.objects.all())
self.table_of_backups = create_table_of_backups(self.list_of_backup_files)
self.set_of_versions = get_set_of_versions(self.table_of_backups)
def return_candidates_for_deletion_within_version(self, version, generations_to_keep=1):
if generations_to_keep == 0:
raise ValueError
list_of_versioned_backups = [
backup for backup in self.table_of_backups if backup['gitlab_version'] == version
]
return [backup['s3_object_name'] for backup in list_of_versioned_backups[:-generations_to_keep]]
def return_candidates_for_deletion(self, generations_to_keep=2):
resulting_list = list()
for version in self.set_of_versions:
resulting_list.extend(self.return_candidates_for_deletion_within_version(version, generations_to_keep))
return resulting_list
def delete_old_backups(self, generations_to_keep=2):
list_to_delete = self.return_candidates_for_deletion(generations_to_keep)
for key in list_to_delete:
self.s3.Object(self.bucket_name, key).delete()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T14:36:54.360",
"Id": "383934",
"Score": "0",
"body": "Out of scope, but you should also consider using S3's object lifecycles, which allow you to delete old objects automatically."
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<p>I think your function names could use some work. There is no need to specify that <code>return_candidates_for_deletion</code> actually returns those candidates (it is obvious). It is also a bit superfluous to know that <code>extract_list_of_backups</code> returns a <code>list</code>. It is enough ... | {
"AcceptedAnswerId": "199544",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T12:46:12.887",
"Id": "199540",
"Score": "6",
"Tags": [
"python",
"amazon-web-services"
],
"Title": "Select and delete objects from S3 container"
} | 199540 |
<p>For some time now, I've been working on a game which is superficially similar in appearance to <a href="https://dan-ball.jp/en/javagame/dust/" rel="noreferrer">this one</a>. A world is filled with particles that move and change state frequently (per frame, often). Drawing is achieved by finding the locations of particles within the camera's viewport, calculating lighting for the grid locations within the viewport, and then tinting a 1x1 white texture with the appropriate color, based on the particle and the lighting present in the particle's grid space:</p>
<pre><code>public void drawParticles(ParticleBoard particle_board) {
final int cam_min_x = camera.getCameraMinX();
final int cam_min_y = camera.getCameraMinY();
final int cam_max_x = camera.getCameraMaxX();
final int cam_max_y = camera.getCameraMaxY();
final float[][] light = light_manager.calculateLighting();
for (int y = cam_min_y; y < cam_max_y; y++) {
for (int x = cam_min_x; x < cam_max_x; x++) {
final float l = light[x - cam_min_x][y - cam_min_y];
if (l <= 0.05f) continue; // don't draw if it's too dark.
final Particle p = particle_board.getParticle(x, y);
if (p != null) {
final Color c = p.getProperty().getColor();
sprite_batch.setColor(new Color(c.r, c.g, c.b, l));
sprite_batch.draw(texture, x, y);
}
}
}
}
</code></pre>
<p>Light calculations are done within an array of floats the size of the current viewport. The approach is somewhat flood-fill-y, in that initial light values are placed at the 'top' of the array and then spread across the rest of the array, changing based on the presence of blocks:</p>
<pre><code>float[][] calculateLighting() {
final int cam_min_x = camera.getCameraMinX();
final int cam_min_y = camera.getCameraMinY();
final int cam_max_x = camera.getCameraMaxX();
final int cam_max_y = camera.getCameraMaxY();
final int light_width = cam_max_x - cam_min_x + 1;
final int light_height = cam_max_y - cam_min_y + 1;
final float[][] ambient_light = new float[light_width][light_height];
for (int y = light_height - 1; y >= 0; y--) {
for (int x = 0; x < light_width; x++) {
final float max = getMaxNeighboringLight(ambient_light, x, y, light_width, light_height);
if (particle_board.getParticle(x + cam_min_x, y + cam_min_y) != null) {
ambient_light[x][y] = max * 0.75f; // TODO: add constant to particle properties for transparency -- use that here.
} else {
ambient_light[x][y] = max;
}
}
}
return ambient_light;
}
</code></pre>
<p>Here's how the max neighboring light level is found:</p>
<pre><code>private float getMaxNeighboringLight(float[][] l, int x, int y, int light_width, int light_height) {
float left = 0f, right = 0f, top = 0f, bottom = 0f;
if (x == 0) {
left = 0f;
} else if (x == light_width - 1) {
right = 0f;
} else {
left = l[x - 1][y];
right = l[x + 1][y];
}
if (y == 0) {
bottom = 0f;
} else if (y == light_height - 1) {
top = 1f;
} else {
bottom = l[x][y - 1];
top = l[x][y + 1];
}
return Math.max(left, right, top, bottom);
}
</code></pre>
<p>Here's the result:
<a href="https://i.stack.imgur.com/NVOIK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NVOIK.png" alt="enter image description here"></a></p>
<p>It would be very interesting to hear suggestions as to how these approaches to rendering and lighting calculations could be improved. It seems rather inefficient to create a new lighting array each frame, but I'm not sure how I could do much better, since many of the particles shift around frequently. Similarly, it seems that drawing could be improved, but I lack the knowledge to do so. If any clarification would be useful, please let me know. The approach used to draw particles is based in part on the responses that I got from <a href="https://gamedev.stackexchange.com/questions/147636/efficiently-drawing-large-numbers-of-small-moving-squares-to-screen-in-libgdx">this question</a>.</p>
| [] | [
{
"body": "<p>From where I sit, this seems to be implemented backwards. You're iterating over every pixel in the viewport and checking to see if it has a particle, then doing something with the particle. It seems like it would be way more efficient to iterate over the particles and calculate the values needed f... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T15:16:21.270",
"Id": "199546",
"Score": "5",
"Tags": [
"java",
"graphics",
"libgdx"
],
"Title": "Drawing a grid-based particle system"
} | 199546 |
<p>I'm writing an application for capturing keyboard shortcuts on Linux, but I don't have a lot of experience with C or the Linux API, so I'm wondering about problems with the code or maybe parts that could be done better.</p>
<p>This is the code so far. I'm planning on adding other shortcuts in the future, not just for brightness.</p>
<p><strong>config.h</strong></p>
<pre><code>static const char *devname_video = "Video Bus";
static const char *devname_kb = "AT Translated Set 2 keyboard";
static const double percent_brightness = 10.0;
static const char *fname_brightness_max = "/sys/class/backlight/intel_backlight/max_brightness";
static const char *fname_brightness_now = "/sys/class/backlight/intel_backlight/brightness";
</code></pre>
<p><strong>ksd.c</strong></p>
<pre><code>#define _GNU_SOURCE
#include <dirent.h>
#include <fcntl.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "config.h"
/* Common. */
static const char *app_name = "ksd";
static void cleanup(void);
static int stop = 0;
static void handle_interrupt() {
stop = 1;
}
/**
* Prints a failure message and exits with a failure status.
*/
static void fail(const char *format, ...) {
char buffer[4096];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
fprintf(stderr, "%s: %s", app_name, buffer);
cleanup();
exit(EXIT_FAILURE);
}
/* Devices. */
static char fname_video[255];
static char fname_kb[255];
static const int fname_n = 2;
/**
* Returns true if the name of a directory file represents an event device.
*/
static int is_evdev(const struct dirent *dir) {
return strncmp("event", dir->d_name, 5) == 0;
}
/**
* Scans input event device files and stores supported device file names.
*/
static void scan_devices(void) {
int res;
struct dirent **fnames;
const int n = scandir("/dev/input", &fnames, is_evdev, versionsort);
if (n < 0) {
fail("could not list /dev/input: %d\n", n);
}
const int devname_video_l = strlen(devname_video);
const int devname_kb_l = strlen(devname_kb);
int found = 0;
for (int i = 0; i < n && found < fname_n; ++i) {
char path[11 /* prefix */ + 256 /* d_name */];
snprintf(path, sizeof(path), "/dev/input/%s", fnames[i]->d_name);
const int fd = open(path, O_RDONLY);
if (fd < 0) {
fail("could not open %s for reading: %d\n", path, fd);
}
char devname[256] = {0};
if ((res = ioctl(fd, EVIOCGNAME(sizeof(devname)), devname)) < 0) {
close(fd);
fail("could not read device name for %s: %d\n", path, res);
}
close(fd);
if (strncmp(devname, devname_video, devname_video_l) == 0) {
memcpy(fname_video, path, strlen(path));
++found;
} else if (strncmp(devname, devname_kb, devname_kb_l) == 0) {
memcpy(fname_kb, path, strlen(path));
++found;
}
}
if (found < fname_n) {
fail("could not find all devices");
}
}
/* Virtual keyboard. */
static const char *vk_name = "Virtual Keyboard";
static int fd_vk;
/**
* Specifies which events the virtual keyboard should support.
*/
static void set_vk_evbits(void) {
if (ioctl(fd_vk, UI_SET_EVBIT, EV_KEY) < 0) {
fail("could not set EV_KEY bit on virtual keyboard\n");
}
if (ioctl(fd_vk, UI_SET_EVBIT, EV_SYN) < 0) {
fail("could not set EV_SYN bit on virtual keyboard\n");
}
}
/**
* Specifies which key codes the virtual keyboard should support.
*/
static void set_vk_keybits(void) {
int res;
for (int i = 0; i < KEY_MAX; ++i) {
if ((res = ioctl(fd_vk, UI_SET_KEYBIT, i)) < 0) {
fail("could not set key bit %d on virtual keyboard device: %d\n",
i, res);
}
}
}
/**
* Creates a virtual keyboard device.
*/
static void create_vk(void) {
int res;
fd_vk = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (fd_vk < 0) {
fail("could not initialize virtual keyboard\n");
}
set_vk_evbits();
set_vk_keybits();
struct uinput_user_dev dev;
memset(&dev, 0, sizeof(dev));
snprintf(dev.name, UINPUT_MAX_NAME_SIZE, vk_name);
dev.id.bustype = BUS_USB;
dev.id.vendor = 1;
dev.id.product = 1;
dev.id.version = 1;
if ((res = write(fd_vk, &dev, sizeof(dev)) < 0)) {
fail("could not write virtual keyboard data: %d\n", res);
}
if ((res = ioctl(fd_vk, UI_DEV_CREATE)) < 0) {
fail("could create virtual keyboard: %d\n", res);
}
}
/**
* Destroys the virtual keyboard and closes the file descriptor.
*/
static void destroy_vk(void) {
if (fd_vk <= 0) {
return;
}
int res;
if ((res = ioctl(fd_vk, UI_DEV_DESTROY)) < 0) {
close(fd_vk);
fail("could not destroy virtual keyboard: %d\n", res);
}
close(fd_vk);
}
/* Devices. */
static int fd_video;
static int fd_kb;
/**
* Opens and captures devices.
*/
static void capture_devices(void) {
int res;
if ((fd_video = open(fname_video, O_RDONLY)) < 0) {
fail("could not open video device %s for reading: %d\n",
fname_video, fd_video);
}
if ((res = ioctl(fd_video, EVIOCGRAB, 1)) < 0) {
fail("could not capture video device %s: %d\n", fname_video, res);
}
if ((fd_kb = open(fname_kb, O_RDONLY)) < 0) {
fail("could not open keyboard device %s for reading: %d\n",
fname_kb, fd_kb);
}
if ((res = ioctl(fd_kb, EVIOCGRAB, 1)) < 0) {
fail("could not capture keyboard device %s: %d\n", fname_kb, res);
}
}
/**
* Releases captured devices.
*/
static void release_devices(void) {
if (fd_video > 0) {
ioctl(fd_video, EVIOCGRAB, 0);
close(fd_video);
}
if (fd_kb > 0) {
ioctl(fd_video, EVIOCGRAB, 0);
close(fd_kb);
}
}
/* Events. */
static struct input_event ev;
static const int ev_size = sizeof(struct input_event);
/* Screen brightness events. */
static int brightness_max;
static int brightness_step;
#define BRIGHTNESS_VAL_MAX 10
/**
* Reads the brightness value from a file.
*/
static int read_brightness(const char *fname) {
const int fd = open(fname, O_RDONLY);
if (fd < 0) {
fail("could not open brightness device %s: %d", fname, fd);
}
char value[BRIGHTNESS_VAL_MAX];
const ssize_t bytes = read(fd, &value, sizeof(value));
close(fd);
if (bytes == 0) {
fail("could not read brightness device %s", fname);
}
const int value_parsed = atoi(value);
if (value_parsed == 0) {
fail("could not parse brightness value \"%s\" from %s", value, fname);
}
return value_parsed;
}
/**
* Returns the maximum screen brightness.
*/
static int get_brightness_max(void) {
if (brightness_max == 0) {
brightness_max = read_brightness(fname_brightness_max);
}
return brightness_max;
}
/**
* Returns the current screen brightness.
*/
static int get_brightness_now(void) {
return read_brightness(fname_brightness_now);
}
/**
* Returns the amount with which the brightness needs to be increased or
* decreased.
*/
static int get_brightness_step(void) {
if (brightness_step == 0) {
brightness_step = percent_brightness / 100.0 * get_brightness_max();
}
return brightness_step;
}
/**
* Sets the specified screen brightness.
*/
static void write_brightness(int value) {
const int fd = open(fname_brightness_now, O_WRONLY);
if (fd < 0) {
fail("could not open brightness file %s for writing: %d",
fname_brightness_now, fd);
}
char value_s[BRIGHTNESS_VAL_MAX];
snprintf(value_s, sizeof(value_s), "%d", value);
write(fd, &value_s, strlen(value_s));
close(fd);
}
/**
* Tries to handle a screen brightness event and returns true if the event was
* handled.
*/
static bool handle_brightness_event(void) {
const int now = get_brightness_now();
const int step = get_brightness_step();
int value;
switch (ev.code) {
case KEY_BRIGHTNESSDOWN:
value = now - step;
if (value < 10) {
value = 10;
}
break;
case KEY_BRIGHTNESSUP:
value = now + step;
const int max = get_brightness_max();
if (value > max) {
value = max;
}
break;
default:
return false;
}
if (value == now) {
return true;
}
write_brightness(value);
return true;
}
/* Main event handling. */
static bool is_ctrl_down = false;
/**
* Returns true if the current event is a Control key event.
*/
static bool is_ctrl_key(void) {
return (
ev.type == EV_KEY &&
(ev.code == KEY_LEFTCTRL || ev.code == KEY_RIGHTCTRL)
);
}
/**
* Tries to handle a keyboard event and returns true if the event was handled.
*/
static bool handle_kb_event(void) {
if (is_ctrl_key()) {
is_ctrl_down = ev.value > 0;
}
if (is_ctrl_down && ev.code == KEY_C && ev.value > 0) {
stop = 1;
}
return false;
}
/**
* Tries to handle a video event and returns true if the event was handled.
*/
static bool handle_video_event(void) {
if (ev.value == 0) {
return true;
}
switch (ev.code) {
case KEY_BRIGHTNESSDOWN:
case KEY_BRIGHTNESSUP:
return handle_brightness_event();
}
return false;
}
/**
* Reads then tries to handle the next event from the supported devices, and
* returns true if the event was handled.
*/
static bool handle_event(void) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd_video, &fds);
FD_SET(fd_kb, &fds);
int fd_max = fd_video;
if (fd_kb > fd_max) {
fd_max = fd_kb;
}
select(fd_max + 1, &fds, NULL, NULL, NULL);
if (stop) {
cleanup();
exit(EXIT_SUCCESS);
}
ssize_t bytes;
#define CHECK_BYTES(b) \
if ((b) < 0) { \
fail("expected to read %d bytes, got %ld\n", ev_size, (long) bytes); \
}
if (FD_ISSET(fd_video, &fds)) {
CHECK_BYTES(bytes = read(fd_video, &ev, ev_size));
return handle_video_event();
} else if (FD_ISSET(fd_kb, &fds)) {
CHECK_BYTES(bytes = read(fd_kb, &ev, ev_size));
return handle_kb_event();
} else {
fail("expected file descriptor to be set\n");
}
return false;
}
/**
* Forwards the current event to the virtual keyboard.
*/
static void forward_event(void) {
int res;
if ((res = write(fd_vk, &ev, ev_size)) < 0) {
fail("could not forward event to virtual keyboard: %d\n", res);
}
}
/* Cleanup. */
static void cleanup(void) {
destroy_vk();
release_devices();
}
/* Cache. */
static void cache(void) {
get_brightness_max();
get_brightness_step();
}
int main(void) {
scan_devices();
create_vk();
capture_devices();
cache();
signal(SIGINT, handle_interrupt);
signal(SIGTERM, handle_interrupt);
while (!stop) {
if (!handle_event()) {
forward_event();
}
}
cleanup();
return EXIT_SUCCESS;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T03:53:00.530",
"Id": "384150",
"Score": "1",
"body": "For the `handle_kb_event()` function, it says it returns true if the event was handled, but I do not see where. For functions like `fail()`, which unconditionally exit the progra... | [
{
"body": "<blockquote>\n <p>I'm wondering about problems with the code or maybe parts that could be done better.</p>\n</blockquote>\n\n<p>Just a small review.</p>\n\n<p><strong>Avoid magic numbers</strong></p>\n\n<p><code>fnames[i]->d_name</code> points to a string of a length not exceeding <a href=\"https... | {
"AcceptedAnswerId": "199645",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T15:20:36.797",
"Id": "199547",
"Score": "5",
"Tags": [
"c",
"linux"
],
"Title": "C application for capturing keyboard shortcuts"
} | 199547 |
<p>For some time I am trying to make a mocking library for C# that mocks objects with just 1 line of code. I am using abstract factory pattern to know what is the object's type so that I can work with concrete factories.</p>
<p>I have the following Abstract factory class which I am not very happy with. </p>
<pre><code>public class MockContext<T>
{
public T CreateMockObject()
{
IFactory<T> factory = null;
if (typeof(T).IsPrimitive || typeof(T) == typeof(string) || typeof(T) == typeof(decimal))
{
factory = new PrimitiveFactory<T>();
}
else if (typeof(T).IsArray)
{
factory = new ArrayFactory<T>();
}
else if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
{
factory = new CollectionFactory<T>();
}
else if (typeof(T).IsClass && typeof(T) != typeof(string))
{
factory = new ClassFactory<T>();
}
return factory.Create();
}
}
}
</code></pre>
<p>Which gets called by the following class</p>
<pre><code> public class Mocker
{
public T MockObject<T>()
{
MockContext<T> context = new MockContext<T>();
T mockObject = context.CreateMockObject();
return mockObject;
}
}
</code></pre>
<p>This abstract factory instantiates other factories depending on of the object.</p>
<p>Here is my class factory:</p>
<pre><code> public class ClassFactory<T> : IFactory<T>
{
public T Create()
{
T mockObject = (T)Activator.CreateInstance(typeof(T));
IEnumerable<PropertyInfo> properties = typeof(T).GetProperties().Where(p => p.CanWrite);
GenericMethodInvokerUtil method = new GenericMethodInvokerUtil();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(T))
throw new Exception("Circular properties are not supported!");
method.InvokeMockObject<T>(property.PropertyType, property, mockObject);
}
return mockObject;
}
}
</code></pre>
<p>Here is my Primitive factory:</p>
<pre><code> public class PrimitiveFactory<T> : IFactory<T>
{
private readonly Dictionary<Type, IPrimitiveFactory<T>> _primitiveFactories = new Dictionary<Type, IPrimitiveFactory<T>>()
{
{ typeof(string), new StringFactory() as IPrimitiveFactory<T> },
{ typeof(bool), new BooleanFactory() as IPrimitiveFactory<T> },
{ typeof(byte), new ByteFactory() as IPrimitiveFactory<T> },
{ typeof(sbyte), new SbyteFactory() as IPrimitiveFactory<T> },
{ typeof(char), new CharFactory() as IPrimitiveFactory<T> },
{ typeof(decimal), new DecimalFactory() as IPrimitiveFactory<T> },
{ typeof(double), new DoubleFactory() as IPrimitiveFactory<T> },
{ typeof(float), new FloatFactory() as IPrimitiveFactory<T> },
{ typeof(int), new IntFactory() as IPrimitiveFactory<T> },
{ typeof(uint), new UintFactory() as IPrimitiveFactory<T> },
{ typeof(long), new LongFactory() as IPrimitiveFactory<T> },
{ typeof(ulong), new UlongFactory() as IPrimitiveFactory<T> },
{ typeof(short), new ShortFactory() as IPrimitiveFactory<T> },
{ typeof(ushort), new UshortFactory() as IPrimitiveFactory<T> },
{ typeof(object), new ObjectFactory() as IPrimitiveFactory<T> },
};
public T Create()
{
if (_primitiveFactories.ContainsKey(typeof(T)))
{
IPrimitiveFactory<T> primitiveFactory = _primitiveFactories[typeof(T)];
return primitiveFactory.Create();
}
throw new KeyNotFoundException($"The key of type: {typeof(T)} is not found.");
}
}
</code></pre>
<p>All primitive types has their own factories which is determined by the type of the object.</p>
<p>Array factory:</p>
<pre><code>public class ArrayFactory<T> : IFactory<T>
{
public T Create()
{
var genericMethodInvoker = new GenericMethodInvokerUtil();
Array array = Activator.CreateInstance(typeof(T), new object[] { RandomUtil.Instance.Next(1, 100) }) as Array;
for (int i = 0; i < array.Length; i++)
{
Type arrayElementType = typeof(T).GetElementType();
array.SetValue(genericMethodInvoker.InvokeMockObject<T>(arrayElementType), i);
}
return (T)Convert.ChangeType(array, typeof(T));
}
}
</code></pre>
<p>Collection factory</p>
<pre><code> public class CollectionFactory<T> : IFactory<T>
{
public T Create()
{
ICollectionFactory<T> factory = null;
if (typeof(IDictionary).IsAssignableFrom(typeof(T)))
{
factory = new DictionaryFactory<T>() as ICollectionFactory<T>;
}
else if (typeof(IList).IsAssignableFrom(typeof(T)))
{
factory = new ListFactory<T>() as ICollectionFactory<T>;
}
return factory.Create();
}
}
</code></pre>
<p>Collections are on the other hand are separated in tow Dictionary and List</p>
<pre><code>public class DictionaryFactory<T> : ICollectionFactory<T>
{
public T Create()
{
GenericMethodInvokerUtil methodInvoker = new GenericMethodInvokerUtil();
IDictionary dictionary = (IDictionary)Activator.CreateInstance(typeof(T));
int numberOfElements = RandomUtil.Instance.Next(1, 100);
Type[] arguments = dictionary.GetType().GetGenericArguments();
Type keyType = arguments[0];
Type valueType = arguments[1];
for (int i = 0; i < numberOfElements; i++)
{
object key = methodInvoker.InvokeMockObject<object>(keyType);
object value = methodInvoker.InvokeMockObject<object>(valueType);
if (!dictionary.Contains(key))
{
dictionary.Add(key, value);
}
}
return (T)dictionary;
}
}
</code></pre>
<p>And List factory</p>
<pre><code>public class ListFactory<T> : ICollectionFactory<T>
{
public T Create()
{
GenericMethodInvokerUtil methodInvoker = new GenericMethodInvokerUtil();
IList list = (IList)Activator.CreateInstance(typeof(T));
int numberOfElements = RandomUtil.Instance.Next(1, 100);
Type valueType = list.GetType().GetGenericArguments()[0];
for (int i = 0; i < numberOfElements; i++)
{
object value = methodInvoker.InvokeMockObject<object>(valueType);
list.Add(value);
}
return (T)list;
}
}
</code></pre>
<p>I am using the above code as follows:</p>
<pre><code> static void Main(string[] args)
{
Mocker mocker = new Mocker();
var mock = mocker.MockObject<Test>();
}
</code></pre>
<p>With Test being some class with properties.</p>
<p>Mock object gets called recursively from the following utility class:</p>
<pre><code> public class GenericMethodInvokerUtil
{
public object InvokeMockObject<T>(Type type, PropertyInfo property, object currentObject)
{
object concreteResult = GetMockObjectResult(type);
property.SetValue(currentObject, concreteResult);
return currentObject;
}
public object InvokeMockObject<T>(Type type)
{
object concreteResult = GetMockObjectResult(type);
return concreteResult;
}
private object GetMockObjectResult(Type type)
{
MethodInfo method = typeof(Mocker).GetMethod("MockObject", new Type[0] { });
MethodInfo generic = method.MakeGenericMethod(type);
object instance = Activator.CreateInstance(typeof(Mocker));
object result = generic.Invoke(instance, null);
object concreteResult = Convert.ChangeType(result, type);
return concreteResult;
}
}
</code></pre>
<p>Can anyone suggest how to write this better?</p>
<p>Maybe there is a pattern that I am not familiar with.
Any help would be appreciated.</p>
<p>You can find the complete source of the project in my github <a href="https://github.com/hasan-hasanov/AutoMocker" rel="nofollow noreferrer">HERE</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T17:13:33.190",
"Id": "383949",
"Score": "2",
"body": "This method is obviously a part of something bigger... could please add the rest of the picture too? It's hard to say anything seeing only this. A usage example would also be ver... | [
{
"body": "<p>Here're a couple of issues that struck me most...</p>\n\n<hr>\n\n<p>Instead of writing lengthy <code>if/else if/else</code> trees you should use early returns with simple <code>if</code>s. This will make your code cleaner and allow you put a nice <code>throw</code> at the end in case an unsupporte... | {
"AcceptedAnswerId": "199610",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T17:06:40.137",
"Id": "199552",
"Score": "0",
"Tags": [
"c#",
".net",
"abstract-factory",
".net-core"
],
"Title": "Mocking objects using abstract factory"
} | 199552 |
<p><strong>Question</strong> (<a href="https://www.codechef.com/problems/SADQ" rel="nofollow noreferrer">SAD Queries</a> on CodeChef)</p>
<blockquote>
<p>The Summed Absolute Difference (SAD) of two arrays. Given arrays
(1-indexed) \$P\$ and \$Q\$ of lengths \$p\$ and \$q\$.</p>
<p>Given a collection of \$n\$ arrays \$A_1, \ldots, A_n\$, report \$SAD(A_i, A_j)\$ for
several queries \$(i, j)\$.</p>
<p>The first line of input contains a single positive integer \$n\$.</p>
<p>Each of the next \$n\$ lines starts with a positive integer \$s_i\$, the size
of \$A_i\$, </p>
<p>followed by \$s_i\$ space-separated integers \$A_{i,1}, \ldots, A_{i,s_i}\$ which denotes
the array \$A_i\$. The next line of input consists of a single positive
integer \$M\$.</p>
<p>Each of the next \$M\$ lines consists of 2 positive integers \$a\$ and \$b\$ which lie<br>
between \$1\$ and \$n\$ (inclusive), specifying the indices of the arrays for
which the SAD value must be reported.</p>
</blockquote>
<p><strong>Example</strong></p>
<blockquote>
<p>Input: </p>
<pre><code>4
4 0 3 1 -2
2 0 4
2 2 4
4 4 -3 -4 4
3
3 4
4 2
1 4
</code></pre>
<p>Output:</p>
<pre><code>30
30
60
</code></pre>
</blockquote>
<p><strong>Explanation</strong></p>
<blockquote>
<p>Query 1: The arrays in question are A3 = [2, 4] and A4 = [4, -3, -4,
4].</p>
<p>$$SAD(A3, A4)$$
$$= |2 - 4| + | 2 - (-3) | + |2 - (-4) | + | 2 - 4 |$$
$$+ | 4 - 4 | + | 4 - (-3) | + | 4 - (-4) | + | 4 - 4 |$$
$$= 2 + 5 + 6 + 2 + 0 + 7 + 8 + 0$$
$$= 30$$</p>
</blockquote>
<p><strong>Constraints</strong></p>
<p>\$1 \leq n, M \leq 10^5\$</p>
<p>\$1 \leq s_1 + ... + s_n \leq 10^5\$ </p>
<p>\$-10^9 \leq A_{i,j} \leq 10^9\$ </p>
<p>\$1 \leq i, j \leq n\$ in each of the queries </p>
<p><strong>My approach</strong> </p>
<pre><code>#include <iostream>
#include<cmath>
using namespace std;
int main()
{
long long int n,x,a,b,sum=0,s=1;
cin>>n;
long long int *size=new long long int[n];
long long int **arr=new long long int*[n];
for(int i=1;i<=n;i++)
{
arr[i]=new long long int[n];
}
for(int i=1;i<=n;i++)
{
cin>>size[s];
for(int j=0;j<size[s];j++)
{
cin>>arr[i][j];
}
s++;
}
long long int m;
cin>>m;
while(m--)
{
cin>>a>>b;
for(int i=1;i<=size[a];i++)
{
for(int j=0;j<size[b];j++)
sum=sum+fabs(arr[a][i]-arr[b][j]);
}
cout<<sum;
cout<<endl;
sum=0;
}
return 0;
}
</code></pre>
<p>How can i reduce the time complexity and space complexity of this program.</p>
<p>I have taken a 1D dynamic array to store the size of arrays and a 2D dynamic array to store the index and the array value for that index</p>
| [] | [
{
"body": "<ul>\n<li><p><strong>Algorithm</strong>.</p>\n\n<p>Thou shalt not brute force.</p>\n\n<p>When computing \\$SAD(P, q_i)\\$ you may notice that is bound be rewritten as \\$SAD(P', q_i) + SAD(P'', q_i)\\$, where \\$P'\\$ consists of values less than \\$q_i\\$, and \\$P''\\$ consists of values greater th... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-15T19:58:01.343",
"Id": "199558",
"Score": "5",
"Tags": [
"c++",
"array",
"time-limit-exceeded"
],
"Title": "Summed absolute difference of two array"
} | 199558 |
<p>I am using the <a href="https://github.com/request/request" rel="nofollow noreferrer">request</a> module and wanted to implement some retries for robustness. It seems excessive to use a whole new or extra module just to do a retries so I've put together the following as an exercise to retry requests using only the <code>request</code> library:</p>
<pre><code>var checkUrl = function(url = 'http://localhost', retriesLeft = 0, timeoutMS = 3000) {
var request = require('request');
request(url, async function (error, response, body) {
if (error) {
if (retriesLeft > 0) {
console.log(url + ' : not available yet');
await sleep(timeoutMS);
checkUrl(url, --retriesLeft);
}
} else {
console.log(url + ' : URL is available');
}
});
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
checkUrl('http://www.example.com/', 3, 5000);
</code></pre>
<p>Is this a reasonable approach? It seems to work. It's just a basic example - I've not considered redirects for instance.</p>
<p>Of course this can be wrapped up to make it easier to use and then, ironically, becomes a sort of module but it would not require pulling anything external.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T06:10:48.453",
"Id": "384005",
"Score": "0",
"body": "It's not excessive to use a pre-made module that does what you want. In fact, if it's solid code, then it's smart to use something that's already written and tested and maintain... | [
{
"body": "<p>It's not \"excessive\" (your term) to use a pre-made module that does what you want. In fact, if it's solid code, then it's smart to use something that's already written and tested and maintained by someone else. There's little cost on a server to using a small module that does what you want.</p>\... | {
"AcceptedAnswerId": "199633",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T05:50:16.670",
"Id": "199568",
"Score": "1",
"Tags": [
"javascript",
"promise"
],
"Title": "Retrying a request using 'request' library without extra modules"
} | 199568 |
<p>I recently failed to finish a code for a job interview. One of the problems is that I decided to use Pandas (it made sense) but I was unfamiliar with it (however I know Python Scipy and Numpy), so it took a lot of time to figure out everything. It's the first time I wrote such kind of code manipulating Pandas data frames, thus I was wondering if you could give me advice to do things better.</p>
<p>The purpose of the code was to read a CSV table of trading data (for a finance company) and then manipulating the data in order to find certain properties. I did not finish it, but do you think I could have done something that make it run faster? it took 43 minutes to do just what it does now. The .csv file is a 1.2GB file.</p>
<p>Moreover, if you have any observation about style it is more than welcome.</p>
<pre><code>import numpy as np
import pandas as pd
import csv
import time
import matplotlib.pyplot as plt
chunk_size = 10**5 #safe on memory
auction_division = 40000.0 #empirical
path = 'scandi.csv'
col_names = ['id','empty0','bid_price','ask_price','trade_price',\
'bid_volume','ask_volume','trade_volume','update',\
'empty1','date','seconds','opening','empty2','con_codes']
col_names_load = ['id','bid_price','ask_price','trade_price',\
'trade_volume','update','date','seconds','con_codes']
start = time.time()
total=0
stocks=set()
days=set()
sub_chunks = []
for i,chunk in enumerate(pd.read_csv(path, sep=',,|,',names=col_names, usecols=\
['id','bid_price','ask_price','date','seconds'],\
engine='python', chunksize=chunk_size)):
ids_unique = set(chunk.id.unique().tolist())
day_unique = set(chunk.date.unique().tolist())
stocks|=ids_unique
days|=day_unique
auction_data = chunk[chunk['bid_price']>chunk['ask_price']]
new_el = auction_data[['date','seconds']]
sub_chunks.append(new_el)
days_list = list(days)
auction = pd.concat(sub_chunks)
au_bound = []
stocky=list(stocks)
for day in days_list:
g=auction[auction['date']==day]
slot1=g[g['seconds']<auction_division].seconds
slot2=g[g['seconds']>auction_division].seconds
au_bound.append((slot1.min(),slot1.max(),slot2.min(),slot2.max()))
the_last_element = pd.DataFrame(np.zeros((7, len(stocks))), columns=stocky)
#rows: 0: bid price, 1: ask price, 2: trade price, 3: trade volumes, 4: date, 5: seconds, 6: flag
for i,chunk in enumerate(pd.read_csv(path, sep=',,|,', names=col_names,
usecols = col_names_load, engine='python', chunksize=chunk_size)):
print i+1, 'th chunk'
#I select just trade updates because ticks and bid-ask spreads make sense at the trade (that's what I think to have learnt from investopedia)
#Tick: https://www.investopedia.com/terms/t/tick.asp
#Bid-Ask Spread: https://www.investopedia.com/terms/b/bid-askspread.asp
chunk_clean = chunk[ chunk['update']==1 & ((chunk.con_codes=='@1') \
| (chunk.con_codes=='XT') | (chunk.con_codes=='XT|C') | (chunk.con_codes=='XT|O') ) ]
stocky_b = set(chunk.id.unique().tolist())
for stock in stocky_b:
for day, ab in zip( days, au_bound ):
stock_chunk=chunk_clean[(chunk_clean['id']==stock) & (chunk_clean['date']==day)]
#time between trades subtraction
stock_chunk.loc[:,'t_b_trades']=stock_chunk['seconds']-stock_chunk['seconds'].shift(1)
#eliminate trades that cross auctions
stock_chunk.loc[stock_chunk[
( (stock_chunk['seconds'] > ab[0]) & (stock_chunk['seconds'] < ab[1] ) )\
| ( (stock_chunk['seconds'] > ab[2]) & (stock_chunk['seconds'] < ab[3] ) )\
| ( (stock_chunk['seconds'].shift(1) > ab[0]) & (stock_chunk['seconds'].shift(1) < ab[1]) )\
| ( (stock_chunk['seconds'].shift(1) > ab[2]) & (stock_chunk['seconds'].shift(1) < ab[3]) )\
| ( (stock_chunk['seconds'].shift(1) < ab[0]) & (stock_chunk['seconds'] > ab[1] ) )\
| ( (stock_chunk['seconds'].shift(1) < ab[2]) & (stock_chunk['seconds'] > ab[3] ) )\
].index.values,'t_b_trades'] = np.nan
#the first row is always wrong
if (the_last_element[stock][6]==1 and the_last_element[stock][4]==day):
if stock_chunk.empty==False:
stock_chunk.loc[stock_chunk[stock_chunk['seconds']==stock_chunk.seconds.iloc[0]].index.values,'t_b_trades'] \
= stock_chunk.seconds.iloc[0]-the_last_element[stock][5]
#eliminate trades that cross auctions
if ( ( (stock_chunk.seconds.iloc[0] >ab[0] ) & (stock_chunk.seconds.iloc[0]< ab[1])) \
| ( (stock_chunk.seconds.iloc[0] >ab[2] ) & (stock_chunk.seconds.iloc[0]< ab[3])) \
| ( (the_last_element[stock][5] > ab[0] ) & (the_last_element[stock][5] < ab[1])) \
| ( (the_last_element[stock][5] > ab[2] ) & (the_last_element[stock][5] < ab[3])) \
| ( (the_last_element[stock][5] < ab[0] ) & (stock_chunk.seconds.iloc[0]> ab[1])) \
| ( (the_last_element[stock][5] < ab[2] ) & (stock_chunk.seconds.iloc[0]> ab[3]))):
stock_chunk.loc[stock_chunk[stock_chunk['seconds'] == stock_chunk.seconds.iloc[0]].index.values,'t_b_trades'] = np.nan
else:
if stock_chunk.empty==False:
stock_chunk.loc[stock_chunk[stock_chunk['seconds']==stock_chunk.seconds.iloc[0]].index.values,'t_b_trades'] = np.nan
#fill the last row for the next chunk
if stock_chunk.empty==False:
the_last_element[stock][0]=stock_chunk.bid_price.iloc[-1]
the_last_element[stock][1]=stock_chunk.ask_price.iloc[-1]
the_last_element[stock][2]=stock_chunk.trade_price.iloc[-1]
the_last_element[stock][3]=stock_chunk.trade_volume.iloc[-1]
the_last_element[stock][4]=stock_chunk.date.iloc[-1]
the_last_element[stock][5]=stock_chunk.seconds.iloc[-1]
the_last_element[stock][6]=1
end = time.time()
tot_time = (end-start)/60.0
print tot_time, 'minutes for data! for', total, 'chunks of size', chunk_size
</code></pre>
<p>Here the first 3 lines of the input file</p>
<pre><code>ID,Underlying Type,Underlying,Risk-Free Rate,Days To Expiry,Strike,Option Type,Model Type,Market Price
0,Future,1.9119,-0.0009,19.3599,2.0264,Call,Bachelier,0.096576518
1,Future,0.8731,-0.0025,278.2703,1.0610,Call,Bachelier,0.40362827
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T06:31:02.410",
"Id": "384006",
"Score": "1",
"body": "Does it work as intended? What does the input and output data look like? Can you post examples of both?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-... | [
{
"body": "<p>A few tips that might help you:</p>\n\n<ul>\n<li>Good job declaring your global variables at the top of the file. Convention is to capitalize them.</li>\n<li>Posting some example data here (even just a row or two) would help greatly.</li>\n<li>To get the unique lists of ids and days, I don't belie... | {
"AcceptedAnswerId": "210846",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T06:29:53.823",
"Id": "199569",
"Score": "0",
"Tags": [
"python",
"pandas"
],
"Title": "Manipulating DataFrames on pandas"
} | 199569 |
<p>I was trying to build a small utility function to check if an array is part of other array. It's testing if an array is a subset of another master array.</p>
<pre><code>const masterArray = [1,2,3,4,5,6];
const candidateArray = [2,5,6];
//Test for subset.
//create a set from the two.
const s1 = new Set(masterArray.concat(candidateArray));
//Compare the sizes of the master array and the created set
//If the sizes are same, no new elements are added that means
//the candidate is complete subset.
s1.size === masterArray.length;
</code></pre>
<p>Can this be handled in a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T07:15:17.733",
"Id": "384007",
"Score": "2",
"body": "Wouldn't that fail if `masterArray` has duplicate elements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T07:22:34.893",
"Id": "384009",
... | [
{
"body": "<p>So the key here is that I value code that's obvious to others.</p>\n\n<p>Someone else <em>is</em> likely to try to stuff duplicate elements in unless it requires a type refactor; making <code>const masterSet: Set<number></code> and using that throughout the code is a Good Idea. That \"someon... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T06:50:21.667",
"Id": "199570",
"Score": "3",
"Tags": [
"array",
"typescript",
"set"
],
"Title": "Test for an array being subset of another master array"
} | 199570 |
<p>I'm testing the influence of the time period on the end result of my calculations. To do this, I'm using a <code>for</code> loop, that is detailed below. In the current state of affairs, this code works well, but it takes more than 10 minutes to go through my complete data set. I believe the use of apply instead of a loop could speed up the process, but I can't work out how to do this. Some assistance would be more than welcome.</p>
<pre><code> ## result vector
HLClist<-vector()
Ts=3600
for(i in 1:length(TimeSpan[,1])){
StartTime=TimeSpan[i,]
EndTime=TimeSpan[i,]+TimeInterval
Xbis<-Choixintervalle(X,StartTime,EndTime)
Xtierce <- resampleDF(Xbis, Ts)
HLC<-CalcAverage(Xtierce$Ph,Xtierce$Ti,Xtierce$Te)
HLC<-HLC[length(HLC)]
HLClist<-append(HLClist,HLC)
}
</code></pre>
<p>Where </p>
<ul>
<li><p>TimeSpan is a list that contains all the startimes (format : double), defined as follows:</p>
<pre><code>InitTime <-as.POSIXct("16/02/2014 0:00", format="%d/%m/%Y %H:%M")
FinalTime <-as.POSIXct("16/03/2014 0:00", format="%d/%m/%Y %H:%M")
TimeInterval <-144*3600
SEndTime <- FinalTime - TimeInterval
TimeSpan<-data.frame(seq(InitTime, SEndTime, by=3600))
</code></pre></li>
<li><p>TimeInterval is the number of seconds between Start and endtime (format : double)</p></li>
<li><p>X is the dataframe containing all my data:</p>
<pre><code>X
t Ph Elec Sol Ti Te DHW
1 16/02/2014 0:00 0.0000 612 0.0 22.70 4.600000 0.0000
2 16/02/2014 0:05 0.0000 612 0.0 22.70 4.600000 0.0000
3 16/02/2014 0:10 0.0000 516 0.0 22.79 4.600000 0.0000
4 16/02/2014 0:15 0.0000 480 0.0 22.70 4.600000 0.0000
5 16/02/2014 0:20 0.0000 540 0.0 22.70 4.600000 0.0000
6 16/02/2014 0:25 0.0000 528 0.0 22.60 4.600000 0.0000
7 16/02/2014 0:30 0.0000 492 0.0 22.60 4.600000 0.0000
8 16/02/2014 0:35 0.0000 528 0.0 22.50 4.600000 0.0000
9 16/02/2014 0:40 0.0000 492 0.0 22.49 4.600000 0.0000
10 16/02/2014 0:45 0.0000 456 0.0 22.43 4.600000 0.0000
11 16/02/2014 0:50 0.0000 480 0.0 22.50 4.600000 0.0000
12 16/02/2014 0:55 0.0000 540 0.0 22.50 4.600000 0.0000
13 16/02/2014 1:00 0.0000 528 0.0 22.46 5.270000 0.0000
14 16/02/2014 1:05 0.0000 516 0.0 22.45 5.170000 0.0000
15 16/02/2014 1:10 0.0000 552 0.0 22.45 5.070000 0.0000
16 16/02/2014 1:15 0.0000 480 0.0 22.40 4.980000 0.0000
17 16/02/2014 1:20 0.0000 420 0.0 22.40 4.900000 0.0000
18 16/02/2014 1:25 0.0000 504 0.0 22.34 4.920000 0.0000
19 16/02/2014 1:30 0.0000 408 0.0 22.30 5.000000 0.0000
20 16/02/2014 1:35 0.0000 468 0.0 22.21 5.000000 0.0000
21 16/02/2014 1:40 0.0000 540 0.0 22.20 5.000000 0.0000
22 16/02/2014 1:45 0.0000 276 0.0 22.09 5.020000 0.0000
23 16/02/2014 1:50 0.0000 252 0.0 21.99 5.080000 0.0000
24 16/02/2014 1:55 0.0000 312 0.0 21.90 5.020000 0.0000
25 16/02/2014 2:00 0.0000 336 0.0 21.89 5.070000 0.0000
26 16/02/2014 2:05 0.0000 312 0.0 21.79 5.040000 0.0000
27 16/02/2014 2:10 0.0000 264 0.0 21.70 5.150000 0.0000
28 16/02/2014 2:15 0.0000 300 0.0 21.67 5.200000 0.0000
29 16/02/2014 2:20 0.0000 264 0.0 21.57 5.200000 0.0000
30 16/02/2014 2:25 0.0000 264 0.0 21.50 5.200000 0.0000
31 16/02/2014 2:30 0.0000 360 0.0 21.46 5.200000 0.0000
32 16/02/2014 2:35 0.0000 360 0.0 21.40 5.150000 0.0000
33 16/02/2014 2:40 0.0000 264 0.0 21.35 5.100000 0.0000
34 16/02/2014 2:45 0.0000 252 0.0 21.30 5.100000 0.0000
35 16/02/2014 2:50 0.0000 444 0.0 21.24 5.100000 0.0000
36 16/02/2014 2:55 0.0000 372 0.0 21.20 5.100000 0.0000
37 16/02/2014 3:00 0.0000 372 0.0 21.11 5.100000 0.0000
38 16/02/2014 3:05 0.0000 420 0.0 21.01 5.180000 0.0000
39 16/02/2014 3:10 0.0000 324 0.0 21.00 5.120000 0.0000
40 16/02/2014 3:15 0.0000 300 0.0 21.00 5.020000 0.0000
41 16/02/2014 3:20 0.0000 420 0.0 20.91 5.000000 0.0000
42 16/02/2014 3:25 0.0000 312 0.0 20.90 4.840000 0.0000
43 16/02/2014 3:30 0.0000 300 0.0 20.80 4.880000 0.0000
44 16/02/2014 3:35 0.0000 384 0.0 20.80 4.820000 0.0000
45 16/02/2014 3:40 0.0000 324 0.0 20.79 4.800000 0.0000
46 16/02/2014 3:45 0.0000 324 0.0 20.70 4.880000 0.0000
47 16/02/2014 3:50 0.0000 432 0.0 20.70 4.980000 0.0000
48 16/02/2014 3:55 0.0000 420 0.0 20.66 5.000000 0.0000
49 16/02/2014 4:00 0.0000 336 0.0 20.60 4.920000 0.0000
50 16/02/2014 4:05 0.0000 372 0.0 20.60 4.900000 0.0000
51 16/02/2014 4:10 0.0000 384 0.0 20.56 4.980000 0.0000
52 16/02/2014 4:15 0.0000 276 0.0 20.50 4.920000 0.0000
53 16/02/2014 4:20 0.0000 276 0.0 20.45 4.900000 0.0000
54 16/02/2014 4:25 0.0000 396 0.0 20.40 4.900000 0.0000
55 16/02/2014 4:30 0.0000 288 0.0 20.40 4.900000 0.0000
56 16/02/2014 4:35 0.0000 276 0.0 20.33 4.900000 0.0000
57 16/02/2014 4:40 0.0000 444 0.0 20.30 4.800000 0.0000
58 16/02/2014 4:45 0.0000 348 0.0 20.30 4.800000 0.0000
59 16/02/2014 4:50 0.0000 372 0.0 20.30 4.700000 0.0000
60 16/02/2014 4:55 0.0000 456 0.0 20.21 4.500000 0.0000
61 16/02/2014 5:00 0.0000 384 0.0 20.20 4.480000 0.0000
62 16/02/2014 5:05 0.0000 324 0.0 20.20 4.370000 0.0000
63 16/02/2014 5:10 0.0000 360 0.0 20.10 4.300000 0.0000
64 16/02/2014 5:15 0.0000 348 0.0 20.10 4.300000 0.0000
65 16/02/2014 5:20 0.0000 324 0.0 20.10 4.330000 0.0000
66 16/02/2014 5:25 0.0000 336 0.0 20.08 4.400000 0.0000
67 16/02/2014 5:30 0.0000 360 0.0 20.00 4.400000 0.0000
68 16/02/2014 5:35 0.0000 312 0.0 20.00 4.400000 0.0000
69 16/02/2014 5:40 0.0000 384 0.0 20.00 4.400000 0.0000
70 16/02/2014 5:45 0.0000 372 0.0 20.00 4.440000 0.0000
71 16/02/2014 5:50 0.0000 360 0.0 19.96 4.500000 0.0000
72 16/02/2014 5:55 0.0000 480 0.0 19.90 4.500000 0.0000
73 16/02/2014 6:00 0.0000 384 0.0 19.90 4.540000 0.0000
74 16/02/2014 6:05 0.0000 312 0.0 19.90 4.520000 0.0000
75 16/02/2014 6:10 0.0000 396 0.0 19.84 4.400000 0.0000
76 16/02/2014 6:15 0.0000 324 0.0 19.80 4.360000 0.0000
77 16/02/2014 6:20 0.0000 312 0.0 19.80 4.260000 0.0000
78 16/02/2014 6:25 0.0000 360 0.0 19.80 4.200000 0.0000
79 16/02/2014 6:30 0.0000 372 0.0 19.80 4.200000 0.0000
80 16/02/2014 6:35 0.0000 312 0.0 19.71 4.200000 0.0000
81 16/02/2014 6:40 0.0000 324 0.0 19.70 4.150000 0.0000
82 16/02/2014 6:45 0.0000 444 0.0 19.70 4.150000 0.0000
83 16/02/2014 6:50 0.0000 408 0.0 19.69 4.150000 0.0000
84 16/02/2014 6:55 0.0000 420 0.0 19.60 4.050000 0.0000
85 16/02/2014 7:00 0.0000 408 0.0 19.60 4.000000 0.0000
86 16/02/2014 7:05 0.0000 312 0.0 19.60 4.060000 0.0000
87 16/02/2014 7:10 0.0000 384 0.0 19.60 4.040000 0.0000
88 16/02/2014 7:15 0.0000 360 0.0 19.57 3.940000 0.0000
89 16/02/2014 7:20 0.0000 288 0.0 19.50 3.840000 0.0000
90 16/02/2014 7:25 0.0000 408 0.0 19.50 3.800000 0.0000
91 16/02/2014 7:30 0.0000 336 11.5 19.50 3.800000 0.0000
92 16/02/2014 7:35 0.0000 300 32.6 19.50 3.800000 0.0000
93 16/02/2014 7:40 0.0000 360 67.6 19.45 3.730000 0.0000
94 16/02/2014 7:45 0.0000 360 100.7 19.40 3.630000 0.0000
95 16/02/2014 7:50 0.0000 408 125.9 19.40 3.750000 0.0000
96 16/02/2014 7:55 0.0000 516 142.2 19.40 3.800000 0.0000
97 16/02/2014 8:00 0.0000 552 162.6 19.47 3.950000 0.0000
98 16/02/2014 8:05 0.0000 576 1386.7 19.50 4.000000 0.0000
99 16/02/2014 8:10 0.0000 1032 1550.6 19.57 4.090000 0.0000
100 16/02/2014 8:15 0.0000 1620 1705.0 19.64 4.100000 0.0000
101 16/02/2014 8:20 0.0000 1236 1846.5 19.70 4.100000 0.0000
102 16/02/2014 8:25 0.0000 876 1976.9 19.70 4.300000 0.0000
103 16/02/2014 8:30 0.0000 912 2097.2 19.70 4.300000 0.0000
104 16/02/2014 8:35 0.0000 756 2206.5 19.80 4.390000 0.0000
105 16/02/2014 8:40 0.0000 780 2307.5 19.81 4.490000 0.0000
106 16/02/2014 8:45 0.0000 912 2398.9 19.90 4.500000 0.0000
107 16/02/2014 8:50 0.0000 816 2483.3 19.90 4.600000 2357.5261
108 16/02/2014 8:55 0.0000 732 2559.9 19.93 4.600000 5087.2931
109 16/02/2014 9:00 0.0000 744 2628.5 20.00 4.700000 0.0000
110 16/02/2014 9:05 0.0000 684 2689.3 20.00 4.890000 0.0000
111 16/02/2014 9:10 0.0000 636 2741.2 20.05 4.900000 0.0000
112 16/02/2014 9:15 0.0000 372 2798.5 20.10 4.910000 0.0000
113 16/02/2014 9:20 0.0000 240 2872.2 20.10 5.010000 0.0000
114 16/02/2014 9:25 0.0000 240 2947.3 20.10 5.110000 0.0000
115 16/02/2014 9:30 0.0000 204 3017.2 20.17 5.200000 0.0000
116 16/02/2014 9:35 0.0000 216 3077.6 20.20 5.220000 0.0000
117 16/02/2014 9:40 0.0000 228 3135.5 20.20 5.400000 0.0000
118 16/02/2014 9:45 0.0000 192 3192.8 20.20 5.430000 0.0000
119 16/02/2014 9:50 0.0000 132 3241.5 20.20 5.530000 0.0000
120 16/02/2014 9:55 0.0000 108 3287.1 20.20 5.630000 12904.3533
121 16/02/2014 10:00 0.0000 60 3330.0 20.20 5.700000 9554.1846
122 16/02/2014 10:05 0.0000 72 3369.2 20.20 5.730000 1116.7229
123 16/02/2014 10:10 0.0000 36 3405.4 20.18 5.840000 2233.4458
124 16/02/2014 10:15 0.0000 36 2983.5 20.10 5.940000 5831.7750
125 16/02/2014 10:20 0.0000 0 2428.1 20.10 6.000000 5583.6144
126 16/02/2014 10:25 0.0000 0 2237.7 20.10 6.000000 0.0000
127 16/02/2014 10:30 0.0000 12 2269.7 20.10 6.050000 0.0000
128 16/02/2014 10:35 0.0000 0 2738.2 20.10 6.100000 0.0000
129 16/02/2014 10:40 0.0000 0 3422.9 20.10 6.100000 0.0000
130 16/02/2014 10:45 0.0000 0 3565.9 20.10 6.160000 0.0000
131 16/02/2014 10:50 0.0000 0 3576.7 20.10 6.260000 0.0000
132 16/02/2014 10:55 0.0000 0 3584.8 20.10 6.360000 0.0000
133 16/02/2014 11:00 0.0000 0 3318.6 20.10 6.340000 0.0000
134 16/02/2014 11:05 0.0000 0 2930.1 20.10 6.360000 0.0000
135 16/02/2014 11:10 0.0000 24 2718.4 20.10 6.530000 0.0000
136 16/02/2014 11:15 0.0000 144 2708.2 20.10 6.670000 0.0000
137 16/02/2014 11:20 0.0000 360 2713.0 20.10 6.560000 0.0000
138 16/02/2014 11:25 0.0000 312 2711.7 20.10 6.500000 0.0000
139 16/02/2014 11:30 0.0000 252 2707.5 20.10 6.580000 0.0000
140 16/02/2014 11:35 0.0000 492 2702.2 20.10 6.510000 0.0000
141 16/02/2014 11:40 0.0000 144 2698.8 20.00 6.940000 0.0000
142 16/02/2014 11:45 0.0000 564 2688.3 20.00 7.260000 0.0000
</code></pre></li>
<li><p><code>Choixintervalle</code> is the following function:</p>
<pre><code>Choixintervalle <-function(X,startTime=NA,endTime=NA) {
## set the start time if not specified
if(is.na(startTime)){startTime <- as.POSIXct(X[1,1], format="%d/%m/%Y %H:%M")}
else{startTime<-as.POSIXct(startTime, format="%d/%m/%Y %H:%M")}
## set the end time if not specified
if(is.na(endTime)){ endTime <- as.POSIXct(X[nrow(X),1], format="%d/%m/%Y %H:%M")}
else{endTime<-as.POSIXct(endTime, format="%d/%m/%Y %H:%M")}
X<-X[(as.POSIXct(X$t,format="%d/%m/%Y %H:%M"))>startTime,]
X<-X[(as.POSIXct(X$t,format="%d/%m/%Y %H:%M"))<endTime,]
return(X)
}
</code></pre></li>
<li><p>ResempleEDF is the following function:</p>
<pre><code>resampleDF <- function(X,Ts,startTime = NA, endTime =NA,timeName="t",includeNA=TRUE,quantizeTime=TRUE,meanNaRm=FALSE)
{
## Split into periods of length Ts, and take the mean of each period
X[,timeName] <-as.POSIXct(X[,timeName], format="%d/%m/%Y %H:%M")-startTime
iSplit <- as.integer(X[,timeName]) %/% Ts
## Do the resampling
Xres <- aggregate(X, list(iSplit), mean, na.rm=meanNaRm)
## Remove the "Group" column
Xres <- Xres[,-1]
## Convert time to POSIXct
Corr<- as.integer(Xres[1,timeName])
Xres[,timeName] <- startTime + as.integer(Xres[,timeName])-Corr
return(Xres)
}
</code></pre></li>
<li><p><code>CalcAverage</code> is the following function:</p>
<pre><code>CalcAverage <- function(Q, Ti,Te) {
Solution = vector(length(Q), mode="double" )
for (i in 1:length(Q)){
Temp<-sum(Ti[1:i]-Te[1:i])
Heat<-sum(Q[1:i])
#création du vecteur R
Solution[i]<-Heat/Temp
}
return(Solution)
}
</code></pre></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T08:07:45.250",
"Id": "384017",
"Score": "0",
"body": "Welcome to Code Review! Your current question title describes how the code is structured, but what we really want in a good title is **the purpose of the code**. You can improve ... | [
{
"body": "<pre><code># GENERATE data\nnmax <- TimeSpan[nrow(TimeSpan), ]\ntSEQ <- seq(as.POSIXct(\"16/02/2014 0:00\", format = \"%d/%m/%Y %H:%M\"),\n to = nmax, by = '5 s')\nn <- length(tSEQ)\nX <- data.frame(tSEQ)\nset.seed(42)\nX <- cbind(X, replicate(6, rnorm(n)))\ncolnames(X) <... | {
"AcceptedAnswerId": "199583",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T07:18:17.863",
"Id": "199571",
"Score": "2",
"Tags": [
"performance",
"r"
],
"Title": "Average calculation"
} | 199571 |
<p><strong>Rules</strong></p>
<ul>
<li>7 mistakes allowed.</li>
<li>Hangman rules.</li>
</ul>
<p><strong>Disclaimer</strong></p>
<p>I don't have a figure (drawing) of the hangman as this project took way longer than I thought I would take. It took like 9 hours during 3 weeks.</p>
<p><strong>General mistakes</strong> <em>(I could detect but can't program away):</em></p>
<ol>
<li><p>Poor way of generating the random word to be guessed.</p></li>
<li><p>I have dummy code that isn't used ( I don't know how to remove this without going line for line )</p></li>
<li><p>I'm used to MVC frameworks but my display functions seem to need some calculating code, because things get difficult when I keep them in a separate function.</p></li>
</ol>
<p><strong>Reflection</strong></p>
<p>I am doing more of these little assignments and realized my "good code" and "fast/dirty code" both are poor and don't differ that much.</p>
<p><strong>Where does one learn how to categorize your code</strong></p>
<p>Does anyone know a book that like explains which kind of code needs to be in which kind of function? As I feel I'm reinventing the wheel. Like how do you guys feel that code should be in another place?</p>
<pre><code>#!/bin/bash
words[1]="twitter"
words[2]="facebook"
words[3]="myspace"
words[4]="youtube"
words[5]="amazon"
random_nr=6
correct_letters[1]=""
mistake_letters[1]=""
imploded_letters[1]=""
geuss_counter=1
correct_counter=0
mistakes=0
place=1
# setters
set_word() {
until [[ $random_nr -lt 6 ]] && [[ $random_nr -gt 0 ]]; do
random_nr=${RANDOM};
word=${words[$random_nr]}
done
}
set_word_length() {
word_length_incl_zero=${#word}
word_length=$((word_length_incl_zero+1))
}
# views
display_result() {
for i in $(seq 1 $word_length); do
if [[ $i -ne $word_length ]]; then
position=$((i-1))
if [[ ${word:position:1} == $user_input ]]; then
correct_counter=$((correct_counter+1))
correct_letters[$correct_counter]=$user_input
continue_game
fi
fi
done
echo "sorry you're wrong"
mistakes=$((mistakes+1))
mistake_letters[$mistakes]=$user_input
}
display_welcome_message() {
echo "GALGJE"
echo
echo "Hello, so happy to see you playing my handmade game"
echo "Basicly you need to guess every letter of the word below"
echo "Before things go badly with the guy on the left"
echo
}
display_dashes() {
letters_not_guessed=0
for i in $(seq 1 $word_length); do
if [[ $i -ne $word_length ]]; then
position=$((i-1))
check_if_already_guessed
if [[ $found -eq 1 ]]; then
echo -n ${word:position:1}
else
letters_not_guessed=$((letters_not_guessed+1))
echo -n "-"
fi
fi
done
echo
echo
}
check_if_already_guessed() {
found=0
for i in "${correct_letters[@]}"
do
if [ "$i" == "${word:position:1}" ] ; then
found=1
fi
done
}
display_asking_for_a_letter() {
if [[ $letters_not_guessed == 0 ]]; then
echo "you've won"
exit
fi
read -sn 1 user_input
echo
}
display_mistakes() {
if [[ $mistakes -lt 7 ]]; then
for i in $(seq 1 ${#mistake_letters[@]}); do
if [[ $mistakes -eq 1 ]]; then
more_mistakes_than_one=""
else
more_mistakes_than_one="s"
fi
if [[ $i -eq 1 ]]; then
echo -n "wrong ($mistakes) letter$more_mistakes_than_one: "
echo -n ${mistake_letters[$i]}
else
echo -n ", ${mistake_letters[$i]}"
fi
done
echo
else
end_game
fi
}
display_correct_letters() {
if [[ $mistakes -lt 7 ]] && [[ $correct_counter -lt $word_length ]]; then
for i in $(seq 1 ${#correct_letters[@]}); do
if [[ $correct_counter -eq 1 ]]; then
more_correct_than_one=""
else
more_correct__than_one="s"
fi
if [[ $i -eq 1 ]]; then
echo -n "right ($correct_counter) letter$more_correct_than_one: "
echo -n ${correct_letters[$i]}
else
echo -n ", ${correct_letters[$i]}"
fi
done
echo
echo
else
end_game
fi
}
continue_game() {
display_mistakes
display_correct_letters
geuss_counter=$((geuss_counter+1))
main
}
end_game() {
echo "sorry you've lost"
exit
}
get_first_time_guess() {
first_time_guess=1
for letter in "${correct_letters[@]}"
do
if [ "$letter" == "$user_input" ] ; then
first_time_guess=0
fi
done
for letter in "${mistake_letters[@]}"
do
if [ "$letter" == "$user_input" ] ; then
first_time_guess=0
fi
done
}
main() {
#visuals
display_dashes
display_asking_for_a_letter
#if this letter is already guessed the user
#shouldnt be penalized for it
get_first_time_guess
if [[ $first_time_guess -eq 1 ]]; then
display_result
fi
continue_game
}
set_word
set_word_length
display_welcome_message
main
</code></pre>
| [] | [
{
"body": "<h3>Code organization and naming</h3>\n\n<p>It's good that you organized your code into functions,\nand that you set everything in motion after all the function definitions,\nusing a few simple terms that drive your program:</p>\n\n<blockquote>\n<pre><code>set_word\nset_word_length\ndisplay_welcome_m... | {
"AcceptedAnswerId": "199628",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T10:29:16.240",
"Id": "199582",
"Score": "3",
"Tags": [
"bash",
"hangman"
],
"Title": "hangman in bash"
} | 199582 |
<p>I wrote the following Rust code to solve <a href="https://www.reddit.com/r/dailyprogrammer/comments/8sjcl0/20180620_challenge_364_intermediate_the_ducci/" rel="noreferrer">this task on /r/DailyProgrammer</a>.</p>
<blockquote>
<p>Given an n-tuple of numbers as input, the Ducci Sequence is formed by
taking the absolute difference of the difference between neighboring
elements. (The last result is the difference between the first and
last elements.)</p>
<h2>Example input</h2>
<pre><code>[0; 653; 1854; 4063]
</code></pre>
<h2>Example output</h2>
<p>Emit the number of steps taken to get to either an all 0 tuple or when
it enters a stable repeating pattern.</p>
<pre><code>[0; 653; 1854; 4063]
[653; 1201; 2209; 4063]
[548; 1008; 1854; 3410]
[460; 846; 1556; 2862]
[386; 710; 1306; 2402]
[324; 596; 1096; 2016]
[272; 500; 920; 1692]
[228; 420; 772; 1420]
[192; 352; 648; 1192]
[160; 296; 544; 1000]
[136; 248; 456; 840]
[112; 208; 384; 704]
[96; 176; 320; 592]
[80; 144; 272; 496]
[64; 128; 224; 416]
[64; 96; 192; 352]
[32; 96; 160; 288]
[64; 64; 128; 256]
[0; 64; 128; 192]
[64; 64; 64; 192]
[0; 0; 128; 128]
[0; 128; 0; 128]
[128; 128; 128; 128]
[0; 0; 0; 0]
24 steps
</code></pre>
</blockquote>
<p>I'm aware all the extra functions and error handling are a bit exaggerated for a task this easy, but I'm learning rust at the moment so I tried to get things right.</p>
<pre><code>extern crate regex;
use std::io::Write;
use std::fmt::Display;
use std::fmt;
use regex::Regex;
use std::io;
use std::error;
fn main() {
match read_input() {
Ok(tuple) => {
run(tuple);
}
Err(e) => {
eprintln!("An error occured: {}", e);
}
}
}
/// Tries to read input from standard input
fn read_input() -> Result<Tuple, Error> {
print!("input: ");
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Tuple::new(input)
}
/// runs Ducci sequence calculation and prints every step
fn run(tuple: Tuple) {
let mut i = tuple;
let mut history: Vec<Tuple> = Vec::new();
let mut steps = 1;
while !&i.zeros() && !history.contains(&i) {
let next = i.next();
history.push(i);
i = next;
println!("{}", i);
steps += 1;
}
println!("{} steps", steps);
}
struct Tuple {
data: Vec<i32>,
}
impl Tuple {
fn new(line: String) -> Result<Tuple, Error> {
// Regex for allowed inputs: (a, b, c, ..., d)
let re = Regex::new(r"\(((\d)+, )*(\d)+\)").unwrap();
if!re.is_match(line.as_str()) {
Err(Error::ParsingError)
}
else {
// seperate single numbers, parse to integer and push into tuple instance
let sep = Regex::new(r"(, |\(|\))").unwrap();
let mut data: Vec<i32> = Vec::new();
for numbers in sep.split(line.as_str()) {
match numbers.parse::<i32>() {
Ok(number) => {
data.push(number);
},
// ignore newline and empty captures
Err(_) => {},
}
}
Ok(Tuple {
data: data,
})
}
}
/// Calculates and returns next tuple in ducci sequence
fn next(&self) -> Tuple {
let mut data: Vec<i32> = Vec::new();
// calculate first n - 1 new values
for i in 0..self.dimension() - 1 {
data.push((self.data[i] - self.data[i + 1]).abs());
}
// calculate last value
data.push((self.data[self.dimension() - 1] - self.data[0]).abs());
Tuple {
data: data,
}
}
/// Returns tuples dimension
fn dimension(&self) -> usize {
self.data.len()
}
/// Determines whether tuple only contains zeros
fn zeros(&self) -> bool {
self.data.iter().fold(true, |acc, x| {acc && *x == 0})
}
}
impl PartialEq for Tuple {
fn eq(&self, other: &Tuple) -> bool {
if self.dimension() != other.dimension() {
false
}
else {
let mut e = true;
for i in 0..self.dimension() {
e = e && self.data[i] == other.data[i];
}
e
}
}
}
impl Display for Tuple {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = String::new();
s.push_str("[");
for i in 0..self.dimension() - 1 {
s.push_str(self.data[i].to_string().as_str());
s.push_str("; ");
}
s.push_str(self.data[self.dimension() - 1].to_string().as_str());
s.push_str("]");
write!(f, "{}", s)
}
}
#[derive(Debug)]
enum Error {
ReadingError,
ParsingError,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
Error::ReadingError => {
f.write_str("Error while reading input line from standard input.")
}
Error::ParsingError => {
f.write_str("Input line does not meet format requirements: (a, b, c, ..., d)")
}
}
}
}
impl error::Error for Error {}
impl std::convert::From<std::io::Error> for Error {
fn from(_e: std::io::Error) -> Self {
Error::ReadingError
}
}
</code></pre>
<p>What are youre thoughts? What can I do better or in a more elegant way?</p>
| [] | [
{
"body": "<p>This is only a summary of some remarks that came to mind when I read your code. It looks good, but I would run it through <code>rustfmt</code>. Also, your delimiters are parentheses and commas (<code>(…,…)</code>) instead of brackets and semicolons (<code>[…;…]</code>), that seems off.</p>\n\n<h1>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T11:18:49.337",
"Id": "199585",
"Score": "7",
"Tags": [
"programming-challenge",
"rust"
],
"Title": "The Ducci Sequence"
} | 199585 |
<p>it would be very interesting to hear suggestions about my the newest project - Car Rental that interact with Data Base. It doesn't have GUI, because I haven't learned it before. That's because you will find a lot of sys.out.print lines.
It contains a lot of classes, I will put down here the most important.
At the bottom I will put link to the project on my github.
You can ask why by creating new client random number is shown. That's because I didn't know how to pair User Object and Client Object, so my App doesn't have possibility to create accounts for user nor worker. Client number is required for example in renting a car. User must input this number. If he want to populate all the rented cars, he must input the same client number that he inputted during renting. That is how every client is unique - it has his own number.</p>
<p><strong>DataBase</strong> class. Contain methods that are responsible for adding/deleting/updating... data in my database. Methods are long, because I used prepared statements. I heard, it's good practice. In methods like <code>rentACar</code>, <code>makeCarUnavailable</code>, <code>makeCarAvailable</code> I added functionality which takes responsible for throwing a message if car doesn't exist.</p>
<pre><code>public class DataBase {
private Connection connection;
private Statement statement;
private PreparedStatement preparedStatement;
private ResultSet result;
public DataBase() throws SQLException {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/rentalcar?autoReconnect=true&serverTimezone=" + TimeZone.getDefault().getID(), "root", "...");
statement = connection.createStatement();
}
public void insertNewCustomer(Client client) throws SQLException {
preparedStatement = connection.prepareStatement("insert into client" + "(namee, surname, street,houseNumber,city,peselNumber,rentDate, clientNumber)" + "values(?,?,?,?,?,?,?,?)");
preparedStatement.setString(1, client.getName());
preparedStatement.setString(2, client.getSurname());
preparedStatement.setString(3, client.getStreet());
preparedStatement.setInt(4, client.getHouseNumber());
preparedStatement.setString(5, client.getCity());
preparedStatement.setLong(6, client.getPeselNumber());
preparedStatement.setString(7, client.getRentDate());
preparedStatement.setInt(8, client.getClientNumber());
preparedStatement.executeUpdate();
}
public void insertNewCar(Car car) throws SQLException {
preparedStatement = connection.prepareStatement("insert into car" + "(brand, productionYear, engineCapacity,dayPrice,available)" + "values(?,?,?,?,?)");
preparedStatement.setString(1, car.getBrand());
preparedStatement.setString(2, car.getProductionYear());
preparedStatement.setString(3, car.getEngineCapacity());
preparedStatement.setInt(4, car.getDayPrice());
preparedStatement.setString(5, car.getAvailable());
preparedStatement.executeUpdate();
}
public void rentACar(RentingACar rentingACar) throws SQLException {
int count = 0;
boolean isAvailable = true;
{
preparedStatement = connection.prepareStatement("SELECT COUNT(0) FROM car WHERE available='1' AND brand=?");
preparedStatement.setString(1, rentingACar.getBrand());
result = preparedStatement.executeQuery();
}
while (result.next()) {
count = result.getInt(1);
}
if (count < 1)
isAvailable = false;
if (isAvailable) {
preparedStatement = connection.prepareStatement("insert into rentcar" + "(brand,namee,surname,rentDate,clientNumber)" + "values(?,?,?,?,?)");
preparedStatement.setString(1, rentingACar.getBrand());
preparedStatement.setString(2, rentingACar.getName());
preparedStatement.setString(3, rentingACar.getSurname());
preparedStatement.setString(4, rentingACar.getRentDate());
preparedStatement.setInt(5, rentingACar.getClientNumber());
preparedStatement.executeUpdate();
preparedStatement = connection.prepareStatement("update car " + " set available='0'" + " where brand= ? ");
preparedStatement.setString(1, rentingACar.getBrand());
preparedStatement.executeUpdate();
System.out.println("Car was rented!");
} else {
System.out.println("There is no " + rentingACar.getBrand() + " in our car or all types of this car are rented!");
}
}
public void returnACar(Car car) throws SQLException {
preparedStatement = connection.prepareStatement("DELETE from rentcar WHERE brand=? AND clientNumber=?");
preparedStatement.setString(1, car.getBrand());
preparedStatement.setInt(2, car.getClientNumber());
preparedStatement.executeUpdate();
preparedStatement = connection.prepareStatement("update car " + " set available='1'" + " where brand=?");
preparedStatement.setString(1, car.getBrand());
preparedStatement.executeUpdate();
}
public void makeCarUnavailable(Car car) throws SQLException {
int count = 0;
boolean isAvailable = true;
{
preparedStatement = connection.prepareStatement("SELECT COUNT(0) FROM car WHERE brand=? AND productionYear=? ");
preparedStatement.setString(1, car.getBrand());
preparedStatement.setString(2, car.getProductionYear());
result = preparedStatement.executeQuery();
}
while (result.next()) {
count = result.getInt(1);
}
if (count < 1)
isAvailable = false;
if (isAvailable) {
preparedStatement = connection.prepareStatement("update car " + " set available='0'" + " where brand=? AND productionYear=?");
preparedStatement.setString(1, car.getBrand());
preparedStatement.setString(2, car.getProductionYear());
preparedStatement.executeUpdate();
System.out.println(car.getBrand() + " was made unavailable");
} else {
System.out.println("No " + car.getBrand() + " in system!");
}
}
public void makeCarAvailable(Car car) throws SQLException {
int count = 0;
boolean isAvailable = true;
{
preparedStatement = connection.prepareStatement("SELECT COUNT(0) FROM car WHERE brand=? AND productionYear=? ");
preparedStatement.setString(1, car.getBrand());
preparedStatement.setString(2, car.getProductionYear());
result = preparedStatement.executeQuery();
}
while (result.next()) {
count = result.getInt(1);
}
if (count < 1)
isAvailable = false;
if (isAvailable) {
preparedStatement = connection.prepareStatement("update car " + " set available='1'" + " where brand=? AND productionYear=?");
preparedStatement.setString(1, car.getBrand());
preparedStatement.setString(2, car.getProductionYear());
preparedStatement.executeUpdate();
System.out.println(car.getBrand() + " was made unavailable");
} else {
System.out.println("No " + car.getBrand() + " in system!");
}
}
public void populateTableViewCars(Car car) throws SQLException {
preparedStatement = connection.prepareStatement("SELECT * FROM car WHERE dayPrice > ?");
preparedStatement.setDouble(1, car.getDayPrice());
result = preparedStatement.executeQuery();
while (result.next()) {
String brand = result.getString("brand");
String productionYear = result.getString("productionYear");
String engineCapacity = result.getString("engineCapacity");
String dayPrice = result.getString("dayPrice");
String available = result.getString("available");
System.out.println("----------------------------");
System.out.printf("Brand:" + brand + "\nEngine Capacity:" + engineCapacity + "\nDayPrice:" + dayPrice + "\nProduction Year:" + productionYear + "\navailable:" + available + "\n");
System.out.println("----------------------------");
}
}
public void populateTableRent(Client client) throws SQLException {
preparedStatement = connection.prepareStatement("SELECT * FROM rentcar WHERE clientNumber=?");
preparedStatement.setInt(1, client.getClientNumber());
result = preparedStatement.executeQuery();
while (result.next()) {
String brand = result.getString("brand");
String name = result.getString("namee");
String surname = result.getString("surname");
String rentDate = result.getString("rentDate");
System.out.println("----------------------------");
System.out.printf("Brand:" + brand + "\nName:" + name + "\nSurname:" + surname + "\nDate of rental:" + rentDate + "\n");
System.out.println("----------------------------");
}
}
public void populateTableViewClients() throws SQLException {
String sql = "SELECT * FROM `client`";
result = statement.executeQuery(sql);
while (result.next()) {
String namee = result.getString("namee");
String surname = result.getString("surname");
String street = result.getString("street");
int houseNumber = result.getInt("houseNumber");
long peselNumber = result.getLong("peselNumber");
String rentDate = result.getString("rentDate");
System.out.println("----------------------------");
System.out.printf("Name:" + namee + "\nSurname:" + surname + "\nStreet:" + street + "\nNumber of house:" + houseNumber + "\nPesel number:" + peselNumber + "\nDate of rental:" + rentDate + "\n");
System.out.println("----------------------------");
}
}
}
</code></pre>
<p>I've package named DataGetter that contains 2 classes - <strong>WorkerDataGetter</strong> and <strong>ClientDataGetter</strong>.
They contain methods that are responsible for getting data and creating objects. For example in WorkerDataGetter we can find <code>createCar</code> method that is collecting data from user and creating object of new car that will be passed to databases' methods. </p>
<p><strong>WorkerDataGetter</strong></p>
<pre><code>public class WorkerDataGetter {
private Scanner input = new Scanner(System.in);
public Car createCar() {
Car car = new Car();
System.out.print("Brand: ");
car.setBrand(input.next());
System.out.print("Day price: ");
car.setDayPrice(input.nextInt());
System.out.print("Engine Capcity: ");
car.setEngineCapacity(input.next());
System.out.print("Production year: ");
car.setProductionYear(input.next());
System.out.print("available: ");
car.setAvailable(input.next());
return car;
}
public Car makeCarUnavailable() {
Car car = new Car();
System.out.print("Brand: ");
car.setBrand(input.next());
System.out.print("production year: ");
car.setProductionYear(input.next());
return car;
}
public Car makeCarAavailable() {
Car car = new Car();
System.out.print("Brand: ");
car.setBrand(input.next());
System.out.print("Production year : ");
car.setProductionYear(input.next());
return car;
}
}
</code></pre>
<p><strong>ClientDataGetter</strong></p>
<pre><code>public class ClientDataGetter {
private Scanner input = new Scanner(System.in);
private Random rand = new Random();
public Client createClient() {
Client client = new Client();
client.setClientNumber(rand.nextInt(999));
System.out.print("name: ");
client.setName(input.next());
System.out.print("surname: ");
client.setSurname(input.next());
System.out.print("city: ");
client.setCity(input.next());
System.out.print("house number: ");
client.setHouseNumber(input.nextInt());
System.out.print("street: ");
client.setStreet(input.next());
System.out.print("pesel number: ");
client.setPeselNumber(input.nextLong());
System.out.print("rent date: ");
client.setRentDate(input.next());
System.out.println("Your client number is: " + client.getClientNumber());
return client;
}
public RentingACar rentACar() {
RentingACar rentingACar = new RentingACar();
System.out.print("Brand: ");
rentingACar.setBrand(input.next());
System.out.print("Name: ");
rentingACar.setName(input.next());
System.out.print("Surname: ");
rentingACar.setSurname(input.next());
System.out.print("Rent Date: ");
rentingACar.setRentDate(input.next());
System.out.print("Client number: ");
rentingACar.setClientNumber(input.nextInt());
return rentingACar;
}
public Car populateTableViewCars() {
Car car = new Car();
System.out.println("Input minimum price per day. If you want to display all cars - input 0.\nMinimum price: ");
car.setDayPrice(input.nextInt());
return car;
}
public Client populateTableRent() {
Client client = new Client();
System.out.println("Input your client number: ");
client.setClientNumber(input.nextInt());
return client;
}
public Car returnACar() {
Car car = new Car();
System.out.println("Input brand of car that you want to return: ");
car.setBrand(input.next());
System.out.println("Input your client number, otherwise car won't be removed from our DataBase!");
car.setClientNumber(input.nextInt());
return car;
}
}
</code></pre>
<p><strong>CarRentalOptions</strong> class - contains all the methods that we can find in the App. </p>
<pre><code>public class CarRentalOptions {
private DataBase dataBase = new DataBase();
CarRentalOptions() throws SQLException {
}
void createNewCustomer(Client client) throws SQLException {
dataBase.insertNewCustomer(client);
System.out.println("Client added successfully!");
}
void createNewCar(Car car) throws SQLException {
dataBase.insertNewCar(car);
System.out.println("Car added successfully!");
}
void makeCarUnavailable(Car car) throws SQLException {
dataBase.makeCarUnavailable(car);
}
void makeCarAvailable(Car car) throws SQLException {
dataBase.makeCarAvailable(car);
}
void rentACar(RentingACar rentingACar) throws SQLException {
dataBase.rentACar(rentingACar);
}
void populateTableViewCars(Car car) throws SQLException {
dataBase.populateTableViewCars(car);
}
void populateTableRent(Client client) throws SQLException {
dataBase.populateTableRent(client);
}
void populateTableViewClients() throws SQLException {
dataBase.populateTableViewClients();
}
void returnACar(Car car) throws SQLException {
dataBase.returnACar(car);
}
}
</code></pre>
<p><strong>CarRentalEngine</strong> - the brain of the App</p>
<pre><code>public class CarRentalEngine {
private int option;
private Scanner input = new Scanner(System.in);
private CarRentalOptions carRentalOptions = new CarRentalOptions();
private ClientDataGetter clientDataGetter = new ClientDataGetter();
private WorkerDataGetter workerDataGetter = new WorkerDataGetter();
CarRentalEngine() throws SQLException {
}
void startCarRental() throws SQLException {
System.out.println("Who are you?\n1. Customer\n2. Worker");
try {
switch (input.nextInt()) {
case 1:
executeClientCase();
break;
case 2:
executeWorkerCase();
break;
}
} catch (InputMismatchException e) {
System.err.println("Your input is wrong!");
}
}
private void executeOptionsForClient(int option) throws SQLException {
switch (option) {
case 1:
carRentalOptions.rentACar(clientDataGetter.rentACar());
break;
case 2:
carRentalOptions.returnACar(clientDataGetter.returnACar());
break;
case 3:
carRentalOptions.populateTableRent(clientDataGetter.populateTableRent());
break;
case 4:
carRentalOptions.populateTableViewCars(clientDataGetter.populateTableViewCars());
break;
case 5:
break;
}
}
private void executeOptionsForWorker(int option) throws SQLException {
switch (option) {
case 1:
carRentalOptions.populateTableViewClients();
break;
case 2:
carRentalOptions.populateTableViewCars(clientDataGetter.populateTableViewCars());
break;
case 3:
carRentalOptions.makeCarAvailable(workerDataGetter.makeCarAavailable());
break;
case 4:
carRentalOptions.makeCarUnavailable(workerDataGetter.makeCarUnavailable());
break;
case 5:
carRentalOptions.createNewCar(workerDataGetter.createCar());
case 6:
break;
}
}
private void executeClientCase() throws SQLException {
System.out.println("1. Have you inputted your data before?\nN/Y: ");
if (input.next().toUpperCase().equals("N")) {
carRentalOptions.createNewCustomer(clientDataGetter.createClient());
System.out.println("Now you have your unique number clinet, use it where it is required!");
} else {
do {
System.out.println("What do you want to do?");
System.out.println("1. Rent a car\n2. Return a car\n3. Populate rented cars\n4. Populate cars\n5. Quit");
option = input.nextInt();
executeOptionsForClient(option);
}
while (option != 5);
}
}
private void executeWorkerCase() throws SQLException {
do {
System.out.println("What do you want to do?");
System.out.println("1. Populate clients\n2. Populate cars\n3. Make car available\n4. Make car unavailable\n5. Insert new car\n6. Quit");
option = input.nextInt();
executeOptionsForWorker(option);
}
while (option != 6);
}
}
</code></pre>
<p>I've got also classes like Car, Client, RentingACar - they contains getters and setters. You can find it on my github CarRental/Model. Here is the link: <a href="https://github.com/must1/RentalCar" rel="nofollow noreferrer">https://github.com/must1/RentalCar</a> .</p>
<p>Thanks for all suggestions.</p>
| [] | [
{
"body": "<p><strong>DataBase</strong></p>\n\n<p>In <code>DataBase</code> class I'd use method scoped variables, rather than class properties. In general, it's better to have method scoped variables since you can keep control about their state. This way:</p>\n\n<pre><code>public void rentACar(RentingACar renti... | {
"AcceptedAnswerId": "199629",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T12:20:19.850",
"Id": "199590",
"Score": "1",
"Tags": [
"java"
],
"Title": "Car Rental with DataBase"
} | 199590 |
<p>I have the following program for a multiple choice quiz game. Before I get stuck in some habits, can anyone please review and propose suggestions for improvements?</p>
<pre><code>import random
import time
YES = ['y', 'Y', 'yes', 'Yes', 'YES']
NO = ['n', 'N', 'no', 'No', 'NO']
CLEAR = ['c', 'C', 'clear', 'Clear', 'CLEAR']
QUIT = ['q', 'Q', 'quit', 'Quit', 'QUIT']
MULTIPLECHOICE = ['a', 'b', 'c', 'd']
class QuizGame:
''' repository of methods to do with QuizGame
- get_username
- play_loop
- ask_play_again
- escape_quiz
- play_quiz
- read_highscores
- write_highscores
- clear_highscores
- display_highscores
'''
questions = \
{1: ('What was the first video game ever made?',
'a) God of War 9\nb) Pacman \nc) Pong \nd) Tennis for Two',
'd'),
2: ('What was the most expensive video game to ever be developed?',
'a) Destiny\nb) Call of Duty: Modern Warfare 2 \n'
'c) Grand Theft Auto: V \nd) Disney Infinity',
'b'),
3: ('What amount of time a day does the average gamer (In the US, '
'age 13 or older) spend gaming?',
'a) 54 minutes\nb) 25 hours\nc) 2 hours\nd) 30 minutes',
'a'),
4: ('Who is the founder of Nintendo?',
'a) Fusajiro Yamauchi\nb) Bob Dylan\nc) Steve Bovaird\n'
'd) Nihonjin no Shimei',
'a'),
5: ('What was the most purchased game of 2017?',
'a) Jesus sim\nb) Farming Simulator 2017\n'
'c) Call of Duty: WWII\nd) Destiny 2',
'c'),
6: ('When was E3 [Electronic Entertainment Expo] 2017?',
'a) 13 Jun 2017 - 15 Jun 2017\nb) 13 Jun 2017 - 14 Jun 2017\n'
'c) 15 July 2017 - 13 July 2017\nd) 10 Jun 2017 - 18 Jun 2017',
'a'),
7: ('What was the most popular console of 2010?',
'a) Xbox 360\nb) PlayStation 3\nc) Xbox 1\nd) PlayStation 4',
'a'),
8: ('Who was the most subscribed gaming youtuber of 2012?',
'a) PrettyL8r\nb) Pewdiepie\nc) Greg\nd) NotGreg',
'b'),
9: ('Who won the Game of The Year award 2016?',
'a) Overwatch\nb) Treyarch\nc) Blizzard\n'
'd) Rainbow Six Siege',
'c'),
10: ('When did DOOM release?',
'a) December 10, 1993\nb) February 23, 1995\n'
'c) January 32, 20019\nd) Yesterday',
'a'), }
welcometext =\
'\nHello {}, welcome to The Videogame Quiz'\
'\nIn this quiz, you will be asked 10 questions about videogames.'\
'\nTry your best to answer all 10 correctly. Enter a, b, c or d '\
'\ndepending on which answer you think is right\n'
users = {}
score = 0
highscore_file = 'highscore.log'
@classmethod
def get_username(cls):
''' method to ask user for user_name, if user name is Quit then leave.
Dictionary of cls.users is checked on existing users. If user
does not exist he/ she is added.
'''
user_name = ''
quit = False
while len(user_name) < 4 and not quit:
user_name = input('Hello! What is your name [enter Q(uit) '
'to leave]?: ').strip().capitalize()
if user_name in QUIT:
quit = True
if not quit:
if user_name not in cls.users:
cls.users.update({user_name: 0})
cls.highscore = 0
print(cls.welcometext.format(user_name))
return user_name, quit
@classmethod
def play_loop(cls, user_name):
''' method to control loop of the quiz, update highscore, and ask
to play again or not
'''
playagain = True
while playagain:
print(f'\n{user_name}, your current highscore is '
f'{cls.users[user_name]}.\n')
if cls.escape_quiz():
break
score = cls.play_quiz()
if score > cls.users[user_name]:
cls.users.update({user_name: score})
playagain = cls.play_again()
@staticmethod
def play_again():
''' ask player if he/ she wants to play quiz again
'''
answered = False
while not answered:
answer = input('Do you want to take the quiz again? Y or N: ')
answered = True
if answer in YES:
playagain = True
elif answer in NO:
playagain = False
else:
answered = False
return playagain
@staticmethod
def escape_quiz():
''' ask player twice if he/ she is ready to continue
'''
answered = 0
question = '\nAre you ready to continue? Y or N? '
while answered < 2:
answer = input(question)
print('---------------------------------------')
answered += 1
if answer in YES:
escape_the_quiz = False
break
elif answer in NO:
escape_the_quiz = True
for i in range(3):
print('Oh... ok')
time.sleep(0.5)
question = '\nNow are you ready to continue? Y or N '
else:
print('Yes or no only please!')
return escape_the_quiz
@classmethod
def play_quiz(cls):
''' core of quiz asking multiple choice questions. Player can leave
by entering quit
'''
questions = cls.questions.copy()
question_choice = {i for i in range(1, len(questions)+1)}
score = 0
question_nr = 1
while questions:
question = random.sample(question_choice, 1)[0]
answered = False
print(f'Question: {question_nr} of {len(cls.questions)}')
print(questions[question][0])
print(questions[question][1])
question_nr += 1
answered = False
while not answered:
answer = input('What is your answer?: ').lower()
if answer in (MULTIPLECHOICE + QUIT):
answered = True
else:
print('ERROR, please input a, b, c or d only please!')
if answer in QUIT:
break
elif answer == questions[question][2]:
print('Good job! You are correct.\n')
score += 1
else:
print('Unfortunately that is not correct! '
'Better luck next time.\n')
questions.pop(question)
question_choice.remove(question)
print(f'Your score is >>> {score}\n')
return score
@classmethod
def read_highscores(cls):
''' read highscores from cls.highscore_file
'''
try:
with open(cls.highscore_file, 'r') as highscores:
for line in highscores:
user_name, score = line.split(':')
cls.users[user_name.strip()] = int(score)
except Exception as e:
print('Error in log file, must be format <name: score>')
@classmethod
def write_highscores(cls):
''' write highscores to cls.highscore_file
'''
try:
with open(cls.highscore_file, 'w') as highscores:
for name in cls.users:
highscores.write('{}: {}\n'.
format(name, str(cls.users[name])))
except Exception as e:
print('Error in log file, must be format <name: score>')
@classmethod
def clear_highscores(cls):
''' clears the highscore file if confirmed by typing 'CLEAR'
'''
answer = input('\nDo you want to clear the scores log, '
'type \'CLEAR\' ')
if answer == 'CLEAR':
with open(cls.highscore_file, 'w') as highscores:
highscores.write('')
@classmethod
def display_highscores(cls):
''' displays highscores in order from high to low
'''
print('\nHighscores')
print('-'*40)
print('{:20}{}'.format('Name', 'Score'))
print('-'*40)
sorted_output = sorted(QuizGame.users.items(), key=lambda v: v[1],
reverse=True)
for line in sorted_output:
print(f'{line[0]:20}{line[1]}')
def main():
''' starts the program
'''
QuizGame.read_highscores()
QuizGame.display_highscores()
quit = False
while not quit:
user_name, quit = QuizGame.get_username()
if not quit:
QuizGame.play_loop(user_name)
QuizGame.display_highscores()
QuizGame.write_highscores()
QuizGame.clear_highscores()
if __name__ == '__main__':
main()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T13:05:28.957",
"Id": "199593",
"Score": "3",
"Tags": [
"python",
"quiz"
],
"Title": "Python quiz game"
} | 199593 |
<p>I need something akin to C++'s shared_ptr. Essentially I need an IDisposable item that I can ensure is cleaned up as soon as possible once all references have been removed, but this resource will be shared between many classes.</p>
<p>I don't allow passing in of a an already existing object as it's an easy way to know that the item I'm using isn't being hasn't already been disposed.</p>
<p>Unfortunately I can't think of a way to prevent the user of <em>Item</em> from disposing the underlying item, but as this is to go into my own program I'm not too concerned about that because it intuitively makes sense to not dispose something within a wrapper, provided every class that needs the item uses the wrapper and not just the contained item.</p>
<p>I simply want to know if anyone can see any potential issues with this solution besides what's mentioned.</p>
<pre><code>public class SharedDisposable<T> : IDisposable where T : class, IDisposable {
static SharedDisposable(){
instances = new Dictionary<T, List<SharedDisposable<T>>>();
}
public SharedDisposable(SharedDisposable<T> share) {
Item = share.Item;
instances[Item].Add(this);
}
public SharedDisposable(object[] ctorArgs = null) {
if(ctorArgs == null)
ctorArgs = new object[] { };
var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.GetType()).ToArray());
Item = (T)ctor.Invoke(ctorArgs);
instances[Item] = new List<SharedDisposable<T>>() { this };
}
public SharedDisposable(KeyValuePair<Type, object>[] ctorArgs) {
var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.Key).ToArray());
Item = (T)ctor.Invoke(ctorArgs.Select(a => a.Value).ToArray());
instances[Item] = new List<SharedDisposable<T>>() { this };
}
public void Dispose() {
var instanceList = instances[Item];
instanceList.Remove(this);
if(instances.Count == 0) {
instances.Remove(Item);
Item.Dispose();
}
}
public T Item { get; }
static Dictionary<T, List<SharedDisposable<T>>> instances;
}
</code></pre>
<p>Example usage:</p>
<pre><code>class MainForm : Form {
public MainForm(){
InitializeComponent();
Port = new SharedDisposable<SerialPort>("COM5", 9600);
}
public MainForm(SharedDisposable<SerialPort> share){
InitializeComponent();
if(share == null)
throw new ArgumentNullException(nameof(share))
Port = new SharedDisposable<SerialPort>(share);
}
public void BtnDevice1Info_Click(object sender, EventArgs e){
new Device1InfoForm(Port).Show();
}
public void BtnDevice2Info_Click(object sender, EventArgs e){
new Device2InfoForm(Port).Show();
}
override Dispose(bool disposing){
if(disposing){
Port.Dispose();
}
base.Dispose(disposing);
}
private SharedDisposable<SerialPort> Port { get; }
}
</code></pre>
<p>In my application I actually have a Modbus interface instead of serial port but I just realised the way the constructor is setup won't allow me to use the Modbus API because the Modbus API uses factories instead of constructors, so I'll need to adjust it for that.
But that API should be able to queue messages to be sent out one at a time, preventing any conflicts on the serial port while also allowing multiple forms or even applications to use the same serial port. In order to make this happen I need multiple forms to be able to share a disposable resource, but none of them to clean it up unless they're the last holder of that resource.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T15:36:13.673",
"Id": "384081",
"Score": "0",
"body": "Could you add an example that shows how this is supposed to be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T16:15:54.103",
"Id": "384... | [
{
"body": "<blockquote>\n<pre><code>public SharedDisposable(object[] ctorArgs = null)\n{\n if (ctorArgs == null)\n ctorArgs = new object[] { };\n\n var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.GetType()).ToArray());\n Item = (T)ctor.Invoke(ctorArgs);\n instances... | {
"AcceptedAnswerId": "199615",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T15:27:49.507",
"Id": "199598",
"Score": "6",
"Tags": [
"c#",
".net",
"memory-management"
],
"Title": "C# version of C++ shared_ptr"
} | 199598 |
<p>I refactored some of my code:</p>
<p><strong>Summary:</strong> This implementation works with PSGI/Plack. It gets the URL from <code>$env->{PATH_INFO}</code> and assigns a different variable according to the value in the URL with regex.</p>
<p>This approach can redirect users to an existing URL in the router system. It also remembers the last page the user visited and detects if the URL has a string with 10 digits (token). All this is done via session file. </p>
<p>The previous code:</p>
<pre><code>my $app = sub {
my $env = shift;
my $form = $env->{' Auth::Form.LoginForm'};
my $token = $env->{'psgix.session'}{token};
my $fromreferer = $env->{PATH_INFO};
my $onfirstnameapp;
if ($fromreferer eq '/'){
$onfirstnameapp = '';
$env->{'psgix.session'}{equal_root} = 'equal_root';
}
elsif(grep(/(nameapp\d{11})/, $fromreferer)){
$env->{'psgix.session'}{greather_ten_digits} = 'greather_ten_digits';
$onfirstnameapp = '/greather_ten_digits';
}
elsif(grep(/(nameapp\d{10})/, $fromreferer)){
$env->{'psgix.session'}{equal_ten} = 'equal_ten';
$onfirstnameapp = $1 if $fromreferer =~ /.:?(nameapp\d{10})\/?/;
}
else{
$env->{'psgix.session'}{not_root_notroute} = 'not_root_notroute';
$onfirstnameapp = $fromreferer . '/not_root_notroute';
}
my $onlineafterAppurl = $1 if $fromreferer =~ /.:?nameapp\d+(\/.*)/;
$env->{'psgix.session'}{current_request} = $onfirstnameapp;
if($env->{'psgix.session'}{user_id}){
my $get_old_token = $env->{'psgix.session'}{old_token};
my $offtoken = $env->{'psgix.session'}{offtoken};
my ($code) = $router->match($env->{PATH_INFO});
if ( $onfirstnameapp ne $token ){
$env->{'psgix.session'}{no_token_equal} = 'no_token_equal';
check_url_exist_inrouter($onlineafterAppurl);
# }
if (grep(/$onlineafterAppurl/, @resulturlcheck) or
(grep(/(nameapp\d{10})/, $offtoken) && $onlineafterAppurl eq '') ) {
delete $env->{'psgix.session'}{offtoken} if $onlineafterAppurl eq '';
$onlineafterAppurl = "/$handler" if $onlineafterAppurl eq '';
if( $onfirstnameapp eq $offtoken || $onfirstnameapp eq $get_old_token ) {
$env->{'psgix.session'}{menus_router_boom_off} = 'off work';
return [
302,
[ Location => URI->new('/' . $token . $onlineafterAppurl) ],
[ '' ]
];
}
}
};
return ["404", ["Content-Type" => "text/html"], ["Not Found, go to : <a href='/'>Home</a> " ] ] unless $code;
return $code->($env);
}
if ($fromreferer ne '/'){
return ["401", ["Content-Type" => "text/html"],
[ $form ]
];
}
return ["404", ["Content-Type" => "text/html"], [ $form ]];
};
</code></pre>
<p>The current code refactory:</p>
<pre><code>my $app = sub {
my $env = shift;
my @all_urls_names = @{$env->{all_urls_names}};
my $router = Routerapp->new;
my %set = (
handler => $all_urls_names[0],
tk => '/' . $env->{'psgix.session'}{token},
fromreferer => $env->{PATH_INFO},
token => $env->{'psgix.session'}{token},
form => $env->{theform},
user => $env->{'psgix.session'}{user_id},
offtoken_form => $env->{'psgix.session'}{offtoken},
get_old_token_form => $env->{'psgix.session'}{old_token},
);
my $onfirsnameapp;
my $onafterappurl //= ''; #here I set a empty value to avoid unitialized value
$onfirsnameapp = do {
if ($set{fromreferer} eq '/') {''}
elsif (grep(/(tapp\d{11})/, $set{fromreferer})) {'/greather_ten_digits'}
elsif (grep(/(tapp\d{10})/, $set{fromreferer})){ $1 if $set{fromreferer} =~ /.:?(tapp\d{10})\/?/}
else {$set{fromreferer} . '/not_root_notroute'}
};
my %add_sesion = (
equal_ten => sub { $env->{'psgix.session'}{equal_ten} = 'equal_ten' if grep( /(tapp\d{10})/, $onfirsnameapp ); },
current_request => sub { $env->{'psgix.session'}{current_request} = $onfirsnameapp; },
no_tkn_equal => sub { $env->{'psgix.session'}{no_tkn_equal} = 'no_tkn_equal'; },
menus_router_off => sub { $env->{'psgix.session'}{menus_router_off} = 'off work'; },
);
$add_sesion{equal_ten}->();
$add_sesion{current_request}->();
if($set{user}){
my ($code) = $router->match($env->{PATH_INFO});
if ( $set{onfirsnameapp} ne $set{token} ){
$onafterappurl = $1 if $set{fromreferer} =~ /.:?tapp\d+\/(.*)/;
$add_sesion{no_tkn_equal}->();
if (grep(/$onafterappurl/, @all_urls_names)
or (grep(/(tapp\d{10})/, $set{offtoken_form})
&& $onafterappurl eq '')
) {
delete $env->{'psgix.session'}{offtoken_form} if $onafterappurl eq '';
if( $onfirsnameapp eq $set{offtoken_form} || $onfirsnameapp eq $set{get_old_token_form} ) {
$add_sesion{menus_router_off}->();
return [
302,
[ Location => URI->new('/' . $set{token} . '/' . $onafterappurl) ],
[ '' ]
];
}
}
}; #here finish is not equal to token
return ["404", ["Content-Type" => "text/html"], ["Not Found, go to : <a href='/'>Home </a> " ] ] unless $code;
return $code->($env);
}
if ($set{fromreferer} ne '/'){
return ["401", ["Content-Type" => "text/html"],
[ $set{form} ]
];
}
return ["404", ["Content-Type" => "text/html"], [ $set{form} ]];
}
</code></pre>
<p>Is my refactoring good enough?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T14:41:54.433",
"Id": "384235",
"Score": "0",
"body": "I don't know what the technical definition of \"good enough\" would be, but it certainly appears to be much easier to read and maintain than what you started with."
},
{
... | [
{
"body": "<p>I'm not really comparing before and after. Without seeing the data that comes in that's a bit hard. Instead I'll focus on the new code.</p>\n\n<p>In general, a lot of your variables could benefit from clearer naming. If you use more than one word for a name, which is good, use underscores <code>_<... | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T16:02:15.253",
"Id": "199601",
"Score": "4",
"Tags": [
"comparative-review",
"regex",
"perl",
"session",
"url-routing"
],
"Title": "Assigning several variables from request URL using regexes"
} | 199601 |
<p>This is my first foray into (modern) Fortran in order to learn a bit more about the language, and I'm attempting the following problem: taking the path of an arbitrarily-sized text or binary file given as a command line argument, output to stdout the contents of the file in reverse (i.e. the first byte becomes the last). I would like to do this by reading the file sequentially into memory in chunks in one pass without using any seeks/rewinds etc.</p>
<p>It works (I think), and I'm interested in..</p>
<ul>
<li>better ways of working with arrays of pointers (to arrays), as used here with the dynamically sized array of <code>chunkptr</code>s. From what I've understood, it is necessary to make these additional types (<a href="https://stackoverflow.com/questions/8900336/arrays-of-pointers">Arrays of Pointers</a>) and access through means of <code>chunks(num_chunks)%ptr%chunk_array</code>. Perhaps there is some better approach?</li>
<li>how best to perform error handling (should note I forgot to add checks here after the (de)allocates, I would do this in a similar way with <code>stat</code> and <code>errmsg</code> variables, similar to as in <code>open</code> )</li>
<li>improvements related to code layout/organisation and use of subroutines and functions.</li>
</ul>
<p>Any other comments or ideas also greatly appreciated.</p>
<pre><code>! take a file and output it to stdout in reverse
program main
use :: iso_fortran_env
implicit none
!!! constants
integer, parameter :: CHUNK_SIZE = 1024
integer, parameter :: MIN_CHUNKS = 1
integer, parameter :: IN_FID = 10
!!! type definitions
type chunk
character, allocatable :: chunk_array(:)
endtype chunk
type chunkptr
type(chunk), pointer :: ptr
end type chunkptr
!!! locals
character(len=256) :: path, io_msg
integer :: total_bytes, num_chunks, i, status
type(chunkptr), allocatable :: chunks(:)
!!! begin program
call get_command_argument(1, path, status=status)
if (status /= 0) then
write (error_unit, *) "usage: ./reverse <file>"
call exit(1)
end if
allocate(chunks(MIN_CHUNKS))
! open, slurp file and close
open(IN_FID, file=path, access="stream", iostat=status, iomsg=io_msg, status="old")
if (status /= 0) then
write (error_unit, *) trim(io_msg)
call exit(1)
end if
call slurp_file(IN_FID, num_chunks, total_bytes, chunks)
close(IN_FID)
! output in reverse, and print debug info
call print_reversed(total_bytes, num_chunks, chunks)
write (error_unit, *) "reversed ", total_bytes, "bytes"
! free allocated resources
do i=num_chunks, 1, -1
deallocate(chunks(i)%ptr%chunk_array)
deallocate(chunks(i)%ptr)
end do
deallocate(chunks)
contains
subroutine slurp_file(fid, num_chunks, total, chunks)
integer :: fid, io_status = 0
integer, intent(out) :: total, num_chunks
type(chunkptr), allocatable :: chunks(:)
num_chunks = 0
total = 1
do
num_chunks = num_chunks + 1
call ensure_capacity(num_chunks, chunks)
allocate(chunks(num_chunks)%ptr)
allocate(chunks(num_chunks)%ptr%chunk_array(CHUNK_SIZE))
READ(fid, pos=total, iostat=io_status) chunks(num_chunks)%ptr%chunk_array
inquire(fid, pos=total)
if (io_status == iostat_end) exit
end do
total = total - 1
end subroutine slurp_file
subroutine ensure_capacity(capacity, chunks)
integer :: capacity
type(chunkptr), allocatable, intent(inout) :: chunks(:)
type(chunkptr), allocatable :: tmp(:)
if (capacity > size(chunks)) then
allocate( tmp( 2*size(chunks)) )
tmp(:size(chunks)) = chunks
call move_alloc(tmp, chunks)
end if
end subroutine ensure_capacity
subroutine print_reversed(total_bytes, num_chunks, chunks)
integer :: total_bytes, num_chunks, i, j
type(chunkptr), allocatable :: chunks(:)
! last chunk may not be a multiple of CHUNK_SIZE...
j = modulo(total_bytes, CHUNK_SIZE)
do i = num_chunks, 1, -1
do j=j, 1, -1
call fputc(output_unit, chunks(i)%ptr%chunk_array(j))
end do
! remaining chunks have size CHUNK_SIZE, however
j = CHUNK_SIZE
end do
end subroutine print_reversed
end program main
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T16:43:37.577",
"Id": "384089",
"Score": "0",
"body": "Any relation with this question: https://stackoverflow.com/questions/51328728/in-fortran-how-to-write-backward-from-a-file-to-another-file-by-blocks-of-line/51329093#51329093 ?"
... | [
{
"body": "<p>Congratulations. For a first try of Fortran that looks overall quite good, \nbut of course there are some things to improve.</p>\n\n<h1>General architecture</h1>\n\n<p>If you assume, that all chunks have always the same size, you could simply use a 2D character array. \nSince you have an array of ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T16:11:36.073",
"Id": "199602",
"Score": "4",
"Tags": [
"beginner",
"file",
"fortran"
],
"Title": "Reversing a file in Fortran"
} | 199602 |
<p>This seems to work fine however I'm sure there must be a neater way. The outcome should be:
If isHidden == true then call canHideAccount. canHideAccount returns a Single.
If isHidden != true then there is no need to call canHideAccount as it is a long asynchronous operation.
If canHideAccount returns false then the user should be shown an error dialog via getView().render().
If canHideAccount is true or isHidden was false then updateExternalAccount should be called. This is a network request that returns a Single.
If the request completes successfully then update the UI, if there is an error then notify the user.</p>
<p>Kicking off the chain with the Single.just(isHidden) seems a bit odd, but I cant see how to kick it off with the condition that it should only call canHideAccount if isHidden == true.</p>
<p>All comments and criticism are welcome.</p>
<pre><code>public void updateAccount(String accountId, boolean isHidden, String type) {
UpdatePostData accountUpdatePost = new UpdatePostData();
accountUpdatePost.accountId = accountId;
accountUpdatePost.isHidden = isHidden;
accountUpdatePost.type = type;
postAccountUpdate = Single.just(isHidden)
.subscribeOn(Schedulers.io())
.flatMap(hideAccount -> {
if (hideAccount) {
return canHideAccount(accountId);
} else {
return Single.just(true);
}
}).flatMap(canHideAccount -> {
if (canHideAccount) {
return getApi().updateAccount(accountUpdatePost);
} else {
return Single.error(new IllegalStateException());
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(response -> {
if (isViewAttached()) {
getView().render(State.accountUpdated);
}
}, error -> {
if (isViewAttached()) {
if (error instanceof IllegalStateException) {
getView().render(State.cannotHideAccount);
} else if (isAuthenticationError(error)) {
getView().render(State.reauthenticate);
} else {
getView().render(error);
}
}
GA.instance.error(error);
});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-13T08:36:58.317",
"Id": "388182",
"Score": "0",
"body": "1. starting with `Single.just()` seems perfectly fine for me - there's no other source of observables in what you've shown\n2. is `updateAccount()` called in an rx chain itself?\... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T16:15:22.127",
"Id": "199603",
"Score": "1",
"Tags": [
"java",
"android",
"rx-java"
],
"Title": "Conditionally perform asynchronous actions with RxJava"
} | 199603 |
<p>I already have some experience with Java and I'm used to modeling with a DDD approach. Therefore, now I'm beginning with JS and NodeJS and I'd like to know which is the best practice to design with a similar approach in Javascript (without ES6).</p>
<p>Here I have an example of what I'm trying to do, but I don't know if these is the better way. I appreciate some opinions.</p>
<pre><code>function Purchase(pCustomer, pOrders, pPayment, pTotal) {
let idPurchase = PurchaseId.purchaseId();
let customer = pCustomer;
let payment = pPayment;
let orders = pOrders;
let deliveryAddress;
let billingAddress;
let total = pTotal;
// Return an object exposed to the public
return {
setOrders: function (o) {
orders = o
},
setDeliveryAddress: function (address1, address2, zipCode, city) {
deliveryAddress = new Address(address1, address2, zipCode, city);
},
setBillingAddress: function (address1, address2, zipCode, city) {
billingAddress = new Address(address1, address2, zipCode, city);
},
getId: function () {
return idPurchase;
},
getOrders: function () {
return orders;
},
getCustomer: function () {
return customer;
},
toJSON: function () {
return {
idPurchase: idPurchase,
customerOnPurchase: customer.toJSON(),
deliveryAddress: deliveryAddress.toJSON(),
billingAddress: billingAddress.toJSON(),
total: total,
}
}
}
}
module.exports = Purchase;
</code></pre>
| [] | [
{
"body": "<p>Based on functions like <code>getId</code> and <code>toJSON</code>, it seems like you would naturally want to have a base class for your models. As such, it would make sense to write your functions in a way that support prototypical inheritance e.g.</p>\n\n<p><strong>Base Model</strong></p>\n\n<pr... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T17:05:02.507",
"Id": "199606",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"ddd"
],
"Title": "DDD model of a purchase in NodeJS"
} | 199606 |
<p>This is the question; <a href="https://www.hackerrank.com/challenges/ctci-ransom-note/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/ctci-ransom-note/problem</a></p>
<p>I have solved this hacker rank challenge but i feel like the complexity is pretty inefficient because i use two nested loops which causes my program to run in quadratic time, i guess... I am sure there there is a better solution. Can someone tell me a better solution than what i have done. I'd also appreciate if i could get any feedback regarding my coding style or if there should be made any improvement to make it look more readable, better etc. Thank you.</p>
<pre><code>function checkMagazine(magazine, note) {
let isRansom=true
note=note.split(' ')
magazine=magazine.split(' ')
for(let i of note){
if(isRansom===false){
console.log('No')
return false;
}
else{
for(let j of magazine){
if(i===j){
var index=magazine.indexOf(j)
if(index>-1){
magazine.splice(index,1)
}
isRansom=true;
break;
}
else{
isRansom=false;
}
}
}
}
if(isRansom){
return true
}
}
checkMagazine('give me one grand today night','give me one grand today')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T20:49:31.830",
"Id": "384128",
"Score": "0",
"body": "Welcome to Code Review! Links can rot. [Please include a description of the challenge here in your question.](http://meta.codereview.stackexchange.com/q/1993/41243)"
}
] | [
{
"body": "<p>Having a look at the HackerRank problem, the title is implying a HashTable might be a nice data structure to use for this problem (\"Hash Tables: Ransom Note\"). You might want to look up more about <a href=\"https://www.youtube.com/watch?v=MfhjkfocRR0\" rel=\"nofollow noreferrer\">the theory</a>,... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T17:06:26.410",
"Id": "199607",
"Score": "0",
"Tags": [
"javascript",
"strings"
],
"Title": "Hackerrank ransomnote"
} | 199607 |
<p>The macro below clears cells that do not match any cell in comparison to a range (a master list). It works on small file but is too slow to work for files with large ranges.</p>
<pre><code>Sub REMOVEINV()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating =False
Application.DisplayStatusBar =False
Application.EnableEvents =False
Dim Rng As Range, Dn As Range
Set Rng = Range("A2:A35524")'Range to match against
With CreateObject("scripting.dictionary")
.CompareMode = vbTextCompare
ForEach Dn In Rng:.Item(Dn.Value)= Empty:Next
Set Rng = Range("C1:DVC62600")' Range to clear
ForEach Dn In Rng
IfNot.exists(Dn.Value)Then Dn.ClearContents
Next Dn
EndWith
EndSub
</code></pre>
<p>The worksheet looks like so:</p>
<p><a href="https://imgur.com/a/usunRgo" rel="nofollow noreferrer"><img src="https://i.imgur.com/DJVSnPj.png" alt="screenshot"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T18:37:03.810",
"Id": "384108",
"Score": "0",
"body": "Welcome to Code Review. If your code is not working correctly, it is off-topic for this site. You might try [Stack Overflow](https://stackoverflow.com/help/how-to-ask) if you can... | [
{
"body": "<p>Okay, so good job giving both declared variables a type, a lot of people forget that!</p>\n\n<p>But, your naming is sort of weak and doesn't follow <a href=\"https://msdn.microsoft.com/en-us/library/1s46s4ew(v=vs.140).aspx\" rel=\"nofollow noreferrer\">Standard VBA naming conventions</a> have <cod... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T17:52:10.100",
"Id": "199612",
"Score": "-1",
"Tags": [
"vba",
"excel",
"time-limit-exceeded"
],
"Title": "Macro to clear cells that do not appear in a master list"
} | 199612 |
<p>I'm wondering if someone could take some time to review this script. I'm parsing through a list of points of any length and calculating the distance. I'm wondering how to make my code better/more efficient (something I'm working on). A sample input file would be like so: </p>
<pre><code>300.754178236262248 103.453277023380423 0,276.62980277988612 90.123295023340319 0,269.345711570634421 103.319531391674346 0,293.447811515317824 116.649513392506364 0,300.754178236262248 103.453277023380423 0
</code></pre>
<p>I'm not sure why the zeros are there; these are from the spacenet label csv's. </p>
<p>And this is my code: </p>
<pre><code>import math
def calc(x1, y1, x2, y2):
dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)
return dist
li = []
res = []
with open("/Users/jin/points.txt") as filestream:
for line in filestream:
temp = line.split(",") #splits by the comma in a single list
for i in temp:
temp = i.split(" ") #splits by spaces to individual lists of points
li.append(temp) #list of lists containing each point
# for item in li:
# x1 = item[1]
# y1 = item[0]
# for item in li:
# for pt in item:
# print pt
for index in range(len(li)-1):
one = li[index]
two = li[index+1]
x1 = float(one[0])
y1 = float(one[1])
x2 = float(two[0])
y2 = float(two[1])
res.append(calc(x1, y1, x2, y2))
print res
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Choose a better name than <code>calc()</code>. Something like <code>distance()</code> or <code>euclidean_distance()</code>.</p></li>\n<li><p>There is no need for the variable <code>temp</code>, just write\n<code>for i in line.split(\",\")</code></p></li>\n<li><p>The <code>for i in temp</... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T18:31:57.227",
"Id": "199614",
"Score": "2",
"Tags": [
"python",
"performance",
"array",
"parsing"
],
"Title": "Algorithm that parses through input of points and finds distance"
} | 199614 |
<p>This is my first attempt to do any hashing. I wanted to make a class that handled everything I needed to implement PBKDF2. The only question I have is am I ok to store the iterations in the database record or is this a bad practice? I was planning on creating a column to store salt, another for the hashed password, and possibly one for the amount of iterations. My thought with the iterations was that I read that it should increase every so often so when creating new users or they update their passwords it would pull the value to pass in from the database.</p>
<pre><code> public static byte[] GenerateSalt()
{
using (var randomNumberGenerator = new RNGCryptoServiceProvider())
{
var salt = new byte[32];
randomNumberGenerator.GetBytes(salt);
return salt;
}
}
public static byte[] HashPassword(byte[] password, byte[] salt, int iterations)
{
using (var rfc2898 = new Rfc2898DeriveBytes(password, salt, iterations))
{
return rfc2898.GetBytes(32);
}
}
public static bool CompareByteArrays(byte[] array1, byte[] array2)
{
if (array1.Length != array2.Length)
{
return false;
}
for (int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T20:27:44.117",
"Id": "384125",
"Score": "0",
"body": "use LINQ `SequenceEqual` rather than your `CompareByteArrays`. Simple to use, has the same \"short circuit\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": ... | [
{
"body": "<p>The code provided might fulfill the functionality however the API is hard to use.</p>\n\n<p>Passwords are usually strings and not binary (<code>byte[]</code>). It would also be nice that the salt could be generated automatically when you <code>hash</code> the password. That way you would call a si... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T18:50:43.360",
"Id": "199616",
"Score": "6",
"Tags": [
"c#"
],
"Title": "PBKDF2 C# Implementation"
} | 199616 |
<p>For <a href="https://www.codewars.com/kata/5b47ba689c9a7591e70001a3" rel="nofollow noreferrer">this</a> code challenge, I want to create a performant function that creates a rectangular N-dimensional array. (min_dim_size, max_dim_size) is the span size of every dimension. So rectangular_properties is a list with sizes of every dimension of the matrix. The matrix contains random integer values. Also I want the matrix to be immutable on every dimension.</p>
<p>Now I have this code:</p>
<pre><code>def random_hyperrectangular_matrix(dimensions, min_dim_size, max_dim_size):
rectangular_properties = [randint(min_dim_size, max_dim_size) for _ in range(dimensions)]
def recc2(dim):
if dim == 0:
return randint(0, 100)
return tuple([recc2(dim - 1) for _ in range(rectangular_properties[dim - 1])])
random_n_dimensional_matrix = recc2(dimensions)
return random_n_dimensional_matrix
</code></pre>
<p>When I run my code it seems that the generation of this matrix takes a huge amount of time. Is there a lack of performance in it?
Does the generation of tuple([...]) out of a list takes much time?</p>
| [] | [
{
"body": "<p>For something like this, <a href=\"http://www.numpy.org/\" rel=\"nofollow noreferrer\"><code>numpy</code></a> is probably unbeatable in terms of performance, since its underlying functions are implemented in C.</p>\n\n<p>In your case the implementation would be rather easy:</p>\n\n<pre><code>impor... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T20:56:01.717",
"Id": "199627",
"Score": "2",
"Tags": [
"python",
"performance",
"array",
"random"
],
"Title": "Generating random N-dimensional arrays"
} | 199627 |
<p>I'm doing a <a href="https://www.hackerrank.com/challenges/java-negative-subarray/problem" rel="nofollow noreferrer">coding challenge</a> that asks to count the number of contiguous subarrays that have a negative sum:</p>
<blockquote>
<p>A subarray of an <em>n</em>-element array is an array composed from a contiguous block of the original array'selements. For example, if <em>array = [1,2,3]</em>, then the subarrays are <em>[1], [2], [3], [1,2], [2,3], and [1,2,3]</em>. Something like <em>[1,3]</em> would not be a subarray as it's not a contiguous subsection of the original array.</p>
<p>The sum of an array is the total sum of its elements.
An array's sum is negative if the total sum of its elements is negative.
An array's sum is positive if the total sum of its elements is positive.
Given an array of integers, find and print its number of negative subarrays on a new line.</p>
</blockquote>
<p>I wrote this method and I'm trying to figure out the runtime for it but I'm not sure how to handle the loop and the recursion. Assume the length of array <code>a</code> is > 0.</p>
<pre><code>int numNegatives(int[] a){
if(a.length == 1){
if(a[0] < 0){ return 1; } else { return 0; }
}
int count = 0;
int sum = 0;
for(int i = 0; i < a.length; i++){ //N
sum += a[i];
if(sum < 0){ count++; }
}
count += numNegatives(Arrays.copyOfRange(a, 1, a.length));//N-1
return count;
}
</code></pre>
<p>The for loop will be O(N), since it loops over the array, and I believe the recursion call will then be O(N-1). Since the recursion call is outside the for loop, does that make the total O(N)? Most solutions to this challenge are two nested for loops with O(N²) runtime, and so I'm not sure if I actually made any improvement. Is it worse than O(N²)?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T23:24:46.113",
"Id": "384142",
"Score": "0",
"body": "Can you include more of the requirements of the coding challenge? Also, if it is publicly available on the Internet then a link can be included but ensure the main parts are cont... | [
{
"body": "<p>To get a rough idea, you could consider: how 'deep' does the recursion go, and for each layer, how much work has to be done? See for example the tree in <a href=\"http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap08.htm\" rel=\"nofollow noreferrer\">8.2 Worst-case partitioning</a>, as t... | {
"AcceptedAnswerId": "199663",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T22:05:37.447",
"Id": "199634",
"Score": "0",
"Tags": [
"java",
"performance",
"array",
"recursion"
],
"Title": "Counting contiguous subarrays with a negative sum"
} | 199634 |
<p>I implemented a method in Java that returns an array of integers with no duplicates (i.e. an array that has no repeated numbers).</p>
<p>My solution seems rather long. I would like to know of ways to improve it...</p>
<pre><code>public class IntArrayProcessor {
private int[] a;
public IntArrayProcessor(int[] a) {
this.a = a;
}
/**
*
* @return Array with no repeated integers.
*/
public int[] getSet() {
/* creates an array with the same entries and length as this.a */
int[] duplicateA = new int[this.a.length];
/* stores the number of repeated entries in array this.a */
int numberOfDuplicates = 0;
/* is the integer a duplicate or not? */
boolean isDuplicate;
/**
* Counts the number of duplicates in array this.a
*/
for (int i = 0; i < this.a.length; i++) {
duplicateA[i] = this.a[i];
}
for (int i = 0; i < duplicateA.length; i++) {
isDuplicate = false;
for (int j = i + 1; j < this.a.length; j++) {
if (duplicateA[i] == this.a[j]) {
isDuplicate = true;
}
}
if (isDuplicate) {
numberOfDuplicates++;
}
}
/*
* the noDuplicate array has the lenght of the this.a array minus the
* number of repeated entries
*/
int[] noDuplicate = new int[this.a.length - numberOfDuplicates];
/* to keep track of the noDuplicate indexes */
numberOfDuplicates = 0;
/**
* An array with no repeated numbers
*/
for (int i = 0; i < duplicateA.length; i++) {
isDuplicate = false;
for (int j = i + 1; j < this.a.length; j++) {
if (duplicateA[i] == this.a[j]) {
isDuplicate = true;
}
}
if (!(isDuplicate)) {
noDuplicate[numberOfDuplicates] = duplicateA[i];
numberOfDuplicates++;
}
}
return noDuplicate;
}
}
</code></pre>
| [] | [
{
"body": "<p>Wouldn't it be easier to just use:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static class IntArrayProcessor {\n\n private Integer[] arr;\n\n public IntArrayProcessor(Integer[] arr) {\n this.arr = arr;\n }\n\n public Integer[] unique() {\n final Set&l... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T22:28:34.277",
"Id": "199635",
"Score": "3",
"Tags": [
"java",
"performance"
],
"Title": "A method that returns an array with no duplicates"
} | 199635 |
<p>I am trying to learn Kotlin. I am coming from some background in Java. As a learning exercise, I wrote this simple program to summarize occurrences of a string by author email in a list of git repositories.</p>
<p>I am curious if I am approaching things in an idiomatic Kotlin way. Extension functions are awesome but I suspect it's something that I should not overuse.</p>
<p>I plan to make this a command line application and maybe use recursion to get the git repositories from the source directory without explicitly providing them. Before I get too far though I would like to see how I can improve what I have.</p>
<p>Any feedback is appreciated!</p>
<pre><code>import java.io.File
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
import kotlin.concurrent.thread
data class CommitSummary(
var author: String,
var regexString: String,
var count: Int)
data class Commit(
var commit: String = "",
var author: String = "",
var date: OffsetDateTime? = null,
var message: String = "")
fun main(args: Array<String>) {
val cmd = "git log --all --branches=* --remotes=*"
val matchStr = "d'{0,1}oh" //case-insensitive
val gitDir = "C:\\dev\\git\\"
arrayListOf("repo-1", "repo-2")
.forEach { repo ->
thread {
val log = cmd.run(File(gitDir + repo), createTempFile())
val commits = log.parseGitLog()
val summaries = commits.summarizeGitMessages(matchStr)
summaries.forEach { author, summary ->
println(String.format("repo: %s, author: %s, %s count: %s", repo, author, summary.regexString, summary.count))
}
}
}
}
fun File.parseGitLog(): ArrayList<Commit> {
return this.readLines().fold(arrayListOf()) { accumulated, current ->
val startingWord = current.split("\\s".toRegex())[0]
when (startingWord) {
"commit" -> accumulated.add(Commit(current.split("\\s".toRegex())[1]))
"Author:" -> accumulated.last().author = current.substring(current.indexOf("<") + 1, current.indexOf(">"))
"Date:" -> accumulated.last().date = current.split("Date:")[1].trim().parseGitDateString()
else -> accumulated.last().message += current.trim()
}
return@fold accumulated
}
}
fun ArrayList<Commit>.summarizeGitMessages(regexString: String): MutableMap<String, CommitSummary> {
val pattern = Pattern.compile(regexString, Pattern.MULTILINE or Pattern.CASE_INSENSITIVE)
return this.fold(mutableMapOf()) { acc, commit ->
val summary: CommitSummary = acc.getOrPut(commit.author) { CommitSummary(commit.author, regexString, 0) }
val match = pattern.matcher(commit.message)
while (match.find()) {
summary.count = summary.count.plus(1)
}
return@fold acc
}
}
// string extensions
fun String.run(workingDir: File, targetFile: File = File("C:\\dev\\tmpFile")): File {
if (targetFile.exists()) {
targetFile.delete()
}
ProcessBuilder(*split(" ").toTypedArray())
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.appendTo(targetFile))
.redirectError(ProcessBuilder.Redirect.INHERIT)
.start()
.waitFor(60, TimeUnit.MINUTES)
return targetFile
}
fun String.parseGitDateString(format: DateTimeFormatter = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy Z")): OffsetDateTime {
return OffsetDateTime.parse(this, format)
}
</code></pre>
| [] | [
{
"body": "<p>I have never used Kotlin, so I can't give a comprehensive review or comment particularly on specific idioms.</p>\n\n<p>I'm slightly bothered by this line, because null objects seems very much like a Java habit which Kotlin's paradigm generally tries to avoid. </p>\n\n<pre><code>var date: OffsetDat... | {
"AcceptedAnswerId": "199709",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-16T23:31:35.607",
"Id": "199638",
"Score": "2",
"Tags": [
"beginner",
"regex",
"git",
"kotlin"
],
"Title": "Kotlin program to summarize git commits by regex match"
} | 199638 |
<p>I was trying to design a chess game in Java. I have just started learning design patterns and am not sure if my approach here is right. Could you please suggest ways to better this design ? Below is how the code looks like :</p>
<pre><code>public enum SquareState {
OCCUPIED, EMPTY
}
</code></pre>
<pre><code>public enum Color {
BLACK, WHITE
}
</code></pre>
<pre><code>public class ChessBoard {
public static final int MAX_ROWS = 8;
public static final int MAX_COLS = 8;
public static final int NUM_SQUARES = 64;
private Square squares[][];
private List<Piece> whitePieces;
private List<Piece> blackPieces;
private Map<Square, Piece> occupiedSquares;
public Piece pieceAt(Square square) {
return occupiedSquares.get(square);
}
}
</code></pre>
<pre><code>//Square class
public class Square {
private int row, col;
private Color color;
private SquareState state;
}
</code></pre>
<pre><code>//Piece class -not an abstract class(do I need one, I already have PieceType)
public class Piece {
private PieceType type;
private Color color;
private Square position;
public void move(ChessBoard chessBoard, Square dest) {
//place the piece from its position to dest on the board
}
}
</code></pre>
<pre><code>public class Move {
private MoveType moveType; //undo operation will require move type
private Square source;
private Square destination;
private Piece sourcePiece; //at source
private Piece killedPiece; //at dest
private Move previous, next;
}
</code></pre>
<pre><code>public class Player {
private boolean isWhite;
private ChessBoard chessBoard;
private MovementGenerator movementGenerator;
private List<Piece> alivePieces;
public void makeMove() {
Piece chosenPiece = alivePieces.get(0);
List<Square> squares = movementGenerator.getPossibleMoves(chessBoard, chosenPiece);
chosenPiece.move(chessBoard, squares.get(0));
}
}
</code></pre>
<pre><code>public class MovementGenerator {
private MovementStrategy movementStrategy;
private MovementStrategyResolver movementStrategyResolver;
public MovementGenerator(MovementStrategy movementStrategy) {
this.movementStrategy = movementStrategy;
}
public List<Square> getPossibleMoves(ChessBoard chessBoard, Piece piece) {
return movementStrategyResolver.resolveStrategy(piece).getPossibleMoves(chessBoard, piece);
}
}
</code></pre>
<pre><code>public interface MovementStrategy {
public List<Square> getPossibleMoves(ChessBoard chessBoard, Piece piece);
}
</code></pre>
<pre><code>public class BishopMovementStrategy implements MovementStrategy{
@Override
public List<Square> getPossibleMoves(ChessBoard chessBoard, Piece piece) {
// TODO Auto-generated method stub
return null;
}
}
</code></pre>
<pre><code>public class KnightMovementStrategy implements MovementStrategy {
@Override
public List<Square> getPossibleMoves(ChessBoard chessBoard, Piece piece) {
// TODO Auto-generated method stub
return null;
}
}
</code></pre>
<pre><code>//A class to validate if move made by the player is a legal one
public class MovementValidator {
private MovementGenerator movementGenerator;
public boolean isValidMove(ChessBoard board, Move move) {
Square source = move.getSource();
Square dest = move.getDestination();
if (outsideBoard(source) || outsideBoard(dest))
return false;
// can't kill own pieces
if (board.pieceAt(source).getColor() == board.pieceAt(dest).getColor())
return false;
// if dest empty then proceed(should also check for checkmate condition
// in this case)
if (dest.getState() == SquareState.EMPTY)
return true;
// try to kill the opponent
List<Square> possiblePositions = movementGenerator
.getPossibleMoves(move.getSourcePiece());
if (!possiblePositions.contains(dest))
return false;
return true;
}
private boolean outsideBoard(Square square) {
int x = square.getRow();
int y = square.getCol();
if (x < 0 || x > 8 || y > 0 || y > 8)
return false;
return true;
}
}
</code></pre>
<p>Also, <code>isValidMove()</code> method of <code>MovementValidator</code> class should get called as soon as a player makes a move and should flag an error if the move made is illegal. How can I enforce this in the above code(given that validating the legality of a move shouldn't be the responsibility of the <code>Player</code> class)?</p>
<p>Alternatively, should I make <code>Piece</code> as a base class and extend it for <code>King</code>, <code>Queen</code>, <code>Bishop</code>, <code>Rook</code>, <code>Pawn</code> and let all these classes have reference to concrete <code>MovementStartegy</code> objects? Would that be a better design?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T04:11:52.710",
"Id": "384151",
"Score": "2",
"body": "Welcome to Code Review. This code is, in my opinion, too sketchy to review. Since it is unfinished, it's hard to tell what parts of the code are real, what parts are hypothetical... | [
{
"body": "<p>Your <code>Piece</code> class should be abstract and you should extend all pieces to it. You can get rid of your conventional <code>MovementValidator</code> and <code>MovementGenerator</code> classes this way. Shorter code is better as long as it's also done conventionally. </p>\n\n<pre><code>publ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T00:12:37.223",
"Id": "199639",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"design-patterns",
"chess"
],
"Title": "Object oriented design of chess game"
} | 199639 |
<p>I'm working on developing a small Ruby program to generate random data for a Neo4J database, including people, addresses, phone numbers, etc.</p>
<p>I'm a total beginner to Ruby, so I wanted to post my progress so far here to get it reviewed. I've just completed the "people" generating functionality.</p>
<p><strong>EntityFaker.rb</strong></p>
<pre><code>=begin
EntityFaker.rb
=end
require_relative "EntityFactory"
class Main
public
def self.generate_entities
puts "Generating entities..."
EntityFactory.test_function
end
generate_entities
end
</code></pre>
<p><strong>EntityFactory.rb</strong></p>
<pre><code>=begin
Entity-Factory
=end
require 'faker'
require 'pp'
require_relative 'Entities/Person'
class EntityFactory
@@person_array = []
public
def self.test_function()
generate_people(15)
end
private
def self.generate_people(number)
number.times do |n|
sex = Faker::Gender.binary_type
age = rand(18...65)
person = Person.new(
rand_bool ? Faker::Name.prefix : nil,
(sex == 'Male') ? Faker::Name.unique.male_first_name : Faker::Name.unique.female_first_name,
rand_bool ? Faker::Name.middle_name : nil,
Faker::Name.unique.last_name,
rand_bool ? Faker::Name.last_name : nil,
rand_bool ? Faker::Name.suffix : nil,
Time.now.to_i - age * 31556900, # dob in seconds since epoch
Person.random_height(sex),
Person.random_weight,
sex,
rand_bool ? sex : Faker::Gender.type,
Person.random_blood_type,
Faker::Color.color_name,
Faker::Color.color_name,
age,
Person.random_complexion,
Person.random_build,
Faker::Demographic.race
)
@@person_array.push(person)
end
pp @@person_array
end
private
def self.rand_bool
[true, false].sample
end
end
</code></pre>
<p><strong>Person.rb</strong></p>
<pre><code>=begin
Person.rb
=end
class Person
# http://chartsbin.com/view/38919
@@min_male_height = 166
@@max_male_height = 184
# http://chartsbin.com/view/38920
@@min_female_height = 147
@@max_female_height = 170
# For males and females combined, no data could be found seperating the two.
# https://en.wikipedia.org/wiki/Human_body_weight#Average_weight_around_the_world
@@min_weight = 49.591
@@max_weight = 87.398
# https://github.com/rubocop-hq/ruby-style-guide/issues/289
def initialize(
prefix,
given_name,
middle_name,
family_name,
maiden_name,
suffix,
dob,
height,
weight,
sex,
gender,
blood_type,
eye_colour,
hair_colour,
age,
complexion,
build,
race
)
@prefix = prefix
@given_name = given_name
@middle_name = middle_name
@family_name = family_name
@maiden_name = maiden_name
@suffix = suffix
create_full_name(prefix, given_name, middle_name, family_name, suffix)
@dob = dob
@height = height
@weight = weight
@sex = sex
@gender = gender
@blood_type = blood_type
@eye_colour = eye_colour
@hair_colour = hair_colour
@age = age
@complexion = complexion
@build = build
@race = race
end
private
def create_full_name(prefix, given_name, middle_name, family_name, suffix)
@legal_name = @full_name = [prefix, given_name, middle_name, family_name, suffix].compact.join(" ")
end
public
def self.random_weight
range(@@min_weight, @@max_weight)
end
public
def self.random_height(sex)
(sex == "Male") ? range(@@min_male_height, @@max_male_height) : range(@@min_female_height, @@max_female_height)
end
public
def self.random_complexion
# https://www.quora.com/What-are-all-the-different-types-of-skin-tones-or-complexions
["Type I", "Type II", "Type III", "Type IV", "Type V", "Type VI"].sample
end
public
def self.random_blood_type
# https://www.livescience.com/36559-common-blood-type-donation.html
["O-positive", "O-negative", "A-positive", "A-negative", "B-positive", "B-negative", "AB-positive", "AB-negative"].sample
end
public
def self.random_build
# https://www.cityofsacramento.org/-/media/Corporate/Files/Police/Resources/Suspect-Description-Form-SPD.pdf?la=en
["Slender", "Medium", "Heavy", "Fat", "Muscular"].sample
end
private
def self.range(min, max)
(rand * (max - min) + min).round(1)
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T04:24:09.893",
"Id": "384152",
"Score": "1",
"body": "Should the data be realistic? For example, height, weight, and build should be correlated. Also, weight and height in a population would each follow a normal distribution."
},
... | [
{
"body": "<p>I'm going to be reviewing your code largely for ruby style and best practices, rather then concrete improvements because it appears that you're unfamiliar with the way that ruby is typically written and are trying to shoehorn ideas from other languages (specifically, it looks like Java) into ruby ... | {
"AcceptedAnswerId": "199882",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T01:24:59.970",
"Id": "199641",
"Score": "3",
"Tags": [
"object-oriented",
"ruby",
"random"
],
"Title": "A Ruby script to generate random \"people\""
} | 199641 |
<p>I would be very grateful to get some thoughts on this toy-implementation of a trie that I wrote to practice my C++.</p>
<p>Some questions I have:</p>
<ul>
<li>Is my <code>create</code> member function idiomatic? What's the standard way avoid duplicated copy in the copy-constructor and assignment operator?</li>
<li>Is there a way that I could avoid using the virtual function <code>get_word</code>? It seems safer to use a virtual function (to avoid accessing undefined memory), but it I don't see why I shouldn't be able to lookup the address where <code>this->word</code> could reside.</li>
</ul>
<p>General tips are appreciated, not just answers to these questions.</p>
<p>Thanks!</p>
<pre><code>#include <unordered_map>
#include <string>
#include <iostream>
#include <stdexcept>
class TrieNode {
public:
std::unordered_map<char, TrieNode*> children;
TrieNode() {}
TrieNode(TrieNode const& trie_node) { create(trie_node); };
TrieNode& operator=(TrieNode const& rhs) {
if (&rhs != this) {
children.clear();
create(rhs);
}
return *this;
}
virtual ~TrieNode() {
for (auto const& it: children) {
delete it.second;
}
}
void create(TrieNode const&);
virtual std::string const& get_word() const { throw std::domain_error("get_word() called on non-terminal node."); };
};
class TerminalTrieNode: public TrieNode {
// terminal nodes represent full words
// they are pointed to by edges with key '\0'
public:
std::string word;
std::string const& get_word() const {return word;}
TerminalTrieNode(std::string word): word(word) {}
TerminalTrieNode(TrieNode const* terminal_trie_node) {
create(*terminal_trie_node);
word = terminal_trie_node->get_word();
}
};
void TrieNode::create(TrieNode const& trie_node) {
for (auto const& it: trie_node.children) {
if (it.first != '\0')
children[it.first] = new TrieNode(*it.second);
else
children[it.first] = new TerminalTrieNode(it.second);
}
}
class Trie {
private:
TrieNode root;
void apply_all(TrieNode const* node, void (function(std::string const&))) const {
// helper function for prefix_apply
// applies the given function to every word in the trie below the given word
auto it = node->children.find('\0');
if (it != node->children.end()) {
function(it->second->get_word());
}
for (auto const& c_it: node->children)
apply_all(c_it.second, function);
}
public:
void insert(std::string const& word) {
// add a new word to the trie
TrieNode* node = &root;
for (char const c: word) {
if (!node->children[c])
node->children[c] = new TrieNode();
node = node->children[c];
}
//mark as a terminal node
node->children['\0'] = new TerminalTrieNode(word);
}
bool contains(std::string const& word) const{
// set-membership test
TrieNode const* node = &root;
for (char const c: word) {
auto it = node->children.find(c);
if (it == node->children.end()) return false;
node = it->second;
}
return node->children.find('\0') != node->children.end();
}
void prefix_apply(std::string const& prefix, void (function(std::string const&))) const {
// Apply the given function to every word in the trie that has the given prefix
TrieNode const* node = &root;
for (char const c: prefix) {
auto it = node->children.find(c);
if (it == node->children.end()) return;
node = it->second;
}
apply_all(node, function);
}
};
int main(int argc, char** argv) {
Trie trie;
trie.insert("apple");
trie.insert("app");
trie.insert("apl");
trie.insert("back");
trie.insert("appl");
Trie new_trie = trie;
new_trie.prefix_apply("app", [](std::string const& s) {std::cout << s << '\n';});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T02:32:19.513",
"Id": "384149",
"Score": "0",
"body": "To answer the second question: `static_cast<TerminalTrieNode*>(_)->word` works."
}
] | [
{
"body": "<p>Looking at this code, I have several remarks, let me start with your questions:</p>\n\n<h1>Is my create member function idiomatic?</h1>\n\n<p>No, I barely see it. Mostly because it doesn't add value. Either classes are small enough so it doesn't matter, or copy/assign ain't supported, or it can be... | {
"AcceptedAnswerId": "199844",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T01:56:36.670",
"Id": "199643",
"Score": "4",
"Tags": [
"c++",
"c++11",
"polymorphism",
"trie"
],
"Title": "Simple trie class in C++"
} | 199643 |
<p>I've written a simple python web scraper that parses text from an html table and stores the scraped data in List of dictionaries. The code works and doesn't seem to have any glaring issues performance-wise, but I only used the bare bones modules of lxml and requests. </p>
<p><strong>Is there a more efficient/elegant way to condense the script or to improve the runtime?</strong> </p>
<p>The code is below:</p>
<pre><code>import requests
from lxml.html import fromstring
import pprint
import re
url = "https://jobs.mo.gov/content/missouri-warn-notices-py-2017"
response = requests.get(url)
root = fromstring(response.content)
table = root.xpath('.//*[@summary="Missouri WARN Notices PY 2016"]')[0]
tableRes = []
columnHeaders = table.xpath(".//tr//th/span/text()")
for row in table.xpath(".//tr")[1:]:
i = 0
rowDict = {}
for col in row.xpath(".//td"):
if i != 1:
rowDict[columnHeaders[i]] = re.sub(r"[\n\t]*", "","".join(col.xpath(".//text()")).replace(u'\xa0', u' '))
else:
rowDict[columnHeaders[i]] = re.sub(r"[\n\t]*", "","".join(col.xpath(".//a/text()")).replace(u'\xa0', u' '))
i += 1
tableRes.append(rowDict)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(tableRes)
</code></pre>
| [] | [
{
"body": "<p>Looked at your script and found a few things that can be improved in terms of code quality as well as performance. On my local machine i was able to cut the runtime in half with the code changes.</p>\n\n<ol>\n<li><p>The default separator value of <code>str.split()</code> is whitespace character(s)... | {
"AcceptedAnswerId": "200058",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T02:47:22.657",
"Id": "199644",
"Score": "2",
"Tags": [
"python",
"html",
"web-scraping",
"lxml"
],
"Title": "Parsing scraped data from html table"
} | 199644 |
<p>I have a question that is similar in spirit to this <a href="https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3">previously asked question</a>. Nonetheless, I can't seem to figure out a suitable solution. </p>
<p><strong>Input</strong>: I have CSV data that looks like (<strong><em>FICTIONAL PATIENT DATA</em></strong>)</p>
<pre><code>id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost
1000000001,Smith,James,AMBIEN,100
1000000002,Garcia,Maria,AMBIEN,200
1000000003,Johnson,James,CHLORPROMAZINE,1000
1000000004,Rodriguez,Maria,CHLORPROMAZINE,2000
1000000005,Smith,David,BENZTROPINE MESYLATE,1500
</code></pre>
<p><strong>Output</strong>: from this I simply need to output each drug, the total cost which is summed over all prescriptions and I need to get a count of the unique number of prescribers. </p>
<pre><code>drug_name,num_prescriber,total_cost
AMBIEN,2,300.0
CHLORPROMAZINE,2,3000.0
BENZTROPINE MESYLATE,1,1500.0
</code></pre>
<p>I was able to accomplish this pretty easily with Python. However, when I try to run my code with a much larger (1gb) input, my code does not terminate in a reasonable amount of time.</p>
<pre><code>import sys, csv
def duplicate_id(id, id_list):
if id in id_list:
return True
else:
return False
def write_file(d, output):
path = output
# path = './output/top_cost_drug.txt'
with open(path, 'w', newline='') as csvfile:
fieldnames = ['drug_name', 'num_prescriber', 'total_cost']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for key, value in d.items():
print(key, value)
writer.writerow({'drug_name': key, 'num_prescriber': len(value[0]), 'total_cost': sum(value[1])})
def read_file(data):
# TODO: https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3
drug_info = {}
with open(data) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
next(readCSV)
for row in readCSV:
prescriber_id = row[0]
prescribed_drug = row[3]
prescribed_drug_cost = float(row[4])
if prescribed_drug not in drug_info:
drug_info[prescribed_drug] = ([prescriber_id], [prescribed_drug_cost])
else:
if not duplicate_id(prescriber_id, drug_info[prescribed_drug][0]):
drug_info[prescribed_drug][0].append(prescriber_id)
drug_info[prescribed_drug][1].append(prescribed_drug_cost)
else:
drug_info[prescribed_drug][1].append(prescribed_drug_cost)
return(drug_info)
def main():
data = sys.argv[1]
output = sys.argv[2]
drug_info = read_file(data)
write_file(drug_info, output)
if __name__ == "__main__":
main()
</code></pre>
<p>I am having trouble figuring out how to refactor this to handle the larger input and was hoping someone on CodeReview could take a look and provide me some suggestions for how to solve this problem. Additionally, if you happen to see any other issues, I'd love the feedback. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T11:23:22.267",
"Id": "384205",
"Score": "2",
"body": "This code is excessively long. Reduce the length first, worry about optimising afterwards. I’m not fluent with numpy but solving this should require **no more than ten lines of c... | [
{
"body": "<p>One very important way to speed up the processing of large files like this is <strong>streaming:</strong> make sure you discard processed information as soon as possible. One simple way of doing this is a quick piece of preprocessing. You can do this in Python as well, but using highly optimised s... | {
"AcceptedAnswerId": "199661",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T03:57:28.140",
"Id": "199646",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"csv"
],
"Title": "Aggregate prescriptions per drug in a CSV file"
} | 199646 |
<h1>The Problem</h1>
<p>Create a javascript method which combines each string of two immutable lists with each other:</p>
<pre><code>const a1 = new List(['a', 'b', 'c']);
const a2 = new List(['x', 'y', 'z']);
const combinedArray = combineArrays(a1,a2);
=> combinedArray: ['a-x', 'a-y', 'a-z', 'b-x', 'b-y', 'b-z', 'c-x', 'c-y', 'c-z']
</code></pre>
<h1>My Solution</h1>
<pre><code>import { List } from 'immutable';
const combineArray = (arrayA = new List([]), arrayB = new List([])) => {
if (arrayA.count() === 0) {
return arrayB;
}
if (arrayB.count() === 0) {
return arrayA;
}
let combinations = new List([]);
combinations = arrayA.reduce((accum, value) => {
if (value) {
return accum.push(arrayB.reduce((accum2, value2) => {
if (value2) {
return accum2.push(`${value}-${value2}`);
}
return value;
}, new List([])));
}
return accum;
}, new List([]));
return combinations.flatten(true);
};
export default combineArray;
</code></pre>
<h1>Updated Solution</h1>
<p>based on @bergis response I updated the implementation</p>
<pre><code>import { List } from 'immutable';
const combineArray = (arrayA = new List([]), arrayB = new List([])) => {
if (arrayA.isEmpty()) { return arrayB; }
if (arrayB.isEmpty()) { return arrayA; }
return arrayA.flatMap(valueA => (
arrayB.map(valueB => (
`${valueA}-${valueB}`
))
));
};
export default combineArray;
</code></pre>
<h1>My Question</h1>
<ul>
<li>Would you have concerns regarding performance? (We are talking about a maximum of 10 items per list)</li>
<li>How would you improve the implementation?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T14:28:11.973",
"Id": "384156",
"Score": "0",
"body": "What's the point of checking `if (value)`? Also you have a mistake in the inner callback, needs to be `return accum2` not `return value`."
},
{
"ContentLicense": "CC BY-S... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-29T12:26:27.513",
"Id": "199650",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"immutable.js"
],
"Title": "Combining immutable lists of strings with each other"
} | 199650 |
<p>In my scenario I have list of object in C# code and need to be converted into JavaScript object. But there are certain condition, where the value of the object might be dynamic based on certain key.</p>
<p>I have a following method which will return string as JavaScript Object.</p>
<pre><code>public string ItemToJson()
{
List < Item > itemObj = GetItemList();
if (itemObj.Count > 0)
{
StringBuilder sbObj = new StringBuilder();
sbObj.Append("<script> let Items = {");
var len = itemObj.Count;
for (int i = 0; i < len; i++)
{
sbObj.Append(itemObj[i].Key);
sbObj.Append(": { placeholder : \" ");
sbObj.Append(itemObj[i].Placeholder);
sbObj.Append(" \" , value : \" ");
if (itemObj[i].Key == "Photo")
{
sbObj.Append(GetImage());
}
else
{
sbObj.Append(itemObj[i].Value);
}
sbObj.Append(" \" } ");
if (i < len - 1)
sbObj.Append(",");
}
sbObj.Append("} </script>");
return sbObj.ToString();
}
else
{
return string.Empty;
}
}
</code></pre>
<p>Here is the complete code of working console app.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace String_Builder_Demo
{
class Program
{
public List<Item> GetItemList()
{
List<Item> items = new List<Item>
{
new Item(){ Key = "FirstName", Placeholder = "##FirstName##", Value="John" },
new Item(){ Key = "LastName", Placeholder = "##LastName##", Value="Doe"},
new Item(){ Key = "Email", Placeholder = "##Email##", Value="john.doe@domain.com " },
new Item(){ Key = "Address", Placeholder = "##Address##", Value="Kathmandu" },
new Item(){ Key = "Photo", Placeholder = "##Photo##", Value=""}
};
return items;
}
public string GetImage()
{
return "http://via.placeholder.com/350x150";
}
static void Main(string[] args)
{
Program obj = new Program();
Console.WriteLine(obj.ItemToJson());
Console.ReadLine();
}
public string ItemToJson()
{
List<Item> itemObj = GetItemList();
if (itemObj.Count > 0)
{
StringBuilder sbObj = new StringBuilder();
sbObj.Append("<script> let Items = {");
var len = itemObj.Count;
for (int i = 0; i < len; i++)
{
sbObj.Append(itemObj[i].Key);
sbObj.Append(": { placeholder : \" ");
sbObj.Append(itemObj[i].Placeholder);
sbObj.Append(" \" , value : \" ");
if (itemObj[i].Key == "Photo")
{
sbObj.Append(GetImage());
}
else
{
sbObj.Append(itemObj[i].Value);
}
sbObj.Append(" \" } ");
if (i < len - 1)
sbObj.Append(",");
}
sbObj.Append("} </script>");
return sbObj.ToString();
}
else
{
return string.Empty;
}
}
}
public class Item
{
public string Placeholder { get; set; }
public string Value { get; set; }
public string Key { get; set; }
}
}
</code></pre>
<p>The above mention code will return following string.</p>
<pre class="lang-js prettyprint-override"><code><script>
let Items = {
FirstName:
{
placeholder: " ##FirstName## ",
value: " John "
},
LastName:
{
placeholder: " ##LastName## ",
value: " Doe "
},
Email:
{
placeholder: " ##Email## ",
value: " john.doe@domain.com "
},
Address:
{
placeholder: " ##Address## ",
value: " Kathmandu "
},
Photo:
{
placeholder: " ##Photo## ",
value: " http://via.placeholder.com/350x150 "
}
}
</script>
</code></pre>
<p>How can I optimize the above code and eliminate the <code>if else</code> condition from <code>ItemToJson()</code> method?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T06:21:08.653",
"Id": "384168",
"Score": "0",
"body": "Is there any particular reason you're doing this yourself instead using json.net?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T07:04:19.797",
... | [
{
"body": "<p><strong>Had to put it here as it was getting too big for comment.</strong></p>\n\n<p>You definitely need to evaluate that condition based on code you have posted. So, the if/else construct is fine. Alternate options will need you to split the list into separate ones which will be more costly opera... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T05:26:30.877",
"Id": "199651",
"Score": "2",
"Tags": [
"c#",
"performance",
"strings",
"json"
],
"Title": "Converting objects into JSON and using the StringBuilder"
} | 199651 |
<p>I have an approach that seems to work though I feel like I must be misusing something to achieve it. I am implementing a keyword matching algorithm to a Java 8 <code>IntStream</code>. The goal is to walk over a stream of <code>char</code> values (created by calling <code>.chars()</code> on an input string called <code>sentence</code>). If a keyword matches it is returned with its replacement value otherwise the original characters are returned unmodified. The code I have written so far looks like this: The <code>Replacer</code> is implemented as a <code>Consumer<Character></code> with some stateful properties:</p>
<pre><code>class Replacer implements Consumer<Character> {
StringBuffer out;
StringBuffer buffer;
KeywordTrieNode current_keyword_trie_node;
KeywordTrieNode keyword_trie_root;
public Replacer(KeywordTrieNode keyword_trie_root) {
this.keyword_trie_root = keyword_trie_root;
this.current_keyword_trie_node = keyword_trie_root;
this.out = new StringBuffer();
this.buffer = new StringBuffer();
}
@Override
public void accept(Character c) {
KeywordTrieNode node = current_keyword_trie_node.get(c);
if (node != null) {
buffer.append(c);
current_keyword_trie_node = node;
} else {
String keyword = current_keyword_trie_node.get();
if (keyword != null) {
out.append(keyword);
} else {
out.append(buffer);
}
out.append(c);
buffer = new StringBuffer();
current_keyword_trie_node = this.keyword_trie_root;
}
}
@Override
public String toString() {
// Flush the buffer
String keyword = current_keyword_trie_node.get();
if (keyword == null) {
out.append(buffer);
} else {
out.append(keyword);
}
return out.toString();
}
}
</code></pre>
<p>Then to use this I have this function:</p>
<pre><code>public String replace(String sentance) {
return replace(sentance.chars());
}
public String replace(IntStream stream) {
Replacer replacer = new Replacer(this.keyword_trie_root);
stream.mapToObj(c -> (char) c).forEachOrdered(replacer);
return replacer.toString();
}
</code></pre>
<p>Here the <code>String</code> is converted into a <code>IntStream</code>, the <code>stream</code> is then mapped into a stream of <code>char</code> values (which are autoboxed into <code>Character</code> which is needed for the underlying <code>Map</code> inside the <code>keyword_trie_root</code>). Then the <code>replacer</code> is passed to <code>forEachOrdered</code> allowing it to see each character and build a bigger and bigger <code>StringBuffer</code> until it's <code>toString()</code> is invoked (performing one final buffer flush). This doesn't feel like the correct use of Java streams but I'm hitting a bit of a wall when trying to reimagine this as a <code>Combiner</code> which I think is the correct way to solve this problem. Any ideas?</p>
| [] | [
{
"body": "<h2>Bug:</h2>\n\n<p>Calling <code>toString</code> repeatedly will append the last keyword (or the buffer) multiple times. This is not really in line with how this should work.</p>\n\n<h2>Conventions:</h2>\n\n<p>Java coding conventions state that member names should be <code>lowerCamelCase</code>. th... | {
"AcceptedAnswerId": "199677",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T06:42:24.823",
"Id": "199653",
"Score": "2",
"Tags": [
"java",
"stream"
],
"Title": "Idiomatic approach to applying a keyword replace algorithm to a Java 8 Stream"
} | 199653 |
<p>Another exercise in Scala in which the goal is to find the target position as fast as possible. The initial input provides the grid size and the initial position. Each turn, this code provide a new position using <code>println</code> and the direction to the target is given back as a string ("UR" up-right, "DL" down-left, etc). The exercise does not require to end the infinite loop.</p>
<pre><code>import math._
import scala.util._
object Player extends App {
def getDirection(input: String): (Int, Int) = {
input match {
case "U" => (0, -1)
case "UR" => (1, -1)
case "R" => (1, 0)
case "DR" => (1, 1)
case "D" => (0, 1)
case "DL" => (-1, 1)
case "L" => (-1, 0)
case "UL" => (-1, -1)
}
}
def findNewRelativePositionOnAxis(direction: Int, min : Int, max : Int, current : Int) : Int = {
direction match {
case 1 => (max - current + 1 ) / 2
case -1 => if(current == 1) -1 else (min - current - 1 ) / 2 //edge case for when the goal is at position 0
case _ => 0
}
}
def loop(x: Int, y: Int, minX: Int, minY: Int, maxX: Int, maxY: Int): Nothing = {
val goaldir = getDirection(readLine)
//Update min and max values to narrow down the search
val newMaxX = if(goaldir._1 == -1) x else maxX
val newMaxY = if(goaldir._2 == -1) y else maxY
val newMinX = if(goaldir._1 == 1) x else minX
val newMinY = if(goaldir._2 == 1) y else minY
//Compute the next position
val newX = x + findNewRelativePositionOnAxis(goaldir._1, newMinX, newMaxX, x)
val newY = y + findNewRelativePositionOnAxis(goaldir._2, newMinY, newMaxY, y)
//Send the result
println(newX + " " + newY)
loop(newX, newY, newMinX, newMinY, newMaxX, newMaxY)
}
// w: width of the building.
// h: height of the building.
val Array(width, height) = for(i <- readLine split " ") yield i.toInt
val Array(x0, y0) = for(i <- readLine split " ") yield i.toInt
loop(x0, y0, 0, 0, width, height)
}
</code></pre>
| [] | [
{
"body": "<p>Your code can be much improved by adding a few data structures:</p>\n\n<pre><code>case class Point(x: Int, y: Int)\ncase class Interval(min: Int, max: Int)\ncase class Dimensions(horizontal: Interval, vertical: Interval)\ncase class Direction(relX: Int, relY: Int)\n</code></pre>\n\n<p>Further you ... | {
"AcceptedAnswerId": "199977",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T07:42:52.753",
"Id": "199660",
"Score": "1",
"Tags": [
"programming-challenge",
"scala",
"binary-search"
],
"Title": "Binary search in Scala"
} | 199660 |
<p>I did some looking around and found some more topics on how to use the $stmt->bind_param function inside another function or class what means the reference variables have to be sort of passed on. With the information, I obtained I was able to create a class that allows a mysqli prepared statement with fewer lines in the code itself (faster coding) and allows for error checking in the prepared statement query. I'd like to know if this method is useful and "correct" as far as code can be correct. I've planned to add more of the prepared statement's functions to the class later on but for now, this is it. </p>
<pre><code>class db_prepare {
public function __construct($query = false) {
global $DB;
$this->stmt = $DB->prepare($query);
$this->error = false;
if($this->stmt == false) {
$this->error = true;
echo $mysqli->error;
}
}
public function bind_param($type, &...$args) {
if($this->error == false) {
call_user_func_array(array($this->stmt, "bind_param"), array_merge([$type], $args));
}
}
public function get_result() {
if($this->error == false) {
$this->stmt->execute();
return $this->stmt->get_result();
}
}
public function execute() {
if($this->error == false) {
return $this->stmt->execute();
}else {
return false;
}
}
public function get_result_array() {
$array = array();
if($this->error == false) {
$this->stmt->execute();
$rows = $this->stmt->get_result();
while($row = $rows->fetch_array()) {
$array[] = $row;
}
}
return $array;
}
public function close() {
$this->stmt->close();
}
}
</code></pre>
<p>This means i can call upon the class in a way like this:</p>
<pre><code>$query = "SELECT * FROM `reactions` WHERE `date` = ? AND `author` = ?";
$stmt = new db_prepare($query);
$stmt->bind_param("ss", $date, $author);
$date = '2018-17-07';
$author = 'Admin';
$results = $stmt->get_result();
$date = '2018-17-07';
$author = 'Mike';
$results = $stmt->get_result();
$stmt->close();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T09:07:02.363",
"Id": "384484",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>Given the main added value in this class is a <em>sort</em> of error handler, I would suggest to make <a href=\"https://phpdelusions.net/mysqli/error_reporting\" rel=\"nofollow noreferrer\">a little addition to your <em>connection code</em></a> that will make mysqli report errors by itself, which... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T10:19:55.543",
"Id": "199669",
"Score": "1",
"Tags": [
"php",
"mysqli"
],
"Title": "PHP Prepare statement shortcut class"
} | 199669 |
<p>I'm currently working through the google FooBar challenge, and I'm on the third level, in which I have to find the distance between the top left and bottom right points on a grid. The grid is filled by ones and zeros, with zeros representing crossable spaces and ones representing non-crossable spaces (a typical grid would look like this):</p>
<pre><code>[[0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0]]
</code></pre>
<p>In each grid you must find the length (int) of the shortest route with from the top left to bottom right, but are allowed to replace any singular one with a zero. My code (shown below) solves through these grids, but doesn't run fast enough to satisfy google's runtime limit. I'd greatly appreciate any advice on how to shorten or make more efficient my code. An in-depth explanation of each class method is below the code itself.</p>
<pre><code>from itertools import chain
from copy import copy, deepcopy
class Map(object):
def __init__(self, map):
self.orig_map = deepcopy(map)
self.map = map
self.current_point = None
self.current_neighbors = None
self.entrance = (0, 0)
self.exit = (len(self.map[0])-1, len(self.map)-1)
self.zero_relations = None
self.ones_positions = None
self.min_path = None
self.min_path_length = None
def check_neighbors(self):
self.current_neighbors = {
"l": {
"value": 1 if (self.current_point[0] == 0) else self.map[self.current_point[1]][self.current_point[0] - 1],
"coord": (self.current_point[0]-1, self.current_point[1])
},
"u": {
"value": 1 if (self.current_point[1] == 0) else self.map[self.current_point[1] - 1][self.current_point[0]],
"coord": (self.current_point[0], self.current_point[1]-1)
},
"r": {
"value": 1 if (self.current_point[0] == len(self.map[0]) - 1) else self.map[self.current_point[1]][
self.current_point[0] + 1],
"coord": (self.current_point[0] + 1, self.current_point[1])
},
"d": {
"value": 1 if (self.current_point[1] == len(self.map)-1) else self.map[self.current_point[1] + 1][self.current_point[0]],
"coord": (self.current_point[0], self.current_point[1]+1)
}
}
def check_value(self, point):
return self.map[point[1]][point[0]]
def map_zero_relations(self):
all_relations = {}
for index, value in enumerate(list(chain.from_iterable(self.map))):
point = (index%len(self.map), int(index/len(self.map)))
self.current_point = point
self.check_neighbors()
neighbors = self.current_neighbors
all_relations[point] = [neighbors[neighbor]["coord"] for neighbor in neighbors if (neighbors[neighbor]["value"]==0 and self.check_value(point)==0)]
self.zero_relations = all_relations
self.current_point = None
def find_min_path(self, start, end, path=[]):
path = path + [start]
if start == end:
self.min_path = path
return
if start not in self.zero_relations:
return None
shortest = None
for node in self.zero_relations[start]:
if node not in path:
newpath = self.find_min_path(node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
def locate_passable_ones(self):
points = [(index%len(self.map), int(index/len(self.map))) for index, value in enumerate(list(chain.from_iterable(self.map)))]
ones_positions = [point for point in points if self.check_value(point) == 1]
for point in copy(ones_positions):
self.current_point = point
self.check_neighbors()
if [self.current_neighbors[neighbor]["value"] for neighbor in self.current_neighbors].count(1) >= 3:
ones_positions.remove(point)
self.current_point = None
self.ones_positions = ones_positions
def find_escape_min_length(self):
self.find_min_path(self.entrance, self.exit)
current_min_path = self.min_path
orig_map = self.orig_map
for wall in self.ones_positions:
self.map = deepcopy(orig_map)
self.map[wall[1]][wall[0]] = 0
self.map_zero_relations()
self.find_min_path(self.entrance, self.exit)
if current_min_path is None:
current_min_path = self.min_path
continue
if len(self.min_path) < len(current_min_path):
current_min_path = self.min_path
self.map = orig_map
self.map_zero_relations()
self.min_path = current_min_path
self.min_path_length = len(current_min_path)
def answer(n):
foo = Map(n)
foo.map_zero_relations()
foo.locate_passable_ones()
foo.find_escape_min_length()
return foo.min_path_length
</code></pre>
<p>NOTE: grid is read with the top left as (0,0) and the bottom right as (max_x, max_y).</p>
<h3>Map Methods</h3>
<p><code>Map.check_neighbors()</code> -
sets the value of Map.current_neighbors to a dict with the value and coordinates of the left, right, upper, and lower points from Map.current_point</p>
<p><code>Map.check_value()</code> -
returns the value of a point given its coordinate on the grid</p>
<p><code>Map.map_zero_relations()</code> -
sets Map.zero_relations to a dict with each zero on the grid and a list of the coordinates of all zeros that point is connected to. The dict for above grid would be:</p>
<pre><code>{(0, 0): [(1, 0)],
(0, 1): [],
(0, 2): [(1, 2), (0, 3)],
(0, 3): [(0, 2), (0, 4)],
(0, 4): [(0, 3), (0, 5)],
(0, 5): [(0, 4), (1, 5)],
(1, 0): [(0, 0), (2, 0)],
(1, 1): [],
(1, 2): [(0, 2), (2, 2)],
(1, 3): [],
(1, 4): [],
(1, 5): [(0, 5), (2, 5)],
(2, 0): [(1, 0), (3, 0)],
(2, 1): [],
(2, 2): [(1, 2), (3, 2)],
(2, 3): [],
(2, 4): [],
(2, 5): [(1, 5), (3, 5)],
(3, 0): [(2, 0), (4, 0)],
(3, 1): [],
(3, 2): [(2, 2), (4, 2)],
(3, 3): [],
(3, 4): [],
(3, 5): [(2, 5), (4, 5)],
(4, 0): [(3, 0), (5, 0)],
(4, 1): [],
(4, 2): [(3, 2), (5, 2)],
(4, 3): [],
(4, 4): [],
(4, 5): [(3, 5), (5, 5)],
(5, 0): [(4, 0), (5, 1)],
(5, 1): [(5, 0), (5, 2)],
(5, 2): [(4, 2), (5, 1)],
(5, 3): [],
(5, 4): [],
(5, 5): [(4, 5)]}
</code></pre>
<p><code>Map.find_min_path()</code> - If unobstructed path between start and end is possible, sets Map.min_path to a list of coords you'd travel over in the shortest path. If not possible, sets Map.min_path to None.</p>
<p><code>Map.locate_passable_ones()</code> - Sets Map.ones_positions a list of coordinates with the value of 1 that should be removed and tested to find shorter routes in Map.find_escape_min_length(). Ones with 3 or more neighboring ones are removed.</p>
<p><code>Map.find_escape_min_length()</code> - Finds shortest path without removing any ones. Then tries finding shortest path while individually replacing each point in Map.ones_positions with zeros. Sets self.min_path and self.min_path_length to the shortest path and path length found.</p>
<h3>Map Attributes</h3>
<p><code>Map.orig_map</code> - Stores original state of the grid</p>
<p><code>Map.map</code> - Stores current state of the grid</p>
<p><code>Map.current_point</code> - Stores current coordinate (used in Map.check_neighbors)</p>
<p><code>Map.current_neighbors</code> - Stores the current point's neighbor's coords and values</p>
<p><code>Map.entrance</code> - stores the grid start point (always (0,0) )</p>
<p><code>Map.exit</code> - stores the grid end point ( (max_x, max_y) )</p>
<p><code>Map.zero_relations</code> - stores dict with all zeros and connected zeros on grid</p>
<p><code>Map.ones_positions</code> - stores list of ones to be removed and tested for shorter path lengths</p>
<p><code>Map.min_path</code> - stores current minimum path from start to end of grid</p>
<p><code>Map.min_path_length</code> - stores length of minimum path</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T12:28:18.770",
"Id": "384215",
"Score": "0",
"body": "I've modified the formatting somewhat to increase readability. What Python version did you write this for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "20... | [
{
"body": "<h2>SPOILER ALERT</h2>\n\n<p>This puzzle is a very slight modification of the well-known <a href=\"https://en.wikipedia.org/wiki/Approximate_string_matching\" rel=\"nofollow noreferrer\">fuzzy string matching</a> problem, which can be solved efficiently using (what else?) <a href=\"https://en.wikiped... | {
"AcceptedAnswerId": "199707",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T10:48:42.347",
"Id": "199672",
"Score": "11",
"Tags": [
"python",
"programming-challenge",
"python-2.x",
"time-limit-exceeded",
"pathfinding"
],
"Title": "Google FooBar \"Prepare The Bunnies Escape\""
} | 199672 |
<p>Question might be more appropriate in StackOverflow, however I'd also like a review.</p>
<p>I'd like to make my code inline as I feel like this could be possible, I'm just not sure how.</p>
<pre><code>int highestWeightOfParcel = 0;
if (collo.WeightGrammes.HasValue)
{
if (collo.WeightGrammes > highestWeightOfParcel)
{
highestWeightOfParcel = collo.WeightGrammes.Value;
}
}
</code></pre>
<p>Could I apply the same technique as this? :</p>
<pre><code>int heigth = collo.HeightMm.HasValue ? collo.HeightMm.Value < 10 ? 1 : (collo.HeightMm.Value / 10) : 0,
</code></pre>
<p>Is there a 'better'/simpler way of writing this? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T18:00:56.290",
"Id": "384270",
"Score": "0",
"body": "This question severely lacks context. The code also does not make any sense because when `highestWeightOfParcel = 0` then it's the same as writing `highestWeightOfParcel = coll... | [
{
"body": "<pre><code>int highestWeightOfParcel = (collo.WeightGrammes.HasValue && (collo.WeightGrammes > highestWeightOfParcel))? collo.WeightGrammes.Value:0;\n</code></pre>\n\n<p>That line code can perhaps be written as above. However, ternary operator tends to become unreadable fairly quickly. Al... | {
"AcceptedAnswerId": "199683",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T11:04:19.080",
"Id": "199673",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Check if nullable int has value and compare value to another integer"
} | 199673 |
<p>I have three modules here <code>models.py</code>, <code>functionals.py</code>, and <code>adjustment.py</code>. These three may be used to perform analysis of Twitter data through <code>tweepy</code> objects.</p>
<p>The <code>Tweets</code> class is a simple one which takes 'tweet' objects and take it as a 'list', which is necessary (not yet implemented as necessary) as an argument of <code>Authors</code> class.</p>
<p>The <code>Authors</code> class is used to perform analysis of tweets by their authors/users. For example, we can plot the number of Followers of each user appearing in the data (the plot is by <code>hbar_plot</code> function).</p>
<p>Here is an example usage :</p>
<pre><code>import numpy
from models import Authors
from models import Tweets
import matplotlib.pyplot as plt
stats = numpy.load('testfile.npy')
tweets = Tweets(stats)
Model = Authors(tweets)
fig, ax = plt.subplots(1, 1)
Model.hbar_plot(ax, measurement = 'Followers', incolor_measurement = 'Following', height = 0.5, color = (1,0,0,1))
fig, ax = plt.subplots(1, 1)
Model.hbar_plot(ax, measurement = 'Sample Tweets', incolor_measurement = 'Followers', height = 0.5, color = (1,0,0,1))
plt.show()
</code></pre>
<p>The example above plots the barplots, with bar colors representing the <code>incolor_measurement</code> variable.</p>
<p>The <code>testfile.npy</code> is available in <strong><a href="https://github.com/anbarief/statistweepy/blob/master/examples/testfile.npy" rel="nofollow noreferrer">https://github.com/anbarief/statistweepy/blob/master/examples/testfile.npy</a></strong> . This file consists of about 200 'tweet' objects of <code>tweepy</code>, collected a few days ago.</p>
<p>My question is, how to make better organization of the classes and their methods, also the functions here? How to write and organize it better?</p>
<hr>
<p><strong>The modules :</strong></p>
<p><code>adjustment.py</code>:</p>
<pre><code>import copy
class Adjustment(object):
def __init__(self, title = "an adjustment.", **kwargs):
self.title = title
if 'freq_lim' in kwargs:
self.freq_lim = kwargs['freq_lim']
else:
self.freq_lim = None
if 'char_lim' in kwargs:
self.char_lim = kwargs['char_lim']
else:
self.char_lim = None
if 'exclude' in kwargs:
self.exclude = kwargs['exclude']
else:
self.exclude = None
</code></pre>
<p><code>functionals.py</code>:</p>
<pre><code>def filter_unique(tweet_stats_list, output = 'status'):
stats = tweet_stats_list
unique = []
for tweet in stats:
try:
if not (tweet.retweeted_status in unique):
if output == 'status':
unique.append(tweet.retweeted_status)
elif output == 'text':
unique.append(tweet.retweeted_status.text)
except:
if not (tweet in unique):
if output == 'status':
unique.append(tweet)
elif output == 'text':
unique.append(tweet.text)
return unique
def split_texts(texts, adjustment = None):
split_list = []
for text in texts:
split = text.split()
split_list.extend(split)
return split_list
</code></pre>
<p><code>models.py</code>:</p>
<pre><code>import copy
import numpy
import matplotlib.pyplot as plt
from matplotlib import colors as mplcolors
from . import adjustment as adjust
from . import functionals as func
class Tweets(list):
"""
Tweets model.
"""
def __init__(self, *args, filter_by_unique = False, **kwargs):
if filter_by_unique:
tweets = func.filter_unique(args[0])
else:
tweets = args[0]
list.__init__(self, tweets, **kwargs)
@property
def sorted_by_time(self):
return sorted(self, key = lambda x: x.created_at)
@property
def oldest(self):
return self.sorted_by_time[0]
@property
def newest(self):
return self.sorted_by_time[-1]
class Authors(object):
"""
Authors model.
"""
def __init__(self, tweets):
self.tweets = tweets
self.authors = {author.name : author for author in list(set([tweet.author for tweet in self.tweets]))}
self.username = {author.screen_name : author for author in list(set([tweet.author for tweet in self.tweets]))}
self.followers_count = {author: self.authors[author].followers_count for author in self.authors}
self.following_count = {author: self.authors[author].friends_count for author in self.authors}
self.totaltweets = {author: self.authors[author].statuses_count for author in self.authors}
self.tweets_by_author = {author: [tweet for tweet in self.tweets if tweet.author.name == author] for author in self.authors}
self.tweets_count = {author: len(self.tweets_by_author[author]) for author in self.tweets_by_author}
def hbar_plot(self, ax, measurement = 'Followers', color = (0,0,1,1), incolor_measurement = None, height = 1, textsize = 7, **kwargs):
measurements = {'Followers': self.followers_count, 'Following' : self.following_count, 'Total Tweets' : self.totaltweets, 'Sample Tweets' : self.tweets_count}
sorted_authors = sorted(measurements[measurement], key = lambda x : measurements[measurement][x])
if type(color) == str:
color = mplcolors.hex2color(mplcolors.cnames[color])
colors = len(self.authors)*[color]
if incolor_measurement != None:
minor_max = max(measurements[incolor_measurement].values())
transparency = [measurements[incolor_measurement][author]/minor_max for author in sorted_authors]
colors = [(color[0], color[1], color[2], trans) for trans in transparency]
var = [i+height for i in range(len(self.authors))]
ax.barh([i-height/2 for i in var], [measurements[measurement][author] for author in sorted_authors], height = height, color = colors, **kwargs)
ax.set_yticks(var)
ax.set_yticklabels(sorted_authors, rotation = 'horizontal', size = textsize)
if incolor_measurement != None:
ax.set_xlabel(measurement + ' (color : '+incolor_measurement+')')
else :
ax.set_xlabel(measurement)
plt.tight_layout()
</code></pre>
<hr>
<hr>
<p>Result of example usage :</p>
<p><a href="https://i.stack.imgur.com/v3GD4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v3GD4.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/X4CaL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X4CaL.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<p>You’ve presented 5 units (classes, functions) in 3 different files. I understand that you have a few more in your repository but I think this is over-splitting. You should at least merge <code>adjustment.py</code> into <code>models.py</code> and <code>radial_bar.py</code> into <code>functional.py<... | {
"AcceptedAnswerId": "199716",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T14:06:26.500",
"Id": "199686",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"functional-programming",
"twitter"
],
"Title": "Models for analysing Twitter data (*which based on tweepy package)"
} | 199686 |
<p>I used a glyphicon as a link to delete a comment:</p>
<pre><code><a class="delCommentLink" href="{% url 'article:comment_delete' comment.id %}">
<span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</code></pre>
<p>I send the request using Ajax.</p>
<ol>
<li>retrieve the <code>comment_url</code></li>
<li>get the grand-grand-parent element to hide</li>
<li>send request to <code>views.py</code> and delete the target comment</li>
</ol>
<pre><code>$(document).ready(function () {
$("body").on("click",".delCommentLink",function (e) {
e.preventDefault();
var comment_url = $(e.target).parent().attr("href");
var $commentEle = $(e.target).closest(".comment");
if (window.confirm("Delete this comment?")) {
$.ajax({
type: "get",
url: comment_url,
success: function (data) {
var ret = JSON.parse(data);
if (ret['status'] == 1) {
$commentEle.hide();
} else {
alert(ret['msg']);
};
},//success
});//ajax
} else {
e.preventDefault()
}
});//click event
})
</code></pre>
<p>Click a link to delete it. My code seems like it has too many lines for such a routine task.</p>
<p>How can I complete it elegantly?</p>
| [] | [
{
"body": "<p>I only see two things to \"reduce\", regarding the line amount.</p>\n\n<ol>\n<li>The <code>if</code> statement in the success callback could be replaced by a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">ter... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T15:08:09.887",
"Id": "199688",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"event-handling",
"ajax",
"django"
],
"Title": "Click a link to delete targeted content using Ajax"
} | 199688 |
<p>I built a class to help me handle image data to use in machine learning. I thought that there would be a pre-existing package that did what I wanted but I couldn't find it so I wrote this. I am not intentionally trying to re-invent the wheel so if there's something that already does this please let me know (although I would still be interested in how I could make this better).</p>
<p>The main goal is the have a class of functions that can read images files from directories and convert them into training and testing sets ready for machine learning. I want to have the flexibility to return the data in any of the following forms:</p>
<ul>
<li>grayscale or rgb</li>
<li>flattened vectors or not</li>
<li>any square image size</li>
<li>rescaled, standardized, or not</li>
<li>labels as either column vector or not ( (n,) or (n, 1) )</li>
<li>number of samples either as first or last in ndarray</li>
</ul>
<p>I use this class to accept directories in the following format:</p>
<pre><code>data
│
└───train
│ └───image1
│ │ im1.jpg
│ │ im2.jpg
│ └───image2
│ im1.jpg
│ im2.jpg
└───test
│ └───image1
│ │ im3.jpg
│ │ im4.jpg
│ └───image2
│ im3.jpg
│ im4.jpg
</code></pre>
<p>then return data in any format I want, including (N, l, w, 3), (N, l*w*1), (l*w*3, N), etc.</p>
<p>The function <code>train_test_sets</code> is the meat of the class, but there are other helper functions as well.</p>
<pre><code>from PIL import Image
import os
import numpy as np
from keras.preprocessing.image import array_to_img, img_to_array, load_img
import random
class Gather_Data(object):
def __init__(self):
self.X_train_ = None
self.X_test_ = None
self.y_train_ = None
self.y_test_ = None
self.image_size_ = None
self.num_train_images_ = None
self.num_test_images_ = None
def get_filenames(self, path):
'''
Returns list of filenames in a path
'''
# os.path.join will add the trailing slash if it's not already there
files = [file for file in os.listdir(
path) if os.path.isfile(os.path.join(path, file))]
return files
def get_images(self, path, result_format='list of PIL images', new_size=0, grayscale=True):
'''
Accepts a path to a directory of images and
returns an ndarray of shape N, H, W, c where
N is the number of images
H is the height of the images
W is the width of the images\
c is 3 if RGB and 1 if grayscale
result can be "ndarray" for a single large ndarray,
"list of ndarrays", or list of PIL Images (PIL.Image.Image)
If a new_size is added, it must be square
This function also allows the images to be resized, but forces square
'''
files = self.get_filenames(path)
images = []
for file in files:
image = Image.open(os.path.join(path, file))
if grayscale:
image = image.convert("L")
if new_size != 0:
image = image.resize((new_size, new_size), Image.ANTIALIAS)
if result_format == 'ndarray' or result_format == 'list of ndarrays':
image = np.array(image)
images.append(image)
if result_format == 'ndarray':
return np.asarray(images)
else:
return images
def make_dir_if_needed(self, folder):
'''
Checks if a directory already exists and if not creates it
'''
if not os.path.isdir(folder):
os.makedirs(folder)
def augment_images(self, original_file, output_path, output_prefix,
image_number, datagen, count=10):
'''
This function works on a single image at a time.
It works best by enumerating a list of file names and passing the file and index.
original_file must be the full path to the file, not just the filename
The image_number should be the index from the enumeration e.g.:
for index, file in enumerate(train_files):
augment_images(os.path.join(train_path, file), output_path,
str(index), datagen, count=10)
'''
self.make_dir_if_needed(output_path)
# load image to array
image = img_to_array(load_img(original_file))
# set_trace()
# reshape to array rank 4
image = image.reshape((1,) + image.shape)
# let's create infinite flow of images
images_flow = datagen.flow(image, batch_size=1)
for index, new_images in enumerate(images_flow):
if index >= count:
break
# we access only first image because of batch_size=1
new_image = array_to_img(new_images[0], scale=True)
output_filename = output_path + output_prefix + image_number + \
'-' + str(index+1) + '.jpg'
new_image.save(output_filename)
def train_test_sets(self, input1_training_path, input2_training_path, input1_testing_path,
input2_testing_path, new_size=256, grayscale=False, num_samples_last=False,
standardization='normalize', seed=None, verbose=False,
y_as_column_vector=False, flatten=True):
'''
This assumes the data arrives in the form (N, H*W*c) where c is color
color is 3 for RGB or 1 for grayscale
To leave the images at their original size pass `new_size = 0`
'''
# Get an ndarray of each group of images
# Array should be N * H * W * c
train1 = self.get_images(
input1_training_path, result_format='ndarray', new_size=new_size, grayscale=grayscale)
train2 = self.get_images(
input2_training_path, result_format='ndarray', new_size=new_size, grayscale=grayscale)
test1 = self.get_images(
input1_testing_path, result_format='ndarray', new_size=new_size, grayscale=grayscale)
test2 = self.get_images(
input2_testing_path, result_format='ndarray', new_size=new_size, grayscale=grayscale)
self.image_size_ = (new_size, new_size)
# make sure the image is square
assert train1.shape[1] == train1.shape[2] == new_size
# Now we have an array of images N * W * H * 3 or N * W * H * 1
if flatten:
if verbose:
print("flattening")
# Flatten the arrays
if grayscale:
flattened_size = new_size * new_size
else:
flattened_size = new_size * new_size * 3
train1 = train1.reshape(train1.shape[0], flattened_size)
train2 = train2.reshape(train2.shape[0], flattened_size)
test1 = test1.reshape(test1.shape[0], flattened_size)
test2 = test2.reshape(test2.shape[0], flattened_size)
# Combine the two different inputs into a single training set
training_images = np.concatenate((train1, train2), axis=0)
# Do same for testing set
testing_images = np.concatenate((test1, test2), axis=0)
# Get the number of training and testing examples
self.num_train_images_ = len(training_images)
self.num_test_images_ = len(testing_images)
# Create labels
training_labels = np.concatenate(
(np.zeros(len(train1)), np.ones(len(train2))))
testing_labels = np.concatenate(
(np.zeros(len(test1)), np.ones(len(test2))))
# Zip the images and labels together so they can be shuffled together
if verbose:
print("zipping")
train_zipped = list(zip(training_images, training_labels))
test_zipped = list(zip(testing_images, testing_labels))
if verbose:
print("shuffling")
# Now shuffle both
random.seed(seed)
random.shuffle(train_zipped)
random.shuffle(test_zipped)
self.X_train_, self.y_train_ = zip(*train_zipped)
self.X_test_, self.y_test_ = zip(*test_zipped)
# Convert tuples back to ndarrays
self.X_train_ = np.asarray(self.X_train_)
self.X_test_ = np.asarray(self.X_test_)
self.y_train_ = np.asarray(self.y_train_)
self.y_test_ = np.asarray(self.y_test_)
if standardization == 'normalize':
if verbose:
print("standardizing")
# Standardize the values
self.X_train_ = (self.X_train_ - self.X_train_.mean()
) / self.X_train_.std()
# Use the train mean and standard deviation
self.X_test_ = (self.X_test_ - self.X_train_.mean()
) / self.X_train_.std()
elif standardization == 'rescale':
if verbose:
print("standardizing")
# Standardize the values
self.X_train_ = self.X_train_ / 255.
# Use the train mean and standard deviation
self.X_test_ = self.X_test_ / 255.
if y_as_column_vector:
# Reshape the y to matrix them n X 1 matricies
self.y_train_ = self.y_train_.reshape(self.y_train_.shape[0], 1)
self.y_test_ = self.y_test_.reshape(self.y_test_.shape[0], 1)
if num_samples_last:
# Code conversion for class
self.X_train_.shape = (
self.X_train_.shape[1], self.X_train_.shape[0])
self.X_test_.shape = (self.X_test_.shape[1], self.X_test_.shape[0])
self.y_train_.shape = (
self.y_train_.shape[1], self.y_train_.shape[0])
self.y_test_.shape = (self.y_test_.shape[1], self.y_test_.shape[0])
def dataset_parameters(self):
'''
Returns the parameters of the dataset
'''
try:
print("X_train shape: " + str(self.X_train_.shape))
print("y_train shape: " + str(self.y_train_.shape))
print("X_test shape: " + str(self.X_test_.shape))
print("y_test shape: " + str(self.y_test_.shape))
print("Number of training examples: " + str(self.num_train_images_))
print("Number of testing examples: " + str(self.num_test_images_))
print("Each image is of size: " + str(self.image_size_))
except AttributeError:
print("Error: The data has not been input or is incorrectly configured.")
</code></pre>
<p>Here are some sample use cases:</p>
<p>Augmenting images:</p>
<p><code>augment_images</code> uses the augmentation functionality of Keras, but gives me more flexibility. I know Keras has <code>save_to_dir</code> and <code>save_prefix</code> arguments, but I wanted to control exactly which images were augmented, how many times they were augmented, and what their files names are.</p>
<pre><code>my_data = Gather_Data()
image_path = 'img/'
aug_path = 'aug/'
filenames = my_data.get_filenames(image_path)
# This import is down here because it would normally be in a separate file
from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(
rotation_range=45
)
for index, file in enumerate(filenames):
my_data.augment_images(os.path.join(image_path, file), aug_path,
'augmented_image', str(index), datagen, count=2)
</code></pre>
<p>Getting data:</p>
<pre><code>im1_train_path = 'data/train/im1/'
im2_train_path = 'data/train/im2/'
im1_test_path = 'data/test/im1/'
im2_test_path = 'data/test/im2/'
datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
my_data.train_test_sets(im1_train_path, im2_train_path, im1_test_path, im2_test_path)
X_train = my_data.X_train_
y_train = my_data.y_train_
X_test = my_data.X_test_
y_test = my_data.y_test_
my_data.dataset_parameters()
</code></pre>
<p>I'm not particularly concerned with line length or blank lines, but I'd really appreciate any suggestions.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-25T04:43:29.007",
"Id": "385416",
"Score": "0",
"body": "What type of images are you using? Are they so specific that you can't find a pre-trained model and then modify that model's weights (i.e. [transfer learning](https://medium.com/... | [
{
"body": "<p>The <code>train_test_sets</code> method limit you to two folders, why? In the directory tree you provided, you only have <code>image1</code> and <code>image2</code>, but what if there's an <code>image3</code> some day? The obvious solution is to pass arrays to your method instead of a specific num... | {
"AcceptedAnswerId": "226037",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T16:04:31.187",
"Id": "199694",
"Score": "6",
"Tags": [
"python",
"object-oriented",
"image",
"machine-learning"
],
"Title": "Python class for organizing images for machine learning"
} | 199694 |
<p>The task is to fetch some JSON data from an API with a GET request. If the location is not available for any reason, read a cache file. Otherwise write the cache file for future use.</p>
<p>The following function works but it is clumsy due to:</p>
<ul>
<li>The nested <code>try</code>/<code>except</code>, which is difficult to read</li>
<li>It's difficult to figure out what the error is (I am catching both <code>HTTPError</code> and the <code>JSONDecodeError</code> to avoid further nesting</li>
<li>I don't dare to use a context manager for opening the file (<code>with</code>) due to a further nesting level within a <code>try</code>/<code>except</code> clause</li>
</ul>
<p>Have you got any ideas for improvement?</p>
<pre><code>def fetch_list(location=MY_LOCATION, cache_file=CACHE_FILE):
"""Goes to the default location and returns
a python list
"""
http = urllib3.PoolManager()
try:
r = http.request("GET",
location)
raw_data = r.data.decode("utf-8")
data = json.loads(raw_data)
except (urllib3.exceptions.HTTPError, JSONDecodeError):
logger.error("Cannot access Intranet List Location - fetching cache")
try:
data = json.loads(open(cache_file).readlines())
except (IOError, JSONDecodeError):
logger.error("Cache File not found or broken")
raise
else:
with open(cache_file, "w") as f:
f.write(raw_data)
return data
</code></pre>
| [] | [
{
"body": "<p>If your <code>logger</code> object is derived from the <a href=\"https://devdocs.io/python~3.6/library/logging#logging.exception\" rel=\"nofollow noreferrer\"><code>logging</code> module</a>, use the <code>logger.exception</code> which'll log the traceback information as well. The docs (linked abo... | {
"AcceptedAnswerId": "199700",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T16:38:22.430",
"Id": "199698",
"Score": "4",
"Tags": [
"python",
"json",
"error-handling",
"http",
"cache"
],
"Title": "Fetching data through HTTP and caching JSON result in a file"
} | 199698 |
<p>A challenge from Code Fights; a function that takes a number no less than 10 and that will always have an even number of digits and determines if the sum of the first half of the digits equals the sum of the second half of digits. The function returns a Boolean. Maximum execution time is 4000 milliseconds.</p>
<p>Here is the function: </p>
<pre><code>// tickets are lucky when sum of first half equals sum of second half
const isLucky = n => {
// min is 10 and we know it's false
if (n === 10) return false;
// store digits in an array
const digitCorral = [];
// use modulo, division and Math.trunc
while (n > 0) {
// push reverses the order but that doesn't matter
// since the sum of each half will still be the same
digitCorral.push(n % 10);
n /= 10;
n = Math.trunc(n);
}
// get sum of first half of array
const firstHalf = digitCorral
.slice(0, digitCorral.length / 2)
.reduce(function(a, b) {
return a + b;
});
// get sum of second half of array
const secondHalf = digitCorral
.slice(digitCorral.length / 2, digitCorral.length)
.reduce(function(a, b) {
return a + b;
});
// return a boolean
return firstHalf === secondHalf;
};
</code></pre>
<p>The function passes all tests, however, I wonder if there is an even more efficient way write it--would recursion be faster? Can the speed of this algorithm be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T20:07:06.260",
"Id": "384284",
"Score": "1",
"body": "Don't know javascript so cannot comment/review the code. An alternative, take number as a string (doesn't matter if string or array of single-digit numbers) and then in a single ... | [
{
"body": "<h1>Bad storage and time</h1>\n\n<p>Your code solves the problem but is a memory hog.</p>\n\n<h2>Algorithm complexity</h2>\n\n<p>You are looping over the digits twice, once to extract each digit, and then once to sum each half. The logic can be improved if you calculate the sums as you extract each d... | {
"AcceptedAnswerId": "199710",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T17:17:54.447",
"Id": "199701",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"algorithm",
"complexity"
],
"Title": "JavaScript Determine if Number is Lucky"
} | 199701 |
<p>This is a follow up to a previously asked <a href="https://codereview.stackexchange.com/questions/198471/finding-the-closest-pair-of-points-divide-and-conquer/199668#199668">Finding the closest pair of points divide-and-conquer</a> question . The original code changed significantly based on answers from @AJNeufeld therefore I created a new question per codereview guidelines for additional help. </p>
<p>After incorporating suggestions from answers to the original question linked above, the run-time improved by 30% which is significant. Nevertheless, the code is still slow and I think there is room for further improvements. My hunch is that <code>find_min_distance_in_rec</code> is slowing the code down. Below is the current code. Again, the code has been stress tested so I am confident that it's correct, however, it's slow.</p>
<pre><code>#Uses python3
import math
import statistics as stats
# helper functions:
def two_point_distance(p0,p1):
# returns distance between two (x,y) pairs
return math.sqrt( ((p0[0]-p1[0])*(p0[0]-p1[0])) +
((p0[1] - p1[1])*(p0[1] - p1[1])) )
def combine_xy(x_arr,y_arr):
# combine x_arr and y_arr to combined list of (x,y) tuples
return list(zip(x_arr,y_arr))
def find_closest_distance_brute(xy_arr):
# brute force approach to find closest distance
dmin = math.inf
for i, pnt_i in enumerate(xy_arr[:-1]):
dis_storage_min = min( two_point_distance(pnt_i, pnt_j) for pnt_j in xy_arr[i+1:])
if dis_storage_min < dmin:
dmin = dis_storage_min
return dmin
def calc_median_x(xy_arr):
# return median of x values in list of (x,y) points
return stats.median( val[0] for val in xy_arr )
def filter_set(xy_arr_y_sorted, median, distance):
# filter initial set such than |x-median|<= distance
return [ val for val in xy_arr_y_sorted if abs(val[0] - median) <= distance ]
def x_sort(xy_arr):
# sort array according to x value
return sorted(xy_arr, key=lambda val: val[0])
def y_sort(xy_arr):
# sort array according to y value
return sorted(xy_arr, key=lambda val: val[1])
def split_array(arr_x_sorted, arr_y_sorted,median):
# split array of size n to two arrays of n/2
# input is the same array twice, one sorted wrt x, the other wrt y
leq_arr_x_sorted = [ val for val in arr_x_sorted if val[0] < median ]
geq_arr_x_sorted = [ val for val in arr_x_sorted if val[0] > median ]
eq_arr_x = [ val for val in arr_x_sorted if val[0] == median ]
n = len(eq_arr_x)//2
leq_arr_x_sorted = leq_arr_x_sorted + eq_arr_x[:n]
geq_arr_x_sorted = eq_arr_x[n:] + geq_arr_x_sorted
leq_arr_y_sorted = [ val for val in arr_y_sorted if val[0] < median ]
geq_arr_y_sorted = [ val for val in arr_y_sorted if val[0] > median ]
eq_arr_y = [ val for val in arr_y_sorted if val[0] == median ]
n = len(eq_arr_y)//2
leq_arr_y_sorted = leq_arr_y_sorted + eq_arr_y[:n]
geq_arr_y_sorted = eq_arr_y[n:] + geq_arr_y_sorted
return leq_arr_x_sorted, leq_arr_y_sorted, geq_arr_x_sorted, geq_arr_y_sorted
def find_min_distance_in_rec(xy_arr_y_sorted,dmin):
# takes in array sorted in y, and minimum distance of n/2 halves
# for each point it computes distance to 7 subsequent points
# output min distance encountered
dmin_rec = dmin
if len(xy_arr_y_sorted) == 1:
return math.inf
if len(xy_arr_y_sorted) > 7:
for i, pnt_i in enumerate(xy_arr_y_sorted[:-7]):
dis_storage_min = min(two_point_distance(pnt_i, pnt_j)
for pnt_j in xy_arr_y_sorted[i+1:i+1+7])
if dis_storage_min < dmin_rec:
dmin_rec = dis_storage_min
dis_storage_min = find_closest_distance_brute(xy_arr_y_sorted[-7:])
if dis_storage_min < dmin_rec:
dmin_rec = dis_storage_min
else:
for k, pnt_k in enumerate(xy_arr_y_sorted[:-1]):
dis_storage_min = min( two_point_distance(pnt_k, pnt_l)
for pnt_l in xy_arr_y_sorted[k+1:])
if dis_storage_min < dmin_rec:
dmin_rec = dis_storage_min
return dmin_rec
def find_closest_distance_recur(xy_arr_x_sorted, xy_arr_y_sorted):
# recursive function to find closest distance between points
if len(xy_arr_x_sorted) <=3 :
return find_closest_distance_brute(xy_arr_x_sorted)
median = calc_median_x(xy_arr_x_sorted)
leq_arr_x_sorted, leq_arr_y_sorted , grt_arr_x_sorted, grt_arr_y_sorted = split_array(xy_arr_x_sorted, xy_arr_y_sorted, median)
distance_left = find_closest_distance_recur(leq_arr_x_sorted, leq_arr_y_sorted)
distance_right = find_closest_distance_recur(grt_arr_x_sorted, grt_arr_y_sorted)
distance_min = min(distance_left, distance_right)
filt_out = filter_set(xy_arr_y_sorted, median, distance_min)
distance_filt = find_min_distance_in_rec(filt_out, distance_min)
return min(distance_min, distance_filt)
def find_closest_point(x_arr, y_arr):
# input is x,y points in two arrays, all x's in x_arr, all y's in y_arr
xy_arr = combine_xy(x_arr,y_arr)
xy_arr_x_sorted = x_sort(xy_arr)
xy_arr_y_sored = y_sort(xy_arr)
min_distance = find_closest_distance_recur(xy_arr_x_sorted, xy_arr_y_sored)
return min_distance
</code></pre>
| [] | [
{
"body": "<p>I guess I didn't make this clear in my answer on the original question.</p>\n\n<p>The minimum of the square-root of the square distances is the square-root of the minimum of the square distances. You can save time by calculating the square-root only when needed.</p>\n\n<p>Replace this (and all ca... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T17:49:51.360",
"Id": "199703",
"Score": "2",
"Tags": [
"python",
"recursion",
"computational-geometry",
"divide-and-conquer"
],
"Title": "Finding the closest pair of points divide-and-conquer speed improvement"
} | 199703 |
<p>I have some zip files somewhere in the order of 2GB+ containing only html files. Each zip contains about <strong><em>170,000</em></strong> html files each. </p>
<p>My code reads the file without extracting them, </p>
<p>Passes the resultant html string into a custom HTMLParser object, </p>
<p>And then writes a summary of all the zip files into a CSV (for that particular zipfile).</p>
<p>Despite my code working, it takes longer than a few minutes to completely parse all the files. In order to save the files to a .csv, I've appended the parsed file contents to a list, and then went on to write rows for every entry in the list. I suspect this is what is drawing back performance.</p>
<p>I've also implemented some light multithreading, a new thread is spawned for each zip file encountered. However the magnitude of the files makes me wonder whether I should have implemented a <code>Process</code> for each file instead that spawned thread batches to parse the html files(i.e parse 4 files at a time).</p>
<p>My fairly naive attempts at timing the operation revealed the following results when processing 2 zip files at a time:</p>
<pre><code>Accounts_Monthly_Data-June2017 has reached file 1500/188495
In: 0.6609588377177715 minutes
Accounts_Monthly_Data-July2017 has reached file 1500/176660
In: 0.7187837697565556 minutes
</code></pre>
<p>Which implies 12 seconds per 500 files, which is approximately 41 files per second; which is certainly much too slow.</p>
<p>You can find some example zip files at <a href="http://download.companieshouse.gov.uk/en_monthlyaccountsdata.html" rel="nofollow noreferrer">http://download.companieshouse.gov.uk/en_monthlyaccountsdata.html</a> and an example CSV (for a single html file, the real csv would contain rows for every file) follows:</p>
<pre><code>Company Number,Company Name,Cash at bank and in hand (current year),Cash at bank and in hand (previous year),Net current assets (current year),Net current assets (previous year),Total Assets Less Current Liabilities (current year),Total Assets Less Current Liabilities (previous year),Called up Share Capital (current year),Called up Share Capital (previous year),Profit and Loss Account (current year),Profit and Loss Account (previous year),Shareholder Funds (current year),Shareholder Funds (previous year)
07731243,INSPIRATIONAL TRAINING SOLUTIONS LIMITED,2,"3,228","65,257","49,687","65,257","49,687",1,1,"65,258","49,688","65,257","49,687"
</code></pre>
<p>I fairly new to implementing intermediate, highly-performant code in python so I can't see how I could further optimize what I've written, any suggestions are helpful.</p>
<p>I've provided a test zip of approximately 875 files:
<a href="https://www.dropbox.com/s/xw3klspg1cipqzx/test.zip?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/xw3klspg1cipqzx/test.zip?dl=0</a></p>
<pre><code>from html.parser import HTMLParser as HTMLParser
from multiprocessing.dummy import Pool as ThreadPool
import time
import codecs
import zipfile
import os
import csv
class MyHTMLParser(HTMLParser):
def __init__(self):
self.fileData = {} # all the data extracted from this file
self.extractable = False # flag to begin handler_data
self.dataTitle = None # column title to be put into the dictionary
self.yearCount = 0
HTMLParser.__init__(self)
def handle_starttag(self, tag, attrs):
yearCount = 0 # years are stored sequentially
for attrib in attrs:
if 'name' in attrib[0]:
if 'UKCompaniesHouseRegisteredNumber' in attrib[1]:
self.dataTitle = 'Company Number'
# all the parsed files in the directory
self.extractable = True
elif 'EntityCurrentLegalOrRegisteredName' in attrib[1]:
self.dataTitle = 'Company Name'
self.extractable = True
elif 'CashBankInHand' in attrib[1]:
self.handle_timeSeries_data('Cash at bank and in hand')
elif 'NetCurrentAssetsLiabilities' in attrib[1]:
self.handle_timeSeries_data('Net current assets')
elif 'ShareholderFunds' in attrib[1]:
self.handle_timeSeries_data('Shareholder Funds')
elif 'ProfitLossAccountReserve' in attrib[1]:
self.handle_timeSeries_data('Profit and Loss Account')
elif 'CalledUpShareCapital' in attrib[1]:
self.handle_timeSeries_data('Called up Share Capital')
elif 'TotalAssetsLessCurrentLiabilities' in attrib[1]:
self.handle_timeSeries_data('Total Assets Less Current Liabilities')
def handle_endtag(self, tag):
None
def handle_data(self, data):
if self.extractable == True:
self.fileData[self.dataTitle] = data
self.extractable = False
def handle_timeSeries_data(self, dataTitle):
if self.yearCount == 0:
self.yearCount += 1
self.dataTitle = dataTitle + ' (current year)'
else:
self.yearCount = 0
self.dataTitle = dataTitle + ' (previous year)'
self.extractable = True
def parseZips(fileName=str()):
print(fileName)
directoryName = fileName.split('.')[0]
zip_ref = zipfile.ZipFile(fileName, 'r')
zipFileNames = tuple(n.filename for n in zip_ref.infolist() if 'html' in n.filename or 'htm' in n.filename)
print('Finished reading ' + fileName+'!\n')
collectHTMLS(directoryName, zip_ref, zipFileNames)
def collectHTMLS(directoryName, zip_ref, zipFileNames):
print('Collection html data into a csv for '+ directoryName+'...')
parser = MyHTMLParser()
fileCollection = []
totalFiles = len(zipFileNames)
count = 0
startTime = time.time()/60
for f in zipFileNames:
parser.feed(str(zip_ref.read(f)))
fileCollection.append(parser.fileData)
if(count % 500 ==0):
print('%s has reached file %i/%i\nIn: {timing} minutes\n'.format(timing = ((time.time()/60)-startTime)) % (directoryName,count,totalFiles))
parser.fileData = {} #reset the dictionary
count += 1
print('Finished parsing files for ' + directoryName)
with open(directoryName+'.csv', 'w') as f:
w = csv.DictWriter(f, fileCollection[0].keys())
w.writeheader()
for parsedFile in fileCollection:
w.writerow(parsedFile)
f.close()
print('Finished writing to file from ' + directoryName)
def main():
zipCollection = [f for f in os.listdir('.') if os.path.isfile(f) and f.split('.')[1] == 'zip']
threadPool = ThreadPool(len(zipCollection))
threadPool.map_async(parseZips, zipCollection)
threadPool.close()
threadPool.join()
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T20:18:45.073",
"Id": "384286",
"Score": "1",
"body": "perhaps you could add a sample zip-file with a few pages, together with the expected csv for that dataset, so we can verify we end at the same results"
},
{
"ContentLicen... | [
{
"body": "<p>Apart from the performance, here are some other tips to make this code clearer</p>\n\n<h1>Pep-008</h1>\n\n<p>Try to stick to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> for style, especially your variable names are a hodgepodge between <code>camelCas... | {
"AcceptedAnswerId": null,
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T19:23:04.363",
"Id": "199704",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"csv",
"multiprocessing"
],
"Title": "Parsing contents of a large zip file into a html parser into a .csv file"
} | 199704 |
<p>This is a follow up of <a href="https://codereview.stackexchange.com/questions/197752/non-generic-skip-list-implementation-in-c-version-2">Non generic Skip List implementation in C++ Version 2</a></p>
<p>If you don't know what a Skip list is: <a href="https://en.wikipedia.org/wiki/Skip_list" rel="noreferrer">https://en.wikipedia.org/wiki/Skip_list</a></p>
<p>I tried to incorporate as much improvements as possible from the code review of the last skip list.</p>
<p>Also the following changes were made:</p>
<p><b> Templates: </b> I turned the skip list into a generic template to support all kinds of types (not only int). The skip list cpp was removed and everything goes into the .h-file</p>
<p><b> Adapting to STL: </b> I checked out which functions std::map provides and tried to implement most of them. I tried to provide similar Interfaces so STL algorithms can work. </p>
<p><b> Unit Tests: </b> I tried to clean up the tests and make most of them run automatically.</p>
<p><b> skip_list.h </b></p>
<pre><code>#ifndef SKIP_LIST_GUARD_170720181942
#define SKIP_LIST_GUARD_170720181942
#include <map> // std::pair
#include <random> // generation of the levels
#include <vector> // for head implementation
namespace skip_list {
template<typename Key,typename T>
class Skip_list {
private:
struct Skip_node; // forward declaration because iterator class needs to know about the node
std::vector<Skip_node*> head = std::vector<Skip_node*>(1, nullptr); // element before first element containg pointers to all the first elements of each level
public:
using key_type = Key;
using mapped_type = T;
using value_type = std::pair<const key_type, mapped_type>;
using size_type = std::size_t;
template<typename IT, bool is_const>
class iterator_base {
public:
using node_type = typename std::conditional<is_const, Skip_node const, Skip_node>::type;
using value_type = typename std::conditional<is_const, IT const, IT>::type;
iterator_base()
: curr{ nullptr }
{
};
explicit iterator_base(node_type* pos)
: curr{ pos }
{
};
iterator_base& operator=(const iterator_base& other) // copy assignment
{
curr = other.curr;
return *this;
}
// the order is determinde by the key so compare by it
bool operator==(const iterator_base& b) const { return curr == b.curr; }
bool operator!=(const iterator_base& b) const { return curr != b.curr; }
bool operator>(const iterator_base& b) const {
////assume nullptr is the biggest element
if (curr != nullptr && b.curr != nullptr)
return curr->value.first > b.curr->value.first;
else if (curr == nullptr && b.curr != nullptr)
return true;
else // (curr != nullptr && b == nullptr)
return false;
}
bool operator<(const iterator_base& b) const
{
return (!(curr < b.curr) && (curr != b.curr));
}
bool operator>=(const iterator_base& b) const
{
return ((curr == b.curr) || (b.curr > curr));
}
bool operator<=(const iterator_base& b) const
{
return ((curr == b.curr) || (b.curr < curr));
}
iterator_base& operator++()
// if next element is empty dont increase more
{
if (curr == nullptr)
return *this;
curr = curr->next[0];
return *this;
}
iterator_base& operator+=(const int offset)
{
if (offset <= 0) return *this;
for (int i = 0; i < offset; ++i)
++*this;
return *this;
}
iterator_base operator+(const int offset)
{
iterator_base it = *this;
it += offset;
return it;
}
value_type& operator*() { return curr->value; }
value_type* operator->() { return &curr->value; }
private:
node_type* curr;
friend class Skip_list; // to access curr in skiplist functions
};
using iterator = iterator_base<value_type,false>;
using const_iterator = iterator_base<value_type const,true>;
Skip_list() = default; // constructor
~Skip_list() noexcept // destructor
{
free_all_nodes(head[0]);
}
Skip_list(const Skip_list& other) // copy constructor
{
try {
copy_nodes(other);
}
catch (...) { // if copy constructor fails, clean up mess and re-throw
free_all_nodes(head[0]);
throw;
}
}
Skip_list& operator=(const Skip_list& other) // copy assignment
{
auto backup = std::move(head); // keep backup to provide better exception guarantee
try {
copy_nodes(other);
}
catch (...) {
free_all_nodes(head[0]);
head = std::move(backup);
throw;
}
free_all_nodes(backup[0]);
return *this;
}
Skip_list(Skip_list&& other) noexcept // move constructor
:head{ std::move(other.head) }
{
other.head.assign(1, nullptr);
}
Skip_list& operator=(Skip_list&& other) noexcept // move assignment
{
if (this != &other) {
free_all_nodes(head[0]);
head = std::move(other.head);
other.head.assign(1, nullptr);
}
return *this;
}
// ------------Iterators
iterator begin() noexcept
{
return iterator{ head[0] };
}
iterator end() noexcept
{
return iterator{ nullptr };
}
const_iterator begin() const noexcept
{
return const_iterator{ head[0] };
}
const_iterator end() const noexcept
{
return const_iterator{ nullptr };
}
const_iterator cbegin() const noexcept
{
return begin();
}
const_iterator cend() const noexcept
{
return end();
}
// ------------capacity
bool empty() const noexcept
{
return (head[0] == nullptr);
}
size_type size() const noexcept // return count of nodes
{
Skip_list<Key, T>::size_type counter = Skip_list<Key, T>::size_type{};
for (auto index = head[0]; index != nullptr; index = index->next[0], ++counter);
return counter;
}
size_type max_size() const noexcept
{
return size_type{ static_cast<size_type>(-1) };
}
// ------------element access
mapped_type& operator[] (const key_type& key)
{
return find(key)->second;
}
mapped_type& operator[] (key_type&& key)
{
return find(key)->second;
}
// ------------modifiers
std::pair<iterator, bool> insert(const value_type& value);
size_type erase(const key_type& key); // search for an element and erase it from the skip list
void clear() noexcept // erase all elements
{
free_all_nodes(head[0]);
head.assign(1, nullptr);
}
// ------------Operations
iterator find(const key_type& key);
const_iterator find(const key_type& key) const;
size_type count(const key_type& key) const
{
return find(key) != end() ? 1 : 0;
}
size_type top_level() const { return head.size(); } // maximum height the Skip_list has reached
void debug_print(std::ostream& os) const; // show all the levels for debug only. can this be put into skiplist_unit_tests ?
private:
size_type generate_level() const;
static bool next_level() noexcept;
struct Skip_node{
value_type value; // key / T
size_type levels;
Skip_node* next[1];
};
static Skip_node* allocate_node(value_type value, size_type levels);
static void free_node(Skip_node* node);
void copy_nodes(const Skip_list& other);
static void free_all_nodes(Skip_node* head) noexcept;
};
template<typename Key, typename T>
std::pair<typename Skip_list<Key,T>::iterator, bool> Skip_list<Key,T>::insert(const value_type& value)
// if key is already present the position of that key is returned and false for no insert
//
// if new key inserted or value of given key was replaced return next pos as iterator and indicate change with true
// otherwise return iterator end() and false
{
const auto insert_level = generate_level(); // top level of new node
const auto insert_node = allocate_node(value, insert_level);
Skip_list::Skip_node* old_node = nullptr;
while (head.size() < insert_level) {
head.push_back(nullptr);
}
auto level = head.size();
auto next = head.data();
Skip_list::iterator insert_pos;
bool added = false;
while (level > 0) {
const auto index = level - 1;
auto node = next[index];
if (node == nullptr || node->value.first > value.first) { //compare by key
if (level <= insert_level) {
insert_node->next[index] = next[index];
next[index] = insert_node;
if (!added) {
insert_pos = Skip_list::iterator{ next[index] };
added = true;
}
}
--level;
}
else if (node->value.first == value.first) {
// key already present, keep node with more levels
// -> no need to insert new node into list if not needed
// -> if insert_node->levels > node->levels, we already modified the list
// so continuing and removing the other node seems like the easier option
// (compared to retracing where links to insert_node have been made)
if (node->levels >= insert_level) {
node->value.second = value.second;
free_node(insert_node);
return std::make_pair(Skip_list::iterator{ node }, true);
}
old_node = node;
insert_node->next[index] = node->next[index];
next[index] = insert_node;
--level;
}
else {
next = node->next;
}
}
if (old_node != nullptr) {
free_node(old_node);
}
return std::make_pair(insert_pos, added);
}
template<typename Key, typename T>
typename Skip_list<Key,T>::size_type Skip_list<Key,T>::erase(const key_type& key)
// starts search on the highest lvl of the Skip_list
// if a node with the erase key is found the algorithm goes
// down until the lowest lvl.
// on the way down all links with the key in the list are removed
// on the lowest lvl the current node which contains the erase key is deleted
//
// the return type indicates how many elements are deleted (like std::map)
// it can become only 0 or 1
{
Skip_node* node = nullptr;
auto level = head.size();
auto next = head.data();
while (level > 0) {
const auto link_index = level - 1;
if (!next[link_index] || next[link_index]->value.first > key) {
--level;
}
else if (next[link_index]->value.first == key) {
node = next[link_index];
next[link_index] = node->next[link_index];
--level;
}
else {
next = next[link_index]->next;
}
}
while (head.size() > 1 && head.back() == nullptr) head.pop_back();
if (node) { // element to erase was found and taken out of list
free_node(node);
return 1;
}
else {
return 0;
}
}
template<typename Key, typename T>
typename Skip_list<Key,T>::const_iterator Skip_list<Key,T>::find(const key_type& key) const
// first it is iterated horizontal and vertical until the last level is reached
// on the last level if the keys match the iterator pointing to it is returned
{
auto level = head.size();
auto next = head.data();
while (level > 0) {
const auto index = level - 1;
if (!next[index] || next[index]->value.first > key) {
--level;
}
else if (next[index]->value.first == key) {
return const_iterator{ next[index] };
}
else {
next = next[index]->next;
}
}
return end();
}
template<typename Key, typename T>
typename Skip_list<Key,T>::iterator Skip_list<Key,T>::find(const key_type& key)
// same as const_iterator function, is there a way to not have this redundant?
{
auto level = head.size();
auto next = head.data();
while (level > 0) {
const auto index = level - 1;
if (!next[index] || next[index]->value.first > key) {
--level;
}
else if (next[index]->value.first == key) {
return iterator{ next[index] };
}
else {
next = next[index]->next;
}
}
return end();
}
template<typename Key, typename T>
void Skip_list<Key,T>::debug_print(std::ostream& os) const
//messy debug routine to print with all available layers
{
if (head[0] == nullptr) {
os << "empty" << '\n';
return;
}
auto level = head.size();
auto next = head.data();
os << "lvl: " << level << " ";
while (level > 0) {
const auto index = level - 1;
if (!next[index]) {
os << '\n';
--level;
if (level > 0) {
os << "lvl: " << index << " ";
next = head.data(); // point back to begining
}
}
else {
os << next[index]->value.first << '/' << next[index]->value.second << ' ';
next = next[index]->next;
}
}
}
template<typename Key, typename T>
typename Skip_list<Key,T>::size_type Skip_list<Key,T>::generate_level() const
// generate height of new node
{
size_type new_node_level = size_type{};
do {
++new_node_level;
} while (new_node_level <= head.size() && next_level());
return new_node_level;
}
template<typename Key, typename T>
bool Skip_list<Key,T>::next_level() noexcept
// arround 50% chance that next level is reached
{
static auto engine = std::mt19937{ std::random_device{}() };
static auto value = std::mt19937::result_type{ 0 };
static auto bit = std::mt19937::word_size;
if (bit >= std::mt19937::word_size) {
value = engine();
bit = 0;
}
const auto mask = std::mt19937::result_type{ 1 } << (bit++);
return value & mask;
}
template<typename Key, typename T>
typename Skip_list<Key,T>::Skip_node* Skip_list<Key, T>::allocate_node(value_type value, size_type levels)
{
const auto node_size = sizeof(Skip_node) + (levels - 1) * sizeof(Skip_node*);
#ifdef _MSC_VER // Visual Studio doesnt support aligned alloc yet ( new in C++ 17)
const auto node = _aligned_malloc(node_size, alignof(Skip_node));
#else
const auto node = std::aligned_alloc(alignof(skip_node), node_size);
#endif
new(node) Skip_node{ value, levels, nullptr };
return reinterpret_cast<Skip_node*>(node);
}
template<typename Key, typename T>
void Skip_list<Key,T>::free_node(Skip_node* node)
{
node->~Skip_node(); // proper destroy potentially dynamicall alocatet types in skip_node
#ifdef _MSC_VER
_aligned_free(node);
#else
std::free(node);
#endif
}
template<typename Key, typename T>
void Skip_list<Key,T>::copy_nodes(const Skip_list& other)
// precondition: head isn't owner of any nodes
{
head.assign(other.head.size(), nullptr);
auto tail = std::vector<Skip_node**>{};
tail.reserve(head.size());
std::for_each(std::begin(head), std::end(head), [&](auto&& link) { tail.push_back(&link); });
for (auto node = other.head[0]; node != nullptr; node = node->next[0]) {
const auto copy_node = allocate_node(node->value, node->levels);
for (auto i = 0u; i < copy_node->levels; ++i) {
*tail[i] = copy_node;
tail[i] = &copy_node->next[i];
}
}
std::for_each(std::begin(tail), std::end(tail), [](auto link) { *link = nullptr; });
}
template<typename Key, typename T>
void Skip_list<Key,T>::free_all_nodes(Skip_node* head) noexcept
{
for (auto index = head; index != nullptr;) {
const auto temp = index;
index = index->next[0];
free_node(temp);
}
}
}
#endif
</code></pre>
<p><b> skip_list_unit_test.h</b></p>
<pre><code>#ifndef SKIPLIST_UNIT_TEST_GUARD_280620182216
#define SKIPLIST_UNIT_TEST_GUARD_280620182216
#include <chrono>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "skip_list.h"
namespace skip_list::unit_test {
int get_random(int min, int max);
namespace copy_and_assignment {
void copy_constructor(std::ostream& os); // OK
void move_constructor(std::ostream& os); // OK
void copy_assignment(std::ostream& os); // OK
void move_assignment(std::ostream& os); // OK
void run_all(std::ostream& os);
}
namespace iterator {
void iterator(std::ostream& os); // OK
void const_iterator(std::ostream& os); // OK
void run_all(std::ostream& os);
}
namespace capacity {
void empty(std::ostream& os); // OK
void max_size(std::ostream& os); // OK
void run_all(std::ostream& os);
}
namespace modifiers {
void insert_and_erase(std::ostream& os); // OK
void insert_same(std::ostream& os); // OK
void iterator_find(std::ostream& os); // OK
void run_all(std::ostream& os);
}
namespace element_access {
void access_operator(std::ostream& os); // OK
void run_all(std::ostream& os);
}
namespace misc {
void performance_of_insert_delete(std::ostream& os, const int repeats, const int count_of_elements); // OK
void debug_print(std::ostream& os); // OK
void leakage_of_memory(std::ostream& os);
}
}
#endif
</code></pre>
<p><b> skip_list_unit_test.cpp </b></p>
<pre><code>#include "skip_list_unit_test.h"
namespace skip_list::unit_test{
int get_random(int min, int max)
{
static std::random_device rd;
static std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(min, max);
return distribution(mt);
}
namespace copy_and_assignment {
void copy_constructor(std::ostream& os)
{
os << "test_copy_constructor START\n";
Skip_list<int,int> a;
for (int i = 2; i<10; ++i)
a.insert(std::make_pair( i , i + 10 ));
Skip_list b{ a };
auto it_a = a.begin();
auto it_b = b.begin();
bool equal = true;
for (; it_a != a.end(), it_b != b.end(); ++it_a, ++it_b) {
if (it_a->first != it_b->first || it_a->second != it_b->second) {
equal = false;
}
}
if (equal) os << "Skip_list a == b " << "PASSED\n";
else os << "Skip_list a == b " << "FAILED\n";
a.clear();
if (a.begin() == a.end() && b.begin() == b.end()) os << "Skip_list a != b " << "FAILED\n";
else os << "Skip_list a != b " << "PASSED\n";
os << "test_copy_constructor FINISHED\n\n";
}
void move_constructor(std::ostream& os)
{
os << "test_move_constructor START\n";
Skip_list<int, int> a;
for (int i = 2; i<10; ++i)
a.insert(std::make_pair( i , i + 10 ));
Skip_list<int,int> a_before{ a }; // make tmp copy to check with b
Skip_list<int, int> b{ std::move(a) };
auto it_a_before = a.begin();
auto it_b = b.begin();
bool equal = true;
for (; it_a_before != a_before.end(), it_b != b.end(); ++it_a_before, ++it_b) {
if (it_a_before != a_before.end() && it_b != b.end()) {
if (it_a_before->first != it_b->first || it_a_before->second != it_b->second) {
equal = false;
}
}
}
os << "move content of a into b\n";
if (equal) os << "Skip_list a(before move) == b " << "PASSED\n";
else os << "Skip_list a(before move) == b " << "FAILED\n";
for (int i = 12; i<15; ++i)
a.insert(std::make_pair( i , i + 20 ));
os << "test_move_constructor FINISHED\n\n";
}
void copy_assignment(std::ostream& os)
{
os << "test_copy_assignment START\n";
Skip_list<int, int> a;
for (int i = 2; i<10; ++i)
a.insert(std::make_pair( i , i + 10 ));
Skip_list<int, int> b = a;
auto it_a = a.begin();
auto it_b = b.begin();
bool equal = true;
for (; it_a != a.end(), it_b != b.end(); ++it_a, ++it_b) {
if (it_a->first != it_b->first || it_a->second != it_b->second) {
equal = false;
}
}
if (equal) os << "Skip_list a == b " << "PASSED\n";
else os << "Skip_list a == b " << "FAILED\n";
a.clear();
if (a.begin() == a.end() && b.begin() == b.end()) os << "Skip_list a != b " << "FAILED\n";
else os << "Skip_list a != b " << "PASSED\n";
os << "test_copy_constructor FINISHED\n\n";
}
void move_assignment(std::ostream& os)
{
os << "test_move_assignment START\n";
Skip_list<int, int> a;
for (int i = 2; i<10; ++i)
a.insert(std::make_pair( i , i + 10 ));
Skip_list<int, int> a_before{ a }; // make tmp copy to check with b
Skip_list<int, int> b = std::move(a);
auto it_a_before = a.begin();
auto it_b = b.begin();
bool equal = true;
for (; it_a_before != a_before.end(), it_b != b.end(); ++it_a_before, ++it_b) {
if (it_a_before != a_before.end() && it_b != b.end()) {
if (it_a_before->first != it_b->first || it_a_before->second != it_b->second) {
equal = false;
}
}
}
os << "move content of a into b\n";
if (equal) os << "Skip_list a(before move) == b " << "PASSED\n";
else os << "Skip_list a(before move) == b " << "FAILED\n";
for (int i = 12; i<15; ++i)
a.insert(std::make_pair(i , i + 20 ));
os << "test_move_constructor FINISHED\n\n";
}
void run_all(std::ostream& os)
{
copy_constructor(os);
move_constructor(os);
copy_assignment(os);
move_assignment(os);
}
}
namespace iterator {
void iterator(std::ostream& os)
{
os << "test_iterator START\n";
std::vector<std::pair<int, int>> insert =
{
{ 1 , 10 },
{ 2 , 11 },
{ 3 , 12 },
{ 4 , 13 },
{ 5 , 14 },
{ 6 , 15 },
};
Skip_list<int, int> test;
for (const auto& x : insert) {
test.insert(x);
}
for (Skip_list<int, int>::iterator it = test.begin(); it != test.end(); ++it) {
os << (*it).first << '/' << (*it).second << '\n';
}
for (const auto& x : test)
os << x.first << '/' << x.second << '\n';
auto it1 = test.begin();
auto it2 = test.end();
os << "auto it1 = test.begin();\t";
os << "auto it2 = test.end()\n";
if (it1 != it2) os << "(it1 != it2) " << "PASSED" << '\n';
else os << "(it1 != it2) " << "FAILED" << '\n';
if (it1 == it1) os << "(it1 == it1) " << "PASSED" << '\n';
else os << "(it1 == it1) " << "FAILED" << '\n';
if (it1 < it2) os << "(it1 < it2) " << "PASSED" << '\n';
else os << "(it1 < it2) " << "FAILED" << '\n';
if (it2 > it1) os << "(it2 > it1) " << "PASSED" << '\n';
else os << "(it2 > it1) " << "FAILED" << '\n';
if (it1 <= it2) os << "(it1 <= it2) " << "PASSED" << '\n';
else os << "(it1 <= it2) " << "FAILED" << '\n';
if (it2 >= it2) os << "(it2 >= it2) " << "PASSED" << '\n';
else os << "(it2 >= it2) " << "FAILED" << '\n';
it2 = it1 + 3;
it1 += 3;
if (it1->first == 4 && it1->second == 13) os << "it1 += 3; " << "PASSED" << '\n';
else os << "it1 += 3; " << "FAILED" << '\n';
if (it2->first == 4 && it2->second == 13) os << "it2 = it1 + 3; " << "PASSED" << '\n';
else os << "it2 = it1 + 3; " << "FAILED" << '\n';
os << "test_iterator FINISHED\n\n";
}
void const_iterator(std::ostream& os)
{
os << "test_const_iterator START\n";
std::vector<std::pair<int, int>> insert =
{
{ std::make_pair( 1 , 10 ) },
{ std::make_pair( 2 , 11 ) },
{ std::make_pair( 3 , 12 ) },
{ std::make_pair( 4 , 13 ) },
{ std::make_pair( 5 , 14 ) },
{ std::make_pair( 6 , 15 ) },
};
Skip_list<int, int> test;
for (const auto& x : insert) {
test.insert(x);
}
for (Skip_list<int, int>::const_iterator it = test.cbegin(); it != test.cend(); ++it) {
os << (*it).first << '/' << (*it).second << '\n';
}
for (const auto& x : test)
os << x.first << '/' << x.second << '\n';
auto it1 = test.begin();
auto it2 = test.end();
os << "auto it1 = test.begin();\n";
os << "auto it2 = test.end()\n";
if (it1 < it2) os << "(it1 < it2) " << "PASSED" << '\n';
else os << "(it1 < it2) " << "FAILED" << '\n';
if (it1 <= it2) os << "(it1 < it2) " << "PASSED" << '\n';
else os << "(it1 < it2) " << "FAILED" << '\n';
if (it1 <= it1) os << "(it1 <= it1) " << "PASSED" << '\n';
else os << "(it1 <= it1) " << "FAILED" << '\n';
if (it2 > it1) os << "(it2 > it1) " << "PASSED" << '\n';
else os << "(it2 > it1) " << "FAILED" << '\n';
if (it2 >= it2) os << "(it2 >= it2) " << "PASSED" << '\n';
else os << "(it2 >= it2) " << "FAILED" << '\n';
if (it1 != it2) os << "(it1 != it2) " << "PASSED" << '\n';
else os << "(it1 != it2) " << "FAILED" << '\n';
if (it1 == it1) os << "(it1 == it1) " << "PASSED" << '\n';
else os << "(it1 == it1) " << "FAILED" << '\n';
it2 = it1 + 3;
it1 += 3;
if (it1->first == 4 && it1->second == 13) os << "it1 += 3; " << "PASSED" << '\n';
else os << "it1 += 3; " << "FAILED" << '\n';
if (it2->first == 4 && it2->second == 13) os << "it2 = it1 + 3; " << "PASSED" << '\n';
else os << "it2 = it1 + 3; " << "FAILED" << '\n';
os << "test_const_iterator FINISHED\n\n";
}
void run_all(std::ostream& os)
{
iterator(os);
const_iterator(os);
}
}
namespace capacity {
void empty(std::ostream& os)
{
os << "test_empty START\n";
Skip_list<int, int> sk;
if (sk.empty()) os << "empty == true" << " PASSED" << '\n';
else os << "empty == true" << " FAILED" << '\n';
sk.insert({ std::make_pair( 1 , 10 ) });
sk.debug_print(os);
if (!sk.empty()) os << "empty == false" << " PASSED" << '\n';
else os << "empty == false" << " FAILED" << '\n';
os << "test_empty FINISHED\n\n";
}
void max_size(std::ostream& os)
{
os << "test_max_size START\n";
Skip_list<int, int> sk;
os << sk.max_size() << '\n';
os << "test_max_size FINISHED\n\n";
}
void run_all(std::ostream& os)
{
empty(os);
max_size(os);
}
}
namespace modifiers {
void insert_and_erase(std::ostream& os)
{
os << "test_insert_and_erase START\n";
Skip_list<int, int> Skip_list;
std::vector<int> keys{ 1,6,2,7,3,8,4,9,5 };
for (const auto& x : keys) {
auto ret = Skip_list.insert(std::make_pair(x , x + 10 ));
os << "insert " << x << " Iterator " << ret.first->first;
if ((*ret.first).first == x) os << " PASSED\n"; // key == iterator == inserted
else os << " FAILED\n";
os << "insert " << x << " True " << std::boolalpha << ret.second; // on insert the true flag should be set
if (ret.second) os << " PASSED\n";
else os << " FAILED\n";
}
std::sort(keys.begin(), keys.end());
for (const auto& x : keys) {
if (Skip_list.erase(x)) os << "Delete " << x << " PASSED\n";
else os << "Delete " << x << " FAILED\n";
}
os << "test_insert_and_erase FINNISHED\n\n";
}
void insert_same(std::ostream& os)
{
os << "insert_same START\n";
Skip_list<int, int> sk;
sk.insert(std::make_pair( 1 , 5 ));
if(sk[1] == 5) os << "sk[1] == 5" << " PASSED\n";
else os << "sk[1] == 5" << " FAILED\n";
if (sk.size() == 1) os << "sk.size() == 1" << " PASSED\n";
else os << "sk.size() == 1" << " FAILED\n";
sk.insert(std::make_pair( 1 , 10 ));
if (sk[1] == 10) os << "sk[1] == 10" << " PASSED\n";
else os << "sk[1] == 10" << " FAILED\n";
if(sk.size() == 1) os << "sk.size() == 1" << " PASSED\n";
else os << "sk.size() == 1" << " FAILED\n";
os << "insert_same FINNISHED\n\n";
}
void iterator_find(std::ostream& os)
{
os << "test_find START\n";
Skip_list<int, int> sk;
std::vector<int> keys{ 1,6,2,7,3,8,4,9,5 };
for (const auto& x : keys)
sk.insert(std::make_pair(x , x + 10 ));
sk.debug_print(os);
std::sort(keys.begin(), keys.end());
for (const auto& x : keys) {
const int search_value = x + 10;
os << "searching with key " << x << " for value " << search_value << '\t';
Skip_list<int, int>::iterator it = sk.find(x);
if (it == sk.end()) {
os << "TEST FAILED\n";
continue;
}
os << "found:" << it->second << '\t';
if (it->second == search_value)
os << "TEST PASSED\n";
else
os << "TEST FAILED\n";
}
const int invalid_key = keys.back() + 1;
os << "searching with key " << invalid_key << " not in Skip_list" << '\t';
auto it = sk.find(invalid_key); // insert element which should not be found
if (it == sk.end()) {
os << "not found" << '\t';
os << "TEST PASSED\n";
}
else {
os << "found:" << it->second << '\t';
os << "TEST FAILED\n";
}
os << "test_find FINNISHED\n\n";
}
void run_all(std::ostream& os)
{
insert_and_erase(os);
iterator_find(os);
}
}
namespace element_access {
void access_operator(std::ostream& os)
{
os << "test_access_operator START\n";
Skip_list<int, int> sk;
sk.insert(std::make_pair(1, 10));
sk.insert(std::make_pair(2, 20));
sk.insert(std::make_pair(3, 30));
if (sk[2] == 20) os << "sk[2] == 20" << " PASSED " << '\n';
else os << "sk[2] == 20" << " FAILED " << '\n';
const int key = 2;
if (sk[key] == 20) os << "sk[const 2] == 20" << " PASSED " << '\n';
else os << "sk[const 2] == 20" << " FAILED " << '\n';
os << "test_access_operator FINISHED\n\n";
}
void run_all(std::ostream& os)
{
access_operator(os);
}
}
namespace misc {
void performance_of_insert_delete(std::ostream& os, const int repeats, const int count_of_elements)
{
os << "test_performance_of_insert_delete START\n";
std::vector <int> rnd;
std::map <int, int > mp;
for (int i = 0; i < repeats; ++i) {
//fill vector with n unique random elements
for (int j = 0; j < count_of_elements; ++j) {
int in = 0;
while (true) {
in = get_random(1, std::numeric_limits<int>::max());
bool twice = false;
auto it = mp.find(in);
if (it == mp.end())
break;
}
rnd.push_back(in);
mp.insert(std::make_pair(in, i));
}
os << rnd.size() << "\n";
mp.clear();
os << '\n';
//fill map and Skip_list and compar
// fill Skip_list
auto begin_sk = std::chrono::system_clock::now();
Skip_list<int, int> sk;
for (std::size_t i = 0; i < rnd.size(); ++i)
sk.insert(std::make_pair( rnd[i] , static_cast<Skip_list<int, int>::mapped_type>(i) ));
auto end_sk = std::chrono::system_clock::now();
os << "Skip_list filled. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_sk - begin_sk).count() << "\n";
// erase Skip_list
auto begin_sk_d = std::chrono::system_clock::now();
for (std::size_t i = 0; i < rnd.size(); ++i)
sk.erase(rnd[i]);
auto end_sk_d = std::chrono::system_clock::now();
os << "Skip_list deleted. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_sk_d - begin_sk_d).count() << "\n";
os << '\n';
// fill map
auto begin_mp = std::chrono::system_clock::now();
std::map<int, int> mp;
for (std::size_t i = 0; i < rnd.size(); ++i)
mp.insert(std::pair<int, int>(rnd[i], i));
auto end_mp = std::chrono::system_clock::now();
os << "map filled. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_mp - begin_mp).count() << "\n";
// erase map
auto begin_mp_d = std::chrono::system_clock::now();
for (std::size_t i = 0; i < rnd.size(); ++i)
mp.erase(rnd[i]);
auto end_mp_d = std::chrono::system_clock::now();
os << "map deleted. Time:" << std::chrono::duration_cast<std::chrono::milliseconds>(end_mp_d - begin_mp_d).count() << "\n";
os << '\n';
}
os << "test_performance_of_insert_delete FINISHED\n\n";
}
void leakage_of_memory(std::ostream& os)
// insert and erase repeatly into a skip list
// if no memory leak there shouldnt be more memory and more memory used
{
std::vector<int>keys;
constexpr int fill_size = 100000;;
constexpr int repeats = 10;
for (int i = 0; i < fill_size; ++i)
keys.push_back(i);
Skip_list<int, int> Skip_list;
for (int i = 0; i < repeats; ++i) {
for (const auto&x : keys)
Skip_list.insert(std::make_pair( x , x + 10 ));
for (const auto&x : keys)
Skip_list.erase(x);
}
}
void debug_print(std::ostream& os)
{
os << "test_debug_print START\n";
Skip_list<int, int> sk;
for (int i = 0; i < 10; ++i) {
sk.insert(std::make_pair(i, i * 2));
}
sk.debug_print(os);
os << "test_debug_print FINISHED\n\n";
}
}
</code></pre>
<p><b> main.cpp </b></p>
<pre><code>#include <fstream>
#include "skip_list_unit_test.h"
int main()
try {
std::ofstream ofs{ "skip_list_unit_test_results.txt" };
skip_list::unit_test::copy_and_assignment::run_all(ofs);
skip_list::unit_test::iterator::run_all(ofs);
skip_list::unit_test::capacity::run_all(ofs);
skip_list::unit_test::modifiers::run_all(ofs);
skip_list::unit_test::element_access::run_all(ofs);
skip_list::unit_test::misc::debug_print(ofs);
//skip_list::unit_test::misc::leakage_of_memory(ofs);
skip_list::unit_test::misc::performance_of_insert_delete(ofs,3, 1'000'000);
}
catch (std::runtime_error& e) {
std::cerr << e.what() << "\n";
std::cin.get();
}
catch (...) {
std::cerr << "unknown error\n";
std::cin.get();
}
</code></pre>
<p>There are some implementation details which bother me:</p>
<p><code>struct Skip_node</code> and <code>std::vector<Skip_node*> head</code> are declared as private before public declarations follow because some public functions need to know them before The remaining <code>private</code> functions follow. Can this be simplified (defining the iterator outside of the class?)?</p>
<p><code>find</code>s definitions only differ in constness. Is it possible to implement them both more efficient, not duplicating most of the code?</p>
<p>I defined short functions directly in the class. Is this a good practice or does it destroy readability in you're opinion?</p>
<p>I wonder if i did everything with the templating the correct way?</p>
<p>Please let me know any improvements suggestions which come in youre mind while checking the code.</p>
| [] | [
{
"body": "<h1><code>skip_list.h</code></h1>\n\n<pre><code>#include <map> // std::pair\n#include <random> // generation of the levels\n#include <vector> // for head implementation\n</code></pre>\n\n<p>You're missing quite a few includes for some of the stuff you use in you... | {
"AcceptedAnswerId": "199942",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T20:11:33.527",
"Id": "199706",
"Score": "8",
"Tags": [
"c++",
"performance",
"c++11",
"collections",
"skip-list"
],
"Title": "Generic Skip list implementation in C++ Version 3"
} | 199706 |
<p>I'm not sure what I'm doing wrong yet, but while I continue to figure it out, I'd love to get some input from others w/ experience. The goal is to cipher the plaintext using a key provided at the command line. I can't wrap my head around why my ciphertext comes out the same as my plaintext. I seem to have figured out case preserving and wrapping around the alphabet, but I'm stuck with this part. Included libraries: stdio.h, stdlib.h, string.h.</p>
<pre><code>int main(int argc, string argv[])
{
int e = 0;
string k;
string p;
int key;
if (argc == 2)
{
k = argv[1];
}
else
{
e++;
printf("Error: %i\n", e);
}
key = atoi(argv[1]);
p = get_string("plaintext: ");
for (int i = 0, n = strlen(p); i < n; i++)
{
if (p[n] >= 'a' && p[n] <= 'z')
{
p[n] = (p[i] + key - 'a') % 26 + 'a';
}
else if (p[n] >= 'A' && p[n] <= 'Z')
{
p[n] = (p[i] + key - 'A') % 26 + 'A';
}
}
printf("ciphertext: %s\n", p);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Bugs:<br>\n1) You're using p[n] instead of p[i]<br>\n2) The top section with k and e serves no purpose.</p>\n\n<p>Style:<br>\n1) Your variables need better (more descriptive) names.</p>\n\n<p>Aside from the bug, the algorithm looks correct. As an improvement, having it take key / input file / out... | {
"AcceptedAnswerId": "199714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-17T23:18:23.983",
"Id": "199713",
"Score": "-4",
"Tags": [
"c",
"caesar-cipher"
],
"Title": "Caesar cipher in C. My plaintext won't shift and the cipher text outcome is identical to it"
} | 199713 |
<p>I am trying to improve the run time of a program I wrote in R. Generally, what I am doing is feeding a function a data frame of values and generating a prediction off of operations on specific columns. The function is a custom function that is being used with <code>sapply</code> (code below). What I'm doing is much too large to provide any meaningful example, so instead I will try to describe the inputs to the process. I know this will restrict how helpful answers can be, but I am interested in any ideas for optimizing the time it takes me to compute a prediction. Currently it is taking me about 10 seconds to generate one prediction (running the <code>sapply</code> for one line of a dataframe).</p>
<pre><code>mean_rating <- function(df){
user<-df$user
movie<-df$movie
u_row<-which(U_lookup == user)[1]
m_row<-which(M_lookup==movie)[1]
knn_match<- knn_txt[u_row,1:100]
knn_match1<-as.numeric(unlist(knn_match))
dfm_test<- dfm[knn_match1,]
dfm_mov<- dfm_test[,m_row] # row number from DFM associated with the query_movie
C<-mean(dfm_mov)
}
test<-sapply(1:nrow(probe_test),function(x) mean_rating(probe_test[x,]))
</code></pre>
<p>Inputs: dfm is my main data matrix, users in the rows and movies in the columns. Very sparse.</p>
<pre><code>> str(dfm)
Formal class 'dgTMatrix' [package "Matrix"] with 6 slots
..@ i : int [1:99072112] 378 1137 1755 1893 2359 3156 3423 4380 5103 6762 ...
..@ j : int [1:99072112] 0 0 0 0 0 0 0 0 0 0 ...
..@ Dim : int [1:2] 480189 17770
..@ Dimnames:List of 2
.. ..$ : NULL
.. ..$ : NULL
..@ x : num [1:99072112] 4 5 4 1 4 5 4 5 3 3 ...
..@ factors : list()
</code></pre>
<p>probe_test is my test set, the set I'm trying to predict for. The actual probe test contains approximately 1.4 million rows but I am trying it on a subset first to optimize the time. It is being fed into my function.</p>
<pre><code>> str(probe_test)
'data.frame': 6 obs. of 6 variables:
$ X : int 1 2 3 4 5 6
$ movie : int 1 1 1 1 1 1
$ user : int 1027056 1059319 1149588 1283744 1394012 1406595
$ Rating : int 3 3 4 3 5 4
$ Rating_Date: Factor w/ 1929 levels "2000-01-06","2000-01-08",..: 1901 1847 1911 1312 1917 1803
$ Indicator : int 1 1 1 1 1 1
</code></pre>
<p>U_lookup is the lookup I use to convert between user id and the line of the matrix a user is in since we lose user id's when they are converted to a sparse matrix.</p>
<pre><code>> str(U_lookup)
'data.frame': 480189 obs. of 1 variable:
$ x: int 10 100000 1000004 1000027 1000033 1000035 1000038 1000051 1000053 1000057 ...
</code></pre>
<p>M_lookup is the lookup I use to convert between movie id and the column of a matrix a movie is in for similar reasons as above.</p>
<pre><code>> str(M_lookup)
'data.frame': 17770 obs. of 1 variable:
$ x: int 1 10 100 1000 10000 10001 10002 10003 10004 10005 ...
</code></pre>
<p>knn_text contains the 100 nearest neighbors for all the lines of dfm</p>
<pre><code>> str(knn_txt)
'data.frame': 480189 obs. of 200 variables:
</code></pre>
<p>Does anyone have suggestions on how I could improve performance within R? Does anyone have other language suggestions? I am slightly familiar with Python so I've been looking into that one, but if anyone has specific tips on redoing this in Python I would be grateful as I'm very inexperienced with it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T06:18:41.557",
"Id": "384320",
"Score": "0",
"body": "@user2355903 Can you supply code that generates or simulates your data, so we can run your code? Otherwise it is really hard to help you."
},
{
"ContentLicense": "CC BY-S... | [
{
"body": "<p>Without exact your data I could think of some improvements.\nTrying to avoid redundant operations.</p>\n\n<pre><code># order data.frame by users and movies\nprobe_test <- probe_test[with(probe_test, order(user, move)), ]\n# initialize resulting column\nprobe_test$res <- rep(as.numeric(NA), n... | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T02:12:41.203",
"Id": "199718",
"Score": "2",
"Tags": [
"performance",
"r",
"clustering",
"data-mining"
],
"Title": "R function to generate predictions from ratings"
} | 199718 |
<p>I need to send email notifications for expired licenses:</p>
<ul>
<li>One Day Before/After Expiration</li>
<li>Two Days Before/After Expiration</li>
<li>Three Days Before/After Expiration</li>
<li>One Week Before/After Expiration</li>
<li>Two Weeks Before/After Expiration</li>
<li>One Month Before/After Expiration</li>
<li>Two Months Before/After Expiration</li>
<li>Three Months Before/After Expiration</li>
<li>At the time of Expiration</li>
</ul>
<p>This is the Stored procedure to fetch expired licenses.</p>
<pre><code>DELIMITER $$
DROP PROCEDURE IF EXISTS `licensetrack`$$
CREATE PROCEDURE `licensetrack`()
BEGIN
DECLARE varOneDay INT;
DECLARE varTwoDay INT;
DECLARE varThreeDay INT;
DECLARE varOneWeek INT;
DECLARE varTwoWeek INT;
DECLARE varOneMonth INT;
DECLARE varTwoMonth INT;
DECLARE varThreeMonth INT;
DECLARE varAtTheTime INT;
DROP TEMPORARY TABLE IF EXISTS templicense;
CREATE TEMPORARY TABLE IF NOT EXISTS templicense(
TYPE VARCHAR(50) NOT NULL,
entityID BIGINT NOT NULL,
expirationDate DATE,
beforeOneDay DATE,
afterOneDay DATE,
beforeTwoDay DATE,
afterTwoDay DATE,
beforeThreeDay DATE,
afterThreeDay DATE,
beforeOneWeek DATE,
afterOneWeek DATE,
beforeTwoWeek DATE,
afterTwoWeek DATE,
beforeOneMonth DATE,
afterOneMonth DATE,
beforeTwoMonth DATE,
afterTwoMonth DATE,
beforeThreeMonth DATE,
afterThreeMonth DATE,
atTheTime DATE
) ;
INSERT INTO templicense(TYPE,entityID,expirationDate,beforeOneDay,afterOneDay, beforeTwoDay,afterTwoDay,beforeThreeDay,afterThreeDay,beforeOneWeek,afterOneWeek,beforeTwoWeek,
afterTwoWeek,beforeOneMonth,afterOneMonth,beforeTwoMonth,afterTwoMonth,beforeThreeMonth,afterThreeMonth,atTheTime)
SELECT 'Organ' AS TYPE, ID AS entityID, expirationDate AS expirationDate,
DATE_SUB(expirationDate, INTERVAL 1 DAY) beforeOneDay, DATE_SUB(expirationDate, INTERVAL -1 DAY) afterOneDay,
DATE_SUB(expirationDate, INTERVAL 2 DAY) beforeTwoDay, DATE_SUB(expirationDate, INTERVAL -2 DAY) afterTwoDay,
DATE_SUB(expirationDate, INTERVAL 3 DAY) beforeThreeDay, DATE_SUB(expirationDate, INTERVAL -3 DAY) afterThreeDay,
DATE_SUB(expirationDate, INTERVAL 1 WEEK) beforeOneWeek, DATE_SUB(expirationDate, INTERVAL -1 WEEK) afterOneWeek,
DATE_SUB(expirationDate, INTERVAL 2 WEEK) beforeTwoWeek, DATE_SUB(expirationDate, INTERVAL -2 WEEK) afterTwoWeek,
DATE_SUB(expirationDate, INTERVAL 1 MONTH) beforeOneMonth, DATE_SUB(expirationDate, INTERVAL -1 MONTH) afterOneMonth,
DATE_SUB(expirationDate, INTERVAL 2 MONTH) beforeTwoMonth, DATE_SUB(expirationDate, INTERVAL -2 MONTH) afterTwoMonth,
DATE_SUB(expirationDate, INTERVAL 3 MONTH) beforeThreeMonth, DATE_SUB(expirationDate, INTERVAL -3 MONTH) afterThreeMonth,
DATE_SUB(expirationDate, INTERVAL 0 DAY) atTheTime
FROM organizationlicenses orglic;
INSERT INTO templicense(TYPE,entityID,expirationDate,beforeOneDay,afterOneDay, beforeTwoDay,afterTwoDay,beforeThreeDay,afterThreeDay,beforeOneWeek,afterOneWeek,beforeTwoWeek,
afterTwoWeek,beforeOneMonth,afterOneMonth,beforeTwoMonth,afterTwoMonth,beforeThreeMonth,afterThreeMonth,atTheTime)
SELECT 'Location' AS TYPE, ID AS entityID, expirationDate AS expirationDate,
DATE_SUB(expirationDate, INTERVAL 1 DAY) beforeOneDay, DATE_SUB(expirationDate, INTERVAL -1 DAY) afterOneDay,
DATE_SUB(expirationDate, INTERVAL 2 DAY) beforeTwoDay, DATE_SUB(expirationDate, INTERVAL -2 DAY) afterTwoDay,
DATE_SUB(expirationDate, INTERVAL 3 DAY) beforeThreeDay, DATE_SUB(expirationDate, INTERVAL -3 DAY) afterThreeDay,
DATE_SUB(expirationDate, INTERVAL 1 WEEK) beforeOneWeek, DATE_SUB(expirationDate, INTERVAL -1 WEEK) afterOneWeek,
DATE_SUB(expirationDate, INTERVAL 2 WEEK) beforeTwoWeek, DATE_SUB(expirationDate, INTERVAL -2 WEEK) afterTwoWeek,
DATE_SUB(expirationDate, INTERVAL 1 MONTH) beforeOneMonth, DATE_SUB(expirationDate, INTERVAL -1 MONTH) afterOneMonth,
DATE_SUB(expirationDate, INTERVAL 2 MONTH) beforeTwoMonth, DATE_SUB(expirationDate, INTERVAL -2 MONTH) afterTwoMonth,
DATE_SUB(expirationDate, INTERVAL 3 MONTH) beforeThreeMonth, DATE_SUB(expirationDate, INTERVAL -3 MONTH) afterThreeMonth,
DATE_SUB(expirationDate, INTERVAL 0 DAY) atTheTime
FROM locationlicenses loclic;
INSERT INTO templicense(TYPE,entityID,expirationDate,beforeOneDay,afterOneDay, beforeTwoDay,afterTwoDay,beforeThreeDay,afterThreeDay,beforeOneWeek,afterOneWeek,beforeTwoWeek,
afterTwoWeek,beforeOneMonth,afterOneMonth,beforeTwoMonth,afterTwoMonth,beforeThreeMonth,afterThreeMonth,atTheTime)
SELECT 'EmpLicense' AS TYPE, ID AS entityID, expirationDate AS expirationDate,
DATE_SUB(expirationDate, INTERVAL 1 DAY) beforeOneDay, DATE_SUB(expirationDate, INTERVAL -1 DAY) afterOneDay,
DATE_SUB(expirationDate, INTERVAL 2 DAY) beforeTwoDay, DATE_SUB(expirationDate, INTERVAL -2 DAY) afterTwoDay,
DATE_SUB(expirationDate, INTERVAL 3 DAY) beforeThreeDay, DATE_SUB(expirationDate, INTERVAL -3 DAY) afterThreeDay,
DATE_SUB(expirationDate, INTERVAL 1 WEEK) beforeOneWeek, DATE_SUB(expirationDate, INTERVAL -1 WEEK) afterOneWeek,
DATE_SUB(expirationDate, INTERVAL 2 WEEK) beforeTwoWeek, DATE_SUB(expirationDate, INTERVAL -2 WEEK) afterTwoWeek,
DATE_SUB(expirationDate, INTERVAL 1 MONTH) beforeOneMonth, DATE_SUB(expirationDate, INTERVAL -1 MONTH) afterOneMonth,
DATE_SUB(expirationDate, INTERVAL 2 MONTH) beforeTwoMonth, DATE_SUB(expirationDate, INTERVAL -2 MONTH) afterTwoMonth,
DATE_SUB(expirationDate, INTERVAL 3 MONTH) beforeThreeMonth, DATE_SUB(expirationDate, INTERVAL -3 MONTH) afterThreeMonth,
DATE_SUB(expirationDate, INTERVAL 0 DAY) atTheTime
FROM employeelicenses emplic;
INSERT INTO templicense(TYPE,entityID,expirationDate,beforeOneDay,afterOneDay, beforeTwoDay,afterTwoDay,beforeThreeDay,afterThreeDay,beforeOneWeek,afterOneWeek,beforeTwoWeek,
afterTwoWeek,beforeOneMonth,afterOneMonth,beforeTwoMonth,afterTwoMonth,beforeThreeMonth,afterThreeMonth,atTheTime)
SELECT 'EmpDrivingLicense' AS TYPE, ID AS entityID, expirationDate AS expirationDate,
DATE_SUB(expirationDate, INTERVAL 1 DAY) beforeOneDay, DATE_SUB(expirationDate, INTERVAL -1 DAY) afterOneDay,
DATE_SUB(expirationDate, INTERVAL 2 DAY) beforeTwoDay, DATE_SUB(expirationDate, INTERVAL -2 DAY) afterTwoDay,
DATE_SUB(expirationDate, INTERVAL 3 DAY) beforeThreeDay, DATE_SUB(expirationDate, INTERVAL -3 DAY) afterThreeDay,
DATE_SUB(expirationDate, INTERVAL 1 WEEK) beforeOneWeek, DATE_SUB(expirationDate, INTERVAL -1 WEEK) afterOneWeek,
DATE_SUB(expirationDate, INTERVAL 2 WEEK) beforeTwoWeek, DATE_SUB(expirationDate, INTERVAL -2 WEEK) afterTwoWeek,
DATE_SUB(expirationDate, INTERVAL 1 MONTH) beforeOneMonth, DATE_SUB(expirationDate, INTERVAL -1 MONTH) afterOneMonth,
DATE_SUB(expirationDate, INTERVAL 2 MONTH) beforeTwoMonth, DATE_SUB(expirationDate, INTERVAL -2 MONTH) afterTwoMonth,
DATE_SUB(expirationDate, INTERVAL 3 MONTH) beforeThreeMonth, DATE_SUB(expirationDate, INTERVAL -3 MONTH) afterThreeMonth,
DATE_SUB(expirationDate, INTERVAL 0 DAY) atTheTime
FROM employeedriving drilic;
INSERT INTO templicense(TYPE,entityID,expirationDate,beforeOneDay,afterOneDay, beforeTwoDay,afterTwoDay,beforeThreeDay,afterThreeDay,beforeOneWeek,afterOneWeek,beforeTwoWeek,
afterTwoWeek,beforeOneMonth,afterOneMonth,beforeTwoMonth,afterTwoMonth,beforeThreeMonth,afterThreeMonth,atTheTime)
SELECT 'EmpImgLicense' AS TYPE, ID AS entityID, expiredDate AS expirationDate,
DATE_SUB(expiredDate, INTERVAL 1 DAY) beforeOneDay, DATE_SUB(expiredDate, INTERVAL -1 DAY) afterOneDay,
DATE_SUB(expiredDate, INTERVAL 2 DAY) beforeTwoDay, DATE_SUB(expiredDate, INTERVAL -2 DAY) afterTwoDay,
DATE_SUB(expiredDate, INTERVAL 3 DAY) beforeThreeDay, DATE_SUB(expiredDate, INTERVAL -3 DAY) afterThreeDay,
DATE_SUB(expiredDate, INTERVAL 1 WEEK) beforeOneWeek, DATE_SUB(expiredDate, INTERVAL -1 WEEK) afterOneWeek,
DATE_SUB(expiredDate, INTERVAL 2 WEEK) beforeTwoWeek, DATE_SUB(expiredDate, INTERVAL -2 WEEK) afterTwoWeek,
DATE_SUB(expiredDate, INTERVAL 1 MONTH) beforeOneMonth, DATE_SUB(expiredDate, INTERVAL -1 MONTH) afterOneMonth,
DATE_SUB(expiredDate, INTERVAL 2 MONTH) beforeTwoMonth, DATE_SUB(expiredDate, INTERVAL -2 MONTH) afterTwoMonth,
DATE_SUB(expiredDate, INTERVAL 3 MONTH) beforeThreeMonth, DATE_SUB(expiredDate, INTERVAL -3 MONTH) afterThreeMonth,
DATE_SUB(expiredDate, INTERVAL 0 DAY) atTheTime
FROM employeeimages empimglic;
select oneDay,twoDay,threeDay,oneWeek,
twoWeek,oneMonth , twoMonth,threeMonth ,atTheTime
into varOneDay,varTwoDay,varThreeDay,varOneWeek,varTwoWeek,varOneMonth,varTwoMonth,
varThreeMonth,varAtTheTime from licensetrackinterval;
if varOneDay = 0 then
update templicense set beforeOneDay= null ,afterOneDay= NULL;
end if;
IF varTwoDay = 0 THEN
UPDATE templicense SET beforeTwoDay= NULL,afterTwoDay= NULL;
END IF;
IF varThreeDay = 0 THEN
UPDATE templicense SET beforeThreeDay= NULL, afterThreeDay= NULL;
END IF;
IF varOneWeek = 0 THEN
UPDATE templicense SET beforeOneWeek= NULL, afterOneWeek= NULL;
END IF;
IF varTwoWeek= 0 THEN
UPDATE templicense SET beforeTwoWeek= NULL,afterTwoWeek= NULL;
END IF;
IF varOneMonth = 0 THEN
UPDATE templicense SET beforeOneMonth= NULL,afterOneMonth= NULL;
END IF;
IF varTwoMonth = 0 THEN
UPDATE templicense SET beforeTwoMonth= NULL,afterTwoMonth= NULL;
END IF;
IF varThreeMonth = 0 THEN
UPDATE templicense SET beforeThreeMonth= NULL,afterThreeMonth= NULL;
END IF;
IF varAtTheTime = 0 THEN
UPDATE templicense SET atTheTime= NULL;
END IF;
select * from templicense ;
END$$
DELIMITER ;
</code></pre>
| [] | [
{
"body": "<p>You can use below reference for your requirement. I did for positive date difference only. you can write for negative values as well in CASE WHEN.</p>\n\n<pre><code> SELECT expirationDate, \n CASE WHEN DATEDIFF(expirationDate, NOW()) = 1 THEN 1\n WHEN DATEDIFF(expiratio... | {
"AcceptedAnswerId": "201355",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T04:06:46.543",
"Id": "199721",
"Score": "3",
"Tags": [
"sql",
"mysql",
"datetime",
"database",
"stored-procedure"
],
"Title": "Stored procedure for sending emails at specified times after license expiration"
} | 199721 |
<pre><code>def add(a,b):
for i in xrange(a-1,b):
box[i]+=1
def count(k):
if box.count(k)!=0:
box.index(k)
return len(box)-box.index(k)
else:
return 0
from sys import stdin,stdout
box=[0]*int(stdin.readline()) #input the number of boxes of chocolate
for i in xrange(int(stdin.readline())): #loops for M days
a,b = stdin.readline().split() #gets the starting and ending index.
add(int(a),int(b)) #adding 1 each time to box for I,R
box.sort()
for i in xrange(int(stdin.readline())):
print count(int(stdin.readline())) #prints the number of boxes of chocolates greater than equal to the input number
</code></pre>
<p>For small values the program works but fails for large value.Suggest any faster method/algorithm.</p>
<p>Constraints:
1 <= N <= 100000</p>
<p>1 <= M <= 1000</p>
<p>1 <= l <= r <= N</p>
<p>1 <= Q <= 100000</p>
<p>1 <= K <= N</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T06:46:19.590",
"Id": "384323",
"Score": "1",
"body": "Hello, and welcome to code review. \nCould I please check what you mean by \"fails for large values?\" Is it giving the wrong answer, or just taking too long to give any answer a... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T06:05:15.603",
"Id": "199724",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"time-limit-exceeded"
],
"Title": "Create list and add 1 to list values from index [I,R].Print the Occurence of a specific number"
} | 199724 |
<p>The application uses <a href="https://github.com/MichaelAguilar/NCalc" rel="nofollow noreferrer">NCalc</a> to execute diverse calculations.</p>
<p>The 'natural' way to write powers using a computer is using the <code>^</code> symbol. However, NCalc already uses it as <code>bitwise or</code>.</p>
<p>I use the following function to parse calculations and convert it to the <code>Pow(a,b)</code> format.</p>
<pre><code> Private Function _replacePower(Str As String) As String
Const PowerString As String = "Pow({0},{1})"
Dim i, j As Integer
Dim c As String
Dim before, after, all As String
Dim other_p As Integer 'Keep track of other opening/closing parenthesis, to avoid breaking for a nested one.
other_p = -1
i = 1
While i <= Len(Str)
c = Mid(Str, i, 1)
If c = "^" Then
If Mid(Str, i - 1, 1) = ")" Then
j = i - 1
Do While Mid(Str, j, 1) <> "(" Or other_p > 0
If Mid(Str, j, 1) = ")" Then other_p = other_p + 1
If Mid(Str, j, 1) = "(" Then other_p = other_p - 1
j = j - 1
Loop
before = Mid(Str, j, i - j)
Else
j = i - 1
'The expression to be raised is everything between the power and + - * / , ( <- Opening parenthesis is not ok if there is no closing one, and this case is handled above.
Do While (Mid(Str, j, 1) <> "+" And Mid(Str, j, 1) <> "-" And Mid(Str, j, 1) <> "*" And Mid(Str, j, 1) <> "/" And Mid(Str, j, 1) <> "," And Mid(Str, j, 1) <> "(")
j = j - 1
If j = 0 Then Exit Do
Loop
before = Mid(Str, j + 1, i - j - 1)
End If
other_p = -1
If Mid(Str, i + 1, 1) = "(" Or other_p > 0 Then
j = i + 1
Do While Mid(Str, j, 1) <> ")"
If Mid(Str, j, 1) = ")" Then other_p = other_p - 1
If Mid(Str, j, 1) = "(" Then other_p = other_p + 1
j = j + 1
Loop
after = Mid(Str, i + 1, j - i)
Else
j = i + 1
Do While (Mid(Str, j, 1) <> "+" And Mid(Str, j, 1) <> "-" And Mid(Str, j, 1) <> "*" And Mid(Str, j, 1) <> "/" And Mid(Str, j, 1) <> "," And Mid(Str, j, 1) <> ")")
j = j + 1
If j = Len(Str) + 1 Then Exit Do
Loop
after = Mid(Str, i + 1, j - i - 1)
End If
all = before & "^" & after
Str = Replace(Str, all, String.Format(PowerString, before, after))
i = 1
End If
i = i + 1
End While
Return Str
End Function
</code></pre>
<p>My issues lies with performance, as it appears that this function is the bottleneck of the entire application. How could I improve?</p>
| [] | [
{
"body": "<p>One of your biggest performance issues is, using <code>Mid</code> to get one character from the string. This gets the character as a string which is inefficient. It would be better to get the character as a <code>Char</code>, by using the index operator of the String class(<code>Str(j)</code>). ... | {
"AcceptedAnswerId": "199760",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T06:49:16.743",
"Id": "199725",
"Score": "3",
"Tags": [
"performance",
".net",
"vb.net",
"symbolic-math"
],
"Title": "Replace a^b by Pow(a,b)"
} | 199725 |
<p>UPD: <a href="https://codereview.stackexchange.com/questions/199829/haskell-game-server-auth-cookie-key-generatecheck">Haskell version</a>, please check it too.</p>
<p><code>gameKey(long id)</code> is authentication function of an MMO game server. When someone wants to play with friends, he sends request to server, server calls <code>gameKey()</code> and returns it as JSON to player via API. When a friend establishes connection, he sends the game id and his key, server calls <code>gameKey(id)</code>, where <code>id</code> is user data, and then checks user's key.</p>
<p>Algorithm is:</p>
<ul>
<li>use current time and internal counter to generate id if it's not provided, or use provided id</li>
<li>make fast crypto hash using Blake2 function of id and secret(Yes, I know about HMAC and using as key, but in this case it doesn't matter)</li>
<li>split 64-bit hash to four 16-bit values, one hash for one user</li>
<li>make JSON object from id and keys and return it</li>
</ul>
<p>I want to make stable code: exploit-free, no memory leaks and high speed (for high load and DDOS prevention). I'm experimenting now, so the algorithm was first written in JavaScript, because I'm skilled in JS coding. Then I rewrote JS code in C++ to increase execution speed. You can see C++ and JS code below. The C++ code is 3x faster than JS: 34s vs 10s, per 1M keys</p>
<p>Please review the C++ code; I think it can be significantly improved (I'm bad in C++). Code compiles and works same as JS. Also please advise me, which programming language is better for this: JS, C++ , Haskell or Go?</p>
<p>Here's the C++ code; it requires <code>libb2-dev</code> and <code>libjsoncpp-dev</code> (run <code>sudo apt install libb2-dev libjsoncpp-dev</code> to install it on Ubuntu):</p>
<pre><code>//"g++" "main.cpp" -o "main" -lb2 -ljsoncpp
#include <sstream>
#include <string>
#include <iostream>
#include <ctime>
#include <blake2.h>//libb2-dev
#include <jsoncpp/json/json.h>//libjsoncpp-dev
#include <iomanip>
char TOPSECRET[] = "TOPSECRET";
long dateCounter = 0;
std::string gameKey(long id2=-1){
long long id = std::time(0)*1000+dateCounter;
if(id2!=-1){
id = id2;
}
dateCounter++;
std::stringstream inStream;
inStream << id << "|keys|" << TOPSECRET;
const std::string inString = inStream.str();
const char* in = inString.c_str();
size_t outlen=64;
uint8_t* out = new uint8_t[outlen];
char key[] = "";
blake2b(out,in,&key,outlen,inString.length(),0);
std::stringstream a,b,c,d;
for(int i=0;i<16;i++){
a << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
}
for(int i=16;i<16*2;i++){
b << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
}
for(int i=16*2;i<16*3;i++){
c << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
}
for(int i=16*3;i<16*4;i++){
d << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
}
Json::Value obj(Json::objectValue);
obj["id"] = id;
Json::Value arr(Json::arrayValue);
arr.append(a.str());
arr.append(b.str());
arr.append(c.str());
arr.append(d.str());
obj["keys"] = arr;
Json::Writer* writer = new Json::FastWriter();
std::string jsonOut = writer->write(obj);
delete writer;
//delete in;//comment=memory leak, uncomment=segfault when gameKey() is called more than once
delete out;
return jsonOut;
}
int main(){
std::cout << gameKey();
std::cout << gameKey();
}
</code></pre>
<p>Here's the node.js version; it needs <code>blakejs</code> (run <code>npm i blakejs</code> to install it):</p>
<pre class="lang-js prettyprint-override"><code>const TOPSECRET = "TOPSECRET", blake = require("blakejs").blake2bHex;
let dateCounter = 0;
function gameKey(checkId){
let id = checkId || (Date.now()/1000>>0)*1000+(dateCounter++%1000),
keys = blake(`${id}|keys|${TOPSECRET}`).match(/.{32}/g);
return {id, keys};
}
console.log(gameKey());
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T09:25:06.213",
"Id": "384337",
"Score": "0",
"body": "Toby Speight, thank you for spelling check and prettify"
}
] | [
{
"body": "<p>We have better random generators in C++ than <code>std::time(0)</code>; if you're using the latter for its speed, it would really be worth a comment in the code to explain that you're willing to live with such a weak random-number source in exchange for the speed.</p>\n\n<p>Note that embedding the... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T07:03:30.720",
"Id": "199727",
"Score": "4",
"Tags": [
"c++",
"game",
"linux",
"server"
],
"Title": "Game server auth: cookie key generate&check"
} | 199727 |
<p>I've written a Vigenere decypher and I would like to have some opinions before I try to refactor it into more OOP style with classes and such.</p>
<pre><code>#include <bits/stdc++.h>
#define Rep(i,a,n) for(int i = a; i < n; i++)
#define rep(i,n) Rep(i,0,n)
using namespace std;
int main(){
string key, line, code = "", dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", decoded = "";
cin >> key;
int n = dict.length();
char** key_matrix = new char*[n];
rep(i,n)
key_matrix[i] = new char[n];
rep(i,n)
rep(j,n)
key_matrix[i][j] = dict[(i+j)%n];
fstream file;
file.open("text.txt");
while(getline(file, line))
code += line;
file.close();
rep(i,code.length()){
if(!iswspace(code[i])){
rep(j,n)
if(key_matrix[j][0] == key[i%key.length()]){
rep(k,n)
if(key_matrix[j][k] == code[i]){
decoded += key_matrix[0][k];
break;
}
}
}else{
decoded += " ";
}
}
cout << decoded;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T07:44:10.927",
"Id": "384327",
"Score": "0",
"body": "Is your odd indentation a direct result of your defines? Have you checked whether the inner loops work as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationD... | [
{
"body": "<pre><code>#include <bits/stdc++.h>\n</code></pre>\n<p>This is distinctly non-portable. The files in <code>bits/</code> are internal to GCC, may change without warning, and and are probably inefficient. Use the correct Standard C++ headers instead:</p>\n<pre><code>#include <cctype>\n#in... | {
"AcceptedAnswerId": "199732",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T07:23:58.387",
"Id": "199729",
"Score": "9",
"Tags": [
"c++",
"vigenere-cipher"
],
"Title": "Vigenere Decypher in C++"
} | 199729 |
<p>I have just started learning C# and decided to do some problems from Project Euler. I wrote a code to find 10 001st prime and I thought it would be cool optimize it to make it as fast as possible. How could I improve this to make it even faster?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace primes
{
class Program
{
static void Main(string[] args)
{
long prime = 2;
long largestprime = 2;
long potentialprime = 3;
Console.WriteLine("Enter the prime you want to find: ");
long primenum = Convert.ToInt64(Console.ReadLine());
long[] primearray = new long[primenum + 1];
primearray[1] = 2;
Stopwatch sw = new Stopwatch();
sw.Start();
while (prime <= primenum)
{
bool isprime = true;
for (long x = 1; x < prime; x += 3)
{
if (primearray[x] * primearray[x] > potentialprime)
break;
if (prime > 3 && (potentialprime % primearray[x] == 0 || potentialprime % primearray[x+1] == 0 || potentialprime % primearray[x+2] == 0))
isprime = false;
if (prime <= 3 && potentialprime % primearray[x] == 0)
isprime = false;
}
if (isprime)
{
primearray[prime] = potentialprime;
prime += 1;
largestprime = potentialprime;
}
potentialprime += 2;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + "ms to find ");
Console.WriteLine(largestprime);
Console.ReadKey();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T08:06:33.193",
"Id": "384332",
"Score": "1",
"body": "You might want to take a look at the answers of my [question](https://codereview.stackexchange.com/questions/124644/project-euler-7-10001st-prime)."
},
{
"ContentLicense"... | [
{
"body": "<p>As mentioned in the comments, you should go for more readable code:</p>\n\n<p>1) Split by responsibility:</p>\n\n<p>One method for user input:</p>\n\n<pre><code>ulong GetPrimeIndex() { // TODO: Get User input from Console }\n</code></pre>\n\n<p>The algorithm itself: </p>\n\n<pre><code>ulong FindNt... | {
"AcceptedAnswerId": "199817",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T07:42:46.000",
"Id": "199731",
"Score": "2",
"Tags": [
"c#",
"performance",
"beginner",
"programming-challenge",
"primes"
],
"Title": "Project Euler: Find 10.001st prime"
} | 199731 |
<p>I've implemented the sieve of Eratosthenes in Python 3 as follows:</p>
<pre><code>def sieve_of_eratosthenes(n):
is_prime = [True] * (n+1)
is_prime[0] = False
is_prime[1] = False
p = 0
while True:
for i, prime in enumerate(is_prime):
if prime and i > p:
p = i
break
else:
break
multiple = p + p
while multiple <= n:
is_prime[multiple]= False
multiple = multiple + p
r = []
for i, prime in enumerate(is_prime):
if prime: r.append(i)
return r
</code></pre>
<p><a href="https://tio.run/##lVLBboMwDL3nK3xM1q0C7YbWHvcFu1UIMWGENTCRCWv79SwZhJWtl/mAzHvPeeYFe3VNz8/TVGENA@EnFn1doJSuH1yDjINmkynwRUNhhTqEA5zeZMQcHkDzLjUb9pTkXvBatgNu8XSLW/@WqO/23FCLEI7MYCkVm7oXoEeYjYkBeezCdqjjwct2sahexCVXQHAEu@WjN/1B3wXLjxVFv@h2cuZXqBtbR7YNcVjYgf1h5u9Z@ZcD8K8dYyZRk98mc8dgbVcfCbeQq39HFOPJQPaltciVpvkCBd0oDKIm6mwvDpyXKXfxRqHbh4c2yk@z0y2yvv@3pEkoY6LyZvbJXcz0BQ" rel="noreferrer">Running this to 100,000</a> takes ~25 seconds. </p>
<p>I felt that was on the slow side, so I decided to take a different approach. The Sieve works prospectivly: it works ahead to clear out all multiples. I made a retrospective function, trial-dividing everything lower than the current prime-candidate:</p>
<pre><code>def retrospect(n):
primes = [2, 3]
i = 5
while i <= n:
isprime = True
lim = math.sqrt(n)+1
for p in primes:
if p > lim:
break
if i % p == 0:
isprime = False
break
if isprime:
primes.append(i)
i += 2
return primes
</code></pre>
<p>This is <a href="https://tio.run/##lVPLboMwELz7K/ZSCUoahUS9oNJjv6C3CEW0WcSqYFzbtOnXp3aMCQ5Ro/qA7H3N7swifnTd8c3xSK3opIa21DVje6xAEX7hrqt2KEvdKV0jRxXxOGNgDqmdkNQi5LB9lT0WcA8RT9I48G5XhQl4KRuFoT0N7cK8Vux0/a6pQbAlMxgO85eqk0ALcMDEAXnf2u4w8oWH7vyhaggu@R4InkGEfo9NM@ubxPJjtKJpNMx0/tHU9o0m0Vg6BCQgzh43z@h/yoFf9Og58THFlJkrAON1xJFWhYL9myJPTwZyWQqBfB@RE1Ci7iUH6VbBvGSnBL7rUf9TnrK46wVsHDaZ5@NURboYl5TfGavvaG6otWOZzVuqT2kxkjTQXNhJHOJcX6OqKZDdUHCIJrizgpttmyecu5vTPy9oi7mEsJJr84JOx06Sw5pN6XWx/tfT5sH0weDb29J@opiZGK6jBnl0/YdMV/bEsY@c5D7oQ8z@qjjR9UaZ4y8" rel="noreferrer">way faster!</a></p>
<p>Questions:</p>
<ul>
<li>Are there any obvious shortcomings to the Sieve implementation?</li>
<li>Is there a point where the retrospect gets slower than the sieve?</li>
</ul>
| [] | [
{
"body": "<blockquote>\n<pre><code> while True: \n for i, prime in enumerate(is_prime):\n if prime and i > p:\n p = i\n break\n else:\n break\n</code></pre>\n</blockquote>\n\n<p>This is the cause of the slowness: track the state bet... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T09:56:37.317",
"Id": "199734",
"Score": "16",
"Tags": [
"python",
"performance",
"python-3.x",
"primes"
],
"Title": "Python 3: Why is my prime sieve so slow?"
} | 199734 |
<p>I've designed a basic Tetris game, and implemented it in Java language. I'll use it for demonstrating software engineering, designing. I'll re-implement it in many different programming languages, in different platforms. Thus, good concept is very important.</p>
<p>Goals:</p>
<ul>
<li>Follow general OOP principles.</li>
<li>Readablity, reasonable classes/algorithms/dependencies.</li>
<li>Views must be replaceable without changing the game's basic logic (console, LED matrix output).</li>
<li>Should be easy to extend with popular features (display next tetromino, scores, time, etc.), change existing features (colors, sizes).</li>
</ul>
<p>Perforance (ie more code/abstraction), KISS/YAGNI are less important.</p>
<p>Java implementation: <a href="https://github.com/klenium/tetris/tree/b7d44dcdc6c16c61cb9aa9e59f3cd9596bf327bc/java/src/hu/klenium/tetris" rel="nofollow noreferrer">Updated version</a> | Original: <a href="https://github.com/klenium/tetris/tree/bf909fb0f07cccda8ad77a3c936523c13327c808/java/src/hu/klenium/tetris" rel="nofollow noreferrer">Full source code</a>, <a href="https://i.stack.imgur.com/29NNO.png" rel="nofollow noreferrer">Class diagram</a>, Relevant codes below:</p>
<p><strong>TetrisGame.java</strong></p>
<pre><code>public class TetrisGame {
private final static Random random = new Random();
private final int blockSize = 30;
private final int columns = 11;
private final int rows = 16;
private boolean isRunning;
private static TetrisGame instance;
private final Board board;
private Tetromino fallingTetromino;
private final PeriodicTask gravity;
private final MainWindow window;
private TetrisGame(MainWindow window) {
this.window = window;
BoardView view = new BoardView(window, blockSize);
board = new Board(rows, columns, view);
gravity = new PeriodicTask(() -> {
boolean moved = fallingTetromino.moveDown();
if (!moved)
tetrominoCantMoveFurther();
}, 700);
}
public static TetrisGame createNew(MainWindow window) {
instance = new TetrisGame(window);
return instance;
}
public static TetrisGame getInstance() {
return instance;
}
public void start() {
isRunning = true;
generateNextTetromino();
gravity.start();
}
private void stop() {
isRunning = false;
fallingTetromino.dispose();
fallingTetromino = null;
gravity.stop();
}
public void handleCommand(UserCommand command) {
if (!isRunning)
return;
switch (command) {
case ROTATE:
fallingTetromino.rotateRight();
break;
case MOVE_LEFT:
fallingTetromino.moveLeft();
break;
case MOVE_DOWN:
if (fallingTetromino.moveDown())
gravity.reset();
else
tetrominoCantMoveFurther();
break;
case MOVE_RIGHT:
fallingTetromino.moveRight();
break;
case DROP:
fallingTetromino.drop();
tetrominoCantMoveFurther();
break;
}
}
public boolean canMoveTetrominoTo(Tetromino tetromino, int x, int y) {
return board.canAddTetromino(tetromino, x, y);
}
private void tetrominoCantMoveFurther() {
board.addTetromino(fallingTetromino);
board.removeFullRows();
generateNextTetromino();
}
private void generateNextTetromino() {
if (fallingTetromino != null)
fallingTetromino.dispose();
int type = random.nextInt(7);
TetrominoView view = new TetrominoView(window, blockSize);
Tetromino next = Tetromino.createAtCenter(type, view, columns);
fallingTetromino = next;
if (next != null)
gravity.reset();
else
stop();
}
}
</code></pre>
<p><strong>Board.java</strong></p>
<pre><code>public class Board {
private final int rows;
private final int columns;
private SquareView[][] board;
private final BoardView view;
public Board(int rows, int cols, BoardView view) {
this.rows = rows;
this.columns = cols;
this.board = new SquareView[rows][cols];
this.view = view;
updateView();
}
public boolean canAddTetromino(Tetromino tetromino, int fromX, int fromY) {
SquareView[][] data = tetromino.getPolyominoData();
int height = data.length;
int width = data[0].length;
if (fromX < 0 || fromX + width > columns ||
fromY < 0 || fromY + height > rows)
return false;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (data[i][j] != null && board[fromY + i][fromX + j] != null)
return false;
}
}
return true;
}
public void addTetromino(Tetromino tetromino) {
SquareView[][] data = tetromino.getPolyominoData();
int x = tetromino.getPosX();
int y = tetromino.getPosY();
int height = data.length;
int width = data[0].length;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (data[i][j] != null)
board[y + i][x + j] = data[i][j];
}
}
updateView();
}
public void removeFullRows() {
boolean isRowFull;
for (int i = 0; i < rows; ++i) {
isRowFull = true;
for (int j = 0; j < columns && isRowFull; ++j) {
if (board[i][j] == null)
isRowFull = false;
}
if (isRowFull) {
for (int j = i; j > 0; --j)
System.arraycopy(board[j - 1], 0, board[j], 0, columns);
for (int j = 0; j < columns; ++j)
board[0][j] = null;
}
}
updateView();
}
private void updateView() {
view.update(board);
}
}
</code></pre>
<p><strong>Tetromino.java</strong></p>
<pre><code>public class Tetromino {
private SquareView[][][] partsData;
private TetrominoView view;
private int currentX = 0;
private int currentY = 0;
private int rotation;
private int width;
private int height;
private Tetromino(int type, TetrominoView view) {
this.view = view;
partsData = TetrominoDataSource.getData(type);
setRotation(0);
}
public static Tetromino createAtCenter(int type, TetrominoView view, int boardWidth) {
Tetromino tetromino = new Tetromino(type, view);
int x = (int) Math.ceil((boardWidth - tetromino.width) / 2);
boolean moved = tetromino.tryMove(x, 0);
if (!moved) {
tetromino.dispose();
return null;
}
return tetromino;
}
public void dispose() {
view.clear();
}
public SquareView[][] getPolyominoData() {
return partsData[rotation];
}
public int getPosX() {
return currentX;
}
public int getPosY() {
return currentY;
}
public boolean rotateRight() {
int nextRotation = (rotation + 1) % 4;
boolean canRotate = false;
int oldRotation = rotation;
setRotation(nextRotation);
if (canMoveTo(0, 0))
canRotate = true;
else {
for (int i = 1; i < width && !canRotate; ++i) {
if (canMoveTo(-i, 0)) {
currentX -= i;
canRotate = true;
}
}
}
if (!canRotate)
setRotation(oldRotation);
else {
setRotation(nextRotation);
updateView();
}
return canRotate;
}
public boolean moveRight() {
return tryMove(1, 0);
}
public boolean moveLeft() {
return tryMove(-1, 0);
}
public boolean moveDown() {
return tryMove(0, 1);
}
public void drop() {
boolean movedDown;
do {
movedDown = moveDown();
} while (movedDown);
}
private void setRotation(int rotation) {
this.rotation = rotation % partsData.length;
height = partsData[this.rotation].length;
width = partsData[this.rotation][0].length;
}
private void updateView() {
view.update(partsData[rotation], currentX, currentY);
}
private boolean tryMove(int x, int y) {
boolean canSlide = canMoveTo(x, y);
if (canSlide) {
currentX += x;
currentY += y;
updateView();
}
return canSlide;
}
private boolean canMoveTo(int deltaX, int deltaY) {
return TetrisGame.getInstance().canMoveTetrominoTo(this, currentX + deltaX, currentY + deltaY);
}
}
</code></pre>
<p><strong>TetrominoDataSource.java</strong></p>
<pre><code>public class TetrominoDataSource {
public static SquareView[][][] getData(int type) {
String[][] masks = rawData[type];
SquareView[][][] result = new SquareView[masks.length][][];
for (int rotation = 0; rotation < masks.length; ++rotation) {
int height = masks[rotation].length;
int width = masks[rotation][0].length();
result[rotation] = new SquareView[height][width];
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (masks[rotation][i].charAt(j) != ' ')
result[rotation][i][j] = new SquareView(type);
}
}
}
return result;
}
private static String[][][] rawData = new String[][][] {
new String[][] {
new String[] {
"XX",
"XX"
}
},
new String[][] {
new String[] {
"X",
"X",
"X",
"X"
},
new String[] {
"XXXX"
}
},
</code></pre>
<p><strong>view/TetrominoView.java</strong> (<strong>view/BoardView.java</strong> is very similar)</p>
<pre><code>public class TetrominoView extends CanvasView {
public TetrominoView(MainWindow window, int squareSize) {
super(window.getTetrominoCanvas(), squareSize);
}
public void update(SquareView[][] data, int baseX, int baseY) {
clear();
int height = data.length;
int width = data[0].length;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (data[i][j] != null)
data[i][j].update(context, baseX + j, baseY + i, squareSize);
}
}
}
}
</code></pre>
<p><strong>view/SquareView.java</strong>: Draws a filled sqaure.</p>
<p><strong>view/CanvasView.java</strong>: Helper class for using canvases.</p>
<p><strong>util/PeriodicTask.java</strong>: Wrapper around <code>java.util.Timer</code>.</p>
<p><strong>window/EventController.java</strong>: Converst <code>javafx.scene.input.KeyEvent</code> to <code>UserCommand</code>.</p>
<p><strong>window/MainWindow.java</strong>: Manages a JavaFX application.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T14:08:29.747",
"Id": "384375",
"Score": "0",
"body": "`TetrominoDataSource` was posted with an incomplete code. Update it to match the one you have on github."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018... | [
{
"body": "<p>Singletons are generally a bad idea unless you have a specific reason for them. (They are almost like global variables.) In this case, I see no reason why <code>TetrisGame</code> should be a singleton. In fact, it seems quite plausible that you might want to instantiate two of them, if you wanted ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T10:38:53.727",
"Id": "199737",
"Score": "5",
"Tags": [
"java",
"object-oriented",
"game",
"tetris"
],
"Title": "Tetris game demonstrating OOP principles"
} | 199737 |
<p>I am a beginner in Python and I am yet to move on from the basics to things like OOP.I wrote all of this code (Python 3) in an hour or so for a simple countdown timer.Although some parts of it are seemingly excessive,is the core of the code pythonic enough or are there better ways of structuring it?I would also like to know a better way for writing comments and variables effectively.More specifically I think the IOTimer() function could be cleaner.</p>
<pre><code>#modules
import datetime
import time
#TIMER
#Enter Preferences
supported_formats = ["hrs","min","sec"]
print("\n")
def get_input():
global unit_input
unit_input = input("Enter the format in which you want to time yourself:{}:".format(supported_formats))
unit_input.lower()
#Check if the format entered is valid.
get_input()
if unit_input in supported_formats:
pass
else:
print("Invalid Input.Please re-enter you desired format.\nThe input is case insenseitive")
get_input()
def countdown_timer(x):
while x >= 0 :
x -= 1
print("{} remaining".format(str(datetime.timedelta(seconds=x))))
print("\n")
time.sleep(1)
#Check for input and assign variable to determine the total amount of seconds
def IOTimer():
while True:
try:
if unit_input == "hrs":
hours = int(input("Enter the number of hours: "))
print("\n")
minutes = int(input("Enter the number of minutes: "))
print("\n")
seconds = int(input("Enter the number of seconds: "))
print("\n")
break
elif unit_input == "min":
hours = 0
minutes = int(input("Enter the number of minutes: "))
print("\n")
seconds = int(input("Enter the number of seconds: "))
print("\n")
break
elif unit_input == "sec":
hours = 0
minutes = 0
seconds = int(input("Enter the number of seconds: "))
print("\n")
break
except:
print("Invalid Input.Re-enter the values")
print("\n")
IOTimer()
hours_in_sec = hours*3600
minutes_in_sec = minutes*60
total_seconds = hours_in_sec + minutes_in_sec + seconds
print("Starting countdown for {}".format(str(datetime.timedelta(seconds=total_seconds))))
print("\n")
time.sleep(2)
countdown_timer(total_seconds)
IOTimer()
</code></pre>
| [] | [
{
"body": "<p>Before entering into the meat of the answer, let's talk about time accuracy for a bit.</p>\n\n<p>For starter, <a href=\"https://docs.python.org/3/library/time.html#time.sleep\" rel=\"noreferrer\"><code>time.sleep</code></a> is not extremely accurate as it can be (a little bit) longer than the requ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T11:43:36.327",
"Id": "199743",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"timer"
],
"Title": "Countdown Timer in Python"
} | 199743 |
<p>Here are two simple classes - Digit class maintains digit behaviour - primarily flipping animations, and Clock class handles everything that is related to time data.</p>
<p>I'm going to use this code for job application, please tell me if there are any improvements that could be done and what do you think of it.</p>
<p>Here is the link for working demo: <a href="https://abm0.github.io/flipping-clock/" rel="nofollow noreferrer">https://abm0.github.io/flipping-clock</a>.</p>
<pre><code>class Digit {
constructor({ selector, value = 0 }) {
const digitEl = document.querySelector(selector);
this.flipperEls = digitEl.querySelectorAll('.flipper');
this.prevDigitEls = digitEl.querySelectorAll('.prev .digit');
this.nextDigitEls = digitEl.querySelectorAll('.next .digit');
this.value = value;
this.prevValue = null;
this.renderInitialValue();
}
setValue(nextValue) {
this.prevValue = this.value;
this.value = nextValue;
if (this.value === this.prevValue) return;
this.flip();
}
renderInitialValue() {
const {
prevDigitEls,
nextDigitEls,
} = this;
[...prevDigitEls, ...nextDigitEls].forEach(el => (el.innerHTML = this.value));
}
flip() {
this.nextDigitEls.forEach(el => el.innerHTML = this.value);
this.flipperEls.forEach(el => el.classList.add('turned'));
setTimeout(() => {
this.prevDigitEls.forEach(el => (el.innerHTML = this.value));
this.flipperEls.forEach((el) => {
el.classList.remove('turned');
});
}, 500);
}
}
class Clock {
constructor(props) {
const baseEl = document.querySelector("#clock");
const currentTime = this.getCurrentTime();
this.digits = [
'hours-tens',
'hours-ones',
'minutes-tens',
'minutes-ones',
'seconds-tens',
'seconds-ones'
];
this.buildDigits(currentTime);
}
getCurrentTime() {
const date = new Date();
const time = {
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds(),
};
this.formatValues(time);
return time;
}
formatValues(time) {
Object.keys(time).forEach(key => {
if (key === "ampm") return;
let value = time[key];
if (parseInt(value) < 10) {
time[key] = "0" + value;
}
time[key] = time[key].toString();
});
}
getDigitProps(digitName) {
const type = digitName.split('-')[0];
const position = digitName.split('-')[1];
let positionIndex;
switch (position) {
case 'tens':
positionIndex = 0;
break;
case 'ones':
positionIndex = 1;
break;
}
return { type, position, positionIndex };
}
buildDigits(time) {
this.digits.forEach((digitName) => {
const { type, position, positionIndex } = this.getDigitProps(digitName);
const selector = `#${type} .${position}-digit`;
this[digitName] = new Digit({
selector,
value: time[type][positionIndex]
});
});
}
tick() {
const time = this.getCurrentTime();
this.digits.forEach((digitName) => {
const { type, positionIndex } = this.getDigitProps(digitName);
this[digitName].setValue(time[type][positionIndex]);
});
}
}
const clock = new Clock();
setInterval(() => {
clock.tick();
}, 1000);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T13:29:12.083",
"Id": "384361",
"Score": "0",
"body": "With `setInterval( ...., 1000)` you'll get your clock to tick once every second. Be aware, however, it's not said it will tick _at the beginning_ of a second. It may tick _at the... | [
{
"body": "<h1>Review</h1>\n<p>If you are after a entry level job then your code shows you can code, which is a good start.</p>\n<p>As an emploier I would ask.</p>\n<ol>\n<li>Why did you choose to use class syntax over more traditional code styles?</li>\n<li>How long did it take you to write this code?</li>\n</... | {
"AcceptedAnswerId": "199782",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T13:14:13.857",
"Id": "199747",
"Score": "3",
"Tags": [
"javascript",
"datetime",
"animation",
"dom",
"timer"
],
"Title": "JavaScript flipping clock"
} | 199747 |
<blockquote>
<p><strong>Task:</strong></p>
<p>For creating <a href="https://www.codewars.com/kata/multidimensional-neighbourhood" rel="nofollow noreferrer">this</a> challenge on Codewars I need a very performant
function that calculates Von Neumann Neighborhood in a N-dimensional
array. This function will be called about 2000 times</p>
<p><strong>The basic recursive approach:</strong></p>
<ul>
<li>calculate the index span influenced by the distance</li>
<li>if the index is in the range of the matrix go one step deeper into the next dimension</li>
<li>if max dimension is reached - append the value to the global neigh list <code>isCenter</code> is just a token that helps to <strong>NOT INCLUDE</strong> the cell
itself to the neighbourhood. There is also <code>remaining_distance</code> that
reduce the span.</li>
</ul>
</blockquote>
<p>You probably do not need to understand the process of this deep math so good. But maybe someone Python experienced can point me to some basic performance upgrade potential the code has.</p>
<p><strong>Questions:</strong></p>
<ul>
<li>What I am curious about. Is <code>.append</code> inefficient? I heard list comprehensions are better than append.</li>
<li>Would <code>not (0 <= dimensions_coordinate < len(arr))</code> changed to <code>len(arr) <= dimensions_coordinate or dimensions_coordinate < 0)</code> boost the code?</li>
<li>Are there performance differences between <code>==</code> and <code>is</code>?</li>
<li>Is <code>dimensions = len(coordinates)... if curr_dim == dimensions:...</code> slower than <code>if curr_dim == len(coordinates)</code>?</li>
<li>if you understood the math do you see a way to do it iterative? Because I heard recursions are slower in python and theoretical informatics says "Everything recursive can be iterative"</li>
</ul>
<p>The whole code:</p>
<ul>
<li>matrix is a N-dimensional matrix</li>
<li>coordinates of the cell is a N-length tuple</li>
<li>distance is the reach of the neighbourhood</li>
</ul>
<hr />
<pre><code>def get_neighbourhood(matrix, coordinates, distance=1):
dimensions = len(coordinates)
neigh = []
app = neigh.append
def recc_von_neumann(arr, curr_dim=0, remaining_distance=distance, isCenter=True):
#the breaking statement of the recursion
if curr_dim == dimensions:
if not isCenter:
app(arr)
return
dimensions_coordinate = coordinates[curr_dim]
if not (0 <= dimensions_coordinate < len(arr)):
return
dimesion_span = range(dimensions_coordinate - remaining_distance,
dimensions_coordinate + remaining_distance + 1)
for c in dimesion_span:
if 0 <= c < len(arr):
recc_von_neumann(arr[c],
curr_dim + 1,
remaining_distance - abs(dimensions_coordinate - c),
isCenter and dimensions_coordinate == c)
return
recc_von_neumann(matrix)
return neigh
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-23T14:37:56.003",
"Id": "385085",
"Score": "1",
"body": "Why remove Moore's neighbourhood?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-23T14:57:38.733",
"Id": "385095",
"Score": "0",
"body":... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T14:29:12.300",
"Id": "199754",
"Score": "7",
"Tags": [
"python",
"performance",
"programming-challenge",
"recursion",
"matrix"
],
"Title": "Codewars: N-dimensional Von Neumann Neighborhood in a matrix"
} | 199754 |
<p>Given the following artificially generated data:</p>
<pre><code>t_steps = 30
data = np.array([
np.arange(t_steps) * .05,
np.arange(t_steps) * .1,
np.arange(t_steps) * .2,
np.arange(t_steps) * .3
])
</code></pre>
<p>I find the time-step the each line of data has passed a threshold. If it does not pass the given threshold, I assign a time-step of <code>-1</code>:</p>
<pre><code>react_tms = []
thresh = 3.5
for dat in data:
whr = np.where(dat > thresh)
if len(whr[0]) == 0:
react_tms.append(-1)
else:
react_tms.append(whr[0][0])
</code></pre>
<p>This gives:</p>
<pre><code>[-1, -1, 18, 12]
</code></pre>
<p>Is there some way to do this without the for-loop? Even before the for-loop is removed, should I be using something other than <code>np.where</code> to find the threshold crossing?</p>
| [] | [
{
"body": "<p>In principle you can use <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html\" rel=\"nofollow noreferrer\"><code>numpy.argmax</code></a> for this. The only problem is that if no value is above the threshold, the maximum is <code>False</code>, so it returns 0 as the ind... | {
"AcceptedAnswerId": "199757",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T14:36:25.107",
"Id": "199756",
"Score": "2",
"Tags": [
"python",
"numpy",
"vectorization"
],
"Title": "Find first threshold crossing in numpy array"
} | 199756 |
<h1>Problem</h1>
<p>Two folders having files with name<code>Efile</code> that store lines starting with hex codes.</p>
<p>Print those hex codes that overlap in both folders.</p>
<hr>
<h1>Solution</h1>
<pre><code>import os
import sys
import re
def process_cache(cache):
event_code_set = set()
for file_name, multi_line_content in cache.items():
if file_name.endswith('Efile'):
for line in multi_line_content.splitlines():
line = line.rstrip('\\') # trailing backslash, if exist
if bool(re.search(r'^0[xX][0-9a-fA-F]+', line)):
# Take the hexcode
obj = re.search(r'^0[xX][0-9a-fA-F]+', line)
event_code_set.add(obj.string[obj.start():obj.end()])
return event_code_set
def scan_files(dir):
cache = {}
for root, dirs, files in os.walk(dir):
for name in files:
if name in ('Efile'):
path = os.path.join(root, name)
with open(path,'r') as file:
cache[path] = file.read()
return cache
cache1 = scan_files(sys.argv[1])
cache2 = scan_files(sys.argv[2])
cache1_event_code_set = process_cache(cache1)
cache2_event_code_set = process_cache(cache2)
overlap_event_codes = cache1_event_code_set & cache2_event_code_set
print(overlap_event_codes)
</code></pre>
<hr>
<p>For a typical three entries in a file, with comments(<code>#</code>),</p>
<blockquote>
<pre><code>0x00010d35 D 11 G 3,0x10009,N R XY.Condition, "({a 0x40001} == {H 0x166}) && ({a 0x11ff8} == {I 15})","0x0763ffc2 "
# Below event codes are from vendor xyz
0x84900c5 M 22 Y 1,0x03330469,4,5,6,7,8
0x04b60ff6 L 50 U \
0x04c60e07,102 && ({a 0x11ff8} == {I 15})","0x0763ffc2 "
</code></pre>
</blockquote>
<p>Picking <code>0x00010d35</code>, <code>0x04b60ff6</code> & <code>0x84900c5</code> is the task. Rest of the line is supposed to be ignored</p>
<p>Some entries are multi-line with trailing backslash.</p>
<p>Each file is in megabytes. Total files in both folders - 80</p>
<hr>
<p>1) Please suggest optimization in the below code, because pattern check is done twice.</p>
<pre><code> if bool(re.search(r'^0[xX][0-9a-fA-F]+', line)):
# Take the hexcode
obj = re.search(r'^0[xX][0-9a-fA-F]+', line)
event_code_set.add(obj.string[obj.start():obj.end()])
</code></pre>
<p>2) Please suggest coding style optimizations for tree walk, cache and command line arguments.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-21T12:48:37.933",
"Id": "384882",
"Score": "0",
"body": "Returning `cache` is a bug and wrong practice, despite it works... `cache1` should not point to local `cache`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": ... | [
{
"body": "<p>Repeating the match can be avoided by storing it in a variable first:</p>\n\n<pre><code>match = re.search(r'^0[xX][0-9a-fA-F]+', line)\nif match:\n event_codes.add(match.group())\n</code></pre>\n\n<p>Note also that you don't need to strip a trailing <code>\\</code>, because it is ignored afterw... | {
"AcceptedAnswerId": "199783",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T15:03:07.210",
"Id": "199759",
"Score": "4",
"Tags": [
"python",
"regex"
],
"Title": "Scan files and pick overlapped hex codes"
} | 199759 |
<p>still new to java and i am trying to improve my understanding and use of OOP concepts.here i am supposed to print the name of a randomly selected card from a deck of 52 cards.</p>
<p><strong><em>Program:</em></strong></p>
<pre><code>/*
* RandomCard.java
* -------------------
* Displays the name of a card randomly chosen from a complete deck of 52
* playing cards.
*/
import java.util.Random;
public class RandomCard {
/* Instance Variables */
private Random rgen = new Random(); /* random generator */
/**
* Display the name of a randomly selected card from a deck of 52 cards
*/
public static void main(String [] args) {
System.out.println("This program displays a randomly chosen card");
Card randomCard = selectCardFromDeckRandomly();
System.out.println(randomCard);
}
/*
* Randomly select a card from a card deck
* @ return The selected card
*/
private Card selectCardFromDeckRandomly() {
String rank = selectRanomCardRank();
String suit = selectRandomCardSuit();
return (new Card(rank, suit));
}
/*
* Randomly select a card rank
* @ return the selected card rank
*/
private String selectRanomCardRank() {
String cardRank;
int r = 1 + rgen.nextInt(13);
switch (r) {
case 1:
cardRank = "Ace";
break;
case 2:
cardRank = "2";
break;
case 3:
cardRank = "3";
break;
case 4:
cardRank = "4";
break;
case 5:
cardRank = "5";
break;
case 6:
cardRank = "6";
break;
case 7:
cardRank = "7";
break;
case 8:
cardRank = "8";
break;
case 9:
cardRank = "9";
break;
case 10:
cardRank = "10";
break;
case 11:
cardRank = "Jack";
break;
case 12:
cardRank = "Queen";
break;
default:
cardRank = "King";
break;
}
return cardRank;
}
/*
* Randomly select a card suit
* @ return The selected card suit
*/
private String selectRandomCardSuit() {
String cardSuit;
int s = 1 + rgen.nextInt(4);
switch (s) {
case 1:
cardSuit = "Clubs";
break;
case 2:
cardSuit = "Diamonds";
break;
case 3:
cardSuit = "Hearts";
break;
default:
cardSuit = "Spades";
break;
}
return cardSuit;
}
}
</code></pre>
<p><strong><em>class Card:</em></strong></p>
<pre><code>/*
* Card.java
* -------------
* Creates a playing card of certain Rank and Suit.
* This class is part of exercises 1 solution.
* This program is intended as a practice on programming methodologies.
*/
public class Card {
/* Instance variables */
private String rank; /* The card rank : Ace,2,3,4,5,6,7,8,9,10,Jack,Queen,King */
private String suit; /* The card suit : Clubs, Diamonds, Hearts, Spades */
/* Constructor */
/**
* Creates an instance object of class Card with the specified rank and suit
* @param rnk The rank of the card
* @param sut The suit of the card
*/
public Card(String rnk, String sut) {
rank = rnk;
suit = sut;
}
public String toString() {
return (rank + " of " + suit);
}
}
</code></pre>
<p>Note: still not in a position to use arrays.</p>
<p>Evaluation points:</p>
<ol>
<li>Encapsulation </li>
<li>Top-Down design (refactoring)</li>
<li>Readability and complexity reduction</li>
<li>Object oriented</li>
<li>Documentation</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T19:58:17.730",
"Id": "384432",
"Score": "0",
"body": "fixed indentation. which parentheses? you mean at return statement? i deliberately included those parentheses to make it clear what is returned. not sure if that is bad or just u... | [
{
"body": "<p>You did many things right. Great! =)</p>\n\n<h1>Readability and complexity reduction</h1>\n\n<p>Your </p>\n\n<pre><code>private String rank;\n</code></pre>\n\n<p>is nice and readable, but what is a <code>rnk</code> in </p>\n\n<pre><code>public Card(String rnk, String sut)\n</code></pre>\n\n<p>?</p... | {
"AcceptedAnswerId": "199781",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T18:06:29.750",
"Id": "199765",
"Score": "1",
"Tags": [
"java",
"beginner",
"random",
"playing-cards"
],
"Title": "Choose random card from a deck"
} | 199765 |
<blockquote>
<blockquote>
<p>Given a string, reverse only the vowels present in it and print the
resulting string.</p>
<p><strong>Input:</strong> </p>
</blockquote>
<p>First line of the input file contains an integer <strong>T</strong> denoting the
number of test cases. Then <strong>T</strong> test cases follow. Each test case has a
single line containing a string.</p>
<blockquote>
<p><strong>Output:</strong> </p>
</blockquote>
<p>Corresponding to each test case, output the string with vowels
reversed.</p>
<blockquote>
<p>Example:</p>
<p><strong>Input:</strong> </p>
<p>4</p>
<p>geeksforgeeks </p>
<p>practice </p>
<p>wannacry </p>
<p>ransomware</p>
<p><strong>Output:</strong> </p>
<p>geeksforgeeks </p>
<p>prectica </p>
<p>wannacry </p>
<p>rensamwora</p>
</blockquote>
</blockquote>
<p>My approach: </p>
<pre><code>/*package whatever //do not write package name here */
import java.util.Scanner;
import java.io.IOException;
import java.lang.StringBuffer;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class GFG {
private static String reverseVowels (String str) {
List <Character>vowels = new ArrayList <>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
List <Character>values = new ArrayList <>();
List <Integer>keys = new ArrayList <>();
for (int i = 0; i < str.length(); i++) {
if (vowels.contains(str.charAt(i))) {
keys.add(i);
values.add(str.charAt(i));
}
}
StringBuffer sb = new StringBuffer(str);
Collections.reverse(values);
int count = 0;
for (Integer num : keys) {
sb.replace(num.intValue(),num.intValue() + 1,String.valueOf(values.get(count)));
count++;
}
return sb.toString();
}
public static void main (String[] args) throws IOException {
Scanner sc = new Scanner (System.in);
int numTests = sc.nextInt();
for (int i = 0; i < numTests; i++) {
String str = sc.next();
System.out.println(reverseVowels(str));
}
}
}
</code></pre>
<p>I have the following questions about my code:</p>
<p>1) How can I further improve my approach?</p>
<p>2) Is there a better way to solve this question?</p>
<p>3) Are there any grave code violations that I have committed?</p>
<p>4) Can space and time complexity be further improved?</p>
<p>My time complexity is O(n) and space complexity is also O(n) currently.</p>
<p><a href="https://practice.geeksforgeeks.org/problems/reversing-the-vowels/0/?track=SP-Strings" rel="nofollow noreferrer">Reference</a></p>
| [] | [
{
"body": "<ul>\n<li><p>Time complexity is \\$O(n)\\$ indeed. Since every input character must be inspected, this asymptotic is impossible to improve. However, it is possible to improve the constant. See below.</p></li>\n<li><p>Space complexity is \\$O(n)\\$ indeed. However, it is possible to solve the problem ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T18:51:09.940",
"Id": "199769",
"Score": "0",
"Tags": [
"java",
"beginner",
"strings",
"interview-questions",
"complexity"
],
"Title": "Reversing the vowels in a String"
} | 199769 |
<p>I come from the R language and I gradually switch to Python (Numpy and Pandas). I coded this python code for fun to solve a Sudoku grid. Could you tell me if my code is pythonic enough? For example, did I use the numpy functions correctly. How to make the code more readable?</p>
<pre><code>import numpy as np
from functools import reduce
def solver_python(grid):
numbers=np.arange(1,10)
i,j = np.where(grid==0)
if (i.size==0):
return(True,grid)
else:
i,j=i[0],j[0]
row = grid[i,:]
col = grid[:,j]
sqr = grid[(i//3)*3:(3+(i//3)*3),(j//3)*3:(3+(j//3)*3)].reshape(9)
values = np.setdiff1d(numbers,reduce(np.union1d,(row,col,sqr)))
grid_temp = np.copy(grid)
for value in values:
grid_temp[i,j] = value
test = solver_python(grid_temp)
if (test[0]):
return(test)
return(False,None)
example = np.array([[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T19:22:49.523",
"Id": "384422",
"Score": "0",
"body": "\"Is my code pythonic enough?\" Enough for what?"
}
] | [
{
"body": "<p>Overall this is a really good approach. There is one main thing you can do to improve the implementation of this algorithm. You are copying the array at each level of recursion, but it is unnecessary in this case. Instead try an in-place approach. This improves cache locality and saves the tin... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T18:56:11.307",
"Id": "199771",
"Score": "3",
"Tags": [
"python",
"recursion",
"numpy",
"sudoku"
],
"Title": "Sudoku solver using NumPy"
} | 199771 |
<p>I'm reading and processing a fairly large csv using Pandas and Python 3.7. Header names in the CSV have periods in them ('full stops', Britons say). That's a problem when you want to address data cells by column name.</p>
<p><strong>test.csv</strong>:</p>
<pre><code>"name","birth.place","not.important"
"John","",""
"Paul","Liverpool","blue"
</code></pre>
<p></p>
<pre><code># -*- coding: utf-8 -*-
import pandas as pd
infile = 'test.csv'
useful_cols = ['name', 'birth.place']
df = pd.read_csv(infile, usecols=useful_cols, encoding='utf-8-sig', engine='python')
# replace '.' by '_'
df.columns = df.columns.str.replace('.', '_')
# we may want to iterate over useful_cols later, so to keep things consistent:
useful_cols = [s.replace('', '') for s in useful_cols]
# now we can do this..
print(df['birth_place'])
# ... and this
for row in df.itertuples():
print(row.birth_place)
# ain't that nice?
</code></pre>
<p>It works, but since Pandas is such a powerful library and the use case is quite common, I'm wondering if there isn't an even better way of doing this. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T00:24:43.397",
"Id": "384449",
"Score": "0",
"body": "This looks a bit short on code, how do you use this, as I may [recommend this](https://gist.github.com/Peilonrayz/c8c5ddbcdadcd4a1112c076c00043361). However if you use it differe... | [
{
"body": "<p>Did a little digging and found that you can use <code>df._columnid</code> when pandas <code>df.columns</code> runs into an issue with a name (in this example dealing with a <code>\".\"</code>)</p>\n\n<p>I am sure you already know that you could just do <code>df['birth.place']</code>, since it's in... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T19:24:31.550",
"Id": "199772",
"Score": "1",
"Tags": [
"python",
"csv",
"pandas"
],
"Title": "Handling periods ('.') in CSV column names with Pandas"
} | 199772 |
<p>The following program converts a string to a double, and checks for errors. It uses the <code>strtod()</code> function to do the conversion, and follows the example given for the <code>strtol()</code> function from the man page to do the error checking.</p>
<p>As an example, the program is executed as follows:</p>
<pre><code>$ ./a.out 123.45
</code></pre>
<p>I would really appreciate any comments regarding the code, specifically whether there are any issues to be address or whether the code can be made more efficient or improved in any way.</p>
<pre><code>#include <stdlib.h>
#include <float.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
char *endptr, *str;
double val;
if (argc < 2) {
fprintf(stderr, "Usage: %s str\n", argv[0]);
exit(EXIT_FAILURE);
}
str = argv[1];
errno = 0; /* To distinguish success/failure after call */
val = strtod(str, &endptr);
/* Check for various possible errors */
if ((errno == ERANGE && (val == DBL_MAX || val == -DBL_MAX))
|| (errno != 0 && val == 0.0)) {
perror("strtod");
exit(EXIT_FAILURE);
}
if (endptr == str) {
fprintf(stderr, "No digits were found\n");
exit(EXIT_FAILURE);
}
/* If we got here, strtod() successfully parsed a number */
printf("strtod() returned %f\n", val);
if (*endptr != '\0') /* Not necessarily an error... */
printf("Further characters after number: %s\n", endptr);
exit(EXIT_SUCCESS);
}
</code></pre>
| [] | [
{
"body": "<p><strong>Good use of <code>errno</code>, but can be improved.</strong></p>\n\n<p>The below is decent code for detecting overflow, yet would benefit with improvements. </p>\n\n<p>On overflow, the return value is <code>HUGE_VAL</code>, not necessarily <code>DBL_MAX</code>. <code>HUGE_VAL</code> may... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T20:04:13.110",
"Id": "199775",
"Score": "3",
"Tags": [
"beginner",
"c",
"parsing",
"validation",
"floating-point"
],
"Title": "Convert string to double and check for errors"
} | 199775 |
<p>I have a binary file <code>input.hgt</code> from the <a href="https://en.wikipedia.org/wiki/Shuttle_Radar_Topography_Mission" rel="nofollow noreferrer">Shuttle Radar Topography Mission</a>. It contains a 3601✕3601 matrix, stored as 2-Byte big-endian integer numbers. My code converts it to a readable text file <code>output.csv</code>.</p>
<p>How can I make it better?</p>
<p>Here is my code:</p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
const int SRTM_SIZE = 3601;
static int height[SRTM_SIZE][SRTM_SIZE] = {{0},{0}};
int main() {
ifstream file("/storage/emulated/0/input.hgt", ios::in | ios::binary);
if(!file) {
cout << "Error opening file!" << endl;
return -1;
}
unsigned char buffer[2];
for (int i = 0; i < SRTM_SIZE; ++i) {
for (int j = 0; j < SRTM_SIZE; ++j) {
if(!file.read(reinterpret_cast<char*>(buffer), sizeof(buffer) )) {
cout << "Error reading file!" << endl;
return -1; }
height[i][j] = (buffer[0] << 8) | buffer[1];
} }
ofstream meinFile;
meinFile.open ("/storage/emulated/0/output.csv");
for(int x = 0; x < SRTM_SIZE; x++)
{ // from row 1 to row SRTM size
for(int y = 0; y < SRTM_SIZE; y++)
{// from column 1 to SRTM_Size
meinFile << height[x][y] << ",";
}
meinFile << endl;
}
meinFile.close();
cout<< "Gratulations!" <<endl;
cout<< "Your file has been converted sucessfully" <<endl;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T21:28:15.100",
"Id": "384441",
"Score": "0",
"body": "Can close-voters point out what is broken with the code? looks fine at a glance, so leaving open"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T2... | [
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Avoid</a> <code>using namespace std</code>.</p></li>\n<li><p>Assuming <code>sizeof(int)</code> is 4, the <code>height</code> array takes more than 40 MB of space. I understand that ... | {
"AcceptedAnswerId": "199787",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T20:12:10.430",
"Id": "199776",
"Score": "7",
"Tags": [
"c++",
"file",
"csv",
"serialization"
],
"Title": "Convert binary raster file to text CSV"
} | 199776 |
<p>This code was reworked and posted here:<a href="https://codereview.stackexchange.com/questions/199931/text-based-game-hunt-the-wumpus-version-2">Text based game “Hunt the Wumpus” Version 2</a> </p>
<p>The following game was a excercise in the PPP book by Stroustrup:</p>
<blockquote>
<p>Implement a version of the game "Hunt the Wumpus".
Hunt the Wumpus" (or just "Wump") is a simple (non-graphically) computer game originally invented by Gregory Yob.
The basic premise is that a rather smelly monster lives in a dark cave consisting of connected rooms. Your job is to slay the wumpus using bow and arrow. In addition to the wumpus, the cave has two hazards: bottomless pits and giant bats. If you enter a room with a bat, the bat picks you up and drops you into another room. If you enter a room with a bottomless pit, its the end of the game for you. If you enter the room with the Wumpus he eats you. When you enter a room you will be told if a hazard is nearby:<br><br>
"I smell the wumpus": It´s in an adjoining room.<br>
"I feel a breeze": One of the adjoining rooms is a bottomless pit.<br>
"I hear a bat": A giant bat is in an adjoining room.
<br><br>
For your convenience, rooms are numbered. Every room is connected by tunnels to three other rooms. When entering a room, you are told something like " You are in room 12; there are tunnels to rooms 1,13, and 4: move or shoot?" Possible answers are m13 ("Move to room 13") and s13-4-3 ("Shoot an arrow through rooms 13,4, and 3"). The range of an arrow is three rooms. At the start of the game, you have five arrows.
The snag about shooting is that it wakes up the wumpus and he moves to a room adjoining the one he was in - that could be your room.
Be sure to have a way to produce a debug output of the state of the cave.</p>
</blockquote>
<p>The excercises doesnt say how much bats or pits are in the game. I did some research and found that most implementations made like <code>count_of_rooms / 6</code> for the amount of bats and pits.</p>
<p>Here is my code:</p>
<p><b>wumpus.h</b></p>
<pre><code>#ifndef WUMPUS_GUARD_110720182013
#define WUMPUS_GUARD_110720182013
#include <iostream>
#include <random>
#include <vector>
#include <string>
#include <sstream>
namespace wumpus {
struct Room {
Room(int rnum)
:wumpus{ false }, pit{ false }, bat{ false }, player{ false }, rnumber{ rnum }
{
brooms.push_back(nullptr);
brooms.push_back(nullptr);
brooms.push_back(nullptr);
}
int rnumber;
std::vector <Room*> brooms; //pointer to 3 rooms next to this room
bool wumpus;
bool pit;
bool bat;
bool player;
};
class Dungeon {
public:
Dungeon();
void indicate_hazards();
bool shoot_arrow(std::vector<int> tar_rooms);
bool Dungeon::move_wumpus();
bool move_player(int tar);
void debug(); //shows the status of the cave for debug purpose
std::vector<int> neigbour_rooms(int room);
int current_room();
private:
static constexpr int count_of_arrows = 5;
static constexpr int count_of_rooms = 12;
static constexpr int count_of_pits = count_of_rooms / 6;
static constexpr int count_of_bats = count_of_rooms / 6;
std::vector <Room> rooms;
int arrows;
int wumpus_room;
int player_room;
bool connect_rooms();
bool room_is_full_connected(const int con, const std::vector<int>& crooms);
};
int get_random(int min, int max);
void hunt_the_wumpus();
void instructions();
int select_room_to_move(Dungeon& d1);
std::vector<int> select_rooms_to_shoot();
}
#endif
</code></pre>
<p><b>wumpus.cpp</b></p>
<pre><code>#include "wumpus.h"
namespace wumpus {
Dungeon::Dungeon()
{
//retry make the connections if not sucessfull
while (true) {
rooms.clear();
for (int i = 1;i <= count_of_rooms;++i) //create rooms
rooms.push_back(i);
if (connect_rooms()) //connect them
break;
}
//add the wumpus
wumpus_room = get_random(1, count_of_rooms);
rooms[wumpus_room - 1].wumpus = true;
//add pit
for (int i = 0; i < count_of_pits; ++i) {
int pit_room = get_random(1, count_of_rooms);
while (rooms[pit_room - 1].wumpus == true //no wumpus or pit already in room
|| rooms[pit_room - 1].pit == true)
pit_room = get_random(1, count_of_rooms);
rooms[pit_room - 1].pit = true;
}
//add bat
for (int i = 0; i < count_of_bats; ++i) {
int bat_room = get_random(1, count_of_rooms);
while (rooms[bat_room - 1].wumpus == true //no wumpus or pit or bat already in room
|| rooms[bat_room - 1].pit == true
|| rooms[bat_room - 1].bat == true)
bat_room = get_random(1, count_of_rooms);
rooms[bat_room - 1].bat = true;
}
//add player
player_room = get_random(1, count_of_rooms);
while (rooms[player_room - 1].wumpus == true //no wumpus or pit or bat already in room
|| rooms[player_room - 1].pit == true
|| rooms[player_room - 1].bat == true)
player_room = get_random(1, count_of_rooms);
rooms[player_room - 1].player = true;
arrows = count_of_arrows;
}
void Dungeon::indicate_hazards()
{
bool found_bat = false;
bool found_pit = false;
for (auto& x : rooms[player_room - 1].brooms) {
if (x->wumpus == true) {
std::cout << "I smell the wumpus\n";
}
if (x->pit == true && found_pit == false) {
found_pit = true;
std::cout << "I feel a breeze\n";
}
if (x->bat == true && found_bat == false) {
found_bat = true;
std::cout << "I hear a bat\n";
}
}
std::cout << "You are in room " << rooms[player_room - 1].rnumber << "\n";
std::cout << "You have "<<arrows<< " arrow(s) left\n";
std::cout << "Tunnels lead to rooms " << rooms[player_room - 1].brooms[0]->rnumber << ", ";
std::cout << rooms[player_room - 1].brooms[1]->rnumber << " and ";
std::cout << rooms[player_room - 1].brooms[2]->rnumber << "\n";
std::cout << "what do you want to do? (M)ove or (S)hoot?\n";
}
bool Dungeon::shoot_arrow(std::vector<int> tar_rooms)
//trys to shoot in the supplied tar rooms an arrow
//if the wumpus is hit returns true to indicate victory
//moves the wumpus on fail
{
--arrows;
int curr_room = player_room - 1;
for (const auto& tr : tar_rooms){
bool room_reached = false;
for (const auto& x : rooms[curr_room].brooms) { //check if neigbour room is one of the vectors
if (x->rnumber == tr) {
room_reached = true;
curr_room = x->rnumber - 1;
if (rooms[curr_room].wumpus) { //wumpus hit
std::cout << "!!!!!!YOU WON!!!!!!: You killed the Wumpus in room " << rooms[curr_room].rnumber << "\n";
return true;
}
break;
}
}
if (!room_reached) { //if not end
std::cout << "Room " << tr << " could not be reached from arrow\n";
return false;
}
}
if (arrows == 0) {
std::cout << "You lost: You ran out of arrows";
return true;
}
}
bool Dungeon::move_wumpus()
//moves the wumpus with a chance of 75% to a new room
//if player room is entered true is returned for game over
{
if (get_random(1, 4) == 4) // no movement on 4
return false;
else {
rooms[wumpus_room - 1].wumpus = false;
wumpus_room = rooms[wumpus_room - 1].brooms[get_random(0, 2)]->rnumber;
rooms[wumpus_room - 1].wumpus = true;
if (rooms[wumpus_room - 1].player) {
std::cout << "You lost: Wumpus enters youre room and eats you\n";
return true;
}
}
return false;
}
bool Dungeon::move_player(int tar)
//trys to move player to the selected room
//if deadly hazard like pit or wumpus is found return game over = true;
//if bat is found choose new random room free from hazards to put the player
{
for (auto& x : rooms[player_room - 1].brooms) {
if (x->rnumber == tar) {
if (x->wumpus == true) {
std::cout << "You lost: You got eaten by the Wumpus\n";
return true;
}
else if (x->pit == true) {
std::cout << "You lost: You fell in a bottomless pit\n";
return true;
}
else if (x->bat) {
std::cout << "Gigantic bat appeared!!!\n";
std::cout << "You got dragged to a new room\n";
int rnd_room = get_random(1, count_of_rooms);
//Only put player in empty room
while (rooms[rnd_room - 1].wumpus == true || rooms[rnd_room - 1].pit == true
|| rooms[rnd_room - 1].bat == true || rooms[rnd_room - 1].player == true)
rnd_room = get_random(1, count_of_rooms);
rooms[player_room - 1].player = false;
player_room = rnd_room;
rooms[player_room - 1].player = true;
return false;
}
else {
rooms[player_room - 1].player = false;
player_room = tar;
rooms[player_room - 1].player = true;
return false;
}
}
}
std::cerr << "Dungeon::move_player: Unknown target room entered";
return false;
}
void Dungeon::debug()
{
for (const auto&x : rooms) {
std::cout << "Room " << x.rnumber << " connects to: ";
for (const auto&y : x.brooms) {
if (y != nullptr) std::cout << y->rnumber << " ";
else std::cout << "np" << " ";
}
std::cout << " ";
if(x.wumpus) std::cout << "wumpus:" << x.wumpus << " ";
if(x.pit) std::cout << "pit:" << x.pit << " ";
if(x.bat) std::cout << "bat:" << x.bat << " ";
if(x.player) std::cout << "player:" << x.player << " ";
std::cout << "\n";
}
}
std::vector<int> Dungeon::neigbour_rooms(int room)
{
std::vector<int> ret;
ret.push_back(rooms[room - 1].brooms[0]->rnumber);
ret.push_back(rooms[room - 1].brooms[1]->rnumber);
ret.push_back(rooms[room - 1].brooms[2]->rnumber);
return ret;
}
int Dungeon::current_room()
{
return player_room;
}
//-------------------------------------------------------------
//Private functions
//-------------------------------------------------------------
bool Dungeon::room_is_full_connected(const int con, const std::vector<int>& crooms)
//checks if the room has already 3 connections so it is on the black list
{
for (const auto &x : crooms) // room is on the black list
if (x == con)
return true;
return false;
}
bool Dungeon::connect_rooms()
//connects the rooms with random algorithm
//it can happen that the last 2 rooms connected are in the same room
//e.g Room 2 connected to 4 np np. the last to connections are in the same room
//in this case it is returned false to re run the connection algorithm
//other case to restart 2 rooms left with one unconnected node because they are already connected
//with each other
{
std::vector <int> conn_rooms;
while (conn_rooms.size() < count_of_rooms) {
int min_room = 1;
int max_room = count_of_rooms;
int source_rnd_room = get_random(min_room, max_room);
while (room_is_full_connected(source_rnd_room, conn_rooms)) //check if rnd room is on black list
source_rnd_room = get_random(min_room, max_room);
int target_rnd_room = get_random(min_room, max_room);
while (room_is_full_connected(target_rnd_room, conn_rooms) || source_rnd_room == target_rnd_room) { //check if rnd room is on black list
target_rnd_room = get_random(min_room, max_room);
if (conn_rooms.size() == count_of_rooms - 2 //special case for last 2 numbers to prevent infinite loop
&& room_is_full_connected(target_rnd_room, conn_rooms)
&& room_is_full_connected(source_rnd_room, conn_rooms)
&& source_rnd_room != target_rnd_room) {
conn_rooms.push_back(source_rnd_room);
conn_rooms.push_back(target_rnd_room);
}
if (conn_rooms.size() == count_of_rooms - 1) {
return false;
}
}
bool conn_full = true;
bool tar_already_conn = false;
for (size_t i = 0; i < rooms[source_rnd_room - 1].brooms.size(); ++i) {
if (rooms[source_rnd_room - 1].brooms[i] == nullptr) {
conn_full = false;
rooms[source_rnd_room - 1].brooms[i] = &rooms[target_rnd_room - 1];
if (i == rooms[source_rnd_room - 1].brooms.size() - 1)
conn_full = true;
break;
}
else if (rooms[source_rnd_room - 1].brooms[i]->rnumber == target_rnd_room) { //skip if room already leads to source_rnd_room
tar_already_conn = true;
break;
}
}
if (tar_already_conn && conn_rooms.size() == count_of_rooms - 2)
return false;
if (tar_already_conn)
continue;
if (conn_full)
conn_rooms.push_back(source_rnd_room);
conn_full = true;
for (size_t i = 0; i < rooms[target_rnd_room - 1].brooms.size(); ++i) {
if (rooms[target_rnd_room - 1].brooms[i] == nullptr) {
conn_full = false;
rooms[target_rnd_room - 1].brooms[i] = &rooms[source_rnd_room - 1];
if (i == rooms[target_rnd_room - 1].brooms.size() - 1)
conn_full = true;
break;
}
}
if (conn_full)
conn_rooms.push_back(target_rnd_room);
}
return true;
}
//-------------------------------------------------------------
//Helper functions
//-------------------------------------------------------------
int get_random(int min, int max)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(min, max);
return distribution(mt);
}
void hunt_the_wumpus()
{
instructions();
while (true)
{
Dungeon d1;
while (true) {
d1.indicate_hazards();
std::string in;
std::cin >> in;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(999, '\n');
continue;
}
bool game_over = false;
if (in == "m" || in == "M" || in == "Move" || in == "move") {
game_over = d1.move_player(select_room_to_move(d1));
}
else if (in == "s" || in == "S" || in == "Shoot" || in == "shoot") {
game_over = d1.shoot_arrow(select_rooms_to_shoot());
if (game_over == true) { break; }
game_over = d1.move_wumpus();
}
if (game_over == true) {
break;
}
}
std::cout << "Press any key to start a new game or (q)uit to end game\n";
std::string in;
std::cin >> in;
if (in == "q" || in == "Q" || in == "Quit" || in == "quit")
break;
}
}
void instructions()
{
std::cout <<
"Welcome to \"Hunt the Wumpus\"!\n"
"The wumpus lives in a cave of rooms.Each room has 3 tunnels leading to\n"
"other rooms. (Look at a dodecahedron to see how this works - if you don't know\n"
"what a dodecahedron is, ask someone).\n"
"\n"
"Hazards\n"
"Bottomless pits - two rooms have bottomless pits in them.If you go there, you\n"
"fall into the pit(and lose!)\n"
"Super bats - two other rooms have super bats.If you go there, a bat grabs you\n"
"and takes you to some other room at random. (Which may be troublesome).\n"
"\n"
"Wumpus\n"
"The wumpus is not bothered by hazards(he has sucker feet and is too big for a\n"
"bat to lift).Usually he is asleep.Two things wake him up : you shooting an\n"
"arrow or you entering his room.\n"
"\n"
"If the wumpus wakes he moves(p = .75) one room or stays still(p = .25).After\n"
"that, if he is where you are, he eats you up and you lose!\n"
"\n"
"You\n"
"Each turn you may move or shoot a crooked arrow.\n"
"Moving: you can move one room(thru one tunnel).\n"
"Arrows : you have 5 arrows.You lose when you run out.Each arrow can go from 1\n"
"to 3 rooms.You aim by telling the computer the rooms you want the arrow to go\n"
"to.If the arrow can\'t go that way (if no tunnel) it moves at random to the\n"
"next room.If the arrow hits the wumpus, you win.If the arrow hits you, you\n"
"lose.\n"
"\n"
"Warnings\n"
"When you are one room away from a wumpus or hazard, the computer says :\n"
"\n"
"Wumpus: \"I smell the wumpus\"\n"
"Bat : \"I hear a bat\"\n"
"Pit : \"I feel a breeze\"\n"
"\n\n"
"Press any key to start\n";
char c;
std::cin.get(c);
}
int select_room_to_move(Dungeon& d1)
{
int in;
while (true) {
std::cout << "To where??\n";
in = 0;
std::cin >> in;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(999, '\n');
continue;
}
std::vector<int> nr = d1.neigbour_rooms(d1.current_room());
if (in == nr[0] || in == nr[1] || in == nr[2])
return in;
}
}
std::vector<int> select_rooms_to_shoot()
{
for(;;){
std::cout << "Enter rooms you want to shoot the arrow (e.g. 2-3-12, eg 4-5, eg 2)\n";
std::string in;
std::cin >> in;
std::istringstream ist{ in };
std::vector<int> tar_rooms;
bool bad_input = false;
while (!ist.eof()) {
int in_int;
char in_char;
ist >> in_int;
if (ist.fail()) {
std::cin.clear();
std::cin.ignore(999, '\n');
bad_input = true;
break;
}
tar_rooms.push_back(in_int);
if (ist.eof()) break;
ist >> in_char;
if (ist.fail()) {
std::cin.clear();
std::cin.ignore(999, '\n');
bad_input = true;
break;
}
if (in_char != '-') { bad_input = true; break; }
if (tar_rooms.size() > 3) { bad_input = true;break; }
if (ist.eof()) { bad_input = true;break; };//to prevent 2-3-12- last sign must be integer
}
if (bad_input) continue;
if (tar_rooms.size() <= 3)
return tar_rooms;
}
}
</code></pre>
<p>}</p>
<p><b> main.cpp </b></p>
<pre><code>#include <iostream>
#include "wumpus.h"
int main()
try {
wumpus::hunt_the_wumpus();
}
catch (std::runtime_error& e) {
std::cerr << e.what() << "\n";
std::cin.get();
}
catch (...) {
std::cerr << "unknown error\n";
std::cin.get();
}
</code></pre>
<p>I wonder what can be improved to clean up the code. Is it a good idea to split the code into smaller classes?</p>
<p>Please let me know if the code is readable or if it needs improvements.</p>
<p>I want the code as clean as possible beause in the next step i want to make it a GUI game (using FLTK).</p>
| [] | [
{
"body": "<p>Your code is too big for me to do a <em>full</em> review, but here are some random observations:</p>\n\n<p>First, the standard miscellany.</p>\n\n<ul>\n<li>Good on you for not <code>using namespace std;</code> anywhere!</li>\n<li>Consider using <code>#pragma once</code> instead of the <code>#ifnde... | {
"AcceptedAnswerId": "199792",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T20:38:34.003",
"Id": "199777",
"Score": "10",
"Tags": [
"c++",
"game"
],
"Title": "Text based game \"Hunt the Wumpus\""
} | 199777 |
<p>I wanted to write a code that each time I will press some button in my menu, a numpy image array will somehow be created, and this image will show up in a new window.</p>
<p>So the following code is the same purpose, but with the same numpy image array for all new windows (for simplifying).</p>
<p>Which means, for a given numpy image array, each time I will press the 'New' button in my menu, The image will show up as a new window. </p>
<p>I just started playing with PyQt5, so I'd love to get any feedback, because I never did these stuff before (GUI, images), so I might get stuff heavily wrong.</p>
<p><strong>NewNumpyImageWindowMenu.py</strong> class (main) pressing 'New' will create a new instance of <code>NewImage</code> (in the other class), and will hold the object in a list, in order for all the windows to still be visible.</p>
<pre><code>import cv2
import sys
from PyQt5 import QtWidgets
from NewNumpyImageWindow import NewImage
class Menu(QtWidgets.QMainWindow):
def __init__(self, numpy_img):
super().__init__()
newAct = QtWidgets.QAction('New', self)
self.numpyPicture = numpy_img
newAct.triggered.connect(self.new_image_window)
toolbar = self.addToolBar('Exit')
toolbar.addAction(newAct)
self.images_list = []
self.setGeometry(300, 300, 350, 250)
self.show()
def new_image_window(self):
self.images_list.append(NewImage(self.numpyPicture))
if __name__ == '__main__':
currentNumpyImage = cv2.imread("capture.png") # some picture
app = QtWidgets.QApplication(sys.argv) # converts picture to numpy array
menu = Menu(currentNumpyImage)
sys.exit(app.exec_())
</code></pre>
<p><strong>NewNumpyImageWindow.py</strong> class</p>
<pre><code>import cv2
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap, QImage
class NewImage(QWidget):
def __init__(self, numpy_image):
super().__init__()
label = QLabel(self)
pixmap = self.convert_numpy_img_to_qpixmap(numpy_image)
label.setPixmap(pixmap)
self.resize(pixmap.width(), pixmap.height())
self.show()
@staticmethod
def convert_numpy_img_to_qpixmap(np_img):
height, width, channel = np_img.shape
bytesPerLine = 3 * width
return QPixmap(QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped())
# if __name__ == '__main__':
# app = QApplication(sys.argv)
# current_numpy_Image = cv2.imread("capture.png")
# window = NewImage(current_numpy_Image)
# sys.exit(app.exec_())
</code></pre>
<p>Any help would be appreciated :)</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-18T21:24:43.997",
"Id": "199779",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"image",
"gui",
"pyqt"
],
"Title": "PyQt5 - Open new image window for each button click in menu"
} | 199779 |
<p><strong>EDIT: I have posted a <a href="https://codereview.stackexchange.com/questions/199801/counting-sort-in-c-revised">follow-up</a> to this question.</strong></p>
<p>I have implemented counting sort in C. This program takes its input as integers from command line arguments, sorts the integers with counting sort, then outputs the sorted array.</p>
<p>This is my first attempt at implementing this and I would really like to see what I could do better in this code. </p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int max(int* arr, int len) {
int out = arr[0];
for (int i = 0; i < len; i++)
if (arr[i] > out)
out = arr[i];
return out;
}
void sort(int** in, int** out, size_t length) {
int* inputs = *in;
int* outputs = *out;
// this is the size of the array of counts
int greatest = max(inputs, length); // find the greatest number in the array
// allocate the array of counts
int* counts = calloc(greatest + 1, sizeof(int));
// count numbers in input array
for (int i = 0; i < length; i++) {
counts[inputs[i]]++;
}
int counter = 0; // keep track of where we are in output array
// loop through all the counts
for (int i = 0; i < (greatest + 1); i++) { // for every count in array
for (int j = 0; j < counts[i]; j++) { // loop that many times
outputs[counter++] = i; // add the integer being counted to the output array
}
}
free(counts);
}
int main(int argc, char** argv) {
int *inputs, *outputs;
size_t length = argc - 1; // number of integers to sort
inputs = malloc(sizeof(int) * (argc - 1));
outputs = malloc(sizeof(int) * (argc - 1));
for (int i = 1; i < argc; i++) {
inputs[i - 1] = atoi(argv[i]); // assign arguments to array
}
sort(&inputs, &outputs, length);
for (size_t i = 0; i < (length); i++) {
printf("%d ", outputs[i]); // print space separated sorted numbers
}
printf("\n");
free(inputs);
free(outputs);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Why do you pass <code>in</code> and <code>out</code> to <code>sort</code> as <code>int **</code>? You only dereference them to get the underlying pointer. Just pass in the pointers (rather than the address of the pointers) and take the parameters as <code>int *inputs</code> and <code>int *output... | {
"AcceptedAnswerId": "199796",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T01:21:03.767",
"Id": "199789",
"Score": "3",
"Tags": [
"c",
"sorting"
],
"Title": "Counting sort in C"
} | 199789 |
<p>I'm working on a d3 project that has multiple sub-plots with updating data. I have a working example below, but I think I might be over complicating the <code>update()</code> pattern. I didn't include an <code>exit()</code> because the data is consistent (there's always the same amount of divisions, teams and values).</p>
<p>d3 experts: does this look right to you? What would you modify to make it more performant / maintainable? Should I invoke a function for each component of the chart? e.g. a function for building the division charts, a function for building the team charts, a function for building the bars, etc.</p>
<p>I'm interested in learning how to write clean maintainable d3 code, so please pass along any resources if you have any.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const dataset1 = [
{"division": "division 1", "team": "team 1", "value": 5},
{"division": "division 1", "team": "team 1", "value": 7},
{"division": "division 1", "team": "team 1", "value": 9},
{"division": "division 1", "team": "team 2", "value": 2},
{"division": "division 1", "team": "team 2", "value": 1},
{"division": "division 1", "team": "team 2", "value": 1},
{"division": "division 1", "team": "team 3", "value": 3},
{"division": "division 1", "team": "team 3", "value": 1},
{"division": "division 1", "team": "team 3", "value": 7},
{"division": "division 2", "team": "team 1", "value": 2},
{"division": "division 2", "team": "team 1", "value": 7},
{"division": "division 2", "team": "team 1", "value": 3},
{"division": "division 2", "team": "team 2", "value": 6},
{"division": "division 2", "team": "team 2", "value": 3},
{"division": "division 2", "team": "team 2", "value": 2},
{"division": "division 2", "team": "team 3", "value": 3},
{"division": "division 2", "team": "team 3", "value": 9},
{"division": "division 2", "team": "team 3", "value": 5},
]
const dataset2 = [
{"division": "division 1", "team": "team 1", "value": 1},
{"division": "division 1", "team": "team 1", "value": 4},
{"division": "division 1", "team": "team 1", "value": 3},
{"division": "division 1", "team": "team 2", "value": 6},
{"division": "division 1", "team": "team 2", "value": 2},
{"division": "division 1", "team": "team 2", "value": 9},
{"division": "division 1", "team": "team 3", "value": 5},
{"division": "division 1", "team": "team 3", "value": 2},
{"division": "division 1", "team": "team 3", "value": 3},
{"division": "division 2", "team": "team 1", "value": 8},
{"division": "division 2", "team": "team 1", "value": 1},
{"division": "division 2", "team": "team 1", "value": 2},
{"division": "division 2", "team": "team 2", "value": 5},
{"division": "division 2", "team": "team 2", "value": 3},
{"division": "division 2", "team": "team 2", "value": 7},
{"division": "division 2", "team": "team 3", "value": 4},
{"division": "division 2", "team": "team 3", "value": 3},
{"division": "division 2", "team": "team 3", "value": 8},
]
function updateChart(data) {
// Divisions
var divisions = d3.nest().key(d=>d.division).entries(data);
var divisionCharts = d3.select("body").selectAll("svg").data(divisions, d=>d.key);
var divisionChartsEnter = divisionCharts.enter().append("svg").attr("width", 200).attr("height", 75);
// Teams
var teamCharts = divisionCharts.merge(divisionChartsEnter).selectAll("svg")
.data(d => d3.nest().key(d=>d.team).entries(d.values), d=>d.key)
var teamChartsEnter = teamCharts.enter().append("svg").attr("x", (d,i) => i*50);
// Values for each team
var bars = teamCharts.merge(teamChartsEnter).selectAll("rect").data(d => d.values);
var barsEnter = bars.enter()
.append("rect")
.attr("x", (d,i)=>i*12)
.attr("width", 10)
bars.merge(barsEnter)
.transition()
.attr("height", d=>d.value*10)
// Toggle dataset
currDataset = data == dataset1 ? dataset2 : dataset1;
}
let currDataset = dataset1;
updateChart(currDataset);
d3.select("#updateData").on("click", () => updateChart(currDataset))</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><button id="updateData">Update Data</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>Overall, your update function is correct. You're appending several SVGs to the HTML, which is a good and very common approach when creating <a href=\"https://en.wikipedia.org/wiki/Small_multiple\" rel=\"nofollow noreferrer\">small multiples</a>. Also, you have a correct (almost, see below) underst... | {
"AcceptedAnswerId": "199794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T02:26:16.027",
"Id": "199793",
"Score": "1",
"Tags": [
"javascript",
"d3.js"
],
"Title": "Update pattern for subplots"
} | 199793 |
<p>I am preparing for multithreading interview questions and I don't have much experience with multithreading. I referred some online article to come up with a solution. Is this solution appropriate?</p>
<pre><code>public class ThreadSafeArrayList<E> {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
private final List<E> list = new ArrayList<>();
public void set(E o) {
writeLock.lock();
try {
list.add(o);
} finally {
writeLock.unlock();
}
}
public E get(int i) {
readLock.lock();
try {
return list.get(i);
} finally {
readLock.unlock();
}
}
public void add(E num) {
List<E> sync = Collections.synchronizedList(list);
sync.add(num);
}
public E remove(int i) {
List<E> sync = Collections.synchronizedList(list);
if (sync.isEmpty()) return null;
return sync.remove(i);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T18:15:08.290",
"Id": "384593",
"Score": "0",
"body": "Not really, for interview questions and production code you do not re-invent the wheel, for academic purposes it appears fine. https://docs.oracle.com/javase/tutorial/essential/... | [
{
"body": "<p>Definitely not!</p>\n\n<p>While using the ReadWriteLock pattern instead of simple intrinsic locking for collections is a good thing to do, you are doing almost everything wrong.\nI recommend you to take a deeper look at Synchronizers in Java and also the Decorator Pattern. Following points are don... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T04:25:25.667",
"Id": "199799",
"Score": "3",
"Tags": [
"java",
"multithreading",
"interview-questions",
"vectors"
],
"Title": "Thread-safe arraylist with get, put, add, remove functions"
} | 199799 |
<p>In this code, I focused more on code readability rather than algorithmic complexity. I didn't really care about the code in the <code>main</code> function because it was just used to test the code. Some of the classes have a D prefix to differentiate them from the regular <code>Nodes</code>. </p>
<p>A few problems in particular I would like comments on:</p>
<ul>
<li>Storing the name of the node both in the dictionary key and the name field seems wrong. I would think it has some of the same problems as <a href="https://codeblog.jonskeet.uk/2014/06/03/anti-pattern-parallel-collections/" rel="nofollow noreferrer">parallel lists</a>.</li>
<li>The <code>DGraph</code> class's only functionality is to be a wrapper for a list. On the otherhand, I like it because it is more verbose.</li>
<li>Should <code>connections</code> stay as <code>(node, cost)</code> tuples or should I make a new <code>DConnection</code> class?</li>
<li>I'm hoping to avoid external libraries</li>
</ul>
<pre><code>class DNode:
def __init__(self, name):
self.connections = []
self.name = name
self.total_cost = -1
self.last_connection = None
self.visited = False
def add_connection(self, node, cost):
self.connections.append((node, cost))
for connection in node.connections:
if connection[0] is self:
return
node.add_connection(self, cost)
class DGraph:
def __init__(self):
self.nodes = []
def new_node(self, name):
node = DNode(name)
self.nodes.append(node)
return node
class Dijkstra:
def __init__(self, graph, start_node, end_node):
self.graph = graph
self.start_node = start_node
self.end_node = end_node
self.dlist = DList(graph.nodes, start_node)
def calculate_shortest_path(self):
self.recursive_helper(self.start_node)
node = self.end_node
node_steps = []
while node != self.start_node:
node_steps.append(node)
node = node.last_connection
node_steps.append(self.start_node)
return reversed(node_steps)
def recursive_helper(self, current_node):
current_cost = current_node.total_cost
for connection in current_node.connections:
neighbor = connection[0]
if not neighbor.visited:
total_cost = current_cost + connection[1]
if neighbor.total_cost == -1 or total_cost < neighbor.total_cost:
neighbor.total_cost = total_cost
neighbor.last_connection = current_node
current_node.visited = True
if self.end_node.visited:
return
self.recursive_helper(self.dlist.get_smallest_unvisited_dnode())
class DList:
def __init__(self, node_list, start_node):
self.nodes = list(node_list)
start_node.total_cost = 0
def get_smallest_unvisited_dnode(self):
smallest = None
for node in self.nodes:
if not node.visited and node.total_cost != -1:
if smallest is None or node.total_cost < smallest.total_cost:
smallest = node
return smallest
class GraphParser:
def __init__(self, unparsed_string):
self.unparsed_string = unparsed_string
self.nodes = {}
self.graph = DGraph()
def create_nodes(self):
for line in self.unparsed_string.split("\n"):
if line[0:5] == "node ":
node_name = line[5:]
node = self.graph.new_node(node_name)
self.nodes[node_name] = node
def create_connections(self):
for line in self.unparsed_string.split("\n"):
if line[0:5] == "node ":
node_name = line[5:]
node = self.nodes[node_name]
elif line[0] == "\t":
connection_data = line[1:].split(",")
neighbor_name = connection_data[0].strip()
if len(connection_data) > 0:
cost = int(connection_data[1].strip())
else:
cost = 1
neighbor = self.nodes[neighbor_name]
node.add_connection(neighbor, cost)
def get_graph(self):
self.create_nodes()
self.create_connections()
return self.graph
def main():
filename = "graph.txt"
f = open(filename, "r")
content = f.read()
f.close()
gp = GraphParser(content)
graph = gp.get_graph()
start_node = gp.nodes["S"]
end_node = gp.nodes["E"]
d = Dijkstra(graph, start_node, end_node)
path = d.calculate_shortest_path()
for i in path:
print(i.name)
main()
</code></pre>
<p>Sample <code>graph.txt</code></p>
<pre><code>node A
D, 4
B, 3
S, 7
node B
S, 2
A, 3
D, 4
H, 1
node C
S, 3
L, 2
node D
A, 4
B, 4
F, 5
node E
K, 5
G, 2
node F
H, 3
D, 5
node G
H, 2
E, 2
node H
B, 1
F, 3
G, 2
node I
L, 4
J, 6
K, 4
node J
L, 4
I, 6
K, 4
node K
I, 4
K, 4
node L
I, 4
J, 4
node S
A, 7
B, 2
C, 3
</code></pre>
| [] | [
{
"body": "<p>I think you are using classes where you don't need to. Your <code>DGraph</code> class is one (as you have already half-realized) but your <code>GraphParser</code> is another. You even have to parse the file content twice because of your separation of concerns. In my opinion it would be way easier ... | {
"AcceptedAnswerId": "199811",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T06:39:01.500",
"Id": "199800",
"Score": "4",
"Tags": [
"python",
"algorithm",
"graph"
],
"Title": "Python: Dijkstra's Algorithm"
} | 199800 |
<p>This is a revised follow-up to <a href="https://codereview.stackexchange.com/questions/199789/counting-sort-in-c">this question</a>.</p>
<p>I have implemented most of the suggestions in the accepted answer. I am interested to see what I could improve in my code and what I could do to make it better.</p>
<blockquote>
<p>I have implemented counting sort in C. This program takes its input as integers from command line arguments, sorts the integers with counting sort, then outputs the sorted array.</p>
</blockquote>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int max(int* arr, size_t len) {
if (len < 1) {
return 0;
}
int greatest = arr[0];
for (size_t i = 0; i < len; i++)
if (arr[i] > greatest)
greatest = arr[i];
return greatest;
}
void sort(int* inputs, int* outputs, size_t length) {
// this is the size of the array of counts
int greatest = max(inputs, length); // find the greatest number in the array
// allocate the array of counts
int* counts = calloc(greatest + 1, sizeof(int));
if (counts == NULL) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
// count numbers in input array
for (size_t i = 0; i < length; i++) {
counts[inputs[i]]++;
}
size_t counter = 0; // keep track of where we are in output array
// loop through all the counts
for (int i = 0; i <= greatest; i++) { // for every count in array
for (int j = 0; j < counts[i]; j++) { // loop that many times
outputs[counter++] = i; // add the integer being counted to the output array
}
}
free(counts);
}
int main(int argc, char** argv) {
int *inputs, *outputs;
size_t length = argc - 1; // number of integers to sort
if (argc < 2) {
fprintf(stderr, "Not enough arguments given.\n");
exit(EXIT_FAILURE);
}
inputs = calloc(length, sizeof(int));
outputs = calloc(length, sizeof(int));
if (inputs == NULL || outputs == NULL) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
for (int i = 1; i < argc; i++) {
inputs[i - 1] = atoi(argv[i]); // assign arguments to array
if (inputs [i - 1] < 0) {
fprintf(stderr, "Integer %d out of range [0, 2^31)\n", inputs[i - 1]);
exit(EXIT_FAILURE);
}
}
sort(inputs, outputs, length);
for (size_t i = 0; i < length; i++) {
printf("%d ", outputs[i]); // print space separated sorted numbers
}
printf("\n");
free(inputs);
free(outputs);
return EXIT_SUCCESS;
}
</code></pre>
| [] | [
{
"body": "<h1>Enable more compiler warnings</h1>\n\n<p>I get</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>gcc-8 -std=c11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion 199801.c -o 199801\n</code></pre>\n\n<pre class=\"lang-none prettyprin... | {
"AcceptedAnswerId": "199806",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T06:43:28.450",
"Id": "199801",
"Score": "3",
"Tags": [
"algorithm",
"c",
"array",
"sorting"
],
"Title": "Counting sort in C, revised"
} | 199801 |
<blockquote>
<p><a href="https://coderbyte.com/editor/guest:Maximal%20Square:Cpp" rel="nofollow noreferrer"><strong>Challenge</strong></a></p>
<p>Using the C++ language, have the function <code>MaximalSquare(strArr)</code> take the <code>strArr</code> parameter being passed which will be a 2D matrix of 0 and 1's, and determine the area of the largest square submatrix that contains all 1's. A square submatrix is one of equal width and height, and your program should return the <strong>area</strong> of the largest submatrix that contains only 1's. For example: if <code>strArr</code> is ["10100", "10111", "11111", "10010"] then this looks like the following matrix: </p>
<pre><code>1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
</code></pre>
<p>For the input above, you can see the bolded 1's create the largest square submatrix of size 2x2, so your program should return the area which is 4. You can assume the input will not be empty. </p>
<p><strong>Sample Test Cases</strong></p>
<pre><code>Input:"0111", "1111", "1111", "1111"
Output:9
Input:"0111", "1101", "0111"
Output:1
</code></pre>
</blockquote>
<p>How can I make improvements to my code? Is there any STL that I might not know of that might make the code simpler and/or efficient?</p>
<pre><code>#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
bool check_Same_Length(std::vector< std::vector<int> > maximalSquareInput)
{
bool state;
size_t length = maximalSquareInput[0].size();
for (int i = 0; i < maximalSquareInput.size(); ++i)
{
if (length == maximalSquareInput[i].size())
{
state = true;
}
else
{
state = false;
return state;
}
}
return state;
}
bool only_1_And_0(std::vector< std::vector<int> > maximalSquareInput)
{
for (int i = 0; i < maximalSquareInput.size(); ++i)
{
if (!(std::all_of(maximalSquareInput[i].begin(), maximalSquareInput[i].end(),
[] (int digit) { return digit == 1 || digit == 0; })))
{
return false;
}
}
return true;
}
int findBiggestElement(std::vector< std::vector<int> > maximalSquareOutput)
{
int biggestElement = 0;
for (int i = 0; i < maximalSquareOutput.size(); ++i)
{
auto itr = std::max_element(maximalSquareOutput[i].begin(), maximalSquareOutput[i].end());
if (*itr > biggestElement)
{
biggestElement = *itr;
}
}
return biggestElement;
}
std::string findLargestSubmatrix(const std::vector< std::vector<int> > maximalSquareInput)
{
std::vector< std::vector<int> > maximalSquareOutput (maximalSquareInput.size(), std::vector<int>(maximalSquareInput[0].size()) );
if(check_Same_Length(maximalSquareInput) && only_1_And_0(maximalSquareInput))
{
for (int row = 0; row < maximalSquareInput.size(); ++row)
{
for (int column = 0; column < maximalSquareInput[row].size(); ++column)
{
if (row == 0 || column == 0 || maximalSquareInput[row][column] == 0)
{
maximalSquareOutput[row][column] = maximalSquareInput[row][column];
}
else
{
int minElement = std::min({maximalSquareOutput[row-1][column], maximalSquareOutput[row-1][column-1], maximalSquareOutput[row][column-1]});
maximalSquareOutput[row][column] = maximalSquareInput[row][column] + minElement;
}
}
}
}
unsigned long long int biggestElement = findBiggestElement(maximalSquareOutput);
return std::to_string(biggestElement * biggestElement);
}
</code></pre>
| [] | [
{
"body": "<pre><code>#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n</code></pre>\n\n<p>Do you need <code><iostream></code>?</p>\n\n<hr>\n\n<pre><code>bool check_Same_Length(std::vector< std::vector<int> > maximalSquareInput)\n</code><... | {
"AcceptedAnswerId": "199887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T08:24:00.547",
"Id": "199808",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"dynamic-programming"
],
"Title": "Demonstration of the Largest Square Submatrix"
} | 199808 |
<p>I wanted to implement <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="noreferrer">Dijkstra's Algorithm</a> in an Excel VBA Add-In and built it to be used as follows:</p>
<ol>
<li>Define a list of paths with distances between points. This list needs to contain 3 headings that are used as flags to pick up where the list is. The 3 headings are <code>!dijk:dat:from</code>, <code>!dijk:dat:to</code> and <code>!dijk:dat:dist</code></li>
<li>Specify from which point to which point you want to go. This is indicated with flags to the left of the cell. The flags are <code>!dijk:get:from</code> and <code>!dijk:get:to</code></li>
<li>If the list of paths is on a different sheet, specify which sheet it is on by putting the name of the sheet in a cell next to a cell with the text <code>!dijk:dat</code></li>
<li>Specify where the output should go. This is defined with a flag at the top left of where it should go. The flag is <code>!dijk:steps</code></li>
<li>Push a button in the Ribbon that triggers <code>Sub sCalcDijkstra()</code> in a module in my Add-In</li>
</ol>
<p>An example of a dummy sheet I used for testing:</p>
<p><a href="https://i.stack.imgur.com/LW6EV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LW6EV.png" alt="Example Sheet"></a></p>
<p>This is the procedure that does all the work:</p>
<pre><code>Sub sCalcDijkstra()
'Calculate the shortest path between 2 points
Dim vError As String
Dim vRange As Range
Dim vRangeDat As Range
Dim vRow As Long
Dim vRowDatHead As Long
Dim vRowSteps As Long
Dim vRowFirst As Long
Dim vRowCount As Long
Dim vRowCountDat As Long
Dim vCol As Long
Dim vColDatFrom As Long
Dim vColDatTo As Long
Dim vColDatDist As Long
Dim vColSteps As Long
Dim vColFirst As Long
Dim vColCount As Long
Dim vColCountDat As Long
Dim vCell As String
Dim vCellFrom As String
Dim vCellTo As String
Dim vValDist As Double
Dim vParFrom As String
Dim vParTo As String
Dim vParDat As String
Dim vDist As Scripting.Dictionary
Dim vKey As Variant
Dim vCurNode As String
Dim vCurDist As Double
Dim vCurDistTo As Double
Dim vSteps() As String
On Error GoTo 0
vError = ""
'Check that there is a workbook open
If ActiveSheet Is Nothing Then vError = "You need to open a workbook in order to do this"
If vError <> "" Then GoTo ErrorHandler
'Get the settings from the current sheet
Set vRange = ActiveSheet.UsedRange
vRowCount = vRange.Rows.Count
vColCount = vRange.Columns.Count
vRowFirst = vRange.Row
vColFirst = vRange.Column
vRowSteps = 0
vColSteps = 0
vParFrom = ""
vParTo = ""
vParDat = ""
For vRow = 1 To vRowCount
For vCol = 1 To vColCount
vCell = ""
On Error Resume Next
vCell = Trim(UCase(vRange.Cells(vRow, vCol).Value))
On Error GoTo 0
If vCell = "!DIJK:GET:FROM" Then
vParFrom = Trim(UCase(vRange.Cells(vRow, vCol + 1).Value))
ElseIf vCell = "!DIJK:GET:TO" Then
vParTo = Trim(UCase(vRange.Cells(vRow, vCol + 1).Value))
ElseIf vCell = "!DIJK:DAT" Then
vParDat = Trim(UCase(vRange.Cells(vRow, vCol + 1).Value))
ElseIf vCell = "!DIJK:STEPS" Then
vRowSteps = vRow
vColSteps = vCol
End If
Next
Next
If vParFrom = "" Then vError = vError & "Need to specify a Source with the parameter !dijk:get:from" & vbCrLf & vbCrLf
If vParTo = "" Then vError = vError & "Need to specify a Destination with the parameter !dijk:get:to" & vbCrLf & vbCrLf
If vRowSteps = 0 Then vError = vError & "Need to designate an area to print the results with the parameter !dijk:steps" & vbCrLf & vbCrLf
If vError <> "" Then GoTo ErrorHandler
'Clean up the output area
vRange.Range(vRange.Cells(vRowSteps + 2 - vRowFirst, vColSteps + 1 - vColFirst).Address, vRange.Cells(vRowCount + vRowFirst - 1, vColSteps + 3 - vColFirst).Address).ClearContents
'Get the paths from the data sheet
If vParDat = "" Then
Set vRangeDat = vRange
Else
Set vRangeDat = ActiveWorkbook.Worksheets(vParDat).UsedRange
End If
vRowCountDat = vRangeDat.Rows.Count
vColCountDat = vRangeDat.Columns.Count
vRowDatHead = 0
vColDatFrom = 0
vColDatTo = 0
vColDatDist = 0
For vRow = 1 To vRowCountDat
For vCol = 1 To vColCountDat
vCell = ""
On Error Resume Next
vCell = Trim(UCase(vRangeDat.Cells(vRow, vCol).Value))
On Error GoTo 0
If vCell = "!DIJK:DAT:FROM" Then
vRowDatHead = vRow
vColDatFrom = vCol
ElseIf vCell = "!DIJK:DAT:TO" Then
vRowDatHead = vRow
vColDatTo = vCol
ElseIf vCell = "!DIJK:DAT:DIST" Then
vRowDatHead = vRow
vColDatDist = vCol
End If
Next
If vRowDatHead > 0 Then Exit For
Next
If vColDatFrom = 0 Then vError = vError & "Data sheet is missing !dijk:dat:from column" & vbCrLf & vbCrLf
If vColDatTo = 0 Then vError = vError & "Data sheet is missing !dijk:dat:to column" & vbCrLf & vbCrLf
If vColDatDist = 0 Then vError = vError & "Data sheet is missing !dijk:dat:dist column" & vbCrLf & vbCrLf
If vError <> "" Then GoTo ErrorHandler
Set vDist = New Scripting.Dictionary
For vRow = vRowDatHead + 1 To vRowCountDat
vCellFrom = ""
vCellTo = ""
vValDist = -1
On Error Resume Next
vCellFrom = Trim(UCase(vRangeDat.Cells(vRow, vColDatFrom).Value))
vCellTo = Trim(UCase(vRangeDat.Cells(vRow, vColDatTo).Value))
vValDist = Val(Trim(UCase(vRangeDat.Cells(vRow, vColDatDist).Value)))
On Error GoTo 0
If vCellFrom <> "" And vCellTo <> "" And vValDist >= 0 Then
If Not vDist.Exists(vCellFrom) Then Set vDist.Item(vCellFrom) = New Scripting.Dictionary
If Not vDist.Exists(vCellTo) Then Set vDist.Item(vCellTo) = New Scripting.Dictionary
vDist(vCellFrom).Item(vCellTo) = vValDist
If Not vDist(vCellTo).Exists(vCellFrom) Then vDist(vCellTo).Item(vCellFrom) = vValDist
End If
Next
If Not vDist.Exists(vParFrom) Then vError = vError & "Source " & vParFrom & " not listed in data" & vbCrLf & vbCrLf
If Not vDist.Exists(vParTo) Then vError = vError & "Destination " & vParTo & " not listed in data" & vbCrLf & vbCrLf
If vError <> "" Then GoTo ErrorHandler
'Calculate the shortest path
For Each vKey In vDist.Keys()
vDist(vKey).Item("!dist") = -1
vDist(vKey).Item("!scan") = False
vDist(vKey).Item("!steps") = ""
Next
vDist(vParFrom).Item("!dist") = 0
vDist(vParFrom).Item("!steps") = vParFrom
Do While True
vCurNode = ""
vCurDist = 0
For Each vKey In vDist.Keys()
If vDist(vKey)("!scan") = False Then
If vDist(vKey)("!dist") >= 0 Then
If vCurNode = "" Or vCurDist > vDist(vKey)("!dist") Then
vCurNode = vKey
vCurDist = vDist(vKey)("!dist")
End If
End If
End If
Next
If vCurNode = "" Then Exit Do
If vCurNode = vParTo Then Exit Do
vDist(vCurNode).Item("!scan") = True
For Each vKey In vDist(vCurNode).Keys()
If Left(vKey, 1) <> "!" And vKey <> vCurNode Then
vCurDistTo = vCurDist + vDist(vCurNode)(vKey)
If vDist(vKey)("!dist") < 0 Or vCurDistTo < vDist(vKey)("!dist") Then
vDist(vKey).Item("!dist") = vCurDistTo
vDist(vKey).Item("!steps") = vDist(vCurNode)("!steps") & "!" & vKey
End If
End If
Next
Loop
'Print the result
If vDist(vParTo)("!dist") < 0 Then
vRange.Cells(vRowSteps + 1, vColSteps).Value = "No path found from source to destination"
Else
vSteps = Split(vDist(vParTo)("!steps"), "!")
For vRow = 1 To UBound(vSteps)
vRange.Cells(vRowSteps + vRow, vColSteps).Value = vSteps(vRow - 1)
vRange.Cells(vRowSteps + vRow, vColSteps + 1).Value = vSteps(vRow)
vRange.Cells(vRowSteps + vRow, vColSteps + 2).Value = vDist(vSteps(vRow - 1))(vSteps(vRow))
Next
vRange.Cells(vRowSteps + vRow, vColSteps).Value = "Total:"
vRange.Cells(vRowSteps + vRow, vColSteps + 2).Value = vDist(vParTo)("!dist")
End If
'Done
MsgBox "Done", vbOKOnly + vbInformation, "Path and Distance"
GoTo Finalize
ErrorHandler:
Err.Clear
MsgBox vError, vbOKOnly + vbCritical, "Error"
Finalize:
Set vDist = Nothing
End Sub
</code></pre>
<p>The code works, but I would like some feedback on the following aspects:</p>
<ul>
<li>How can I make this easier and more intuitive for a user? I know I can use named ranges instead of flags, but I would prefer to keep it more visibly obvious what the code is using</li>
<li>How can I apply the DRY principle more here. I'm repeating the same patterns all the time, but it seems like the details vary too much for me to just stick something like the nested for loops into a function</li>
<li>I use <code>Scripting.Dictionary</code> for almost everything due to it's flexibility and simply due to the fact that I am comfortable with how it works, but I suspect there may be better data structures that I can use which work better for this use case</li>
<li>At the heart of this is the <code>Do While True</code> loop which is probably a horribly inefficient way to implement Dijkstra's Algorithm. How can I make it more efficient?</li>
<li>Any help/critique is greatly appreciated. I taught myself VBA with the help of Google and I may be doing some bad things I never even realised</li>
</ul>
| [] | [
{
"body": "<p>That is a humungous procedure you got there. It's all in one piece and it's following a lot of conventions from older VBA code that you should not let become a habit.</p>\n\n<p>The first of these \"conventions\" is to declare every variable at the top of the block they're scoped to. This is a reli... | {
"AcceptedAnswerId": "199839",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T09:32:37.810",
"Id": "199812",
"Score": "5",
"Tags": [
"vba",
"excel"
],
"Title": "Dijkstra's algorithm implemented in Excel VBA"
} | 199812 |
<p>TCP/IP server which controls up to 500 clients. There's a list of added computers and the server gets this list, selects computers which are not already connected and ping them using host name.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
using Timer = System.Threading.Timer;
namespace Server.Communications
{
/// <summary>
/// Checks statuses of computers (online/offline) which are not connected to server.
/// </summary>
[ServiceId(ServiceId.RemoteComputersService)]
public class RemoteComputersService : PublicService, IDisposable
{
private Timer _timer;
private bool _skipTimerElapse;
public RemoteComputersService(ServerTools tools)
: base(tools)
{ }
/// <summary>
/// Ping function to check status of EAM client before creating pipe to avoid stuck
/// </summary>
/// <param name="clientName">Domain or workgroup name of computer.</param>
/// <param name="computerId">Computer id.</param>
/// <returns>True if computer is online.</returns>
private async Task<ComputerPingReply> IsMachineOnlineAsync(string clientName, long computerId)
{
try
{
var ping = new Ping();
var pingReply = await ping.SendPingAsync(clientName, 500);
return new ComputerPingReply(computerId, pingReply);
}
catch (Exception)
{
return new ComputerPingReply(computerId, null);
}
}
private async Task PingAllComputers(IEnumerable<Computer> computers)
{
var pingConnectionStatus = computers
.Select(computer => IsMachineOnlineAsync(computer.HostName, computer.ComputerId))
.ToList();
while (pingConnectionStatus.Count > 0)
{
//Wait for the first end task
var task = await Task.WhenAny(pingConnectionStatus);
pingConnectionStatus.Remove(task);
var result = await task;
//Do nothing if computer is already connected
if (result.PingReply != null &&
SSLDaemonProviderService.IsComputerConnected(result.ComputerId)) continue;
var connectionStatus = result.PingReply == null ||
result.PingReply.Status != IPStatus.Success
? ConnectionStatus.Offline
: ConnectionStatus.Online;
ComputerInfoProviderService.UpdateConnectionStatus(connectionStatus, result.ComputerId);
}
}
private async void CheckRemoteComputers()
{
if (_skipTimerElapse) return;
_skipTimerElapse = true;
try
{
// Computers which are not connected to server shall be checked only.
var allComputers = ComputerInfoProviderService.GetComputers();
var notConnectedComputers = allComputers
.Where(c => !SSLDaemonProviderService.IsComputerConnected(c.ComputerId))
.OrderBy(c => Guid.NewGuid()) //randomize list of computers
.ToArray();
if (notConnectedComputers.Length == 0) return;
Tools.LogDebug(Localization.RemoteComputersService.PingingOfRemoteComputersStarted, notConnectedComputers.Length);
await PingAllComputers(notConnectedComputers);
}
catch (Exception ex)
{
Tools.LogException(ex);
}
finally
{
Tools.LogDebug(Localization.RemoteComputersService.PingingOfRemoteComputersFinished);
_skipTimerElapse = false;
}
}
protected override void OnStart()
{
_timer = new Timer(
_ => CheckRemoteComputers(),
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(10));
}
protected override void OnStop()
{
Dispose();
}
#region IDisposable
private bool _disposed;
private void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_timer.Dispose();
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T18:57:14.030",
"Id": "384602",
"Score": "1",
"body": "The description for this question is also very general. Please give us more details like what do you mean by _in a solid way_. How is it pinging the clients etc etc."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T09:44:31.170",
"Id": "199813",
"Score": "2",
"Tags": [
"c#",
".net",
"async-await"
],
"Title": "Server app: pinging up to 500 clients asynchronyosly"
} | 199813 |
<p>I need to process rabbitmq messages with golang with worker style,
is this correct way to process rabbitmq messages with golang?</p>
<pre><code>package main
import (
"log"
"github.com/streadway/amqp"
)
func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
panic(err)
}
defer conn.Close()
for _, q := range []string{"q1", "q2", "q3"} {
go RunFetcher(q, conn, 3, 50)
}
select {}
}
func RunFetcher(queueName string, conn *amqp.Connection, workers, qos int) {
ch, err := conn.Channel()
if err != nil {
log.Println(err.Error())
return
}
ch.Qos(qos, 0, false)
defer ch.Close()
msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
if err != nil {
log.Println(err.Error())
return
}
for index := 0; index < workers; index++ {
go func() {
for d := range msgs {
// process message
d.Ack(false)
}
}()
}
select {}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T11:06:44.977",
"Id": "384500",
"Score": "0",
"body": "Note: your code has `main` function but lacks `package` and `import` parts. You may edit your question to add them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationD... | [
{
"body": "<p>There's not really a one <em>\"right\"</em> way of doing things, and all of the others are wrong. However, there's a number of things that are considered good practice, and WRT to those, your code can do with a bit of TLC.</p>\n\n<p>To that end, I'll just run through your code line by line, leavin... | {
"AcceptedAnswerId": "199894",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T09:44:58.703",
"Id": "199814",
"Score": "6",
"Tags": [
"go",
"rabbitmq"
],
"Title": "golang rabbitmq message consumer"
} | 199814 |
<p>I have implemented a little snake game with Javascript and Html. This is my first game with Javascript. I use a Linkedlist to represent the snake. Both code snippets are in snake.js file.</p>
<p>It would be really nice if someone could give me feedback.</p>
<p>LinkedList:</p>
<pre><code>function Point(x, y) {
this.x=x;
this.y=y;
this.toString = function toString() {
return this.x +" "+this.y;
}
}
function Node(point) {
var next =null;
this.point=point;
this.getX = function getX() {
return this.point.x;
}
this.getY = function getY() {
return this.point.y;
}
this.setX = function setX(x) {
this.point.x=x;
}
this.setY = function setY(y) {
this.point.y=y;
}
this.toString = function toString() {
return this.point.x +" "+this.point.y + " "+this.next;
}
}
function LinkedList() {
var first = null;
var elements = 0;
this.getLength = function getLength() {
return elements;
}
this.addFirst = function addFirst(point) {
elements++;
var newNode = new Node(point);
newNode.next = first;
first = newNode;
}
this.addLast = function addLast(point) {
elements++;
var newNode = new Node(point);
var currentNode = first;
while(currentNode.next!=null) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
newNode = currentNode;
}
this.getX = function getX(index) {
var currentNode = first;
var tmp =0;
while(true) {
if(index> elements - 1) {
//console.log("Fehler: ungültiger Index");
return null;
}
if(tmp==index) {
return currentNode.getX();
}
tmp++;
currentNode= currentNode.next;
}
}
this.setX = function setX(index, value) {
var currentNode = first;
var tmp =0;
while(true) {
if(index> elements - 1) {
//console.log("Fehler: ungültiger Index");
return null;
}
if(tmp==index) {
currentNode.setX(value);
return currentNode;
}
tmp++;
currentNode= currentNode.next;
}
}
this.setY = function setX(index, value) {
var currentNode = first;
var tmp =0;
while(true) {
if(index> elements - 1) {
//console.log("Fehler: ungültiger Index");
return null;
}
if(tmp==index) {
currentNode.setY(value);
return currentNode;
}
tmp++;
currentNode= currentNode.next;
}
}
this.getY = function getY(index) {
var currentNode = first;
var tmp =0;
while(true) {
if(index> elements - 1) {
//console.log("Fehler: ungültiger Index");
return null;
}
if(tmp==index) {
return currentNode.getY();
}
tmp++;
currentNode= currentNode.next;
}
}
}
</code></pre>
<p>Snake:</p>
<pre><code> var boardWidth = 40;
var boardHeight = 40;
var canvas;
var context;
var snakeList = new LinkedList();
function Food() {
var positionX;
var positionY;
this.randomFood = function randomFood() {
this.positionX= Math.floor((Math.random() * (boardWidth-1)));
this.positionY = Math.floor((Math.random() * (boardHeight-1)));
}
this.getX = function getX() {
return this.positionX;
}
this.getY = function getY() {
return this.positionY;
}
}
function Snake() {
var positionX = Math.floor((Math.random() * (boardWidth-5)));
var positionY = Math.floor((Math.random() * (boardWidth-5)));
var interval = setInterval(update, 100);
var pressedKey = 0; // start game with arroa key
var food = new Food();
var points =0;
food.randomFood();
snakeList.addFirst(new Point(positionX,positionY));
snakeList.addFirst(new Point(positionX-1,positionY));
snakeList.addFirst(new Point(positionX-2,positionY));
function update() {
if(pressedKey!=0) {
move();
}
eatApple();
changeDirection();
checkGameOver();
repaint();
if(pressedKey==0) {
context.strokeText("Start Game with arrow key, new Game with F5",100,20,150);
}
}
function move() {
for(var i= snakeList.getLength()-1; i > 0; i--) {
snakeList.setX(i,snakeList.getX(i-1));
snakeList.setY(i,snakeList.getY(i-1));
}
}
function eatApple() {
if(snakeList.getX(0)==food.getX(0) && snakeList.getY(0)==food.getY(0)) {
snakeList.addLast(new Point());
points++;
document.getElementById("textareapoints").value = "Points: "+points;
food.randomFood();
}
}
function changeDirection() {
var xDirection= snakeList.getX(0);
var yDirection= snakeList.getY(0);
window.onkeydown = function(evt) {
if (evt.keyCode == 37) { pressedKey=37;} //left
if (evt.keyCode == 38) { pressedKey=38;} //up
if (evt.keyCode == 39) { pressedKey=39;} //right
if (evt.keyCode == 40) { pressedKey=40;} //down
}
switch(pressedKey) {
case 37: snakeList.setX(0,xDirection-1); break;
case 38: snakeList.setY(0,yDirection-1); break;
case 39: snakeList.setX(0,xDirection+1); break;
case 40: snakeList.setY(0,yDirection+1); break;
default: break;
}
}
function checkGameOver() {
for(var i=1; i<snakeList.getLength(); i++) { // eat itself
if(snakeList.getX(0)== snakeList.getX(i) &&
snakeList.getY(0)==snakeList.getY(i)) {
clearInterval(interval);
context.strokeText("new Game with F5",100,20,150);
}
}
if(snakeList.getX(0) < 0 || snakeList.getX(0) > boardWidth-1 || // hit border
snakeList.getY(0) < 0 || snakeList.getY(0) > boardHeight-1) {
clearInterval(interval);
context.strokeText("new Game with F5",100,20,150);
}
}
function repaint() {
context.fillStyle = "yellow"; // repaint whole canvas
for(var i=0; i<boardWidth; i++) {
for(var j=0; j<boardHeight; j++) {
context.fillRect(i*10, j*10,10,10);
}
}
context.fillStyle = "green"; // food
context.fillRect(food.getX()*10, food.getY()*10, 10, 10)
context.fillStyle = "red"; //snake head
context.fillRect(snakeList.getX(0)*10, snakeList.getY(0)*10,10,10);
context.fillStyle = "blue"; // snake body
for(var i=1; i<snakeList.getLength(); i++) {
context.fillRect(snakeList.getX(i)*10, snakeList.getY(i)*10,10,10);
}
}
}
function initCanvas() {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
context.fillStyle = "yellow";
context.fillRect(0,0,canvas.width, canvas.height);
context.fillStyle = "black";
}
window.onload = function() {
initCanvas();
var s = new Snake();
}
</code></pre>
<p>Html page:</p>
<pre><code><!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>Snake</title>
<link href="snakecss.css" rel="stylesheet">
<script src="snake.js"></script>
</head>
<body>
<header>
<h1>Snake</h1>
</header>
<canvas id="canvas"> </canvas>
<textarea id="textareapoints" type="text" rows="1" cols="30">
Points: 0
</textarea>
</body>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/uWdjK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uWdjK.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<h2>Worst use of linked list, ever!</h2>\n<p>Linked list are convenient for many reasons, one of them is fast splicing, much faster than array splicing and thus the best option when you are often inserting and deleting items at random positions in the list.</p>\n<p>Linked list are very (VERY) poor at... | {
"AcceptedAnswerId": "199842",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T09:47:36.983",
"Id": "199815",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"object-oriented",
"game",
"snake-game"
],
"Title": "Javascript Snake"
} | 199815 |
<p>I was wondering if there is a better, more elegant way to write the following JavaScript code block:</p>
<pre><code>var searchString = 'ma';
var names = ['Mark Kennel', 'Hellen Smith', 'Jane Mary Annet', 'Peter'];
var filteredNames = names.filter(name => {
var words = name.toLowerCase().split(' ');
for(var i = 0; i < words.length; i++) {
if (words[i].indexOf(searchString.toLowerCase()) === 0 )
return true;
}
}
</code></pre>
<p>This runs in a function that filters an autocomplete input results. The filtering rule is:</p>
<blockquote>
<p>Show the names that have a word which begins with the <code>searchString</code></p>
</blockquote>
<p>The above code (with <code>searchString = 'ma'</code>) should return an array with two names: 'Mark Kennel' and 'Jane Mary Annet'.</p>
| [] | [
{
"body": "<p>There is no need to call <code>searchString.toLowerCase()</code> every loop iteration. I'd suggest to do it once outside the loop.</p>\n\n<pre><code>var searchStringLowCase = searchString.toLowerCase();\n</code></pre>\n\n<p>Also instead of splitting the name we can make use of <code>indexOf</code>... | {
"AcceptedAnswerId": "199822",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T10:29:18.083",
"Id": "199818",
"Score": "4",
"Tags": [
"javascript",
"array",
"ecmascript-6",
"autocomplete"
],
"Title": "Filtering a name Array in JavaScript"
} | 199818 |
<p>I have a use case in which I need to check whether a given value is explicitly <code>True</code> or <code>False</code>:</p>
<pre><code>def stringify(value):
"""Returns the string representation of the value."""
if value is None:
return '-'
if value is True:
return '✓'
if value is False:
return '✗'
return str(value)
</code></pre>
<p>I know, that in most cases, where you just need the <em>truthiness</em>, you'd just do <code>if value:</code>. But here this will not suffice, since I want zero <code>int</code>s and <code>float</code>s to be displayed in their decimal form as well as empty <code>list</code>s, <code>set</code>s <code>dict</code>s as such.
Is the above code acceptable or should I rather check using <code>isinstance(value, bool)</code> first and then do <code>if value:</code>?</p>
<p>What's the <em>least surprising</em> way to go?</p>
<p><strong>Usage Context</strong><br>
The function is part of an API that converts database records to terminal output:<br>
MariaDB → <a href="http://docs.peewee-orm.com/en/latest/" rel="noreferrer">peewee</a> → API → terminal</p>
<p>Example output:</p>
<pre class="lang-none prettyprint-override"><code>$ termutil ls -T 1000
ID TID CID VID OS IPv4 Address Deployed Testing Tainted Address Annotation
214 1 1000 - HIDSL latest XX.Y.Z.75 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
215 2 1000 - HIDSL latest XX.Y.Z.76 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
216 3 1000 - HIDSL latest XX.Y.Z.77 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
217 4 1000 - HIDSL latest XX.Y.Z.78 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
218 5 1000 - HIDSL latest XX.Y.Z.79 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
219 6 1000 - HIDSL latest XX.Y.Z.80 - ✓ ✗ Musterstraße 42, 123456 Irgendwo -
330 7 1000 399 HIDSL latest XX.Y.Z.182 - ✗ ✗ Musterstraße 42, 123456 Irgendwo -
508 8 1000 - HIDSL latest XX.Y.Z.189 - ✗ ✗ N/A -
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T13:44:47.697",
"Id": "384523",
"Score": "2",
"body": "Personally not fond of the end case here. What if I pass in '-', '✓', or '✗'? The returned value will be ambiguous. Or you could specify that you don't accept strings in your doc... | [
{
"body": "<p>Because the code snippet is so small and missing any other context, it's hard to identify any problems in scaling / that may arise elsewhere in the code. Thus if you want a more tailored answer, you should add more code.</p>\n\n<p>Yes, this is fine.</p>\n\n<p>Regarding the <code>isinstance()</code... | {
"AcceptedAnswerId": "199824",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T10:57:22.670",
"Id": "199819",
"Score": "20",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python function to map True, False, and None to symbols for display"
} | 199819 |
<pre><code>public static void main(String[] args) {
int minKmh = 10;
int maxKmh = 20;
int step = 5;
String allSpeeds = "";
while (minKmh <= maxKmh) {
allSpeeds += minKmh + ",";
minKmh += step;
}
String[] allSpeedsAsArray = removeLastChar(allSpeeds).split(","); // result: 10,15,20
}
private static String removeLastChar(String str) {
return str.substring(0, str.length() - 1);
}
</code></pre>
<p>I have a minimum car speed and a maximum car speed. In this case 10 and 20. And I want every speed which is between minimum and maximum where the speed gets incremented by a step speed. </p>
<p>I don't like my current version because it is large in my opinion. Is it possible to shorten the code to 1-2 liner?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T18:12:00.973",
"Id": "384591",
"Score": "0",
"body": "Use a for loop and remember clarity is not about the fewest number of lines if are long and convoluted."
}
] | [
{
"body": "<p>First off, you should capture this functionality in a dedicated method, rather than in the class' main method.</p>\n\n<p>Secondly, I'm not sure why you want an array of <code>String</code>. I don't know the context, but as you're already calculating with speeds, it seems likely you'll calculate mo... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T11:40:51.737",
"Id": "199823",
"Score": "1",
"Tags": [
"java",
"algorithm"
],
"Title": "Calculate different speeds between min and max speed with a stepsize"
} | 199823 |
<p>Hello I wrote the following code. It allows me to use objects as keys in a map. I have a constraint though:</p>
<ul>
<li>In <code>addElement</code> function both arguments must be pointers</li>
</ul>
<hr />
<pre><code>// Example program
#include <iostream>
#include <string.h>
#include <map>
typedef struct {
std::string name;
} Test;
class Tester {
/*I want the TestCompare to be in class Tester*/
struct TestCompare {
bool operator()(const Test & LQuery, const Test & RQuery) const {
return LQuery.name.compare(RQuery.name) < 0;
}
};
public:
Tester() {};
~Tester() {};
void addElement(const Test *key, const Test *value) {
m.insert(std::make_pair((*key),value));
}
void printElement() {
for(auto &e:m){
std::cout<< e.first.name << " " << e.second->name << std::endl;
}
}
private:
std::map<const Test, const Test*,TestCompare> m;
};
int main()
{
Test k1 = {"1"};
Test v1 = {"1"};
Test k2 = {"2"};
Test v2 = {"2"};
Test k3 = {"3"};
Test v3 = {"3"};
Tester tester;
tester.addElement(&k1, &v1);
tester.addElement(&k2, &v2);
tester.addElement(&k3, &v3);
tester.printElement();
return 0;
}
</code></pre>
<hr />
<h1>Questions</h1>
<ul>
<li>Is the <code>TestCompare</code> implemented correctly?</li>
<li>Does it bother you on how I dereference the pointer? I MUST have a pointer to object in the arguments</li>
<li>Is <code>TestCompare</code> placed correctly inside the class <code>Tester</code>?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T13:31:40.733",
"Id": "384515",
"Score": "1",
"body": "Is there a reason you can't simply use a `std::map<std::string, std::string>` (or a `std::map<std::string_view, std::string_view>`)?"
},
{
"ContentLicense": "CC BY-SA 4.0... | [
{
"body": "<pre><code>#include <string.h>\n</code></pre>\n\n<p>I'm sure you either mean <code><string></code> or <code><cstring></code>, probably the former.</p>\n\n<pre><code>typedef struct {\n std::string name;\n} Test;\n</code></pre>\n\n<p>This is not C; there is no sensible reason for d... | {
"AcceptedAnswerId": "199874",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T13:17:42.873",
"Id": "199828",
"Score": "-4",
"Tags": [
"c++",
"object-oriented",
"hash-map"
],
"Title": "Use key as object in map C++: Check if the less operator is implemented correcty"
} | 199828 |
<p><a href="https://codereview.stackexchange.com/questions/199727/game-server-auth-cookie-key-generatecheck">C++ code version</a> (description copied from it)</p>
<p><code>gameKeys id</code> is authentication function of an MMO game server. When someone wants to play with friends, he sends request to server, server calls <code>generateId</code>, then <code>gameKeys id</code> and returns it as JSON using <code>encodeJSON</code> to player via API. When a friend establishes connection, he sends the game id and his key, server calls <code>gameKeys id</code>, where <code>id</code> is user data, and then checks user's key.</p>
<p>Algorithm is:</p>
<ul>
<li>use current time and internal counter to generate id if it's not provided, or use provided id</li>
<li>make fast crypto hash using Blake2 function of id and secret(Yes, I know about HMAC and using as key, but in this case it doesn't matter)</li>
<li>split 64-bit hash to four 16-bit values, one hash for one user</li>
<li>make JSON object from id and keys and return it</li>
</ul>
<p>I want to make stable code: exploit-free, no memory leaks and high speed (for high load and DDOS prevention). I'm experimenting now, so the algorithm was first written in JavaScript, then in C++ and now in Haskell.</p>
<p>I think Haskell is best in writing stable code.</p>
<p>Please review the Haskell code; I think it can be improved (I'm new to Haskell). Code compiles and works same as JS and C++. Also please advise me, which programming language is better for this: JS, C++ , Haskell or Go?</p>
<p>Here's the Haskell code; install dependencies <code>cabal install blake2 hex split unix-time json</code> to run it:</p>
<pre><code>{-# LANGUAGE DeriveDataTypeable #-}
import Data.IORef
import System.IO.Unsafe
import qualified Crypto.Hash.BLAKE2.BLAKE2b as Blake2
import qualified Data.ByteString.Char8 as Char8
import Data.Hex
import Data.Char
import Data.List.Split
import Data.UnixTime
import Text.JSON.Generic
topsecret = "TOPSECRET"
dateCounter :: IORef Int
dateCounter = unsafePerformIO (newIORef 0)
hashBytes :: Char8.ByteString -> Char8.ByteString
hashBytes = Blake2.hash 64 mempty;
hashHex :: String -> String
hashHex = (map toLower) . Char8.unpack . hex . hashBytes . Char8.pack;
makeKeys :: String -> [String]
makeKeys = (chunksOf 32) . hashHex;
data GameAuth = GameAuth
{ id :: Int
, keys :: [String]
} deriving (Show, Data, Typeable)
gameKeys id = GameAuth id (makeKeys ((show id)++"|keys|"++topsecret))
generateId = do
time <- getUnixTime
counter <- readIORef dateCounter
modifyIORef dateCounter addCounter
return $ shiftTime time counter
shiftTime time counter = (fromEnum (utSeconds time))*1000 + counter
addCounter c = (c+1) `mod` 1000
main = do
id <- generateId
putStrLn (encodeJSON (gameKeys id))
</code></pre>
<p>Here's the node.js version; it needs <code>blakejs</code> (run <code>npm i blakejs</code> to install it):</p>
<pre class="lang-js prettyprint-override"><code>const TOPSECRET = "TOPSECRET", blake = require("blakejs").blake2bHex;
let dateCounter = 0;
function gameKey(checkId){
let id = checkId || (Date.now()/1000>>0)*1000+(dateCounter++%1000),
keys = blake(`${id}|keys|${TOPSECRET}`).match(/.{32}/g);
return {id, keys};
}
console.log(gameKey());
</code></pre>
| [] | [
{
"body": "<p>As <a href=\"http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-IORef.html#v:modifyIORef\" rel=\"nofollow noreferrer\"><code>modifyIORef</code></a> notes, use <code>modifyIORef'</code> for counters.</p>\n\n<p>I would wrap the unsafe usage of <code>unsafePerformIO</code> into a safer interf... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T13:33:26.483",
"Id": "199829",
"Score": "1",
"Tags": [
"game",
"haskell",
"linux",
"server"
],
"Title": "Haskell game server auth: cookie key generate&check"
} | 199829 |
<p>I have a function:</p>
<pre><code>def palindrome(n):
assert(n < 10)
res = [['0']]
for x in range(1, n + 1):
str_x = str(x)
l = len(res)
res.insert(0, [str_x] * l)
res.append([str_x] * l)
for line in res:
line.insert(0, str_x)
line.append(str_x)
return '\n'.join(
''.join(row) for row in res
)
</code></pre>
<p>which creates strings like:</p>
<pre><code>>palindrome(1)
111
101
111
>palindrome(7)
777777777777777
766666666666667
765555555555567
765444444444567
765433333334567
765432222234567
765432111234567
765432101234567
765432111234567
765432222234567
765433333334567
765444444444567
765555555555567
766666666666667
777777777777777
</code></pre>
<p>Is there any way to improve the code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T14:39:23.357",
"Id": "384555",
"Score": "4",
"body": "The first step might be to document what this function wants to achieve? You have some outputs, but right _now_ I have to read the entire code to know what it is doing, since I c... | [
{
"body": "<p>So you have a lot of list manipulation, I believe you can reduce that to work with strings and use <a href=\"https://docs.python.org/2/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub</code></a> to fill in the gaps.</p>\n\n<p>Let's start by analyzing the answer:</p>\n\n<p>I see th... | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T14:35:44.413",
"Id": "199834",
"Score": "10",
"Tags": [
"python",
"palindrome",
"ascii-art"
],
"Title": "Circles of numbers"
} | 199834 |
<p>I've recently made a program which generates a (pseudo) random binary digit (1,0) which is tied to a specific subject to learn for every day of the week.</p>
<p>The program generates the digits the first time it's used, stores them in a file for later use and after that every Monday it generates them again. Currently I'm using only 2 subjects and the program has only one option (to view the current week subjects) but I <em>may</em> expand it in the future. </p>
<p>I'm putting it here so I can get a review of it, to understand where and what are my problems, how to fix them and what to do and how to do it for future projects.</p>
<pre><code>#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define FILE_DOESNT_EXIST_NUMBER 0
#define FILE_EXISTS_NUMBER 1
#define MAX_DIGITS_FOR_YEAR_NUMBER 4
#define MONDAY_NUMBER 1
#define NUMBER_OF_SUBJECTS 7
#define USER_CHOICE_VIEW '1'
#define USER_CHOICE_UNKNOWN '2'
#define YEAR_DAY_DIFFERENT 1
#define YEAR_DAY_SAME 0
char *year_day (struct tm *Date);
char user_input ();
int if_previously_saved_year_date (char yearDay[5]);
int if_rand_numbers_exist ();
int week_day (struct tm *Date);
struct DataInfo schedule_rand ();
struct WYDay date_retrieval ();
void date_and_nums_save (struct WYDay CurDay, int isFileCreated, int randBits[8]);
void program_start ();
void progress_view (int weekDayNumb);
void stdin_buffer_cleanup ();
void usr_choices (struct WYDay WeekYearDay, char usrChoice);
struct DataInfo
{
int subjNumb[8];
};
struct WYDay
{
int weekNumb;
char yearNumb[5];
};
int main ()
{
program_start();
return 0;
}
void program_start()
{
char usrOption;
int fileExistence;
int ifDiffYearDate;
struct DataInfo Data;
struct WYDay Days;
puts("This is the math and programming schedule check!\n"
"Would you like to see what you've done this week or add something?\n\n"
"1.See your progress!\n\n\n");
usrOption = user_input();
Days = date_retrieval();
fileExistence = if_rand_numbers_exist();
ifDiffYearDate = if_previously_saved_year_date(Days.yearNumb);
if((Days.weekNumb == MONDAY_NUMBER && ifDiffYearDate == YEAR_DAY_DIFFERENT) ||
fileExistence == FILE_DOESNT_EXIST_NUMBER)
{
Data = schedule_rand();
date_and_nums_save(Days, fileExistence, Data.subjNumb);
}
usr_choices(Days, usrOption);
// remove("RandomNumbers.txt");
// remove("DateOfFileCreation.txt");
}
char user_input()
{
char usrChoice;
do
{
usrChoice = getchar();
stdin_buffer_cleanup();
}while(usrChoice != USER_CHOICE_VIEW && usrChoice != USER_CHOICE_UNKNOWN);
return usrChoice;
}
void stdin_buffer_cleanup()
{
char ch;
while((ch = getchar()) != '\n' && ch != EOF);
}
struct WYDay date_retrieval()
{
char *yearDigit;
int iterat = 0;
time_t currentDate;
struct tm *Date;
struct WYDay Day;
time(&currentDate);
Date = localtime(&currentDate);
Day.weekNumb = week_day(Date);
yearDigit = year_day(Date);
for(iterat = 0; iterat < MAX_DIGITS_FOR_YEAR_NUMBER; iterat++)
{
Day.yearNumb[iterat] = yearDigit[iterat];
}
Day.yearNumb[MAX_DIGITS_FOR_YEAR_NUMBER] = '\0';
free(yearDigit);
return Day;
}
int week_day(struct tm *Date)
{
char numbOfWeekDay[2];
int weekDay;
strftime(numbOfWeekDay, 2, "%w", Date);
weekDay = numbOfWeekDay[0] - '0';
if(weekDay == '0')
{
weekDay = '7';
}
return weekDay;
}
char *year_day(struct tm *Date)
{
char *numbOfYearDay;
numbOfYearDay = calloc(MAX_DIGITS_FOR_YEAR_NUMBER, sizeof(char));
strftime(numbOfYearDay, MAX_DIGITS_FOR_YEAR_NUMBER, "%j", Date);
return numbOfYearDay;
}
int if_rand_numbers_exist()
{
int fileIsCreated;
FILE *fcheck;
fcheck = fopen("RandomNumbers.txt", "r");
if(fcheck == NULL)
{
fclose(fcheck);
fileIsCreated = FILE_DOESNT_EXIST_NUMBER;
return fileIsCreated;
}
else
{
fclose(fcheck);
fileIsCreated = FILE_EXISTS_NUMBER;
return fileIsCreated;
}
}
int if_previously_saved_year_date(char yearDay[5])
{
int diffYearDay;
int lastYearDay;
int yearDayInt;
FILE *ftest;
sscanf(yearDay, "%i", &yearDayInt);
ftest = fopen("DateOfFileCreation.txt", "r");
if(ftest == NULL)
{
fclose(ftest);
return diffYearDay = YEAR_DAY_DIFFERENT;
}
else
{
fclose(ftest);
fscanf(ftest, "%i", &lastYearDay);
}
if(lastYearDay == yearDayInt)
{
return diffYearDay = YEAR_DAY_SAME;
}
else
{
return diffYearDay = YEAR_DAY_DIFFERENT;
}
}
struct DataInfo schedule_rand()
{
const int BASE_VALUE = 10;
const int RAND_DIVIDE_FOR_REMAINDER = 2;
float maxNumFloat, minNumFloat;
int incr1 = 0;
int maxNumInt, minNumInt;
int randZeroAmount;
int randNumber;
struct DataInfo SubjInfo;
srand(time(NULL));
for(incr1 = 0; incr1 < NUMBER_OF_SUBJECTS; incr1++)
{
randZeroAmount = rand() %4 + 1;
maxNumFloat = pow(BASE_VALUE, randZeroAmount);
minNumFloat = pow(BASE_VALUE, randZeroAmount - 1);
maxNumInt = maxNumFloat;
minNumInt = minNumFloat;
randNumber = rand() %(maxNumInt - minNumInt) + minNumInt; /*No idea how this formula works!*/
SubjInfo.subjNumb[incr1] = randNumber %RAND_DIVIDE_FOR_REMAINDER;
// printf("Max numb of zeros:[%i]\n", randZeroAmount);
// printf("Min numb:(%i)\n", minNumInt);
// printf("Max numb:{%i}\n", maxNumInt);
// printf("Rand numb between min and max:%i\n\n", randNumber);
}
return SubjInfo;
}
void date_and_nums_save(struct WYDay CurDay, int isFileCreated, int randBits[8])
{
int fIterat = 0;
int lastTimeYearDay;
int yearNumbInt;
FILE *filep;
sscanf(CurDay.yearNumb, "%i", &yearNumbInt);
filep = fopen("DateOfFileCreation.txt", "r");
if(CurDay.weekNumb == MONDAY_NUMBER || (filep == NULL))
{
fclose(filep);
filep = fopen("DateOfFileCreation.txt", "w");
fprintf(filep, "%s", CurDay.yearNumb);
fclose(filep);
}
filep = fopen("DateOfFileCreation.txt", "r");
fscanf(filep, "%i", &lastTimeYearDay);
fclose(filep);
if((CurDay.weekNumb == MONDAY_NUMBER && yearNumbInt != lastTimeYearDay) ||
isFileCreated == FILE_DOESNT_EXIST_NUMBER)
{
filep = fopen("RandomNumbers.txt", "w");
for(fIterat = 0; fIterat < NUMBER_OF_SUBJECTS; fIterat++)
{
fprintf(filep, "%i\n", randBits[fIterat]);
}
fclose(filep);
}
}
void usr_choices(struct WYDay WeekYearDay, char usrChoice)
{
if(usrChoice == USER_CHOICE_VIEW)
{
progress_view(WeekYearDay.weekNumb);
}
}
void progress_view(int weekDayNumb)
{
char subjectNumb;
const char CURRENT_DAY_SUBJECT_CHARACTER[] = "<--";
const char NUMB_ONE_SUBJ[] = "Programming";
const char NUMB_ZERO_SUBJ[] = "Mathematics";
const char REMAINDER_ONE = '1';
const char REMAINDER_ZERO = '0';
int subjectIterator = 0;
FILE *fview;
fview = fopen("RandomNumbers.txt", "r");
while(subjectIterator < NUMBER_OF_SUBJECTS)
{
subjectNumb = fgetc(fview);
if(subjectNumb == '\n')
{
continue;
}
else if(feof(fview))
{
break;
}
else
{
if(subjectNumb == REMAINDER_ZERO)
{
printf("\n%s", NUMB_ZERO_SUBJ);
subjectIterator++;
}
else if(subjectNumb == REMAINDER_ONE)
{
printf("\n%s", NUMB_ONE_SUBJ);
subjectIterator++;
}
else
{
printf("Unrecognized subject");
}
if(subjectIterator == weekDayNumb)
{
printf(" %s", CURRENT_DAY_SUBJECT_CHARACTER);
}
}
}
fclose(fview);
}
</code></pre>
| [] | [
{
"body": "<p>I think that you've got some decent stuff here. You've made <code>struct</code>s for a variety of data types you use, which is helpful for understanding the code. You've broken things into functions, which is good, too. Here are some things you could do to improve it.</p>\n<h1>Use Typed <code>cons... | {
"AcceptedAnswerId": "199886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-19T14:57:06.370",
"Id": "199836",
"Score": "2",
"Tags": [
"c",
"datetime",
"random",
"file"
],
"Title": "Random binary digit generation and file I/O"
} | 199836 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.