body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I'm working on a product category page where the product images have inconsistent heights so I've been asked to improve the page appearance without changing the images.</p>
<p>The page contains x number of products in a 3 column grid.</p>
<p>I decided to set the height of the image wrapper to the height of the image with the maximum height in each row, then use flex to vertically center the images.</p>
<p>How could I improve my JavaScript?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
* Ensure all rows appear the same height even if they contain products with
* small images.
*/
const imgWrappers = Array.from(document.querySelectorAll('.summary-image-wrapper'));
const rows = [];
// 3 Products per row - First group the image wrappers into groups of 3
while (imgWrappers.length !== 0) {
rows.push({
elements: imgWrappers.splice(0, 3),
});
}
// Then establish which element is the tallest in it's group
rows.forEach((row) => {
let height = 0;
row.elements.forEach((el) => {
const currHeight = el.firstElementChild.getAttribute('height');
height = currHeight > height ? currHeight : height;
});
row.height = height;
// Set the height of each element to that of the tallest element in the row
row.elements.forEach((el) => {
el.style.height = `${row.height}px`;
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="row">
<div class="col-6 col-md-4">
<div class="summary-product">
<a href="http://examplelink.com/" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">
<div class="summary-image-wrapper" style="height: 413px;">
<img width="300" height="413" src="http://via.placeholder.com/300x413" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail wp-post-image" alt="alt ttext" srcset="http://via.placeholder.com/300x413 300w, http://via.placeholder.com/218x300 218w, http://via.placeholder.com/350x482 350w, http://via.placeholder.com/581x800 581w" sizes="(max-width: 300px) 100vw, 300px">
</div>
<h2 class="woocommerce-loop-product__title summary-product-title">Example title</h2>
<span class="price summary-product-price">POA</span>
</a>
</div>
<!-- Further .summary-products have been omitted for brevity-->
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>EDIT:
I discovered an error within my original code due to string comparison. Take the following row of 3 images and their height:</p>
<p>Image a: 365</p>
<p>Image b: 91</p>
<p>Image c: 401</p>
<p>Given the above images using the code originally given 'image b' will be considered the largest. This is because <code>el.firstElementChild.getAttribute('height')</code> returns a string, when comparing strings javascript does it "alphabetically". This means that js looks at the first character of the string then the second and so on. When comparing two numberic strings if a string starts with a 9 it will always be the largest!</p>
<pre><code>'10000000000' > '9' //false
'89999999999' > '9' //false
'91' > '9' //true
</code></pre>
<p>To ensure the original code works the value stored in currHeight needs to be converted to a number e.g <code>currHeight = Number.parseInt(el.firstElementChild.getAttribute('height'));</code> before comparison.</p>
| [] | [
{
"body": "<h1>Keep it simple</h1>\n<p>Your algorithm is too complex, with too many iterations and uses too much memory. It can be simplified using only a single outer iteration to get a row, and the row's max height. Then an inner loop to set the new height values. (see rewrite)</p>\n<p>Some points</p>\n<ul>\n... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T16:33:34.150",
"Id": "200917",
"Score": "4",
"Tags": [
"javascript",
"css",
"ecmascript-6",
"dom",
"layout"
],
"Title": "Breaking group of items into rows then ensure consistent height of each row element"
} | 200917 |
<p>I want to use Python and Matplotlib to create a data set of images. I want to do this by transforming the plot to a numpy matrix. At the moment it takes about 0.1 second to generate 100 images of size 50x50 pixels:</p>
<p><a href="https://i.stack.imgur.com/UWxyW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UWxyW.png" alt="enter image description here"></a></p>
<p>Question: How can I speed up things a lot?</p>
<p>This is my code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import time
import cv2
fig = plt.figure(frameon=False)
ax = fig.add_axes([0., 0., 1., 1.])
fig.set_size_inches((0.5,0.5))
fig_size = fig.canvas.get_width_height() + (3,)
points, = ax.plot([],[])
ax.set_xlim(0.,1.)
ax.set_ylim(0.,1.)
ax.set_axis_off()
ax.set_frame_on(False)
ax.grid(False)
def plot2mat():
data = np.random.rand(20,2)
points.set_xdata(data[:,0])
points.set_ydata(data[:,1])
fig.canvas.draw()
fig.canvas.flush_events()
M = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
M = M.reshape(fig_size)
M = cv2.cvtColor(M, cv2.COLOR_BGR2GRAY)
return M
I = []
t0 = time.time()
runs = 1000
for k in range(runs):
I.append(plot2mat())
print(time.time()-t0)
plt.close(fig)
for k in range(100):
plt.subplot(10,10,k+1)
plt.imshow(I[k])
plt.axis("off")
plt.savefig("plot.png", dpi=400)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T17:39:42.537",
"Id": "386997",
"Score": "0",
"body": "An execution time of 0.1 second is not much. Do you want to scale this up by much that you're concerned about speed? What's your goal?"
},
{
"ContentLicense": "CC BY-SA 4... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T17:28:13.067",
"Id": "200920",
"Score": "3",
"Tags": [
"python",
"performance",
"numpy",
"matplotlib",
"opencv"
],
"Title": "Data set generation with Python and Matplotlib"
} | 200920 |
<blockquote>
<p>Write a program to sort an array of 0's,1's and 2's in ascending
order.</p>
<p><strong>Input:</strong></p>
<p>The first line contains an integer 'T' denoting the total number of
test cases. In each test cases, First line is number of elements in
array 'N' and second its values.</p>
<p><strong>Output:</strong> </p>
<p>Print the sorted array of 0's, 1's and 2's.</p>
<p><strong>Constraints:</strong> </p>
<ul>
<li>1 <= T <= 100 </li>
<li>1 <= N <= 105</li>
<li>0 <= arr[i] <= 2</li>
</ul>
<p><strong>Example:</strong></p>
<p><strong>Input :</strong></p>
<pre><code>2
5
0 2 1 2 0
3
0 1 0
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>0 0 1 2 2
0 0 1
</code></pre>
</blockquote>
<p>My approach:</p>
<pre><code>import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class GFG {
private static void printSortedArr (int[] arr) {
int count0 = 0, count1 = 0, count2 = 0;
for (Integer elem : arr) {
if (elem == 0) {
count0++;
}
else if (elem == 1) {
count1++;
}
else {
count2++;
}
}
while (count0 != 0) {
System.out.print(0 + " ");
count0--;
}
while (count1 != 0) {
System.out.print(1 + " ");
count1--;
}
while (count2 != 0) {
System.out.print(2 + " ");
count2--;
}
System.out.println();
}
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int numTests = Integer.parseInt(line);
for (int i = 0; i < numTests; i++) {
String line2 = br.readLine();
int size = Integer.parseInt(line2);
int[] arr = new int[size];
String line3 = br.readLine();
String[] inps = line3.split(" ");
for (int j = 0; j < size; j++) {
arr[j] = Integer.parseInt(inps[j]);
}
printSortedArr(arr);
}
}
}
</code></pre>
<p>I have the following questions with regards to the above code:</p>
<ol>
<li><p>How can I further improve my approach?</p></li>
<li><p>Is there a better way to solve this question?</p></li>
<li><p>Are there any grave code violations that I have committed?</p></li>
<li><p>Can space and time complexity be further improved? </p></li>
</ol>
<p><a href="https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0/?track=Placement" rel="noreferrer">Reference</a></p>
| [] | [
{
"body": "<p>That's the correct approach, and so I don't think time or space complexity can be improved significantly. </p>\n\n<p>However, you could improve the re-usability of the function by using an array to store the counts, rather than individual variables.</p>\n\n<pre><code>private static void printSort... | {
"AcceptedAnswerId": "200974",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T17:37:56.527",
"Id": "200922",
"Score": "6",
"Tags": [
"java",
"beginner",
"sorting",
"interview-questions",
"complexity"
],
"Title": "Sort an array of 0s, 1s and 2s in Java"
} | 200922 |
<p>This is a very simple concern, could somebody take a look at a few lines of my code? I'm writing a simple Java multi-user messenger, it is structured in a desktop client with a Swing GUI, a java server based on plain sockets and a service library holding general utilities... At the moment I transmit messages through a <code>ObjectOutputStream</code>/<code>ObjectInputStream</code> with a custom <code>Packet</code> class...</p>
<pre><code>package org.x1c1b.carrierpigeon.service.packet;
import java.io.Serializable;
import java.util.Objects;
public class Packet implements Serializable
{
protected String source;
protected String destination;
protected int type;
protected String payload;
public Packet(String source, String destination, PacketType type, String payload)
{
this.source = source;
this.destination = destination;
this.type = type.getIdentifier();
this.payload = payload;
}
public Packet(Packet packet)
{
this.source = packet.source;
this.destination = packet.destination;
this.type = packet.type;
this.payload = packet.payload;
}
protected Packet(PacketBuilder builer)
{
this.source = builer.source;
this.destination = builer.destination;
this.type = builer.type;
this.payload = builer.payload;
}
public String getSource()
{
return this.source;
}
public String getDestination()
{
return this.destination;
}
public PacketType getType()
{
return PacketType.getByIdentifier(this.type);
}
public String getPayload()
{
return this.payload;
}
@Override public boolean equals(Object object)
{
if(this == object)
{
return true;
}
if(object == null || getClass() != object.getClass())
{
return false;
}
Packet packet = (Packet) object;
return type == packet.type && Objects.equals(source, packet.source) && Objects
.equals(destination, packet.destination) && Objects.equals(payload, packet.payload);
}
@Override public int hashCode()
{
return Objects.hash(this.source, this.destination, this.type, this.payload);
}
}
</code></pre>
<p>This is the <code>Packet</code> class used to transmit the message, for identifying the message purpose I uses a Enum defining different <code>PacketType</code>'s...</p>
<pre><code>package org.x1c1b.carrierpigeon.service.packet;
import java.util.NoSuchElementException;
public enum PacketType
{
HANDSHAKE_REQUEST(1),
HANDSHAKE_REPLY(2),
HANDSHAKE_ERROR(3),
AUTHENTICATION_REQUEST(4),
AUTHENTICATION_REPLY(5),
AUTHENTICATION_ERROR(6),
CONNECTIVITY_ESTABLISHED(7),
CONNECTIVITY_HALTED(8),
CONNECTIVITY_STATUS(9),
CONNECTIVITY_SETUP(10),
CONNECTIVITY_ERROR(11),
DATA_TRANSFER(12),
DATA_TRANSFER_ERROR(13);
private int identifier;
private PacketType(int identifier)
{
this.identifier = identifier;
}
public int getIdentifier()
{
return this.identifier;
}
public static PacketType getByIdentifier(int identifier)
{
for(PacketType type : PacketType.values())
{
if(type.identifier == identifier)
{
return type;
}
}
throw new NoSuchElementException("Identifier: " + identifier);
}
}
</code></pre>
<p>Maybe for taking a look at the whole project:</p>
<ul>
<li><a href="https://github.com/0x1C1B/CarrierPigeon-Service" rel="nofollow noreferrer">Service Library</a> Containing basic API and Packet implementations</li>
<li><a href="https://github.com/0x1C1B/CarrierPigeon-Server" rel="nofollow noreferrer">Server</a></li>
<li><a href="https://github.com/0x1C1B/CarrierPigeon-Desktop" rel="nofollow noreferrer">Desktop Client</a></li>
</ul>
<p>I'm not that much expired in network development with java, so are there any improvements by transmission of messages? Is it common practice to use <code>ObjectStream</code>'s with a custom "Protocol"/Packet to transmit data or should I use already existing protocols like <code>HTTP</code> instead? I tried to hold it simple without REST or huge webservers...</p>
<p><em>I will be glad about any improvements or tips for the data transmission...</em></p>
<p><strong>EDIT</strong></p>
<p>I also anticipate to write a basic API with the <code>Remote Procedure Call</code> pattern, here a basic example to illustrate what I mean:</p>
<pre><code>public interface MessengerServiceAPI
{
public abstract boolean login(String name);
}
</code></pre>
<p>Here the server-side implementation of the service API:</p>
<pre><code>public class MessengerService implements MessengerServiceAPI
{
@Override public boolean login(String name)
{
// Some login logic and database interaction on server-side
}
}
</code></pre>
<p>Now I superior to call this server-side method with RPC through a <code>ObjectStream</code>:</p>
<pre><code>// Method used on client-side to call remote method of service API
public Object call(String name, Object [] params) throws Exception
{
try(Socket socket = new Socket(this.address, this.port);
ObjectOutputStream sout = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream sin = new ObjectInputStream(socket.getInputStream()))
{
sout.writeObject(name);
sout.writeObject(params);
sout.flush();
Object object = sin.readObject();
if(object instanceof Exception)
{
throw (Exception) object;
}
return object;
}
}
// The server-side handler to handle API requests, which execute the requested action on server-side and return the return value of it
@Override public void handle(Socket socket)
{
try (ObjectInputStream sin = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream sout = new ObjectOutputStream(socket.getOutputStream()))
{
Object object;
String name = (String) sin.readObject();
Object [] params = (Object[]) sin.readObject();
try
{
Class <?> [] paramTypes = null;
if(null != params)
{
types = new Class[params.length];
for(int index = 0; index < params.length; ++index)
{
paramTypes[index] = params[index].getClass();
}
}
Method method = this.service.getClass().getMethod(name, paramTypes);
object = method.invoke(this.service, params);
}
catch(InvocationTargetException exc)
{
object = exc.getTargetException();
}
catch(Exception exc)
{
object = exc;
}
sout.writeObject(object);
sout.flush();
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
</code></pre>
<p>This is one possible implementation of such a service handling, but is it recommended to write such a basic API and service? Or is it recommended to send a string or packet instead with a identifier and the server executes the action by parsing this identifier?</p>
<p><strong><em>Sorry because it is also in big parts software design not just code review but I'm waiting for somebody who takes a look on my code to give tips or improvements...</em></strong></p>
| [] | [
{
"body": "<blockquote>\n <p>Is it common practice to use ObjectStream's with a custom \"Protocol\"/Packet to transmit data or should I use already existing protocols like HTTP instead?</p>\n</blockquote>\n\n<p>I am not en expert and would say that it depends of your needs. However if you want to have other cl... | {
"AcceptedAnswerId": "201056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T18:56:14.103",
"Id": "200927",
"Score": "3",
"Tags": [
"java",
"api",
"networking",
"socket",
"web-services"
],
"Title": "Java Messenger data transmission"
} | 200927 |
<p>Given the CSV data:</p>
<pre><code>,fan1,fan2,foil1,foil2
0,0.0,0.0,0.0,0.125
1,0.0625,0.0,0.0625,0.125
2,0.0625,0.0,0.0,0.3125
</code></pre>
<p>Which I want to turn into a kind of annotated pivot-table which can be plotted as a bar-plot:</p>
<pre><code>,Err,PairType,StimType
0,0.0,Target,1
1,0.0625,Target,1
2,0.0625,Target,1
0,0.0,Target,2
1,0.0,Target,2
2,0.0,Target,2
0,0.0,RPFoil,1
1,0.0625,RPFoil,1
2,0.0,RPFoil,1
0,0.125,RPFoil,2
1,0.125,RPFoil,2
2,0.3125,RPFoil,2
</code></pre>
<p>I currently accomplish this with the following code:</p>
<pre><code>import numpy as np
import pandas as pd
def df_plotable(model_err: pd.DataFrame):
t_len = len(model_err.fan1)
cols = ("Err", "PairType", "StimType")
fan1_df = pd.DataFrame(np.array([model_err.fan1, ["Fan"]*t_len, [1]*t_len]).T,
columns=cols)
fan2_df = pd.DataFrame(np.array([model_err.fan2, ["Fan"]*t_len, [2]*t_len]).T,
columns=cols)
foil1_df = pd.DataFrame(np.array([model_err.foil1, ["Foil"]*t_len, [1]*t_len]).T,
columns=cols)
foil2_df = pd.DataFrame(np.array([model_err.foil2, ["Foil"]*t_len, [2]*t_len]).T,
columns=cols)
new_model_err = pd.concat((fan1_df, fan2_df, foil1_df, foil2_df))
new_model_err["Err"] = new_model_err["Err"].astype(float)
new_model_err["StimType"] = new_model_err["StimType"].astype(int)
return new_model_err
</code></pre>
<p>Such that:</p>
<pre><code>df = pd.read_csv("in.csv", "r", delimiter=",", index_col=0)
df_plotable(df).to_csv("out.csv")
</code></pre>
<p>Is there a way to do this more cleanly?</p>
| [] | [
{
"body": "<h3>Don't hard-code your transformation</h3>\n\n<p>With your current approach, as soon as you are faced with a new PairType or StimType you will have to adjust your function accordingly to account for them. What your current code is doing is really a hard-coded version of a wide-form to long-form con... | {
"AcceptedAnswerId": "200967",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T19:18:46.757",
"Id": "200928",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "Pivot and annotate Pandas DataFrame"
} | 200928 |
<p>I don't get to write multithreaded applications very often, so be gentle with my threads :-)</p>
<p>I have an API input which contains a "score" and then a bunch of child nodes which also have scores, and perhaps child nodes of their own. I need to quickly sum up the total score of the entire tree.</p>
<p>I've elected a newWorkStealingPool as I have read that this is a good implementation for applications where workers may spawn other workers.</p>
<p>My handler is awfully static. I don't always work in Java, but this felt like the appropriate solution. Correct if wrong? :-)</p>
<p>I <em>think</em> I've made thread safe the methods that could be troublesome. I'd obviously like to remove the synchronization from methods that maybe don't need it.</p>
<p>I'm <strong>very</strong> concerned about how I monitor the running threads to decide when my work is done. I think there is a race condition here that I am having trouble understanding, even if for now, this project works.</p>
<p>Don't worry too much about my throwing an Exception, please :-). It's just for now so as to not clutter up the other code.</p>
<p>Thank you!!</p>
<p>Oh! Java 8 is pretty new to me, too. I only just considered where I could use some new functionality.</p>
<p>Runner</p>
<pre><code>import java.net.URL;
public class Runner {
public static void main(String[] args) throws Exception {
try{
NodeHandler.addNode(new Node(new URL(args[0])));
}catch(java.net.MalformedURLException e){
System.out.println("Malformed URL Exception: " + e.getMessage());
}
System.out.println(Double.toString(NodeHandler.getTotal()));
}
}
</code></pre>
<p>Node Handler</p>
<pre><code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class NodeHandler {
private static int runningThreads = 0;
private static double rewardsTotal = 0;
private static ExecutorService es = Executors.newWorkStealingPool();
public static synchronized void addNode(Node node) {
es.execute(node);
}
public static synchronized void incrementThreadCount() {
runningThreads++;
}
public static synchronized void decrementThreadCount() {
runningThreads--;
}
public static synchronized void updateScore(double score){
scoreTotal += score;
}
public static int getRunningThreads() {
return runningThreads;
}
public static double getTotal(){
while(getRunningThreads() > 0){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return scoreTotal;
}
}
</code></pre>
<p>Node</p>
<pre><code>import java.util.*;
import java.net.URL;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Node implements Runnable{
private URL url;
private StringBuilder rawJson = new StringBuilder();
Node(URL url){
NodeHandler.incrementThreadCount();
this.url = url;
}
private void processNode() throws Exception{
Scanner sc = new Scanner(url.openStream());
while (sc.hasNext()) {
rawJson.append(sc.nextLine());
}
sc.close();
JSONParser jParser = new JSONParser();
JSONObject jObj = (JSONObject) jParser.parse(rawJson.toString());
JSONArray children = (JSONArray) jObj.get("children");
NodeHandler.updateScore(Double.parseDouble(jObj.get("score").toString()));
if (children != null && children.size() > 0) {
for (Object o : children) {
URL url = new URL(o.toString());
NodeHandler.addNode(new Node(url));
}
}
NodeHandler.decrementThreadCount();
}
@Override
public void run(){
try {
processNode();
}catch(Exception e){
e.printStackTrace();
}
}
}
</code></pre>
| [] | [
{
"body": "<p>A few things that I noticed, not necessarily in order:</p>\n\n<ul>\n<li><p>The globally locked and secured <code>total</code> is an unnecessary bottleneck. The aggregation you're performing is really well-suited for subresult aggregation. Instead of <code>updateScore</code> which can only ever be ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T19:40:45.787",
"Id": "200929",
"Score": "3",
"Tags": [
"java",
"multithreading",
"api",
"thread-safety",
"concurrency"
],
"Title": "Java Concurrent Recursive API Access"
} | 200929 |
<p>The program is written mainly for the status bar in dwm (a window manager for Linux), but it can be used for any manager that takes input from the root window in X. It queries different resources in the computer and displays the formatted information in the status bar.</p>
<p>This is a full, tested, ready-and-waiting program. Here is the main repository for the code: <a href="https://github.com/snhilde/dwm-statusbar/tree/c55bc81d513379f2da0d97da54887147b226d0a7" rel="nofollow noreferrer">dwm-statusbar</a></p>
<p>I am looking for others to review my code and give me any and all feedback. This project is open so that I can learn how to be a better developer and hopefully others can learn along with me.</p>
<p>I could not add the README due to character constraints. The file explains the different macros and functions and helps to localize the program to your system, if you choose to actually run it and play with it. You can view the README on the GitHub page.</p>
<h1>dwm-statusbar.h:</h1>
<pre><code>#include <sys/stat.h>
#include <fcntl.h>
#include <libgen.h>
// X11
#include <X11/Xlib.h>
// weather
#include <curl/curl.h>
#include <cJSON/cJSON.h>
// wifi
#include <net/if.h>
#include <netlink/genl/genl.h>
#include <netlink/genl/ctrl.h>
#include <linux/nl80211.h>
#include <libnetlink.h>
#include <linux/if_arp.h>
#include <ctype.h>
#include <stdbool.h>
// disk usage
#include <sys/statvfs.h>
// memory
#include <proc/sysinfo.h>
// volume
#include <alsa/asoundlib.h>
#include <math.h>
#define COLOR_NORMAL color1
#define COLOR_ACTIVE color2
#define COLOR1 color3
#define COLOR2 color4
#define COLOR_WARNING color5
#define COLOR_ERROR color6
#define GREEN_TEXT color7
#define RED_TEXT color8
#define COLOR_HEADING COLOR_ACTIVE
#define TODO_MAX_LEN 100
#define WIFI_INTERFACE "wlp4s0"
#define DISPLAY_KBD true
#define TODO_FILE "/home/user/.TODO"
#define STATUSBAR_LOG_FILE "/home/user/.logs/dwm-statusbar.log"
#define DWM_LOG_FILE "/home/user/.logs/dwm.log"
#define BACKUP_STATUS_FILE "/home/user/.backup/.sb"
#define LOCATION "0000000"
#define KEY "00000000000000000000000000000000"
#define RH_LOGIN "username={username}&password={password}
#define DWM_CONFIG_FILE "/home/user/.dwm/config.h"
#define NET_RX_FILE NET_CAT(WIFI_INTERFACE, rx)
#define NET_TX_FILE NET_CAT(WIFI_INTERFACE, tx)
#define CPU_USAGE_FILE "/proc/stat"
#define CPU_TEMP_DIR "/sys/class/hwmon/hwmon0/"
#define FAN_SPEED_FILE "/sys/class/hwmon/hwmon2/device/fan1_input"
#define SCREEN_BRIGHTNESS_FILE "/sys/class/backlight/nvidia_backlight/brightness"
#define KBD_BRIGHTNESS_FILE "/sys/class/leds/smc::kbd_backlight/brightness"
#define BATT_STATUS_FILE "/sys/class/power_supply/BAT0/status"
#define BATT_CAPACITY_FILE "/sys/class/power_supply/BAT0/capacity"
#define ERR(str, val) \
{ snprintf(str, sizeof(str) - 1, "%c %s%c ", COLOR_ERROR, val, COLOR_NORMAL); \
str[sizeof(str) - 1] = '\0'; \
fprintf(stderr, "%s\t%s\n\n", asctime(tm_struct), val); \
return -1; }
#define INIT_ERR(val) \
{ fprintf(stderr, "%s\t%s\n", asctime(tm_struct), val); \
perror("\tError"); \
printf("\n"); \
return -1; }
#define SND_ERR(val) \
{ snd_mixer_close(handle); \
handle = NULL; \
snd_config_update_free_global(); \
snprintf(volume_string, sizeof(volume_string) - 1, "%c %s%c ", COLOR_ERROR, val, COLOR_NORMAL); \
volume_string[sizeof(volume_string) - 1] = '\0'; \
fprintf(stderr, "%s%s\n\n", asctime(tm_struct), val); \
return -1; }
#define SND_INIT_ERR(val) \
{ snd_mixer_close(handle); \
handle = NULL; \
snd_config_update_free_global(); \
fprintf(stderr, "%s%s\n", asctime(tm_struct), val); \
perror("Error"); \
printf("\n"); \
return -1; }
#define CAT_5(A, B, C, D, E) #A B #C #D #E
#define NET_CAT(X, Y) CAT_5(/sys/class/net/, X, /statistics/, Y, _bytes)
struct json_struct {
char *data;
int size;
};
struct disk_usage_struct {
struct statvfs fs_stat;
float bytes_used;
float bytes_total;
char unit_used;
char unit_total;
} root_fs;
struct cpu_temp_list {
char *filename;
struct cpu_temp_list *next;
} *temp_list = NULL;
const char color1 = '';
const char color2 = '';
const char color3 = '';
const char color4 = '';
const char color5 = '';
const char color6 = '';
const char color7 = '';
const char color8 = '';
long TODO_mtime = 0;
char weather_url[128];
char forecast_url[128];
int day_safe; // due to cJSON's not being thread-safe
int temp_today;
bool weather_update = true;
long backup_mtime = 0;
bool equity_found = false;
bool portfolio_init = false;
char portfolio_url[128];
char token_header[64];
char account_number[32];
float equity_previous_close = 0.0;
struct curl_slist *headers = NULL;
bool wifi_connected = false;
int devidx;
struct tm *tm_struct = NULL;
int block_size;
int cpu_ratio;
int temp_max;
int fan_min;
int fan_max;
int screen_brightness_max;
int kbd_brightness_max;
float vol_range;
char statusbar_string[1024];
char top_bar[512];
char bottom_bar[512];
int bar_max_len;
char TODO_string[128];
char log_status_string[32];
char weather_string[96];
char backup_status_string[32];
char portfolio_value_string[32];
char wifi_status_string[32];
char time_string[32];
char network_usage_string[64];
char disk_usage_string[64];
char memory_string[32];
char cpu_load_string[32];
char cpu_usage_string[32];
char cpu_temp_string[32];
char fan_speed_string[32];
char brightness_string[32];
char volume_string[32];
char battery_string[32];
</code></pre>
<h1>dwm-statusbar.c:</h1>
<pre><code>#include "dwm-statusbar.h"
static void
center_bottom_bar(char *bottom_bar)
{
if (strlen(bottom_bar) < bar_max_len) {
int half = (bar_max_len - strlen(bottom_bar)) / 2;
memmove(bottom_bar + half, bottom_bar, strlen(bottom_bar));
for (int i = 0; i < half; i++)
bottom_bar[i] = ' ';
}
}
static int
format_string(Display *dpy, Window root)
{
memset(statusbar_string, '\0', 1024);
memset(top_bar, '\0', 512);
memset(bottom_bar, '\0', 512);
strcat(top_bar, TODO_string);
strcat(top_bar, log_status_string);
strcat(top_bar, weather_string);
strcat(top_bar, backup_status_string);
strcat(top_bar, portfolio_value_string);
strcat(top_bar, wifi_status_string);
strcat(top_bar, time_string);
strcat(bottom_bar, network_usage_string);
strcat(bottom_bar, disk_usage_string);
strcat(bottom_bar, memory_string);
strcat(bottom_bar, cpu_load_string);
strcat(bottom_bar, cpu_usage_string);
strcat(bottom_bar, cpu_temp_string);
strcat(bottom_bar, fan_speed_string);
strcat(bottom_bar, brightness_string);
strcat(bottom_bar, volume_string);
strcat(bottom_bar, battery_string);
center_bottom_bar(bottom_bar);
sprintf(statusbar_string, "%s;%s", top_bar, bottom_bar);
if (!XStoreName(dpy, root, statusbar_string))
return -1;
if (!XFlush(dpy))
return -1;
return 0;
}
static int
get_TODO(void)
{
// dumb function
struct stat file_stat;
if (stat(TODO_FILE, &file_stat) < 0)
ERR(TODO_string, "Error Getting TODO File Stats")
if (file_stat.st_mtime <= TODO_mtime)
return 0;
TODO_mtime = file_stat.st_mtime;
FILE *fd;
char line[128];
if (!memset(TODO_string, '\0', 128))
ERR(TODO_string, "Error resetting TODO_string")
fd = fopen(TODO_FILE, "r");
if (!fd)
ERR(TODO_string, "Error Opening TODO File")
// line 1
if (fgets(line, 128, fd) == NULL)
ERR(TODO_string, "All tasks completed!")
line[strlen(line) - 1] = '\0'; // remove weird characters at end
snprintf(TODO_string, 128, "%cTODO:%c%s",
COLOR_HEADING, COLOR_NORMAL, line);
// lines 2 and 3
for (int i = 0; i < 2; i++) {
memset(line, '\0', 128);
if (fgets(line, 128, fd) == NULL) break;
line[strlen(line) - 1] = '\0'; // remove weird characters at end
switch (line[i]) {
case '\0': break;
case '\n': break;
case '\t':
memmove(line, line + i + 1, strlen(line));
strncat(TODO_string, " -> ", sizeof TODO_string - strlen(TODO_string));
strncat(TODO_string, line, sizeof TODO_string - strlen(TODO_string));
break;
default:
if (i == 1) break;
strncat(TODO_string, " | ", sizeof TODO_string - strlen(TODO_string));
strncat(TODO_string, line, sizeof TODO_string - strlen(TODO_string));
break;
}
}
memset(TODO_string + TODO_MAX_LEN - 3, '.', 3);
TODO_string[TODO_MAX_LEN] = '\0';
if (fclose(fd))
ERR(TODO_string, "Error Closing File")
return 0;
}
static int
get_log_status(void)
{
struct stat sb_stat;
struct stat dwm_stat;
if (stat(STATUSBAR_LOG_FILE, &sb_stat) < 0)
ERR(log_status_string, "dwm-statusbar.log error")
if (stat(DWM_LOG_FILE, &dwm_stat) < 0)
ERR(log_status_string, "dwm.log error")
if ((intmax_t)sb_stat.st_size > 1)
sprintf(log_status_string, "%c Check SB Log%c ",
COLOR_ERROR, COLOR_NORMAL);
else if ((intmax_t)dwm_stat.st_size > 1)
sprintf(log_status_string, "%c Check DWM Log%c ",
COLOR_ERROR, COLOR_NORMAL);
else
if (!memset(log_status_string, '\0', 32))
ERR(log_status_string, "error resetting log_status_string")
return 0;
}
static int
get_index(cJSON *time_obj)
{
const time_t time = time_obj->valueint;
struct tm *ft_struct = localtime(&time);
const int ft_day_of_week = ft_struct->tm_wday;
int day = ft_day_of_week - day_safe;
if (day < 0)
day += 7;
return day;
}
static int
parse_forecast_json(char *raw_json)
{
// for 5-day forecast (sent as 3-hour intervals for 5 days)
// only able to handle rain currently
cJSON *parsed_json = cJSON_Parse(raw_json);
cJSON *list_array, *list_child;
cJSON *main_dict, *temp_obj;
cJSON *rain_dict, *rain_obj;
int i;
char forecast_string[32], tmp_str[16];
if (!memset(forecast_string, '\0', 32))
return -1;
struct data {
int high;
int low;
float precipitation;
} data[5];
const char days_of_week[10][4] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed" };
for (i = 0; i < 5; i++) {
if (!i) {
data[i].high = temp_today;
data[i].low = temp_today;
} else {
// god help us all if these values don't work
data[i].high = -1000;
data[i].low = 1000;
}
data[i].precipitation = 0.0;
}
list_array = cJSON_GetObjectItem(parsed_json, "list");
if (!list_array)
ERR(weather_string, "Error finding 'list' in forecast")
cJSON_ArrayForEach(list_child, list_array) {
int f_day = get_index(cJSON_GetObjectItem(list_child, "dt"));
if (f_day > 3)
break;
main_dict = cJSON_GetObjectItem(list_child, "main");
if (!main_dict)
ERR(weather_string, "Error finding 'main_dict' in forecast")
temp_obj = cJSON_GetObjectItem(main_dict, "temp");
if (!temp_obj)
ERR(weather_string, "Error finding 'temp_obj' in forecast")
data[f_day].high = (int)fmax(data[f_day].high, temp_obj->valueint);
data[f_day].low = (int)fmin(data[f_day].low, temp_obj->valueint);
if (rain_dict = cJSON_GetObjectItem(list_child, "rain"))
if (rain_obj = rain_dict->child)
data[f_day].precipitation += rain_obj->valuedouble;
}
for (i = 0; i < 4; i++) {
snprintf(tmp_str, 16, "%c %s(%2d/%2d)",
data[i].precipitation >= 3 ? COLOR_WARNING : COLOR_NORMAL,
i > 0 ? days_of_week[day_safe + i - 1] : "",
data[i].high, data[i].low);
strncat(weather_string, tmp_str, sizeof weather_string - strlen(weather_string) - 1);
}
cJSON_Delete(parsed_json);
return 0;
}
static int
parse_weather_json(char *raw_json)
{
// for current weather
// only able to handle rain currently (winter is not coming)
// if (id >= 200 && id < 300)
// Stormy
// else if (id >= 300 && id < 400)
// Drizzly
// else if (id >= 500 && id < 600)
// Rainy
// else if (id >= 700 && id < 800)
// Low visibility
// else if (id == 800)
// Clear
// else if (id > 800 && id < 900)
// Cloudy
cJSON *parsed_json = cJSON_Parse(raw_json);
cJSON *main_dict, *temp_obj;
cJSON *weather_dict;
int id;
main_dict = cJSON_GetObjectItem(parsed_json, "main");
if (!main_dict)
ERR(weather_string, "Error finding 'main' in weather")
temp_obj = cJSON_GetObjectItem(main_dict, "temp");
if (!temp_obj)
ERR(weather_string, "Error finding 'temp' in weather")
temp_today = temp_obj->valueint;
weather_dict = cJSON_GetObjectItem(parsed_json, "weather");
if (!weather_dict)
ERR(weather_string, "Error finding 'weather' in weather")
weather_dict = weather_dict->child;
if (!weather_dict)
ERR(weather_string, "Error finding 'weather' in weather")
id = cJSON_GetObjectItem(weather_dict, "id")->valueint;
if (!id)
ERR(weather_string, "Error getting id from weather")
snprintf(weather_string, 96, " %c weather:%c%2d F",
id < 800 ? COLOR_WARNING : COLOR_HEADING,
id < 800 ? COLOR_WARNING : COLOR_NORMAL,
temp_today);
cJSON_Delete(parsed_json);
return 0;
}
static size_t
curl_callback(char *weather_json, size_t size, size_t nmemb, void *userdata)
{
const size_t received_size = size * nmemb;
struct json_struct *tmp;
tmp = (struct json_struct *)userdata;
tmp->data = realloc(tmp->data, tmp->size + received_size + 1);
if (!tmp->data)
return -1;
memcpy(&(tmp->data[tmp->size]), weather_json, received_size);
tmp->size += received_size;
tmp->data[tmp->size] = '\0';
return received_size;
}
static int
get_weather(void)
{
if (!memset(weather_string, '\0', 96))
ERR(weather_string, "Error resetting weather_string")
if (wifi_connected == false) {
sprintf(weather_string, "%c weather:%cN/A ", COLOR_HEADING, COLOR_NORMAL);
return -2;
}
CURL *curl;
int i;
struct json_struct json_structs[2];
static const char *urls[2] = { weather_url, forecast_url };
char cap[3];
day_safe = tm_struct->tm_wday;
if (curl_global_init(CURL_GLOBAL_ALL))
ERR(weather_string, "Error curl_global_init(). Please fix issue and restart.")
if (!(curl = curl_easy_init()))
ERR(weather_string, "Error curl_easy_init(). Please fix issue and restart.")
for (i = 0; i < 2; i++) {
json_structs[i].data = (char *)malloc(1);
if (json_structs[i].data == NULL)
ERR(weather_string, "Out of memory");
json_structs[i].size = 0;
if (curl_easy_setopt(curl, CURLOPT_URL, urls[i]) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0") != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &json_structs[i]) != CURLE_OK)
ERR(weather_string, "Error curl_easy_setops() in get_weather(). Please fix issue and restart.")
if (curl_easy_perform(curl) == CURLE_OK) {
if (!i) {
if (parse_weather_json(json_structs[i].data) < 0)
ERR(weather_string, "Error parsing weather json. Please fix issue and restart.")
} else {
if (parse_forecast_json(json_structs[i].data) < 0)
ERR(weather_string, "Error parsing forecast json. Please fix issue and restart.")
}
sprintf(cap, "%c ", COLOR_NORMAL);
strcat(weather_string, cap);
weather_update = false;
} else
sprintf(weather_string, "%c weather:%cN/A ",
COLOR_HEADING, COLOR_NORMAL);
}
free(json_structs[0].data);
free(json_structs[1].data);
curl_easy_cleanup(curl);
curl_global_cleanup();
return 0;
}
static int
parse_error_code(int code, char *ret_str)
{
switch (code) {
case 20:
strcpy(ret_str, "already done"); break;
case 21:
strcpy(ret_str, "tar error"); break;
case 22:
strcpy(ret_str, "gpg error"); break;
case 23:
strcpy(ret_str, "no acc token"); break;
case 24:
strcpy(ret_str, "error get url"); break;
case 25:
strcpy(ret_str, "token timeout"); break;
case 26:
strcpy(ret_str, "err verifying"); break;
default:
strcpy(ret_str, "err in backup");
}
return 0;
}
static int
get_backup_status(void)
{
struct stat file_stat;
if (stat(BACKUP_STATUS_FILE, &file_stat) < 0)
ERR(backup_status_string, "Error Getting Backup File Stats")
if (file_stat.st_mtime <= backup_mtime)
return 0;
backup_mtime = file_stat.st_mtime;
FILE *fd;
char line[32], print[16], color = COLOR_ERROR;
int value;
time_t curr_time;
time_t t_diff;
if (!memset(backup_status_string, '\0', 32))
ERR(backup_status_string, "Error resetting backup_status_string")
if (!(fd = fopen(BACKUP_STATUS_FILE, "r")))
ERR(backup_status_string, "Error Opening Backup Status File")
if (fgets(line, 32, fd) == NULL)
ERR(backup_status_string, "No Backup History")
if (fclose(fd))
ERR(backup_status_string, "Error Closing Backup Status File")
if (isdigit(line[0])) {
sscanf(line, "%d", &value);
if (value >= 20 && value <= 26)
parse_error_code(value, print);
else {
time(&curr_time);
t_diff = curr_time - value;
if (t_diff > 86400)
strcpy(print, "missed");
else {
strcpy(print, "done");
color = COLOR1;
}
}
} else {
line[strlen(line) - 1] = '\0';
strcpy(print, line);
color = COLOR2;
}
snprintf(backup_status_string, 32, "%cbackup:%c %s%c ",
COLOR_HEADING, color, print, COLOR_NORMAL);
return 0;
}
static double
parse_portfolio_json(char *raw_json)
{
cJSON *parsed_json = cJSON_Parse(raw_json);
cJSON *equity_obj, *extended_hours_equity_obj;
cJSON *equity_previous_close_obj;
double equity_f;
equity_obj = cJSON_GetObjectItem(parsed_json, "equity");
if (!equity_obj)
return -1;
extended_hours_equity_obj = cJSON_GetObjectItem(parsed_json, "extended_hours_equity");
if (!extended_hours_equity_obj)
return -1;
if (extended_hours_equity_obj->valuestring == NULL)
equity_f = atof(equity_obj->valuestring);
else
equity_f = atof(extended_hours_equity_obj->valuestring);
if (!equity_previous_close) {
equity_previous_close_obj = cJSON_GetObjectItem(parsed_json, "equity_previous_close");
if (!equity_previous_close_obj)
return -1;
equity_previous_close = atof(equity_previous_close_obj->valuestring);
}
cJSON_Delete(parsed_json);
return equity_f;
}
static int
get_portfolio_value(void)
{
// Robinhood starts trading at 9:00 am EST
if (timezone / 3600 + tm_struct->tm_hour < 14 && equity_found == true)
return 0;
// Robinhood stops after-market trading at 6:00 pm EST
if (timezone / 3600 + tm_struct->tm_hour > 23 && equity_found == true)
return 0;
if (wifi_connected == false) {
sprintf(portfolio_value_string, "%crobinhood:%cN/A",
COLOR_HEADING, COLOR_NORMAL);
return -2;
}
if (portfolio_init == false)
return -2;
if (!memset(portfolio_value_string, '\0', 32))
ERR(portfolio_value_string, "Error resetting portfolio_va...")
int tz_gap;
CURL *curl;
struct json_struct portfolio_jstruct;
static double equity;
portfolio_jstruct.data = (char *)malloc(1);
if (portfolio_jstruct.data == NULL)
ERR(portfolio_value_string, "Out of memory");
portfolio_jstruct.size = 0;
if (curl_global_init(CURL_GLOBAL_ALL))
ERR(portfolio_value_string, "Error curl_global_init()")
if (!(curl = curl_easy_init()))
ERR(portfolio_value_string, "Error curl_easy_init()")
if (curl_easy_setopt(curl, CURLOPT_URL, portfolio_url) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0") != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &portfolio_jstruct) != CURLE_OK)
ERR(portfolio_value_string, "Error curl_easy_setops()")
if (curl_easy_perform(curl) == CURLE_OK) {
if ((equity = parse_portfolio_json(portfolio_jstruct.data)) < 0)
ERR(portfolio_value_string, "Error parsing portfolio json")
sprintf(portfolio_value_string, "%crobinhood:%c%.2lf",
COLOR_HEADING, equity >= equity_previous_close ? GREEN_TEXT : RED_TEXT, equity);
equity_found = true;
} else
sprintf(portfolio_value_string, "%crobinhood:%cN/A",
COLOR_HEADING, COLOR_NORMAL);
free(portfolio_jstruct.data);
curl_easy_cleanup(curl);
curl_global_cleanup();
return 0;
}
static int
free_wifi_list(struct nlmsg_list *list)
{
struct nlmsg_list *next;
while (list != NULL) {
next = list->next;
free(list);
list = next;
}
}
static int
format_wifi_status(char color)
{
char tmp[32];
if (strlen(wifi_status_string) > (sizeof wifi_status_string - 6))
memset(wifi_status_string + strlen(wifi_status_string) - 3, '.', 3);
sprintf(tmp, " %cwifi:%c %s %c ",
COLOR_HEADING, color, wifi_status_string, COLOR_NORMAL);
strcpy(wifi_status_string, tmp);
return 0;
}
static int
print_ssid(uint8_t len, uint8_t *data)
{
// stolen from iw
int i;
uint8_t tmp_str[2];
memset(wifi_status_string, '\0', 32);
for (i = 0; i < len && i < sizeof wifi_status_string; i++) {
if (isprint(data[i]) && data[i] != ' ' && data[i] != '\\')
sprintf(tmp_str, "%c", data[i]);
else if (data[i] == ' ' && (i != 0 && i != len -1))
sprintf(tmp_str, " ");
else
sprintf(tmp_str, "\\x%.2x", data[i]);
strncat(wifi_status_string, tmp_str,
sizeof wifi_status_string - strlen(wifi_status_string) - 1);
}
return 0;
}
static int
wifi_callback(struct nl_msg *msg, void *arg)
{
struct nlattr *tb[NL80211_ATTR_MAX + 1];
struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
uint8_t len;
uint8_t *data;
nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
genlmsg_attrlen(gnlh, 0), NULL);
if (tb[NL80211_ATTR_SSID]) {
len = nla_len(tb[NL80211_ATTR_SSID]);
data = nla_data(tb[NL80211_ATTR_SSID]);
print_ssid(len, data);
}
return NL_SKIP;
}
static int
store_nlmsg(const struct sockaddr_nl *who, struct nlmsghdr *hdr, void *arg)
{
// stolen from iproute2
struct nlmsg_list **linfo = (struct nlmsg_list**)arg;
for (linfo; *linfo; linfo = &(*linfo)->next);
*linfo = (struct nlmsg_list *)malloc(hdr->nlmsg_len + sizeof(void*));
if (*linfo == NULL)
return -1;
memcpy(&(*linfo)->h, hdr, hdr->nlmsg_len);
(*linfo)->next = NULL;
return 0;
}
static int
ip_check(int flag)
{
// stolen from iproute2
struct rtnl_handle rth;
struct nlmsg_list *linfo = NULL;
struct nlmsg_list *head = NULL;
struct ifinfomsg *ifi;
struct rtattr *tb[IFLA_MAX+1];
int len;
int rv;
if (rtnl_open(&rth, 0) < 0)
ERR(wifi_status_string, "error: rtnl_open")
if (rtnl_wilddump_request(&rth, AF_PACKET, RTM_GETLINK) < 0)
ERR(wifi_status_string, "error: rtnl_wilddump_request")
if (rtnl_dump_filter(&rth, store_nlmsg, &linfo) < 0)
ERR(wifi_status_string, "error: rtnl_dump_filter")
rtnl_close(&rth);
head = linfo;
for (int i = 1; i < devidx; i++, linfo = linfo->next);
ifi = NLMSG_DATA(&linfo->h);
if (!ifi)
ERR(wifi_status_string, "error accessing ifi")
len = linfo->h.nlmsg_len - NLMSG_LENGTH(sizeof(*ifi));
parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len);
if (flag)
// 2 if down, 6 if up
rv = *(__u8 *)RTA_DATA(tb[IFLA_OPERSTATE]);
else
// 0 if down, 1 if up
rv = ifi->ifi_flags & IFF_UP;
free_wifi_list(head);
return rv;
}
static int
get_wifi_status(void)
{
struct nl_sock *socket;
int id;
struct nl_msg *msg;
struct nl_cb *cb;
int ifi_flag;
int op_state;
char color = COLOR2;
ifi_flag = ip_check(0);
if (ifi_flag == -1) return -1;
op_state = ip_check(1);
if (op_state == -1) return -1;
if (ifi_flag == 0 && op_state == 2) {
strncpy(wifi_status_string, "Wireless Device Set Down", 31);
wifi_connected = false;
} else if (ifi_flag && op_state == 0) {
strncpy(wifi_status_string, "Wireless State Unknown", 31);
wifi_connected = false;
} else if (ifi_flag && op_state == 2) {
strncpy(wifi_status_string, "No Connection Initiated", 31);
wifi_connected = false;
} else if (ifi_flag && op_state == 5) {
strncpy(wifi_status_string, "No Carrier", 31);
wifi_connected = false;
} else if (ifi_flag && op_state == 6) {
if (wifi_connected == true) return 0;
if (!memset(wifi_status_string, '\0', 32))
ERR(wifi_status_string, "Error resetting wifi_status_string")
socket = nl_socket_alloc();
if (!socket)
ERR(wifi_status_string, "err: nl_socket_alloc()")
if (genl_connect(socket) < 0)
ERR(wifi_status_string, "err: genl_connect()")
id = genl_ctrl_resolve(socket, "nl80211");
if (!id)
ERR(wifi_status_string, "err: genl_ctrl_resolve()")
msg = nlmsg_alloc();
if (!msg)
ERR(wifi_status_string, "err: nlmsg_alloc()")
cb = nl_cb_alloc(NL_CB_DEFAULT);
if (!cb)
ERR(wifi_status_string, "err: nl_cb_alloc()")
genlmsg_put(msg, 0, 0, id, 0, 0, NL80211_CMD_GET_INTERFACE, 0);
if (nla_put(msg, NL80211_ATTR_IFINDEX, sizeof(uint32_t), &devidx) < 0)
ERR(wifi_status_string, "err: nla_put()")
nl_send_auto_complete(socket, msg);
if (nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, wifi_callback, NULL) < 0)
ERR(wifi_status_string, "err: nla_cb_set()")
if (nl_recvmsgs(socket, cb) < 0)
strncpy(wifi_status_string, "No Wireless Connection", 31);
else
color = COLOR1;
wifi_connected = true;
nlmsg_free(msg);
nl_socket_free(socket);
free(cb);
} else
ERR(wifi_status_string, "Error with WiFi Status")
format_wifi_status(color);
return 0;
}
static int
get_time(void)
{
if (!memset(time_string, '\0', 32))
ERR(time_string, "Error resetting time_string")
if (strftime(time_string, 32, "%b %d - %I:%M", tm_struct) == 0)
ERR(time_string, "Error with strftime()")
if (tm_struct->tm_sec % 2)
time_string[strlen(time_string) - 3] = ' ';
return 0;
}
static char
get_unit(int unit)
{
switch (unit) {
case 1: return 'K';
case 2: return 'M';
case 3: return 'G';
default: return 'B';
}
}
static int
format_bytes(long *bytes, int *step)
{
long bytes_n = *bytes;
int step_n = 0;
while (bytes_n >= 1 << 10) {
bytes_n = bytes_n >> 10;
step_n++;
}
*bytes = bytes_n;
*step = step_n;
return 0;
}
static int
get_network_usage(void)
{
if (!memset(network_usage_string, '\0', 64))
ERR(network_usage_string, "Error resetting network_usage")
/* from top.c */
const char* files[2] = { NET_RX_FILE, NET_TX_FILE };
FILE *fd;
char line[64];
static long rx_old, tx_old;
long rx_new, tx_new;
long rx_bps, tx_bps;
int step = 0;
char rx_unit, tx_unit;
for (int i = 0; i < 2; i++) {
fd = fopen(files[i], "r");
if (!fd)
ERR(network_usage_string, "Read Error")
fgets(line, 64, fd);
if (fclose(fd))
ERR(network_usage_string, "Close Error")
if (i) {
sscanf(line, "%d", &tx_new);
tx_bps = tx_new - tx_old;
format_bytes(&tx_bps, &step);
tx_unit = get_unit(step);
} else {
sscanf(line, "%d", &rx_new);
rx_bps = rx_new - rx_old;
format_bytes(&rx_bps, &step);
rx_unit = get_unit(step);
}
}
if (rx_bps > 999) rx_bps = 999;
if (tx_bps > 999) tx_bps = 999;
snprintf(network_usage_string, 64, "%cnetwork:%c%3d %c/S down,%c%3d %c/S up%c ",
COLOR_HEADING, rx_unit == 'M' ? COLOR_WARNING : COLOR_NORMAL, rx_bps, rx_unit,
tx_unit == 'M' ? COLOR_WARNING : COLOR_NORMAL, tx_bps, tx_unit, COLOR_NORMAL);
rx_old = rx_new;
tx_old = tx_new;
return 0;
}
static int
process_stat(struct disk_usage_struct *dus)
{
int unit_int = 0;
float bytes_used;
float bytes_total;
bytes_used = (float)(dus->fs_stat.f_blocks - dus->fs_stat.f_bfree) * block_size;
bytes_total = (float)dus->fs_stat.f_blocks * block_size;
while (bytes_used > 1 << 10) {
bytes_used /= 1024;
unit_int++;
}
dus->bytes_used = bytes_used;
dus->unit_used = get_unit(unit_int);
unit_int = 0;
while (bytes_total > 1 << 10) {
bytes_total /= 1024;
unit_int++;
}
dus->bytes_total = bytes_total;
dus->unit_total = get_unit(unit_int);
return 0;
}
static int
get_disk_usage(void)
{
if (!memset(disk_usage_string, '\0', 64))
ERR(disk_usage_string, "Error resetting disk_usage_string")
int rootperc;
if (statvfs("/", &root_fs.fs_stat) < 0)
ERR(disk_usage_string, "Error getting filesystem stats")
process_stat(&root_fs);
rootperc = rint((double)root_fs.bytes_used / (double)root_fs.bytes_total * 100);
snprintf(disk_usage_string, 64, " %c disk:%c%.1f%c/%.1f%c%c ",
rootperc >= 75? COLOR_WARNING : COLOR_HEADING,
rootperc >= 75? COLOR_WARNING : COLOR_NORMAL,
root_fs.bytes_used, root_fs.unit_used, root_fs.bytes_total, root_fs.unit_total,
COLOR_NORMAL);
return 0;
}
static int
get_memory(void)
{
if (!memset(memory_string, '\0', 32))
ERR(memory_string, "Error resetting memory_string")
int memperc;
meminfo();
memperc = rint((double)kb_active / (double)kb_main_total * 100);
if (memperc > 99)
memperc = 99;
snprintf(memory_string, 32, " %c RAM:%c%2d%% used%c ",
memperc >= 75? COLOR_WARNING : COLOR_HEADING,
memperc >= 75? COLOR_WARNING : COLOR_NORMAL,
memperc, COLOR_NORMAL);
return 0;
}
static int
get_cpu_load(void)
{
if (!memset(cpu_load_string, '\0', 32))
ERR(cpu_load_string, "Error resetting cpu_load_string")
// why was this static?
double av[3];
loadavg(&av[0], &av[1], &av[2]);
snprintf(cpu_load_string, 32, " %c load:%c%.2f %.2f %.2f%c ",
av[0] > 1 ? COLOR_WARNING : COLOR_HEADING,
av[0] > 1 ? COLOR_WARNING : COLOR_NORMAL,
av[0], av[1], av[2], COLOR_NORMAL);
return 0;
}
static int
get_cpu_usage(void)
{
if (!memset(cpu_usage_string, '\0', 32))
ERR(cpu_usage_string, "Error resetting cpu_usage_string")
/* from top.c */
FILE *fd;
char buf[64];
int seca = 0, secb = 0, secc = 0, secd = 0, top, bottom, total = 0;
int i;
static struct {
int oldval[4];
int newval[4];
} cpu;
fd = fopen(CPU_USAGE_FILE, "r");
if (!fd)
ERR(cpu_usage_string, "Read Error")
fgets(buf, 64, fd);
if (fclose(fd))
ERR(cpu_usage_string, "Close Error")
sscanf(buf, "cpu %d %d %d %d", &cpu.newval[0], &cpu.newval[1], &cpu.newval[2], &cpu.newval[3]);
// exclude first run
if (cpu.oldval[0]) {
for (i = 0; i < 4; i++) {
secc += cpu.newval[i];
secd += cpu.oldval[i];
if (i == 3) continue;
seca += cpu.newval[i];
secb += cpu.oldval[i];
}
top = seca - secb + 1;
bottom = secc - secd + 1;
total = rint((double)top / (double)bottom * 100);
total *= cpu_ratio;
}
for (i = 0; i < 4; i++)
cpu.oldval[i] = cpu.newval[i];
if (total >= 100) total = 99;
snprintf(cpu_usage_string, 32, " %c CPU usage:%c%2d%%%c ",
total >= 75 ? COLOR_WARNING : COLOR_HEADING,
total >= 75 ? COLOR_WARNING : COLOR_NORMAL,
total, COLOR_NORMAL);
return 0;
}
static int
get_cpu_temp(void)
{
if (!memset(cpu_temp_string, '\0', 32))
ERR(cpu_temp_string, "Error resetting cpu_temp_string")
struct cpu_temp_list *snake;
int counter;
int temp = 0;
int tempperc;
for (snake = temp_list, counter = 0; snake != NULL; snake = snake->next, counter++) {
char path[128];
FILE *fd;
int tmp;
strcpy(path, CPU_TEMP_DIR);
strcat(path, snake->filename);
fd = fopen(path, "r");
if (!fd)
ERR(cpu_temp_string, "Error Opening CPU File")
if (!fscanf(fd, "%d", &tmp))
ERR(cpu_temp_string, "Error Scanning CPU File")
if (fclose(fd))
ERR(cpu_temp_string, "Error Closing CPU File")
temp += tmp;
}
temp /= counter;
tempperc = rint((double)temp / (double)temp_max * 100);
temp >>= 10;
snprintf(cpu_temp_string, 32, " %c CPU temp:%c%2d degC%c ",
tempperc >= 75? COLOR_WARNING : COLOR_HEADING,
tempperc >= 75? COLOR_WARNING : COLOR_NORMAL,
temp, COLOR_NORMAL);
return 0;
}
static int
get_fan_speed(void)
{
if (!memset(fan_speed_string, '\0', 32))
ERR(fan_speed_string, "Error resetting fan_speed_string")
FILE *fd;
int rpm;
int fanperc;
fd = fopen(FAN_SPEED_FILE, "r");
if (!fd)
ERR(fan_speed_string, "Error Opening File")
if (!fscanf(fd, "%d", &rpm))
ERR(fan_speed_string, "Error Scanning File")
if (fclose(fd))
ERR(fan_speed_string, "Error Closing File")
rpm -= fan_min;
if (rpm <= 0)
rpm = 0;
fanperc = rint((double)rpm / (double)fan_max * 100);
if (fanperc >= 100)
snprintf(fan_speed_string, 32, " %c fan: MAX%c ", COLOR_WARNING, COLOR_NORMAL);
else
snprintf(fan_speed_string, 32, " %c fan:%c%2d%%%c ",
fanperc >= 75? COLOR_WARNING : COLOR_HEADING,
fanperc >= 75? COLOR_WARNING : COLOR_NORMAL,
fanperc, COLOR_NORMAL);
return 0;
}
static int
get_brightness(void)
{
if (!memset(brightness_string, '\0', 32))
ERR(brightness_string, "Error resetting brightness_string")
const char* b_files[2] = { SCREEN_BRIGHTNESS_FILE, KBD_BRIGHTNESS_FILE };
int scrn, kbd;
int scrn_perc, kbd_perc;
for (int i = 0; i < 2; i++) {
if (i == 1 && DISPLAY_KBD == false) continue;
FILE *fd;
fd = fopen(b_files[i], "r");
if (!fd)
ERR(brightness_string, "Error w File Open")
fscanf(fd, "%d", i == 0 ? &scrn : &kbd);
if (fclose(fd))
ERR(brightness_string, "Error File Close")
}
scrn_perc = rint((double)scrn / (double)screen_brightness_max * 100);
if (DISPLAY_KBD == true)
kbd_perc = rint((double)kbd / (double)kbd_brightness_max * 100);
if (DISPLAY_KBD == true)
snprintf(brightness_string, 32, " %c brightness:%c%3d%%, %3d%%%c ",
COLOR_HEADING, COLOR_NORMAL, scrn_perc, kbd_perc, COLOR_NORMAL);
else
snprintf(brightness_string, 32, " %c brightness:%c%3d%%%c ",
COLOR_HEADING, COLOR_NORMAL, scrn_perc, COLOR_NORMAL);
return 0;
}
static int
get_volume(void)
{
if (!memset(volume_string, '\0', 32))
ERR(volume_string, "Error resetting volume_string")
// stolen from amixer utility from alsa-utils
long pvol;
int swch, volperc;
snd_mixer_t *handle = NULL;
snd_mixer_elem_t *elem;
snd_mixer_selem_id_t *sid;
if (snd_mixer_open(&handle, 0))
SND_ERR("Error Open")
if (snd_mixer_attach(handle, "default"))
SND_ERR("Error Attch")
if (snd_mixer_selem_register(handle, NULL, NULL))
SND_ERR("Error Rgstr")
if (snd_mixer_load(handle))
SND_ERR("Error Load")
snd_mixer_selem_id_alloca(&sid);
snd_mixer_selem_id_set_name(sid, "Master");
if (!(elem = snd_mixer_find_selem(handle, sid)))
SND_ERR("Error Elem")
if (snd_mixer_selem_get_playback_switch(elem, SND_MIXER_SCHN_MONO, &swch))
SND_ERR("Error Get S")
if (!swch) {
snprintf(volume_string, 32, " %c volume:%cmute%c ",
COLOR_HEADING, COLOR_NORMAL, COLOR_NORMAL);
} else {
if (snd_mixer_selem_get_playback_volume(elem, SND_MIXER_SCHN_MONO, &pvol))
SND_ERR("Error Get V")
// round to the nearest ten
volperc = (double)pvol / vol_range * 100;
volperc = rint((float)volperc / 10) * 10;
snprintf(volume_string, 32, " %c volume:%c%3d%%%c ",
COLOR_HEADING, COLOR_NORMAL, volperc, COLOR_NORMAL);
}
if (snd_mixer_close(handle))
SND_ERR("Error Close")
handle = NULL;
snd_config_update_free_global();
return 0;
}
static int
get_battery(void)
{
if (!memset(battery_string, '\0', 32))
ERR(battery_string, "Error resetting battery_string")
/* from acpi.c and other acpi source files */
FILE *fd;
char status_string[20];
int status; // -1 = discharging, 0 = full, 1 = charging
int capacity;
const char *filepaths[2] = { BATT_STATUS_FILE, BATT_CAPACITY_FILE };
fd = fopen(BATT_STATUS_FILE, "r");
if (!fd)
ERR(battery_string, "Err Open Bat Fil")
fscanf(fd, "%s", &status_string);
if (fclose(fd))
ERR(battery_string, "Err Close Bat fd")
if (!strcmp(status_string, "Full") || !strcmp(status_string, "Unknown")) {
status = 0;
snprintf(battery_string, 32, " %c battery:%c full %c",
COLOR_HEADING, COLOR1, COLOR_NORMAL);
return 0;
}
if (!strcmp(status_string, "Discharging"))
status = -1;
else if (!strcmp(status_string, "Charging"))
status = 1;
else
ERR(battery_string, "Err Read Bat Sts")
fd = fopen(BATT_CAPACITY_FILE, "r");
if (!fd)
ERR(battery_string, "Err Open Bat Fil")
fscanf(fd, "%d", &capacity);
if (fclose(fd))
ERR(battery_string, "Err Close Bat fd")
if (capacity > 99)
capacity = 99;
snprintf(battery_string, 32, " %c battery: %c%2d%% %c",
capacity < 20 ? COLOR_ERROR : status > 0 ? COLOR2 : COLOR_WARNING,
status > 0 ? '+' : '-', capacity, COLOR_NORMAL);
return 0;
}
static int
parse_account_number_json(char *raw_json)
{
cJSON *parsed_json = cJSON_Parse(raw_json);
cJSON *results, *account, *account_num;
cJSON *weather_dict;
int id;
results = cJSON_GetObjectItem(parsed_json, "results");
if (!results)
return -1;
account = results->child;
if (!account)
return -1;
account_num = cJSON_GetObjectItem(account, "account_number");
if (!account_num)
return -1;
strncpy(account_number, account_num->valuestring, 31);
cJSON_Delete(parsed_json);
return 0;
}
static int
get_account_number(void)
{
CURL *curl;
struct json_struct account_number_struct;
account_number_struct.data = (char *)malloc(1);
if (account_number_struct.data == NULL)
INIT_ERR("error allocating account_number_struct.data")
account_number_struct.size = 0;
if (curl_global_init(CURL_GLOBAL_ALL))
INIT_ERR("error curl_global_init() in get_account_number()")
if (!(curl = curl_easy_init()))
INIT_ERR("error curl_easy_init() in get_account_number()")
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, token_header);
if (headers == NULL)
INIT_ERR("error curl_slist_append() in get_account_number()")
if (curl_easy_setopt(curl, CURLOPT_URL, "https://api.robinhood.com/accounts/") != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0") != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &account_number_struct) != CURLE_OK)
INIT_ERR("error curl_easy_setopt() in get_account_number()")
if (curl_easy_perform(curl) != CURLE_OK)
INIT_ERR("error curl_easy_perform() in get_account_number()")
if (parse_account_number_json(account_number_struct.data) < 0)
INIT_ERR("error parse_account_number_json() in get_account_number()")
free(account_number_struct.data);
curl_easy_cleanup(curl);
curl_global_cleanup();
return 0;
}
static int
parse_token_json(char *raw_json)
{
cJSON *parsed_json = cJSON_Parse(raw_json);
cJSON *token = cJSON_GetObjectItem(parsed_json, "token");
if (!token)
INIT_ERR("error finding \"token\" in token json")
snprintf(token_header, 64, "Authorization: Token %s", token->valuestring);
cJSON_Delete(parsed_json);
return 0;
}
static int
get_token(void)
{
CURL *curl;
struct json_struct token_struct;
struct curl_slist *header = NULL;
token_struct.data = (char *)malloc(1);
if (token_struct.data == NULL)
INIT_ERR("error allocating token_struct.data")
token_struct.size = 0;
if (curl_global_init(CURL_GLOBAL_ALL))
INIT_ERR("error curl_global_init() in get_token()")
if (!(curl = curl_easy_init()))
INIT_ERR("error curl_easy_init() in get_token()")
header = curl_slist_append(header, "Accept: application/json");
if (header == NULL)
INIT_ERR("error curl_slist_append() in get_token()")
if (curl_easy_setopt(curl, CURLOPT_URL, "https://api.robinhood.com/api-token-auth/") != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, RH_LOGIN) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0") != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &token_struct) != CURLE_OK)
INIT_ERR("error curl_easy_setopt() in get_token()")
if (curl_easy_perform(curl) != CURLE_OK)
INIT_ERR("error curl_easy_perform() in get_token()")
if (parse_token_json(token_struct.data) < 0)
INIT_ERR("error parse_token_json() in get_token()")
free(token_struct.data);
curl_slist_free_all(header);
curl_easy_cleanup(curl);
curl_global_cleanup();
return 0;
}
static int
init_portfolio()
{
if (get_token() < 0)
return -1;
if (get_account_number() < 0)
return -1;
snprintf(portfolio_url, 128, "https://api.robinhood.com/accounts/%s/portfolio/", account_number);
portfolio_init = true;
return 0;
}
static int
populate_tm_struct(void)
{
time_t tval;
time(&tval);
tm_struct = localtime(&tval);
return 0;
}
static int
loop (Display *dpy, Window root)
{
int weather_return = 0;
while (1) {
// get times
populate_tm_struct();
// // run every second
get_time();
get_network_usage();
get_cpu_usage();
if (weather_update == true && wifi_connected == true)
if ((weather_return = get_weather()) < 0)
if (weather_return != -2)
break;
if (portfolio_init == false && wifi_connected == true)
init_portfolio();
// run every five seconds
if (tm_struct->tm_sec % 5 == 0) {
get_TODO();
get_backup_status();
if (get_portfolio_value() == -1)
break;
if (get_wifi_status() < 0)
break;
get_memory();
get_cpu_load();
get_cpu_temp();
get_fan_speed();
get_brightness();
get_volume();
get_battery();
}
// run every minute
if (tm_struct->tm_sec == 0) {
get_log_status();
get_disk_usage();
}
// run every 3 hours
if ((tm_struct->tm_hour + 1) % 3 == 0 && tm_struct->tm_min == 0 && tm_struct->tm_sec == 0)
if (wifi_connected == false)
weather_update = true;
else
if ((weather_return = get_weather()) < 0)
if (weather_return != -2)
break;
format_string(dpy, root);
sleep(1);
}
return -1;
}
static int
make_urls(void)
{
snprintf(weather_url, 128, "http://api.openweathermap.org/data/2.5/weather?id=%s&appid=%s&units=imperial", LOCATION, KEY);
snprintf(forecast_url, 128, "http://api.openweathermap.org/data/2.5/forecast?id=%s&appid=%s&units=imperial", LOCATION, KEY);
return 0;
}
static int
get_vol_range(void)
{
long min, max;
snd_mixer_t *handle = NULL;
snd_mixer_elem_t *elem;
snd_mixer_selem_id_t *sid;
// stolen from amixer utility from alsa-utils
if ((snd_mixer_open(&handle, 0)) < 0)
SND_INIT_ERR("error opening volume handle")
if ((snd_mixer_attach(handle, "default")) < 0)
SND_INIT_ERR("error attaching volume handle")
if ((snd_mixer_selem_register(handle, NULL, NULL)) < 0)
SND_INIT_ERR("error registering volume handle")
if ((snd_mixer_load(handle)) < 0)
SND_INIT_ERR("error loading volume handle")
snd_mixer_selem_id_alloca(&sid);
if (sid == NULL)
SND_INIT_ERR("error allocating memory for volume id")
snd_mixer_selem_id_set_name(sid, "Master");
if (!(elem = snd_mixer_find_selem(handle, sid)))
SND_INIT_ERR("error finding volume property")
if (snd_mixer_selem_get_playback_volume_range(elem, &min, &max))
SND_INIT_ERR("error getting volume range")
if (snd_mixer_close(handle))
SND_INIT_ERR("error closing volume handle")
handle = NULL;
snd_config_update_free_global();
return max - min;
}
static int
get_kbd_brightness_max(void)
{
char file_str[128];
char dir_str[128];
DIR *dir;
struct dirent *file;
int count = 0;
FILE *fd;
int max;
strcpy(file_str, KBD_BRIGHTNESS_FILE);
strcpy(dir_str, dirname(file_str));
if ((dir = opendir(dir_str)) == NULL)
INIT_ERR("error opening keyboard brightness directory")
while ((file = readdir(dir)) != NULL)
if (!strcmp(file->d_name, "max_brightness")) {
if (strlen(dir_str) + strlen(file->d_name) + 2 > sizeof dir_str)
break;
strcat(dir_str, "/");
strcat(dir_str, file->d_name);
count++;
break;
}
if (!count)
INIT_ERR("error finding keyboard brightness directory")
fd = fopen(dir_str, "r");
if (!fd)
INIT_ERR("error opening keyboard brightness file")
fscanf(fd, "%d", &max);
if (fclose(fd) < 0)
INIT_ERR("error closing keyboard brightness file")
if (closedir(dir) < 0)
INIT_ERR("error closing keyboard brightness directory")
return max;
}
static int
get_screen_brightness_max(void)
{
char file_str[128];
char dir_str[128];
DIR *dir;
struct dirent *file;
int count = 0;
FILE *fd;
int max;
strcpy(file_str, SCREEN_BRIGHTNESS_FILE);
strcpy(dir_str, dirname(file_str));
if ((dir = opendir(dir_str)) == NULL)
INIT_ERR("error opening screen brightness directory")
while ((file = readdir(dir)) != NULL)
if (!strcmp(file->d_name, "max_brightness")) {
if (strlen(dir_str) + strlen(file->d_name) + 2 > sizeof dir_str)
break;
strcat(dir_str, "/");
strcat(dir_str, file->d_name);
count++;
break;
}
if (!count)
INIT_ERR("error finding screen brightness directory")
fd = fopen(dir_str, "r");
if (!fd)
INIT_ERR("error opening screen brightness file")
fscanf(fd, "%d", &max);
if (fclose(fd) < 0)
INIT_ERR("error closing screen brightness file")
if (closedir(dir) < 0)
INIT_ERR("error closing screen brightness directory")
return max;
}
static int
get_fan_max(void)
{
char file_str[128];
char dir_str[128];
DIR *dir;
struct dirent *file;
char tmp[64];
char *token;
FILE *fd;
int count = 0;
int max;
strcpy(file_str, FAN_SPEED_FILE);
strcpy(dir_str, dirname(file_str));
if ((dir = opendir(dir_str)) == NULL)
INIT_ERR("error opening fan directory")
while ((file = readdir(dir)) != NULL) {
strcpy(tmp, file->d_name);
if ((token = strtok(tmp, "_")))
if ((token = strtok(NULL, "_")))
if (!strcmp(token, "max")) {
if (strlen(dir_str) + strlen(file->d_name) + 2 > sizeof dir_str)
break;
strcat(dir_str, "/");
strcat(dir_str, file->d_name);
count++;
break;
}
}
if (!count)
INIT_ERR("error finding fan max file")
fd = fopen(dir_str, "r");
if (!fd)
INIT_ERR("error opening file in get_fan_max")
fscanf(fd, "%d", &max);
max -= fan_min;
if (fclose(fd) < 0)
INIT_ERR("error closing file in get_fan_max")
if (closedir(dir) < 0)
INIT_ERR("error closing directory in get_fan_max")
return max;
}
static int
get_fan_min(void)
{
char file_str[128];
char dir_str[128];
DIR *dir;
struct dirent *file;
char tmp[64];
char *token;
FILE *fd;
int count = 0;
int min;
strcpy(file_str, FAN_SPEED_FILE);
strcpy(dir_str, dirname(file_str));
if ((dir = opendir(dir_str)) == NULL)
INIT_ERR("error opening fan directory")
while ((file = readdir(dir)) != NULL) {
strcpy(tmp, file->d_name);
if ((token = strtok(tmp, "_")))
if ((token = strtok(NULL, "_")))
if (!strcmp(token, "min")) {
if (strlen(dir_str) + strlen(file->d_name) + 2 > sizeof(dir_str))
break;
strcat(dir_str, "/");
strcat(dir_str, file->d_name);
count++;
break;
}
}
if (!count)
INIT_ERR("error finding fan min file")
fd = fopen(dir_str, "r");
if (!fd)
INIT_ERR("error opening file in get_fan_min")
fscanf(fd, "%d", &min);
if (fclose(fd) < 0)
INIT_ERR("error closing file in get_fan_min")
if (closedir(dir) < 0)
INIT_ERR("error closing directory in get_fan_min")
return min;
}
static int
free_list(struct cpu_temp_list *list)
{
struct cpu_temp_list *next;
while (list != NULL) {
next = list->next;
free(list->filename);
free(list);
list = next;
}
}
static struct cpu_temp_list *
add_link(struct cpu_temp_list *list, char *filename)
{
struct cpu_temp_list *new;
struct cpu_temp_list *worm;
new = (struct cpu_temp_list *)malloc(sizeof(struct cpu_temp_list));
if (new == NULL) {
fprintf(stderr, "%serror allocating memory for cpu temperature file list\n",
asctime(tm_struct));
perror("Error");
printf("\n");
return NULL;
}
new->filename = (char *)malloc(strlen(filename) + 1);
if (new->filename == NULL) {
fprintf(stderr, "%serror allocating memory for cpu temperature file list name\n",
asctime(tm_struct));
perror("Error");
printf("\n");
return NULL;
}
strcpy(new->filename, filename);
new->next = NULL;
if (list == NULL)
return new;
else {
for (worm = list; worm->next != NULL; worm = worm->next);
worm->next = new;
}
return list;
}
static struct cpu_temp_list *
populate_temp_list(struct cpu_temp_list *list, char *match)
{
DIR *dir;
struct dirent *file;
char tmp[64];
char *token;
int count = 0;
if ((dir = opendir(CPU_TEMP_DIR)) == NULL)
return NULL;
while ((file = readdir(dir)) != NULL) {
strcpy(tmp, file->d_name);
if ((token = strtok(tmp, "_")))
if ((token = strtok(NULL, "_")))
if (!strcmp(token, match)) {
list = add_link(list, file->d_name);
if (list == NULL) {
fprintf(stderr, "%serror adding link to cpu temperature file list\n",
asctime(tm_struct));
perror("Error");
printf("\n");
return NULL;
}
count++;
}
}
if (!count) {
fprintf(stderr, "%serror finding files for cpu temp list\n",
asctime(tm_struct));
perror("Error");
printf("\n");
return NULL;
}
if (closedir(dir) < 0) {
fprintf(stderr, "%serror closing directory in populate_temp_list\n",
asctime(tm_struct));
perror("Error");
printf("\n");
return NULL;
}
return list;
}
static int
get_temp_max(void)
{
struct cpu_temp_list *max_list = NULL, *snake;
FILE *fd;
int max;
int total = 0;
int counter;
max_list = populate_temp_list(max_list, "max");
if (max_list == NULL)
INIT_ERR("error populating temperature file list in get_temp_max")
for (snake = max_list, counter = 0; snake != NULL; snake = snake->next, counter++) {
char path[128];
strcpy(path, CPU_TEMP_DIR);
strcat(path, snake->filename);
if (!(fd = fopen(path, "r")))
INIT_ERR("error opening file in get_temp_max")
if (!fscanf(fd, "%d", &max))
INIT_ERR("error reading value in get_temp_max")
if (fclose(fd) < 0)
INIT_ERR("error closing file in get_temp_max")
total += max;
}
free_list(max_list);
return total / counter;
}
static int
get_cpu_ratio(void)
{
FILE *fd;
char line[256];
char *token;
int cores;
int threads;
fd = fopen("/proc/cpuinfo", "r");
if (!fd)
INIT_ERR("error opening file in get_cpu_ratio")
while (fgets(line, 256, fd) != NULL && strncmp(line, "cpu cores", 9));
if (fclose(fd) < 0)
INIT_ERR("error closing file in get_cpu_ratio")
token = strtok(line, ":");
if (token == NULL)
INIT_ERR("error parsing /proc/cpuinfo to get cpu ratio")
token = strtok(NULL, ":");
if (token == NULL)
INIT_ERR("error parsing /proc/cpuinfo to get cpu ratio")
cores = atoi(token);
if ((threads = sysconf(_SC_NPROCESSORS_ONLN)) < 0)
INIT_ERR("error getting threads in get_cpu_ratio")
return threads / cores;
}
static int
get_font(char *font)
{
FILE *fd;
char line[256];
char *token;
if (!(fd = fopen(DWM_CONFIG_FILE, "r")))
INIT_ERR("error opening file in get_font")
while (fgets(line, 128, fd) != NULL && strncmp(line, "static const char font[]", 24));
if (line == NULL)
INIT_ERR("no font found in config file")
if (fclose(fd) < 0)
INIT_ERR("error closing file in get_font")
token = strtok(line, "=");
if (token == NULL)
INIT_ERR("error parsing dwm config to get font")
token = strtok(NULL, "=");
if (token == NULL)
INIT_ERR("error parsing dwm config to get font")
while (*token != '"') token++;
token++;
token = strtok(token, "\"");
if (token == NULL)
INIT_ERR("error parsing dwm config to get font")
memcpy(font, token, strlen(token));
return 0;
}
static int
get_bar_max_len(Display *dpy)
{
int width_p, width_c;
char *fontname;
char **miss_list, *def;
int count;
XFontSet fontset;
XFontStruct *xfont;
XRectangle rect;
width_p = DisplayWidth(dpy, DefaultScreen(dpy));
fontname = (char *)malloc(256);
if (fontname == NULL)
INIT_ERR("error allocating memory for fontname")
if (get_font(fontname) < 0)
return -1;
fontset = XCreateFontSet(dpy, fontname, &miss_list, &count, &def);
if (fontset) {
width_c = XmbTextExtents(fontset, "0", 1, NULL, &rect);
XFreeFontSet(dpy, fontset);
} else {
if (!(xfont = XLoadQueryFont(dpy, fontname))
&& !(xfont = XLoadQueryFont(dpy, "fixed")))
INIT_ERR("error loading font for bar\n")
width_c = XTextWidth(xfont, "0", 1);
XFreeFont(dpy, xfont);
}
free(fontname);
return (width_p / width_c) - 2;
}
static int
get_block_size(void)
{
if (statvfs("/", &root_fs.fs_stat) < 0)
INIT_ERR("error getting root file stats")
return root_fs.fs_stat.f_bsize;
}
static int
get_dev_id(void)
{
int index = if_nametoindex(WIFI_INTERFACE);
if (!index)
INIT_ERR("error finding index value for wireless interface")
return index;
}
static int
get_consts(Display *dpy)
{
if ((devidx = get_dev_id()) == 0 )
INIT_ERR("error getting device id")
if ((block_size = get_block_size()) < 0 )
INIT_ERR("error getting block size")
if ((bar_max_len = get_bar_max_len(dpy)) < 0 )
INIT_ERR("error calculating max bar length")
if ((cpu_ratio = get_cpu_ratio()) < 0 )
INIT_ERR("error calculating cpu ratio")
if ((temp_max = get_temp_max()) < 0 )
INIT_ERR("error getting max temp")
if ((fan_min = get_fan_min()) < 0 )
INIT_ERR("error getting min fan speed")
if ((fan_max = get_fan_max()) < 0 )
INIT_ERR("error getting max fan speed")
if ((screen_brightness_max = get_screen_brightness_max()) < 0 )
INIT_ERR("error getting max screen brightness")
if ((kbd_brightness_max = get_kbd_brightness_max()) < 0 )
INIT_ERR("error getting max keyboard brightness")
if ((vol_range = get_vol_range()) < 0 )
INIT_ERR("error getting volume range")
return 0;
}
static int
init(Display *dpy, Window root)
{
time_t curr_time;
if ((temp_list = populate_temp_list(temp_list, "input")) == NULL)
INIT_ERR("error opening temperature directory")
populate_tm_struct();
if (get_consts(dpy) < 0)
INIT_ERR("error intializing constants")
make_urls();
get_TODO();
get_log_status();
get_weather();
get_backup_status();
get_portfolio_value();
get_wifi_status();
get_time();
get_network_usage();
get_disk_usage();
get_memory();
get_cpu_load();
get_cpu_usage();
get_cpu_temp();
get_fan_speed();
get_brightness();
get_volume();
get_battery();
time(&curr_time);
if (format_string(dpy, root) < 0)
INIT_ERR("error format_string() in init()")
return 0;
}
int
main(void)
{
static Display *dpy;
static int screen;
static Window root;
dpy = XOpenDisplay(NULL);
screen = DefaultScreen(dpy);
root = RootWindow(dpy, screen);
if (init(dpy, root) < 0)
strcpy(statusbar_string, "Initialization failed. Check log for details.");
else {
switch (loop(dpy, root)) {
case 1:
strcpy(statusbar_string, "Error getting weather. Loop broken. Check log for details.");
break;
case 2:
strcpy(statusbar_string, "Error getting WiFi info. Loop broken. Check log for details.");
break;
default:
strcpy(statusbar_string, "Loop broken. Check log for details.");
break;
}
}
XStoreName(dpy, root, statusbar_string);
XFlush(dpy);
return -1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T15:43:40.297",
"Id": "387067",
"Score": "0",
"body": "@HildeN, FYI I suggest you to check [slstatus](https://git.suckless.org/slstatus) directory structure. It seems to be way cleaner."
},
{
"ContentLicense": "CC BY-SA 4.0",... | [
{
"body": "<p>Lots of code there, I'll just pick a few things.</p>\n\n<ul>\n<li>Return value from <code>main</code> should be <code>0</code> on success and then something\nelse in case any of those error cases were hit. In general it makes\nsense to keep to this convention so that e.g. typical shell operations... | {
"AcceptedAnswerId": "200975",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T20:36:23.343",
"Id": "200933",
"Score": "2",
"Tags": [
"c",
"parsing",
"linux",
"status-monitoring",
"x11"
],
"Title": "Sysinfo parser for a window manager status bar"
} | 200933 |
<p>I want an integer parser so fast it risks discovering time travel.</p>
<p>I'm stuck in C# for a language, but that doesn't mean I can't try to use c++. So I wrote the following:</p>
<p><strong>The best I could do</strong></p>
<pre class="lang-c# prettyprint-override"><code>public static unsafe bool FastTryParseInt(string input, out int result)
{
fixed (char* cString = input) {
unchecked {
char* nextChar = cString;
bool isNegative = false;
if (*nextChar == CharNegative) {
isNegative = true;
nextChar++;
}
result = 0;
while (*nextChar >= '0' && *nextChar <= '9')
result = result * 10 + (*nextChar++ - '0');
if (*nextChar != Char.MinValue) return false;
long ptrLen = nextChar - cString;
if (isNegative) {
result = -result;
return ptrLen < 11L || ptrLen <= 11L && result <= 0;
}
return ptrLen < 10L || ptrLen <= 10L && result >= 0;
}
}
}
</code></pre>
<p>Shoutout to @chux who gave me many good suggestions while reviewing our custom Double parser at <a href="https://codereview.stackexchange.com/questions/200627/custom-double-parser-optimized-for-performance">Custom double parser optimized for performance</a> .</p>
<p><strong>With comments</strong></p>
<p>Here it is with comments, because I'm not a monster (at least not that kind of monster):</p>
<pre><code>// High performance integer parser with rudimentary flexibility.
// Supports leading negatives, but no white-space or other non-numeric characters.
public static unsafe bool FastTryParseInt(string input, out int result)
{
fixed (char* cString = input) { // Allows pointer math
unchecked { // Allows faster integer math by not testing for overflows
char* nextChar = cString;
bool isNegative = false;
// Handle a possible negative sign at the beginning of the string.
if (*nextChar == CharNegative)
{
isNegative = true;
nextChar++;
}
// Now process each character of the string
result = 0;
while (*nextChar >= '0' && *nextChar <= '9')
result = result * 10 + (*nextChar++ - '0');
// If the non-numeric character encountered to end the while loop
// wasn't the null terminator, the string is invalid.
if (*nextChar != Char.MinValue) return false;
// We need to check for an integer overflow based on the length of the string
long ptrLen = nextChar - cString;
// Result and overflow logic is different if there was a minus sign.
if (isNegative)
{
result = -result;
// Less than 11 characters (including negative) is no risk of overflow
// Longest possible negative int is 11 chars (-2147483648)
// If exactly 11 characters, we know our negative integer overflowed
// if the final result is greater than zero, otherwise it's fine.
return ptrLen < 11L || ptrLen <= 11L && result <= 0;
}
// Otherwise, overflow logic is the same, but opposite, and one fewer
// characters is allowed (because there was no minus sign)
return ptrLen < 10L || ptrLen <= 10L && result >= 0;
}
}
}
</code></pre>
<p>This is ~6x faster than a billion calls to <code>Int.TryParse</code>.</p>
<blockquote>
<p>Native parser took <strong>13808 ms</strong>. Custom parser took <strong>2191 ms</strong>. Performance gain was <strong>530%</strong></p>
</blockquote>
<p><strong>Unsafe? Gross!</strong></p>
<p>I tried getting as close as I could to the above algorithm without using <code>unsafe</code>, and to my surprise, it's about as good. It made me sad, because I was proud of my pointer math:</p>
<pre><code>public static bool FastTryParseIntOld(string input, out int result)
{
result = 0;
int length = input.Length;
if (length == 0) return false;
bool isNegative = false;
int currentIndex = 0;
char nextChar = input[0];
unchecked
{
if (nextChar == CharNegative)
{
isNegative = true;
++currentIndex;
}
while (currentIndex < length)
{
nextChar = input[currentIndex++];
if (nextChar < '0' || nextChar > '9') return false;
result = result * 10 + (nextChar - '0');
}
if (isNegative)
{
result = -result;
return length < 11 || length <= 11 && result <= 0;
}
return length < 10 || length <= 10 && result >= 0;
}
}
</code></pre>
<blockquote>
<p>Native parser took <strong>13727 ms</strong>. Custom parser took <strong>2377 ms</strong>. Performance gain was <strong>477%</strong></p>
</blockquote>
<p><strong>Frequently Asked Questions</strong></p>
<blockquote>
<p>Is <code>Double.Parse</code> really your performance bottleneck?</p>
</blockquote>
<p>Yes! We benchmarked it in release mode and everything. We're ripping through billions of strings loaded into memory from a super-fast CSV reader, and calling native <code>Double.TryParse</code> was around ~70% of our execution time. More than I/O even.</p>
<blockquote>
<p>Then why are you using C#?</p>
</blockquote>
<p>It's much nicer for the 100 other things our app has to do that aren't performance critical.</p>
<blockquote>
<p>What's your benchmark code?</p>
</blockquote>
<p>Here it is. I'm pretty sure it's a good measure:</p>
<pre><code>const int iterations = 100000000;
string[] randomIntegers = Enumerable.Repeat(0, iterations )
.Select(i => generateRandomInput()).ToArray();
CultureInfo cachedCulture = CultureInfo.CurrentCulture;
Stopwatch timer = Stopwatch.StartNew();
foreach (string value in randomIntegers)
Int32.TryParse(value, nativeNumberStyles, cachedCulture, out T _);
Console.WriteLine($"Native parser took {timer.ElapsedMilliseconds} ms.");
timer.Restart();
foreach (string value in randomIntegers)
FastTryParseInt(value, out T _);
Console.WriteLine($"Custom parser took {timer.ElapsedMilliseconds} ms.");
</code></pre>
<p>Compiled and run as "Release|Any CPU" on a 64 bit machine.</p>
<p><strong>My Question</strong></p>
<p>Can we do better? Did I miss something in <code>unsafe</code> mode that can make it <em>way</em> better than boring, safe C#?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T21:24:33.763",
"Id": "387013",
"Score": "0",
"body": "Not sure on performance, but this is broke: `FastTryParseInt(4294967296)` will return `True / 0`. This works for `[4294967296,6442450943]`, `[8589934592,9999999999]`, `[-64424509... | [
{
"body": "<p>Like @202_accepted has mentioned in his comment you have a <strong>bug</strong> in your code which is hidden because of using unchecked in addition with your resulting condition. </p>\n\n<p>I would divide this algorithm into 3 branches. </p>\n\n<ul>\n<li><p>If the length of <code>input</code> is ... | {
"AcceptedAnswerId": null,
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T20:45:05.570",
"Id": "200935",
"Score": "6",
"Tags": [
"c#",
"performance",
"parsing",
"integer"
],
"Title": "Custom integer parser optimized for performance"
} | 200935 |
<p>I have a DataFrame with values in columns <code>a</code> and <code>b</code> and a third column with the count of that row. I would like to convert this into a DataFrame (either new or remake the old one) with columns <code>a</code> and <code>b</code> repeated the number of times as is in the count column. It's probably more clear with an example. I have this DataFrame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a' : [1,2,3], 'b' : [0,0,1], 'count' : [3,1,4]})
</code></pre>
<p>I am converting it like this:</p>
<pre><code>new_df = pd.DataFrame(columns=df.columns[:-1])
for _, row in df.iterrows():
num = row['count']
for i in range(num):
pd.concat([new_df, row])
new_df = new_df.append(row[:-1])
</code></pre>
<p>This does exactly what I want but seems inelegant to me because of the for-loop inside iterrows. Is there a better or more pythonic way to do this?</p>
| [] | [
{
"body": "<p>You are correct in thinking that <code>iterrows</code> is a very bad sign for Pandas code. Even worse is building up a DataFrame one row at a time like this with <code>pd.concat</code> - the performance implications are dreadful.</p>\n\n<p>Instead of reaching for loops, your first step should be t... | {
"AcceptedAnswerId": "200952",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T22:52:04.290",
"Id": "200945",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Python pandas: Take column of counts and create DataFrame with a row per count"
} | 200945 |
<p>Here is my code for the below packet time simulation problem using queue. My code works correctly but it's slow, please help with suggestions to improve run time and other suggestions for performance improvement.</p>
<p>Problem: You are given a series of incoming packets in an array of [t_a, t_d] pairs (one pair for each packet) where t_a is arrival time of the packet and t_d is the processing time required for that packet. The processor has a buffer with a fixed size and when full, packets are dropped. For each packet, output either the start of process time or -1 if the packet is dropped. Processor only processes one packet at the time and packet arrival times are non-decreasing.</p>
<p>eg. input of [ [0, 2], [1, 4], [5, 3] ] with buffer size of 2 gives output equal to [0, 2, 6].</p>
<pre><code>def process_packets(packets, buffSize):
# base case for packet size or buffSize == 0
if packets == [] or buffSize == 0:
return []
# initializing parameters:
# ts_te is array of [ts,te] pairs where ts = start of packet process time
# and te = end of packet process time
# length of ts_te array is treated as buffer size
ts_te = [ [ packets[0][0], packets[0][0] + packets[0][1] ] ]
# results is either start of packet process time (if packet makes it to buffer)
# or -1 for packets when buffer is full at their arrival time
results = [ ts_te[0][0] ]
# since first packet is processed in initialization, I remove it
packets = packets[1:]
for packet in packets:
packetArr = packet[0]
packetDur = packet[1]
# processor's start time is either end of last packet in buffer or
# new packet's arrival time, whichever is bigger
startTime = max ( ts_te[-1][1], packetArr )
# removing all packets that have been processed from buffer when new
# packet arrives
for elem in ts_te:
if packetArr >= elem[1]:
ts_te.pop(0)
# if there is room in the buffer, add new packets [ts,te] information
# and append process time start to result
if len(ts_te) < buffSize:
ts_te.append( [startTime , startTime+packetDur] )
results.append(startTime)
else:
results.append(-1)
return results
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T07:49:30.553",
"Id": "387047",
"Score": "1",
"body": "Could you add more examples to clarify? Does the buffer need to store the packet being processed or not? For example, if the buffer size is 1, and the inputs are (0, 2) and (1, 4... | [
{
"body": "<h2>Efficiency</h2>\n\n<p>Your algorithm is actually quite simple and efficient. Keeping track of the scheduled finish times for each packet in the buffer (using <code>ts_te</code>) is a great idea. The main problem is your poor choice of data structure for <code>ts_te</code>.</p>\n\n<p>Actually, e... | {
"AcceptedAnswerId": "200978",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T03:03:19.170",
"Id": "200950",
"Score": "4",
"Tags": [
"python",
"performance",
"queue",
"simulation"
],
"Title": "Packet process time simulation using queue"
} | 200950 |
<p>First of all, I have my basic main method which does pretty much nothing:</p>
<pre><code>public static void main(String[] args) {
higherOrLower HOL = new higherOrLower();
HOL.playGame();
}
</code></pre>
<p>Then I have the class and methods where all the action happens:</p>
<pre><code>import java.util.Arrays;
import java.util.Scanner;
public class higherOrLower {
int set[] = new int[8];
private int flips = 1;
public higherOrLower() {
deck deck = new deck();
for (int i = 0; i < 8; i++) {
set[i] = deck.draw();
}
}
public void playGame() {
Scanner sc = new Scanner(System.in);
paint();
for (int i = 0; i < 7; i++) {
System.out.println("Higher or Lower?");
String an = sc.nextLine();
switch (an) {
case "Higher":
case "higher":
case "H":
case "h":
if (set[i] > set[i + 1]) {
System.out.println("You Lose");
endGame();
}
break;
case "Lower":
case "lower":
case "L":
case "l":
if (set[i] < set[i + 1]) {
System.out.println("You Lose");
endGame();
}
break;
default:
System.out.println("Please enter one of the following \nHigher\nhigher\nH\nh\nLower\nlower\nL\nl");
i--;
break;
}
flips++;
paint();
}
System.out.println("You win!");
endGame();
}
public static void playAgain() {
higherOrLower HOL = new higherOrLower();
HOL.playGame();
}
public void flip() {
flips++;
}
void endGame() {
Scanner sc = new Scanner(System.in);
System.out.println("Play again?");
boolean done = false;
while(!done){
String ans = sc.nextLine();
switch (ans) {
case "Yes":
case "yes":
case "Y":
case "y":
done = true;
playAgain();
break;
case "No":
case "no":
case "N":
case "n":
done = true;
System.exit(0);
break;
default:
System.out.println("Please enter one of the following \nYes\nyes\nY\ny\nNo\nno\nN\nn");
break;
}
}
}
public void paint() {
if (flips == 1) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
}
if (flips == 2) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(set[1], i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
}
if (flips == 3) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(set[1], i);
System.out.print(" ");
graphics(set[2], i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
}
if (flips == 4) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(set[1], i);
System.out.print(" ");
graphics(set[2], i);
System.out.print(" ");
graphics(set[3], i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
}
if (flips == 5) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(set[1], i);
System.out.print(" ");
graphics(set[2], i);
System.out.print(" ");
graphics(set[3], i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(set[4], i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
}
if (flips == 6) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(set[1], i);
System.out.print(" ");
graphics(set[2], i);
System.out.print(" ");
graphics(set[3], i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(set[4], i);
System.out.print(" ");
graphics(set[5], i);
System.out.print(" ");
graphics(-1, i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
}
if (flips == 7) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(set[1], i);
System.out.print(" ");
graphics(set[2], i);
System.out.print(" ");
graphics(set[3], i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(set[4], i);
System.out.print(" ");
graphics(set[5], i);
System.out.print(" ");
graphics(set[6], i);
System.out.print(" ");
graphics(-1, i);
System.out.println("");
}
}
if (flips == 8) {
for (int i = 0; i < 8; i++) {
graphics(set[0], i);
System.out.print(" ");
graphics(set[1], i);
System.out.print(" ");
graphics(set[2], i);
System.out.print(" ");
graphics(set[3], i);
System.out.println("");
}
System.out.println("");
System.out.println("");
for (int i = 0; i < 8; i++) {
graphics(set[4], i);
System.out.print(" ");
graphics(set[5], i);
System.out.print(" ");
graphics(set[6], i);
System.out.print(" ");
graphics(set[7], i);
System.out.println("");
}
}
}
void graphics(int card, int row) {
switch (card) {
case 1:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|A.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......A|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 2:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|2.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......2|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 3:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|3.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......3|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 4:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|4.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......4|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 5:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|5.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......5|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 6:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|6.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......6|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 7:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|7.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......7|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 8:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|8.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......8|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 9:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|9.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......9|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 10:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|10......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|......10|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 11:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|J.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......J|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 12:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|Q.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......Q|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 13:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("|K.......|");
break;
case 3:
System.out.print("|........|");
break;
case 4:
System.out.print("|....֍...|");
break;
case 5:
System.out.print("|........|");
break;
case 6:
System.out.print("|.......K|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case -1:
switch (row) {
case 1:
System.out.print(" ________ ");
break;
case 2:
System.out.print("| |");
break;
case 3:
System.out.print("|\\//\\/\\/\\|");
break;
case 4:
System.out.print("|/\\/\\/\\/\\|");
break;
case 5:
System.out.print("|\\//\\/\\/\\|");
break;
case 6:
System.out.print("|/\\/\\/\\/\\|");
break;
case 7:
System.out.print("|________|");
break;
}
break;
case 0:
System.out.println("000000000000000000000000000000000000000");
default:
System.out.println("error?");
}
}
}
</code></pre>
<p>And after that I have one other class, the deck:</p>
<pre><code>public class deck {
public int deck[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
public deck() {
shuffle();
}
private void shuffle() {
Random rnd = ThreadLocalRandom.current();
for (int i = deck.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int a = deck[index];
deck[index] = deck[i];
deck[i] = a;
}
}
public int draw(){
int top = 0;
for (int i = 0; i < 52; i++) {
if(deck[i]!=0){
top = deck[i];
deck[i] = 0;
break;
}
}
return top;
}
@Override
public String toString(){
String temp = "[";
for (int i = 0; i < 51; i++) {
temp = temp + deck[i]+",";
}
temp = temp + deck[51] + "]";
return temp;
}
}
</code></pre>
<p>What do you think? Could I have done anything better?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T15:52:14.793",
"Id": "387068",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>I can't give special improvements for performance in general, but I can give you a first impression of your code and some improvements I would take:</p>\n\n<p><strong>playGame and endGame Method</strong></p>\n\n<p>First for a plain true/false or a/b decision based on terminal input like you use it... | {
"AcceptedAnswerId": "200960",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T04:20:14.283",
"Id": "200951",
"Score": "5",
"Tags": [
"java",
"performance",
"game",
"playing-cards"
],
"Title": "Java version of card game \"higher or lower\""
} | 200951 |
<p>I have written a disassembler for Intel 8080, able to translate binaries into opcodes and parameters. Sorry for posting so much code, but everything posted here is useful for the understanding of the code (and I hope that you will criticize all of it too).
Thanks a lot for your time.</p>
<p><code>FileReaderHelper</code> holds some functions that help with reading and parsing.</p>
<p><em>FileReaderHelper.h</em></p>
<pre><code>#include <vector>
#include <string>
class FileReaderHelper
{
public:
static const std::vector<std::string> splitString(const std::string& toSplit, char delimiter);
static const int hexStringToInt(const std::string& toSplit);
static const std::vector<unsigned char> loadBinaryFile(const std::string& filepath);
};
</code></pre>
<p><em>FileReaderHelper.cpp</em></p>
<pre><code>#include "FileReaderHelper.h"
#include <sstream>
#include <fstream>
#include <iterator>
const std::vector<std::string> FileReaderHelper::splitString(const std::string& toSplit, char delimiter)
{
std::istringstream iss(toSplit);
std::vector<std::string> results;
std::string s;
while (std::getline(iss, s, delimiter)) {
results.emplace_back(s);
}
return results;
}
const int FileReaderHelper::hexStringToInt(const std::string& input)
{
std::stringstream stringToHex;
stringToHex << std::hex << input;
int hexValue = 0;
stringToHex >> hexValue;
return hexValue;
}
const std::vector<unsigned char> FileReaderHelper::loadBinaryFile(const std::string& filepath)
{
std::ifstream inputStream(filepath, std::ios::binary);
std::vector<unsigned char> result(std::istreambuf_iterator<char>{inputStream}, {});
return result;
}
</code></pre>
<p>The <code>OpCodeCatalog</code> class contains all the OpCodes, parsed from a text file that contains lines like these (it is much more readable with tabs indentation):</p>
<pre><code>0xc0 RNZ 1 if NZ, RET
0xc1 POP B 1 C <- (sp) B <- (sp+1) sp <- sp+2
0xc2 JNZ $%02x%02x 3 if NZ, PC <- adr
0xc3 JMP $%02x%02x 3 PC <= adr
0xc4 CNZ $%02x%02x 3 if NZ, CALL adr
0xc5 PUSH B 1 (sp-2)<-C (sp-1)<-B sp <- sp - 2
0xc6 ADI #%02x 2 Z, S, P, CY, AC A <- A + byte
0xc7 RST 0 1 CALL $0
</code></pre>
<p><em>OpCodeCatalog.h</em></p>
<pre><code>#include <string>
#include <vector>
#include "OpCode.h"
class OpCodeCatalog
{
private:
public:
OpCodeCatalog(const std::string& filename);
void loadCatalog(const std::string& filename);
const OpCode& getOpCode(int code) const;
size_t getOpCodeCount() const noexcept;
private:
std::vector<OpCode> opCodes;
};
</code></pre>
<p><em>OpCodeCatalog.cpp</em></p>
<pre><code>#include "OpCodeCatalog.h"
#include <fstream>
#include <sstream>
#include <iterator>
#include <string>
#include "File\FileReaderHelper.h"
OpCodeCatalog::OpCodeCatalog(const std::string& filename)
{
loadCatalog(filename);
}
void OpCodeCatalog::loadCatalog(const std::string& filename)
{
opCodes.clear();
std::ifstream input(filename);
for(std::string line; std::getline(input, line);)
{
const auto tokens = FileReaderHelper::splitString(line, ' ');
if (tokens.size() < 3) {
throw "Malformed catalog line: " + line;
}
opCodes.emplace_back(OpCode{ FileReaderHelper::hexStringToInt(tokens[0]),
std::stoi(tokens[2], nullptr, 10),
tokens[1] });
}
}
const OpCode& OpCodeCatalog::getOpCode(int code) const
{
if (code < 0 || code >= opCodes.size())
{
throw std::invalid_argument("OpCode value outside the range of the catalog. Value: " + code);
}
return opCodes[code];
}
size_t OpCodeCatalog::getOpCodeCount() const noexcept
{
return opCodes.size();
}
</code></pre>
<p>The <code>OpCode</code> class holds the informations for one OpCode: its code and byte count. It can also generate the associated assembly line using the template string.</p>
<p><em>OpCode.h</em></p>
<pre><code>#include <string>
#define OPCODE_TEMPLATE_MAX_LENGTH 32
class OpCode
{
public:
OpCode(int code, int byteCount, std::string resultTemplate);
constexpr int getCode() const noexcept
{
return code;
}
constexpr int getByteCount() const noexcept
{
return byteCount;
}
const std::string getGeneratedAsm() const;
const std::string getGeneratedAsm(int v1) const;
const std::string getGeneratedAsm(int v1, int v2) const;
private:
const int code;
const int byteCount;
const std::string resultTemplate;
};
</code></pre>
<p><em>OpCode.cpp</em></p>
<pre><code>#include "OpCode.h"
OpCode::OpCode(int code, int byteCount, std::string resultTemplate) :
code{ code },
byteCount{ byteCount },
resultTemplate{ resultTemplate }
{
if (resultTemplate.length() > OPCODE_TEMPLATE_MAX_LENGTH)
{
throw std::invalid_argument("This template string is too long: " + resultTemplate);
}
}
const std::string OpCode::getGeneratedAsm() const
{
return resultTemplate;
}
const std::string OpCode::getGeneratedAsm(int v1) const
{
char temp[OPCODE_TEMPLATE_MAX_LENGTH];
std::snprintf(temp, OPCODE_TEMPLATE_MAX_LENGTH, resultTemplate.c_str(), v1);
return std::string(temp);
}
const std::string OpCode::getGeneratedAsm(int v1, int v2) const
{
char temp[OPCODE_TEMPLATE_MAX_LENGTH];
std::snprintf(temp, OPCODE_TEMPLATE_MAX_LENGTH, resultTemplate.c_str(), v1, v2);
return std::string(temp);
}
</code></pre>
<p>The <code>AssemblyLine</code> class holds all the information of a line of assembly language (code, parameters, bytecount).</p>
<p><em>AssemblyLine.h</em></p>
<pre><code>#pragma once
#include "Source\OpCode.h"
class AssemblyLine
{
public:
AssemblyLine(uint8_t code, uint8_t byteCount);
AssemblyLine(uint8_t code, uint8_t byteCount, const uint8_t param1);
AssemblyLine(uint8_t code, uint8_t byteCount, const uint8_t param1, const uint8_t param2);
uint8_t getParam1() const;
uint8_t getParam2() const;
uint8_t getCode() const;
uint8_t getByteCount() const;
protected:
const uint8_t byteCount;
const uint8_t code;
const uint8_t param1;
const uint8_t param2;
};
</code></pre>
<p><em>AssemblyLine.cpp</em></p>
<pre><code>#include "AssemblyLine.h"
AssemblyLine::AssemblyLine(uint8_t code, uint8_t byteCount) :
code(code),
byteCount(byteCount),
param1(0),
param2(0)
{
}
AssemblyLine::AssemblyLine(uint8_t code, uint8_t byteCount, const uint8_t param1) :
code(code),
byteCount(byteCount),
param1(param1),
param2(0)
{
}
AssemblyLine::AssemblyLine(uint8_t code, uint8_t byteCount, const uint8_t param1, const uint8_t param2) :
code(code),
byteCount(byteCount),
param1(param1),
param2(param2)
{
}
uint8_t AssemblyLine::getParam1() const
{
return param1;
}
uint8_t AssemblyLine::getParam2() const
{
return param2;
}
uint8_t AssemblyLine::getCode() const
{
return code;
}
uint8_t AssemblyLine::getByteCount() const
{
return byteCount;
}
</code></pre>
<p>Last but not least, <code>Disassembler</code> is the interface that use all the previous classes to provide the user with meaningful information.</p>
<p><em>Disassembler.h</em></p>
<pre><code>#pragma once
#include "Source\OpCodeCatalog.h"
#include "AssemblyLine.h"
class Disassembler
{
public:
Disassembler(const OpCodeCatalog& catalog);
const std::vector<AssemblyLine> disasemble(const std::vector<unsigned char>& data);
const AssemblyLine disasembleOneCode(const std::vector<unsigned char>& data, size_t codeIndex);
private:
const OpCodeCatalog& catalog;
};
</code></pre>
<p><em>Disassembler.cpp</em></p>
<pre><code>#include "Disassembler.h"
Disassembler::Disassembler(const OpCodeCatalog& catalog) :
catalog{ catalog }
{
}
const std::vector<AssemblyLine> Disassembler::disasemble(const std::vector<unsigned char>& data)
{
size_t currentId = 0;
std::vector<AssemblyLine> disasembledCode;
for (; currentId < data.size() - 1;)
{
const auto asmLine = disasembleOneCode(data, currentId);
currentId += asmLine.getByteCount();
disasembledCode.emplace_back(asmLine);
}
return disasembledCode;
}
const AssemblyLine Disassembler::disasembleOneCode(const std::vector<unsigned char>& data, size_t codeIndex)
{
int codeValue = data[codeIndex];
const auto& opCode = catalog.getOpCode(codeValue);
const auto byteCount = opCode.getByteCount();
switch (byteCount) {
default:
case 1:
return AssemblyLine(opCode.getCode(), opCode.getByteCount());
break;
case 2:
return AssemblyLine(opCode.getCode(), opCode.getByteCount(), data[codeIndex + 1]);
break;
case 3:
return AssemblyLine(opCode.getCode(), opCode.getByteCount(), data[codeIndex + 2], data[codeIndex + 1]);
break;
}
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>C++ is not Java. While there is a valid use-case for classes treated as namespaces with a type-name, that's only for traits-classes used with templates, and not for general consumption.</p></li>\n<li><p>I don't know why, but you seem quite attached to \"a class for everything\" and \"eve... | {
"AcceptedAnswerId": "200992",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T09:53:07.140",
"Id": "200957",
"Score": "10",
"Tags": [
"c++",
"file-system",
"assembly",
"c++17"
],
"Title": "Disassembler for intel 8080"
} | 200957 |
<p>I wrote this function in order to create unique url's for my site. Using these urls, visitors could demo site functionality without having to create a login. The function was intended to return a unique string of characters which could be added to a url like this:</p>
<p><a href="http://www.mysite.com?temp_user=dd5vbrk4ax4v4o09l2bm" rel="nofollow noreferrer">http://www.mysite.com?temp_user=dd5vbrk4ax4v4o09l2bm</a></p>
<p>My function had the following criteria:</p>
<ol>
<li>Every call must generate a unique string of alpha numeric characters.</li>
<li>Most important: Zero chance of string duplication.</li>
<li>It should be 20 characters long (secure, but not awkwardly long.)</li>
<li>Repeat calls should reflect a high degree of dissimilarity.</li>
<li>Character usage should appear as random as possible.</li>
</ol>
<p>Here is my code </p>
<pre><code>function url_code(){
$letters = "1234567890abcdefghijklmnopqrstuvwxyz";
$microtime = microtime();
$time_array = explode(' ', substr($microtime,2));
$code = '';
$time_array[0] = substr($time_array[0],0,6);
$time_array[0] .= strrev($time_array[0]);
$time_array[2] = strrev($time_array[1]);
for($i = 0; $i <10; $i++){
$num = ((int)$time_array[1][$i]);
$num += ((int)$time_array[2][$i])*10;
$num += ((int)$time_array[0][$i])*100;
$mult = (int)($num / 36);
$mod = $num - ($mult * 36);
$code .= $letters[$mult].$letters[$mod];
}
return $code;
}
</code></pre>
<p>Please let me know if there are any simple improvements I could make or if I missed any serious problems with string repetition.</p>
<p>One interesting note on character randomness: currently, characters generated by the $mult variable (the first, third, fifth, and other odd character in the code string) will never be t,u,v,w,x,y, or z. How can I fix this so that [t-z] are also used?</p>
<p>Possible fix (all characters will be used. However, [8-9a-s] are twice as likely to appear as the other characters, [0-7t-z]):</p>
<pre><code>$mult = (int)($num / 36);
$mod = $num - ($mult * 36);
if($mult < 9 && mt_rand(0,1)){$mult += 27;}
$code .= $letters[$mult].$letters[$mod];
</code></pre>
<p>Note, Scalability issue found: If this function is run on more than one server, there is a tiny chance that two users could send a request at exactly the same time and get a duplicated code. </p>
| [] | [
{
"body": "<p>I would rather use the integrated md5 funcion that should be faster. \nIn case it s too long. The string could be shorten.\nBy the end. There s a probability that the same string is to be generated twice... so bigger is the string and lower is that probability.</p>\n",
"comments": [
{
... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T14:46:19.513",
"Id": "200962",
"Score": "5",
"Tags": [
"php",
"strings",
"random"
],
"Title": "Function for creating unique strings for urls"
} | 200962 |
<p>So, I've been working on a very simple MVC framework and I wanted some feedback on how it works. I've worked it slightly differently where the controllers don't need to extend the base <code>Controller</code> class (I really didn't see the need to).</p>
<p>Firstly, you'll see the main classes <code>Controller.php</code>, <code>View.php</code> and <code>index.php</code>.</p>
<p><strong>Controller.php</strong></p>
<pre><code>class Controller {
public function __construct($module)
{
$class = implode('', array_map('ucwords', explode('-', $module)));
$model = MODELS . $class . '.php';
$controller = CONTROLLERS . $class . '.php';
if (file_exists($controller) && file_exists($model)) {
require_once $controller;
require_once $model;
$ctrl = '\ctrl\\' . $class;
$model = '\model\\' . $class;
require_once VIEWS . DS . 'partials' . DS . 'header.php';
new $ctrl(new $model(), new View());
require_once VIEWS . DS . 'partials' . DS . 'footer.php';
}
}
}
</code></pre>
<p><strong>View.php</strong></p>
<pre><code>class View {
public function __construct()
{
$this->view = null;
$this->data = [];
}
public function load($view)
{
if (!file_exists($view))
exit('View 404: ' . $view);
$this->view = $view;
}
public function set($k, $v)
{
$this->data[$k] = $v;
}
public function get($k)
{
return $this->data[$k];
}
public function render()
{
extract($this->data);
ob_start();
require_once $this->view;
echo ob_get_clean();
}
}
</code></pre>
<p><strong>index.php</strong></p>
<pre><code><?php
session_start();
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', __DIR__ . DS);
define('SRC', __DIR__ . DS . 'src' . DS);
define('VIEWS', __DIR__ . DS . 'app' . DS . 'views' . DS);
define('MODELS', __DIR__ . DS . 'app' . DS . 'models' . DS);
define('CONTROLLERS', __DIR__ . DS . 'app' . DS . 'controllers' . DS);
spl_autoload_register(function ($class_name) {
$core = SRC . 'core' . DS . $class_name . '.php';
$app = SRC . 'app' . DS . $class_name . '.php';
if (file_exists($core)) {
require_once $core;
} else if (file_exists($app)) {
require_once $app;
} else {
exit('Class 404: ' . $class_name);
}
});
if (isset($_GET['module'])) {
$module = $_GET['module'];
$ctrl = new Controller($module);
} else {
$ctrl = new Controller('sign-in');
}
</code></pre>
<p>Now we have an actual example:</p>
<pre><code>app
models
controllers
views
partials
header.php
footer.php
sign-in.php
</code></pre>
<p><strong>sign-in.php (View)</strong></p>
<pre><code><h1><?= $title ?></h1>
<form method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="sign-in" />
</form>
<?php if (isset($errors)) : ?>
<?php foreach ($errors as $error) : ?>
<li style="font-weight: bold; color: red;">
<?= $error ?>
</li>
<?php endforeach ?>
<?php endif ?>
</code></pre>
<p><strong>SignIn (Controller)</strong></p>
<pre><code><?php
namespace ctrl;
class SignIn {
private $tpl = VIEWS . 'sign-in.php';
public function __construct($model, $view)
{
$this->model = $model;
$this->view = $view;
$view->load($this->tpl);
if (isset($_POST['sign-in'])) {
$this->sign_in();
}
$this->render();
}
public function render()
{
$this->view->set('title', 'Sign In');
$this->view->render();
}
public function sign_in()
{
$errors = [];
if (!isset($_POST['username']) || empty(trim($_POST['username']))) {
$errors[] = 'Username is empty';
}
if (!isset($_POST['password']) || empty(trim($_POST['password']))) {
$errors[] = 'Password is empty';
}
if (empty($errors)) {
$this->model->find();
} else {
$this->view->set('errors', $errors);
}
}
}
</code></pre>
<p><strong>Model (Model)</strong></p>
<pre><code><?php
namespace model;
class SignIn {
public function find()
{
echo 'found';
}
}
</code></pre>
<p>I understand the error reporting / validation can be improved for example from the <code>exit</code> to actual logging along with environment management and the code cann be tidied up but I'm mainly looking for feedback on how the base controller and view class interacts with rest of the system.</p>
| [] | [
{
"body": "<p>Ill just jump right in; </p>\n\n<h2>Composer To The Rescue</h2>\n\n<p>So you have attempted autoloading, thats great! But by modern standards you should be using composer to; </p>\n\n<ol>\n<li>Manage your dependecies</li>\n<li>Manage autoloading your namespaces </li>\n</ol>\n\n<p><a href=\"https:/... | {
"AcceptedAnswerId": "201003",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T15:48:28.573",
"Id": "200968",
"Score": "1",
"Tags": [
"php",
"mvc"
],
"Title": "Custom MVC framework"
} | 200968 |
<p>I use ASP.NET Core 2.1 and would like to fetch <code>User</code> at a <strong>service level</strong>.</p>
<p>I've seen examples when <code>HttpContextAccessor</code> gets injected into some service and then we fetch the current <code>User</code> via <code>UserManager</code></p>
<pre><code>var user = await _userManager.GetUserAsync(accessor.HttpContext.User);
</code></pre>
<p>or in controller</p>
<pre><code>var user = await _userManager.GetUserAsync(User);
</code></pre>
<hr>
<p>Problems:</p>
<ul>
<li><p>Injecting <code>HttpContextAccessor</code> into service seems to be <strong>wrong</strong> - simply because we violate SRP and the <em>Service Layer</em> isn't isolated (it is dependant on <em>http context</em>).</p></li>
<li><p>We can of course <strong>fetch user in a controller</strong> (a somewhat better approach), but we face a dilemma - we simply don't want to pass <code>User</code> as parameter in every single service method</p></li>
</ul>
<hr>
<h2>I spent a few hours thinking about how best to implement it and have come up with a solution.</h2>
<p>I'm just not entirely sure my approach is adequate and doesn't violate any of the software-design principles.</p>
<p><strong>Sharing my code in hopes to get recommendations from StackOverflow community.</strong></p>
<p>The idea is the following:</p>
<p>First, I introduce <code>SessionProvider</code> which is registered as Singleton.</p>
<pre><code>services.AddSingleton<SessionProvider>();
</code></pre>
<p><code>SessionProvider</code> has a <code>Session</code> property which holds <code>User</code>, <code>Tenant</code>, etc.</p>
<p>Secondly, I introduce <code>SessionMiddleware</code> and register it</p>
<pre><code>app.UseMiddleware<SessionMiddleware>();
</code></pre>
<p>In the <code>Invoke</code> method I resolve <code>HttpContext</code>, <code>SessionProvider</code> & <code>UserManager</code>.</p>
<ul>
<li><p>I fetch <code>User</code></p></li>
<li><p>Then I initialise <code>Session</code> property of <code>ServiceProvider</code> singleton:</p></li>
</ul>
<p><code>sessionProvider.Initialise(user);</code></p>
<p>At this stage <code>ServiceProvider</code> has <code>Session</code> object containing the info we need.</p>
<p>Now we inject <code>SessionProvider</code> into any service and its <code>Session</code> object is ready for use.</p>
<hr>
<p><strong>Code:</strong></p>
<p><code>SessionProvider</code>:</p>
<pre><code>public class SessionProvider
{
public Session Session;
public SessionProvider(
)
{
Session = new Session();
}
public void Initialise(ApplicationUser user)
{
Session.User = user;
Session.UserId = user.Id;
Session.Tenant = user.Tenant;
Session.TenantId = user.TenantId;
Session.Subdomain = user.Tenant.HostName;
}
}
</code></pre>
<p><code>Session</code>:</p>
<pre><code>public class Session
{
public ApplicationUser User { get; set; }
public Tenant Tenant { get; set; }
public long? UserId { get; set; }
public int? TenantId { get; set; }
public string Subdomain { get; set; }
}
</code></pre>
<p><code>SessionMiddleware</code>:</p>
<pre><code>public class SessionMiddleware
{
private readonly RequestDelegate next;
public SessionMiddleware(RequestDelegate next)
{
this.next = next ?? throw new ArgumentNullException(nameof(next));
}
public async Task Invoke(
HttpContext context,
SessionProvider sessionProvider,
MultiTenancyUserManager<ApplicationUser> userManager
)
{
await next(context);
var user = await userManager.GetUserAsync(context.User);
if (user != null)
{
sessionProvider.Initialise(user);
}
}
}
</code></pre>
<p>And now <strong>Service Layer</strong> code:</p>
<pre><code>public class BaseService
{
public readonly AppDbContext Context;
public Session Session;
public BaseService(
AppDbContext context,
SessionProvider sessionProvider
)
{
Context = context;
Session = sessionProvider.Session;
}
}
</code></pre>
<p>So this is the <em>base</em> class for any service, as you can see we can now fetch <code>Session</code> object easily and it's ready for use:</p>
<pre><code>public class VocabularyService : BaseService, IVocabularyService
{
private readonly IVocabularyHighPerformanceService _vocabularyHighPerformanceService;
private readonly IMapper _mapper;
public VocabularyService(
AppDbContext context,
IVocabularyHighPerformanceService vocabularyHighPerformanceService,
SessionProvider sessionProvider,
IMapper mapper
) : base(
context,
sessionProvider
)
{
_vocabularyHighPerformanceService = vocabularyHighPerformanceService;
_mapper = mapper;
}
public async Task<List<VocabularyDto>> GetAll()
{
List<VocabularyDto> dtos = _vocabularyHighPerformanceService.GetAll(Session.TenantId.Value);
dtos = dtos.OrderBy(x => x.Name).ToList();
return await Task.FromResult(dtos);
}
}
</code></pre>
<p>Focus on the following bit:</p>
<pre><code>.GetAll(Session.TenantId.Value);
</code></pre>
<p>also, we can easily get current user</p>
<pre><code>Session.UserId.Value
</code></pre>
<p>or</p>
<pre><code>Session.User
</code></pre>
<p><strong>Update 1</strong> - <code>VocabularyController.cs</code></p>
<pre><code>[Route("api/[controller]/[action]")]
[Authorize]
public class VocabularyController : ControllerBase
{
private readonly IVocabularyService _vocabularyService;
public VocabularyController(
IVocabularyService vocabularyService
)
{
_vocabularyService = vocabularyService;
}
public async Task<List<VocabularyDto>> GetAll()
{
var result = await _vocabularyService.GetAll();
return result;
}
}
</code></pre>
<p>So, that's it.</p>
<p><em>I tested my code and it works well when several tabs are open - each tab has different subdomain in url</em>.</p>
<p><em>(Tenant is resolved from subdomain - the data is being fetched correctly)</em></p>
<hr>
<p><strong>Maybe some of you have a better idea of how to implement this?</strong></p>
<p>Thanks in advance!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T17:40:08.630",
"Id": "387083",
"Score": "1",
"body": "_from StackOverflow community_ - have you cross-posted it? This is Code Review ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T17:41:29.347",
... | [
{
"body": "<p>Here's a better workaround in my opinion - we no longer make a DB call <strong>per every single request</strong>, we just retrieve UserID & TenantID from Claims instead:</p>\n\n<p>Please note that the lifetime of <code>SessionContext</code> is Per Request - when the request starts we hook into... | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T17:34:34.263",
"Id": "200973",
"Score": "7",
"Tags": [
"c#",
"asp.net",
"asp.net-core"
],
"Title": "asp.net core - get User at Service Layer"
} | 200973 |
<p>I am a student and I am implementing data structures concept by myself using C and C++.</p>
<p>I have implemented the concept of hash table here by making a "Phone book" program that takes input which includes the user's name and his phone number and saves the data in the hash table.</p>
<p>The implementation covers insertion and searching operation. Collisions are also handled in this program by implementing the "chaining" concept.</p>
<p>The hasTable structure contains the basic <strong>key</strong> and <strong>value</strong> variables as well as the other two:</p>
<p><strong>isEmpty</strong>: for checking if the slot in the table is filled or is Empty.</p>
<p><strong>next</strong>: for storing data when collision happens. (chaining concept)</p>
<p>Can someone please review it and let me know of anything I should improve? Like in terms of optimizations, standard practices or how to cover boundary/error condition?</p>
<pre><code>#include<iostream>
#include<cstring>
using namespace std;
struct hashTable{
string key;
int64_t value;
bool isEmpty=true;
hashTable *next;
};
class Contacts{
int num; //number of entries
hashTable *phoneBook;
public:
Contacts():phoneBook(NULL){
}
void ins(){
int index;
int64_t phoneNumber;
string name;
cout<<"enter number of entries: ";
cin>>num;
phoneBook=new hashTable[num];
cout<<"Enter name and phone number respectively:"<<endl;
for(int i=0;i<num;i++){
cin>>name>>phoneNumber;
index=hashing(name,num);
if(phoneBook[index].isEmpty){ //if the slot is empty(no collision)...
phoneBook[index].key=name;
phoneBook[index].value=phoneNumber;
phoneBook[index].isEmpty=false; //it is now filled...
phoneBook[index].next=NULL;
}
else{ //in case of collision...
hashTable *temp=&(phoneBook[index]);
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=new hashTable;
temp->next->key=name;
temp->next->value=phoneNumber;
temp->next->isEmpty=false;
temp->next->next=NULL;
}
}
}
int hashing(string name,int n){
int len,sum=0;
//converting string into char array...
len=name.length();
char temp[len+1];
strcpy(temp,name.c_str());
//calculating hash value...
for(int i=0;i<len;i++){
sum=sum+temp[i];
}
return (sum%n);
}
void searchContact(string name){
int check;
check=hashing(name,num);
if(phoneBook[check].next==NULL){ //if there is no collision seen in the current block..
if(phoneBook[check].key==name){
cout<<"Name: "<<phoneBook[check].key<<endl;
cout<<"Phone number: "<<phoneBook[check].value<<endl;
}
else{
cout<<"Not found"<<endl;
}
}
else{ //if collision is seen in the current block...
hashTable *temp=&(phoneBook[check]);
while(temp!=NULL){
if(temp->key==name){
cout<<"Name: "<<temp->key<<endl;
cout<<"Phone number: "<<temp->value<<endl;
break;
}
else
temp=temp->next;
}
if(temp==NULL)
cout<<"Not found"<<endl;
}
}
~Contacts(){
delete []phoneBook;
}
};
int main(){
string name;
int n;
Contacts d1;
d1.ins();
cout<<"Enter number of names you want to search: ";
cin>>n;
cout<<"Enter names: "<<endl<<endl;
for(int i=1;i<=n;i++){
cin>>name;
d1.searchContact(name);
cout<<endl;
}
}
</code></pre>
| [] | [
{
"body": "<h3>Separate responsibilities</h3>\n\n<p>Key concepts are not separated well.\nThe functionality of the hash table and user interaction are all mixed up and spread out across the various functions of the program.</p>\n\n<p>I propose a different program organization where the responsibilities are sepa... | {
"AcceptedAnswerId": "201001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T20:14:43.400",
"Id": "200979",
"Score": "6",
"Tags": [
"c++",
"beginner",
"hash-map"
],
"Title": "Phone book program using hash table in C++"
} | 200979 |
<p>I've implemented a simple AVL binary search tree. For no real reason I decided to implement this without multiplicity, so if we try to insert(5) twice, it's only stored once in the tree. I've also left out the in-order traversal and a few other methods I want to use this for, because I want to implement those elsewhere and just have the tree itself here. </p>
<p>I'd appreciate any and all comments relating to anything from how the code runs to how easy/difficult it is to read and maintain. I can take a beating - I'm new at this and want to improve as much as possible. Thanks in advance for your help.</p>
<pre><code>#pragma once
#include "stdafx.h"
#include <cstdlib>
#include <algorithm> // For std::max. I only use it in one place. Should implement it myself in like 1 line. "(a < b) ? a b" sort of thing.
template <class T>
struct Vertex {
T m_value;
int height;
Vertex * left;
Vertex * right;
Vertex * parent;
Vertex(T tee) { m_value = tee; height = 0; left = NULL; right = NULL; parent = NULL; }
};
template <class T> // The only property we need is that T admits a total ordering. User-made classes work as long as '<' is defined for them.
class AVL_Tree {
private:
Vertex<T> * m_root;
public:
AVL_Tree<T>() { m_root = NULL; }
Vertex<T> * findValue(T n) { // Finds the value 'n' in the tree and returns a pointer to the vertex containing it, or NULL if it doesn't exist.
Vertex<T> * current = m_root;
if (m_root == NULL)
return NULL; // If the tree is empty, return NULL
while (current != NULL) {
if (current->m_value == n) // Walk down the tree doing binary search. If we find 'x', return a pointer to the vertex containing it.
return current;
else if (n > current->m_value)
current = current->right;
else if (n < current->m_value)
current = current->left;
} // If this loop terminates without returning anything, then x is not in the tree.
return NULL;
}
bool isInTree(T x) {
return (this->findValue(x) != NULL); // x is in the tree if and only if findValue returns something different from NULL
}
bool isLeaf(Vertex<T> * X) {
if (X == NULL)
return false; // null pointers aren't leaves
return ((X->left == NULL) && (X->right == NULL)); // X is a leaf if and only if both children are null
}
int getHeight(Vertex<T> * X) {
if (X == NULL)
return -1;
else
return X->height;
}
int leftHeight(Vertex<T> * X) { return getHeight(X->left); }
int rightHeight(Vertex<T> * X) { return getHeight(X->right); }
void updateHeight(Vertex<T> * X) { // Updates the height of the vertex X by adding 1 to the max of the heights of its children
X->height = std::max(getHeight(X->left), getHeight(X->right)) + 1;
}
// Next four methods: Rotations for AVL update. I forgot a few pointers the first time around, which resulted in the tree not working as intended.
void right_rotate(Vertex<T> * X) {
Vertex<T> * Y = X->left;
Vertex<T> * Z = X->parent;
if (Z != NULL) {
if (Z->left == X)
Z->left = Y;
else if (Z->right == X)
Z->right = Y;
}
X->left = Y->right; // There's no way Y is NULL since X is left-heavy whenever we call this method.
Y->right = X;
Y->parent = Z;
X->parent = Y;
updateHeight(X);
updateHeight(Y);
}
void other_right_rotate(Vertex<T> * X) {
Vertex<T> * Y = X->left;
Vertex<T> * B = Y->right;
Vertex<T> * Z = X->parent;
if (Z != NULL) {
if (Z->left == X)
Z->left = B;
else if (Z->right == X)
Z->right = B;
}
Vertex<T> * b1 = B->left;
Vertex<T> * b2 = B->right;
Y->right = b1;
X->left = b2;
B->left = Y;
B->right = X;
B->parent = Z;
Y->parent = B;
X->parent = B;
if (b1 != NULL)
b1->parent = Y;
if (b2 != NULL)
b2->parent = X;
updateHeight(X);
updateHeight(Y);
updateHeight(B);
}
void left_rotate(Vertex<T> * X) {
Vertex<T> * Y = X->right;
Vertex<T> * Z = X->parent;
if (Z != NULL) {
if (Z->left == X)
Z->left = Y;
else if (Z->right == X)
Z->right = Y;
}
X->right = Y->left;
Y->left = X;
X->parent = Y;
Y->parent = Z;
updateHeight(X);
updateHeight(Y);
}
void other_left_rotate(Vertex<T> * X) {
Vertex<T> * Y = X->right;
Vertex<T> * B = Y->left;
Vertex<T> * Z = X->parent;
if (Z != NULL) {
if (Z->left == X)
Z->left = B;
else if (Z->right == X)
Z->right = B;
}
Vertex<T> * b1 = B->left;
Vertex<T> * b2 = B->right;
X->right = b1;
Y->left = b2;
if (b1 != NULL)
b1->parent = X;
if (b2 != NULL)
b2->parent = Y;
B->left = X;
B->right = Y;
B->parent = Z;
X->parent = B;
Y->parent = B;
updateHeight(X);
updateHeight(Y);
updateHeight(B);
}
void updateRoot(Vertex<T> * X) { // walks up the tree from X until hitting a vertex with no parent. Updates m_root to that vertex pointer.
Vertex<T> * current = X;
while (current->parent != NULL)
current = current->parent;
m_root = current;
}
void AVL_Update(Vertex<T> * X) { // Starting at X, work our way up to the root, performing rotations when necessary to preserve the AVL property.
while (X != NULL) {
updateHeight(X);
int leftrightdifference = leftHeight(X) - rightHeight(X);
if ((-1 <= leftrightdifference) && (leftrightdifference <= 1)) {} // Do nothing. This vertex is balanced.
else if (leftrightdifference == -2) {
Vertex<T> * Y = X->right;
if (leftHeight(Y) <= rightHeight(Y))
left_rotate(X);
else if (leftHeight(Y) > rightHeight(Y))
other_left_rotate(X);
}
else if (leftrightdifference == 2) {
Vertex<T> * Y = X->left;
if (rightHeight(Y) <= leftHeight(Y))
right_rotate(X);
else if (rightHeight(Y) > leftHeight(Y))
other_right_rotate(X);
}
X = X->parent;
}
updateRoot(m_root);
}
Vertex<T> * PartialInOrderSuccessor(Vertex<T> * X) { // This assumes X has a right child. Otherwise doesn't do what it should.
Vertex<T> * current = X->right;
while (current->left != NULL)
current = current->left;
return current;
}
void deleteVertex(T n) {
Vertex<T> * X = findValue(n); // X is a pointer to the vertex containing n, or NULL if there isn't one.
if (X == NULL)
return;
if (isLeaf(X)) { // If X is a leaf, delete it and AVL update starting with its parent.
Vertex<T> * Y = X->parent;
if (Y == NULL) {
delete X;
m_root = NULL;
return; // If our tree consisted of only one node, delete it and set m_root to NULL
}
else if (Y->left == X)
Y->left = NULL;
else if (Y->right == X)
Y->right = NULL;
delete X;
updateHeight(Y);
AVL_Update(Y);
}
else if ((X->left == NULL) || (X->right == NULL)) {
// If X has exactly one child, delete X, replace it with its child, and AVL update from there.
Vertex<T> * B = NULL;
if (X->left == NULL)
B = X->right;
else if (X->right == NULL)
B = X->left; // B is X's unique non-null child
Vertex<T> * Y = X->parent;
if (Y == NULL) {
B->parent = NULL;
delete X;
m_root = B; // If X was the root, now B is the root.
}
else {
B->parent = Y;
if (Y->left == X)
Y->left = B;
else if (Y->right == X)
Y->right = B;
delete X;
updateHeight(Y);
AVL_Update(Y);
}
}
// Now, what if X has two children:
else {
Vertex<T> * B = PartialInOrderSuccessor(X);
Vertex<T> * C = B->parent; // B is 'lower' than X, hence definitely has a non-NULL parent.
B->left = X->left;
B->right = X->right;
C->left = NULL; // It may have been the case that B was X's right child. Then C = X and this doesn't matter
// As we're going to delete X anyway. But in any other case, B had to be C's LEFT child.
B->parent = X->parent;
if (C == X) {
delete X;
updateHeight(B);
AVL_Update(B);
}
else {
delete X;
updateHeight(C);
AVL_Update(C);
}
}
}
void insert(T n) {
if (m_root == NULL) {
m_root = new Vertex<T>(n);
return;
}
Vertex<T> * current = m_root;
Vertex<T> * X = NULL;
Vertex<T> * newVertex = new Vertex<T>(n);
while (current != NULL) {
X = current;
T m = current->m_value;
if (m == n) return; // Because in this implementation we've chosen to not allow multiplicity. This would, of course, be easy to change.
if (n < m)
current = current->left;
else if (n > m)
current = current->right;
}
// So now X is storing the leaf under which we'll insert our new vertex
if (n < X->m_value) {
X->left = newVertex;
newVertex->parent = X;
updateHeight(X);
}
else if (n > X->m_value) {
X->right = newVertex;
newVertex->parent = X;
updateHeight(X);
}
AVL_Update(X);
}
};
</code></pre>
| [] | [
{
"body": "<p>I see some things that may help you improve your code.</p>\n\n<h2>Isolate platform-specific code</h2>\n\n<p>If you must have <code>stdafx.h</code>, (and it's not necessary here) consider wrapping it so that the code is portable:</p>\n\n<pre><code>#ifdef WINDOWS\n#include \"stdafx.h\"\n#endif\n</co... | {
"AcceptedAnswerId": "201019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T20:24:47.050",
"Id": "200980",
"Score": "3",
"Tags": [
"c++",
"tree",
"reinventing-the-wheel",
"binary-search"
],
"Title": "First Swing at an AVL Tree Implementation in C++"
} | 200980 |
<p>I was doing this JavaScript problem called "Minimum steps to 1." You can find the <a href="http://edusagar.com/questions/dynamic-programming/dynamic-programming-minimum-steps-to-1" rel="nofollow noreferrer">problem here</a>.</p>
<blockquote>
<p>Given a positive integer - num, Following is a list of possible operations which can be performed on it:</p>
<ol>
<li>num / 2, If number is divisible by 2</li>
<li>num / 3, If number is divisible by 3</li>
<li>num - 1</li>
</ol>
<p>With these 3 available operations, find out the minimum number of steps required to reduce the number to 1.</p>
<p>For example:</p>
<ol>
<li>For num = 1, no. of steps needed - 0</li>
<li>For num = 2, no. of steps needed - 1 (num/2)</li>
<li>For num = 6, no. of steps needed - 2 (num/3 followed by num/2)</li>
<li>For num = 9, no. of steps needed - 2 (num/3 followed by num/3)</li>
</ol>
</blockquote>
<pre><code>function minStepstoOne(n) {
let steps = [];
steps[0] = 0;
steps[1] = 0;
for(let i = 2; i <= n; i ++) {
let minChoice = steps[i - 1];
if(i % 2 == 0) {
let divideByTwo = steps[i/2]
minChoice = Math.min(divideByTwo, minChoice);
}
if(i % 3 == 0) {
let divideByThree = steps[i/3]
minChoice = Math.min(divideByThree, minChoice);
}
steps[i] = minChoice + 1;
}
return steps[n];
}
//console.log(minStepstoOne(9));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T19:42:47.713",
"Id": "498629",
"Score": "0",
"body": "Shouldn't steps[1] be initialized to 1 ?"
}
] | [
{
"body": "<p>Your function is right. </p>\n\n<p>However, for dynamic programming I always propagate state n to all states n+1 (Forward). Your code calculates state n+1 from state n (Backward). In this case both methods are okay and it is mostly a personal preference. But in other cases the backward method may ... | {
"AcceptedAnswerId": "200990",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T21:03:09.457",
"Id": "200984",
"Score": "3",
"Tags": [
"javascript",
"dynamic-programming"
],
"Title": "Minimum steps to 1 to find minimum operations to transform n to 1"
} | 200984 |
<p>Lets say i have 3 tables: <code>users</code>, <code>posts</code> and <code>comments</code>.</p>
<p><code>users</code> - contains information about registered users</p>
<p><code>posts</code> - contains information about posts that were created by users</p>
<p><code>comments</code> - all comments on one or multiple posts created by one or multiple users</p>
<p><a href="https://i.stack.imgur.com/kPGi3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kPGi3.png" alt="enter image description here"></a>
.</p>
<p>This image is how my <code>comments</code> table looks like. <code>user_id</code> and <code>post_id</code> are foreign keys in this table but primary keys in <code>users</code> and <code>posts</code> tables respectively. However this structure doesn't seem right to me because as you can see the <code>post_id</code> and <code>user_id</code> may get repeated multiple times.</p>
<p>My question is - is this structure good and should i use this, or should i create a new "middleman" table to hold <code>user_id</code> and <code>post_id</code> in order to somehow reduce redundancy? If so, how? Can you give me an example?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T02:16:28.070",
"Id": "387117",
"Score": "0",
"body": "Shouldn't this be placed in stackoverflow?"
}
] | [
{
"body": "<p>If your example means that, say, comment #1 is by user 8 about post 2,\nand comment #2 is by user 9 about post 7 then you're doing it right. This is a classic method to organize a table that relates the contents of other tables; you can use it to get all the comments on a particular post, or all ... | {
"AcceptedAnswerId": "200995",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T21:56:22.523",
"Id": "200985",
"Score": "-3",
"Tags": [
"python",
"sql",
"mysql"
],
"Title": "3 tables in SQL"
} | 200985 |
<blockquote>
<p><strong>The problem</strong></p>
<p>We want to use a very large array for some computations. When created, all the elements of this array have to be initialized to some value. We'll only use a few values from the array1, so we don't want the runtime of the algorithm to be dominated by the initialization time.</p>
<p>In other words, we want to create and access an initialized array in constant time2.</p>
<p>How can this be done ? (Hint: we may use extra memory)</p>
</blockquote>
<p>After reading about the <a href="https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)" rel="nofollow noreferrer">rule of three</a> I decided to take <a href="https://eli.thegreenplace.net/2008/08/23/initializing-an-array-in-constant-time" rel="nofollow noreferrer">this</a> implementation and make it a little bit better. So here is what I came up with ...</p>
<p>The source code is also available <a href="https://gist.github.com/xorz57/d85e547a11a908b7da8bc555bb2f2b8a" rel="nofollow noreferrer">here</a></p>
<pre><code>#pragma once
#include <algorithm>
#ifndef NDEBUG
#include <iostream>
#endif
template <typename T>
class InitializedArray {
public:
InitializedArray() = default;
InitializedArray(size_t length, T initial) : mInitial(initial), mTop(0), mLength(length) {
#ifndef NDEBUG
std::cout << "[InitializedArray] Constructor" << std::endl;
#endif
// Allocate Arrays
mFrom = new size_t[mLength];
mTo = new size_t[mLength];
mElements = new T[mLength];
}
InitializedArray(const InitializedArray & other) {
#ifndef NDEBUG
std::cout << "[InitializedArray] Copy Constructor" << std::endl;
#endif
if (mLength == 0) {
// Allocate Arrays
mFrom = new size_t[other.mLength];
mTo = new size_t[other.mLength];
mElements = new T[other.mLength];
// Copy Arrays
std::copy(other.mFrom , other.mFrom + other.mLength, mFrom );
std::copy(other.mTo , other.mTo + other.mLength, mTo );
std::copy(other.mElements, other.mElements + other.mLength, mElements);
mInitial = other.mInitial;
mTop = other.mTop;
mLength = other.mLength;
} else if (mLength >= other.mLength) {
// Copy Arrays
std::copy(other.mFrom , other.mFrom + other.mLength, mFrom );
std::copy(other.mTo , other.mTo + other.mLength, mTo );
std::copy(other.mElements, other.mElements + other.mLength, mElements);
mInitial = other.mInitial;
mTop = other.mTop;
mLength = other.mLength;
}
}
~InitializedArray() {
#ifndef NDEBUG
std::cout << "[InitializedArray] Destructor" << std::endl;
#endif
// Free Arrays
delete[] mFrom;
delete[] mTo;
delete[] mElements;
}
InitializedArray & operator=(const InitializedArray & other) {
#ifndef NDEBUG
std::cout << "[InitializedArray] Copy Assignment Operator" << std::endl;
#endif
if (&other != this) {
if (mLength == 0) {
// Allocate Arrays
mFrom = new size_t[other.mLength];
mTo = new size_t[other.mLength];
mElements = new T[other.mLength];
// Copy Arrays
std::copy(other.mFrom , other.mFrom + other.mLength, mFrom );
std::copy(other.mTo , other.mTo + other.mLength, mTo );
std::copy(other.mElements, other.mElements + other.mLength, mElements);
mInitial = other.mInitial;
mTop = other.mTop;
mLength = other.mLength;
} else if (mLength >= other.mLength) {
// Copy Arrays
std::copy(other.mFrom , other.mFrom + other.mLength, mFrom );
std::copy(other.mTo , other.mTo + other.mLength, mTo );
std::copy(other.mElements, other.mElements + other.mLength, mElements);
mInitial = other.mInitial;
mTop = other.mTop;
mLength = other.mLength;
}
}
return *this;
}
T & operator[](size_t index) {
#ifndef NDEBUG
std::cout << "[InitializedArray] Subscript Operator" << std::endl;
#endif
if (mFrom[index] < mTop && mTo[mFrom[index]] == index) {
return mElements[index];
} else {
mFrom[index] = mTop;
mTo[mTop] = index;
mElements[index] = mInitial;
mTop++;
return mElements[index];
}
}
size_t size() {
return mLength;
}
private:
size_t * mFrom = nullptr;
size_t * mTo = nullptr;
T * mElements = nullptr;
T mInitial;
size_t mTop = 0;
size_t mLength = 0;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T00:17:03.307",
"Id": "387112",
"Score": "0",
"body": "I guess the default constructor can lead to problems :/"
}
] | [
{
"body": "<p>The default constructor is almost OK, since most members of the class have default values specified. If the type <code>T</code> has a default construtor there are no problems. If it is a type without one (like <code>int</code>), then <code>mInitial</code> will be uninitialized.</p>\n\n<p>Your co... | {
"AcceptedAnswerId": "200994",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T00:02:04.130",
"Id": "200987",
"Score": "4",
"Tags": [
"c++",
"beginner",
"object-oriented",
"design-patterns",
"library"
],
"Title": "Initialized Array Template Class (C++)"
} | 200987 |
<p>I just wrote this password and password confirmation validation code function that checks to see if a password is empty or not, and is it match (password = confirmPassword). I'm not sure this is the best way to do it, but for now it dont works really well.</p>
<pre><code>private void checkDataEntered()
{
if(isEmpty(RegisterFirstName))
{
RegisterFirstName.setError("You must enter first name to register");
}
if(isEmpty(RegisterLastName))
{
RegisterLastName.setError("Last name is required");
}
if(isEmail(RegisterEmail) == false)
{
RegisterEmail.setError("Enter your valid email.");
}
if(isEmpty(RegisterPassword))
{
RegisterPassword.setError("Enter your password.");
}
if(isEmpty(RegisterConfirmPassword))
{
RegisterConfirmPassword.setError("Enter your confirmation password");
if (!RegisterConfirmPassword.equals(RegisterPassword))
{
Toast.makeText(Signup.this, "Password do not match", Toast.LENGTH_SHORT).show();
}
}
else
{
loadingBar.setTitle("Creating New Account");
loadingBar.setMessage("Please wait while we are creating account for you.");
loadingBar.show();
String email = null;
String password = null;
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>()
{
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
Toast.makeText(Signup.this, "You have successfully signed up", Toast.LENGTH_SHORT).show();
Intent mainIntent = new Intent(Signup.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
else
{
Toast.makeText(Signup.this, "Error occured, please try again.", Toast.LENGTH_SHORT).show();
}
loadingBar.dismiss();
}
});
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T07:54:30.327",
"Id": "387127",
"Score": "0",
"body": "Does this actually work when the form is correctly filled? The call `mAuth.createUserWithEmailAndPassword(email, password)` is suspicious, because at that point `email` and `pass... | [
{
"body": "<h3>Inconsistent UX</h3>\n\n<p>Most validation errors call <code>setError</code> of the relevant input field.\nAn exception is when the confirmation password doesn't match the first entry,\nthat pops up a toast.\nIt would be better to handle validation errors consistently,\nby using <code>setError</c... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T05:48:16.987",
"Id": "200996",
"Score": "0",
"Tags": [
"java",
"android",
"validation"
],
"Title": "Password and confirm password validation in Android Studio"
} | 200996 |
<p>I recently started on C++ multithreading. Here is my code to print odd and even numbers in two different thread. Can somebody please review this code?</p>
<pre><code>#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
int x = 1;
mutex m;
bool evenready = false;
bool oddready = true;
condition_variable cond;
void printEven()
{
for (; x < 10;) {
unique_lock<mutex> mlock(m);
cond.wait(mlock, [] {
return evenready;
});
oddready = true;
evenready = false;
cout << "Even Print" << x << endl;
x++;
cond.notify_all();
}
}
void printOdd()
{
for (; x < 10;){
unique_lock<mutex> mlock(m);
cond.wait(mlock, [] {
return oddready;
});
oddready = false;
evenready = true;
cout << "Odd Print" << x << endl;
x++;
cond.notify_all();
}
}
int main()
{
thread t1(printOdd);
thread t2(printEven);
t1.join();
t2.join();
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Multiple threads are usually used to compute things in parallel.\nIn this example nothing is computed in parallel:\nwhile one thread is running,\nthe other is waiting.\nWith no practical value,\nit's not a great demonstration of multithreading.\nI suggest to look for more practical targets in the ... | {
"AcceptedAnswerId": "201007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T05:57:39.537",
"Id": "200997",
"Score": "11",
"Tags": [
"c++",
"c++11",
"multithreading"
],
"Title": "Multithread to print odd and even numbers"
} | 200997 |
<p>I just started learning Racket as my first lisp dialect so after getting used to the syntax I implemented the <a href="https://oeis.org/A005132" rel="nofollow noreferrer">Recamán's sequence</a>.</p>
<p>Apart from the style, I'd also like to know if my code is a linear iteration or not. I kind of get the idea but I don't know how to be sure it is.</p>
<pre class="lang-lisp prettyprint-override"><code>#lang racket
(define (recaman-seq size)
(define (recaman-iter curr-seq n goal)
(if (= n goal)
(reverse curr-seq)
(cond
[(and (= n 0) (empty? curr-seq))
(recaman-iter (list n) (+ n 1) goal)]
[else
(define a (- (car curr-seq) n))
(define b (+ (car curr-seq) n))
(define is-new (not (member a curr-seq)))
(cond
[(and (positive? a) is-new)
(recaman-iter (list* a curr-seq) (+ n 1) goal)]
[else
(recaman-iter (list* b curr-seq) (+ n 1) goal)])])))
(recaman-iter '() 0 (+ size 1)))
(recaman-seq 10)
</code></pre>
| [] | [
{
"body": "<p>This code is not exactly linear as <code>member</code> is a o(n) time function and grown in proportion to <code>curr-seq</code>, making the whole function about O(n^2). </p>\n\n<p>However without an algorithmic trick, the function requires a search of past results, and the best search that I know... | {
"AcceptedAnswerId": "201173",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T15:57:13.050",
"Id": "201010",
"Score": "4",
"Tags": [
"lisp",
"scheme",
"racket"
],
"Title": "Recamán's Sequence in Racket"
} | 201010 |
<p>Because neither sklearn nor Pandas provide a straightforward and complete one-hot encoder, I decided to write one myself. Both Pandas and sklearn do have an encoder with no option to decode, and the <code>sklearn.LabelEncoder</code> that has the decoding only produces that, labels.</p>
<p>Here's the class:</p>
<pre><code>import numpy as np
class OneHotEncoder:
def __init__(self):
self.unq = np.array([])
self.n_features = len(self.unq)
def set_unq(self, unq):
self.unq = unq
self.n_features = len(unq)
@staticmethod
def _assure(cond, msg):
if not cond:
raise ValueError(msg)
def fit_transform(self, np_arr):
"""
From categories to one-hot encoding. Calculate unique occurences.
:param np_arr: categorical data of shape (samples, 1)
:return: one-hot encoding with shape (sample, categories)
"""
self._assure(np_arr.shape[-1] == 1, 'Last axis must be length 1.')
unq, idx = np.unique(np_arr, return_inverse=True)
self.set_unq(unq)
arr = np.zeros((len(idx), len(self.unq)))
arr[range(len(idx)), idx] = 1
return arr
def transform(self, np_arr):
"""
From categories to one-hot encoding based on previous samples.
:param np_arr: categorical data of shape (samples, 1)
:return: one-hot encoding with shape (sample, categories)
"""
self._assure(np_arr.shape[-1] == 1, 'Last axis must be length 1.')
arr = np.argwhere(self.unq == np_arr)[:, 1]
zr = np.zeros((len(arr), len(self.unq)))
zr[range(len(arr)), arr] = 1
return zr
def fit_transform_to_labels(self, np_arr):
"""
From categories to label values. Calculate unique occurences.
:param np_arr: categorical data of shape (samples, 1)
:return: label values with shape (sample, 1)
"""
self._assure(np_arr.shape[-1] == 1, 'Last axis must be length 1.')
unq, idx = np.unique(np_arr, return_inverse=True)
self.set_unq(unq)
return idx.reshape(-1, 1)
def transform_to_labels(self, np_arr):
"""
From categories to label values based on previous samples.
:param np_arr: categorical data of shape (samples, 1)
:return: label values with shape (sample, 1)
"""
self._assure(np_arr.shape[-1] == 1, 'Last axis must be length 1.')
arr = np.argwhere(self.unq == np_arr)
return arr[:, 1:2]
def transform_from_labels(self, np_arr):
"""
From label values to one-hot encoding.
:param np_arr: label values of shape (samples, 1)
:return: one-hot encoding with shape (samples, categories)
"""
self._assure(np_arr.shape[-1] == 1, 'Last axis must be length 1.')
arr = np.zeros((len(np_arr), len(self.unq)))
arr[range(len(arr)), np_arr.reshape(-1)] = 1
return arr
def inverse_from_labels(self, np_arr):
"""
From label values to original categorical values.
:param np_arr: label values of shape (samples, 1)
:return: original categorical values with shape (samples, 1)
"""
self._assure(np_arr.shape[-1] == 1, 'Last axis must be length 1.')
return self.unq[np_arr]
def inverse_to_lables(self, np_arr):
"""
From one-hot encoding to label values.
:param np_arr: one-hot encoding of shape (samples, categories)
:return: label values with shape (samples, 1)
"""
self._assure(np_arr.shape[-1] == len(self.unq), 'Inverting array must be same length as available labels.')
return np.argmax(np_arr, axis=-1).reshape(-1, 1)
def inverse(self, np_arr):
"""
From one-hot encoding to original categorical values.
:param np_arr: one-hot encoding of shape (samples, categories)
:return: original categorical values with shape (samples, 1)
"""
self._assure(np_arr.shape[-1] == len(self.unq), 'Inverting array must be same length as available labels.')
return self.inverse_from_labels(np.argmax(np_arr, axis=-1).reshape(-1, 1))
</code></pre>
<p>So in short, this class combines the functionality of <code>sklearn.LabelEncoder</code> and <code>sklearn.OneHotEncoder</code>. The assertions are a bit redundant, I just like to keep my vectors as column vectors.</p>
<p>This class does work.</p>
<ul>
<li>Is it missing something in terms of functionality or safety?</li>
<li>Could it be expanded to some different cases I haven't yet taken into account?</li>
</ul>
<p>Here's a small snippet of using the class:</p>
<pre><code>a = np.array([1,2,3,4,3,2,1]).reshape(-1, 1)
oh = OneHotEncoder()
labs = oh.fit_transform_to_labels(a)
encoded = oh.transform_from_labels(labs)
decoded = oh.inverse(encoded)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-02T18:35:00.177",
"Id": "391226",
"Score": "0",
"body": "Revised version below as an answer for anyone who's interested!"
}
] | [
{
"body": "<h1>variable naming</h1>\n\n<p><code>np_arr</code> is a bad name for a variable, especially if you use it in multiple places, each with a different meaning. Name the part, so for example in <code>fit_transform</code>, <code>samples</code> is a better name.\n<code>self.unq</code> is also unclear, I wo... | {
"AcceptedAnswerId": "201088",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T16:06:38.187",
"Id": "201011",
"Score": "4",
"Tags": [
"python",
"numpy"
],
"Title": "Simple one-hot encoder"
} | 201011 |
<p>A Minesweeper library in C#. To be included with any GUI stack.</p>
<p>Did some breakpoint tests and unit testing, seems to work fine. </p>
<p>I'm asking if the code makes sense to everyone, and if there can be improvements.</p>
<p>Three classes: Tile, Board and Game.</p>
<p><strong>Tile</strong></p>
<pre><code>public enum TileStatus
{
Revealed,
Flagged,
Hidden
}
public class Tile
{
public Tile(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
public int AdjacentMines { get; internal set; }
public bool HasAdjacentMines => AdjacentMines != 0;
public bool IsMine { get; internal set; }
public TileStatus Status { get; private set; } = TileStatus.Hidden;
public bool IsRevealed => Status == TileStatus.Revealed;
public bool IsFlagged => Status == TileStatus.Flagged;
internal void SetRevealed() => Status = TileStatus.Revealed;
internal void SetFlagged() => Status = TileStatus.Flagged;
internal void SetHidden() => Status = TileStatus.Hidden;
}
</code></pre>
<p><strong>Board</strong></p>
<pre><code>public class Board
{
private Tile[,] _tiles;
public int Columns => _tiles.GetLength(0);
public int Rows => _tiles.GetLength(1);
public Board(int columns, int rows)
{
_tiles = new Tile[columns, rows];
InitializeTiles(columns, rows);
}
private void InitializeTiles(int columns, int rows)
{
for (int x = 0; x < columns; x++)
for (int y = 0; y < rows; y++)
_tiles[x, y] = new Tile(x, y);
}
public Tile this[int x, int y] => _tiles[x, y];
}
</code></pre>
<p><strong>Game</strong></p>
<pre><code>public interface IGame
{
Board Board { get; }
int Columns { get; }
int Rows { get; }
int Mines { get; }
IList<Tile> Reveal(int x, int y);
void Flag(int x, int y);
void Unflag(int x, int y);
string VisualizeCurrentState();
string VisualizeEverything();
}
public class Game : IGame
{
public Game(int columns, int rows, int mines)
{
if (columns < 1 || rows < 1)
throw new ArgumentException("Board can't be smaller than 1x1.");
if (mines >= columns * rows)
throw new ArgumentException("Must be fewer mines than tiles.");
Mines = mines;
Board = new Board(columns, rows);
}
private bool _isFirstReveal = true;
public Board Board { get; }
public int Columns => Board.Columns;
public int Rows => Board.Rows;
public int Mines { get; }
/// <summary>
/// Reveal tiles and return list of revealed tiles.
///
/// If the initial tile was blank (no mines, no adjacent mines), reveals and returns a list of safe tiles.
/// If the initial tile was a mine (game over), reveals and returns a list of all mines.
/// </summary>
public IList<Tile> Reveal(int initialX, int initialY)
{
if (initialX >= Columns || initialX < 0 || initialY >= Rows || initialY < 0)
throw new ArgumentException("Given (x, y) out of bounds.");
// Populate the board with mines after first click, because first click must be safe.
if (_isFirstReveal)
{
_isFirstReveal = false;
PopulateTiles(initialX, initialY);
}
// Set the revealed tile's status.
var initialTile = Board[initialX, initialY];
initialTile.SetRevealed();
// Prepare the return list.
var area = new HashSet<Tile>
{
initialTile
};
if (initialTile.IsMine)
{
// If the clicked tile was a mine, reveal all mines and return them.
area.UnionWith(RevealMines());
}
else if (!initialTile.HasAdjacentMines)
{
// If the clicked tile was blank (no mine, no adjacent mines), reveal a surrounding safe area.
SearchRecursively(initialTile);
}
return area.ToList();
// Method for finding safe area around a tile.
void SearchRecursively(Tile fromTile)
{
InvokeOnAdjacentTiles(fromTile, (tile) =>
{
if (tile.IsMine || tile.IsFlagged || tile.IsRevealed)
return;
tile.SetRevealed();
area.Add(tile);
if (!tile.HasAdjacentMines)
SearchRecursively(tile);
});
}
}
/// <summary>
/// Reveals all mines and return a list.
/// </summary>
private IList<Tile> RevealMines()
{
var mines = new HashSet<Tile>();
for (int x = 0; x < Columns; x++)
{
for (int y = 0; y < Rows; y++)
{
var tile = Board[x, y];
if (tile.IsMine)
{
tile.SetRevealed();
mines.Add(tile);
}
}
}
return mines.ToList();
}
/// <summary>
/// Populate all tiles with mines and numbers. The initial tile should not have a mine.
/// </summary>
private void PopulateTiles(int initialX, int initialY)
{
// Populate mines.
var random = new Random();
var placed = 0;
while (placed < Mines)
{
var x = random.Next(Columns);
var y = random.Next(Rows);
if (!(x == initialX && y == initialY) && !Board[x, y].IsMine)
{
Board[x, y].IsMine = true;
placed++;
}
}
// Populate tiles with adjacent mines count.
for (int x = 0; x < Rows; x++)
{
for (int y = 0; y < Columns; y++)
{
var tile = Board[x, y];
if (tile.IsMine)
continue;
tile.AdjacentMines = CountAdjacentMines(tile);
}
}
int CountAdjacentMines(Tile tile)
{
var count = 0;
InvokeOnAdjacentTiles(tile, (a) => {
if (a.IsMine)
count++;
});
return count;
}
}
/// <summary>
/// Invoke an action on adjacent tiles.
/// </summary>
private void InvokeOnAdjacentTiles(Tile tile, Action<Tile> action)
{
for (int nx = tile.X - 1; nx <= tile.X + 1; nx++)
{
if (nx < 0 || nx == Columns)
continue;
for (int ny = tile.Y - 1; ny <= tile.Y + 1; ny++)
{
if (ny < 0 || ny == Rows)
continue;
if (nx == tile.X && ny == tile.Y)
continue;
action.Invoke(Board[nx, ny]);
}
}
}
/// <summary>
/// Flag a tile.
/// </summary>
public void Flag(int x, int y)
{
if (x >= Columns || x < 0 || y >= Rows || y < 0)
throw new ArgumentException("Given (x, y) out of bounds.");
Board[x, y].SetFlagged();
}
/// <summary>
/// Unflag the tile.
/// </summary>
public void Unflag(int x, int y)
{
if (x >= Columns || x < 0 || y >= Rows || y < 0)
throw new ArgumentException("Given (x, y) out of bounds.");
Board[x, y].SetHidden();
}
/// <summary>
/// Get a text visualization of the current state of the board.
/// </summary>
public string VisualizeCurrentState()
{
var sb = new StringBuilder();
for (var y = 0; y < Rows; y++)
{
for (var x = 0; x < Columns; x++)
{
var tile = Board[x, y];
if (!tile.IsRevealed)
sb.Append(" ");
else if (tile.IsFlagged)
sb.Append(">");
else if (tile.IsMine)
sb.Append("x");
else if (!tile.HasAdjacentMines)
sb.Append("_");
else
sb.Append(tile.AdjacentMines.ToString());
if (x == Columns - 1)
sb.Append("\n");
}
}
return sb.ToString();
}
/// <summary>
/// Get a text visualization of everything on the board, including hidden tiles.
/// </summary>
public string VisualizeEverything()
{
var sb = new StringBuilder();
for (var y = 0; y < Rows; y++)
{
for (var x = 0; x < Columns; x++)
{
var tile = Board[x, y];
if (tile.IsMine)
sb.Append("x");
else if (!tile.HasAdjacentMines)
sb.Append("_");
else
sb.Append(tile.AdjacentMines.ToString());
if (x == Columns - 1)
sb.Append("\n");
}
}
return sb.ToString();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T17:01:15.213",
"Id": "387148",
"Score": "2",
"body": "Just a comment on the naming of `GetAdjacentTiles`: It doesn't get tiles, it applies an action on tiles. I would name it `ApplyOnAdjacentTiles`."
},
{
"ContentLicense": ... | [
{
"body": "<p>Looks alright to me. Some minor issues:</p>\n\n<p>1) I don't like those methods:</p>\n\n<blockquote>\n<pre><code>internal void SetRevealed() => Status = TileStatus.Revealed;\ninternal void SetFlagged() => Status = TileStatus.Flagged;\ninternal void SetHidden() => Status = TileStatus.Hidde... | {
"AcceptedAnswerId": "201051",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T16:45:13.090",
"Id": "201012",
"Score": "7",
"Tags": [
"c#",
"game",
"minesweeper"
],
"Title": "Minesweeper library for any GUI"
} | 201012 |
<p>I'm looking for advice on implementing many-to-many. I'm modeling a site such as stack exchange: each Member has many Groups, each Group has many Members. I've introduce a Membership class. This class diagram summarized the code belowEventually there will be question and answer classes, but I want to get this part correct first.</p>
<p><a href="https://i.stack.imgur.com/bzHp2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bzHp2.png" alt="Class diagram"></a></p>
<pre><code>import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class Member {
private LocalDateTime dateCreated;
private String firstName;
private String lastName;
private String screenName;
private String userID;
private List<Membership> memberships = new ArrayList<Membership>();
public Member(String firstName, String lastName, String screenName, String userID) {
super();
this.dateCreated = LocalDateTime.now();
this.firstName = firstName;
this.lastName = lastName;
this.screenName = screenName;
this.userID = userID;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getScreenName() {
return screenName;
}
public String getUserID() {
return userID;
}
protected void addMembership(Membership m) {
memberships.add(m);
}
public int getNumGroups() {
return memberships.size();
}
public List<Group> getGroups() {
List<Group> groups = new ArrayList<>();
for(Membership membership : memberships) {
groups.add(membership.getGroup());
}
return groups;
}
@Override
public String toString() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formatDateTime = dateCreated.format(formatter);
return "Member [dateCreated=" + formatDateTime + ", firstName=" + firstName + ", lastName=" + lastName
+ ", screenName=" + screenName + ", userID=" + userID + "]";
}
public static void main(String[] args) {
Member m = new Member("Les", "Wrigley", "Lesman", "lwrigley@gmail.com");
System.out.println(m);
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class Group {
private LocalDateTime dateCreated;
private String title;
private String description;
private List<Membership> memberships = new ArrayList<Membership>();
public Group(String title, String description) {
super();
this.title = title;
this.description = description;
this.dateCreated = LocalDateTime.now();
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
protected void addMembership(Membership m) {
memberships.add(m);
}
@Override
public String toString() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formatDateTime = dateCreated.format(formatter);
return "Group [dateCreated=" + formatDateTime + ", title=" + title + ", description=" + description + "]";
}
public int getNumMembers() {
return memberships.size();
}
public List<Member> getMembers() {
List<Member> members = new ArrayList<Member>();
for(Membership membership : memberships) {
members.add(membership.getMember());
}
return members;
}
public static void main(String[] args) {
Group g = new Group("Java Programming", "Questions related to programming in Java");
System.out.println(g.toString());
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Membership {
private LocalDateTime dateJoined;
private Member member;
private Group group;
public Membership(Member m, Group g) {
dateJoined = LocalDateTime.now();
this.member = m;
this.group = g;
member.addMembership(this);
group.addMembership(this);
}
public LocalDateTime getDateJoined() {
return dateJoined;
}
public Member getMember() {
return member;
}
public Group getGroup() {
return group;
}
@Override
public String toString() {
String groupName = group.getTitle();
String memberName = member.getLastName() + ", " + member.getFirstName();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formatDateTime = dateJoined.format(formatter);
String msg = String.format("Member:%s, Group:%s, Joined:%s", groupName, memberName, formatDateTime);
return msg;
}
public static void main(String[] args) {
Member m = new Member("Les", "Wrigley", "Lesman", "lwrigley@gmail.com");
Group g = new Group("Java Programming", "Questions related to programming in Java");
Membership membership = new Membership(m,g);
System.out.println(membership.toString());
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T19:52:47.043",
"Id": "387155",
"Score": "0",
"body": "Each membership could be part of many groups as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T00:33:04.087",
"Id": "387178",
"Scor... | [
{
"body": "<blockquote>\n<pre><code>public class Member {\n private LocalDateTime dateCreated;\n private String firstName;\n private String lastName;\n private String screenName;\n private String userID;\n private List<Membership> memberships = new ArrayList<Membership>();\n</code>... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T16:50:32.173",
"Id": "201014",
"Score": "0",
"Tags": [
"java",
"object-oriented"
],
"Title": "Implementing many-to-many"
} | 201014 |
<p>I would love to get some feedback on my implementation of "Simon Says." I have not followed the original in that I have created a new sequence each time, rather and adding a new item to the pattern.</p>
<p>I'm particularly interested in the overall structure of my JS/JQuery - did I make good choices for the methods, is there enough separation of concerns etc. Are there any obvious conceptual errors? </p>
<p>I'm trying to cross the expanse from experienced beginner to "intermediate developer".</p>
<p>My code is at codepen: <a href="https://codepen.io/robin-andrews/full/BPPRWm/" rel="nofollow noreferrer">https://codepen.io/robin-andrews/full/BPPRWm/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$( document ).ready( function() {
var Simon = {
// Game constants
cacheDom: function() {}, // to be implemented
flashSpeed: 400,
score : 0,
level: 1,
// Init whole game
init: function() {
this.bindControls();
},
newRound : function(){
this.unbindPads();
this.bindControls();
},
bindControls: function() {
// currently only start button needs event
$( '#start-button' ).on( 'click', this.playerRound.bind( this ) );
},
unbindControls: function() {
$( '#start-button' ).off( 'click' );
},
bindPads: function() {
$( '#play-area' ).on( 'click', '.pad', this.checkSequence.bind( this ) ); // pass object
},
unbindPads: function() {
$( '#play-area' ).off( 'click' );
},
playerRound: function() {
this.unbindControls();
$( '#info' ).text( 'Copy the sequence using mouse clicks' );
this.computerSequence = this.generateSequence( this.level );
this.remainingSequence = this.computerSequence.slice( 0 );
this.displaySequence( this.computerSequence );
this.bindPads();
},
// Generate random sequence for pads
generateSequence: function( length ) {
var seq = [];
for ( var i = 0; i < length; i++ ) {
seq.push( Math.floor( Math.random() * 4 ) + 1 ); // returns a random integer from 1 to 10]
}
return seq;
},
// Display sequence to player
displaySequence: function( seq ) {
var self = this;
if ( seq.length >= 1 ) {
var current_list_item = seq[ 0 ];
$( '#pad' + current_list_item ).css( 'opacity', '1' );
$( '#pad' + current_list_item ).animate( {
'opacity': '0.4'
}, self.flashSpeed, function() {
self.displaySequence( seq.slice( 1 ) );
} );
return;
}
},
checkSequence: function( e ) {
var boxNum = $( e.target ).attr( 'id' ).slice( -1 );
if ( boxNum != this.remainingSequence[ 0 ] ) {
this.playerLoses();
return; //?
}
this.remainingSequence = this.remainingSequence.slice( 1 );
if ( this.remainingSequence.length < 1 ) {
this.playerWins();
}
},
playerWins : function(){
$( '#info' ).text( 'You won. Press play to continue.' );
this.score += this.level;
$( '#score' ).text( 'Score: ' + this.score);
this.level += 1;
this.newRound();
},
playerLoses: function() {
$( '#info' ).text( 'You lost. Press play to play again.' );
this.level = 1;
this.score = 0;
$( '#score' ).text( 'Score: ' + this.score);
this.newRound();
}
};
Simon.init();
} );
// To do
// increae speed with level?
// Track highest score?</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
body {
margin: 0;
background-color: grey;
font-family: "Lucida Console", Monaco, monospace;
}
#wrapper{
width: 600px;
height: 400px;
margin: auto;
position: relative;
}
#control-area{
width: 200px;
height: 400px;
background-color: black;
float: left;
}
#start-button{
display: block;
width: 100px;
margin: 20px auto;
background-color: white;
border: none;
border-radius: 30px;
padding: 5px;
top: 200px;
font-size: inherit;
font-family:inherit;
outline: none;
}
#info{
background-color: white;
width: 150px;
height: 90px;
padding: 5px;
margin: 20px auto;
border-radius: 5px;
}
#score{
background-color: white;
width: 100px;
padding: 5px;
margin: 20px auto;
border-radius: 5px;
}
#play-area{
width: 400px;
height: 400px;
float: right;
}
.pad{
width: 200px;
height: 200px;
float: left;
opacity: 0.4;
}
#pad1{
background: #66ff00;
}
#pad2{
background: red;
}
#pad3{
background: yellow;
}
#pad4{
background: blue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Robin Says</title>
<link rel="stylesheet" href="style.css">
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<h1 id="title">Robin Says</h1>
<div id="control-area">
<p id="info">
Press start to play
</p>
<div id="score">Score: 0</div>
<button id="start-button">Start</button>
</div>
<div id="play-area">
<div id="pad1" class="pad"></div><!-- Could use data attributes -->
<div id="pad2" class="pad"></div>
<div id="pad3" class="pad"></div>
<div id="pad4" class="pad"></div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T17:49:59.993",
"Id": "387150",
"Score": "0",
"body": "Note that the code you posted here is a bit different from your CodePen (the button is labeled \"Start\" rather than \"Play\")."
}
] | [
{
"body": "<h1>Separate game for unrelated stuff</h1>\n<p>The core of a game should be independent of the user interface. It should be able to work using the DOM or a console. It could be sounds sequences, words, shapes or anything. As long as the external interfaces implement the required properties and the ca... | {
"AcceptedAnswerId": "201057",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T17:00:49.283",
"Id": "201015",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"simon-says"
],
"Title": "Simon Says implementation using jQuery"
} | 201015 |
<p>I started learning Python by making an IRC bot, as it took some pains in another language. I've improved it now over time. As it involves networking, I'd also like some comments on that side.</p>
<pre><code># -*- coding: utf-8 -*-
import socket
import os
import importlib
plugins = []
class Bot_core(object):
def __init__(self,
server_url = 'chat.freenode.net',
port = 6667,
name = 'appinvBot',
owners = ['appinv'],
password = '',
friends = ['haruno'],
autojoin_channels = ['##bottestingmu']
):
self.server_url = server_url
self.port = port
self.name = name
self.owners = owners
self.password = password
self.autojoin_channels = autojoin_channels
self.friends = friends
'''
NORMAL ATTRIBUTES
'''
self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.isListenOn = 1
dom = self.server_url.split('.')
self.domain = '.'.join(dom[-2:])
self.sp_command = 'hbot'
self.plugins = []
'''
STRINGS
'''
def set_nick_command(self):
return 'NICK ' + self.name + '\r\n'
def present_command(self):
return 'USER '+self.name+' '+self.name+' '+self.name+' : '+self.name+' IRC\r\n'
def identify_command(self):
return 'msg NickServ identify ' + self.password + ' \r\n'
def join_channel_command(self, channel):
return 'JOIN ' + channel + ' \r\n'
def specific_send_command(self, target, msg):
return "PRIVMSG "+ target +" :"+ msg +"\r\n"
def pong_return(self):
return 'PONG \r\n'
def info(self, s):
def return_it(x):
if x == None:
return ''
else:
return x
try:
prefix = ''
trailing = []
address = ''
if not s:
print("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
if '#' in args[0]:
address = args[0]
else:
address = prefix.split('!~')[0]
# return prefix, command, args, address
return {
'prefix':return_it(prefix),
'command':return_it(command),
'args':['' if e is None else e for e in args],
'address':return_it(address)
}
except Exception as e:
print('woops',e)
'''
MESSAGE UTIL
'''
def send(self, msg):
self.irc.send(bytes( msg, "UTF-8"))
def send_target(self, target, msg):
self.send(self.specific_send_command(target, msg))
def join(self, channel):
self.send(self.join_channel_command(channel))
'''
BOT UTIL
'''
def load_plugins(self, list_to_add):
try:
to_load = []
with open('PLUGINS.conf', 'r') as f:
to_load = f.read().split('\n')
to_load = list(filter(lambda x: x != '', to_load))
for file in to_load:
module = importlib.import_module('plugins.'+file)
Plugin = getattr(module, 'Plugin')
obj = Plugin()
list_to_add.append(obj)
except ModuleNotFoundError as e:
print('module not found', e)
def methods(self):
return {
'send_raw':self.send,
'send':self.send_target,
'join':self.join
}
def run_plugins(self, listfrom, incoming):
for plugin in listfrom:
plugin.run(incoming, self.methods(), self.info(incoming))
'''
MESSAGE PARSING
'''
def core_commands_parse(self, incoming):
'''
PLUGINS
'''
self.run_plugins(self.plugins, incoming)
'''
BOT IRC FUNCTIONS
'''
def connect(self):
self.irc.connect((self.server_url, self.port))
def identify(self):
self.send(self.identify_command())
def greet(self):
self.send(self.set_nick_command())
self.send(self.present_command())
for channel in self.autojoin_channels:
self.send(self.join_channel_command(channel))
def pull(self):
while self.isListenOn:
try :
data = self.irc.recv(2048)
raw_msg = data.decode("UTF-8")
msg = raw_msg.strip('\n\r')
self.stay_alive(msg)
self.core_commands_parse(msg)
print(
"""***
{}
""".format(msg))
if len(data) == 0:
try:
self.irc.close()
self.registered_run()
except Exception as e:
print(e)
except Exception as e:
print(e)
# all in one for registered bot
def registered_run(self):
self.connect()
self.identify()
self.greet()
self.load_plugins(self.plugins)
self.pull()
def unregistered_run(self):
self.connect()
self.greet()
self.load_plugins(plugins)
self.pull()
'''
ONGOING REQUIREMENT/S
'''
def stay_alive(self, incoming):
if 'ping' in incoming.lower():
part = incoming.split(':')
if self.domain in part[1]:
self.send(self.pong_return())
print('''
***** message *****
ping detected from
{}
*******************
'''.format(part[1]))
self.irc.recv(2048).decode("UTF-8")
x = Bot_core(); x.registered_run()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T04:18:39.680",
"Id": "387183",
"Score": "1",
"body": "which python version are you building this in?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T07:57:32.063",
"Id": "387193",
"Score": "0"... | [
{
"body": "<p>I have the following points to make on the code:<br>\n - No logging<br>\n - No external config file for the settings (Open/Close Principal violation)<br>\n - Creating resources in the init instead of in a separate section (no re-use of common functions should the user attempt to connect to multipl... | {
"AcceptedAnswerId": "201048",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T17:41:38.847",
"Id": "201017",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"plugin",
"chat"
],
"Title": "Internet Relay Chat bot core with plugins system"
} | 201017 |
<p>I have been working on credit problem for edx CS50 and got it working as intended. an issue I find with it is the way I have to reinitialise the <code>cardNumber</code> variable each time it enters a loop, and there are plenty of loops in my solution. Same goes for my bool value. Is there a better, cleaner way to go around this?</p>
<pre><code>#include <stdio.h>
#include <cs50.h>
// Implement a program that determines whether a provided credit card number
// is valid according to Luhn’s algorithm.
int main(void)
{
long long userInput;
// Prompt for user input as long long.
do
{
userInput = get_long_long("Enter credit card number to validate: ");
// Ensure user inputs integer otherwise prompt "Retry: "
if (userInput < 0)
{
printf("Retry: \n");
}
} while (userInput < 0);
long long cardNumber = userInput;
int checkSum = 0;
int secDig, lastDig, multDig;
// start from second to last digit (cc_number / 10) % 10 and multiply every other digit by 2.
while (cardNumber > 0)
{
// sum digits that weren't multiplied.
lastDig = (cardNumber % 10);
// add the sum to the sum of the digits that weren't multipied by 2.
checkSum += lastDig;
secDig = (cardNumber / 10) % 10;
cardNumber /= 100;
// multiply every other digit
multDig = secDig * 2;
// add those products (separate /10, return modulus of 10) digits together.
if (multDig > 10)
{
checkSum += (multDig % 10) + 1;
}
else if (multDig == 10)
{
checkSum += 1;
}
else
{
checkSum += multDig;
}
}
// validate checksum
// if sum of digits ends in 0 ergo % 10 = 0 then number is valid.
bool valid = false;
if (checkSum % 10 == 0)
{
valid = true;
}
int numOfDigits = 0;
cardNumber = userInput;
// validate number's length
// track number's length
while (cardNumber > 0)
{
cardNumber /= 10;
numOfDigits++;
}
cardNumber = userInput;
// validate company's identifier
// if 15 digits, starts with 34 or 37 - AMEX
if (valid == true && numOfDigits > 12)
{
if (numOfDigits == 15)
{
for (int i = 0; i < numOfDigits - 2; i++)
{
cardNumber /= 10;
}
if (cardNumber == 34 || cardNumber == 37)
{
printf("AMEX\n");
valid = true;
}
else
{
valid = false;
}
}
// if 16 digits, starts with 51-55 - MASTERCARD
cardNumber = userInput;
if (numOfDigits == 16)
{
for (int i = 0; i < numOfDigits - 2; i++)
{
cardNumber /= 10;
}
if (cardNumber >= 51 && cardNumber <= 55)
{
printf("MASTERCARD\n");
valid = true;
}
else
{
valid = false;
}
}
// if 13 OR 16 digits, starts with 4 - VISA
cardNumber = userInput;
if (numOfDigits == 13 || numOfDigits == 16)
{
for (int i = 0; i < numOfDigits - 1; i++)
{
cardNumber /= 10;
}
if (cardNumber == 4)
{
printf("VISA\n");
valid = true;
}
else
{
valid = false;
}
}
if (valid == false)
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
}
</code></pre>
<p>All comments are part of pseudocode for this solution. I left them there to satisfy style50. I would appreciate advice so I can write cleaner next time and make it into a habit. I am a beginner starting CS degree next year with only experience with doing C# courses with Mosh Hamedani.</p>
| [] | [
{
"body": "<p>First thing I think of is that you have a pretty long <code>main</code>. You should split the code in more functions. Your code could look like this:</p>\n\n<pre><code>long long readCardnumber();\nbool validateChecksum(long long cardnumber);\ntypedef enum { invalid, amex, mastercard, visa } compan... | {
"AcceptedAnswerId": "201026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T19:34:56.463",
"Id": "201023",
"Score": "7",
"Tags": [
"beginner",
"c",
"checksum"
],
"Title": "Determining whether a provided credit card number is valid according to Luhn’s algorithm"
} | 201023 |
<h1>Explanation</h1>
<p>I started learning Haskell about a month ago. As an exercise, I recreated a little command line tool, which I had previously written in PowerShell. In the current state, it displays a list of videos in a specific directory and its subdirectories. Later I will add the functionality to play or delete those videos (which should be easy). But the big part is displaying the list. That's all this code does, at the moment.</p>
<p>As much as I like Haskell so far, I'm unhappy with how wordy and complicated this code is. It is 100 lines and seems very hard to read. The PowerShell script is only 70 lines (complete with playback and deletion of videos), less wordy and very easy to read.</p>
<p>Is it mostly due to my lack of knowledge how to write good Haskell code? Or is Haskell not a good tool for this kind of task?</p>
<p>What bothers me in particular:</p>
<ul>
<li><p>I have all those little functions, which do one specific task and call each other to achieve the end goal. This makes it very hard to read the code if one is not familiar with it. Because the functions are not connected in an obvious control structure, one has to analyse each one, see what other function it calls and so forth until the picture is complete.<br>
Compare this with an imperative language: there are some <code>if</code> statements with easy to read conditions and some large code blocks. At a glance one can see what is done where and if it's of interest, one can look more into the details of the implementation. It's very easy to get a feeling of the overall structure of the program.</p></li>
<li><p><code>getRecursiveContents</code> (I copied this from the internet). It's huge and complicated. Getting files recursively is such an everyday task - is there really no library function which does this?</p></li>
<li><p>It's nice that I can describe how a custom type should <code>Show</code> itself when printed. But because I'm dealing with lists, I then have to <code>unlines $ map show</code> it, which is not pretty.</p></li>
</ul>
<h1>Directory structure</h1>
<pre><code>└───Videos
│ Heat.1995.1080p.BRrip.x264.YIFY.mp4
│ heat.png
│ leon.png
│ Leon.the.Professional.Extended.1994.BrRip.x264.YIFY.mp4
│ mononoke hime.png
│ Mononoke.hime.[Princess.Mononoke].[DUAL.AUDIO]1997.HDTVRip.x264.YIFY.mkv
│ Oblivion.2013.1080p.BluRay.x264.YIFY.mp4
│ oblivion.png
│ terminator 2.png
│ Terminator.2.Judgment.Day.1991.DC.1080p.BRrip.x264.GAZ.YIFY.mp4
│ traffic.png
│
└───Series
S01E01.Some.Show.mp4
S01E02.Some.Show.mp4
S01E03.Some.Show.mp4
</code></pre>
<h1>Output</h1>
<pre><code> Videos
1 Heat.1995.1080p.BRrip.x264.YIFY
2 Leon.the.Professional.Extended.1994.BrRip.x264.YIFY
3 Mononoke.hime.[Princess.Mononoke].[DUAL.AUDIO]1997.HDTVRip.x264.YIFY
4 Oblivion.2013.1080p.BluRay.x264.YIFY
5 Terminator.2.Judgment.Day.1991.DC.1080p.BRrip.x264.GAZ.YIFY
Series
6 S01E01.Some.Show
7 S01E02.Some.Show
8 S01E03.Some.Show
</code></pre>
<h1>Source</h1>
<pre><code>module Main where
import Control.Monad (forM)
import Data.Char (toLower)
import Data.List (isInfixOf, nub, sort, sortBy)
import Data.List.Split (splitOn)
import System.Directory (doesDirectoryExist, listDirectory)
import System.FilePath (takeBaseName, takeDirectory, takeExtension, (</>))
import Text.Printf (printf)
videoDirectory = "C:\\Users\\Swonkie\\Downloads\\Videos"
videoExtensions = [".mp4", ".mkv", ".avi", ".m4v"]
-- ANSI / VT color codes
color = "\ESC[1;31m"
reset = "\ESC[m"
type Library = [Directory]
data Directory = Directory { name :: String
, files :: [Video]
}
instance Show Directory where
show (Directory name files) = " " ++ color ++ name ++ reset ++ "\n" ++ (unlines $ map show files)
data Video = Video { index :: Integer
, path :: FilePath
}
instance Show Video where
show (Video i path) = printf "%3d %s" i (takeBaseName path)
isVideoFile :: FilePath -> Bool
isVideoFile path = takeExtension path `elem` videoExtensions
-- | not used yet
getVideoByIndex :: [Video] -> Integer -> Maybe Video
getVideoByIndex files i =
if length v > 0
then Just (head v)
else Nothing
where v = filter (\ v -> index v == i) files
-- | not used yet
getVideoByName :: [Video] -> String -> Maybe Video
getVideoByName files s =
if length v > 0
then Just (head v)
else Nothing
where v = filter (\ v -> isInfixOf (map toLower s) (map toLower $ takeBaseName $ path v)) files
-- | The name of the folder containing the file, without its parent folders.
bottomFolder :: FilePath -> String
bottomFolder path = last $ splitOn "\\" $ takeDirectory path
-- | A list of all unique directory names which appear in the list of videos.
getDirectories :: [Video] -> [String]
getDirectories videos = nub $ map (bottomFolder . path) videos
-- | Filters the list of videos down to only those which are in a specific directory.
getVideosInDirectory :: [Video] -> String -> [Video]
getVideosInDirectory videos name = filter (\ v -> (bottomFolder $ path v) == name) videos
-- | Bundles the videos in a specific directory in a Directory type.
getDirectory :: [Video] -> String -> Directory
getDirectory videos name = Directory name (getVideosInDirectory videos name)
-- | Creates Video objects with indexes
getVideos :: [FilePath] -> [Video]
getVideos list = [Video (fst tp) (snd tp) | tp <- zip [1..] list]
-- | Gets all the directories of the videos and creates a list of Directory types.
getLibrary :: [Video] -> Library
getLibrary videos = map (getDirectory videos) $ getDirectories videos
getRecursiveContents :: FilePath -> IO [FilePath]
getRecursiveContents topdir = do
names <- listDirectory topdir
paths <- forM names $ \ name -> do
let path = topdir </> name
isDirectory <- doesDirectoryExist path
if isDirectory
then getRecursiveContents path
else return [path]
return (concat paths)
main :: IO ()
main = do
-- get all video files recursively
files <- getRecursiveContents videoDirectory
let videoFiles = sort $ filter isVideoFile files
-- adding a character to the end of the path is a hack, to have subdirs sorted below parent dirs
-- apparently "end of string" is last in the sort order, not first (weird)
let sortedByDirectory = sortBy (\ a b -> compare (takeDirectory a ++ "$") (takeDirectory b ++ "$")) videoFiles
let lib = getLibrary $ getVideos sortedByDirectory
-- show the list of videos
putStrLn ""
putStr $ unlines $ map show lib
</code></pre>
| [] | [
{
"body": "<p>I believe some of the perceived awkwardness comes from the fact that <code>getRecursiveContents</code> throws away the directory structure when building the list of files, and then the code tries to partially reconstruct it in order to print the list.</p>\n\n<p>Another approach would be to use <a ... | {
"AcceptedAnswerId": "201061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T20:20:12.253",
"Id": "201029",
"Score": "6",
"Tags": [
"beginner",
"haskell",
"file-system"
],
"Title": "Command line tool, listing video files on a local drive"
} | 201029 |
<p>I have looked at some previous posts and changed my code accordingly. Do you have some suggestions about my current code? </p>
<p>Here are my specific questions:</p>
<ol>
<li><p>What should <code>top()</code> return if the stack is empty?</p></li>
<li><p>Why it’s better to use <code>size_t</code> for count?</p></li>
<li><p>I didn’t use <code>new</code> to create the stack in <code>main()</code>. Do I need to call the destructor? If no, why? If yes, how should I do it?</p></li>
<li><p>According to the rule of three, how will I define the assignment operator for stack? Can you give one example?</p></li>
<li><p>I feel I have some misunderstanding about <code>private</code>. I put <code>top_node</code> in the private section, but why I am able to access <code>top_node</code> in the copy constructor?</p></li>
</ol>
<p>The following code compiles and runs.</p>
<pre><code>#include<iostream>
using namespace std;
template<class T>
class MyStack{
public:
MyStack(): top_node(nullptr), count(0){};
MyStack(MyStack& st){
top_node = new Node(st.top());
Node* temp = st.top_node->next;
Node* pre = top_node;
while(temp){
Node* cur = new Node(temp->val);
pre->next = cur;
temp = temp->next;
}
count = st.size();
}
void push(T item){
Node* temp = new Node(item);
if(empty()){
top_node = temp;
}else{
temp->next = top_node;
top_node = temp;
}
count++;
}
void pop(){
if(empty()){
cout<<"Nothing to pop!"<<endl;
return;
}
Node* temp = top_node;
top_node = temp->next;
delete temp;
}
int top() const{
if(empty()){
cout<<"Nothing to top!"<<endl;
return -1;
}
return top_node->val;
}
size_t size() const{
return count;
}
void print() const{
Node* temp = top_node;
while(temp){
cout<<temp->val<<" ";
temp = temp->next;
}
cout<<endl;
}
bool empty() const{
return count==0;
}
~MyStack(){
Node* temp = top_node;
while(temp){
Node* t = temp;
temp = temp->next;
delete t;
}
top_node = nullptr;
}
private:
struct Node{
T val;
Node* next;
Node(T x): val(x), next(nullptr){};
};
Node* top_node;
size_t count;
};
int main(){
MyStack<char> sasa;
cout<<"default top: "<<sasa.top()<<endl;
cout<<"default count: "<<sasa.size()<<endl;
sasa.pop();
sasa.push('a');
sasa.push('p');
sasa.push('p');
sasa.print();
sasa.top();
cout<<"The current size is "<<sasa.size()<<endl;
sasa.pop();
sasa.print();
cout<<"if empty: "<<sasa.empty()<<endl;
MyStack<char> sec(sasa);
sec.print();
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T21:35:10.507",
"Id": "387163",
"Score": "0",
"body": "Which C++ version is this targeting? You might get better reviews if we know what to look for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T21:... | [
{
"body": "<blockquote>\n <p>I didn’t use new to create the stack in main(). Do I need to call the destructor? If no, why? If yes, how should I do it?</p>\n</blockquote>\n\n<p>You do not need. It will be automatically called.</p>\n\n<blockquote>\n <p>What should top() return if the stack is empty?</p>\n</bloc... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T20:57:27.780",
"Id": "201031",
"Score": "1",
"Tags": [
"c++",
"c++11",
"linked-list",
"stack"
],
"Title": "Stack implemented with linked list"
} | 201031 |
X11 is an extensible windowing system for bitmap displays. It forms the foundation of most Unix operating system GUIs. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T22:23:19.007",
"Id": "201036",
"Score": "0",
"Tags": null,
"Title": null
} | 201036 |
<p>I use Python daily for long-running simulations (yes, very very optimal, I know). As you could probably guess, my coworkers and I have issues with simulations running for several minutes before finally bombing out. Part of what occupies my free time is finding ways to make out simulation framework detect and report error sooner to reduce turn-around time on bugs. </p>
<p>To that effect, I've written a string of implementations of a "strict interface" library, this being the ultimate version. The user creates "interfaces", which are merely sets of attribute names, that implementing objects are required to define. These sets can be composed to define new interfaces and compared to check mutual compliance. After a user defines a new interface, they "implement" the interface by calling the <code>Implement()</code> function. <code>Implement()</code> generates a mixin with a metaclass, the objective of which is to save the interface into the object and hook the objects's <code>__init__</code> with an interface compliant check. The mixin class also prevents deletions of interface attributes.</p>
<p>This library seems to me to be more useful than the ABC library, at least for me. With ABC, all abstract values are required to be defined before object creation. This library does the check after <code>__init__</code>, but this could be a class's <code>__init__</code>, or a metaclass's <code>__init__</code>.</p>
<p>We use the concept of interfaces throughout our simulation framework, so it's not just useful for arbitrary attribute checks. Those could be done ad-hoc. The typical usage will follow:</p>
<pre><code>""" WRITTEN BY LIBRARY DEV """
# this part is new
WriteDriverInterface = Interface('data', 'start', 'write_now_signal')
# this part is the same as the old way
class WriteDriverInterfaceObject(Implements(WriteDriverInterface), AnonymousObject): pass
def Writer(interfaceObj):
assert WriteDriverInterface <= interfaceObj # but this is new
# from here we know 'data', 'start', and 'write_now_signal' exist and are protected from being deleted
yield RisingEdge(interfaceObj.start) # wait until start
while True:
yield RisingEdge(interfaceObj.write_now_signal)
port <= interfaceObj.data
""" WRITTEN BY LIBRARY USER """
# absolutely no change here, this is how it was done before (for better or worse)
a = Write(WriteDriverInterfaceObject(data = inputport, start = start, write_now_signal = sampler_signal)
</code></pre>
<p>Because this library will be used by people fairly new to programming (co-workers are mostly older engineers and new graduates), I want it to be as intuitive and noninvasive as possible. If the implementation is transparent enough, I could even re-write portions of our reuse libraries with it. And as seen in the above example, the end-user will never touch mixins or metaclasses. Even the library dev doesn't have to touch any of that, which was the point of the <code>Implements()</code> function.</p>
<pre><code>class Interface(frozenset):
"""
Defines an interface for a type that must be defined by instantiation (after __init__). Works in concert with Implements().
Interfaces are just sets of valid attributes and may be composed and compared.
"""
def __new__(cls, *attrs, copyconstruct=None):
if copyconstruct:
return super().__new__(cls, copyconstruct)
# run check to ensure all args are valid attribute names
for attr in attrs:
if not attr.isidentifier():
raise AttributeError(f"{attr} cannot be used as an attribute name.")
#
return super().__new__(cls, attrs)
def __repr__(cls):
return f"Interface({', '.join(cls)})"
"""
Run type fix-ups on result of set operations
"""
# FIXME, is there a cleaner way to go about this?
def union(self, *others):
return Interface(copyconstruct=(super().union(*others)))
def __or__(self, other):
return Interface(copyconstruct=(super().__or__(other)))
def intersection(self, *others):
return Interface(copyconstruct=(super().intersection(*others)))
def __and__(self, other):
return Interface(copyconstruct=(super().__and__(other)))
def difference(self, *others):
return Interface(copyconstruct=(super().difference(*others)))
def __sub__(self, other):
return Interface(copyconstruct=(super().__sub__(other)))
def symmetric_difference(self, other):
return Interface(copyconstruct=(super().symmetric_difference(other)))
def __xor__(self, other):
return Interface(copyconstruct=(super().__xor__(other)))
def copy(self):
return Interface(copyconstructor=self)
def __copy__(self):
return self.copy()
class ImplementMixinBase():
"""
Base class for Interface Implementer mixin
"""
def __delattr__(self, attr):
"""
Protects against deleting interface attributes that would cause the interface spec to not be met
"""
if attr in self.__interface__:
raise AttributeError("{attr} in type's interface, cannot remove.")
else:
# forward del call
super().__del__(attr)
def __init__(self, *args, **kwargs):
"""Simple __init__ that forwards __init__ calls to base objects"""
super().__init__(*args, **kwargs)
class Implementer(type):
"""
Metaclass used to ensure compliance of given interface after the user __init__
"""
def __new__(self, name, parents, namespace):
# hook __init__ with compliance checker
user_init = namespace['__init__'] if '__init__' in namespace else self._fake_no_init
init_hook = self._init_hook
namespace['__init__'] = lambda self, *args, **kwargs: init_hook(user_init, self, *args, **kwargs)
#
return super().__new__(self, name, parents, namespace)
def _init_hook(user_init, self, *args, **kwargs):
# run user __init__
user_init(self, *args, **kwargs)
# run interface compliance check
not_implemented = tuple(attr for attr in self.__interface__ if not hasattr(self, attr))
if len(not_implemented) > 0:
raise NotImplementedError(f"Interface not compliant, missing: {', '.join(not_implemented)}")
def _fake_no_init(self, *args, **kwargs):
"""
If no __init__ is present in class, it is inherited from the superclass. When we hook __init__ we define an __init__
that would otherwise not be there, which ends up overloading the superclass's __init__. So this simple method calls
the superclass's __init__ as there were no __init__ defined in the subclass
"""
super(type(self).__base__, self).__init__(*args, **kwargs)
def Implements(interface):
"""
Function that generates a new interface implementer mixin with the implementer metaclass and __interface__ set
"""
if not isinstance(interface, Interface):
raise ValueError("'interface' argument must be an Interface.")
return Implementer("ImplementMixin", (ImplementMixinBase,), {'__interface__':interface})
# Example
class AnonymousObject():
"""
Creates an object using keyword arguments at __init__
AnonymousObject(a=1, b=2, c=3) # creates an object with the attributes 'a', 'b', and 'c' set to 1, 2, and 3, respectively
"""
def __init__(self, **kwargs):
vars(self).update(kwargs)
# Tests, obviously need to flush this out
InterfaceA = Interface('a', 'b', 'c')
InterfaceB = Interface('d') | InterfaceA
class InterfaceAAnonymousObject(Implements(InterfaceA), AnonymousObject): pass
a = InterfaceAAnonymousObject(a=1, b=2, c=3)
try:
b = InterfaceAAnonymousObject(a=1, b=2)
assert False # should complain about the interface missing 'c'
except NotImplementedError as err:
print(err)
required_interface = Interface('a', 'b')
def do_stuff(obj):
assert isinstance(obj, ImplementMixinBase) # FIXME might change the names around so this is clearer
#assert isinstance(obj, InterfaceObject) # this maybe?
assert required_interface <= obj.__interface__
pass # do stuff here with attributes known to be in object
do_stuff(a)
</code></pre>
<p>I need some feedback on the architecture of my implementation. Could it be simplified? Is there some way to utilize the builtin abstract base classes library to achieve post-<code>__init__</code> interface compliance checking? Am I handling the mixin correct or is there some corner-case I'm missing? Is there some simple feature that would fit well with the rest of the code that would increase the useful of the code? And is there an easier way to get set operations to return an <code>Interface</code> and not a <code>frozenset</code> without the repetitive and probably incomplete set of type-fixing proxy functions I wrote?</p>
<h1>Response to @theodox</h1>
<p>As you can see in the above example of a typical usage, there isn't much expected of either the end-user or the "library" writer. At least given the current implementation. We could easily just define InterfaceObjects like so:</p>
<pre><code>class InterfaceObject():
def __init__(self, data, start, write_now_signal, **kwargs):
pass # this will error if you don't give it all the required args, and you can still use keyword argument syntax
# but who am I?
</code></pre>
<p>I totally agree that creating attributes on the fly using something like <code>AnonymousObject</code> is not a great idea, but it is pervasive throughout the reuse libraries and embedded like shrapnel into the minds of most of the older engineers I work with. It's better to make something that fits easily with what they know. They might actually start using it then. So compliance can only ever be really checked post-<code>__init__</code>.</p>
<blockquote>
<p>A unit test framework that tests for the presence of the expected
attributes might be a better "promise" to maintain than a complex
metaprogramming system that may not be well understood by the newer
members of the staff.</p>
</blockquote>
<p><em>This</em>, however is a great idea. I'm not 100% sure how I would end up going about it with our simulation framework, but I might wander down this path in the future. It might even play well with the suggestion of <code>mypy</code> given by a commenter on the OP.</p>
<p>Finally, I do like your class decorator implementation, it's surprisingly simple and does what I need it to. I had written a class decorator before, but the way it was written defined a new class instead of monkey patching the given class, which I was afraid would break a lot of old code. I am somewhat new to python myself, and it never occurred to me that you could use a decorator to monkey patch class. This is the cleaner solution by far. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T03:58:45.340",
"Id": "387182",
"Score": "0",
"body": "I've already thought of a few things. First, it would be nice to define a function on an `Interface` called `implemented_by()` that would take an object and would return a boolea... | [
{
"body": "<p>You may want to step back and make sure you know where you want to put the responsibility for compliance, and how you want your users to express their expectations. My initial impression (an outsider's to your problem set, of course) is that you're expecting a good deal from \"novice\" users -- m... | {
"AcceptedAnswerId": "201055",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T22:30:00.983",
"Id": "201037",
"Score": "6",
"Tags": [
"python",
"error-handling",
"interface"
],
"Title": "Catching missing attribute errors sooner in Python using strict interface specifications"
} | 201037 |
<p>I created a Greasemonkey script to allow me to quickly fill a specific form on a specific URL, for testing/dev purposes. If the current URL matches any of the urls found in the <code>formsDefault</code> array a button is added to the page that allows the user to auto fill with the default values.</p>
<p>This is my first time using arrow functions in JS.</p>
<pre><code>/*jshint esversion: 6 */
(function($) {
'use strict';
var formDefaults = [
{
urlPattern : '/profile/user',
valueSet : [
{ selector : '#username', value : 'bill' },
{ selector : '#lastname', value : 'miller' },
{ selector : '#auth_pin', value : '1234' },
]
},
{
urlPattern : '/profile/company',
valueSet : [
{ selector : '#companyname', value : 'bill' },
{ selector : '#state', value : 'washington' },
]
},
];
var formFiller = {
valueSet : null,
run(formDefaults) {
var valueSetObj = this.tryEachPattern(this);
if (valueSetObj !== null) {
this.valueSet = valueSetObj.valueSet;
this.showFormFillButton(this);
}
},
tryEachPattern : (_this) => {
var valueSetObj = null;
for (var i = formDefaults.length - 1; i >= 0; i--) {
valueSetObj = formDefaults[i];
var matched = _this.matchUrl(_this, valueSetObj.urlPattern);
if (matched === true)
{
break;
}
}
return valueSetObj;
},
matchUrl : (_this, urlPattern) => {
var matched = !!location.href.match(urlPattern);
return matched;
},
fillForm : (_this) => {
var valueSet = _this.valueSet;
for (var i = valueSet.length - 1; i >= 0; i--) {
var value = valueSet[i];
$(value.selector).val(value.value);
}
},
showFormFillButton : (_this) => {
var button = $('<button type="button" style="position: absolute; right: 10px; bottom: 10px">Auto Fill</button>');
button.on('click', function(event) {
event.preventDefault();
_this.fillForm(_this);
});
$('body').append(button);
},
};
// Ready, set, go
formFiller.run(formDefaults);
})(jQuery);
</code></pre>
| [] | [
{
"body": "<p>While your code is generally easy to read and understand, I believe you have slightly over complicated things, there's no need to define an object with several methods to autocomplete a form.</p>\n\n<p>Before I get to that though, let's take a look at your code.</p>\n\n<ol>\n<li><p>Good work with ... | {
"AcceptedAnswerId": "201046",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T23:36:41.580",
"Id": "201040",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Greasemonkey script to auto fill the values of a form on a specified page"
} | 201040 |
<p>I am extending this post following from <a href="https://codereview.stackexchange.com/questions/200861/generic-single-linked-list-using-smart-pointers/200988?noredirect=1#comment387172_200988">here</a>. I made some of the changes that I could make in the previous post. Although, I have not been successful in creating iterators for my class.</p>
<p>The reason for the new post is to see if there is any additional changes I need to make to my code. As well as steps in creating iterators for this class. Should I perhaps follow what is done <a href="https://www.geeksforgeeks.org/implementing-iterator-pattern-of-a-single-linked-list/" rel="nofollow noreferrer">here</a>?</p>
<p>I am still in the learning process with smart pointers and there is still much I need to learn, I find it useful when people post detailed answers instead of computer science jargon that my ears are still new to.</p>
<p>Here is my header file:</p>
<pre><code>#ifndef SingleLinkedList_h
#define SingleLinkedList_h
template <class T>
class SingleLinkedList {
private:
struct Node {
T data;
std::unique_ptr<Node> next = nullptr;
// disable if noncopyable<T> for cleaner error msgs
explicit Node(const T& x, std::unique_ptr<Node>&& p = nullptr)
: data(x)
, next(std::move(p)) {}
// disable if nonmovable<T> for cleaner error msgs
explicit Node(T&& x, std::unique_ptr<Node>&& p = nullptr)
: data(std::move(x))
, next(std::move(p)) {}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;
void do_pop_front() {
head = std::move(head->next);
}
public:
// Constructors
SingleLinkedList() = default; // empty constructor
SingleLinkedList(SingleLinkedList const &source); // copy constructor
// Rule of 5
SingleLinkedList(SingleLinkedList &&move) noexcept; // move constructor
SingleLinkedList& operator=(SingleLinkedList &&move) noexcept; // move assignment operator
~SingleLinkedList();
// Overload operators
SingleLinkedList& operator=(SingleLinkedList const &rhs);
// This function is for the overloaded operator <<
void display(std::ostream &str) const {
for (Node* loop = head.get(); loop != nullptr; loop = loop->next.get()) {
str << loop->data << "\t";
}
str << "\n";
}
friend std::ostream& operator<<(std::ostream &str, SingleLinkedList &data) {
data.display(str);
return str;
}
// Memeber functions
void swap(SingleLinkedList &other) noexcept;
bool empty() const { return head.get() == nullptr; }
int size() const;
void push_back(const T &theData);
void push_back(T &&theData);
void push_front(const T &theData);
void insertPosition(int pos, const T &theData);
void clear();
void pop_front();
void pop_back();
void deleteSpecific(int delValue);
bool search(const T &x);
};
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T> const &source) {
for(Node* loop = source.head.get(); loop != nullptr; loop = loop->next.get()) {
push_back(loop->data);
}
}
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T>&& move) noexcept {
move.swap(*this);
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
SingleLinkedList<T>::~SingleLinkedList() {
clear();
}
template <class T>
void SingleLinkedList<T>::clear() {
while (head) {
do_pop_front();
}
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList const &rhs) {
SingleLinkedList copy{ rhs };
swap(copy);
return *this;
}
template <class T>
void SingleLinkedList<T>::swap(SingleLinkedList &other) noexcept {
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
}
template <class T>
int SingleLinkedList<T>::size() const {
int size = 0;
for (auto current = head.get(); current != nullptr; current = current->next.get()) {
size++;
}
return size;
}
template <class T>
void SingleLinkedList<T>::push_back(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
if (!head) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_back(T &&thedata) {
std::unique_ptr<Node> newnode = std::make_unique<Node>(std::move(thedata));
if (!head) {
head = std::move(newnode);
tail = head.get();
}
else {
tail->next = std::move(newnode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_front(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
newNode->next = std::move(head);
head = std::move(newNode);
}
template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
if (pos > size() || pos < 0) {
throw std::out_of_range("The insert location is invalid.");
}
auto node = head.get();
int i = 0;
for (; node && node->next && i < pos; node = node->next.get(), i++);
if (i != pos) {
throw std::out_of_range("Parameter 'pos' is out of range.");
}
auto newNode = std::make_unique<Node>(theData);
if (node) {
newNode->next = std::move(node->next);
node->next = std::move(newNode);
}
else {
head = std::move(newNode);
}
}
template <class T>
void SingleLinkedList<T>::pop_front() {
if (empty()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
do_pop_front();
}
template <class T>
void SingleLinkedList<T>::pop_back() {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto current = head.get();
Node* previous = nullptr;
while (current->next != nullptr) {
previous = current;
current = current->next.get();
}
tail = previous;
previous->next = nullptr;
}
template <class T>
void SingleLinkedList<T>::deleteSpecific(int delValue) {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto temp1 = head.get();
Node* temp2 = nullptr;
while (temp1->data != delValue) {
if (temp1->next == nullptr) {
throw std::invalid_argument("Given node not found in the list!!!");
}
temp2 = temp1;
temp1 = temp1->next.get();
}
temp2->next = std::move(temp1->next);
}
template <class T>
bool SingleLinkedList<T>::search(const T &x) {
auto current = head.get();
while (current) {
if (current->data == x) {
return true;
}
current = current->next.get();
}
return false;
}
#endif /* SingleLinkedList_h*/
</code></pre>
<p>Here is the main.cpp file:</p>
<pre><code>//
// main.cpp
// Data Structure - LinkedList
//
// Created by Morgan Weiss on 7/24/2018
// Copyright © 2018 Morgan Weiss. All rights reserved.
//
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
#include <utility>
#include <stdexcept>
#include <ostream>
#include <iosfwd>
#include <stdexcept>
#include "SingleLinkedList.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////
///////////////////////////// Single Linked List //////////////////////
///////////////////////////////////////////////////////////////////////
SingleLinkedList<int> obj;
obj.push_back(2);
obj.push_back(4);
obj.push_back(6);
obj.push_back(8);
obj.push_back(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------displaying all nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.push_front(50);
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------inserting at particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertPosition(5,60);
std::cout << obj << "\n";
std::cout << "\n--------------------------------------------------\n";
std::cout << "-------------Get current size ---=--------------------";
std::cout << "\n--------------------------------------------------\n";
std::cout << obj.size() << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_front();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at end-----------------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_back();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"--------------Deleting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteSpecific(4);
std::cout << obj << "\n";
obj.search(8) ? printf("yes"):printf("no");
std::cout << "\n--------------------------------------------------\n";
std::cout << "--------------Testing copy----------------------------";
std::cout << "\n--------------------------------------------------\n";
SingleLinkedList<int> obj1 = obj;
std::cout << obj1 << "\n";
//std::cout << "\n-------------------------------------------------------------------------\n";
//std::cout << "--------------Testing to insert in an empty list----------------------------";
//std::cout << "\n-------------------------------------------------------------------------\n";
//SingleLinkedList<int> obj2;
//obj2.insertPosition(5, 60);
//std::cout << obj2 << "\n";
std::cin.get();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T00:33:34.070",
"Id": "387179",
"Score": "0",
"body": "@hoffmale Thank you, I really appreciate that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T00:50:33.783",
"Id": "387295",
"Score": "0"... | [
{
"body": "<h3>Move <code>public</code> section of the class to the top</h3>\n<p>I prefer, and suggest others, to put the <code>public</code> section of a class before the <code>protected</code> and <code>private</code> sections.</p>\n<p>The rationale for it is that users of the class want to see the <code>publ... | {
"AcceptedAnswerId": "201049",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-05T23:55:55.937",
"Id": "201042",
"Score": "2",
"Tags": [
"c++",
"beginner",
"linked-list",
"pointers"
],
"Title": "Generic Single Linked List Using Smart Pointers Follow up"
} | 201042 |
<p>The <code>Helloworld</code> class executes all of the methods. <code>Human</code> is the interface, and <code>Nate</code> & <code>Ryan</code> are two classes that implement the <code>Human</code> interface. Are there any deficiencies or faults that my code contains that could help me in the long run?</p>
<pre><code>public class Helloworld{
public static void main(String[] args) {
Human ryan = new Ryan();
ryan.setHeight(12);
System.out.println("Ryan's height is " + ryan.getHeight());
Human nate = new Nate();
nate.setHeight(32);
System.out.println("Nate's height is " + nate.getHeight());
nate.hit(ryan);
/*
* OUTPUT --------------------------------------
*
* Ryan's height is 12
* Nate's height is 32
* Nate has hit Ryan
*
*/
}
}
</code></pre>
<pre><code>interface Human{
public void sleep();
public void eat();
public void wakeUp();
public void walk();
public void hit(Human name);
public void setHeight(int height);
public int getHeight();
public String getName();
}
</code></pre>
<pre><code>class Nate implements Human{
int height = 0;
final String name = "Nate";
public String getName() {
return this.name;
}
public void setHeight(int height) {
if(height > 0) {
this.height = height;
}else {
System.out.println("You can't set Nate's height to less than 0.");
}
}
public int getHeight() {
return this.height;
}
public void sleep() {
System.out.println("Nate has fallen asleep");
}
public void eat() {
System.out.println("Nate has eaten");
}
public void wakeUp() {
System.out.println("Nate has woken up");
}
public void walk() {
System.out.println("Nate is walking");
}
public void hit(Human name) {
System.out.println("Nate has hit " + name.getName());
}
}
</code></pre>
<pre><code>class Ryan implements Human{
int height = 0;
final String name = "Ryan";
public String getName() {
return this.name;
}
public void setHeight(int height) {
if(height > 0) {
this.height = height;
}else {
System.out.println("You can't set Ryan's height to less than 0.");
}
}
public int getHeight() {
return this.height;
}
public void sleep() {
System.out.println("Ryan has fallen asleep");
}
public void eat() {
System.out.println("Ryan has eaten");
}
public void wakeUp() {
System.out.println("Ryan has woken up");
}
public void walk() {
System.out.println("Ryan is walking");
}
public void hit(Human name) {
System.out.println("Ryan has hit " + name.getName());
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T06:27:04.813",
"Id": "387188",
"Score": "2",
"body": "From what data you are storing, Nate and Ryan should be objects of Human class, they shouldn't be two different classes violating DRY principle."
}
] | [
{
"body": "<p>What is the purpose of your code ? Without clear intentions it is harder to review it because many decisions may be taken regarding a context that we don't have.</p>\n\n<p>From what I see, both <code>Ryan</code> and <code>Nate</code> can be two instances of the same <code>Human</code> class. The t... | {
"AcceptedAnswerId": "201052",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T04:50:32.793",
"Id": "201047",
"Score": "0",
"Tags": [
"java",
"beginner",
"object-oriented",
"interface"
],
"Title": "\"Human\" interfaces with two implementation classes"
} | 201047 |
<p>Looking to improve building UI in pure ES6. </p>
<p>This is the pattern I have adopted and has worked fairly well. This code increments the count, sets a data attribute to toggle the button, and issues a POST to the server with the vote payload object.</p>
<pre><code>import axios from "axios";
class Vote {
constructor(el) {
this.el = el;
this.url = this.el.dataset.url;
this.id = this.el.dataset.id;
this.count = this.el.dataset.count;
this.count_el = this.el.querySelector('span.count')
this.setClickHandlers();
}
setClickHandlers() {
this.el.addEventListener("click", ()=> {
this.postVote();
this.toggle();
this.toggleCount();
})
}
postVote() {
axios({
url: this.url,
method: 'post',
data: { "idea":
{"id": this.id}
}
})
.then((data) => {
console.log(`${data}: Posted vote`);
})
.catch((data) => {
console.log(data);
})
}
toggle() {
if (this.el.dataset.toggled == "true") {
this.el.dataset.toggled = "false"
} else {
this.el.dataset.toggled = "true"
}
}
toggleCount() {
var current = parseInt(this.count_el.innerHTML);
if (this.el.dataset.toggled == "true") {
this.count_el.innerHTML = ++current;
} else {
this.count_el.innerHTML = --current;
}
}
}
document.addEventListener("turbolinks:load", ()=> {
let votes = document.querySelectorAll('[data-vote]');
if (votes.length) {
votes.forEach((el) => {
new Vote(el);
})
}
});
</code></pre>
| [] | [
{
"body": "<h1>Consistency</h1>\n\n<p>Sometimes you use snake_case and sometimes you use camelCase: in JavaScript we usually use camel case, it's not mandatory but stick to one. Then, for example, <code>count_el</code> should be <code>countEl</code> (or a better, more descriptive name, IMHO no need to abbreviat... | {
"AcceptedAnswerId": "201067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T05:32:23.457",
"Id": "201050",
"Score": "5",
"Tags": [
"javascript",
"ecmascript-6",
"ajax",
"dom",
"promise"
],
"Title": "Upvote/counter in Javascript"
} | 201050 |
<p>I recently read "The C++ programming language" chapter 22 and I thought the example given in chapter 22.2.4 was quite interesting. I thought it should be possible to make this system caching, so it could be used as a resource cache. It's unlike most other approaches I found on the net, and I got it working (the code in the book has a couple of typos). I wonder whether this is a good approach to use in real code. The usage is simple, and for every kind of resource, the only thing that has to be added is the load function.</p>
<p>It prints 42 twice, but the second time it's from the cache. I chose to store weak_ptr's and give shared_ptr's, so the cache doesn't keep the resources alive when not used anymore. Of course, it's just as valid to store unique_ptr's and give out non-owning raw pointers. But in that case, the lifetime of the resources is equal to the lifetime of the cache (unless the cache is purged manually).</p>
<pre><code>#include <iostream>
#include <filesystem>
#include <type_traits>
#include <memory>
#include <map>
namespace fs = std::filesystem;
class Resource_base
{
public:
virtual Resource_base* clone() const = 0; //must be polymorphic to allow dynamic_cast
virtual ~Resource_base() {}
};
//using Pf = Resource_base * (*)(const std::string& key); // classic way
using Pf = std::add_pointer_t<Resource_base*(const std::string& key)>; // C++ 14 way
std::map<std::string, Pf> loadfuncs;
std::map<std::string, fs::path> paths;
std::map<std::string, std::weak_ptr<Resource_base>> cache;
std::shared_ptr<Resource_base> get_obj(const std::string& key)
{
if (auto res = cache[key].lock())
{
return res;
}
if (auto f = loadfuncs[key])
{
auto res = std::shared_ptr<Resource_base>(f(key));
cache[key] = res;
return res;
}
return nullptr;
}
template <typename T>
struct Resource : Resource_base
{
T val;
explicit Resource(fs::path);
Resource* clone()const override { return new Resource(*this); }
static Resource_base* load_resource(const std::string& key)
{
auto file = paths[key];
return new Resource(file);
}
};
template <typename T>
T* get_val(Resource_base* p)
{
if (auto pp = dynamic_cast<Resource<T>*>(p)) return &pp->val;
return nullptr;
}
using Int_resource = Resource<int>;
Int_resource::Resource(fs::path file)
{
val = 42; // dummy, most resources should load from file
}
int main()
{
loadfuncs["bla"] = &Int_resource::load_resource;
paths["bla"] = fs::path("d:/temp");
auto p{ get_obj("bla") };
if (auto sp = get_val<int>(p.get()))
{
std::cout << *sp << std::endl;
}
auto q{ get_obj("bla") };
if (auto sp2 = get_val<int>(q.get()))
{
std::cout << *sp2 << std::endl;
}
std::cout << "hello world" << std::endl;
}
</code></pre>
<p>Edit: Refined it a bit more:
- put the three tables in a struct, to make it easier to control visibility
- made get_obj a member function of the Cache struct
- moved the construction of the shared_ptr to the creation of the object itself</p>
<p>I like this approach. The best thing about it, is that it subclasses the resource, not the cache, so you don't end up with a Font_cache, Texture_cache, Sound_cache etc. Just one cache for all resources. The point of the original example was to demonstrate dynamic_cast, but I think the really clever bit is the table of function pointers. </p>
<p>The new code:</p>
<pre><code>#pragma once
#include <iostream>
#include <filesystem>
#include <type_traits>
#include <memory>
#include <map>
#include <SFML/Graphics.hpp>
namespace fs = std::filesystem;
class Resource_base
{
public:
virtual Resource_base* clone() const = 0;
virtual ~Resource_base() {}
};
//using Pf = std::shared_ptr<Resource_base> (*)(fs::path); // classic way
using Pf = std::add_pointer_t<std::shared_ptr<Resource_base>(fs::path)>; // C++ 14 way
struct Cache
{
std::map<std::string, Pf> loadfuncs;
std::map<std::string, fs::path> paths;
std::map<std::string, std::weak_ptr<Resource_base>> cache;
std::shared_ptr<Resource_base> get_obj(const std::string& key)
{
if (auto res = cache[key].lock())
{
return res;
}
if (auto f = loadfuncs[key])
{
auto path = paths.at(key);
auto res = f(path);
cache[key] = res;
return res;
}
return nullptr;
}
};
template <typename T>
struct Resource : Resource_base
{
T val;
explicit Resource(fs::path);
Resource* clone()const override { return new Resource(*this); }
static std::shared_ptr<Resource_base> load_resource(fs::path path)
{
return std::make_shared<Resource>(path);
}
};
template <typename T>
T* get_val(Resource_base* p)
{
if (auto pp = dynamic_cast<Resource<T>*>(p)) return &pp->val;
return nullptr;
}
using Texture_resource = Resource<sf::Texture>;
Texture_resource::Resource(fs::path file)
{
val.loadFromFile(file.string());
}
</code></pre>
<p>Edit 24-5-2019:
Recently, I realised this can be simplified quite a bit using a variant instead of the inheritance and dynamic_cast used here. Also, the syntax for function pointers is kind of evil, using std::function and lambda's is more easy to the eye. The code becomes this:</p>
<pre><code>#include <iostream>
#include <filesystem>
#include <memory>
#include <map>
#include <functional>
#include <variant>
//#include <SFML/Graphics.hpp>
namespace fs = std::filesystem;
using Resource = std::variant<int, std::string>;
using Pf = std::function<Resource(fs::path)>;
struct Cache
{
std::map<std::string, Pf> loadfuncs;
std::map<std::string, fs::path> paths;
std::map<std::string, std::weak_ptr<Resource>> cache;
std::shared_ptr<Resource> get_obj(const std::string& key)
{
if (auto res = cache[key].lock())
{
return res;
}
if (auto f = loadfuncs[key])
{
auto path = paths.at(key);
auto res = std::make_shared<Resource> (f(path));
cache[key] = res;
return res;
}
return nullptr;
}
};
auto int_loader = [](fs::path p)->Resource {return 42; };
auto string_loader = [](fs::path p) -> Resource {return "hello world"; };
int main()
{
Cache c;
c.loadfuncs["bla"] = int_loader;
c.loadfuncs["hello"] = string_loader;
c.paths["bla"] = fs::path("d:/temp");
c.paths["hello"] = fs::path("d:/temp");
auto p{ c.get_obj("bla") };
auto sp = std::get<int>(*p);
std::cout << sp << std::endl;
auto q{ c.get_obj("bla") };
auto sp2 = std::get<int>(*q);
std::cout << sp2 << std::endl;
auto i{ c.get_obj("hello") };
auto str = std::get<std::string>(*i);
std::cout << str << std::endl;
}
</code></pre>
<p>It prints
42
42
hello world</p>
<p>Of course de load functions are dummies: in reality they would take the path parameter to load the resource from file.</p>
<p>This solution is quite a bit shorter and it does work. But I guess it is not without a cost: the variant is as big as the biggest member (plus some overhead) and if one of the resources is big, that could lead to a waste of memory. In performance terms, I guess the variant does about the same thing under the hood as what the older code did. What do you think is better?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T20:29:00.357",
"Id": "427716",
"Score": "0",
"body": "Why are the lambdas outside `main` and not directly assigned to the `loadfuncs` map? Why are you passing `std::path` along, it doesn't seem to be doing anything?"
},
{
"C... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T11:27:09.367",
"Id": "201063",
"Score": "6",
"Tags": [
"c++",
"cache"
],
"Title": "Resource cache based on Stroustrup 22.2.4"
} | 201063 |
<p>I have following task, form a given array, I want the longest ascending array.
I will give you an example </p>
<pre><code>int[] a = {19,12,13,1,2,3,4,5,14,23,24,25,26,31,32};
</code></pre>
<p>will return array of <code>{1,2,3,4,5}</code> - that is the largest sequence of ascending numbers in the given array.</p>
<p>Below is the sample code:</p>
<pre><code>int[] a = {19,12,13,1,2,3,4,5,14,23,24,25,26,27,31,32};
List<Integer> longestArray = new ArrayList<Integer>();
List<Integer> currentArary = new ArrayList<Integer>();
for (int i = 1; i < a.length; i++) {
if(currentArary.isEmpty()) {
currentArary.add(a[i-1]);
}
if (a[i]-1 == a[i-1]) {
currentArary.add(a[i]);
} else {
if(longestArray.size()<currentArary.size()) {
longestArray.clear();
longestArray.addAll(currentArary);
}
currentArary.clear();
}
}
System.out.println(longestArray);
</code></pre>
<p>Any feedback received on this method is more than welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T13:14:15.390",
"Id": "387227",
"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><strong>Variable names/typos</strong></p>\n\n<p>In 7 places, you've written <code>Arary</code> instead of <code>Array</code>. A single simple review of your own code should have caught that.</p>\n\n<p><strong>Separation of concerns/testability</strong></p>\n\n<p>Instead of having a function with t... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T11:35:42.800",
"Id": "201064",
"Score": "3",
"Tags": [
"java",
"algorithm"
],
"Title": "Find the longest ascending subarray from a given array"
} | 201064 |
<p>I have a table of users, where each user has a group (or multiple groups) he/she is part of. </p>
<p>Currently I'm handling the users group via a Users class: </p>
<pre><code><?php
/**
*
* User (class) Model: Handles users (not system users).
*
*/
class User{
/*=================================
= Variables =
=================================*/
# Database instance
private $db;
# Users ID
public $user_id;
# User Realm
public $realm;
# User Name
public $user_name;
# User display name
public $display_name;
# User creation
public $created;
# User last seen
public $last_seen;
# Is user deleted?
public $deleted;
# Is user ignored?
public $ignored;
# Is user blacklisted
public $blacklisted;
# Is user whitelisted
public $whitelisted;
# Is user blocked
public $blocked;
# Is user filtered
public $filtered;
# User Group
public $group = array();
/*===============================
= Methods =
================================*/
/**
*
* Constructor
* @param $user_id Init User id.
* @throws Object User object of a single user.
*
*/
public function __construct($user_id) {
# Get database instance
$this->db = Database::getInstance();
# If user_id isn't passed
if ( $user_id ) {
# Get this user by id
$this->get_user_by_id($user_id);
}
}
/**
*
* Get user by id
* @param $id Init User id
* @throws Object Returns the object with data applied.
*
*/
private function get_user_by_id($id)
{
if ($id) {
# Search for the user in the Database 'users' table.
$data = $this->db->row("SELECT user_id, realm, user_name, display_name, created, last_seen, deleted, ignored, blacklisted, whitelisted, blocked, filtered FROM users WHERE user_id = :id", array('id' => $id));
# If there is a result
if ( $data ) {
# Get group/s
// -- Get Group method --
# Set data in this user object
$this->data($data);
return $this;
} else { return false; }
} else {
return false;
}
}
/**
*
* Insert Data to this object
* @param $data Array Gets a result array of user data
*
*/
private function data($data)
{
# Set data for this user object
$this->user_id = $data['user_id'];
$this->realm = $data['realm'];
$this->user_name = $data['user_name'];
$this->display_name = $data['display_name'];
$this->created = $data['created'];
$this->last_login = $data['last_seen'];
$this->deleted = $data['deleted'];
$this->ignored = $data['ignored'];
$this->blacklisted = $data['blacklisted'];
$this->whitelisted = $data['whitelisted'];
$this->blocked = $data['blocked'];
$this->filtered = $data['filtered'];
// $this->group = $data['group'];
}
</code></pre>
<p>I have just added the group variable, and not sure if it's "good practice" to add a <code>fetch_group_by_user_id()</code> method (separate table in my DB), or create a new group object, and use it inside my User class. </p>
<p>My user class is pasted ^ </p>
<p>Please review my User class code and update me if you think it can be written better, and please tell me what is best to fetch the group. </p>
| [] | [
{
"body": "<h2>Logical inconsistencies</h2>\n\n<p>You create a <code>User</code> object expecting a <code>user_id</code> to be passed to setup the object, id object to this design but im sure you've got it covered, but then later on you ask for a <code>user_id</code> to run a query? </p>\n\n<p>I would leave it ... | {
"AcceptedAnswerId": "201076",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T11:50:48.173",
"Id": "201066",
"Score": "1",
"Tags": [
"php",
"object-oriented"
],
"Title": "Should I add the \"fetch_group\" method to my user class or should I create a separate class for group"
} | 201066 |
<p>I am developing a microservice that enables business partners to order systems for common customers:</p>
<pre><code>/*
ordering.js - Terminal ordering JavaScript library.
(C) 2017 HOMEINFO - Digitale Informationssysteme GmbH
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
Maintainer: Richard Neumann <r dot neumann at homeinfo period de>
Requires:
* jquery.js
* sweetalert.js
* homeinfo.js
* his.js
*/
'use strict';
var ordering = ordering || {};
/*
Static globals.
*/
ordering._BASE_URL = 'https://top.secret.com/endpoint';
ordering._ORDERS_ENDPOINT = ordering._BASE_URL + '/order';
ordering._CUSTOMERS_ENDPOINT = ordering._BASE_URL + '/customers';
ordering._CLASSES_ENDPOINT = ordering._BASE_URL + '/classes';
ordering._OSS_ENDPOINT = ordering._BASE_URL + '/oss';
/*
Runtime globals.
*/
ordering.orders = ordering.orders || [];
ordering.customers = ordering.customers || [];
ordering.classes = ordering.classes || [];
ordering.oss = ordering.oss || [];
/*
Displays an error using sweetalert.
*/
ordering.error = function (title, text, type) {
return function () {
swal({
title: title,
text: text,
type: type || 'error'
});
};
};
/*
Queries orders from the API.
*/
ordering._getOrders = function () {
return his.auth.get(ordering._ORDERS_ENDPOINT).then(
function (orders) {
ordering.orders = orders;
},
ordering.error('Fehler.', 'Konnte verfügbare Bestellungen nicht abfragen.')
);
};
/*
Queries customers from the API.
*/
ordering._getCustomers = function () {
return his.auth.get(ordering._CUSTOMERS_ENDPOINT).then(
function (customers) {
ordering.customers = customers;
},
ordering.error('Fehler.', 'Konnte verfügbare Kunden nicht abfragen.')
);
};
/*
Queries classes from the API.
*/
ordering._getClasses = function () {
return his.auth.get(ordering._CLASSES_ENDPOINT).then(
function (classes) {
ordering.classes = classes;
},
ordering.error('Fehler.', 'Konnte verfügbare Terminal-Klassen nicht abfragen.')
);
};
/*
Queries classes from the API.
*/
ordering._getOSs = function () {
return his.auth.get(ordering._OSS_ENDPOINT).then(
function (oss) {
ordering.oss = oss;
},
ordering.error('Fehler.', 'Konnte verfügbare Betriebssysteme nicht abfragen.')
);
};
/*
Performs a HIS login.
*/
ordering._login = function () {
var queryString = new homeinfo.QueryString();
return his.session.login(queryString.userName, queryString.passwd);
};
/*
Initializes the page.
*/
ordering.init = function () {
ordering._login().then(
ordering._getData().then(
ordering._initPage
)
);
};
/*
Submit form.
*/
ordering._submitForm = function (event) {
event.preventDefault(); // Avoid to execute the actual submit of the form.
his.auth.post(ordering._ORDERS_ENDPOINT, jQuery('#orders').serialize()).then(ordering._resetForm);
};
/*
Resets the form.
*/
ordering._resetForm = function () {
document.getElementById('orders').reset();
ordering.init();
};
/*
Initialization function.
*/
ordering._getData = function () {
var getOrders = ordering._getOrders();
var getCustomers = ordering._getCustomers();
var getClasses = ordering._getClasses();
var getOSs = ordering._getOSs();
return Promise.all([getOrders, getCustomers, getClasses, getOSs]);
};
/*
Refreshes the orders list.
*/
ordering._renderList = function () {
var tableContainer = document.getElementById('tableContainer');
tableContainer.innerHTML = '';
tableContainer.appendChild(ordering._dom.list());
};
/*
Renders the orders input.
*/
ordering._renderOrders = function () {
var formContainer = document.getElementById('formContainer');
formContainer.innerHTML = '';
formContainer.appendChild(ordering._dom.orders());
};
/*
Initializes the page.
*/
ordering._initPage = function () {
ordering._renderList();
ordering._renderOrders();
jQuery('#orders').submit(ordering._submitForm);
};
/*
Deletes the respective order.
*/
ordering._deleteOrder = function (id) {
return his.auth.delete(ordering._ORDERS_ENDPOINT + '/' + id).then(ordering._getData).then(ordering._renderList);
};
/*
Adds an order.
*/
ordering._addOrderForm = function () {
var orderForms = document.getElementById('orderForms');
var order = ordering._dom.order(true);
orderForms.appendChild(order);
};
/*
Deletes the respective order form.
*/
ordering._deleteOrderForm = function (index) {
var orderForms = document.getElementById('orderForms');
var order = document.getElementById('order_' + index);
orderForms.removeChild(order);
};
/*
DOM model.
*/
ordering._dom = ordering._dom || {};
ordering._dom.COLUMNS = [
'Konto', 'Bestelldatum', 'Bearbeitungsstatus', 'Kunde', 'Klasse', 'Betriebssystem', 'Adresse', 'Anmerkung',
'Stornieren'];
/*
ID of orders form.
*/
ordering._dom.ORDERS = 0;
/*
Builds an order set.
*/
ordering._dom.orders = function () {
var form = document.createElement('form');
form.setAttribute('id', 'orders');
var orderForms = document.createElement('div');
orderForms.setAttribute('id', 'orderForms');
orderForms.setAttribute('class', 'row row-center');
var firstOrder = ordering._dom.order();
orderForms.appendChild(firstOrder);
form.appendChild(orderForms);
form.appendChild(ordering._dom.buttonAddOrderForm());
form.appendChild(document.createTextNode(' '));
form.appendChild(ordering._dom.submit());
return form;
};
/*
Creates a button to add an order form input for a further terminal.
*/
ordering._dom.buttonAddOrderForm = function () {
var button = document.createElement('button');
button.setAttribute('class', 'btn btn-success');
button.setAttribute('onclick', 'ordering._addOrderForm();');
button.textContent = 'Weiteres Terminal hinzufügen.';
return button;
};
/*
Creates a button to delete the respective oder inputs.
*/
ordering._dom.buttonDeleteOrderForm = function (index) {
var buttonDeleteOrderForm = document.createElement('button');
buttonDeleteOrderForm.setAttribute('onclick', 'ordering._deleteOrderForm(' + index + ');');
buttonDeleteOrderForm.setAttribute('class', 'btn btn-danger');
buttonDeleteOrderForm.textContent = 'X';
return buttonDeleteOrderForm;
};
/*
Creates a button to delete the respective order.
*/
ordering._dom.buttonDeleteOrder = function (id) {
var button = document.createElement('button');
button.setAttribute('class', 'btn btn-danger');
button.setAttribute('onclick', 'ordering._deleteOrder(' + id + ');');
button.textContent = 'X';
return button;
};
/*
Creates the title for the terminal order.
*/
ordering._dom.caption = function (index, additional) {
var caption = document.createElement('legend');
var textNode = document.createTextNode('Terminal ');
caption.appendChild(textNode);
if (additional) {
caption.appendChild(ordering._dom.buttonDeleteOrderForm(index));
}
return caption;
};
/*
Builds a single order.
*/
ordering._dom.order = function (additional) {
if (additional == null) {
additional = false;
}
var index = ordering._dom.ORDERS;
ordering._dom.ORDERS += 1;
var order = document.createElement('fieldset');
order.setAttribute('id', 'order_' + index);
order.setAttribute('class', 'row');
var caption = ordering._dom.caption(index, additional);
order.appendChild(caption);
var columnSelects = document.createElement('div');
columnSelects.setAttribute('class', 'col-md-6');
var customerSelect = ordering._dom.customerSelect(index);
columnSelects.appendChild(customerSelect);
var classSelect = ordering._dom.classSelect(index);
columnSelects.appendChild(classSelect);
var osSelect = ordering._dom.osSelect(index);
columnSelects.appendChild(osSelect);
var columnAddress = document.createElement('div');
columnAddress.setAttribute('class', 'col-md-6');
var address = ordering._dom.address(index);
columnAddress.appendChild(address);
order.append(columnSelects);
order.append(columnAddress);
return order;
};
/*
Builds a default option for a dropdown list.
*/
ordering._dom.defaultOption = function (text) {
var defaultOption = document.createElement('option');
var attributeSelected = document.createAttribute('selected');
defaultOption.setAttributeNode(attributeSelected);
var attributeDisabled = document.createAttribute('disabled');
defaultOption.setAttributeNode(attributeDisabled);
defaultOption.textContent = text;
return defaultOption;
};
/*
Builds the customer selection dropdown menu.
*/
ordering._dom.customerSelect = function (index) {
var select = document.createElement('select');
select.setAttribute('required', true);
select.setAttribute('name', 'customer_' + index);
select.setAttribute('class', 'form-control');
var defaultOption = ordering._dom.defaultOption('Kunde*');
select.appendChild(defaultOption);
for (var i = 0; i < ordering.customers.length; i++) {
var customer = ordering.customers[i];
var option = document.createElement('option');
option.setAttribute('value', customer.id);
option.textContent = customer.company.name;
select.appendChild(option);
}
return select;
};
/*
Builds the class selection dropdown menu.
*/
ordering._dom.classSelect = function (index) {
var select = document.createElement('select');
select.setAttribute('required', true);
select.setAttribute('name', 'class_' + index);
select.setAttribute('class', 'form-control');
var defaultOption = ordering._dom.defaultOption('Klasse*');
select.appendChild(defaultOption);
for (var i = 0; i < ordering.classes.length; i++) {
var class_ = ordering.classes[i];
var option = document.createElement('option');
option.setAttribute('value', class_.id);
option.textContent = class_.full_name;
select.appendChild(option);
}
return select;
};
/*
Builds the operating system selection dropdown menu.
*/
ordering._dom.osSelect = function (index) {
var select = document.createElement('select');
select.setAttribute('required', true);
select.setAttribute('name', 'os_' + index);
select.setAttribute('class', 'form-control');
var defaultOption = ordering._dom.defaultOption('Betriebssystem*');
select.appendChild(defaultOption);
for (var i = 0; i < ordering.oss.length; i++) {
var os = ordering.oss[i];
var option = document.createElement('option');
option.setAttribute('value', os.id);
option.textContent = os.name + ' ' + os.version;
select.appendChild(option);
}
return select;
};
/*
Builds the address input fields.
*/
ordering._dom.address = function (index) {
var address = document.createElement('fieldset');
address.setAttribute('class', 'form-group');
var street = document.createElement('input');
street.setAttribute('type', 'text');
street.setAttribute('required', true);
street.setAttribute('name', 'street_' + index);
street.setAttribute('placeholder', 'Straße*');
address.appendChild(street);
var houseNumber = document.createElement('input');
houseNumber.setAttribute('type', 'text');
houseNumber.setAttribute('required', true);
houseNumber.setAttribute('name', 'houseNumber_' + index);
houseNumber.setAttribute('placeholder', 'Hausnummer*');
address.appendChild(houseNumber);
var zipCode = document.createElement('input');
zipCode.setAttribute('type', 'text');
zipCode.setAttribute('required', true);
zipCode.setAttribute('name', 'zipCode_' + index);
zipCode.setAttribute('placeholder', 'PLZ*');
address.appendChild(zipCode);
var city = document.createElement('input');
city.setAttribute('type', 'text');
city.setAttribute('required', true);
city.setAttribute('name', 'city_' + index);
city.setAttribute('placeholder', 'Ort*');
address.appendChild(city);
var annotation = document.createElement('input');
annotation.setAttribute('type', 'text');
annotation.setAttribute('name', 'annotation_' + index);
annotation.setAttribute('placeholder', 'Anmerkung');
address.appendChild(annotation);
return address;
};
/*
Builds a submit button.
*/
ordering._dom.submit = function () {
var submit = document.createElement('input');
submit.setAttribute('type', 'submit');
submit.setAttribute('value', 'Kostenpflichtig bestellen.');
submit.setAttribute('class', 'btn btn-primary');
return submit;
};
/*
Builds the list of existing orders.
*/
ordering._dom.list = function () {
var table = document.createElement('table');
table.setAttribute('id', 'list');
table.setAttribute('class', 'table table-hover');
var thead = document.createElement('thead');
var tr = document.createElement('tr');
var th;
for (var i = 0; i < ordering._dom.COLUMNS.length; i++) {
th = document.createElement('th');
th.setAttribute('scope', 'col');
th.textContent = ordering._dom.COLUMNS[i];
tr.appendChild(th);
}
thead.appendChild(tr);
var tbody = document.createElement('tbody');
var empty = true;
for (var attr in ordering.orders) {
if (ordering.orders.hasOwnProperty(attr)) {
empty = false;
tbody.appendChild(ordering._dom.listItem(ordering.orders[attr]));
}
}
if (empty) {
var h2 = document.createElement('h2');
h2.setAttribute('align', 'center');
h2.textContent = 'Keine Bestellungen vorhanden.';
return h2;
}
table.appendChild(thead);
table.appendChild(tbody);
return table;
};
/*
Builds the list items for each existing order.
*/
ordering._dom.listItem = function (order) {
var row = document.createElement('tr');
var columnAccount = document.createElement('td');
columnAccount.textContent = order.account.name;
row.appendChild(columnAccount);
var columnIssued = document.createElement('td');
columnIssued.textContent = order.issued;
row.appendChild(columnIssued);
var columnAccepted = document.createElement('td');
var notProcessedYet = 'Noch nicht bearbeitet.';
switch (order.accepted) {
case null:
columnAccepted.textContent = notProcessedYet;
break;
case undefined:
columnAccepted.textContent = notProcessedYet;
break;
case true:
columnAccepted.textContent = 'Angelegt.';
break;
case false:
columnAccepted.textContent = 'Auftrag abgewiesen.';
break;
}
row.appendChild(columnAccepted);
var columnCustomer = document.createElement('td');
columnCustomer.textContent = order.customer.company.name + ' (' + order.customer.id + ')';
row.appendChild(columnCustomer);
var columnClass = document.createElement('td');
columnClass.textContent = order.class_.name;
row.appendChild(columnClass);
var columnOs = document.createElement('td');
columnOs.textContent = order.os.name + ' ' + order.os.version;
row.appendChild(columnOs);
var columnAddress = document.createElement('td');
var address = order.address;
columnAddress.textContent = address.street + ' ' + address.house_number + ', ' + address.zip_code + ' ' + address.city;
row.appendChild(columnAddress);
var columnAnnotation = document.createElement('td');
columnAnnotation.textContent = order.annotation || '-';
row.appendChild(columnAnnotation);
var columnDelete = document.createElement('td');
columnDelete.appendChild(ordering._dom.buttonDeleteOrder(order.id));
row.appendChild(columnDelete);
return row;
};
jQuery(document).ready(ordering.init);
</code></pre>
<p>The corresponsing HTML document is:</p>
<pre><code><!DOCTYPE HTML>
<head>
<meta charset="utf-8"/>
<title>Terminal Bestellung</title>
<link rel="stylesheet" href="https://libraries.homeinfo.de/bootstrap/latest/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://libraries.homeinfo.de/sweetalert/dist/sweetalert.css">
<script src="https://libraries.homeinfo.de/jquery/jquery-latest.min.js"></script>
<script src="https://libraries.homeinfo.de/bootstrap/latest/js/bootstrap.min.js"></script>
<script src="https://libraries.homeinfo.de/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://javascript.homeinfo.de/homeinfo.min.js"></script>
<script src="https://javascript.homeinfo.de/his/his.js"></script>
<script src="https://javascript.homeinfo.de/his/session.js"></script>
<script src="ordering.js"></script>
</head>
<body>
<h1 align="center">Ihre Bestellungen bei HOMEINFO</h1>
<br>
<div class="container">
<div id="tableContainer" class="row"></div>
<br>
<div id="formContainer" class="row"></div>
</div>
</body>
</code></pre>
<p>I'd like to have general feedback especially on the JavaScript code.</p>
| [] | [
{
"body": "<p>If you ask for specific questions, we can provide better feedback. </p>\n\n<p>A few thoughts:</p>\n\n<ul>\n<li>if you're including jQuery, go ahead and use it for DOM generation, as it will be much more concise and readable, instead of all the bulky <code>createElement</code>, <code>setAttribute</... | {
"AcceptedAnswerId": "201542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T12:29:44.133",
"Id": "201070",
"Score": "3",
"Tags": [
"javascript",
"user-interface"
],
"Title": "Front end for system ordering"
} | 201070 |
<p>As many suggestions were given for the code I posted <a href="https://codereview.stackexchange.com/questions/200957/disassembler-for-intel-8080/200992#200992">here</a>, I decided to show you the new version for review.</p>
<ul>
<li><p>I Removed the <code>OpenCatalog</code> class, <code>Disassembler</code> now has the responsibility for handling the catalog of <code>OpCode</code> that is now stored in an <code>std::map</code>.</p></li>
<li><p><code>OpCode</code> is now a <code>struct</code> and <code>AssemblyLine</code> handles the generation of the assembler code.</p></li>
<li><code>FileReaderHelper</code> is now <code>file_parse_helpers</code>, a namespace containing helper functions.</li>
<li>I used <code>string_view</code> everywhere I though I could.</li>
<li>I fixed all the things like initialization order, includes, spelling, consts, etc</li>
<li>Reduced the amount of streams I was using.</li>
</ul>
<p><strong>file_parse_helpers.h</strong></p>
<pre><code>#ifndef FILE_PARSER_HELPER_H
#define FILE_PARSER_HELPER_H
#include <vector>
#include <string>
namespace file_parse_helpers
{
std::vector<std::string_view> splitString(std::string_view toSplit, std::string_view delimiter);
int hexStringToInt(std::string_view toSplit);
std::vector<unsigned char> loadBinaryFile(std::string filepath);
}
#endif // FILE_PARSER_HELPER_H
</code></pre>
<p><strong>file_parse_helpers.cpp</strong></p>
<pre><code>#include "FileReaderHelper.h"
#include <fstream>
#include <algorithm>
namespace file_parse_helpers
{
std::vector<std::string_view> splitString(std::string_view toSplit, std::string_view delimiter)
{
std::vector<std::string_view> result;
size_t lastPos = 0;
while (lastPos < toSplit.size()) {
const auto position = toSplit.find_first_of(delimiter, lastPos);
if (lastPos != position) {
result.emplace_back(toSplit.substr(lastPos, position - lastPos));
}
if (position == std::string_view::npos)
break;
lastPos = position + 1;
}
return result;
}
int hexStringToInt(std::string_view toSplit)
{
const auto pouet = std::strtol(toSplit.data(), 0, 16);
return pouet;
}
std::vector<unsigned char> file_parse_helpers::loadBinaryFile(std::string filepath)
{
std::ifstream inputStream(filepath, std::ios::binary);
std::vector<unsigned char> result(std::istreambuf_iterator<char>{inputStream}, {});
return result;
}
}
</code></pre>
<p><strong>OpCode.h</strong></p>
<pre><code>#ifndef OPCODE_H
#define OPCODE_H
#include <string>
struct OpCode {
uint8_t code;
int byteCount;
std::string resultTemplate;
};
#endif // OPCODE_H
</code></pre>
<p><strong>AssemblyLine.h</strong></p>
<pre><code>#ifndef ASSEMBLYLINE_H
#define ASSEMBLYLINE_H
#include <string>
#include "OpCode.h"
class AssemblyLine
{
public:
AssemblyLine(const OpCode& opCode);
AssemblyLine(const OpCode& opCode, const uint8_t param1);
AssemblyLine(const OpCode& opCode, const uint8_t param1, const uint8_t param2);
uint8_t getParam1() const;
uint8_t getParam2() const;
uint8_t getCode() const;
uint8_t getByteCount() const;
std::string generateAssembler(const std::string& templateString) const;
protected:
const uint8_t byteCount;
const uint8_t code;
const uint8_t param1;
const uint8_t param2;
};
#endif
</code></pre>
<p><strong>AsemblyLine.cpp</strong></p>
<pre><code>#include "AssemblyLine.h"
#include <stdexcept>
AssemblyLine::AssemblyLine(const OpCode& opCode) :
byteCount(opCode.byteCount),
code(opCode.code),
param1(0),
param2(0)
{
}
AssemblyLine::AssemblyLine(const OpCode& opCode, const uint8_t param1) :
byteCount(opCode.byteCount),
code(opCode.code),
param1(param1),
param2(0)
{
}
AssemblyLine::AssemblyLine(const OpCode& opCode, const uint8_t param1, const uint8_t param2) :
byteCount(opCode.byteCount),
code(opCode.code),
param1(param1),
param2(param2)
{
}
uint8_t AssemblyLine::getParam1() const
{
return param1;
}
uint8_t AssemblyLine::getParam2() const
{
return param2;
}
uint8_t AssemblyLine::getCode() const
{
return code;
}
uint8_t AssemblyLine::getByteCount() const
{
return byteCount;
}
std::string AssemblyLine::generateAssembler(const std::string& templateString) const
{
const int maxStringLength{ 32 };
if (templateString.length() > maxStringLength)
{
throw std::invalid_argument("This template string is too long: " + templateString);
}
char temp[maxStringLength];
switch (byteCount) {
case 1:
return templateString;
case 2:
std::snprintf(temp, maxStringLength, templateString.c_str(), param1);
break;
case 3:
std::snprintf(temp, maxStringLength, templateString.c_str(), param1, param2);
break;
}
return temp;
}
</code></pre>
<p><strong>Disassembler.h</strong></p>
<pre><code>#ifndef DISASSEMBLER_H
#define DISASSEMBLER_H
#include <map>
#include <vector>
#include "AssemblyLine.h"
#include "OpCode.h"
class Disassembler
{
public:
Disassembler(const std::string& filename);
std::vector<AssemblyLine> disassemble(const std::vector<unsigned char>& data);
void printAssembly(const std::vector<unsigned char>& data);
AssemblyLine disasembleOneCode(const std::vector<unsigned char>& data, size_t codeIndex);
void loadCatalog(const std::string& filename);
private:
std::map<uint8_t, OpCode> opCodes;
};
#endif
</code></pre>
<p><strong>Disassembler.cpp</strong></p>
<pre><code>#include "Disassembler.h"
#include "File/FileReaderHelper.h"
#include <iostream>
#include <fstream>
Disassembler::Disassembler(const std::string& filename)
{
loadCatalog(filename);
}
AssemblyLine Disassembler::disasembleOneCode(const std::vector<unsigned char>& data, size_t codeIndex)
{
uint8_t codeValue = data[codeIndex];
const auto& opCode = opCodes[codeValue];
const auto byteCount = opCode.byteCount;
switch (byteCount) {
default:
case 1:
return AssemblyLine(opCode);
break;
case 2:
return AssemblyLine(opCode, data[codeIndex + 1]);
break;
case 3:
return AssemblyLine(opCode, data[codeIndex + 2], data[codeIndex + 1]);
break;
}
}
std::vector<AssemblyLine> Disassembler::disassemble(const std::vector<unsigned char>& data)
{
size_t currentId = 0;
std::vector<AssemblyLine> disasembledCode;
for (; currentId < data.size() - 1;)
{
const auto asmLine = disasembleOneCode(data, currentId);
currentId += asmLine.getByteCount();
disasembledCode.emplace_back(asmLine);
}
return disasembledCode;
}
void Disassembler::loadCatalog(const std::string& filename)
{
opCodes.clear();
std::ifstream input(filename);
for (std::string line; std::getline(input, line);)
{
const auto tokens = file_parse_helpers::splitString(line, "\t");
if (tokens.size() < 3) {
throw "Malformed catalog line: " + line;
}
uint8_t code = file_parse_helpers::hexStringToInt(std::string(tokens[0]));
opCodes.emplace(code, OpCode{ code,
std::stoi(std::string(tokens[2]), nullptr, 10),
std::move(std::string(tokens[1])) });
}
}
void Disassembler::printAssembly(const std::vector<unsigned char>& data)
{
size_t currentId = 0;
for (; currentId < data.size() - 1;)
{
const auto asmLine = disasembleOneCode(data, currentId);
currentId += asmLine.getByteCount();
std::cout << asmLine.generateAssembler(opCodes[asmLine.getCode()].resultTemplate) << std::endl;
}
}
</code></pre>
<p>Edit: After posting I realized that I made a mistake. I throw an exception about the size of the template string provided in the catalog, but I should do it when parsing the catalog, not when I use the string. Now, how do I replace <code>maxStringLength</code> so that I can use it when loading the catalog <strong>and</strong> as the size of the <code>temp</code> array in <code>generateAssembler</code>? Are C macros the only solution here?</p>
| [] | [
{
"body": "<ol>\n<li><code>loadBinaryFile</code> should either take a <code>std::string_view</code>, or, at least, a <code>std::string const&</code> as argument. You don't want to take ownership of the string here.</li>\n<li>Your filenames do not match. <code>file_parse_helpers.cpp</code> begins with <code>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T12:53:58.020",
"Id": "201072",
"Score": "3",
"Tags": [
"c++",
"file-system",
"assembly",
"c++17"
],
"Title": "Disassembler for intel 8080 v2"
} | 201072 |
<p>I have added a correct question callback for different types of questions like: radio, checkbox and descriptive..</p>
<p><strong>QuestionListActivity.class</strong> (it shows the list of questions to attempt)</p>
<pre><code> public class QuestionListActivity extends AppCompatActivity {
private Context mContext;
private List<QuestionBO> questionList;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView noResultTv;// FIXME: 8/1/2018 update it after other work done...
private QuestionAdapter mAdapter;
private FirebaseFirestore db = null;
private final String TAG = getClass().getSimpleName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_list);
FrameLayout frameLayout = findViewById(R.id.parent);
frameLayout.setBackgroundColor(Color.WHITE);
mContext = QuestionListActivity.this;
questionList = new ArrayList<>();
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
noResultTv = findViewById(R.id.tv_no_result);
mSwipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getQuestionsFromServer(true);
}
});
if (mAdapter == null) {
mAdapter = new QuestionAdapter(questionList, new OnRecyclerItemClickListener() {
@Override
public void onItemClick(View view, int position, boolean isCorrectAnswer) {
int post = position + 1;
Toast.makeText(mContext, "Answer Correct at : " + post
+ " " + isCorrectAnswer, Toast.LENGTH_LONG).show();
}
});
}
mRecyclerView.setAdapter(mAdapter);
getQuestionsFromServer(true);
}
public void getQuestionsFromServer(boolean isRefresh) {
db = FirebaseFirestore.getInstance();
//fetching data by comparison...
/*Query radioQuestions = db.collection("questionCollection").whereEqualTo("questionType", 1);*/
db.collection("questionCollection")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (queryDocumentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
questionList = queryDocumentSnapshots.toObjects(QuestionBO.class);
if (questionList != null && questionList.size() > 0)
mAdapter.updateQuestions(questionList);
}
}
});
if(mSwipeRefreshLayout.isRefreshing())
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_questions, menu);
return true;
///return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_action_save) {
Toast.makeText(QuestionListActivity.this, "Action clicked", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>where <strong>activity_question_list.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/parent"
tools:context=".QuestionListActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
<include layout="@layout/no_result" />
</FrameLayout>
</code></pre>
<p><strong>QuestionAdapter.class</strong></p>
<pre><code>public class QuestionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<QuestionBO> items;
private OnRecyclerItemClickListener onRecyclerItemClickListener;
private static final int VIEW_TYPE_DESCRIPTIVE = 0;
private static final int VIEW_TYPE_CHECKBOX = 1;
private static final int VIEW_TYPE_RADIO = 2;
public QuestionAdapter(List<QuestionBO> questions,
OnRecyclerItemClickListener onRecyclerItemClickListener) {
this.items = questions;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_CHECKBOX) {
return new CheckBoxVH(parent, R.layout.item_checkbox, onRecyclerItemClickListener);
} else if (viewType == VIEW_TYPE_RADIO) {
return new RadioVH(parent, R.layout.item_radio, onRecyclerItemClickListener);
} else
return new DescriptiveVH(parent, R.layout.item_descriptive, onRecyclerItemClickListener);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof CheckBoxVH)
((CheckBoxVH) holder).onBindData(items.get(position));
else if (holder instanceof RadioVH)
((RadioVH) holder).onBindData(items.get(position));
else if (holder instanceof DescriptiveVH)
((DescriptiveVH) holder).onBindData(items.get(position));
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public int getItemViewType(int position) {
if (items.get(position).getQuestionType() == EnumUtils.QuestionType.CHECKBOX)
return VIEW_TYPE_CHECKBOX;
else if (items.get(position).getQuestionType() == EnumUtils.QuestionType.RADIO)
return VIEW_TYPE_RADIO;
else
return VIEW_TYPE_DESCRIPTIVE;
}
public QuestionBO getItemAt(int position) {
return items.get(position);
}
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
public void updateQuestions(List<QuestionBO> newQuestions) {
items.clear();
items.addAll(newQuestions);
this.notifyDataSetChanged();
}
}
</code></pre>
<p><strong>CheckBoxVH</strong></p>
<pre><code>public class CheckBoxVH extends BaseQuestionTypeVH<QuestionBO> {
private TextView questionTitleTv;
private LinearLayout checkboxLL;
private Context mContext;
private boolean isAnswerCorrect = false;
public CheckBoxVH(ViewGroup parent, int layoutId, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(parent, layoutId, onRecyclerItemClickListener);
mContext = parent.getContext();
questionTitleTv = itemView.findViewById(R.id.tv_question_title);
checkboxLL = itemView.findViewById(R.id.ll_checkbox);
}
@Override
public void onBindData(final QuestionBO data) {
questionTitleTv.setText(data.getTitle());
if (data.getOptions() != null && data.getOptions().size() > 0) {
checkboxLL.removeAllViews();
for (int x = 0; x < data.getOptions().size(); x++) {
final CheckBox subCheckbox = new CheckBox(mContext);
subCheckbox.setText(data.getOptions().get(x));
subCheckbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isAnswerCorrect = false;
int counter = 0;
int numberOfChecked = 0;
for(int y =0 ; y < checkboxLL.getChildCount() ; y++){
CheckBox checkBox = (CheckBox) checkboxLL.getChildAt(y);
if (checkBox.isChecked()){
numberOfChecked++;
for (Integer intVariable : data.getOptionIndexes()) {
if(intVariable.intValue() == y)
counter++;
}
}
}
if(counter == data.getOptionIndexes().size() && numberOfChecked == data.getOptionIndexes().size()){
isAnswerCorrect = true;
}
}
});
checkboxLL.addView(subCheckbox, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
}
@Override
public void onClick(View view) {
if(onItemClicked != null){
onItemClicked.onItemClick(view,getAdapterPosition(),isAnswerCorrect);
}
}
}
</code></pre>
<p><strong>RadioVH.class</strong></p>
<pre><code>public class RadioVH extends BaseQuestionTypeVH<QuestionBO> {
private TextView questionTitleTv;
private RadioGroup radioLL;
private Context mContext;
private boolean isAnswerCorrect = false;
public RadioVH(ViewGroup parent, int layoutId, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(parent, layoutId, onRecyclerItemClickListener);
mContext = parent.getContext();
questionTitleTv = itemView.findViewById(R.id.tv_question_title);
radioLL = itemView.findViewById(R.id.ll_radio);
}
@Override
public void onBindData(final QuestionBO data) {
questionTitleTv.setText(data.getTitle());
if (data.getOptions() != null && data.getOptions().size() > 0) {
radioLL.removeAllViews();
for (int x = 0; x < data.getOptions().size(); x++) {
final RadioButton subRadio = new RadioButton(mContext);
subRadio.setText(data.getOptions().get(x));
radioLL.addView(subRadio, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
radioLL.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
View radioButton = itemView.findViewById(checkedId);
int index = radioGroup.indexOfChild(radioButton);
isAnswerCorrect = false;
for (Integer intVariable : data.getOptionIndexes()) {
if (intVariable.intValue() == index) {
isAnswerCorrect = true;
}
}
}
});
}
@Override
public void onClick(View view) {
if (onItemClicked != null)
onItemClicked.onItemClick(view, getAdapterPosition(), isAnswerCorrect);
}
}
</code></pre>
<p><strong>DescriptiveVH.class</strong></p>
<pre><code>public class DescriptiveVH extends BaseQuestionTypeVH<QuestionBO> {
private TextView questionTitleTv;
private EditText answerEt;
private boolean isAnswerCorrect = false;
public DescriptiveVH(ViewGroup parent, int layoutId, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(parent, layoutId, onRecyclerItemClickListener);
questionTitleTv = itemView.findViewById(R.id.tv_question_title);
answerEt = itemView.findViewById(R.id.et_answer);
}
@Override
public void onBindData(final QuestionBO data) {
questionTitleTv.setText(data.getTitle());
answerEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if(editable.toString().equalsIgnoreCase(data.getAnswer()))
isAnswerCorrect = true;
else
isAnswerCorrect = false;
}
});
}
@Override
public void onClick(View view) {
if(onItemClicked != null)
onItemClicked.onItemClick(view,getAdapterPosition(),isAnswerCorrect);
}
}
</code></pre>
<p><strong>item_checkbox.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_question_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Title Text"
android:textColor="@android:color/black" />
<LinearLayout
android:id="@+id/ll_checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</LinearLayout>
</code></pre>
<p><strong>item_descriptive.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_question_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Title Text"
android:textColor="@android:color/black" />
<EditText
android:id="@+id/et_answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</LinearLayout>
</code></pre>
<p><strong>item_radio.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_question_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Title Text"
android:textColor="@android:color/black" />
<RadioGroup
android:id="@+id/ll_radio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</LinearLayout>
</code></pre>
<p><strong>BaseQuestionTypeVH.class</strong></p>
<pre><code>public abstract class BaseQuestionTypeVH<T> extends RecyclerView.ViewHolder implements View.OnClickListener{
public abstract void onBindData(T data);
public OnRecyclerItemClickListener onItemClicked;
public BaseQuestionTypeVH(ViewGroup parent, int layoutId , OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false));
this.onItemClicked = onRecyclerItemClickListener;
itemView.setOnClickListener(this);
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T12:59:11.127",
"Id": "201074",
"Score": "1",
"Tags": [
"java",
"android",
"quiz",
"callback",
"firebase"
],
"Title": "Correct Callback for each item"
} | 201074 |
<p>imaging a folder structure like:</p>
<pre><code>Peter
|- Cats
|- Mini
|- Maunz
|- Tippsi
|– Dogs
|- Brutus
Eva
|- animals
|- Mini
|- Brutus
</code></pre>
<p>I'd like to delete all subfolders in <code>Peter/*/</code> if they not present in <code>Eva/animals/</code> (Maunz and Tippsi).
This is what I have so far. It's working but it feels as my combination of loop and find is not the best solution:</p>
<pre><code>for dir in ./Peter/*/*/
do
dir=${dir%*/}
if find './Eva/animals' -type d -name ${dir##*/} -exec false {} +
then
echo "${dir%*/} not found and deleted"
rm -rf ${dir%*/}
fi
done
</code></pre>
<p>For learning, can this code be optimized?</p>
| [] | [
{
"body": "<p><code>find</code> is good for finding files and directories recursively in a filesystem tree.\nBased on your description and example, you probably don't need that.\nIf you want to check that some directory <code>foo</code> exists directly under <code>/some/path</code>,\nit's much simpler and more ... | {
"AcceptedAnswerId": "201102",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T14:13:05.770",
"Id": "201079",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Bash delete folder if not present in other folder"
} | 201079 |
<h2>Problem:</h2>
<blockquote>
<p>We are interested in triangles that have integer length sides, all of
which are between <code>minLength</code> and <code>maxLength</code>, inclusive. How many
such triangles are there? Two triangles differ if they have a
different collection of side lengths, ignoring order. Triangles with
side lengths {2,3,4} and {4,3,5} differ, but {2,3,4} and {4,2,3} do
not. We are only interested in proper triangles; the sum of the two
smallest sides of a proper triangle must be strictly greater than the
length of the biggest side.</p>
<p>Create a class <code>TriCount</code> that contains a method <code>count</code> that is given
ints <code>minLength</code> and <code>maxLength</code> and returns the number of different
proper triangles whose sides all have lengths between <code>minLength</code> and
<code>maxLength</code>, inclusive. If there are more than 1,000,000,000, return
-1.</p>
</blockquote>
<h2>My solution:</h2>
<p><a href="https://i.stack.imgur.com/b9kq3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b9kq3.png" alt="enter image description here"></a>
<pre><code>class Form{
/**
*@var array données utilisées par le formulaire
*/
protected $data;
/**
*@var string tag qui entoure les champs
*/
public $surroud ='p';
/**
*@param array $data
*@return string
*/
public function __construct($data = array()){
$this->data = $data;
}
/**
*@param $html string
*@return string
*/
protected function surroud(string $html){
return "<{$this->surroud}>".$html."</{$this->surroud}>";
}
/**
*@param $index string
*@return string
*/
protected function getValue(string $index){
return isset($this->data[$index]) ? $this->data[$index] : null;
}
/**
*@param $name string
*@return string
*/
public function input(string $name){
return $this->surroud("<label for='".$name."'>".$name.": </label><input type='text' name='".$name."' value='".$this->getValue($name)."'>");
}
/**
*@return string
*/
public function submit(){
return $this->surroud("<button type='submit'>Envoyer</button>");
}
}
</code></pre>
<hr>
<pre><code><?php
class FormController{
/**
*@return objet
*/
public function registerI()
{
return new TriCount();
}
/**
*@param $params array
*@return integer
*/
public function register(array $params)
{
//les champs sont remplis d'entier
if(intval($params['min']) && intval($params['max'])){
//instancier la classe pour le calcul des probabilités
$inst = new TriCount();
//appel de la methode qui calcul les probabilités
$nbre = $inst->count($params['min'], $params['max']);
return $nbre;
}else{
$message_erreur = "Vous devez remplir avec des entiers superieur à 0!";
return $message_erreur;
}
}
}
</code></pre>
<hr>
<pre><code><?php
/**
*Class TriCount
*/
class TriCount{
/**
*@var integer minimum du tableau
*/
private $minLength;
/**
*@var integer maximum du tableau
*/
private $maxLength;
/**
*@var integer nombre de triangle possible
*/
private $count;
/**
*@param $minLength integer
*@param $maxLength integer
*@return integer
*/
public function count(int $minLength , int $maxLength ){
//initialiser le compteur
$count = 0;
//3 boucles qui font varier le (i,j,k)
// le script s'arrete si la condition n'est pas vérifiée
for ($i = $minLength; $i <= $maxLength; $i++){
for($j = $i ; $j <= $maxLength; $j++){
for($k = $j ; $k <= $maxLength; $k++){
//condition: la somme des deux petits cotés du triangle superieur au troisieme coté
if( ($i + $j ) > $k ) {
$count++;
}else{
break;
}
}
}
}
//si le nombre de possibilité dépasse 1000000000
if ($count <= 1000000000 ){
return $count;
}else {
return -1;
}
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n<pre><code> for($k = $j ; $k <= $maxLength; $k++){\n //condition: la somme des deux petits cotés du triangle superieur au troisieme coté\n if( ($i + $j ) > $k ) {\n\n $count++;\n\n }else... | {
"AcceptedAnswerId": "201096",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T14:47:34.647",
"Id": "201083",
"Score": "5",
"Tags": [
"php",
"algorithm"
],
"Title": "Counting distinct triangles that have integer-length sides"
} | 201083 |
<p>I have the following Python output class that I'm planning to use across a number of modules in a terminal application:</p>
<pre><code>from colorclass import Color
from colorclass import disable_all_colors, enable_all_colors, is_enabled
from time import gmtime, strftime
class OutputHelper(object):
def __init__(self, color, domain):
if color:
disable_all_colors()
self.domain = domain
def Terminal(self, severity, message):
leader = ''
if severity == 1:
leader = Color('{green}[GOOD]{/green}')
elif severity == 2:
leader = Color('{cyan}[INFO]{/cyan}')
elif severity == 3:
leader = Color('{yellow}[LOW]{/yellow}')
elif severity == 4:
leader = Color('{magenta}[MEDIUM]{/magenta}')
elif severity == 5:
leader = Color('{red}[HIGH]{/red}')
elif severity == 6:
leader = Color('{red}[!!CRITICAL!!]{/red}')
else:
leader = '[#]'
print('[{}] [{}] {} {}'.format(strftime("%H:%M:%S", gmtime()), self.domain, leader, message))
</code></pre>
<p>The idea being that one module can raise multiple messages for a single domain. So usage would be similar to:</p>
<pre><code>output = OutputHelper(arguments.nocolor, arguments.domains)
output.Terminal(1, 'All dependencies up to date')
output.Terminal(6, "Cryptojacking script identified: aaaa")
</code></pre>
<p>I'm sure there's better ways to design this, but I don't know what I don't know, and I'd value input and guidance!</p>
| [] | [
{
"body": "<h1><code>if</code> - <code>elif</code></h1>\n\n<p>instead of the <code>if</code> - <code>elif</code> statements, use <code>dict.get(key, default)</code>:</p>\n\n<pre><code>formatting = {\n 1: Color('{green}[GOOD]{/green}'),\n 2: Color('{cyan}[INFO]{/cyan}'),\n 3: Color('{yellow}[LOW]{/yello... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T15:26:03.890",
"Id": "201085",
"Score": "8",
"Tags": [
"python",
"object-oriented",
"python-3.x"
],
"Title": "Python Output Class"
} | 201085 |
<p>In my architecture I have service layer, and for my question two relevant classes in this layer:</p>
<ol>
<li>UserManagementService</li>
<li>EmailSenderService</li>
</ol>
<p>In first service there is method: <code>UnsubscribeUser</code> which unsubscribes the user from a mailing list, and after user is successfully unsubscribed it dispatches event <code>UserUnsubscribedFromEmails</code>. </p>
<p>In second service there is event handler which, after <code>UserUnsubscribedFromEmails</code> is dispatched, adds the email (of user who unsubscribed from mailing list) to Suppression list (black list) of our email delivery service.</p>
<p>I have following issue with my current implementation: </p>
<p>At the moment <code>EmailSenderService</code> subscribes to this event (<code>UserUnsubscribedFromEmails</code>) inside of the constructor of <code>UserManagementService</code>, which makes <code>UserManagementService</code> dependant on <code>EmailSenderService</code> and as far as my understanding goes, this should not be the case. </p>
<p>Here is code for UserManagementService:</p>
<pre><code>public class UserManagementService : IUserManagementService
{
/// <summary>
/// The subscription service.
/// </summary>
private readonly ISubscriptionService subscriptionService;
/// <summary>
/// The user service.
/// </summary>
private readonly IUserService userService;
/// <summary>
/// The email sender.
/// </summary>
private readonly IEmailSender emailSender;
/// <summary>
/// Initializes a new instance of the <see cref="UserManagementService"/> class.
/// </summary>
/// <param name="subscriptionService">
/// The subscription service.
/// </param>
/// <param name="userService">
/// The user Service.
/// </param>
/// <param name="emailSender">
/// Email sender
/// </param>
public UserManagementService(ISubscriptionService subscriptionService, IUserService userService, IEmailSender emailSender)
{
this.subscriptionService = subscriptionService;
this.userService = userService;
this.emailSender = emailSender;
// should this be here?
this.UserUnsubscribedFromEmails += this.emailSender.OnUserUnsubscribedFromEmailsEventHandler;
}
/// <summary>
/// User unsubscribed from emails event
/// </summary>
public event EventHandler<UserUnsubscribedFromEmailsEventArgs> UserUnsubscribedFromEmails;
/// <summary>
/// Unsubscribe user from mailing list
/// </summary>
/// <param name="userId">
/// The user id.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Throws if user id is null or empty
/// </exception>
/// <exception cref="InvalidOperationException">
/// Throws if user could not be found
/// </exception>
public async Task<bool> UnsubscribeUser(string userId)
{
if (string.IsNullOrEmpty(userId) || string.IsNullOrWhiteSpace(userId))
{
throw new ArgumentNullException(nameof(userId));
}
using (var db = new DatabaseContext())
{
var user = db.Users.Find(userId);
if (user == null)
{
throw new InvalidOperationException("Could not find user");
}
if (user.IsSubscribedToEmails)
{
user.IsSubscribedToEmails = false;
await db.SaveChangesAsync();
// Fires UserUnsubscribedFromEmails event
OnUserUnsubscribedFromEmails(new UserUnsubscribedFromEmailsEventArgs(user.Email, "Unsubscribed via portal"));
}
return true;
}
}
/// <summary>
/// User unsubscribed from emails
/// </summary>
/// <param name="args">
/// The args.
/// </param>
protected virtual void OnUserUnsubscribedFromEmails(UserUnsubscribedFromEmailsEventArgs args)
{
if (UserUnsubscribedFromEmails != null)
{
UserUnsubscribedFromEmails(this, args);
}
}
}
</code></pre>
<p>And the relevant code for the EmailSenderService:</p>
<pre><code>/// <summary>
/// The email sender.
/// </summary>
public class EmailSender : IEmailSender
{
/// <summary>
/// The on user unsubscribed from emails event handler.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="args">
/// The args.
/// </param>
/// <exception cref="ArgumentNullException">
/// Throws if arguments are null
/// </exception>
public void OnUserUnsubscribedFromEmailsEventHandler(object source, UserUnsubscribedFromEmailsEventArgs args)
{
if (args == null || string.IsNullOrEmpty(args.Email))
{
throw new ArgumentNullException(nameof(args));
}
this.AddEmailToSuppressionListAsync(new List<string> { args.Email }, args.Info);
}
}
</code></pre>
<p>So my question is where should I subscribe <code>EmailSenderService</code> to <code>UserUnsubscribedFromEmails</code> event? </p>
<p><code>UserManagementService</code> is called in ASP.net Web API controller - should I inject both services in the controller and subscribe <code>EmailSenderService</code> there or there is some better design solution?</p>
<p>Thanks in advance!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T17:11:19.913",
"Id": "387263",
"Score": "0",
"body": "not sure why you have a list of users that are Unsubscribed from emails...you have a field for the user that defines whether or not they are subscribed that should be enough to s... | [
{
"body": "<p>in your <code>UnsubscribeUser</code> Method, I wouldn't worry about checking to see whether or not the user is actually subscribed or not, if this method is called I would simply just set that value to false, it shouldn't hurt anything if the user is already unsubscribed, and it may even keep trac... | {
"AcceptedAnswerId": "201097",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T16:48:04.973",
"Id": "201095",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"event-handling",
"asp.net-web-api"
],
"Title": "Subscribe to Event form one service to another"
} | 201095 |
<p>I have written some code that computes flexural moments imposed by different trucks for a bridge with 300 ft length. Truck data are contained in two lists: <code>ax_list</code> and <code>sp_list</code>, which are the axle weights and axle spacings, respectively.</p>
<p>There is nothing much to the code, however, this needs to be repeated for millions of different truck types, and I am trying to optimize my code, which takes real long time when the actual data size set is concerned.</p>
<p>I tried using Numba to see if I can get any speed gains, but it did not change the execution time, whether I add Numba <code>@jit</code> decorators for each function or not. What am I doing wrong here? Any help would be welcome! I also included code to generate representative pseudo data for 1000 records below:</p>
<pre><code>import random
from numba import jit
import numpy as np
from __future__ import division
#Generate Random Data Set
ax_list=[]
sp_list=[]
for i in xrange(1000):
n = random.randint(3,10)
ax = []
sp = [0]
for i in xrange(n):
a = round(random.uniform(8,32),1)
ax.append(a)
for i in xrange(n-1):
s = round(random.uniform(4,30), 1)
sp.append(s)
ax_list.append(ax)
sp_list.append(sp)
#Input Parameters
L=300
step_size=4
cstep_size=4
moment_list=[]
@jit
#Simple moment function
def Moment(x):
if x<L/2.0:
return 0.5*x
else:
return 0.5*(L-x)
#Attempt to vectorize the Moment function, hoping for speed gains
vectMoment = np.vectorize(Moment,otypes=[np.float],cache=False)
@jit
#Truck movement function that uses the vectorized Moment function above
def SimpleSpanMoment(axles, spacings, step_size):
travel = L + sum(spacings)
spacings=list(spacings)
maxmoment = 0
axle_coords =(0-np.cumsum(spacings))
while np.min(axle_coords) < L:
axle_coords = axle_coords + step_size
moment_inf = np.where((axle_coords >= 0) & (axle_coords <=L), vectMoment(axle_coords), 0)
moment = sum(moment_inf * axles)
if maxmoment < moment:
maxmoment = moment
return maxmoment
</code></pre>
<p>Then to run the loop for 1000 times:</p>
<pre><code>%%timeit
for i in xrange(len(ax_list)):
moment_list.append(np.around(SimpleSpanMoment(ax_list[i], sp_list[i], step_size),1))
</code></pre>
<p>yields:</p>
<pre><code>1 loop, best of 3: 2 s per loop
</code></pre>
| [] | [
{
"body": "<p>Just a few quick points on your code: </p>\n\n<ul>\n<li>any future imports should be at the top of any code. Are you using this intentionally (2to3?) or this is leftover code?</li>\n<li>your loop to generate test data overrides <code>i</code> in two secondary loops - this is bad coding practice.<... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T19:36:12.723",
"Id": "201103",
"Score": "5",
"Tags": [
"python",
"performance",
"numpy",
"numba"
],
"Title": "Optimizing Python loop with Numba for live load analysis"
} | 201103 |
<p>I want to implement <code>for_each_in_tuples</code> that takes a functor and one or more tuples of the same <code>size</code> and applies this functor to <code>i</code>'th elements of each tuple for <code>i = 0, ..., size - 1</code>.</p>
<p>Example:</p>
<pre><code>#include <iostream>
#include <tuple>
std::tuple t1(1, 2.2, false);
std::tuple t2(3.3, 'a', 888);
std::cout << std::boolalpha;
for_each_in_tuples(
[](auto a1, auto a2)
{
std::cout << a1 << ' ' << a2 << '\n';
}, t1, t2);
// Outputs:
// 1 3.3
// 2.2 a
// false 888
</code></pre>
<p>Implementation:</p>
<pre><code>#include <cstddef>
#include <tuple>
#include <type_traits>
namespace impl
{
template<typename T, typename... Ts>
struct First { using Type = T; };
template<typename... Ts>
using First_t = typename First<Ts...>::Type;
template<auto value, auto... values>
inline constexpr auto all_same = (... && (value == values));
template<class Tuple>
inline constexpr auto tuple_size = std::tuple_size_v<std::remove_reference_t<Tuple>>;
template<std::size_t index = 0, class Function, class... Tuples>
constexpr void for_each_in_tuples(Function func, Tuples&&... tuples)
{
constexpr auto size = tuple_size<First_t<Tuples...>>;
func(std::get<index>(std::forward<Tuples>(tuples))...);
if constexpr (index + 1 < size)
for_each_in_tuples<index + 1>(func, std::forward<Tuples>(tuples)...);
}
}
template<class Function, class... Tuples>
constexpr void for_each_in_tuples(Function func, Tuples&&... tuples)
{
static_assert(sizeof...(Tuples) > 0);
static_assert(impl::all_same<impl::tuple_size<Tuples>...>);
impl::for_each_in_tuples(func, std::forward<Tuples>(tuples)...);
}
</code></pre>
<p>At Compiler explorer: <a href="https://godbolt.org/g/cYknQT" rel="nofollow noreferrer">https://godbolt.org/g/cYknQT</a></p>
<p>Main questions:</p>
<ol>
<li><p>Is this implementation correct and can it be simplified?</p></li>
<li><p>Which name is better, <code>for_each_in_tuple</code> or <code>for_each_in_tuples</code> (or ...)?</p></li>
</ol>
| [] | [
{
"body": "<p>There's not much I can criticize about your code; as far as I can see, everything seems well thought out and well written.</p>\n\n<p>As to question number 1: Yes, I think your implementation is correct. I also don't think there's much to be simplified; the implementation is pretty concise, and get... | {
"AcceptedAnswerId": "201129",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T20:04:54.107",
"Id": "201106",
"Score": "4",
"Tags": [
"c++",
"template-meta-programming",
"c++17"
],
"Title": "Iteration over \"zipped\" tuples (for_each_in_tuples)"
} | 201106 |
<p>I have started to code Snake in C++. I am finding it hard to make progress on this project because the code is quite messy. How can I improve the structure of my program?</p>
<p>main.cpp:</p>
<pre><code>#include <iostream>
#include "Game.h"
#define FRAMERATE 500
int main(void)
{
Game game;
int count = 0;
while (game.program_is_running)
{
game.key_events();
if (count >= FRAMERATE)
{
game.tick();
count = 0;
}
else
count++;
}
std::cout << "\nYou lose.\n";
std::cin.get();
return 0;
}
</code></pre>
<p>game.h:</p>
<pre><code>#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <vector>
#include "Snake.h"
#define NUMBER_OF_ROWS 25
#define NUMBER_OF_COLUMNS 25
class Game
{
public:
Game(void);
void tick(void);
void key_events(void);
bool program_is_running;
private:
char grid[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
Snake snake;
Block apple;
enum { right = 1, left, down, up };
bool snake_is_touching_wall(void);
void display_grid(void);
};
</code></pre>
<p>game.cpp:</p>
<pre><code>#include <stdlib.h>
#include "Game.h"
Game::Game(void)
{
for (int y = 0; y < NUMBER_OF_ROWS; y++)
{
for (int x = 0; x < NUMBER_OF_COLUMNS; x++)
{
if (y == 0 || y == NUMBER_OF_ROWS - 1)
grid[y][x] = '#';
else if (x == 0 || x == NUMBER_OF_COLUMNS - 1)
grid[y][x] = '#';
else
grid[y][x] = ' ';
}
}
apple.x = rand() % 25;
apple.y = rand() % 25;
program_is_running = true;
}
void Game::tick(void)
{
for (int y = 0; y < NUMBER_OF_ROWS; y++)
{
for (int x = 0; x < NUMBER_OF_COLUMNS; x++)
{
if (y == 0 || y == NUMBER_OF_ROWS - 1)
grid[y][x] = '#';
else if (x == 0 || x == NUMBER_OF_COLUMNS - 1)
grid[y][x] = '#';
else
grid[y][x] = ' ';
}
}
std::vector<Block> snake_body = snake.get_body();
if (snake.direction == right)
{
snake.move(0, 1);
}
else if (snake.direction == left)
{
snake.move(0, -1);
}
else if (snake.direction == down)
{
snake.move(1, 0);
}
else if (snake.direction == up)
{
snake.move(-1, 0);
}
for (int y = 0; y < NUMBER_OF_ROWS; y++)
{
for (int x = 0; x < NUMBER_OF_COLUMNS; x++)
{
if (y == apple.y && x == apple.x)
grid[y][x] = '@';
for (int i = 0; i < snake_body.size(); i++)
{
if (snake_body[i].y == y && snake_body[i].x == x)
{
grid[y][x] = snake.get_symbol();
}
}
}
}
display_grid();
if (snake_is_touching_wall())
{
program_is_running = false;
}
}
void Game::key_events(void)
{
char c;
if (_kbhit())
{
c = _getch();
switch (c)
{
case 'q':
program_is_running = false;
break;
case 'l':
if(snake.direction != left)
snake.direction = right;
break;
case 'j':
if(snake.direction != right)
snake.direction = left;
break;
case 'k':
if(snake.direction != up)
snake.direction = down;
break;
case 'i':
if(snake.direction != down)
snake.direction = up;
break;
}
}
}
bool Game::snake_is_touching_wall(void)
{
std::vector<Block> snake_body = snake.get_body();
const int SNAKE_HEAD_X = snake_body[0].x;
const int SNAKE_HEAD_Y = snake_body[0].y;
return grid[SNAKE_HEAD_Y][SNAKE_HEAD_X] == '#';
}
void Game::display_grid(void)
{
system("cls");
for (int y = 0; y < NUMBER_OF_ROWS; y++)
{
for (int x = 0; x < NUMBER_OF_COLUMNS; x++)
{
std::cout << grid[y][x] << ' ';
}
std::cout << std::endl;
}
}
</code></pre>
<p>snake.h:</p>
<pre><code>#include <vector>
struct Block
{
int y, x;
};
class Snake
{
public:
Snake();
std::vector<Block> get_body();
char get_symbol(void);
void add_block(int, int);
void move(int, int);
int direction;
private:
std::vector<Block> body;
char symbol;
};
</code></pre>
<p>snake.cpp:</p>
<pre><code>#include "Snake.h"
Snake::Snake(void)
{
symbol = 'X';
direction = 0;
add_block(12, 12);
}
std::vector<Block> Snake::get_body()
{
return body;
}
char Snake::get_symbol(void)
{
return symbol;
}
void Snake::add_block(int y, int x)
{
Block block;
block.y = y;
block.x = x;
body.push_back(block);
}
void Snake::move(int y, int x)
{
body[0].y += y;
body[0].x += x;
}
</code></pre>
| [] | [
{
"body": "<h1>C++ is not C</h1>\n\n<p>First problem is that you are writing everything like you were doing in C.\nRead about huge differences between languages. You should not write C++ code based on your experience in C.</p>\n\n<h1>Use constexpr</h1>\n\n<p>This is simply wrong, use <code>constexpr</code>.</p>... | {
"AcceptedAnswerId": "201113",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T20:27:25.323",
"Id": "201108",
"Score": "4",
"Tags": [
"c++",
"console",
"windows",
"snake-game"
],
"Title": "Snake game for Windows text console"
} | 201108 |
<p>This app register where you click on the screen, then it writes the inputs on the page. The text is responsive, you can change the dimension or orientation of the webpage and it still will be in the middle with the right size to fill the entire page. With a double click the program will restart.</p>
<p><a href="http://jsfiddle.net/Diquadro/ah1nfxkb/" rel="nofollow noreferrer">http://jsfiddle.net/Diquadro/ah1nfxkb/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Text {
constructor (element) {
this.element = element
}
write (inputs) {
for (let i = 0; i < inputs.length - 1; ++i) {
this.element.appendChild(document.createTextNode(`${i + 1}: ${inputs[i]}`))
this.element.appendChild(document.createElement('br'))
}
this.element.appendChild(document.createTextNode(`${inputs.length}: ${inputs[inputs.length - 1]}`))
}
erase () {
while (this.element.firstChild) {
this.element.removeChild(this.element.firstChild)
}
}
resize () {
this.element.style.fontSize = '50vw'
// fitting the text the whole page
for (let i = 50; window.innerWidth < this.element.offsetWidth || window.innerHeight < this.element.offsetHeight; --i) {
this.element.style.fontSize = `${i}vw`
}
}
}
async function application () {
const inputs = await new Promise(resolve => {
const inputs = []
function touch (event) {
// it will be replace with event.touches[event.touches.length - 1].clientX
if (event.clientX >= window.innerWidth / 2) {
inputs.push('RIGHT')
} else {
inputs.push('LEFT')
}
if (inputs.length === 4) {
// it will be replace with touchstart
window.removeEventListener('click', touch)
resolve(inputs)
}
}
// it will be replace with touchstart
window.addEventListener('click', touch)
})
const text = new Text(document.getElementById('text'))
text.write(inputs)
text.resize()
function resize () {
text.resize()
}
window.addEventListener('resize', resize)
function reset () {
window.removeEventListener('resize', resize)
window.removeEventListener('dblclick', reset)
text.erase()
application()
}
window.addEventListener('dblclick', reset)
}
application()</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
border: 0;
padding: 0;
user-select: none;
overflow:hidden;
}
body {
background: black;
}
#text {
white-space: nowrap;
color: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'>
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Magic</title>
</head>
<body>
<div id="text"></div>
<script src="main.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T23:59:49.803",
"Id": "201116",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Register inputs (click) - write the inputs"
} | 201116 |
<h2>Problem</h2>
<p>I'm <a href="https://codereview.stackexchange.com/questions/200686/verilog-implementation-of-trapezoidal-integration-method">writing a verilog program</a> that does the trapezoidal integration method (where a review is also welcome, wink wink). But turns out you need input for these kind of things, so in the overly complicated setup I'm doing, I'm writing a python program on a Raspberry Pi to output inputs for the FPGA which then outputs to a d to a which outputs to an oscilloscope which is where you all go, "Thank goodness I'm not that programmer" and I go half mad.</p>
<p>The main requirements for the code is that it output each bit of the input for the FPGA at a separate pin, as serial data is slower, and that the output be two's complement (i.e., the signals are signed integers, so the bits given to the FPGA must also be signed).</p>
<h2>Approach</h2>
<p>My code can be broken up into three phases: signal generation, signal conversion, and signal output.</p>
<h3>Signal generation</h3>
<p>Right now, I'm just using a simple square wave. This is done using </p>
<pre><code>x = 0
signal = 1
while x <= 25:
if x % 2 == 0:
signal*=-1
signals.append(signal)
x+=1
</code></pre>
<h3>Signal conversion</h3>
<p>This iterates over <code>signals</code> and applies <code>twos_comp()</code> to each. <code>twos_comp()</code> converts the integer to its binary representation (carefully slicing off all the unneeded nonsense) and then if the original value was greater than zero, just returns that. Otherwise, the number is inverted using the <code>invert()</code> function, and then has one added to it, and is returned. Type conversions are rife, and this whole thing is rather hack-y.</p>
<p>This assumes 8 bit numbers.</p>
<h3>Signal output</h3>
<p>Using RPi.GPIO, a clock pin (which is mapped to the FPGA's clock) is setup and a set of 8 pins is setup for the signal. Again, parallel not serial. For each item in the new list generated by <code>twos_comp()</code>, the program waits for the clock's rising edge (I know this is somewhat frowned upon, but the output needs to be synced to the clock and the clock is also pretty fast, so it's not like it's going to be waiting for a while (50 mega hertz, can be faster). Then, for each item in the 8-bit number, it's outputted to the appropriate pin.</p>
<h2>Concerns/reviewing</h2>
<p>Any and all comments are welcome in this review, with speed comments (especially in the latter part of the program) extra welcome as I want it to be able to keep up with the FPGA clock. (Speed in the first part obviously isn't as necessary as it all can be done before the FPGA starts up. I also don't know if RPi.GPIO will be able to output the bits fast enough.) As I mentioned earlier, the <code>invert()</code> and <code>twos_comp()</code> functions are...kinda hacky.</p>
<p>Thanks!</p>
<h2>Code</h2>
<pre><code>import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
x = 21
while x <= 28: #signal pins
GPIO.setup(x, GPIO.OUT)
x+=1
GPIO.setup(5, GPIO.IN) #clock
signals = []
bit_signals = []
def invert(bit_val):
new_val = []
for i in bit_val:
new_val.append(str(int(not(int(i)))))
return ''.join(new_val)
def twos_comp(val):
bin_val = format(val, '09b')[-8:]
if val < 0:
return format(int(invert(bin_val),2) + int('1', 2), '08b')
else:
return bin_val
x = 0
signal = 1
while x <= 25:
if x % 2 == 0:
signal*=-1
signals.append(signal)
x+=1
for i in signals:
bit_signals.append(twos_comp(i))
for i in bit_signals:
GPIO.wait_for_edge(5, GPIO.RISING)
counter = 21
for k in str(i):
GPIO.output(counter, k) #k will be 0 or 1 which is accepted input
counter += 1
GPIO.cleanup()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T08:05:17.950",
"Id": "387319",
"Score": "0",
"body": "Pasting your code into https://create.withcode.uk/ which has a Raspberry Pi simulator that includes the RPi.GPIO library throws the error `ExternalError: TypeError: pin is undefi... | [
{
"body": "<p>You should start by organising your code better. Try to avoid global variables and group together code in functions.</p>\n\n<p>In addition, you should learn about list comprehensions. They make initializing your signals way easier.</p>\n\n<pre><code>import RPi.GPIO as GPIO\n\ndef twos_comp(i):\n ... | {
"AcceptedAnswerId": "201153",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T00:49:42.030",
"Id": "201118",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"raspberry-pi",
"fpga"
],
"Title": "Signal output on Raspberry Pi that acts as input for FPGA"
} | 201118 |
<p>I need help with optimizing my Python code. I have a bunch of orders and each order has several SKUs. This is what my data looks like:</p>
<pre><code>ORD_KEY ORD_DT_KEY ORD_TM_KEY QTY SKU_KEY
10001 1 0 1 1
10001 1 0 1 2
10001 1 0 1 3
10002 2 0 1 1
10002 2 0 1 3
10003 3 0 1 4
10004 4 0 1 4
10004 4 0 1 5
10005 5 0 1 1
10006 6 0 1 1
10006 6 0 1 4
</code></pre>
<p>I want to group orders in batches and create a "SKU Count" for each order such that, for every order in a batch, only count the SKU if it was not present in any previous orders of that batch. For example, if my batch size is 3 orders and I'm looking at 1st batch having orders 10001, 10002 & 10003, SKU Counts will be as below:</p>
<ul>
<li>10001 = 3 since it has 3 SKUs {1,2,3} </li>
<li>10002 = 0 since it has 2 SKUs {1,3} but both were part of 10001 </li>
<li>10003 = 1 since it has 1 SKU {4} but it was not part of orders 10001 & 10002</li>
</ul>
<p>Now, in this way, I want to create a matrix called <code>oskupicks</code> of dimensions = [batch size, orders] i.e. each row representing batch size and each column representing an order. Values are the SKU Counts calculated as above. So, for above example, it would look something like this:</p>
<pre><code>Batch size = 1 [... ...]
Batch size = 2 [... ...]
Batch size = 3 [3, 0, 1 ...]
. .
. .
. .
[... ...]
</code></pre>
<p>I tried few approaches and matrix computations seems to be the fastest one -- current code is as below. However, when I ran it for larger data of 10,000 orders and lot many SKUs possible, run time went into hours. Since I'm very new to Python, I'm wondering if there's an even faster way of achieving this or can we have even better logic?</p>
<pre><code>import pandas as pd
import numpy as np
df_ord = pd.DataFrame(
[[10001,1,0,1,1],
[10001,1,0,1,2],
[10001,1,0,1,3],
[10002,2,0,1,1],
[10002,2,0,1,3],
[10003,3,0,1,4],
[10004,4,0,1,4],
[10004,4,0,1,5],
[10005,5,0,1,1],
[10006,6,0,1,1],
[10006,6,0,1,4],
[10007,7,0,1,3],
[10007,7,0,1,4],
[10008,8,0,1,5],
[10009,9,0,1,1],
[10009,9,0,1,4],
[10009,9,0,1,5],
[10010,10,0,2,1],
[10010,10,0,2,2],
[10010,10,0,2,3],
[10011,11,0,1,1],
[10011,11,0,1,3],
[10012,12,0,1,4],
[10012,12,0,1,5],
[10013,13,0,1,1],
[10014,14,0,2,1],
[10014,14,0,2,4]],
columns=['ORD_KEY','ORD_DT_KEY','ORD_TM_KEY','QTY','SKU_KEY'])
#Define input parameters
TotalOrders = df_ord['ORD_KEY'].drop_duplicates().count() #Orders
MaxBatchSize = 10 #Total chutes
#Pivot data to flag SKU presence in each order
print 'Creating Order-SKU pivot...'
arr_order_sku_pivot = pd.pivot_table(df_ord, values = 'QTY', index = 'ORD_KEY', columns = 'SKU_KEY').reset_index(drop=True).values
for i in range(0,arr_order_sku_pivot.shape[0]):
for j in range(0,arr_order_sku_pivot.shape[1]):
if arr_order_sku_pivot[i][j] > 0:
arr_order_sku_pivot[i][j] = 1
else:
arr_order_sku_pivot[i][j] = 0
print 'Building oskupicks matrix...'
oskupicks_matrix = np.zeros((MaxBatchSize,TotalOrders)) # Create empty matrix
distinct_skus = arr_order_sku_pivot.shape[1] # Count of distinct SKUs
for OrdersPerBatch in range(1,MaxBatchSize+1):
print '\n\nOrders per batch =', OrdersPerBatch, ' out of', MaxBatchSize
#Batches required
if TotalOrders % OrdersPerBatch == 0:
Batches = TotalOrders//OrdersPerBatch
else:
Batches = TotalOrders//OrdersPerBatch + 1
print 'Total batches needed =', Batches, '\nProcessing batch...'
for b in range(0,Batches): #Batch ids are from 0 to (Batches-1)
print b+1, '...',
o_min = b*OrdersPerBatch #Starting order number for (b+1)th batch
o_max = min((b+1)*OrdersPerBatch-1, TotalOrders-1) #Ending order number for (b+1)th batch
for o in range(o_min,o_max+1):
arr_sum = np.sum(arr_order_sku_pivot[o_min:o+1], axis = 0)
for s in range(0,distinct_skus):
if arr_sum[s] != 1: arr_sum[s] = 0
arr_curr_order = arr_order_sku_pivot[o]
arr_dot = np.dot(arr_sum, arr_curr_order)
oskupicks_matrix[OrdersPerBatch-1][o] = arr_dot
</code></pre>
| [] | [
{
"body": "<p>Two warnings before I give my suggestions:</p>\n\n<ol>\n<li><p>I'm no expert with pandas, numpy or this domain. There could be a one line solution that has a nice name and has been implemented already. If there is I don't know it.</p></li>\n<li><p>I'm testing the code I provide with python 3.6.6, ... | {
"AcceptedAnswerId": "201230",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T01:03:24.267",
"Id": "201119",
"Score": "7",
"Tags": [
"python",
"performance",
"numpy",
"pandas"
],
"Title": "Counting SKUs that have not appeared in previous orders"
} | 201119 |
<p>I want to efficiently calculate Spearman correlations between a Numpy array and every Pandas <code>DataFrame</code> row:</p>
<pre><code>import pandas as pd
import numpy as np
from scipy.stats import spearmanr
n_rows = 2500
cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
df = pd.DataFrame(np.random.random(size=(n_rows, len(cols))), columns=cols)
v = np.random.random(size=len(cols))
corr, _ = zip(*df.apply(lambda x: spearmanr(x,v), axis=1))
corr = pd.Series(corr)
</code></pre>
<p>For now, the calculation time of <code>corr</code> is:</p>
<pre><code>%timeit corr, _ = zip(*df.apply(lambda x: spearmanr(x,v), axis=1))
>> 1.26 s ± 5.19 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<p>I found <a href="https://stackoverflow.com/a/41806756/3679682">another good approach</a> but it calculates only Pearson correlations:</p>
<pre><code>%timeit df.corrwith(pd.Series(v, index=df.columns), axis=1)
>> 466 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<p>Is there a way to calculate Spearman correlations faster?</p>
| [] | [
{
"body": "<p>Since Spearman correlation is the Pearson correlation coefficient of the ranked version of the variables, it is possible to do the following:</p>\n\n<ol>\n<li>Replace values in <code>df</code> rows with their ranks using <code>pandas.DataFrame.rank()</code> function.</li>\n<li>Convert <code>v</cod... | {
"AcceptedAnswerId": "201223",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T05:23:00.623",
"Id": "201122",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"numpy",
"pandas",
"scipy"
],
"Title": "Spearman correlations between Numpy array and every Pandas DataFrame row"
} | 201122 |
<p>In this example I've a refresh method that might be called by multiple threads. Requirements are: </p>
<ol>
<li><code>refresh()</code> method must be processed by only one thread at a time (blocking)</li>
<li>If already a thread is waiting, skip any new thread tries to acquire the lock to avoid processing multiple times</li>
</ol>
<p>The <code>refresh()</code> method not returning anything nor changing state for the calling thread (fire and forget). So it is not necessary that it's called for every thread, instead, if multiple thread ask for a refresh it should only be executed once.</p>
<p>I'm trying to use a Semaphore with 1 permit for this task. If the semaphore has any queued threads I'm just returning, otherwise the thread will acquire the lock.</p>
<pre><code>class Scratch {
private final Semaphore refreshLock = new Semaphore(1);
public void refresh() {
System.out.println("call refresh()");
try {
synchronized (refreshLock) {
if (refreshLock.hasQueuedThreads()) {
System.out.println("skip this thread ... " + Thread.currentThread().getId());
return; // don't put one more to the queue
}
}
// wait till release of lock
System.out.println("wait for lock release, queue: " + refreshLock.getQueueLength());
refreshLock.acquire();
try {
System.out.println("process ... " + Thread.currentThread().getId());
Thread.sleep(5000);
System.out.println("### DONE");
} finally {
refreshLock.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Task implements Runnable {
private int taskId;
private Scratch scratch;
Task(int id, Scratch scratch) {
this.taskId = id;
this.scratch = scratch;
}
@Override
public void run() {
System.out.println("Task ID : " + this.taskId + " performed by " + Thread.currentThread().getName());
try {
Thread.sleep(300 + taskId * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
scratch.refresh();
}
}
public static void main(String[] args) {
Scratch scratch = new Scratch();
ExecutorService service = Executors.newFixedThreadPool(10);
IntStream.range(0, 12).forEach(i -> service.submit(new Task(i, scratch)));
service.shutdown();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T10:05:33.503",
"Id": "387332",
"Score": "0",
"body": "I think this one is what you want: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html#tryLock()"
}
] | [
{
"body": "<blockquote>\n <p><code>refresh()</code> method must be processed by only one thread at a time ...</p>\n</blockquote>\n\n<pre><code>private final Semaphore refreshLock = new Semaphore(1);\n</code></pre>\n\n<p>A mutex is arguably a better synchronization object choice when you only need one thread at... | {
"AcceptedAnswerId": "201133",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T07:22:34.270",
"Id": "201127",
"Score": "4",
"Tags": [
"java",
"concurrency"
],
"Title": "Semaphore skipping additional threads"
} | 201127 |
<p>I'm working on <a href="https://www.codewars.com/kata/find-all-the-possible-numbers-multiple-of-3-with-the-digits-of-a-positive-integer/train/javascript" rel="nofollow noreferrer">this kata</a> from Codewars. The task is:</p>
<blockquote>
<p>Given a certain number, how many multiples of three could you obtain with its digits?</p>
<p>Supose that you have the number 362. The numbers that can be generated from it are:</p>
<p>362 → 3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632</p>
</blockquote>
<p>I've written the following recursive function to calculate all possiblities:</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 findMult_3 = (num) => {
const powerset = (set) => {
const combinations = []
const combine = (prefix, chars) => {
for (let i = 0; i < chars.length; i++) {
const newPrefix = parseInt(prefix + chars[i])
if (!combinations.includes(newPrefix)) {
combinations.push(newPrefix)
} else {
console.log('encountered duplicate')
}
combine(newPrefix, chars.filter((x, ind) => ind !== i))
}
}
combine('', set)
return combinations.sort((a, b) => a - b)
}
const allCombinations = powerset(num.toString().split(''))
const factorsOfThree = allCombinations.filter(x => x % 3 === 0).filter(x => x !== 0)
return [factorsOfThree.length, factorsOfThree.pop()]
}
findMult_3(43522283000229)</code></pre>
</div>
</div>
</p>
<p>I noticed early on that I encountered <em>a lot</em> of duplicate cases, hence the <code>console.log('encountered duplicate')</code> flag.</p>
<p>Execution of this algorithm is taking an extremely long time for large numbers, eg <code>43522283000229</code>.</p>
<p>How can I improve the performance of this code? Or should it be scrapped entirely?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T11:05:53.123",
"Id": "387339",
"Score": "1",
"body": "@ischnmn This isn't Stack Overflow. Can you please clarify whether the code produces the correct output in the format as required by the challenge or not?"
},
{
"ContentL... | [
{
"body": "<blockquote>\n <p>How can I improve the performance of this code? Or should it be scrapped entirely?</p>\n</blockquote>\n\n<p>I personally would consider taking a wildly different approach, but there are major performance improvements which can be made and which might be sufficient for your purposes... | {
"AcceptedAnswerId": "201137",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T10:41:24.750",
"Id": "201134",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"combinatorics"
],
"Title": "Forming all multiples of 3 using the given digits"
} | 201134 |
<p>I'm working on a web form that functions with numeric inputs. I have <code><input type="number"></code> input fields and with Chrome and Firefox things work nicely since they only allow numeric data to be filled in.</p>
<p>However, I need to support IE11 and it does not enforce the number type when inputting data (but does when submitting data).</p>
<p>Since I want to make it as easy as possible for users (who often copy-paste data from different sources), I wanna sanitize the numbers both on paste as well as on submit.</p>
<p>Things I'm achieving here:</p>
<ul>
<li><p>Replacing spaces and commas as thousand-separators (<code>100 000.25 -> 100000.25</code> and <code>100,000.25 -> 100000.25</code></p></li>
<li><p>Replacing commas a decimal pointer with a dot (<code>100000,25 -> 100000.25</code>)</p></li>
</ul>
<p>How would you improve the code and are there some edge cases I'm forgetting?</p>
<pre><code>function sanitizeValue(value) {
return value.replace(/ /g, '')
.replace(/\./g, ',')
.replace(/[,](?=.*[,])/g, "")
.replace(/,/g, '.')
}
var form = document.getElementById('form')
var inputs = document.getElementsByTagName('input')
form.onsubmit = function(event) {
Object.values(inputs).forEach(function(input) {
input.value = sanitizeValue(input.value)
})
}
Object.values(inputs).forEach(input => {
input.onpaste = ev => {
ev.preventDefault()
let pasteValue = ev.clipboardData.getData('text/plain')
ev.target.value = sanitizeValue(pasteValue)
}
})
</code></pre>
| [] | [
{
"body": "<h1>Don't guess!</h1>\n<p>You should not attempt to correct client input unless you make sure that the client knows (via a click) that a change has been made.</p>\n<p>Converting a value like <code>100,1.0</code> to <code>1001.0</code> is a guess. The client may have intended only the <code>100</code>... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T11:10:23.733",
"Id": "201135",
"Score": "4",
"Tags": [
"javascript",
"regex",
"html5",
"form",
"fixed-point"
],
"Title": "Enforcing numeric inputs and sanitizing different formats for IE11 input fields"
} | 201135 |
<p>I built a workbook to help me extract data from a MSSQL database into Excel. I realize that this is fairly easy to do with Microsoft SQL Server Management Studio, but I can't easily get that installed on my machine at work, so I first have to remote to the server every time to get any data, which becomes a mission if you have to do it often.</p>
<p>The workbook has a small control sheet as follows:
<a href="https://i.stack.imgur.com/sHbhJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sHbhJ.png" alt="Workbook Control Sheet"></a></p>
<p>The button calls <code>Sub ExecSQL()</code> which will scan this sheet for SQL statements, execute them and then paste the results into the corresponding sheet. In this example, it will execute one <code>SELECT</code> statement and paste the result into <code>Fct201712</code>.</p>
<p>I know about SQL injection, but given that I won't be giving this out to users and the SQL auths I use anyway do not have write access to the database, I'm not too concerned about that.</p>
<p>I'm trying to implement some of the suggestions I received on <a href="https://codereview.stackexchange.com/questions/199812/dijkstras-algorithm-implemented-in-excel-vba">this previous question</a>. Given how I now handle errors, I am not closing the DB connection if I get an error. How can I elegantly structure my code so that I always close the connection even if I get an error without using <code>GoTo</code>?</p>
<p>Any other advice on how to improve this code will be greatly appreciated. Also, if you think I'm making the code too complicated, please let me know</p>
<p>Here is the full module:</p>
<pre><code>Option Explicit
Sub ExecSQL()
Dim ActSh As Worksheet
Set ActSh = ActiveSheet
'Connect to the database
Dim Conn As ADODB.Connection
Set Conn = NewDBConnection()
'Get the SQL statements and Worksheets from this sheet
Dim Stmt As Scripting.Dictionary
Set Stmt = GetStatements()
If Not CheckStatements(Stmt) Then Exit Sub
'Execute the SQL commands and paste the results
Dim Sh As Variant
For Each Sh In Stmt.Keys()
If Not ExecSQLStmt(Conn, Sh, Stmt(Sh)) Then Exit Sub
Next
'Clean up
Conn.Close
Set Conn = Nothing
ActSh.Activate
MsgBox "SQL statement execution completed", vbInformation + vbOKOnly, "Completed"
End Sub
Private Function NewDBConnection() As ADODB.Connection
Dim ConStr As String
ConStr = "" _
& "Provider=SQLOLEDB.1;" _
& "Password={redacted};" _
& "Persist Security Info=True;" _
& "User ID={redacted};" _
& "Initial Catalog={redacted};" _
& "Data Source={redacted};" _
& "Use Procedure for Prepare=1;" _
& "Auto Translate=True;" _
& "Packet Size=4096;" _
& "Workstation ID=W530;" _
& "Use Encryption for Data=False;" _
& "Tag with column collation when possible=False"
Dim Conn As ADODB.Connection
Set Conn = New ADODB.Connection
Conn.Open ConStr
Set NewDBConnection = Conn
End Function
Private Function GetStatements() As Scripting.Dictionary
Dim Rng As Range
Set Rng = ActiveSheet.UsedRange
Dim Row As Long
Dim RowHdr As Long
Dim RowCount As Long
RowHdr = 0
RowCount = Rng.Rows.Count
Dim Col As Long
Dim ColSh As Long
Dim ColSQL As Long
Dim ColCount As Long
ColSh = 0
ColSQL = 0
ColCount = Rng.Columns.Count
'Get the header row and applicable columns
Dim ValHdr As String
For Row = 1 To RowCount
For Col = 1 To ColCount
ValHdr = UCase(Trim(GetStrValue(Rng.Cells(Row, Col))))
If ValHdr = "!SHEET" Then
RowHdr = Row
ColSh = Col
ElseIf ValHdr = "!SQL" Then
RowHdr = Row
ColSQL = Col
End If
Next
If RowHdr > 0 Then Exit For
Next
'Scan the rows for any applicable entries
Dim Stmt As Scripting.Dictionary
Set Stmt = New Scripting.Dictionary
Dim ValSh As String
Dim ValSQL As String
If ColSh > 0 And ColSQL > 0 Then
For Row = RowHdr + 1 To RowCount
ValSh = Trim(GetStrValue(Rng.Cells(Row, ColSh)))
ValSQL = Trim(GetStrValue(Rng.Cells(Row, ColSQL)))
If ValSh <> "" And ValSQL <> "" Then
Stmt(ValSh) = ValSQL
End If
Next
End If
Set GetStatements = Stmt
End Function
Private Function CheckStatements(Stmt As Scripting.Dictionary) As Boolean
Dim ErrStr As String
ErrStr = ""
If Stmt.Count = 0 Then
ErrStr = "Could not find any SQL statements on the current sheet." _
& vbCrLf _
& "Did you remember to add ""!Sheet"" and ""!SQL"" header tags?"
End If
If ErrStr = "" Then
CheckStatements = True
Else
MsgBox ErrStr, vbCritical + vbOKOnly, "Error"
CheckStatements = False
End If
End Function
Private Function GetStrValue(Rng As Range) As String
'Get the value of a cell, but do not throw and error if the cell
'contains and error. Intead, just return an empty string
Dim Val As String
Val = ""
On Error Resume Next
Val = Rng.Value
On Error GoTo 0
GetStrValue = Val
End Function
Private Function ExecSQLStmt(Conn As ADODB.Connection, ByVal ShName As String, SQLStmt As String) As Boolean
'Execute the SQL statement and paste the result into the corresponding sheet
Dim Sh As Worksheet
'Delete the sheet if it already exists
On Error Resume Next
Set Sh = ActiveWorkbook.Worksheets(ShName)
On Error GoTo 0
If Not Sh Is Nothing Then
Application.DisplayAlerts = False
Sh.Delete
Application.DisplayAlerts = True
End If
'Create the sheet
With ActiveWorkbook
Set Sh = .Sheets.Add(After:=.Sheets(.Sheets.Count))
End With
Sh.Name = ShName
'Execute the SQL statement
Dim Rs As ADODB.Recordset
On Error Resume Next
Set Rs = Conn.Execute(SQLStmt)
If Rs Is Nothing Then
Dim ErrStr As String
ErrStr = "There was an error executing the SQL statement" & vbCrLf _
& SQLStmt & vbCrLf _
& vbCrLf _
& "Error: " & Err.Description
MsgBox ErrStr, vbCritical + vbOKOnly, "Error"
ExecSQLStmt = False
Exit Function
End If
On Error GoTo 0
'Paste the result into the sheet
Dim Col As Long
For Col = 1 To Rs.Fields.Count
Sh.Cells(1, Col).Value = Rs.Fields(Col - 1).Name
Next
Sh.Cells(1, 1).EntireRow.Font.Bold = True
Sh.Range("A2").CopyFromRecordset Rs
ExecSQLStmt = True
End Function
</code></pre>
| [] | [
{
"body": "<p>Everytime you pass something without <em>ByVal</em> you <strong>are</strong> passing it <em>ByRef</em>, which is general, isn't necessary.</p>\n\n<p>I also see you passing a <code>Scripting.Dictionary</code> around, <em>ByRef</em>. I'd pass this as an object, but I also always use late-binding. I ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T12:00:59.790",
"Id": "201140",
"Score": "2",
"Tags": [
"vba",
"excel",
"error-handling",
"adodb"
],
"Title": "Executing arbitrary SQL statements using VBA in Excel"
} | 201140 |
<p>This is my code for generating augmented training batches in Tensorflow</p>
<pre><code># x_image is the input image tensor
# y_true is the input onehot tensor
# The input tensors to the batch generator.
# These will be fed with the entire training set
images_tensor = tf.placeholder(tf.float32, shape=self.x_image.shape)
onehots_tensor = tf.placeholder(tf.float32, shape=self.y_true.shape)
# Create a dataset object
data = tf.data.Dataset.from_tensor_slices((images_tensor, onehots_tensor))
# Augment the images
data = data.map(lambda x, y: (self.augment_fn(x), y), num_parallel_calls=32)
# Shuffle them and repeat (images_train is actual data)
data = data.apply(tf.contrib.data.shuffle_and_repeat(len(images_train), None))
# Create a batch
data = data.batch(batch_size)
# Pre-fetch a batch worth of data
data = data.prefetch(batch_size)
# Create batch iterator
iterator = data.make_initializable_iterator()
next_element = iterator.get_next()
init_op = iterator.initializer
# Initialise the generator
# images_train and onehot_train are the actual training data (numpy)
session.run(init_op, feed_dict={images_tensor: images_train, onehots_tensor: onehot_train})
</code></pre>
<p>Now inside the training loop I get new batches like:</p>
<pre><code>X, y = session.run(next_element)
</code></pre>
<p>Questions:</p>
<ul>
<li>I put the <code>prefetch</code> size to the <code>batch_size</code>. What would be the point of having more or less? Some examples I see have <code>prefetch</code> size only 5 etc.</li>
<li>Similarly, I put the randomisation size to that of the whole training set, so that the batches are as random as possible. Is there any case for using less than this? Maybe if memory is a problem and the images are being loading from disk?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T12:43:35.617",
"Id": "387345",
"Score": "0",
"body": "Could you add the python version tag?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T12:18:54.757",
"Id": "201141",
"Score": "1",
"Tags": [
"python",
"tensorflow"
],
"Title": "Augmented training batch generation using `tensorflow.data`"
} | 201141 |
<p>I created registration system with PHP. I have User class that will handle all the input and insert the user input into database, and i created Database class with Singleton pattern that will connect to database. After user submited his data, new User object is created. </p>
<p>This is my Database class with singleton patter:</p>
<pre><code>class Database {
private static $instance = null;
private $conn;
private function __construct() {
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$this->conn = new PDO($dsn, DB_USER, DB_PASS);
}
private function __clone() {
return false;
}
private function __wakeup() {
return false;
}
public static function getInstance() {
if(!self::$instance) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->conn;
}
}
</code></pre>
<p>And this is my User class:</p>
<pre><code>class User {
public $errors = array();
protected $username;
protected $pw1;
protected $pw2;
protected $mail;
private $db;
private $conn;
public function __construct() {
$this->db = Database::getInstance();
$this->conn = $this->db->getConnection();
}
}
</code></pre>
<p>I didn't copied rest of the User class code, because my question is: Is this a good way to create singleton pattern for db connection, and a good way to use it in other classes?
I'm fairly new to PHP, and i understand good amount of writing the PHP code, but what i lack is practical knowledge, what are common practices and how to structure the code.</p>
| [] | [
{
"body": "<p>For reasons laid out in <a href=\"https://stackoverflow.com/questions/21832809/php-singleton-database-connection-pattern\">this stackoverflow question</a> the singleton design pattern is not good match for PHP! </p>\n\n<h2>Clone Prevention</h2>\n\n<p>The advice from <a href=\"https://stackoverflo... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T12:54:10.807",
"Id": "201143",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"design-patterns",
"singleton"
],
"Title": "PHP OOP registration with User class and singleton Database class"
} | 201143 |
<p>I have written this module that takes input of configuration of multiple lines with first item as available storage and remaining are the process at different rate using <code>sys.stdin</code> .</p>
<pre><code>#! /usr/bin/python
""" this script calculates the time remaining for available storage to get filled up.
"""
import sys
def time_to_meltdown(proc_r, available_storage):
"""
this functions caclulates the time it will take to full the available disk space
by n number of proceses by the rate of 1 byte after every d(p_i) seconds.
:param list proc_r: number of process with constant but different rate memmory consumption
:param int available_storage: total amount of free storage available on the farm.
:return: time in seconds taken by n process to fill up the storage
:rtype: int
"""
mem = 0 # Initial consumption
timeTaken = 0
while mem < available_storage:
timeTaken += 1 # increament each second by 1
mem = 0
for v in proc_r:
mem += timeTaken // v
return timeTaken
def main():
""" this function builds data from the input and pass it
to function that calculate time it will take to for
available storage to get filled.
"""
input_data = sys.stdin.read()
config_lines = input_data.split("\n")
for line in config_lines:
if line:
data = [int(data) for data in line.split() if data]
available_storage = data[0]
pr_i = data[1:]
print "{} processes will take {} seconds to fill storage".format(len(pr_i), time_to_meltdown(pr_i, available_storage))
if __name__ == "__main__":
main()
</code></pre>
<p>Please review the code for optimal performance.</p>
<p>When I run this code:</p>
<pre><code> while mem < available_storage:
timeTaken += 1 # increament each second by 1
mem = 0
for v in proc_r:
mem += timeTaken // v
return timeTaken
</code></pre>
<p>above lines take quite substantial amount of time for long list of processes.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T20:36:41.123",
"Id": "387395",
"Score": "1",
"body": "As suggested [here](https://stackoverflow.com/a/51719100/3403834), use binary search."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T06:14:08.367... | [
{
"body": "<p>You may be able to speed up the body of the loop using the <code>sum</code> function & list comprehension:</p>\n\n<pre><code>mem = sum( timeTaken // v for v in proc_r )\n</code></pre>\n\n<p>But the real speed up won’t come until you realize you can compute a lower limit for <code>timeTaken</co... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T12:54:23.720",
"Id": "201144",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "performance test the code for finding time taken to fill the disk space"
} | 201144 |
<p>Is there a nicer way to write the <code>maybeWhen</code> portion of <code>displayConnectionAction</code> ? I want to conditionally display an <code>Action</code> depending on whether or not the player is connected. </p>
<p>This bit of code is lifted from a wider system where there are multiple calls like <code>displayConnectionAction</code> (conditional actions built up by a <code>Reader GameState</code>), so I am not after any feedback around things like the <code>Reader</code> being overkill etc, more the implementation of the function <code>displayConnectionAction</code>, the actual code has 12+ functions like this, all generating <code>Maybe Action</code>s based off various bits of logic.</p>
<pre><code>data Action = Action
{ actionLabel :: Text
, actionUrl :: Text
, actionPlayer :: Int
}
data GameState = GameState
{ currentPlayer :: Player
}
data Player = Player
{ playerId :: Int
, playerName :: Text
, playerConnected :: Bool
}
displayConnectionAction :: Reader GameState (Maybe Action)
displayConnectionAction = maybeWhen not <$> isConnected <*> action
where
action =
Just . Action "Connect" "/connect" <$> currentPlayerId
isConnected =
asks (playerConnected . currentPlayer)
currentPlayerId =
asks (playerId . currentPlayer)
maybeWhen :: (a -> Bool) -> a -> Maybe b -> Maybe b
maybeWhen f a mb =
if f a then mb else Nothing
</code></pre>
| [] | [
{
"body": "<p>It always looks a little odd when one has to 'invent' something that seems like it ought to be a common, built-in expression, so I can understand why you ask.</p>\n\n<p>Please interpret any of the following as nothing but my humble attempt to share what I know about Haskell programming. I don't co... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T13:40:27.333",
"Id": "201146",
"Score": "3",
"Tags": [
"haskell",
"optional"
],
"Title": "Conditionally display an Action depending on whether or not a player is connected"
} | 201146 |
<p>I was solving this dynamic programming problem, and I was wondering if I can get any code review and feedback. You can find this <a href="https://www.geeksforgeeks.org/minimum-step-reach-one/" rel="nofollow noreferrer">problem online</a>.</p>
<blockquote>
<pre><code># Coding Problem: Minimum Steps to One
#
# Prompt: Given a positive integer, you can perform any combination of these 3 steps:
# 1.) Subtract 1 from it.
# 2.) If its divisible by 2, divide by 2.
# 3.) If its divisible by 3, divide by 3.
#
# Find the minimum number of steps that it takes get from N to1
#
</code></pre>
</blockquote>
<pre><code>def min_steps_to_one(n):
work = [0, 0]
for i in range(2, n+1):
min_choice = work[i-1]
if i % 3 == 0:
divide_by_three = work[i//3]
min_choice = min(min_choice, divide_by_three)
if i % 2 == 0:
divide_by_two = work[i//2]
min_choice = min(min_choice, divide_by_two)
work.append(min_choice + 1)
return work[n]
</code></pre>
<p>I also include some test cases for Minimum Steps to One Tests</p>
<ol>
<li>true: should return 3 for 10</li>
<li>true: should return 0 for 1 </li>
<li>true: should work for large numbers PASSED: 3 / 3</li>
</ol>
<p></p>
<pre><code>def expect(count, name, test):
if (count is None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
error_msg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception as err:
error_msg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if error_msg is not None:
print(' ' + error_msg + '\n')
print('Minimum Steps to One Tests')
test_count = [0, 0]
def test():
example = min_steps_to_one(10)
return example == 3
expect(test_count, 'should return 3 for 10', test)
def test():
example = min_steps_to_one(1)
return example == 0
expect(test_count, 'should return 0 for 1', test)
def test():
example = min_steps_to_one(1334425)
return example == 22
expect(test_count, 'should work for large numbers', test)
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T05:56:49.023",
"Id": "387410",
"Score": "1",
"body": "The link points to a slightly different problem. Do you mean https://www.geeksforgeeks.org/minimum-steps-minimize-n-per-given-condition/"
}
] | [
{
"body": "<p>This is an alternate to your function which I made out of curiosity. It is similar to yours. It checks the 'path to minimum' with a list. </p>\n\n<p>However, unlike your code, it tests from the top-down rather than from the bottom-up, as suggested by @Josiah. I find this approach way easier to... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T18:00:40.983",
"Id": "201157",
"Score": "5",
"Tags": [
"python"
],
"Title": "Minimum Steps to One to find minimum operations to transform n to 1"
} | 201157 |
<p>I'm writing a function that renders a grid using ASCII line-drawing characters, based on a provided 2D array (or array of arrays), with each top-level array representing a row, and the items inside those arrays as columns.</p>
<p>The function works, but it is <em>absurdly</em> ugly and hard to read. I want to resolve that somehow, but the only things I can think of would already make a massive function even longer and more verbose.</p>
<p>How can this function be improved?</p>
<h3>drawgrid</h3>
<pre><code># Renders an ASCII grid based on a 2D array
def drawgrid(args, boxlen=3)
#Define box drawing characters
side = '│'
topbot = '─'
tl = '┌'
tr = '┐'
bl = '└'
br = '┘'
lc = '├'
rc = '┤'
tc = '┬'
bc = '┴'
crs = '┼'
##############################
draw = []
args.each_with_index do |row, rowindex|
# TOP OF ROW Upper borders
row.each_with_index do |col, colindex|
if rowindex == 0
colindex == 0 ? start = tl : start = tc
draw << start + (topbot*boxlen)
colindex == row.length - 1 ? draw << tr : ""
end
end
draw << "\n" if rowindex == 0
# MIDDLE OF ROW: DATA
row.each do |col|
draw << side + col.to_s.center(boxlen)
end
draw << side + "\n"
# END OF ROW
row.each_with_index do |col, colindex|
if colindex == 0
rowindex == args.length - 1 ? draw << bl : draw << lc
draw << (topbot*boxlen)
else
rowindex == args.length - 1 ? draw << bc : draw << crs
draw << (topbot*boxlen)
end
endchar = rowindex == args.length - 1 ? br : rc
#Overhang elimination if the next row is shorter
if args[rowindex+1]
if args[rowindex+1].length < args[rowindex].length
endchar = br
end
end
colindex == row.length - 1 ? draw << endchar : ""
end
draw << "\n"
end
draw.each do |char|
print char
end
return true
end
</code></pre>
<h3>Usage</h3>
<pre><code>drawgrid([[123,456,789,'baz'], ['abc','def','ghi'], ['foo', 'bar'], ['buz']])
# Output
┌───┬───┬───┬───┐
│123│456│789│baz│
├───┼───┼───┼───┘
│abc│def│ghi│
├───┼───┼───┘
│foo│bar│
├───┼───┘
│buz│
└───┘
</code></pre>
<p>It is a known limitation with the code given that grids with more columns in later rows will display incorrectly. For the purpose this function is being used for, it is an acceptable limitation. I'm okay with fixing it as long as it doesn't bloat this method even further.</p>
<p>I'm also aware of a ruby library, <code>terminal-table</code>, but it's not 100% suited for the kind of terse output I'm looking for. This will be used to display an IP space map, while <code>terminal-table</code> appears to work better for formatted tables like MySQL output.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T14:16:19.610",
"Id": "389591",
"Score": "0",
"body": "How flexible does this need to be, in terms of different numbers of rows/columns being specified?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T18:49:33.673",
"Id": "201159",
"Score": "3",
"Tags": [
"ruby",
"array",
"reinventing-the-wheel"
],
"Title": "Drawing an ASCII grid in Ruby based on a 2D array"
} | 201159 |
<p>You can find the problem <a href="https://stackoverflow.com/questions/51716129/excel-formula-vba-to-keep-a-value-and-edit-cells-to-maintain-that-value/51717706#51717706">here</a>.</p>
<p>The example:</p>
<p>Column A, B, and C are each 3 and together equal 9:</p>
<pre><code>| A | B | C |...| Total |
+----+-----+----+...+-------+
| 3 | 3 | 3 |...| 9 |
</code></pre>
<p>Columns A and B are edited to equal 2 each, but I still want to maintain the total of 9, so I want column C to automatically change to 5:</p>
<pre><code>| A | B | C |...| Total |
+----+-----+----+...+-------+
| 2 | 2 | 3 |...| 7 |
</code></pre>
<p><a href="https://i.stack.imgur.com/fOu4d.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fOu4d.jpg" alt="enter image description here"></a></p>
<p>I realized that my code was a bit of a mess, so I broke it into sheet1, module main and a class named <code>CollectionOfGeneratedValues</code>.</p>
<blockquote>
<p>The only variables you have to adjust in your code are the <code>masterRange</code>, Columns in <code>rangeToFill</code> and a column in <code>sumTarget</code> to suit your data input.</p>
</blockquote>
<p>Quick runthrough:</p>
<ul>
<li><p>You have to set the <code>masterRange</code>, or the range that you are working with, inside VBA. Inside the spreadsheet you must set the <code>sumtarget</code> for each row of the <code>masterRange</code>.</p></li>
<li><p>When a value is entered into a cell inside of your <code>masterRange</code>, we find out what row this is and generate a separate range that is just that row.</p></li>
<li><p>If the input amount is greater than the <code>sumTarget</code> we <code>Exit Sub</code> and scold user.</p></li>
<li><p>We generate an array of values whose sum, along with user input will be the <code>sumtarget</code>. We then take the sum target and subtract the user input.</p>
<ul>
<li>Afterwards generate a random number between 0 and the new <code>sumtarget.value</code> </li>
<li>We then store that rand number and subtract its value from <code>sumtarget</code>.</li>
<li>We do this <code>columnsInRange</code> - 1 times. </li>
<li>When we step out of the <code>for loop</code> for the last value we set the value to whatever is leftover of <code>sumtarget</code>.</li>
<li>With the collection that was created by the steps above we perform a <code>Fisher-Yates Shuffle</code>, so that we don't always the values of collection / our spreadsheet come in a descending order</li>
</ul></li>
</ul>
<p><strong>Sheet 1:</strong></p>
<pre><code>Option Explicit
Private Sub Worksheet_Change(ByVal target As Range)
Main.Main target
End Sub
</code></pre>
<p><strong>Module <code>Main</code>:</strong></p>
<pre><code>Option Explicit
Sub Main(ByRef target As Range)
Dim masterRange As Range
Dim rangeToFill As Range
Dim valuesToFillRange As CollectionOfGeneratedValues
Application.EnableEvents = False
Set masterRange = Range("B1:E5")
Set valuesToFillRange = New CollectionOfGeneratedValues
If Not Intersect(masterRange, target) Is Nothing Then
If checkUserInputValid(target) Then Exit Sub
valuesToFillRange.generateValues target
valuesToFillRange.shuffleCollection
Call printValues(valuesToFillRange, target)
End If
Application.EnableEvents = True
End Sub
Function checkUserInputValid(ByRef userInput As Range) As Boolean
checkUserInputValid = False
If userInput.value > getSumTarget(userInput) Then
MsgBox ("WILL NOT CALCULATE FOR ROW " & userInput.Row & ", USER INPUT GREATER THEN SUMTARGET")
checkUserInputValid = True
Application.EnableEvents = True
End If
End Function
Function getSumTarget(ByRef userInput As Range) As Long
getSumTarget = Range("F" & userInput.Row)
End Function
Function printValues(ByRef valuesToFillRange As CollectionOfGeneratedValues, ByRef userInput As Range)
Dim rangeToFill As Range
Dim collectionCounter As Long
Dim cellInRangeToFill As Range
Set rangeToFill = Range("A" & userInput.Row & ":E" & userInput.Row)
collectionCounter = 1
For Each cellInRangeToFill In rangeToFill
If cellInRangeToFill.Address <> userInput.Address Then
cellInRangeToFill.value = valuesToFillRange(collectionCounter)
collectionCounter = collectionCounter + 1
End If
Next cellInRangeToFill
End Function
</code></pre>
<p><strong>Class named <code>CollectionOfGeneratedValues</code>:</strong></p>
<pre><code>Option Explicit
Private CollectionOfGeneratedValues As Collection
Private Sub Class_Initialize()
Set CollectionOfGeneratedValues = New Collection
End Sub
Private Sub Class_Terminate()
Set CollectionOfGeneratedValues = Nothing
End Sub
Private Property Get NewEnum() As IUnknown
Set NewEnum = CollectionOfGeneratedValues.[_NewEnum]
End Property
Friend Property Get Count() As Long
Count = CollectionOfGeneratedValues.Count
End Property
Friend Sub Add(num As Long)
CollectionOfGeneratedValues.Add num
End Sub
Public Property Get Item(Index As Variant) As Long
Item = CollectionOfGeneratedValues.Item(Index)
End Property
Public Sub Clear()
Set CollectionOfGeneratedValues = New Collection
End Sub
Public Sub shuffleCollection()
Dim holdValuesArray As Collection
Set holdValuesArray = generateColOfValues()
Call swap(holdValuesArray)
End Sub
Private Function generateColOfValues() As Collection
Dim counter As Long
Dim maxNum As Long
Set generateColOfValues = New Collection
maxNum = Me.Count
For counter = 1 To maxNum
generateColOfValues.Add Me.Item(counter)
Next counter
End Function
Private Sub swap(ByRef holdValuesArray As Collection)
Dim randomNum As Long
Dim maxNum As Long
Dim counter As Long
Me.Clear
maxNum = holdValuesArray.Count
For counter = 1 To maxNum
randomNum = Application.WorksheetFunction.RandBetween(1, holdValuesArray.Count)
Me.Add (holdValuesArray(randomNum))
holdValuesArray.Remove (randomNum)
Next counter
End Sub
Public Sub generateValues(ByRef userInput As Range)
Dim userSetValue As Long
Dim sumTarget As Long
Dim sumLeft As Long
Dim numbersToGenerate As Long
userSetValue = userInput.value
sumTarget = getSumTarget(userInput)
sumLeft = setInitialSumLeft(sumTarget, userSetValue)
numbersToGenerate = getNumbersToGenerate(userInput)
Call getValues(numbersToGenerate, sumLeft)
End Sub
Private Function getSumTarget(ByRef userInput As Range) As Long
getSumTarget = Range("F" & userInput.Row)
End Function
Private Function setInitialSumLeft(ByVal sumTarget As Long, ByVal userSetValue As Long) As Long
setInitialSumLeft = sumTarget - userSetValue
End Function
Private Function getNumbersToGenerate(ByRef userInput As Range) As Long
Dim rangeToFill As Range
Set rangeToFill = Range("A" & userInput.Row & ":E" & userInput.Row)
getNumbersToGenerate = rangeToFill.Columns.Count - 1
End Function
Private Sub getValues(ByVal numbersToGenerate As Long, ByVal sumLeft As Long)
Dim counter As Long
Dim value As Long
For counter = 1 To numbersToGenerate - 1
value = Application.WorksheetFunction.RandBetween(0, sumLeft / 1.25)
Me.Add value
sumLeft = sumLeft - value
Next counter
Me.Add sumLeft
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-21T14:45:44.050",
"Id": "389402",
"Score": "0",
"body": "Please do not revise the code. If you do that, you will invalidate the answers given. If you want a review of the new revised code, you can post a new question"
},
{
"Con... | [
{
"body": "<p>The usage of <code>Worksheet_Change</code> event should <em>really</em> have a check built into it e.g.</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal target As Range)\n Dim workingRange As Range\n Set workingRange = Sheet1.Range(\"A2:E5\")\n If Not Intersect(target, workingRange) I... | {
"AcceptedAnswerId": "201780",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T19:56:37.407",
"Id": "201163",
"Score": "7",
"Tags": [
"performance",
"algorithm",
"vba",
"excel",
"sudoku"
],
"Title": "Sudoku-lite challenge"
} | 201163 |
<p>Over the past few weeks, I've been doing the Google Foobar challenges and I've been progressing quite well. I'm currently 1/3 of the way through the third level. However, there were plenty of times over the past few weeks where I felt that my code could have been a lot better. So today I stumbled upon this community and I think that it will be a good idea to ask you guys to review my code.</p>
<p>So this is what I was instructed to do:</p>
<blockquote>
<p>The fuel control mechanisms have three operations: </p>
<ol>
<li><p>Add one fuel pellet</p></li>
<li><p>Remove one fuel pellet</p></li>
<li><p>Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets)</p></li>
</ol>
<p>Write a function called <code>answer(n)</code> which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits.</p>
</blockquote>
<p>This is my solution:</p>
<pre><code> public static int answer(String n) {
//convert n to BigInteger
BigInteger x = new BigInteger(n);
BigInteger two = new BigInteger("2");
BigInteger three = new BigInteger("3");
BigInteger y, z;
int counter = 0;
//Loop for as long as x is not equal to 1
while(!x.equals(BigInteger.ONE)){
//Check if x is divisible by 2
if(x.mod(two).equals(BigInteger.ZERO)){
//divide x by 2
x = x.divide(two);
} else {
//subtract x by 1 and then divide by 2 store in variable z
y = x.subtract(BigInteger.ONE);
z = y.divide(two);
//check if the result of that leaves a number that's divisible by 2, or check if x is equal to 3
if(z.mod(two).equals(BigInteger.ZERO) || x.equals(three)){
x = y;
} else {
x = x.add(BigInteger.ONE);
}
}
counter++;
}
return counter;
}
</code></pre>
<p>For this challenge, I'm a lot more confident and happy with the cleanliness of my code compared to the previous challenges. But seeing that I'm still very much a newbie and this being my first time using BigInteger, I'd very much like a review.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T07:59:50.813",
"Id": "500263",
"Score": "0",
"body": "Is there some requirement to make the implementation as fast and efficient as possible? If not then I would completely discount all the bitwise operator nonsense in the answers y... | [
{
"body": "<p>You could have used the bitwise methods in BigInteger.</p>\n\n<p>You could get rid of both .mod(two) and BigInteger two and instead use !__.testBit(0).</p>\n\n<blockquote>\n <p>Returns true if and only if the designated bit is set. (Computes <code>((this & (1<<n)) != 0)</code>.)</p>\n</... | {
"AcceptedAnswerId": "201167",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T21:08:56.747",
"Id": "201165",
"Score": "2",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Google Foobar level 3"
} | 201165 |
<p>If you press the damage button, it will damage armor before health. If you press the heal button, it will heal armor before health.</p>
<p>The project is here: <a href="https://github.com/austingaee/DamageHealth-Armor/tree/bda2764f5051d688a2cbf75a3328e6abe979f707" rel="nofollow noreferrer">https://github.com/austingaee/DamageHealth-Armor</a></p>
<p>Are there any improvements I can make?</p>
<pre><code>import UIKit
class ViewController: UIViewController {
@IBOutlet weak var armorBarView: UIView!
@IBOutlet weak var healthBarView: UIView!
var damageAmount : Float = 0.0
var healAmount : Float = 0.0
//Maximum Health
var barAmount : Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
damageAmount = Float(self.armorBarView.frame.size.width) * 0.10
healAmount = Float(self.armorBarView.frame.size.width) * 0.05
barAmount = Float(self.armorBarView.frame.size.width)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func damageBar(_ sender: UIButton) {
//7.63 came from how much damage was left after 10 hits
if self.armorBarView.frame.size.width > 7.63 {
self.armorBarView.frame.size.width -= CGFloat(damageAmount)
} else if self.healthBarView.frame.size.width > 7.63 {
self.healthBarView.frame.size.width -= CGFloat(damageAmount)
}
}
@IBAction func healBar(_ sender: Any) {
if self.armorBarView.frame.size.width < CGFloat(barAmount) {
self.armorBarView.frame.size.width += CGFloat(healAmount)
print(self.armorBarView.frame.size.width)
} else if self.healthBarView.frame.size.width < CGFloat(barAmount) {
self.healthBarView.frame.size.width += CGFloat(healAmount)
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T23:04:34.580",
"Id": "387400",
"Score": "0",
"body": "Is it okay to post a link to my github?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T10:48:15.303",
"Id": "387611",
"Score": "0",
"... | [
{
"body": "<p>not so much but some tiny changes:</p>\n\n<p><strong>DRY</strong></p>\n\n<p>i just would avoid all the <code>self.healthBarView.frame.size.width</code> </p>\n\n<p>and make methods:</p>\n\n<ul>\n<li><code>getWidth</code></li>\n<li><code>setWidth</code>(or <code>updateWidth</code> because you set th... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-07T23:03:52.887",
"Id": "201168",
"Score": "1",
"Tags": [
"swift",
"ios",
"cocoa"
],
"Title": "Damage or Heal based on the buttons you press"
} | 201168 |
<p>I have decided to rewrite what I did <a href="https://codereview.stackexchange.com/questions/195430/generic-vector-class-follow-up">here</a>, following the suggestions to use smart pointers. I will rewrite the other data structures as well using smart pointers where appropriate.</p>
<p>I just want to see how my code stands now, I am sure there are still areas I need to improve or fix. I again want to thank this community in their effort in evaluating my code, I really appreciate it and I believe it is slowly but surely taking my coding skills to the next level.</p>
<p>Here is my header file:</p>
<pre><code>#ifndef Vector_h
#define Vector_h
template <class T>
class Vector {
private:
static constexpr int initial_capacity = 100;
// Instance variables
int capacity = 0;
int size = 0;
std::unique_ptr<T[]> data = nullptr;
void deepCopy(const Vector<T> &source) {
capacity = source.size + initial_capacity;
data = std::make_unique<T[]>(capacity);
for (int i = 0; i < source.size; i++) {
data[i] = source.data[i];
}
size = source.size;
}
void expandCapacity() {
auto oldData = std::move(data);
capacity *= 2;
data = std::make_unique<T[]>(capacity);
for (int i = 0; i < size; i++) {
data[i] = oldData[i];
}
}
public:
// Constructors
Vector(); // empty constructor
Vector(int n, const T &value); // constructor
Vector(Vector<T> const &vec); // copy constructor
Vector<T>& operator=(Vector<T> const &rhs); // assignment operator
// Rule of 5
Vector(Vector<T> &&move) noexcept; // move constructor
Vector& operator=(Vector<T> &&move) noexcept; // move assignment operator
~Vector(); // destructor
// Overload operators
T& operator[](int index);
T const& operator[](int index) const;
bool operator==(const Vector<T>&) const;
Vector<T>& operator+=(const Vector<T> &other) {
Vector<T> newValue(size + other.size);
std::copy(this->data, this->data + this->size, newValue.data);
std::copy(other.data, other.data + other.size, newValue.data + this->size);
newValue.swap(*this);
}
friend Vector<T>& operator+(Vector<T> &source1, Vector<T> &source2) {
int n = source1.getSize() + source2.getSize();
Vector<T> newSource(n,0);
for (int i = 0; i < source1.size; i++) {
newSource[i] = source1[i];
}
for (int i = 0; i < source2.size; i++) {
newSource[i + source1.getSize()] = source2[i];
}
return newSource;
}
friend std::ostream& operator<<(std::ostream &str, Vector<T> &data) {
data.display(str);
return str;
}
// Member functions
void swap(Vector<T> &other) noexcept;
void display(std::ostream &str) const;
int getSize() const { return size; }
int getCapacity() const { return capacity; }
bool empty() const { return size == 0; }
void clear() { size = 0; }
T get(int index) const;
void set(int index, const T &value);
void set(int index, T &&value);
void insert(int index, const T &value);
void insert(int index, T &&value);
void remove(int index);
void push_back(const T &value);
void pop_back();
};
template <class T>
Vector<T>::Vector() : capacity(initial_capacity), size(0), data{ new T[capacity] } {}
template <class T>
Vector<T>::Vector(int n, const T &value) {
capacity = (n > initial_capacity) ? n : initial_capacity;
data = std::make_unique<T[]>(capacity);
size = n;
for (int i = 0; i < n; i++) {
data[i] = value;
}
}
template <class T>
Vector<T>::Vector(Vector<T> const &vec) {
deepCopy(vec);
}
template <class T>
Vector<T>::Vector(Vector<T> &&move) noexcept {
move.swap(*this);
}
template <class T>
Vector<T>& Vector<T>::operator=(Vector<T> const &rhs) {
Vector<T> copy(rhs);
swap(copy);
return *this;
}
template <class T>
Vector<T>& Vector<T>::operator=(Vector<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
Vector<T>::~Vector() {
while (!empty()) {
pop_back();
}
}
template <class T>
T& Vector<T>::operator[](int index) {
return data[index];
}
template <class T>
T const& Vector<T>::operator[](int index) const {
return data[index];
}
template <class T>
bool Vector<T>::operator==(const Vector<T> &rhs) const {
if (getSize() != rhs.getSize()) {
return false;
}
for (int i = 0; i < getSize(); i++) {
if (data[i] != rhs[i]) {
return false;
}
}
return true;
}
template <class T>
void Vector<T>::swap(Vector<T> &other) noexcept {
using std::swap;
swap(capacity, other.capacity);
swap(size, other.size);
swap(data, other.data);
}
template <class T>
void Vector<T>::display(std::ostream &str) const {
for (int i = 0; i < size; i++) {
str << data[i] << "\t";
}
str << "\n";
}
template <class T>
T Vector<T>::get(int index) const {
if (index < 0 || index >= size) {
throw std::out_of_range("[]: index out of range.");
}
return data[index];
}
template <class T>
void Vector<T>::set(int index, const T& value) {
if (index < 0 || index >= size) {
throw std::invalid_argument("set: index out of range");
}
data[index] = value;
}
template <class T>
void Vector<T>::set(int index, T&& value) {
if (index < 0 || index >= size) {
throw std::invalid_argument("set: index out of range");
}
data[index] = std::move(value);
}
template <class T>
void Vector<T>::insert(int index, const T& value) {
if (size == capacity) {
expandCapacity();
}
for (int i = size; i > index; i--) {
data[i] = data[i - 1];
}
data[index] = value;
size++;
}
template <class T>
void Vector<T>::insert(int index, T&& value) {
if (size == capacity) {
expandCapacity();
}
if (index < 0 || index >= size) {
throw std::invalid_argument("insert: index out of range");
}
for (int i = size; i > index; i--) {
data[i] = data[i - 1];
}
data[index] = std::move(value);
size++;
}
template <class T>
void Vector<T>::remove(int index) {
if (index < 0 || index >= size) {
throw std::invalid_argument("insert: index out of range");
}
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
}
template<class T>
void Vector<T>::push_back(const T& value) {
insert(size, value);
}
template<class T>
void Vector<T>::pop_back() {
remove(size - 1);
}
#endif /* Vector_h */
</code></pre>
<p>Here is the main.cpp file:</p>
<pre><code>#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <cassert>
#include <ostream>
#include "Vector.h"
int main() {
///////////////////////////////////////////////////////////////////////
///////////////////////////// VECTOR //////////////////////////////////
///////////////////////////////////////////////////////////////////////
Vector<int> nullVector; // Declare an empty Vector
assert(nullVector.getSize() == 0); // Make sure its size is 0
assert(nullVector.empty()); // Make sure the vector is empty
assert(nullVector.getCapacity() == 100); // Make sure its capacity is greater than 0
Vector<int> source(20, 0); // Declare a 20-element zero Vector
assert(source.getSize() == 20); // Make sure its size is 20
for (int i = 0; i < source.getSize(); i++) {
source.set(i, i);
assert(source.get(i) == i); // Make sure the i-th element has value i
}
source.remove(15); // Remove the 15th element
assert(source[15] == 16); // Make sure the 15th element has value 16
source.insert(15, 15); // Insert value 15 at the index 15
assert(source[15] == 15); // Make sure the 15th element has value 15
source.pop_back(); // Remove the last element
assert(source.getSize() == 19); // Make sure its size is 19
source.push_back(19); // Insert value 20 at the bottom
assert(source.getSize() == 20); // Make sure its size is 20
assert(source.get(19) == 19); // Make sure the 19th element has value 19
Vector<int> copyVector(source); // Declare a Vector equal to source
for (int i = 0; i < source.getSize(); i++) {
assert(copyVector[i] == source[i]); // Make sure copyVector equal to source
}
std::cout << "source: \n" << source; // Print out source
std::cout << "copyVector: \n" << copyVector; // Print out copyVector
//Vector<int> newSource = source + copyVector; // Concatenate source and copyVector
//std::cout << "newSource: \n" << newSource; // Print out source + copyVector
source.clear(); // Clear source
assert(source.getSize() == 0); // Make sure its size is 0
std::cout << "Vector unit test succeeded." << std::endl;
std::cin.get();
}
</code></pre>
| [] | [
{
"body": "<h2><code>#include</code> every necessary header</h2>\n\n<p>or your code won't compile and is technically unfit for review here. So don't forget <code><memory></code> and <code><ostream></code> in your <code>.h</code>.</p>\n\n<h2>Memory management</h2>\n\n<p>That's what's most disappointi... | {
"AcceptedAnswerId": "201192",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T00:44:28.330",
"Id": "201171",
"Score": "1",
"Tags": [
"c++",
"pointers",
"vectors"
],
"Title": "Generic Vector Class using smart_pointers"
} | 201171 |
<p>You need to remove the first element which contains a given value from a doubly linked list.</p>
<p>I created two solutions since I find the edge case of removing the first element to be problematic. So I solved it using 2 approaches:</p>
<ol>
<li>using void function and ref</li>
<li>using return value</li>
</ol>
<pre><code>using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
//remove the first element in the list which equals to value
[TestClass]
public class DoublyLinkedListTest
{
private Node head;
[TestInitialize]
public void InitList()
{
head = new Node();
Node two = new Node();
Node three = new Node();
Node four = new Node();
head.Value = 1;
head.Next = two;
two.Value = 2;
two.Prev = head;
two.Next = three;
three.Value = 3;
three.Next = four;
three.Prev = two;
four.Value = 4;
four.Prev = three;
}
[TestMethod]
public void RemoveValueRefFromMiddleOfListTest()
{
DoublyLinkedListHelper.RemoveRefElement(ref head, 3);
Assert.AreEqual(1, head.Value);
Assert.AreEqual(2, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
[TestMethod]
public void RemoveValueFromMiddleOfListTest()
{
head = DoublyLinkedListHelper.RemoveElement(head, 3);
Assert.AreEqual(1,head.Value);
Assert.AreEqual(2, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
[TestMethod]
public void RemoveValueRefFromTopOfListTest()
{
DoublyLinkedListHelper.RemoveRefElement(ref head, 1);
Assert.AreEqual(2, head.Value);
Assert.AreEqual(3, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
[TestMethod]
public void RemoveValueFromTopOfListTest()
{
head = DoublyLinkedListHelper.RemoveElement(head, 1);
Assert.AreEqual(2, head.Value);
Assert.AreEqual(3, head.Next.Value);
Assert.AreEqual(4, head.Next.Next.Value);
}
}
public class DoublyLinkedListHelper
{
public static void RemoveRefElement(ref Node head, int value)
{
if (head == null)
{
return;
}
Node curr = head;
Node prev = null;
Node next = head.Next;
while (curr != null)
{
if (curr.Value == value)
{
if (prev != null)
{
prev.Next = next;
}
if (next != null)
{
next.Prev = prev;
}
curr.Next = null;
curr.Prev = null;
if (curr == head)
{
head = next;
}
break;
}
prev = curr;
curr = next;
next = curr.Next;
}
}
public static Node RemoveElement(Node head, int value)
{
if (head == null)
{
return null;
}
Node curr = head;
Node prev = null;
Node next = head.Next;
while (curr != null)
{
if (curr.Value == value)
{
if (prev != null)
{
prev.Next = next;
}
if (next != null)
{
next.Prev = prev;
}
curr.Next = null;
curr.Prev = null;
if (curr == head)
{
return next;
}
else
{
return head;
}
break;
}
prev = curr;
curr = next;
next = curr.Next;
}
return head;
}
}
public class Node
{
public int Value { get; set; }
public Node Prev { get; set; }
public Node Next { get; set; }
}
}
</code></pre>
| [] | [
{
"body": "<p><s>The methods look fine to me. Reasonable variable names; no confusing control-flow; sensible enough signatures for what they are doing.</s> (see t2chb0t's answer as to why I am wrong)</p>\n\n<p>The tests could be more comprehensive. They should probably check the length of the list, and since th... | {
"AcceptedAnswerId": "201188",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T06:39:09.700",
"Id": "201181",
"Score": "5",
"Tags": [
"c#",
"unit-testing",
"linked-list",
"interview-questions",
"comparative-review"
],
"Title": "Remove the first value for a doubly linked list"
} | 201181 |
<p><strong>Outline:</strong></p>
<p>This code uses the <code>Split</code> function to extract specific information from the following website: <a href="https://www.webscraper.io/test-sites/tables" rel="nofollow noreferrer">https://www.webscraper.io/test-sites/tables</a>.</p>
<p>The required information are the four tables visible on the page with headers <code>"#", "First Name","Last Name","Username"</code>. I am extracting the information within these into 4 dataframes. </p>
<hr>
<p><strong>Example table:</strong></p>
<p><a href="https://i.stack.imgur.com/4R9Lp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4R9Lp.png" alt="table1"></a></p>
<hr>
<p><strong>Description:</strong></p>
<p>I use the <code>requests</code> library to make the <code>GET</code> request, and split the response text on <code>"table table-bordered"</code> to generate my individual table chunks. </p>
<p>There is a fair amount of annoying fiddly indexing to get just the info I want, but the tutorial I am following requires the use of the <code>Split</code> function, and not something far more logical, to my mind, like Beautiful Soup, where I could just apply CSS selectors, for example, and grab what I want. The latter method would be less fragile as well.</p>
<p>I have written a function, <code>GetTable</code>, to parse the required information from each chunk and return a dataframe. There is a difference between the <code>Split</code> delimiter for table 1 versus 2-4. </p>
<p>There isn't an awful lot of code but I would appreciate any pointers on improving the code I have written.</p>
<p>I am running this from Spyder 3.2.8 with Python 3.6.</p>
<hr>
<p><strong>Code:</strong></p>
<pre><code>def GetTable(tableChunk):
split1 = tableChunk.split('tbody')[1]
split2 = split1.split('<table')[0]
values = []
aList = split2.split('>\n\t\t\t\t<')
if len(aList) !=1:
for item in aList[1:]:
values.append(item.split('</')[0].split('d>'[1])[1])
else:
aList = split2.split('</td')
for item in aList[:-1]:
values.append(item.split('td>')[1])
headers = ["#", "First Name", "Last Name", "User Name"]
numberOfColumns = len(headers)
numberOfRows = int((len(values) / numberOfColumns))
df = pd.DataFrame(np.array(values).reshape( numberOfRows, numberOfColumns ) , columns = headers)
return df
import requests as req
import pandas as pd
import numpy as np
url = "http://webscraper.io/test-sites/tables"
response = req.get(url)
htmlText = response.text
tableChunks = htmlText.split('table table-bordered')
for tableChunk in tableChunks[1:]:
print(GetTable(tableChunk))
print('\n')
</code></pre>
| [] | [
{
"body": "<ol>\n<li>Don't parse HTML manually, you should use the <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/\" rel=\"nofollow noreferrer\"><code>BeautifulSoup</code></a> module!</li>\n<li><code>import</code> should be at the top of the file</li>\n<li>Use a <code>if __name__ == '__main__'<... | {
"AcceptedAnswerId": "201202",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T06:58:39.397",
"Id": "201183",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"web-scraping"
],
"Title": "Scrape data from website into dataframe(s) using Split function"
} | 201183 |
<p>This is only the front end side of things which I have at the moment, as the back end is still being worked on. But as this is my first attempt at a react component, I'd like to know if there is anything I can improve on it. </p>
<p>The component has a text area for viewing the current data stored in the cache within our application, another text area for viewing the result when we send that data off to our API and get a transformed version of the data back, as well as two buttons: one for loading the cached data into one of the text areas and one for calling the API with the cached data. This component is used in development/UAT environment for testing purposes. </p>
<pre><code>class DataRevealer extends React.Component {
constructor(props) {
super(props);
this.state = {input: '', result: ''};
this.getCachedDataHandler = this.getCachedDataHandler.bind(this);
this.transformDataHandler = this.transformDataHandler.bind(this);
this.inputDataChanged = this.inputDataChanged.bind(this);
}
getCachedDataHandler() {
let cachedData = DataRevealActions.getCachedData();
this.setState({input: cachedData});
}
transformDataHandler() {
if (this.state.input) {
let transformedData = DataRevealActions.transformData(this.state.input);
this.setState({result: transformedData});
} else {
alert('No data to transform');
}
}
inputDataChanged(event) {
this.setState({input: event.target.value});
}
get getCachedDataButtonText() {
//TODO: localise string
return 'Get Cached Data';
}
get transformDataButtonText() {
//TODO: localise string
return 'Transform Data';
}
render() {
return (
<div className='data-revealer-container'>
<textarea value={ this.state.input }
className='data-revealer-textarea centred-control'
onChange={ this.inputDataChanged }
/>
<div className='action-buttons centred-control'>
<Button onClick={ this.getCachedDataHandler }
className='data-revealer-button centred-control'>
<span>{ this.getCachedDataButtonText }</span>
</Button>
<Button onClick={ this.transformDataHandler }
className='data-revealer-button centred-control' >
<span>{ this.transformDataButtonText }</span>
</Button>
</div>
<textarea value={ this.state.result }
className='data-revealer-textarea centred-control'
/>
</div>
);
}
}
export default DataRevealer;
</code></pre>
<p>Couple of things to note:</p>
<ul>
<li>The <code>Button</code> is one of our custom controls, it acts as a normal button but with pre-implemented styling tweaks. </li>
<li>The <code>TODO</code> may not actually be needed, as the strings may not need to be localised. </li>
<li><code>DataRevealActions</code> are where the back-end code will go, once that work is done. </li>
</ul>
| [] | [
{
"body": "<ul>\n<li><p>You can just remove the TODO until it's needed. The code will be easier to follow and if someone needs to localize later, they can figure it out themselves. It's clutter.</p></li>\n<li><p><code>DataRevealActions</code> would probably be nice to pass in as properties, so the component is ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T07:52:22.417",
"Id": "201187",
"Score": "2",
"Tags": [
"javascript",
"react.js",
"user-interface"
],
"Title": "Simple React component to view cached data and test result from API"
} | 201187 |
<p>Having a view (grid control) that provides some functionallity via methods (primary SerializeView / DeserializeView) that should be called from the view model which is bound to the view.</p>
<p>One point to consinder is, that the view model may not be bound to the view during the deserialization process. Therefore, the serialization state of the view must be buffered in the view model and applied when the view model will be bound to the view.</p>
<p>The following solution can handle such use cases in general:</p>
<h1>Implementation</h1>
<p><strong>IViewAwareViewModel</strong> interface that must be implemented by the view model:</p>
<pre><code>public interface IViewAwareViewModel<TView> where TView : class
{
ViewConnection<TView> ViewConnection { get; }
}
</code></pre>
<p><strong>ViewConection</strong> that encapsulates the view and provides "delayed access".</p>
<pre><code>public class ViewConnection<TView> where TView : class
{
private TaskCompletionSource<TView> taskCompletionSource = new TaskCompletionSource<TView>();
public Task<TView> View => this.taskCompletionSource.Task;
public bool IsConnected => this.taskCompletionSource.Task.IsCompleted;
public void Release()
{
this.taskCompletionSource = new TaskCompletionSource<TView>();
}
public void RunOnView(Action<TView> action)
{
this.View.ContinueWith(task => action(task.Result));
}
internal void SetView(TView view)
{
if (this.IsConnected)
{
throw new InvalidOperationException("Unable to connect to a view twice.");
}
this.taskCompletionSource.SetResult(view);
}
}
</code></pre>
<p><strong>ViewConnector</strong> that provides a helper method for connecting the view with the view model.</p>
<pre><code>public static class ViewConnector<TView> where TView : class
{
public static void Register(FrameworkElement target)
{
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
if (!typeof(TView).IsInstanceOfType(target))
{
throw new InvalidOperationException($"Object of type '{target.GetType()}' is not compatible to type '{typeof(TView)}'.");
}
target.DataContextChanged += TargetDataContextChanged;
}
private static void TargetDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var oldViewModel = e.OldValue as IViewAwareViewModel<TView>;
var newViewModel = e.NewValue as IViewAwareViewModel<TView>;
if (oldViewModel != null)
{
oldViewModel.ViewConnection?.Release();
}
if (newViewModel != null)
{
newViewModel.ViewConnection.SetView(sender as TView);
}
}
}
</code></pre>
<h1>Usage</h1>
<p><strong>View Registration</strong></p>
<pre><code>var dataGrid = new MyDataGrid(); // implements: IDataGridAbstractionForViewModel
ViewConnector<IDataGridAbstractionForViewModel>.Register(dataGrid);
</code></pre>
<p><strong>ViewModel Implementaion</strong></p>
<pre><code>public class DataGridViewModel : ViewModelBase, IViewAwareViewModel<IDataGridAbstractionForViewModel>
{
public ViewConnection<IDataGridAbstractionForViewModel> ViewConnection { get; } = new ViewConnection<IDataGridAbstractionForViewModel>();
protected override string SerializeState()
{
if (this.ViewConnector.IsConnected)
{
var view = this.ViewConnection.View.Result;
return view.SaveLayout();
}
return string.Empty;
}
protected override void DeserializeState(string state)
{
base.DeserializeState(state);
if (string.IsNullOrEmpty(state))
{
return;
}
this.ViewConnection.RunOnView(view => view.RestoreLayout(state));
}
protected override void OnRemoved()
{
base.OnRemoved();
this.ViewConnection.Release();
}
}
</code></pre>
<h1>Questions</h1>
<ul>
<li>Are there other cleaner solutions / approaches?</li>
<li>Do you see any risk of memory leaks?</li>
<li>General feedback? :)</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T14:18:11.667",
"Id": "387502",
"Score": "0",
"body": "What happened to the `my` prefix?! ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T18:27:51.187",
"Id": "387538",
"Score": "1",
"b... | [
{
"body": "<p><code>ViewConnection</code> class looks cool, I think that's a clever use of tasks. But frankly I don't see why you can't have a </p>\n\n<pre><code>public string State { get {...} set {...}}\n</code></pre>\n\n<p>property on both view and viewmodel and solve your problem with two-way databinding. Y... | {
"AcceptedAnswerId": "201207",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T09:55:34.393",
"Id": "201191",
"Score": "5",
"Tags": [
"c#",
"wpf",
"mvvm",
"databinding"
],
"Title": "Accessing View from ViewModel"
} | 201191 |
<p>I'm working on a website where different things can occur on <code>resize</code> and <code>scroll</code> events. I only want one event handler that comes into play, whenever something in the DOM must be changed.</p>
<p>So I created a <code>TaskManager</code> where you can register objects and callbacks, that are run, when the specific event is fired.</p>
<p>The <code>TaskManager</code> is injected into other objects, where <code>this.taskManager.registerTask()</code> is called to send all necessary information.</p>
<p>The <code>TaskManager</code> then executes all registered tasks, as soon as an event occurs. It also sends the current <code>scrollTop</code>-value to the callback.</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>class TaskManager {
constructor() {
this.DOM = {
html: document.getElementsByTagName('html')[0],
}
this.tasks = {
scroll: [],
resize: [],
};
window.addEventListener('scroll', event => {
window.requestAnimationFrame(timestamp => {
this.processTasksOnScroll();
});
});
}
registerTask(type, task) {
if (!this.tasks[type]) {
return false;
}
this.tasks[type].push(task);
return true;
}
processTasksOnScroll() {
const scrollTop = window.scrollY || window.scrollTop || this.DOM.html.scrollTop;
for (const task of this.tasks.scroll) {
task.target[task.callback](scrollTop);
}
}
}
class Test {
constructor(config) {
this.taskManager = config.taskManager || null;
if (this.taskManager) {
this.taskManager.registerTask('scroll', {target: this, callback: 'onScroll'});
}
}
onScroll(scrollTop) {
console.log('Callback in Test with scrollTop: ' + scrollTop);
}
}
const taskManager = new TaskManager();
const test = new Test({taskManager: taskManager});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
height: 120vh;
padding: 20px;
background: rgba(0, 0, 0, 0.2);
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test">Scroll here …</div></code></pre>
</div>
</div>
</p>
<p>Is this a good approach or could something be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T15:38:41.903",
"Id": "387512",
"Score": "0",
"body": "I'm having difficulty understanding why you'd do this over just doing `window.addEventListener('scroll', myFunc)`. You said that you only want one event handler, but this isn't m... | [
{
"body": "<p>Some points.</p>\n\n<ul>\n<li><p><code>window</code> is the default object. You don't need to use is. It is highlighted by the fact you don't use it sometimes <code>window.document</code>, or <code>window.TaskManager</code> but then for objects you are unsure of <code>window.addEventListener</code... | {
"AcceptedAnswerId": "201221",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T10:36:22.840",
"Id": "201195",
"Score": "0",
"Tags": [
"javascript",
"performance",
"event-handling",
"dependency-injection"
],
"Title": "Manager that collects and handles multiple tasks that run on events like window.scroll, window.resize etc"
} | 201195 |
<p>I am new to C# programming. I wrote a little program in C# to calculate all primes until a user-given value. Ignoring the lack of computing power I wrote this program to handle theoretically very huge numbers.</p>
<p>The code works properly. I have no error handling simply because it is a little program for myself. But I'd like some suggestions about error handling. :)</p>
<p>Can you give me suggestions to improve the code? Maybe even to make it faster?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace ConsolePrimes
{
public static class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Up to which number shall all primes be calculated?");
string inputvar = Console.ReadLine();
ulong inputnumber = Convert.ToUInt64(inputvar);
var primes = new List<ulong>();
primes.Add(2);
primes.Add(3);
bool isprime = false;
double result = 0;
for (ulong i = 4; i<inputnumber; i++)
{
isprime = true;
foreach (ulong prime in primes)
{
result = i % prime;
if (result == 0)
{
isprime = false;
break;
}
}
if (isprime == true)
{
primes.Add(i);
}
}
int numberofprimes = primes.Count;
Console.WriteLine("The Range from 0 to " + inputvar + " has " + Convert.ToString(numberofprimes) + " primes.");
Console.WriteLine("The list of all primes is now getting exported to \"primes.txt\".");
TextWriter tw = new StreamWriter("primes.txt");
foreach (ulong nr in primes)
{
tw.WriteLine(nr);
}
tw.Close();
Console.ReadLine();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T12:02:57.830",
"Id": "387468",
"Score": "4",
"body": "You might want to look at other C# programs that also involve prime numbers, e.g. https://codereview.stackexchange.com/questions/26272/prime-numbers-store , https://codereview.st... | [
{
"body": "<p>So this is a curious writeup, because primes can be calculated in many, many ways.</p>\n\n<p>That said, there's one huge optimization we can use to cut your search pattern in half, and it starts here:</p>\n\n<blockquote>\n<pre><code>for (ulong i = 4; i<inputnumber; i++)\n{\n</code></pre>\n</blo... | {
"AcceptedAnswerId": "201205",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T11:56:00.613",
"Id": "201197",
"Score": "11",
"Tags": [
"c#",
"beginner",
"primes"
],
"Title": "Calculating primes until a user-given value"
} | 201197 |
<p>I would like to have some input here if possible, this code should make a request to an API and the call should return the desired object. The client to make the requests was made with Retrofit and Okkhttp3. </p>
<p>I did the following structure so I can mock and unit test more friendly.</p>
<p>I'm implementing it using Single, and when it is subscribed, I create a new instance of a custom SingleObserver to deal with the emitted result and trigger the view update. </p>
<p>Feel free to give feedback or suggestions of how to improve or why I should not apply this structure to trigger the view in an MVP application.</p>
<p>Any feedback or suggestions to improve it I guess...</p>
<p><strong>Interface</strong></p>
<pre><code>public interface MovieService {
@GET("/services/movie")
Single<Movie> getMovie(@Query("name") String name);
</code></pre>
<p><strong>Interactor</strong></p>
<pre><code>public class MovieInteractor implements MovieService {
private final MovieService client;
public MovieInteractor(MovieService client) {
this.client= client;
}
@Override
public Single<Movie> getMovie(String name) {
return client.getMovie(movie);
}
}
</code></pre>
<p><strong>MoviePresenter</strong></p>
<pre><code> @ConfigPersistent
public class MoviePresenter extends BasePresenter<MovieView> implements Serializable {
@Inject
public MoviePresenter() {
}
@Override
public void attachView(MovieView mvpView) {
super.attachView(mvpView);
}
@Override
public void detachView() {
super.detachView();
}
public void requestMovieData(String name, MovieService client) {
MovieIntercator interactor = new MovieInteractor(client);
interactor.getMovie(name)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new MovieSingleObserver(getMvpView()));
}
}
</code></pre>
<p><strong>MovieSingleObserver</strong></p>
<pre><code> public class MovieSingleObserver extends BaseSingleObserver<Movie>{
private MovieView mView;
public MovieSingleObserver(MovieView mView) {
super(mView);
this.mView = mView;
}
@Override
public void onSuccess(Movie item) {
super.onSuccess(item);
mvView.onFetchData(item);
}
@Override
public void onError(Throwable e) {
super.onError(e);
mvView.onFetchDataError(e);
}
}
</code></pre>
<p><strong>MovieInteractorTest</strong></p>
<pre><code> @RunWith(MockitoJUnitRunner.class)
public class MovieInteractorTest {
@Mock
MovieView view;
@Mock
MovieInteractor interactor;
MockedServer mockedServer;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockedServer = new MockedServer();
}
@Test
public void requestMovie_shouldReturn_OnSuccess() {
MockResponse response = new MockResponse().setBody(new Gson().toJson(new Movie()));
response.setResponseCode(200);
mockedServer.setResponse(response);
interactor = new MovieInteractor(mockedServer.getService("/services/movie/", MovieInterface.class));
interactor.getMovie("").subscribe(new MovieSingleObserver(view));
verify(view, atLeastOnce()).onFetchData(refEq(new Movie()));
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T11:58:57.433",
"Id": "201198",
"Score": "1",
"Tags": [
"java",
"android",
"mvp",
"rx-java"
],
"Title": "Consuming APi using Rx in an MVP project"
} | 201198 |
<p>I wrote PHP code to display a Woocommerce notice - "<em>free shipping for $40 & under</em>" only once on shop page and once on cart page, but also in cart should not be more than 40$. The code works, but i am not sure that it is the best way to do it:</p>
<pre><code>$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$shop_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") ."://$_SERVER[HTTP_HOST]/shop/";
$cart_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") ."://$_SERVER[HTTP_HOST]/cart/";
$first_time_shop = false;
if ((!isset($_COOKIE["mynoticeshop"]))&&($actual_link == $shop_link))
{
$first_time_shop = true;
setcookie("mynoticeshop", "mynoticesaleshop", time() + 600, $shop_link);
}
if ($first_time_shop) {
function sp_custom_notice() {
$subtotal = WC()->cart->subtotal;
$free_shipping_threshold = 40;
if ($subtotal < $free_shipping_threshold) {
wc_add_notice( 'free shipping for $40 & under', 'notice' );
}
}
add_filter( 'woocommerce_init', 'sp_custom_notice' );
}
$first_time_cart = false;
if ((!isset($_COOKIE["mynoticecart"]))&&($actual_link == $cart_link)) {
$first_time_cart = true;
setcookie("mynoticecart", "mynoticesalecart", time() + 600, $cart_link);
}
if ($first_time_cart) {
function sp_custom_notice() {
$subtotal = WC()->cart->subtotal;
$free_shipping_threshold = 40;
if ($subtotal < $free_shipping_threshold) {
wc_add_notice( ' free shipping for $40 & under', 'notice' );
}
}
add_filter( 'woocommerce_init', 'sp_custom_notice' );
}
</code></pre>
<p>I am new to Programming and I am interested to know if there is a better and shorter solution of this code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T20:03:04.660",
"Id": "387548",
"Score": "0",
"body": "cross-posted [on SO](https://stackoverflow.com/q/51746382/1575353)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T20:21:46.813",
"Id": "38772... | [
{
"body": "<h2>Don't Repeat Yourself</h2>\n<p>The <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\">D.R.Y. principle</a> is a fundamental principle in programming. Anytime logic is repeated more than once, it should be abstracted. For example, the first three variable assignments ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T12:50:31.853",
"Id": "201206",
"Score": "3",
"Tags": [
"beginner",
"php",
"wordpress",
"e-commerce"
],
"Title": "Conditionally displaying a notice about free shipping in Woocommerce"
} | 201206 |
<p>I wrote a simple C++ template meta function for filtering out types from a list not matching a predicate. This is similar to <a href="https://codereview.stackexchange.com/questions/115740/filtering-variadic-template-arguments">Filtering variadic template arguments</a> but does pattern matching instead of <code>std::conditional</code> with the aim of being faster. To that end no empty typelists are concatenated which should incur less instantiations and be faster according to <a href="https://blog.galowicz.de/2016/06/25/cpp_template_type_list_performance" rel="nofollow noreferrer">https://blog.galowicz.de/2016/06/25/cpp_template_type_list_performance</a></p>
<p>The below code works for all my test cases. Any hints how to make it faster (less template instantiations), smaller, better, ...? (Note: Assume appropriate *_t using-templates)</p>
<pre><code>template <typename... Ts>
struct typelist;
template <typename... TLists>
struct concat;
template <typename... Args1, typename... Args2>
struct concat<typelist<Args1...>, typelist<Args2...>>
{
using type = typelist<Args1..., Args2...>;
};
template <class Seq1, class Seq2, class... Seqs>
struct concat<Seq1, Seq2, Seqs...> : concat<Seq1, concat_t<Seq2, Seqs...>>
{
};
template <class TList, template <typename> class Cond>
struct filter;
template<bool matches, template <typename> class Cond, typename...>
struct filter_helper;
template<template <typename> class Cond, typename T, typename... Ts>
struct filter_helper<true, Cond, T, Ts...>
{
using type = concat_t<typelist<T>, filter_t<typelist<Ts...>, Cond>>;
};
template<template <typename> class Cond, typename T, typename... Ts>
struct filter_helper<false, Cond, T, Ts...>
{
using type = filter_t<typelist<Ts...>, Cond>;
};
template<template <typename> class Cond, typename T, typename... Ts>
struct filter<typelist<T, Ts...>, Cond>
{
using type = typename filter_helper<Cond<T>::value, Cond, T, Ts...>::type;
};
template<template <typename> class Cond>
struct filter<typelist<>, Cond>
{
using type = typelist<>;
};
</code></pre>
<p>Some tests (<code>TMP_ASSERT</code> is like <code>static_assert</code>):</p>
<pre><code>using list1 = tmp::typelist<int, double>;
using list2 = tmp::typelist<float>;
using list3 = tmp::typelist<double>;
using list4 = tmp::typelist<float, double, double>;
using list5 = tmp::typelist<double, float, double>;
using list6 = tmp::typelist<double, double, float>;
using empty = tmp::typelist<>;
template<typename T>
struct is_not_double: std::true_type{};
template<>
struct is_not_double<double>: std::false_type{};
TMP_ASSERT_SAME((tmp::filter_t<list1, is_not_double>), (tmp::typelist<int>));
TMP_ASSERT_SAME((tmp::filter_t<list2, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<list3, is_not_double>), (tmp::typelist<>));
TMP_ASSERT_SAME((tmp::filter_t<list4, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<list5, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<list6, is_not_double>), (tmp::typelist<float>));
TMP_ASSERT_SAME((tmp::filter_t<empty, is_not_double>), (tmp::typelist<>));
</code></pre>
<p>Note: Code is from a library licensed under BSD 3-Clause.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T08:44:20.357",
"Id": "387597",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y... | [
{
"body": "<p>Are you doing it in a namespace? <code>concat</code> and <code>filter</code> are too simple and generic names.</p>\n\n<pre><code>using type = concat_t<typelist<T>, filter_t<typelist<Ts...>, Cond>>;\n</code></pre>\n\n<p>As long as it's the only case you prepend an element to... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T13:26:08.917",
"Id": "201209",
"Score": "7",
"Tags": [
"c++",
"c++14",
"template-meta-programming"
],
"Title": "Filter template meta function"
} | 201209 |
<p>I just wanted to ask if this is a secure code (doesn't really matter if it's optimal or not)</p>
<p>The code</p>
<pre><code>if(!$_SESSION['logged']){
if(!$_POST['inputlogin']||!$_POST['inputpassword']){
require 'cpanellogin.php';
die();
}
else{
$con=mysqli_connect("localhost","root","","librarydb");
mysqli_query($con,'SET CHARACTER SET utf8');
mysqli_query($con,'SET collation_connection = latin2_general_ci');
$login = $_POST['inputlogin'];
$password = $_POST['inputpassword'];
$loginsquery = mysqli_query($con,"SELECT Konta_login, Konta_haslo FROM konta");
while($row = mysqli_fetch_array($loginsquery))
{
$logins[] = $row['Konta_login'];
$passwords[] = $row['Konta_haslo'];
}
$misslogin=0;
for($i=0;$i<count($logins);$i++){
if($login==$logins[$i]){
if(MD5($password)==$passwords[$i]){
$_SESSION['logged'] = $logins[$i];
require 'cpanel.php';
die();
}
else{
$_POST['logerror'] = "Wrong password";
require 'cpanellogin.php';
die();
}
}
else{
$misslogin++;
}
if($misslogin==count($logins)){
$_POST['logerror'] = "Wrong login";
require 'cpanellogin.php';
die();
}
}
}
}
</code></pre>
<p>haslo means password</p>
<p>konta means accounts</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T15:41:33.973",
"Id": "387514",
"Score": "3",
"body": "There is no reason to load all of the user names and passwords into an array and it would be a practice to do so. Change your query to only look for the user name entered then co... | [
{
"body": "<h2>Security</h2>\n\n<h2>Weak comparison</h2>\n\n<p>Unless there is a good reason, you never want to use <code>==</code>, but <code>===</code>. </p>\n\n<p>With your code, passwords that aren't the same would be interpreted as being <a href=\"https://news.ycombinator.com/item?id=9484757\" rel=\"nofoll... | {
"AcceptedAnswerId": "201286",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T15:25:35.567",
"Id": "201217",
"Score": "0",
"Tags": [
"php",
"mysql",
"authentication"
],
"Title": "PHP/MySQL login"
} | 201217 |
<p>I am attempting to update some legacy code that I work with, but my knowledge of data access is limited to a basic use of Entity Framework and simple Dapper. After some research, I have a loose attempt at implementing the repository and unit of work patterns in C# using Dapper.</p>
<p>In the actual implementation of this, there is little or no raw SQL, but all CRUD operations are done with stored procedures as some of the objects are not single table rows. I just used a really rudimentary example here so I could save time. The same goes for connections to the actual database, but I actually do not know the best way to share a connection between repositories without passing it as a parameter to the constructor. A downloadable repository can be found <a href="https://github.com/neldridg/RepositoryExample/" rel="nofollow noreferrer">here</a>.</p>
<p>This is the repository interface that is being implemented.</p>
<pre class="lang-cs prettyprint-override"><code>namespace Repository.Interfaces
{
public interface IRepository<T>
{
void Insert(T entity);
void Delete(T entity);
void Update(T entity);
T GetById(int id);
void Commit();
}
}
</code></pre>
<p>This is the generic base class.</p>
<pre class="lang-cs prettyprint-override"><code>using Repository.Interfaces;
using System;
using System.Data.SQLite;
using Dapper;
namespace Repository.Repositories
{
public abstract class RepositoryBase<T> : IRepository<T>, IDisposable
{
/// <summary>
/// Just using a SQLite database for the purposes of this demo.
/// </summary>
protected SQLiteConnection _connection = new SQLiteConnection("Data Source=:memory:");
protected SQLiteTransaction _transaction;
private bool _disposed;
/// <summary>
/// Opens a connection for each object created.
/// </summary>
protected internal RepositoryBase()
{
_connection.Open();
_transaction = _connection.BeginTransaction();
}
public abstract void Delete(T entity);
public abstract T GetById(int id);
public abstract void Insert(T entity);
public abstract void Update(T entity);
/// <summary>
/// Cleans up after a transaction is complete.
/// </summary>
public void Commit()
{
try
{
_transaction.Commit();
}
catch
{
_transaction.Rollback();
}
finally
{
_transaction.Dispose();
_transaction = _connection.BeginTransaction();
}
}
public void Dispose()
{
Disposable(true);
_connection.Dispose();
GC.SuppressFinalize(this);
}
private void Disposable(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_transaction.Dispose();
_transaction = null;
}
_disposed = true;
}
}
public void CreateDatabase()
{
const string sqlCmd = @"create table Dogs (Id int PRIMARY KEY, Name varchar(50), Breed varchar(50)); "
+ "create table Cats (Id int PRIMARY KEY, Name varchar(50), ShortHair bit); "
+ "insert into Dogs VALUES (1, 'Fido', 'Chocolate Lab');"
+ "insert into Dogs VALUES (2, 'Spot', 'Dalmation');"
+ "insert into Cats VALUES (1, 'Mittens', 1);"
+ "insert into Cats VALUES (2, 'Mr. Floof', 0);";
_connection.Query(sqlCmd);
}
}
}
</code></pre>
<p>This is my rudimentary implementation of a repository.
</p>
<pre><code>using Dapper;
using Repository.Models;
using System.Linq;
using System.Collections.Generic;
namespace Repository.Repositories
{
public class DogRepository : RepositoryBase<Dog>
{
public override void Delete(Dog dog)
{
var dogSql = @"delete from Dogs where Id = " + dog.Id +";";
_connection.Query(dogSql, transaction: _transaction);
}
public override Dog GetById(int id)
{
return _connection.Query<Dog>("select * from Dogs where Id = " + id + ";", transaction: _transaction).FirstOrDefault();
}
public override void Insert(Dog dog)
{
var dogSql = @"insert into Dogs VALUES (" +
dog.Id + ", '" + dog.Name + "', '" + dog.Breed + "');";
_connection.Query(dogSql, transaction: _transaction);
}
public override void Update(Dog dog)
{
var dogSql = @"update Dogs set Name = '" + dog.Name + "' and Breed = '" + dog.Breed + "' where Id = " + dog.Id + ";";
_connection.Query(dogSql, transaction: _transaction);
}
public IEnumerable<Dog> GetAll()
{
return _connection.Query<Dog>("select * from Dogs", transaction: _transaction);
}
}
}
</code></pre>
<p>For a calling example, I have a really basic console application:</p>
<pre class="lang-cs prettyprint-override"><code>using Repository.Repositories;
using System;
namespace RepositoryConsole
{
public class Program
{
public static void Main(string[] args)
{
var dogs = new DogRepository();
dogs.CreateDatabase();
dogs.Insert(new Repository.Models.Dog
{
Breed = @"German Shepherd",
Id = 3,
Name = @"Good boy"
});
var allDogs = dogs.GetAll();
Console.WriteLine("Dogs: ");
foreach (var dog in allDogs)
{
Console.WriteLine(dog);
}
dogs.Commit();
Console.ReadKey();
}
}
}
</code></pre>
<p>Is this code structured correctly to implement a transaction featuring rollbacks?</p>
<p>As I am using Dapper, do I even need to implement managed transactions?</p>
<p>What changes could be made to make the code more resistant to errors on saves/deletes?</p>
<p>For reference, I will actually be using SQL Server rather than SQLite in the production code.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T19:05:22.130",
"Id": "201228",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"sqlite",
"repository",
"dapper"
],
"Title": "Structure and Implementation of Generic Repository and Unit of Work patterns with Dapper and SqlTransactions"
} | 201228 |
<p>I have implemented travelling salesman problem using genetic algorithm.
Since project is not so small I will give short introduction.</p>
<p><code>GeneticAlgorithmParameters</code> - Struct responsible for general algorithm parameters.</p>
<p><code>Point</code> - Super small struct, you can think about it as a city or whatever.</p>
<p><code>Path</code> - Class which contains one path (one solution to the problem). </p>
<p><code>Population</code> - As name indicates class which contains whole population. It is main class for solving this problem. </p>
<p><code>PointInitializer</code> - Interface for 2 classes. Consists of one method <code>getInitialPoints</code>.</p>
<p><code>FilePointInitializer</code> - Derive from mentioned class, it is responsible for reading file (passed by user) and returning <code>std::vector</code> of points as a cities.</p>
<p><code>RandomPointInitializer</code> - Derive from mentioned class, it is responsible for randomly creating and returing <code>std::vector</code> of points as a cities.</p>
<p><code>Parser</code> - It is used to valide command arguments passed by user. For example, when user passes command "help" it prints of help information. After validating arguments it is returning <code>GeneticAlgorithmParameters</code> struct as a settings.</p>
<p><code>Plotter</code> - It is class which is responsible for plotting final solution (OpenCV).</p>
<p><code>Genetic_TSP.cpp</code> file where <code>main.cpp</code> is.</p>
<p>This code uses <code>C++17</code>.</p>
<p><code>GeneticAlgorithmParameters.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_GENETICALGORITHMPARAMETERS_HPP
#define TSP_FINAL_GENETICALGORITHMPARAMETERS_HPP
struct GeneticAlgorithmParameters
{
int numberOfPoints{50};
int sizeOfPopulation{500};
int numberOfIterations{1000};
double mutationRate{0.05};
double percentageOfChildrenFromPreviousGeneration{0.9};
};
#endif
</code></pre>
<p><code>Point.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_POINT_HPP
#define TSP_FINAL_POINT_HPP
struct Point
{
Point() = default;
Point(double x, double y) : x(x), y(y)
{}
bool operator==(const Point &rhs) const
{
return rhs.x == x and rhs.y == y;
}
double x = 0;
double y = 0;
};
#endif
</code></pre>
<p><code>PointInitializer.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_POINTINITIALIZER_HPP
#define TSP_FINAL_POINTINITIALIZER_HPP
#include <Path.hpp>
class PointInitializer
{
public:
virtual ~PointInitializer() = default;
virtual std::vector<Point> getInitialPoints(int) = 0;
};
#endif
</code></pre>
<p><code>FilePointInitializer.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_FILEPOINTINITIALIZER_HPP
#define TSP_FINAL_FILEPOINTINITIALIZER_HPP
#include "PointInitializer.hpp"
#include <string>
#include <fstream>
class FilePointInitializer : public PointInitializer
{
public:
FilePointInitializer(const std::string &);
std::vector<Point> getInitialPoints(int) override;
private:
std::ifstream infile{};
};
#endif
</code></pre>
<p><code>RandomPointInitializer.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_RANDOMPOINTINITIALIZER_HPP
#define TSP_FINAL_RANDOMPOINTINITIALIZER_HPP
#include <random>
#include <algorithm>
#include "PointInitializer.hpp"
class RandomPointInitializer : public PointInitializer
{
public:
RandomPointInitializer(int, int);
std::vector<Point> getInitialPoints(int) override;
private:
std::mt19937 rng{};
std::uniform_int_distribution<std::mt19937::result_type> randX{};
std::uniform_int_distribution<std::mt19937::result_type> randY{};
};
#endif
</code></pre>
<p><code>Path.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_PATH_HPP
#define TSP_FINAL_PATH_HPP
#include "Point.hpp"
#include "PointInitializer.hpp"
#include <vector>
#include <memory>
class Path
{
public:
explicit Path(std::vector<Point>);
double getFitness() const;
double calculateFitness() const;
std::vector<Point> getPath() const;
void mutate(int, int);
std::vector<Point> crossover(const Path &parent) const;
private:
std::vector<Point> path;
double fitness{};
};
#endif
</code></pre>
<p><code>Population.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_POPULATION_HPP
#define TSP_FINAL_POPULATION_HPP
#include <optional>
#include <random>
#include "Path.hpp"
#include "GeneticAlgorithmParameters.hpp"
class Population
{
public:
Population(const GeneticAlgorithmParameters &, std::shared_ptr<PointInitializer>);
Path performTournamentSelection();
void mutation();
void addBestPathsFromPreviousPopulationToNextPopulation(std::vector<Path> &, int) const;
void updatePopulation();
std::vector<Point> getBestSolutionPath() const;
double getBestSolutionFitness() const;
Path getBestSolutionInCurrentPopulation() const;
std::vector<double> getHistoryOfLearning() const;
int getNumberOfBestSolution() const;
void runAlgorithm();
private:
int getRandomNumberInRange(int, int);
void createAllInitialSolutions();
void checkForBetterSolution();
void saveActualScore(double);
std::vector<Path> population{};
GeneticAlgorithmParameters geneticAlgorithmParameters{};
std::shared_ptr<PointInitializer> initializer{};
std::optional<Path> bestSolution{};
std::vector<double> historyOfLearning{};
int bestSolutionNumber{};
};
#endif
</code></pre>
<p><code>Parser.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_PARSER_HPP
#define TSP_FINAL_PARSER_HPP
#include <string>
#include <vector>
#include <optional>
#include "GeneticAlgorithmParameters.hpp"
class Parser
{
public:
explicit Parser(std::vector<std::string>);
void printHelpOptions() const;
bool isCommandPassed(std::string_view) const;
bool isRandomModeEnabled() const;
std::optional<GeneticAlgorithmParameters> validateInput();
std::string getValueFromPassedCommand(std::string_view command) const;
std::string getPassedFilePath() const;
private:
void setSizeOfPopulationParameterFromInput();
void setMutationRateParameterFromInput();
void setNumberOfIterationsParameterFromInput();
void setNumberOfPointsFromInput();
void setPercentageOfChildrenFromPreviousGeneration();
GeneticAlgorithmParameters geneticAlgorithmParameters{};
std::vector<std::string> arguments{};
};
#endif
</code></pre>
<p><code>Plotter.hpp</code></p>
<pre><code>#ifndef TSP_FINAL_PLOTTER_HPP
#define TSP_FINAL_PLOTTER_HPP
#include <vector>
#include "Point.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
class Plotter
{
public:
Plotter(int, int);
void drawPoints(const std::vector<Point> &points) const;
private:
cv::Mat image{};
const int imageWidth{};
const int imageHeight{};
};
#endif
</code></pre>
<p><code>FilePointInitializer.cpp</code></p>
<pre><code>#include "FilePointInitializer.hpp"
#include <iostream>
FilePointInitializer::FilePointInitializer(const std::string &file) : infile(file)
{}
std::vector<Point> FilePointInitializer::getInitialPoints(int sizeOfInitialSolution)
{
double x, y;
std::vector<Point> initialSolution;
initialSolution.reserve(sizeOfInitialSolution);
while (infile >> x >> y)
{
initialSolution.emplace_back(x, y);
if (initialSolution.size() == sizeOfInitialSolution)
{
break;
}
}
if (initialSolution.size() != sizeOfInitialSolution)
{
throw std::invalid_argument("There are not enough data to load from file");
}
infile.clear();
infile.seekg(0, std::ios::beg);
return initialSolution;
}
</code></pre>
<p><code>RandomPointInitializer.cpp</code></p>
<pre><code>#include "RandomPointInitializer.hpp"
RandomPointInitializer::RandomPointInitializer(int imageHeight, int imageWidth) : randX(0, imageWidth),
randY(0, imageHeight)
{
rng.seed(std::random_device()());
}
std::vector<Point> RandomPointInitializer::getInitialPoints(int sizeOfSolution)
{
std::vector<Point> initialSolution;
initialSolution.reserve(sizeOfSolution);
for (auto i = 0; i < sizeOfSolution; ++i)
{
initialSolution.emplace_back(double(randX(rng)), double(randY(rng)));
}
return initialSolution;
}
</code></pre>
<p><code>Parser.cpp</code></p>
<pre><code>#include <iostream>
#include "Parser.hpp"
#include <algorithm>
Parser::Parser(std::vector<std::string> arguments) : arguments(std::move(arguments))
{}
std::string Parser::getValueFromPassedCommand(std::string_view command) const
{
for (const auto &elem : arguments)
{
if (elem.find(command) != std::string::npos)
{
return elem.substr(elem.find('=') + 1);
}
}
}
std::optional<GeneticAlgorithmParameters> Parser::validateInput()
{
if (isCommandPassed("--help"))
{
printHelpOptions();
return {};
}
setSizeOfPopulationParameterFromInput();
setMutationRateParameterFromInput();
setNumberOfIterationsParameterFromInput();
setNumberOfPointsFromInput();
setPercentageOfChildrenFromPreviousGeneration();
return geneticAlgorithmParameters;
}
void Parser::setSizeOfPopulationParameterFromInput()
{
if (isCommandPassed("sizeOfPopulation"))
{
geneticAlgorithmParameters.sizeOfPopulation = std::stoi(getValueFromPassedCommand("sizeOfPopulation"));
}
}
void Parser::setMutationRateParameterFromInput()
{
if (isCommandPassed("mutationRate"))
{
geneticAlgorithmParameters.mutationRate = std::stod(getValueFromPassedCommand("mutationRate"));
}
}
void Parser::setNumberOfIterationsParameterFromInput()
{
if (isCommandPassed("numberOfIterations"))
{
geneticAlgorithmParameters.numberOfIterations = std::stoi(getValueFromPassedCommand("numberOfIterations"));
}
}
void Parser::setNumberOfPointsFromInput()
{
if (isCommandPassed("numberOfPoints"))
{
geneticAlgorithmParameters.numberOfPoints = std::stoi(getValueFromPassedCommand("numberOfPoints"));
}
}
void Parser::setPercentageOfChildrenFromPreviousGeneration()
{
if (isCommandPassed("percentageOfChildrenFromPreviousGeneration"))
{
geneticAlgorithmParameters.percentageOfChildrenFromPreviousGeneration = std::stod(
getValueFromPassedCommand("percentageOfChildrenFromPreviousGeneration"));
}
}
bool Parser::isRandomModeEnabled() const
{
return isCommandPassed("random");
}
bool Parser::isCommandPassed(std::string_view command) const
{
return std::any_of(std::begin(arguments), std::end(arguments), [command](const auto &elem)
{ return elem.find(command) != std::string::npos; });
}
std::string Parser::getPassedFilePath() const
{
return getValueFromPassedCommand("file");
}
void Parser::printHelpOptions() const
{
std::cout << "Travelling Salesman Problem solved by Genetic Algorithm " << '\n' <<
"Options:" << '\n' <<
"--help Print this help" << '\n' <<
"--sizeOfPopulation=<int> Pass size of population" << '\n' <<
"--mutationRate=<double> Pass mutation rate" << '\n' <<
"--numberOfIteration=<int> Pass number of iterations" << '\n' <<
"--random Pass this flag to use randomly generated points" << '\n' <<
"--file=pathToFile Pass path to file which will be used as points in algorithm" << '\n' <<
"--numberOfPoints=<int> Pass numberOfPoints which will be used from file or randomly generated" << '\n' <<
"--percentageOfChildrenFromPreviousGeneration=<double> Pass which percentage best from previous generation will be included"
<< '\n';
}
</code></pre>
<p><code>Path.cpp</code></p>
<pre><code>#include <PointInitializer.hpp>
#include <cmath>
#include <algorithm>
Path::Path(std::vector<Point> path) : path(std::move(path))
{
if (this->path.size() <= 1)
{
throw std::invalid_argument("Number of points in Path should be greater than 1");
}
fitness = calculateFitness();
}
double Path::getFitness() const
{
return fitness;
}
std::vector<Point> Path::getPath() const
{
return path;
}
void Path::mutate(int lowerBound, int upperBound)
{
std::swap(path[lowerBound], path[upperBound]);
}
std::vector<Point> Path::crossover(const Path &parent) const
{
std::vector<Point> child;
child.reserve(path.size());
int halfOfSize = path.size() / 2;
std::copy_n(std::begin(path), halfOfSize, std::back_inserter(child));
for (auto const &elem : parent.path)
{
if (std::find(child.begin(), child.end(), elem) == child.end())
{
child.emplace_back(elem);
}
}
child.emplace_back(path[0]);
return child;
}
double Path::calculateFitness() const
{
auto sum = 0.0;
for (size_t i = 0; i < path.size() - 1; ++i)
{
sum += sqrt(pow(path[i].x - path[i + 1].x, 2.0) + pow(path[i].y - path[i + 1].y, 2.0));
}
return sum;
}
</code></pre>
<p><code>Plotter.cpp</code></p>
<pre><code>#include "Plotter.hpp"
Plotter::Plotter(int imageHeight, int imageWidth) : imageWidth(imageWidth), imageHeight(imageHeight)
{
image = cv::Mat::zeros(imageHeight, imageWidth, CV_8UC3);
}
void Plotter::drawPoints(const std::vector<Point> &points) const
{
for (size_t i = 0; i < points.size() - 1; ++i)
{
cv::line(image, cv::Point(points[i].x, points[i].y), cv::Point(points[i + 1].x, points[i + 1].y),
cv::Scalar(0, 255, 0));
}
for (const auto &point : points)
{
cv::circle(image, cv::Point(point.x, point.y), 3.0, cv::Scalar(255, 255, 255), cv::FILLED, 8);
}
cv::imshow("TSP", image);
cv::waitKey(0);
}
</code></pre>
<p><code>Population.cpp</code></p>
<pre><code>#include "Population.hpp"
#include <algorithm>
#include <iterator>
Population::Population(const GeneticAlgorithmParameters &geneticAlgorithmParameters,
std::shared_ptr<PointInitializer> initializer) :
geneticAlgorithmParameters(geneticAlgorithmParameters),
initializer(std::move(initializer))
{
if (geneticAlgorithmParameters.sizeOfPopulation <= 0)
{
throw std::invalid_argument("sizeOfPopulation must be greater than 0");
}
population.reserve(geneticAlgorithmParameters.sizeOfPopulation);
historyOfLearning.reserve(geneticAlgorithmParameters.numberOfIterations);
createAllInitialSolutions();
bestSolution = getBestSolutionInCurrentPopulation();
saveActualScore(getBestSolutionFitness());
}
Path Population::getBestSolutionInCurrentPopulation() const
{
return *std::min_element(population.begin(),
population.end(),
[](const auto &lhs, const auto &rhs)
{
return lhs.getFitness() < rhs.getFitness();
});
}
void Population::runAlgorithm()
{
for (auto i = 0; i < geneticAlgorithmParameters.numberOfIterations; ++i)
{
updatePopulation();
}
}
void Population::createAllInitialSolutions()
{
auto rng = std::default_random_engine{};
std::vector<Point> initialSolution = initializer->getInitialPoints(geneticAlgorithmParameters.numberOfPoints);
for (auto i = 0; i < geneticAlgorithmParameters.sizeOfPopulation; ++i)
{
std::shuffle(std::begin(initialSolution), std::end(initialSolution), rng);
std::vector<Point> temp(initialSolution);
temp.emplace_back(temp[0]);
population.emplace_back(temp);
}
}
int Population::getRandomNumberInRange(int lowerBound, int upperBound)
{
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<> distr(lowerBound, upperBound);
return distr(eng);
}
Path Population::performTournamentSelection()
{
auto firstRandomNumber = getRandomNumberInRange(0, population.size() - 1);
auto secondRandomNumber = getRandomNumberInRange(0, population.size() - 1);
return std::min(population[firstRandomNumber], population[secondRandomNumber], [](const auto &lhs, const auto &rhs)
{ return lhs.getFitness() < rhs.getFitness(); });
}
void Population::addBestPathsFromPreviousPopulationToNextPopulation(std::vector<Path> &newPopulation,
int howManyPathFromOldPopulationToAdd) const
{
std::vector<Path> temp = population;
std::sort(std::begin(temp), std::end(temp), [](const auto &lhs, const auto &rhs)
{ return lhs.getFitness() > rhs.getFitness(); });
std::copy_n(std::begin(population), howManyPathFromOldPopulationToAdd, std::back_inserter(newPopulation));
}
void Population::mutation()
{
for (auto &elem : population)
{
if (getRandomNumberInRange(0, 1) < geneticAlgorithmParameters.mutationRate)
{
elem.mutate(getRandomNumberInRange(1, geneticAlgorithmParameters.numberOfPoints - 1),
getRandomNumberInRange(1, geneticAlgorithmParameters.numberOfPoints - 1));
}
}
}
void Population::updatePopulation()
{
std::vector<Path> newPopulation;
newPopulation.reserve(geneticAlgorithmParameters.numberOfPoints);
int numberOfChildrenFromParents =
int(geneticAlgorithmParameters.sizeOfPopulation *
geneticAlgorithmParameters.percentageOfChildrenFromPreviousGeneration) / 2;
for (auto i = 0; i < numberOfChildrenFromParents; ++i)
{
Path firstParent = performTournamentSelection();
Path secondParent = performTournamentSelection();
newPopulation.emplace_back(firstParent.crossover(secondParent));
newPopulation.emplace_back(secondParent.crossover(firstParent));
}
addBestPathsFromPreviousPopulationToNextPopulation(newPopulation, geneticAlgorithmParameters.sizeOfPopulation -
numberOfChildrenFromParents * 2);
population = newPopulation;
mutation();
checkForBetterSolution();
}
void Population::checkForBetterSolution()
{
auto bestSolutionInCurrentPopulation = getBestSolutionInCurrentPopulation();
saveActualScore(bestSolutionInCurrentPopulation.getFitness());
if (bestSolutionInCurrentPopulation.getFitness() < bestSolution->getFitness())
{
bestSolution = bestSolutionInCurrentPopulation;
bestSolutionNumber = historyOfLearning.size();
}
}
std::vector<Point> Population::getBestSolutionPath() const
{
return bestSolution->getPath();
}
double Population::getBestSolutionFitness() const
{
return bestSolution->getFitness();
}
std::vector<double> Population::getHistoryOfLearning() const
{
return historyOfLearning;
}
void Population::saveActualScore(double bestSolution)
{
historyOfLearning.emplace_back(bestSolution);
}
int Population::getNumberOfBestSolution() const
{
return bestSolutionNumber;
}
</code></pre>
<p><code>Genetic_TSP.cpp</code></p>
<pre><code>#include "Population.hpp"
#include <algorithm>
#include <Plotter.hpp>
#include <Parser.hpp>
#include <RandomPointInitializer.hpp>
#include <FilePointInitializer.hpp>
void start(std::shared_ptr<PointInitializer>, const GeneticAlgorithmParameters&, int, int);
int main(int argc, char* argv[])
{
Parser parser(std::vector<std::string>(argv+1, argv + argc));
auto parserAlgorithmParameters = parser.validateInput();
auto imageWidth = 1700;
auto imageHeight = 1000;
if(not parserAlgorithmParameters)
{
return 0;
}
if (parser.isRandomModeEnabled())
{
start(std::make_shared<RandomPointInitializer>(imageHeight, imageWidth), *parserAlgorithmParameters, imageHeight, imageWidth);
}
else
{
start(std::make_shared<FilePointInitializer>(parser.getPassedFilePath()), *parserAlgorithmParameters, imageHeight, imageWidth);
}
return(0);
}
void start(std::shared_ptr<PointInitializer> pointInitializer, const GeneticAlgorithmParameters& geneticAlgorithmParameters, int imageHeight, int imageWidth)
{
Population population(geneticAlgorithmParameters, std::move(pointInitializer));
population.runAlgorithm();
auto result = population.getBestSolutionPath();
Plotter plotter(imageHeight, imageWidth);
plotter.drawPoints(result);
}
</code></pre>
<p>Edit:
I have <code>.hpp</code> files in directory "include" and source files in directory "src". </p>
<p>I am adding slightly modified CMakeLists.txt which I use in Clion. I also set in CLion program arguments as <code>--random</code></p>
<pre><code>cmake_minimum_required(VERSION 3.10)
project(TSP_FINAL)
set(CMAKE_CXX_STANDARD 17)
set(GCC_COVERAGE_COMPILE_FLAGS "-Wall -Weffc++ -Wextra ")
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
include_directories(include)
file(GLOB TSP_SRC
"src/*.cpp"
)
add_executable(tsp ${TSP_SRC})
set_target_properties(tsp
PROPERTIES COMPILE_FLAGS ${GCC_COVERAGE_COMPILE_FLAGS})
target_link_libraries(tsp ${OpenCV_LIBS} )
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T09:43:09.043",
"Id": "387605",
"Score": "1",
"body": "Can you provide an example invocation (i.e. show some reasonable command-line arguments, and any necessary file inputs), so that we run a good example?"
}
] | [
{
"body": "<p>There seems to be an error in this function (Parser.cpp):</p>\n\n<pre><code>std::string Parser::getValueFromPassedCommand(std::string_view command) const\n{\n for (const auto &elem : arguments)\n {\n if (elem.find(command) != std::string::npos)\n {\n return elem.... | {
"AcceptedAnswerId": "205062",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T19:12:08.983",
"Id": "201229",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"c++17",
"genetic-algorithm"
],
"Title": "Travelling salesman problem using genetic algorithm in C++"
} | 201229 |
<p>I implemented the Shunting-yard algorithm in Python, I have experience in C# but I'm looking for comments making this more pythonic. I'm also be interested if these methods would be better as <em>classmethods</em> instead of <em>staticmethods</em>.</p>
<pre><code>from collections import deque
import re
class ShuntingYardParser:
"""Converts an infix expression to a postfix expression
using the Shunting-yard algorithm"""
_operatorPrecedence = {"*": 3,
"/": 3,
"+": 2,
"-": 2}
@staticmethod
def _tokenize(expression):
tokenizer = re.compile(r'\s*([()+*/-]|\d+)')
index = 0
tokens = []
while index < len(expression):
match = tokenizer.match(expression, index)
if match is None:
raise ValueError("Syntax error.")
tokens.append(match.group(1))
index = match.end()
return tokens
@staticmethod
def _is_operand(token):
try:
int(token)
return True
except ValueError:
return False
@staticmethod
def _is_operator(token):
return token in ShuntingYardParser._operatorPrecedence
@staticmethod
def parse(infix_expression):
"""Parses the infix expression and returns the postfix expression"""
if not isinstance(infix_expression, str):
raise TypeError("Input is not of type string")
output = list()
operators = deque()
tokens = ShuntingYardParser._tokenize(infix_expression)
for token in tokens:
if ShuntingYardParser._is_operand(token):
output.append(token)
elif ShuntingYardParser._is_operator(token):
current_operator_precedence = ShuntingYardParser._operatorPrecedence[token]
while (operators
and operators[-1] != "("
and ShuntingYardParser._operatorPrecedence[operators[-1]] <= current_operator_precedence):
output.append(operators.pop())
operators.append(token)
elif token == "(":
operators.append(token)
elif token == ")":
# Pop all the operators in front of the "(".
while operators and operators[-1] != "(":
output.append(operators.pop())
# The previous operation would have removed all the operators
# because there is no matching opening parenthesises.
if not operators:
raise ValueError("Non matching parenthesises in the input.")
# Remove matching parenthesis.
operators.pop()
for operator in operators:
# If there are still opening parenthesises in the stack this means
# we haven't found a matching closing one.
if operator == "(":
raise ValueError("Non matching parenthesises in the input.")
output.append(operator)
return output
if __name__ == "__main__":
while True:
action = input("Enter infix expression:")
try:
postfix_notation = ShuntingYardParser.parse(action)
print(postfix_notation)
except ValueError as e:
print(e.args)
</code></pre>
<p>Unit tests:</p>
<pre><code>from unittest import TestCase
from ShuntingYardParser import ShuntingYardParser
class TestShuntingYardParser(TestCase):
def test_single_number(self):
# arrange & act
output = ShuntingYardParser.parse("5")
# assert
self.assertEqual(output, list("5"))
def test_non_string_input(self):
# arrange & act & assert
self.assertRaises(TypeError, ShuntingYardParser.parse, 5)
def test_matching_parenthesises(self):
# arrange & act
output = ShuntingYardParser.parse("(5+2)")
# assert
self.assertEqual(output, ["5", "2", "+"])
def test_non_matching_parenthesises_start(self):
# arrange & act
self.assertRaises(ValueError, ShuntingYardParser.parse, "((5+2)")
def test_non_matching_parenthesises_end(self):
# arrange & act
self.assertRaises(ValueError, ShuntingYardParser.parse, "(5+2))")
</code></pre>
| [] | [
{
"body": "<h2>Interface design</h2>\n\n<p>Note that you only support nonnegative integers as operands.</p>\n\n<p>Your algorithm correctly rearranges the input tokens in postfix order, but it would be more useful if it preserved the operator/operand categorization in its output. It's likely that the results wi... | {
"AcceptedAnswerId": "201240",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T20:04:55.537",
"Id": "201232",
"Score": "5",
"Tags": [
"python",
"algorithm",
"python-3.x",
"math-expression-eval"
],
"Title": "Shunting-yard algorithm"
} | 201232 |
<p>I created this script to stop and then start specific services across an environment of 8 servers. The server names are Apollo-1 thru Apollo-8. I'm looking for suggested changes to make sure my script is acceptable for production. </p>
<pre><code>#Create a credential to be used on remote machines
$User = "MyDomain\myusername"
$Password = ConvertTo-SecureString 'password' -asplaintext -force
$Credential = New-Object -typename System.Management.Automation.PSCredential
-ArgumentList $User, $Password
$Server1 = New-Object System.Object
$Server1 | Add-Member -type NoteProperty -name Name -value "Apollo-1"
$arrServ1Services = @("MSSQLSERVER","QueueManager")
$Server1 | Add-Member -type NoteProperty -name Services -value $arrServ1Services
$Server2 = New-Object System.Object
$Server2 | Add-Member -type NoteProperty -name Name -value "Apollo-2"
$arrServ2Services = @("Analytics Engine", "MSSQLSERVER")
$Server2 | Add-Member -type NoteProperty -name Services -value $arrServ2Services
$Server3 = New-Object System.Object
$Server3 | Add-Member -type NoteProperty -name Name -value "Apollo-3"
$arrServ3Services = @("EDDS Agent Manager", "MSSQLSERVER", "Secret Store")
$Server3 | Add-Member -type NoteProperty -name Services -value
$arrServ3Services
$Server4 = New-Object System.Object
$Server4 | Add-Member -type NoteProperty -name Name -value "Apollo-4"
$arrServ4Services = @("Service Host Manager", "MSSQLSERVER","Service Bus
Gateway","Service Bus Message Broker","Service Bus Resource
Provider","Service Bus VSS","EDDS Agent Manager","Analytics Engine")
$Server4 | Add-Member -type NoteProperty -name Services -value arrServ4Services
$Server5 = New-Object System.Object
$Server5 | Add-Member -type NoteProperty -name Name -value "Apollo-5"
$arrServ5Services = @("MSSQLSERVER")
$Server5 | Add-Member -type NoteProperty -name Services -value $arrServ5Services
$Server6 = New-Object System.Object
$Server6 | Add-Member -type NoteProperty -name Name -value "Apollo-6"
$arrServ6Services = @("Web Processing Manager", "Service Host Manager")
$Server6 | Add-Member -type NoteProperty -name Services -value $arrServ6Services
$Server7 = New-Object System.Object
$Server7 | Add-Member -type NoteProperty -name Name -value "Apollo-7"
$arrServ7Services = @("Web Processing Manager", "Service Host Manager")
$Server7 | Add-Member -type NoteProperty -name Services -value
$arrServ7Services
$Server8 = New-Object System.Object
$Server8 | Add-Member -type NoteProperty -name Name -value "Apollo-8"
$arrServ8Services = @("elasticsearch-service-x64")
$Server8 | Add-Member -type NoteProperty -name Services -value
$arrServ8Services
#Create an object to represent the entire Server environment
$ServerEnvironment = New-Object System.Object
$ServerEnvironment | Add-Member -type NoteProperty -name Machines -value
@($Server1, $Server2, $Server3, $Server4, $Server5, $Server6, $Server7,
$Server8)
#Iterate through each machine in the environment and stop the services.
for ($x = $ServerEnvironment.Machines.Length-1; $x -gt -1; $x--) {
Write-Host " "
Write-Host " "
Write-Host "Machine:" $ServerEnvironment.Machines[$x].Name
Write-Host "No. of Services we are monitoring:"
$ServerEnvironment.Machines[$x].Services.Length
#iterate through services
for ($c = 0; $c -lt $ServerEnvironment.Machines[$x].Services.Length; $c++) {
$_s = Invoke-Command -ComputerName $ServerEnvironment.Machines[$x].Name -
Credential $Credential -Command{param($SERV) Get-Service -Name $SERV} -
ArgumentList $ServerEnvironment.Machines[$x].Services[$c]
Write-Host $ServerEnvironment.Machines[$x].Services[$c] $_s.Status
$_s.StartType
Invoke-Command -ComputerName $ServerEnvironment.Machines[$x].Name -
Credential $Credential -Command{param($SERV) Stop-Service -Name $SERV} -
ArgumentList $ServerEnvironment.Machines[$x].Services[$c]
}
}
#Iterate through each machine in the environment. Here we are starting the
services.
for ($x = 0; $x -lt $ServerEnvironment.Machines.Length; $x++) {
Write-Host " "
Write-Host " "
Write-Host "Machine:" $ServerEnvironment.Machines[$x].Name
Write-Host "No. of Services we are monitoring:"
$ServerEnvironment.Machines[$x].Services.Length
#iterate through service
for ($c = 0; $c -lt $ServerEnvironment.Machines[$x].Services.Length; $c++) {
$_s = Invoke-Command -ComputerName $ServerEnvironment.Machines[$x].Name -
Credential $Credential -Command{param($SERV) Get-Service -Name $SERV} -ArgumentList $ServerEnvironment.Machines[$x].Services[$c]
Write-Host $ServerEnvironment.Machines[$x].Services[$c] $_s.Status $_s.StartType
Invoke-Command -ComputerName $ServerEnvironment.Machines[$x].Name -
Credential $Credential -Command{param($SERV) Start-Service -Name $SERV} -
ArgumentList $ServerEnvironment.Machines[$x].Services[$c]
}
}
Write-Host "Done"
</code></pre>
| [] | [
{
"body": "<p>I don't understand why you build a coplicated structure with separate $server variables. You have a list of server names with associated services. </p>\n\n<p>That's a simple list that could be contained in a csv file. If read into a variable object you could iterate through the list without the n... | {
"AcceptedAnswerId": "201236",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T20:07:41.100",
"Id": "201233",
"Score": "2",
"Tags": [
"powershell"
],
"Title": "Restarts specific services across 8 servers"
} | 201233 |
<p>I'm trying to figure out how to create a <code>NHibernate</code> <code>UnitOfWork</code> using .NET Core Dependency Injection. I was just hard-coding the connection string before moving it to appsettings.json configuration file. Is this form of creating a UOW in the service.scope valid? </p>
<p>It works, but I'm not sure if this is the intended way to do it.</p>
<p><strong>Startup.cs</strong></p>
<pre class="lang-js prettyprint-override"><code>services.AddScoped<IUnitOfWork, UnitOfWorkV>( x=> { return new UnitOfWorkV(Configuration); });
</code></pre>
<p><strong>UnitOfWorkV.cs</strong></p>
<pre class="lang-js prettyprint-override"><code>public UnitOfWorkV(IConfiguration configuration)
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(configuration.GetSection("ConnectionStrings:ConexionV").Value))
.ExposeConfiguration(ConfigureNhibernateValidator)
.Mappings(m =>
{
m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
m.HbmMappings.AddFromAssemblyOf<JobQueue>();
})
.BuildSessionFactory();
Session = _sessionFactory.OpenSession();
Session.FlushMode = FlushMode.Auto;
}
</code></pre>
<p><strong>appsettings.json</strong></p>
<pre class="lang-js prettyprint-override"><code>{
"ConnectionStrings": {
"ConexionV": "Some connection string"
}
}
</code></pre>
| [] | [
{
"body": "<p>In some camps it is not advised to tightly couple your code to framework specific dependencies like <code>IConfiguration</code>.</p>\n\n<p>Based on the shown constructor it looks like the <code>UnitOfWorkV</code> really needs the connection string and not the configuration. That late bound constru... | {
"AcceptedAnswerId": "202231",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T21:34:28.350",
"Id": "201239",
"Score": "1",
"Tags": [
"c#",
".net",
"dependency-injection",
"hibernate",
"asp.net-core"
],
"Title": "Creating an instance of an unit of work (NHibernate)"
} | 201239 |
<p>I was solving this sorting problem, and I was wondering if I can get any code review and feedback. You can find this problem online.</p>
<blockquote>
<pre><code># Find Kth Smallest Element in a Range
#
# Prompt: Given an unsorted array of whole integers in the range
# 1000 to 9000, find the Kth smallest element in linear time
# The array can have duplicates.
#
# Input: Unsorted array of whole integers in range of 1000 to 9000
# Kth smallest element you want to find
#
# Output: Kth smalest element in the range
#
# Example: array = [1984, 1337, 9000, 8304, 5150, 9000, 8304], k=5
# output = 8304
#
# Notes: What are the time and auxilliary space complexity?
# Time Complexity: O(N)
# Auxiliary Space Complexity: O(N)
</code></pre>
</blockquote>
<pre><code>def kthSmallest(lst, k):
if k > len(lst):
return None
int_counts = [0 for x in range(8001)]
for i in range(len(lst)):
int_counts[lst[i] - 1000] += 1
cumulative = []
prev = 0
for i in range(len(int_counts)):
cumulative.append(int_counts[i] + prev)
prev += int_counts[i]
for i in range(len(lst) - 1, -1, -1):
if cumulative[lst[i] - 1000] - 1 == k - 1:
return lst[i]
cumulative[lst[i] - 1000] -= 1
</code></pre>
<h1>it passes all of the following test</h1>
<pre><code>from cStringIO import StringIO
import sys
import random
# code for capturing print output
#
# directions: capture_print function returns a list of all elements that were
# printed using print with the function that it is given. Note that
# the function given to capture_print must be fed using lambda.
# Example cis provided below
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stdout = self._stdout
# custom assert function to handle tests
# input: count {List} - keeps track out how many tests pass and how many total
# in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
# indicating if test passed
# output: {None}
def expect(count, name, test):
if (count is None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
error_msg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception, err:
error_msg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if error_msg is not None:
print(' ' + error_msg + '\n')
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
print('Kth Smallest Element Tests')
test_count = [0, 0]
def test():
example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 5)
return example == 8304
expect(test_count, 'should return 8304 for sample input', test)
def test():
example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 1)
return example == 1337
expect(test_count, 'should return 1337 for 1st smallest element with sample input array', test)
def test():
example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 10)
return example == None
expect(test_count, 'should error out when asking for kth smallest when k exceeds size of input array', test)
def test():
example = kthSmallest([8304], 1)
return example == 8304
expect(test_count, 'should work for single-element array', test)
def test():
test_case = []
for i in range(0, 1000000):
test_case.append(int(random.random() * 8000) + 1000)
example = kthSmallest(test_case, 185)
test_case.sort()
return example == test_case[184]
expect(test_count, 'should work for a large array', test)
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T04:52:18.333",
"Id": "387567",
"Score": "3",
"body": "You keep using `expect()` to test your code. Please look at using pytest or unittest as you might not have a minimum skill level to interview for a coding job. Knowing or having ... | [
{
"body": "<p>There is no need to have a cumulative array. Using append repeatedly is also no such a great idea, because of the cost of memory reallocation.</p>\n\n<pre><code>def kthSmallest(lst, k):\n if k > len(lst):\n return None\n int_counts = [0 for x in range(8001)]\n for i in range(len... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-08T22:42:15.363",
"Id": "201241",
"Score": "4",
"Tags": [
"python"
],
"Title": "K’th SmallestElement in Unsorted Array in python"
} | 201241 |
<p>I would like to get some code review for my recursive implementation of python flatten array method. </p>
<blockquote>
<p>Write a piece of functioning code that will flatten an array of
arbitrarily nested arrays of integers into a flat array of integers.
e.g. [[1,2,[3]],4] -> [1,2,3,4].</p>
</blockquote>
<p>I'm particularly looking for some feedback on the following:</p>
<p>Is usage of TypeError exception justified?
Did I miss some valid edge cases in my tests?
Here is my solution including unit tests:</p>
<pre><code>def flatten(input_array):
result_array = []
for element in input_array:
if isinstance(element, int):
result_array.append(element)
elif isinstance(element, list):
result_array += flatten(element)
return result_array
</code></pre>
<p>it has passed all of the following tests</p>
<pre><code>from io import StringIO
import sys
# custom assert function to handle tests
# input: count {List} - keeps track out how many tests pass and how many total
# in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
# indicating if test passed
# output: {None}
def expect(count, name, test):
if (count is None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
error_msg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception as err:
error_msg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if error_msg is not None:
print(' ' + error_msg + '\n')
# code for capturing print output
#
# directions: capture_print function returns a list of all elements that were
# printed using print with the function that it is given. Note that
# the function given to capture_print must be fed using lambda.
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stdout = self._stdout
def capture_print(to_run):
with Capturing() as output:
pass
with Capturing(output) as output: # note the constructor argument
to_run()
return output
def test():
results = flatten([1, [2, 3, [4]], 5, [[6]]])
return (len(results) == 6 and
results[0] == 1 and
results[1] == 2 and
results[2] == 3 and
results[3] == 4 and
results[4] == 5 and
results[5] == 6)
expect(test_count, 'should return [1,2,3,4,5,6] output for [1, [2, 3, [4]], 5, [[6]]] input', test)
def test():
results = flatten([])
return len(results) == 0
expect(test_count, 'should return [] output for [] input', test)
def test():
results = flatten([1, [2, 3, [4], []], [], 5, [[], [6]]])
return (len(results) == 6 and
results[0] == 1 and
results[1] == 2 and
results[2] == 3 and
results[3] == 4 and
results[4] == 5 and
results[5] == 6)
expect(test_count, 'should return [1,2,3,4,5,6] output for [1, [2, 3, [4], []], [], 5, [[], [6]]] input (note the empty arrays)', test)
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T07:09:22.530",
"Id": "387578",
"Score": "0",
"body": "In terms of your flatten function itself - you could simplify by only checking if the element is a list (and if so, extending recursively), and appending if it's not. Unnecessary... | [
{
"body": "<p>Your code looks fine, however to improve it, you should use a proper test system like pytest or unittest. To demonstrate, here is your code when using pytest, and making the test proper (you don't need to test every specific item:</p>\n\n<pre><code>def flatten(input_array):\n result_array = []\... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T00:36:52.970",
"Id": "201244",
"Score": "5",
"Tags": [
"python"
],
"Title": "Flatten an array in Python"
} | 201244 |
<p>I'm retrieving the operating system platform with .NET Core with <a href="https://www.nuget.org/packages/System.Runtime.InteropServices/" rel="nofollow noreferrer">system.runtime.interopservices</a><br><br>I have created the code below and was wondering if there was any other way that I could improve it since I haven't been able to get a switch statement to work in the OperatingSystem class.</p>
<pre><code>/// <summary>
/// Operating System Class
/// For Retrieving The OS
/// Platform.
/// AE : 9/08/2018
/// </summary>
class OperatingSystem
{
/// <summary>
/// Operating System Platforms.
/// </summary>
public enum OSPlatform
{
Windows,
OSX,
Linux,
Not_Supported
}
/// <summary>
/// Return Operating System
/// </summary>
public static OSPlatform GetPlatform
{
// Switch Statement Not Compatitable
get
{
if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
return OSPlatform.Windows;
}
else if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
{
return OSPlatform.OSX;
}
else if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux))
{
return OSPlatform.Linux;
}
else
{
return OSPlatform.Not_Supported;
}
}
}
}
</code></pre>
<p>The class is being called like this,</p>
<pre><code>static void Main()
{
switch (OperatingSystem.GetPlatform)
{
case OperatingSystem.OSPlatform.Windows:
Console.WriteLine("Goto Windows Class");
break;
case OperatingSystem.OSPlatform.OSX:
Console.WriteLine("Goto OSX Class");
break;
case OperatingSystem.OSPlatform.Linux:
Console.WriteLine("Goto Linux Class");
break;
default:
Console.WriteLine("OS Not Supported");
break;
}
Console.ReadKey();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T09:21:42.227",
"Id": "387600",
"Score": "0",
"body": "I have a question: why have you created another enum that is virtually exactly the same as the core's one instead of using the original one?"
},
{
"ContentLicense": "CC B... | [
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>Don't use underscores in enum values <code>NotSupported</code></li>\n<li>The enum value with integer value 0 represents its default value; I would make this <code>NotSupported</code> in order to avoid some bias</li>\n<li><code>GetPlatform</code> is a method name; prefer <... | {
"AcceptedAnswerId": "227105",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T07:03:38.587",
"Id": "201259",
"Score": "2",
"Tags": [
"c#",
".net-core"
],
"Title": "Retrieving OS Platform .NET Core"
} | 201259 |
<p>I was given 15 minutes to write the code to reverse a singly-linked list.</p>
<p>What do you think of the code style here?</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
[TestClass]
public class ReverseLinkedList
{
[TestMethod]
public void ReservseLinkedListTest()
{
Node<int> head = new Node<int>();
Node<int> two = new Node<int>();
Node<int> three = new Node<int>();
Node<int> four = new Node<int>();
head.Value = 1;
head.Next = two;
two.Value = 2;
two.Next = three;
three.Value = 3;
three.Next = four;
four.Value = 4;
LinkedListHandler.Reserve(ref head);
Assert.AreEqual(4, head.Value);
Assert.AreEqual(3, head.Next.Value);
Assert.AreEqual(2, head.Next.Next.Value);
Assert.AreEqual(1, head.Next.Next.Next.Value);
}
}
public class LinkedListHandler
{
public static void Reserve(ref Node<int> head)
{
Node<int> current = head;
Node<int> previous = null;
while (current != null)
{
Node<int> temp = current.Next;
current.Next = previous;
previous = current;
current = temp;
}
head = previous;
}
}
public class Node<T>
{
public T Value { get; set; }
public Node<T> Next { get; set; }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T07:57:21.287",
"Id": "387590",
"Score": "2",
"body": "What exactly was the interview question (any specific requirements beyond 'reverse a linked list')? And what kind of feedback are you looking for?"
},
{
"ContentLicense":... | [
{
"body": "<p>Test cases right off the bat are a good sign. You only have one, but it is now easier to expand other conditions. I like to add in conditions for list has 0 elements and list is null. You'll be able to prove that those work, or if they don't work, prove that changing it didn't break anything.</p>\... | {
"AcceptedAnswerId": "202143",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T07:34:26.070",
"Id": "201261",
"Score": "2",
"Tags": [
"c#",
"linked-list",
"interview-questions"
],
"Title": "Reverse a linked list"
} | 201261 |
<p>The method below is returning a string of random characters using <code>RNGCryptoServiceProvider</code>. The return string <code>result</code> is built by picking characters from the string <code>chars</code> by applying <code>% chars.length</code>
on the byte values (0-255) in the array of bytes returned by <code>GetBytes()</code>. This means that some characters will be favoured over others, depending on the length of <code>chars</code>.</p>
<p>Can this method be re-written so that all the characters in <code>chars</code> have an equal chance of being picked?</p>
<pre><code>/// <summary>
/// Returns a string of cryptographically sound random characters
/// </summary>
/// <param name="type">Accepted parameter variables are HEX (0-F), hex (0-f),
/// DEC/dec/NUM/num (0-9), ALPHA (A-Z), alpha (a-z), ALPHANUM (A-Z and 0-9),
/// alphanum (a-z and 0-9) and FULL/full (A-Z, a-z and 0-9)</param>
/// <param name="length">The length of the output string</param>
/// <returns>String of cryptographically sound random characters</returns>
public static string Serial(string type, int length)
{
if (length < 1) return "";
string chars;
switch (type)
{
case "HEX":
chars = "0123456789ABCDEF";
break;
case "hex":
chars = "0123456789abcdef";
break;
case "DEC":
chars = "0123456789";
break;
case "dec":
chars = "0123456789";
break;
case "NUM":
chars = "0123456789";
break;
case "num":
chars = "0123456789";
break;
case "ALPHA":
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
break;
case "alpha":
chars = "abcdefghijklmnopqrstuvwxyz";
break;
case "ALPHANUM":
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
break;
case "alphanum":
chars = "abcdefghijklmnopqrstuvwxyz0123456789";
break;
case "FULL":
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
break;
case "full":
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
break;
default:
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
break;
}
byte[] data = new byte[length];
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
crypto.GetBytes(data);
}
StringBuilder result = new StringBuilder(length);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T14:06:55.440",
"Id": "387649",
"Score": "4",
"body": "I would say that this is off-topic, as the code has a known bug. Possibly Stack Overflow is a better place for this."
}
] | [
{
"body": "<ol>\n<li><p>IMO the <code>type</code> parameter calls for an <code>enum</code>:</p>\n\n<pre><code>public enum SerialType\n{\n HEX = 1,\n hex = 2,\n ...\n}\n</code></pre></li>\n<li><p>The two last cases and the default can be combined in one entry:</p>\n\n<pre><code> switch (type)\n {\n ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T08:51:06.613",
"Id": "201264",
"Score": "-2",
"Tags": [
"c#",
"cryptography"
],
"Title": "Generate cryptographically strong random string of characters"
} | 201264 |
<p>I implemented a password field based on the <a href="https://github.com/coleifer/peewee" rel="nofollow noreferrer">peewee</a> framework to handle passwords of accounts in web applications for Python 3.4.</p>
<p>My goals were</p>
<ol>
<li>Secure hashing.</li>
<li>No plain password leakage.</li>
<li>Easy password verification.</li>
</ol>
<p>And this is what I came up with:</p>
<p><code>peeweeplus.passwd</code>:</p>
<pre><code>"""Argon2-based password hashing."""
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError, VerifyMismatchError
from peewee import FieldAccessor
from peeweeplus.exceptions import PasswordTooShortError
__all__ = ['PASSWORD_HASHER', 'is_hash', 'Argon2Hash', 'Argon2FieldAccessor']
PASSWORD_HASHER = PasswordHasher()
_MIN_PW_LEN = 8
def is_hash(hasher, value):
"""Determines whether value is a valid Argon2 hash for hasher."""
try:
return hasher.verify(value, '')
except VerifyMismatchError:
return True
except VerificationError:
return False
class Argon2Hash(str):
"""An Argon2 hash."""
def __new__(cls, _, hash_):
"""Override str constructor."""
return str.__new__(cls, hash_)
def __init__(self, hasher, hash_):
"""Sets the hasher."""
super().__init__()
if not is_hash(hasher, hash_):
raise ValueError('Not an Argon2 hash.')
self._hasher = hasher
@classmethod
def create(cls, hasher, passwd):
"""Creates a hash from the respective hasher and password."""
return cls(hasher, hasher.hash(passwd))
def verify(self, passwd):
"""Validates the plain text password against this hash."""
return self._hasher.verify(self, passwd)
class Argon2FieldAccessor(FieldAccessor):
"""Accessor class for Argon2Field."""
def __get__(self, instance, instance_type=None):
"""Returns an Argon2 hash."""
value = super().__get__(instance, instance_type=instance_type)
if instance is not None:
if value is None:
return None
return Argon2Hash(self.field.hasher, value)
return value
def __set__(self, instance, value):
"""Sets the password hash."""
if value is not None:
if isinstance(value, Argon2Hash):
value = str(value)
else:
# If value is a plain text password, hash it.
if len(value) < _MIN_PW_LEN:
raise PasswordTooShortError(len(value), _MIN_PW_LEN)
value = self.field.hasher.hash(value)
super().__set__(instance, value)
</code></pre>
<p>The actual field:</p>
<pre><code>class PasswordField(FixedCharField):
"""Common base class for password
fields to identify them as such.
"""
pass
class Argon2Field(PasswordField):
"""An Argon2 password field."""
accessor_class = Argon2FieldAccessor
def __init__(self, max_length=None, hasher=PASSWORD_HASHER, **kwargs):
"""Initializes the char field, defaulting
max_length to the respective hash length.
"""
if max_length is None:
max_length = len(hasher.hash(''))
super().__init__(max_length=max_length, **kwargs)
self.hasher = hasher
def python_value(self, value):
"""Returns an Argon2 hash."""
if value is None:
return None
return Argon2Hash(self.hasher, value)
</code></pre>
<p>Any critique is welcome.</p>
<p><strong>Example usage:</strong></p>
<pre><code>>>> from his import Account
>>> account = Account.get(Account.name == 'neumann')
>>> account.passwd = 'top secret'
>>> account.passwd
'$argon2i$v=19$m=512,t=2,p=2$ROFipndj8u2hbr8UhaPOcQ$BcEf+z8mHnYjKYZnausIyA'
>>> account.passwd.verify('wrong')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/peeweeplus/passwd.py", line 51, in verify
return self._hasher.verify(self, passwd)
File "/usr/local/lib/python3.4/dist-packages/argon2/_password_hasher.py", line 133, in verify
Type.I,
File "/usr/local/lib/python3.4/dist-packages/argon2/low_level.py", line 160, in verify_secret
raise VerifyMismatchError(error_to_str(rv))
argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash
>>> account.passwd.verify('top secret')
True
</code></pre>
<p><strong>API notice:</strong></p>
<p>In <code>peewee</code>, when data is retrieved from the database table and "put" on the model instance, the raw data will be converted first using the respective field's <code>python_value</code> method.<br>
Then the respective property is set, which is actually the corresponding <code>FieldAccessor</code> using its <code>__set__</code> method.<br>
When accessing model field properties, this is analogously proxied through the respective field accessor's <code>__get__</code> method.</p>
<p><strong>Library notice:</strong></p>
<p>I am using <code>argon2_cffi</code> as <code>argon2</code> library.</p>
| [] | [
{
"body": "<p>All in all, I find the code very well written.</p>\n\n<p>I don't really understand the purpose of the <code>Argon2Hash.create</code> class method, but I'd venture it is for convenience and testing, so it's harmless to keep it; with a slight change, though:</p>\n\n<pre><code>class Argon2Hash(str):\... | {
"AcceptedAnswerId": "201282",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T09:06:47.283",
"Id": "201265",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"orm"
],
"Title": "Password field based on peewee ORM framework"
} | 201265 |
<p>I wanted to create slider when it slide center slide width must have incresed and the two slide next to it stay on normal slide.</p>
<p>I have tried one using <a href="http://kenwheeler.github.io/slick/" rel="nofollow noreferrer">slick</a> slider.</p>
<p>Here is the code pen <a href="https://codepen.io/sameeraliyanage/pen/ejLqpB" rel="nofollow noreferrer">link</a> that I have tried.</p>
<p>But this is not smooth and slide next to center slide not showing properly.</p>
<p>If anyone know some better slider for do exact kind of this please suggest me a link.</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>$('.slider').slick({
slidesToShow: 3,
centerMode: true,
centerPadding: "0px",
speed: 1000
});
$('.slider').on('beforeChange', function(event, slick, currentSlide, nextSlide){
$(slick).next().css({
'margin-left':'auto'
});//this code not working
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
background: #102131;
}
.slider {
width: 1140px;
margin: 20px auto;
text-align: center;
padding: 20px;
color: white;
}
.slider .slide {
padding: 0px;
}
.slider .slide .child-element {
transition: all .2s ease;
background: #0c1c79;
width: 100%;
height: 800px;
width: 300px;
}
.slider .slide .child-element .imgWrap img {
width: 100%;
max-width: 100%;
}
.slider .slide .child-element .desc {
display: none;
}
.slider .slide.slick-active:last-chid .child-element {
margin-left: auto;
}
.slider .slide.slick-center .child-element {
background: rebeccapurple;
-webkit-transform: translate(-70px, 0px);
transform: translate(-70px, 0px);
width: calc(100% + 140px);
max-width: initial;
}
.slider .slide.slick-center .child-element .desc {
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<link href="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css" rel="stylesheet"/>
<link href="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick-theme.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick.min.js"></script>
<div class="slider">
<div class="slide">
<div class="child-element">
<div class="imgWrap">
<img src="https://www.scopecinemas.com/images/movie/dark900x12001.jpg" alt="">
</div>
<div class="text">Title1</div>
<div class="desc">Lorem ipsum dolor</div>
</div>
</div>
<div class="slide">
<div class="child-element">
<div class="imgWrap">
<img src="https://www.scopecinemas.com/images/movie/trans900x1200.jpg" alt="">
</div>
<div class="text">Title2</div>
<div class="desc">Lorem ipsum dolor</div>
</div>
</div>
<div class="slide">
<div class="child-element">
<div class="imgWrap">
<img src="https://www.scopecinemas.com/images/movie/mi900x1200.jpg" alt="">
</div>
<div class="text">Title3</div>
<div class="desc">Lorem ipsum dolor</div>
</div>
</div>
<div class="slide">
<div class="child-element">
<div class="imgWrap">
<img src="https://www.scopecinemas.com/images/movie/Venom900x1200.jpg" alt="">
</div>
<div class="text">Title4</div>
<div class="desc">Lorem ipsum dolor</div>
</div>
</div>
<div class="slide">
<div class="child-element">
<div class="imgWrap">
<img src="https://www.scopecinemas.com/images/movie/alpha900x1200.jpg" alt="">
</div>
<div class="text">Title5</div>
<div class="desc">Lorem ipsum dolor</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T10:17:51.797",
"Id": "201269",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Slider that increased center slide width. (Slider plugin suggestions)"
} | 201269 |
<p>I'm very new to python and programming in general. For a school assignment, I made this Memory Game and would love to receive feedback from you guys. </p>
<pre><code>import tkinter as tk # imports tkinter as tk
from tkinter import font as tkfont # imports font as tkfont
import random # imports random
import string # imports string
import sys # imports sys
import time # imports time
import pygame # imports pygame (enables me to use its functions)
pygame.mixer.pre_init(44100, 16, 2, 4096) # Enables me to use music in pygame
pygame.init() # Enables me to use music in pygame
button_click = pygame.mixer.Sound('151022__bubaproducer__laser-shot-silenced.wav')
# Loads '151022__bubaproducer__laser-shot-silenced.wav' file
button_click2 = pygame.mixer.Sound('Mario Coin.wav') # Makes button_click2 play 'Mario Coin.wav' file
pygame.mixer.music.load('merge_from_ofoct.mp3') # Loads my music file
pygame.mixer.music.play(-1) # -1 plays the song infinitely
pygame.mixer.music.set_volume(0.8) # Sets the volume of the music
def logout_logout(): # Defines logout_logout
entUsername.delete(0, tk.END) # Deletes past entry's in the Username entry box
entPassword.delete(0, tk.END) # Deletes past entry's in the Password entry box
entUsername.focus_set() # Makes it so the Username entry box is targeted
def play_music1(): # Defines play_music1
pygame.mixer.music.load('merge_from_ofoct.mp3') # Loads 'merge_from_ofoct.mp3' file
pygame.mixer.music.play(-1) # Makes the song play infinitely
pygame.mixer.music.set_volume(0.8) # Sets the volume (volume can be adjusted from 0-1)
def play_music2(): # Defines play_music2
pygame.mixer.music.load('251461__joshuaempyre__arcade-music-loop.wav')
# Loads '251461__joshuaempyre__arcade-music-loop.wav3' file
pygame.mixer.music.play(-1) # Makes the song play infinitely
pygame.mixer.music.set_volume(0.8) # Sets the volume (volume can be adjusted from 0-1)
def play_music3(): # Defines play_music3
pygame.mixer.music.load('Off Limits.wav') # Loads 'Off Limits.wav') file
pygame.mixer.music.play(-1) # Makes the song play infinitely
pygame.mixer.music.set_volume(0.8) # Sets the volume (volume can be adjusted from 0-1)
def play_music4(): # Defines play_music4
pygame.mixer.music.load('Pim Poy.wav') # Loads 'Pim Poy.wav') file
pygame.mixer.music.play(-1) # Makes the song play infinitely
pygame.mixer.music.set_volume(0.8) # Sets the volume (volume can be adjusted from 0-1)
def play_music5(): # Defines play_music5
pygame.mixer.music.load('Puzzle-Game.mp3') # Loads 'Puzzle-Game.mp3') file
pygame.mixer.music.play(-1) # Makes the song play infinitely
pygame.mixer.music.set_volume(0.8) # Sets the volume (volume can be adjusted from 0-1)
def return_to_main_menu2(): # Defines return_to_main_menu2
pygame.mixer.Sound.play(button_click2).set_volume(0.8) # Plays button_click2/sets the volume of the song
def return_to_main_menu(): # Defines return_to_main_menu
pygame.mixer.Sound.play(button_click).set_volume(0.6) # Plays button_click/sets the volume of the sound
def random_char(y): # Defines random_char
return ''.join(random.choice(string.ascii_letters) for x in range(y))
x = (random_char(6)) # Spawns 6 random characters
word = x # Makes word=x
</code></pre>
<p>Class #1</p>
<pre><code>class SampleApp(tk.Tk): # Class - Basically my Main hub
def __init__(self, *args, **kwargs): # Arguments is controller and kwargs are keyword arguments
tk.Tk.__init__(self, *args, **kwargs) # Arguments is controller and kwargs are keyword arguments
self.geometry("1920x1080") # Size of the window when the programs run
self.title("Memory Mania") # Puts "Memory Mania" in the top left of the window
self.title_font = tkfont.Font(family='verdana', size=45, weight="bold", slant="italic")
# Whenever i use use "font=controller.title_font", this font will be used
container = tk.Frame(self) # Defines it
container.pack(side="top", fill="both", expand=True) # Packs it
container.grid_rowconfigure(0, weight=1) # Changes the size
container.grid_columnconfigure(0, weight=1) # Changes the size
self.frames = {} # Below this is all my classes, if the class isn't listed here it wont show
for F in (Login, MainMenu, Tutorial, Tutorial2, Difficulty, Settings, Music, EasyDifficulty, MediumDifficulty,
HardDifficulty, InsaneDifficulty, EnterCharacterScreen, CorrectScreen, IncorrectScreen, Level2,
WinGameScreen):
page_name = F.__name__ # Makes page_name = F._name_
frame = F(parent=container, controller=self) # frame = F(parent=container, controller=self)
self.frames[page_name] = frame # self.frame(page_name) = frame
frame.grid(row=0, column=0, sticky="nsew") # the frames grid size
self.show_frame("Login") # Shows the Login screen as the first screen
def show_frame(self, page_name): # Shows a frame for the given page name
frame = self.frames[page_name] # Makes frame = self.frames(page_name)
frame.tkraise() # Raises the frame
</code></pre>
<p>Class #2</p>
<pre><code>class Login(tk.Frame): # Class - My Login screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
background_image = tk.PhotoImage(file="9a4a50632b464e426a71c800f80ad778.png")
background_label = tk.Label(self, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
background_label.image = background_image
def login_button(): # Defines login_button
controller.show_frame("MainMenu"), return_to_main_menu2()
your_username = entUsername.get()
username_label.configure(text=your_username)
# Shows MainMenu and uses return_to_main_menu2 function
def login_button2(event): # Defines login_button2 and marks it as an event
controller.show_frame("MainMenu"), return_to_main_menu2()
your_username = entUsername.get()
username_label.configure(text=your_username)
# Shows MainMenu and uses return_to_main_menu2 function
lbl1 = tk.Label(self, text=" ", fg="white", bg="black") # Bg="#2699C3" is another form of blue
# These labels are used to create blank spaces to centre my program
lbl1.pack() # Packs the label wherever there's space
lbl2 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl2.pack() # Packs the label wherever there's space
lbl3 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl3.pack() # Packs the label wherever there's space
lbl4 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl4.pack() # Packs the label wherever there's space
lbl5 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl5.pack() # Packs the label wherever there's space
lbl6 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl6.pack() # Packs the label wherever there's space
lbl7 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl7.pack() # Packs the label wherever there's space
lbl8 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl8.pack() # Packs the label wherever there's space
lblUsername = tk.Label(self, text="Username:", fg="white", bg="black") # Makes the Label display Username
lblUsername.place(anchor="center") # Centers the label
global entUsername # Changes entUsername to a global variable (global variables can be used in all classes)
entUsername = tk.Entry(self, justify="center") # Centers the entry box
lblUsername.pack() # Packs it wherever there's space
lblUsername.config(font=("Courier", 32)) # Changes the font/size
entUsername.pack() # Packs it wherever there's space
entUsername.config(font=("Courier", 32)) # Changes the font/size
lblPassword = tk.Label(self, text="Password:", fg="white", bg="black") # Makes the Label display Password
lblPassword.place(anchor="center") # Centers the label
global entPassword # Changes entPassword to a global variable
entPassword = tk.Entry(self, justify="center") # Centers the entry box
lblPassword.pack() # Packs it wherever there's space
lblPassword.config(font=("Courier", 32)) # Changes the font/size
entPassword.pack() # Packs it wherever there's space
entPassword.config(font=("Courier", 32)) # Changes the font/size
entUsername.focus_set()
entPassword.bind("<Return>", login_button2)
btn = tk.Button(self, text="Login", fg="black", bg="lawn green", width=6, height=1, # Changes colour
command=login_button) # Uses login_button function
btn.pack(pady=10) # How many pixels to pad widget, vertically
</code></pre>
<p>Class #3</p>
<pre><code>class MainMenu(tk.Frame): # Class - My Main Menu screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label = tk.Label(self, text="Memory Mania", font=controller.title_font, bg="#2699C3")
# Puts Memory Mania as a large Label
label.pack(side="top", fill="x", pady=10) # Packs the label at the top of the program
global username_label # Makes username_label a global variable
label1 = tk.Label(self, text="Logged in as:", bg="#2699C3") # Changes colour
label1.pack() # Packs the label wherever there's space
username_label = tk.Label(self, text=" ", bg="#2699C3") # Users username is posted here
username_label.pack() # Packs the label wherever there's space
def get_answer2(event):
if entry_characters.get() == word: # Tells program that if the entry of characters = the correct/incorrect
controller.show_frame("CorrectScreen") # Show correct screen (if answer is correct)
else:
controller.show_frame("IncorrectScreen") # Show incorrect screen (if answer is wrong)
def start_game():
pygame.mixer.Sound.play(button_click).set_volume(0.6)
controller.show_frame("Difficulty")
entry_characters.bind("<Return>", get_answer2) # Makes you able to click enter
button1 = tk.Button(self, text="Play", bg="#76EE00", fg="black", height=4, width=20, # Changes colour/size
command=start_game)
# Makes this button take me to the Difficulty screen and uses the 'return_to_main_menu' function
button2 = tk.Button(self, text="Tutorial", bg="yellow", fg="black", height=4, width=20, # Changes colour/size
command=lambda: [controller.show_frame("Tutorial"), return_to_main_menu()])
# Makes this button take me to the Tutorial screen and uses the 'return_to_main_menu function'
button3 = tk.Button(self, text="Settings", bg="#00EEEE", fg="black", height=4, width=20, # Changes colour/size
command=lambda: [controller.show_frame("Settings"), return_to_main_menu()])
# Makes this button take me to the Settings screen and uses the 'return_to_main_menu function'
button4 = tk.Button(self, text="Logout", bg="orange", fg="black", height=4, width=20, # Changes colour/size
command=lambda: [controller.show_frame("Login"), logout_logout()])
# Makes this button take me to the Login screen and uses the 'logout_logout' function
button5 = tk.Button(self, text="Quit", bg="red", fg="black", height=4, width=20, cursor="pirate",
# Changes colour/size/cursor
command=sys.exit)
# Makes this button Quit the program
button1.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button1.config(font=("System", 10)) # Changes font/size
button2.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button2.config(font=("System", 10)) # Changes font/size
button3.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button3.config(font=("System", 10)) # Changes font/size
button4.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button4.config(font=("System", 10)) # Changes font/size
button5.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button5.config(font=("System", 10)) # Changes font/size
</code></pre>
<p>Class #4</p>
<pre><code>class Tutorial(tk.Frame): # Class - My Tutorial screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
# These labels are used to create blank spaces to centre my program
lbl1 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl1.pack() # Packs it wherever there's space
lbl2 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl2.pack() # Packs it wherever there's space
lbl3 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl3.pack() # Packs it wherever there's space
label = tk.Label(self, text="Tutorial (1)", font=controller.title_font, bg="#2699C3") # Changes font/colour
label1 = tk.Label(self, text="Once you click the Play button you will be brought to the Difficulty screen",
bg="#2699C3") # Changes text/colour
label2 = tk.Label(self, text="Once you're in the Difficulty screen, you can select 1 of 4 Difficulties",
bg="#2699C3") # Changes text/colour
label3 = tk.Label(self, text="Easy, Medium, Hard, Insane, all which have 5 levels",
bg="#2699C3") # Changes text/colour
label.pack(side="top", fill="x", pady=10)
# How many pixels to pad widget, vertically/horizontally and at the top
label1.pack(side="top", fill="x", pady=10)
# How many pixels to pad widget, vertically/horizontally
label2.pack(side="top", fill="x", pady=10)
# How many pixels to pad widget, vertically/horizontally
label3.pack(side="top", fill="x", pady=10)
# How many pixels to pad widget, vertically/horizontally
label1.config(font=("System", 14)) # Changes font/size
label2.config(font=("System", 14)) # Changes font/size
label3.config(font=("System", 14)) # Changes font/size
button1 = tk.Button(self, text="Next Page", bg="yellow", fg="black", height=4, width=20,
# Changes colour/size of button
command=lambda: [controller.show_frame("Tutorial2"), return_to_main_menu()])
# Makes this button take me to Tutorial2 screen and uses the 'return_to_main_menu' function
button2 = tk.Button(self, text="Return to Main Menu", bg="yellow", fg="black", height=4, width=20,
# Changes colour/size of button
command=lambda: [controller.show_frame("MainMenu"), return_to_main_menu()])
# Makes this button take me to the Main Menu and uses the 'return_to_main_menu' function
label4 = tk.Label(self, text="Note: Lowercase and Capital letters matter!", bg="#2699C3") # Changes colour
label4.config(font=("System", 10)) # Changes font/size
label4.pack(side="bottom", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontal
button1.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button1.config(font=("System", 10)) # Changes font/size
button2.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button2.config(font=("System", 10)) # Changes font/size
</code></pre>
<p>Class #6</p>
<pre><code>class Difficulty(tk.Frame): # Class - My Difficulty screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label = tk.Label(self, text="Difficulty", font=controller.title_font, bg="#2699C3") # Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
def wait_fifteen_seconds(): # Defines "wait_fifteen_seconds"
label_check.configure(text="Level 1") # Configures the label to the level specified
global seconds_to_wait # Changes "seconds_to_wait" to a global variable
# Changes "seconds_to_wait" to a global variable meaning you can use it in all classes
seconds_to_wait = 15 # Makes the screen change in 15 seconds
entry_characters.delete(0, tk.END) # Gets rid of the past entry's
x = (random_char(6)) # Generates 6 random characters
global word # Changes "word" to a global variable
word = x # Makes word=x
label2_easy.configure(text=word) # Configures the label to show the "word" variable
controller.show_frame("EasyDifficulty"), return_to_main_menu() # Displays the "EasyDifficulty screen"
entry_characters.pack_forget() # Makes you unable to enter the characters before the screen appears
app.update() # Updates the program
time.sleep(seconds_to_wait) # Makes the program wait for however many seconds depending on difficulty
controller.show_frame("EnterCharacterScreen") # Displays the "EnterCharacterScreen"
entry_characters.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_submit.pack(fill=tk.X, padx=80, pady=80, side=tk.BOTTOM)
# How many pixels to pad widget, vertically/horizontally
entry_characters.focus_set() # Automatically clicks the entry box
def wait_ten_seconds(): # Defines "wait_ten_seconds"
label_check.configure(text="Level 1 ") # Configures the label to the level specified
global seconds_to_wait # Changes "seconds_to_wait" to a global variable
# Changes "seconds_to_wait" to a global variable meaning you can use it in all classes
seconds_to_wait = 10 # Makes the screen change in 10 seconds
entry_characters.delete(0, tk.END) # Gets rid of the past entry's
x = (random_char(6)) # Generates 6 random characters
global word # Changes "word" to a global variable meaning you can use it in all classes
word = x # Makes word=x
label2_medium.configure(text=word) # Configures the label to show the "word" variable
controller.show_frame("MediumDifficulty"), return_to_main_menu() # Displays the "MediumDifficulty screen"
entry_characters.pack_forget() # Makes you unable to enter the characters before the screen appears
app.update() # Updates the program
time.sleep(seconds_to_wait) # Makes the program wait for however many seconds depending on difficulty
controller.show_frame("EnterCharacterScreen") # Displays the "EnterCharacterScreen"
entry_characters.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_submit.pack(fill=tk.X, padx=80, pady=80, side=tk.BOTTOM)
# How many pixels to pad widget, vertically/horizontally
entry_characters.focus_set() # Automatically clicks the entry box
def wait_five_seconds(): # Defines "wait_five_seconds"
label_check.configure(text="Level 1 ") # Configures the label to the level specified
global seconds_to_wait # Changes "seconds_to_wait" to a global variable
# Changes "seconds_to_wait" to a global variable meaning you can use it in all classes
seconds_to_wait = 5 # Makes the screen change in 5 seconds
entry_characters.delete(0, tk.END) # Gets rid of the past entry's
x = (random_char(6)) # Generates 6 random characters
global word # Changes "word" to a global variable meaning you can use it in all classes
word = x # Makes word=x
label2_hard.configure(text=word) # Configures the label to show the "word" variable
controller.show_frame("HardDifficulty"), return_to_main_menu() # Displays the "HardDifficulty screen"
entry_characters.pack_forget() # Makes you unable to enter the characters before the screen appears
app.update() # Updates the program
time.sleep(seconds_to_wait) # Makes the program wait for however many seconds depending on difficulty
controller.show_frame("EnterCharacterScreen") # Displays the "EnterCharacterScreen"
entry_characters.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_submit.pack(fill=tk.X, padx=80, pady=80, side=tk.BOTTOM)
# How many pixels to pad widget, vertically/horizontally
entry_characters.focus_set() # Automatically clicks the entry box
def wait_two_seconds(): # Defines "wait_two_seconds"
label_check.configure(text="Level 1") # Configures the label to the level specified
global seconds_to_wait # Changes "seconds_to_wait" to a global variable
# Changes "seconds_to_wait" to a global variable meaning you can use it in all classes
seconds_to_wait = 2 # Makes the screen change in 2 seconds
entry_characters.delete(0, tk.END) # Gets rid of the past entry's
x = (random_char(6)) # Generates 6 random characters
global word # Changes "word" to a global variable meaning you can use it in all classes
word = x # Makes word=x
label2_insane.configure(text=word) # Configures the label to show the "word" variable
controller.show_frame("InsaneDifficulty"), return_to_main_menu() # Displays the "InsaneDifficulty screen"
entry_characters.pack_forget() # Makes you unable to enter the characters before the screen appears
app.update() # Updates the program
time.sleep(seconds_to_wait) # Makes the program wait for however many seconds depending on difficulty
controller.show_frame("EnterCharacterScreen") # Displays the "EnterCharacterScreen"
entry_characters.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_submit.pack(fill=tk.X, padx=80, pady=80, side=tk.BOTTOM)
# How many pixels to pad widget, vertically/horizontally
entry_characters.focus_set() # Automatically clicks the entry box
button = tk.Button(self, text="Easy", bg="yellow", fg="black", height=4, width=20,
command=wait_fifteen_seconds)
# Makes button wait fifteen seconds/changes text/colour/size
button1 = tk.Button(self, text="Medium", bg="#E99B15", fg="black", height=4, width=20, command=wait_ten_seconds)
# Makes button wait ten seconds/changes text/colour/size
button2 = tk.Button(self, text="Hard", bg="#C04141", fg="black", height=4, width=20, command=wait_five_seconds)
# Makes button wait five seconds/changes text/colour/size
button3 = tk.Button(self, text="Insane", bg="#FC0000", fg="black", height=4, width=20, command=wait_two_seconds)
# Makes button wait two seconds/changes text/colour/size
button4 = tk.Button(self, text="Back", bg="green", fg="black", height=4, width=20,
command=lambda: [controller.show_frame("MainMenu"), return_to_main_menu()])
# Makes this button take me to the MainMenu and uses the 'return_to_main_menu' function
button.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button.config(font=("System", 10)) # Changes font/size
button1.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button1.config(font=("System", 10)) # Changes font/size
button2.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button2.config(font=("System", 10)) # Changes font/size
button3.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button3.config(font=("System", 10)) # Changes font/size
button4.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button4.config(font=("System", 10)) # Changes font/size
</code></pre>
<p>Class #7</p>
<pre><code>class Settings(tk.Frame): # Class - My Settings screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
lbl1 = tk.Label(self, text=" ", fg="white", bg="#2699C3")
lbl1.pack() # Packs the label wherever there's space
lbl2 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl2.pack() # Packs the label wherever there's space
lbl3 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl3.pack() # Packs the label wherever there's space
label = tk.Label(self, text="Settings", font=controller.title_font, bg="#2699C3") # Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
button1 = tk.Button(self, text="Pause Music", bg="red", fg="white", height=4, width=20, # Changes colour/size
command=pygame.mixer.music.pause)
# Pauses the current song
button2 = tk.Button(self, text="Resume Music", bg="green", fg="white", height=4, width=20, # Colour/size
command=pygame.mixer.music.unpause)
# Resumes the current song
button3 = tk.Button(self, text="Music", bg="yellow", fg="black",
height=4, width=20, # Colour/size
command=lambda: [controller.show_frame("Music"), return_to_main_menu()])
# Makes this button take me to the Music screen and play the 'return_to_main_menu' function
button = tk.Button(self, text="Back", bg="#00EEEE", fg="black", height=4, width=20, # Changes colour/size
command=lambda: [controller.show_frame("MainMenu"), return_to_main_menu()])
# Makes this button take me to the Main Menu and play the 'return_to_main_menu function
label1 = tk.Label(self, text="Note: Music takes a few seconds to start up!", bg="#2699C3") # Changes colour
label1.config(font=("System", 10)) # Changes font/size
label1.pack(side="bottom", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
button1.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button1.config(font=("System", 10)) # Changes font/size
button2.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button2.config(font=("System", 10)) # Changes font/size
button3.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button3.config(font=("System", 10)) # Changes font/size
button.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button.config(font=("System", 10)) # Changes font/size
</code></pre>
<p>Class #8</p>
<pre><code>class Music(tk.Frame): # Class - My Music screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label = tk.Label(self, text="Music", font=controller.title_font, bg="#2699C3") # Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
button1 = tk.Button(self, text="Soundtrack 1", bg="#0000FF", fg="white", height=4, width=20,
# Changes colour/size
command=play_music1)
# plays the function 'play_music1'
button2 = tk.Button(self, text="Soundtrack 2", bg="#EE3B3B", fg="white", height=4, width=20,
# Changes colour/size
command=play_music2)
# plays the function 'play_music2'
button3 = tk.Button(self, text="Soundtrack 3", bg="#7AC5CD", fg="white", height=4, width=20,
# Changes colour/size
command=play_music3)
# plays the function 'play_music3'
button4 = tk.Button(self, text="Soundtrack 4", bg="#00C957", fg="white", height=4, width=20,
# Changes colour/size
command=play_music4)
# plays the function 'play_music4'
button5 = tk.Button(self, text="Soundtrack 5", bg="#FFB90F", fg="white", height=4, width=20,
# Changes colour/size
command=play_music5)
# plays the function 'play_music5'
button = tk.Button(self, text="Return", bg="#00EEEE", fg="black", height=4, width=20, # Changes colour/size
command=lambda: [controller.show_frame("Settings"), return_to_main_menu()])
button1.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button1.config(font=("System", 10)) # Changes font/size
button2.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button2.config(font=("System", 10)) # Changes font/size
button3.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button3.config(font=("System", 10)) # Changes font/size
button4.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button4.config(font=("System", 10)) # Changes font/size
button5.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button5.config(font=("System", 10)) # Changes font/size
button.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button.config(font=("System", 10)) # Changes font/size
</code></pre>
<p>Class #9</p>
<pre><code>class EasyDifficulty(tk.Frame): # Class - My EasyDifficulty screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label_level = tk.Label(self, text="Level 1", bg="#2699C3") # Changes colour
label_level.pack() # Packs the label wherever there's space
label = tk.Label(self, text="Remember these characters", font=controller.title_font, bg="#2699C3")
# Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
global label2_easy # Global variable
label2_easy = tk.Label(self, height=4, width=15, text=word) # Changes size, text = word
label2_easy.config(font=("Courier", 64)) # Changes font/size
label2_easy.pack() # Packs the label wherever there's space
</code></pre>
<p>Class #10</p>
<pre><code>class MediumDifficulty(tk.Frame): # Class - My MediumDifficulty screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label_level = tk.Label(self, text="Level 1", bg="#2699C3") # Changes colour
label_level.pack() # Packs the label wherever there's space
label = tk.Label(self, text="Remember these characters", font=controller.title_font, bg="#2699C3")
# Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
global label2_medium # Global variable
label2_medium = tk.Label(self, height=4, width=15, text=word) # Changes size, text = word
label2_medium.config(font=("Courier", 64)) # Changes font/size
label2_medium.pack() # Packs the label wherever there's space
</code></pre>
<p>Class #11</p>
<pre><code>class HardDifficulty(tk.Frame): # Class - My HardDifficulty screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label_level = tk.Label(self, text="Level 1", bg="#2699C3") # Changes colour
label_level.pack() # Packs the label wherever there's space
label = tk.Label(self, text="Remember these characters", font=controller.title_font, bg="#2699C3")
# Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
global label2_hard # Global variable
label2_hard = tk.Label(self, height=4, width=15, text=word) # Changes size, text = word
label2_hard.config(font=("Courier", 64)) # Changes font/size
label2_hard.pack() # Packs the label wherever there's space
</code></pre>
<p>Class #12</p>
<pre><code>class InsaneDifficulty(tk.Frame): # Class - My InsaneDifficulty screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label_level = tk.Label(self, text="Level 1", bg="#2699C3") # Changes colour
label_level.pack() # Packs the label wherever there's space
label = tk.Label(self, text="Remember these characters", font=controller.title_font, bg="#2699C3")
# Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
global label2_insane # Global variable
label2_insane = tk.Label(self, height=4, width=15, text=word) # Changes size, text = word
label2_insane.config(font=("Courier", 64)) # Changes font/size
label2_insane.pack() # Packs the label wherever there's space
</code></pre>
<p>Class #13</p>
<pre><code>class EnterCharacterScreen(tk.Frame): # Class - My EnterCharacterScreen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
# These labels are used to create blank spaces to centre my program
lbl1 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl1.pack() # Packs label wherever there's space
lbl2 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl2.pack() # Packs label wherever there's space
lbl3 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl3.pack() # Packs label wherever there's space
lbl4 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl4.pack() # Packs label wherever there's space
lbl5 = tk.Label(self, text=" ", fg="white", bg="#2699C3") # Changes colour of label
lbl5.pack() # Packs label wherever there's space
label = tk.Label(self, text="What were your characters?", font=controller.title_font, bg="#2699C3")
# Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
def get_answer(): # Defines get_answer
if entry_characters.get() == word: # Tells program that if the entry of characters = the correct/incorrect
controller.show_frame("CorrectScreen") # Show correct screen (if answer is correct)
else:
controller.show_frame("IncorrectScreen") # Show incorrect screen (if answer is wrong)
def get_answer2(event): # Defines get_answer (event is needed so users can click enter when submitting)
if entry_characters.get() == word: # Tells program that if the entry of characters = the correct/incorrect
controller.show_frame("CorrectScreen") # Show correct screen (if answer is correct)
else:
controller.show_frame("IncorrectScreen") # Show incorrect screen (if answer is wrong)
global entry_characters # Global variable
entry_characters = tk.Entry(self, justify="center") # Centers the entry
entry_characters.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
entry_characters.config(font=("Courier", 96)) # Changes the font/size
entry_characters.bind("<Return>", get_answer2) # Makes you able to click enter
global button_submit # Global variable
button_submit = tk.Button(self, text="Submit", command=get_answer, height=4, width=20) # Changes size of button
button_submit.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_submit.config(font=("System", 10)) # Changes the font/size
</code></pre>
<p>Class #14</p>
<pre><code>class CorrectScreen(tk.Frame): # Class - My CorrectScreen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="green") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
# These labels are used to create blank spaces to centre my program
lbl1 = tk.Label(self, text=" ", fg="white", bg="green") # Changes colour of label
lbl1.pack() # Packs label wherever there's space
lbl2 = tk.Label(self, text=" ", fg="white", bg="green") # Changes colour of label
lbl2.pack() # Packs label wherever there's space
lbl3 = tk.Label(self, text=" ", fg="white", bg="green") # Changes colour of label
lbl3.pack() # Packs label wherever there's space
lbl4 = tk.Label(self, text=" ", fg="white", bg="green") # Changes colour of label
lbl4.pack() # Packs label wherever there's space
label = tk.Label(self, text="CORRECT!!:)", font=controller.title_font, bg="green") # Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
def next_level_two(): # Defines next_level_two
label_check.configure(text="Level 2") # Shows Level 2 at the top
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
button_next_screen.configure(command=next_level_three) # Shows Level 3 screen
button_lose.configure(command=difficulty_change) # Shows Difficulty screen
button_tutorial_lose.configure(command=tutorial_show) # Shows Tutorial screen
button_main_lose.configure(command=main_menu) # Shows Main Menu
def next_level_three(): # Defines next_level_three
label_check.configure(text="Level 3") # Shows Level 3 at the top
button_next_screen.configure(command=next_level_four) # Shows Level 4 screen
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
def next_level_four(): # Defines next_level_four
label_check.configure(text="Level 4") # Shows Level 4 at the top
button_next_screen.configure(command=next_level_five) # Shows Level 5 screen
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
def next_level_five(): # Defines next_level_five
entry_characters.bind("<Return>", win_game) # Makes you able to click enter
label_check.configure(text="Level 5") # Shows Level 5 at the top
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
def get_answer_last_screen(): # Defines get_answer_last_screen
if entry_characters.get() == word:
# Tells program that if the entry of characters = the correct/incorrect
controller.show_frame("WinGameScreen") # if answer is correct, WinGameScreen is shown
else:
controller.show_frame("IncorrectScreen") # if answer is incorrect, IncorrectScreen is shown
button_submit.configure(command=get_answer_last_screen)
# Upon pressing button will change screen to either WinGameScreen or IncorrectScreen
global button_next_screen # Global variable
button_next_screen = tk.Button(self, text="Progress to Next Level", bg="white", fg="black", height=4, width=20,
# Changes colour/size
command=next_level_two)
# Uses the 'next_level_two' function
def tutorial_show(): # Defines tutorial_show
button_next_screen.configure(command=next_level_two) # Uses the 'next_level_two' function
controller.show_frame("Tutorial") # Shows Tutorial screen
def main_menu(): # Defines main_menu
entUsername.focus_set() # Makes it so the Username entry box is targeted
button_next_screen.configure(command=next_level_two) # Uses the 'next_level_two' function
controller.show_frame("MainMenu") # Shows MainMenu
def win_game(event): # Activated when user is on level 5
controller.show_frame("WinGameScreen") # Shows the WinGameScreen
def difficulty_change(): # Defines difficulty_change
entUsername.focus_set() # Makes it so the Username entry box is targeted
button_next_screen.configure(command=next_level_two) # Uses the 'next_level_two' function
controller.show_frame("Difficulty") # Shows Difficulty screen
button2 = tk.Button(self, text="Try a different difficulty", bg="white", fg="black", height=4, width=20,
# Changes colour/size
command=difficulty_change)
# Shows Difficulty screen and uses the 'difficulty_change' function
button3 = tk.Button(self, text="Return to Main Menu", bg="white", fg="black", height=4, width=20,
# Changes colour/size
command=main_menu)
# Shows Main Menu and uses the 'main_menu' function
button_next_screen.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_next_screen.config(font=("System", 10)) # Changes font/size
button2.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button2.config(font=("System", 10)) # Changes font/size
button3.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button3.config(font=("System", 10)) # Changes font/size
</code></pre>
<p>Class #15</p>
<pre><code>class IncorrectScreen(tk.Frame): # Class - Incorrect Screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="red") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
# These labels are used to create blank spaces to centre my program
lbl1 = tk.Label(self, text=" ", fg="white", bg="red") # Changes colour of label
lbl1.pack() # Packs label wherever there's space
lbl2 = tk.Label(self, text=" ", fg="white", bg="red") # Changes colour of label
lbl2.pack() # Packs label wherever there's space
lbl3 = tk.Label(self, text=" ", fg="white", bg="red") # Changes colour of label
lbl3.pack() # Packs label wherever there's space
lbl4 = tk.Label(self, text=" ", fg="white", bg="red") # Changes colour of label
lbl4.pack() # Packs label wherever there's space
label = tk.Label(self, text="INCORRECT!!:C", font=controller.title_font, bg="red") # Changes font/colour
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
def retry_lose(): # Defines retry_lose
pygame.mixer.Sound.play(button_click).set_volume(0.6) # Sets the volume of 'button_click' function
controller.show_frame("Difficulty") # Shows Difficulty screen
entUsername.focus_set() # Makes it so the Username entry box is targeted
global button_lose # Global variable
button_lose = tk.Button(self, text="Retry on a different difficulty", bg="white", fg="black", height=4,
# Changes size/colour
width=20, command=retry_lose)
# Shows Difficulty screen and uses the 'retry_lose' function
def tutorial_lose(): # Defines retry_lose
pygame.mixer.Sound.play(button_click).set_volume(0.6) # Sets the volume of 'button_click' function
controller.show_frame("Tutorial") # Shows Tutorial screen
entUsername.focus_set() # Makes it so the Username entry box is targeted
global button_tutorial_lose # Global variable
button_tutorial_lose = tk.Button(self, text="Review How to Play", bg="white", fg="black", height=4, width=20,
# Changes size/colour
command=tutorial_lose)
# Uses the Tutorial screen and uses the 'tutorial_lose' function
global button_main_lose # Global variable
def main_lose(): # Defines main_lose
pygame.mixer.Sound.play(button_click).set_volume(0.6) # Sets the volume of 'button_click' function
controller.show_frame("MainMenu") # Shows MainMenu
entUsername.focus_set() # Makes it so the Username entry box is targeted
button_main_lose = tk.Button(self, text="Return to Main Menu", bg="white", fg="black", height=4, width=20,
# Changes size/colour
command=main_lose)
# Shows MainMenu and uses the 'main_lose' function
button_lose.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_lose.config(font=("System", 10)) # Changes font/size
button_tutorial_lose.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_tutorial_lose.config(font=("System", 10)) # Changes font/size
button_main_lose.pack(fill=tk.X, padx=10, pady=10) # How many pixels to pad widget, vertically/horizontally
button_main_lose.config(font=("System", 10)) # Changes font/size
</code></pre>
<p>Class #16</p>
<pre><code>class Level2(tk.Frame): # Class - Level2 Screen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
label = tk.Label(self, text="Remember these characters", font=controller.title_font, bg="#2699C3")
# Changes font/colour
global label_check # Global variable
label_check = tk.Label(self, text="Level 1", bg="#2699C3") # Changes colour of label
label_check.pack() # Packs the label wherever there's space
label.pack(side="top", fill="x", pady=10) # How many pixels to pad widget, vertically/horizontally
global label2_level2 # Global variable
label2_level2 = tk.Label(self, height=4, width=15, text=word) # Changes size, text=word
label2_level2.config(font=("Courier", 64)) # Changes font/size
label2_level2.pack() # Packs the label wherever there's space
</code></pre>
<p>Class #17</p>
<pre><code>class WinGameScreen(tk.Frame): # Class - WinGameScreen
def __init__(self, parent, controller): # Defines the window
tk.Frame.__init__(self, parent, bg="#2699C3") # Sets the background as that colour
self.controller = controller # Makes self.controller = controller
# These labels are used to create blank spaces to centre my program
background_image2 = tk.PhotoImage(file="videogame-well-done-4k-a-videogame-screen-with-the-text-well-done-8-bit-retro-style-4k_hv0skuloke_thumbnail-full05.png")
background_label2 = tk.Label(self, image=background_image2)
background_label2.place(x=0, y=0, relwidth=1, relheight=1)
background_label2.image = background_image2
lbl1 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl1.pack() # Packs the label wherever there's space
lbl2 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl2.pack() # Packs the label wherever there's space
lbl3 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl3.pack() # Packs the label wherever there's space
lbl4 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl4.pack() # Packs the label wherever there's space
lbl5 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl5.pack() # Packs the label wherever there's space
lbl6 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl6.pack() # Packs the label wherever there's space
lbl7 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl7.pack() # Packs the label wherever there's space
lbl8 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl8.pack() # Packs the label wherever there's space
lbl9 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl9.pack() # Packs the label wherever there's space
lbl10 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl10.pack() # Packs the label wherever there's space
lbl11 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl11.pack() # Packs the label wherever there's space
lbl12 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl12.pack() # Packs the label wherever there's space
lbl13 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl13.pack() # Packs the label wherever there's space
lbl14 = tk.Label(self, text=" ", fg="white", bg="black") # Changes colour of label
lbl14.pack() # Packs the label wherever there's space
def get_answer_last_screen(): # Defines get_answer_last_screen
if entry_characters.get() == word:
# Tells program that if the entry of characters = the correct/incorrect
controller.show_frame("WinGameScreen") # if answer is correct, WinGameScreen is shown
else:
controller.show_frame("IncorrectScreen") # if answer is incorrect, IncorrectScreen is shown
def get_answer(): # Defines get_answer
if entry_characters.get() == word: # Tells program that if the entry of characters = the correct/incorrect
controller.show_frame("CorrectScreen") # Show correct screen (if answer is correct)
else:
controller.show_frame("IncorrectScreen") # Show incorrect screen (if answer is wrong)
def get_answer2(event): # Defines get_answer
if entry_characters.get() == word: # Tells program that if the entry of characters = the correct/incorrect
controller.show_frame("CorrectScreen") # Show correct screen (if answer is correct)
else:
controller.show_frame("IncorrectScreen") # Show incorrect screen (if answer is wrong)
def tutorial_show(): # Defines tutorial_show
button_next_screen.configure(command=next_level_two) # Uses the 'next_level_two' function
controller.show_frame("Tutorial") # Shows Tutorial screen
def main_menu(): # Defines main_menu
button_next_screen.configure(command=next_level_two) # Uses the 'next_level_two' function
controller.show_frame("MainMenu") # Shows MainMenu
def difficulty_change(): # Defines difficulty_change
button_next_screen.configure(command=next_level_two) # Uses the 'next_level_two' function
controller.show_frame("Difficulty") # Shows Difficulty screen
def next_level_two(): # Defines next_level_two
label_check.configure(text="Level 2") # Shows Level 2 at the top
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
button_next_screen.configure(command=next_level_three) # Shows Level 3 screen
button_lose.configure(command=difficulty_change) # Shows Difficulty screen
button_tutorial_lose.configure(command=tutorial_show) # Shows Tutorial screen
button_main_lose.configure(command=main_menu) # Shows Main Menu
def next_level_three(): # Defines next_level_three
label_check.configure(text="Level 3") # Shows Level 3 at the top
button_next_screen.configure(command=next_level_four) # Shows Level 4 screen
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
def next_level_four(): # Defines next_level_four
label_check.configure(text="Level 4") # Shows Level 4 at the top
button_next_screen.configure(command=next_level_five) # Shows Level 5 screen
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
def next_level_five(): # Defines next_level_five
label_check.configure(text="Level 5")
button_next_screen.configure(command=get_answer_last_screen) # Shows Level 5 at the top
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
x = (random_char(6)) # Displays 6 random characters
global word # Global variable
word = x # Word = x
label2_level2.configure(text=word) # Text=word
entry_characters.delete(0, tk.END) # Makes it so last entry's are deleted
controller.show_frame("Level2") # Shows Level 2 screen
app.update() # Updates program
time.sleep(float(seconds_to_wait)) # Time program waits before changing to next screen
controller.show_frame("EnterCharacterScreen") # Shows EnterCharacterScreen
def game_finished(): # Defines game_finished
controller.show_frame("MainMenu"), return_to_main_menu()
# Shows MainMenu and uses the 'return_to_main_menu' function
label_check.configure(text="Level 1") # Shows Level 1 at the top of the screen
label2_easy.configure(text=word) # Configures the label so text=word for the corresponding difficulty
label2_medium.configure(text=word) # Configures the label so text=word for the corresponding difficulty
label2_hard.configure(text=word) # Configures the label so text=word for the corresponding difficulty
label2_insane.configure(text=word) # Configures the label so text=word for the corresponding difficulty
button_submit.configure(command=get_answer) # Uses the 'get_answer' function
button_next_screen.configure(command=next_level_two) # Uses the 'next_level_two function
button1 = tk.Button(self, text="Return to Main Menu", bg="yellow", fg="black", height=2, width=20,
# Changes size/colour
command=game_finished)
# Shows MainMenu and uses the 'game_finished' function
button1.pack(pady=10) # How many pixels to pad widget, vertically/horizontally
button1.config(font=("System", 10)) # Changes font/size
if __name__ == "__main__": # If _name="main":
app = SampleApp() # Makes app = SampleApp
app.mainloop() # Loops the program so it can stay open
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T11:10:36.163",
"Id": "387617",
"Score": "0",
"body": "There also a class called Tutorial2, which is the second page of it, but due to the limit of characters i was unable to add it in!"
},
{
"ContentLicense": "CC BY-SA 4.0",... | [
{
"body": "<h2>Most of your inline comments are useless</h2>\n\n<p>I see lots of comments like this:</p>\n\n<pre><code>def login_button(): # Defines login_button\n</code></pre>\n\n<p>That comment adds no information. It just adds visual \"noise\". I recommend removing all comments that simply state what the co... | {
"AcceptedAnswerId": "201288",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T11:09:40.600",
"Id": "201274",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tkinter",
"pygame"
],
"Title": "Memory Game using Tkinter/Pygame"
} | 201274 |
<p>I'm currently learning python / network programming altogether and I coded this simple python reverse shell; I would like to hear any remarks from you regarding code structure, any common beginner mistake, actually pretty much anything that feels wrong with my code.</p>
<p>The code is pretty straightforward, the client sends a command to the server, then listens for the command output; the server listens for the command, executes it and sends the command output.</p>
<p><strong>client.py :</strong> </p>
<pre><code>#!/usr/bin/env python3
import networking
import prompt_handler
def interpreter():
while True:
prompt = prompt_handler.pull_prompt(sockt)
cmd = input(prompt)
sockt.sendto(cmd.encode('utf-8'), server)
output = networking.receive_data(sockt)
print(output)
if cmd == "quit":
break
server = ('127.0.0.1', 8001)
sockt = networking.socket_init('127.0.0.1', 9001)
sockt.sendto('client hello'.encode('utf-8'), server)
interpreter()
</code></pre>
<p><strong>server.py :</strong></p>
<pre><code>#!/usr/bin/env python3
import os
import platform
import networking
# separated sends for cwd and user_string to be able to color them client side
def get_sys_info():
user_string = 'someone@' + str(platform.dist()[0]).lower()
sockt.sendto(user_string.encode('utf-8'), client)
user_cwd = os.getcwd()
sockt.sendto(user_cwd.encode('utf-8'), client)
return
def shell():
while True:
try:
get_sys_info()
cmd = networking.receive_data(sockt)
if cmd.strip() == 'quit':
sockt.sendto('Closing session...'.encode('utf-8'), client)
sockt.close()
break
else:
proc = os.popen(cmd)
output = ''.join([i for i in proc.readlines()])
sockt.sendto(output.encode('utf-8'), client)
except Exception as e:
sockt.sendto(repr(e).encode('utf-8'), client)
pass
sockt = networking.socket_init('127.0.0.1', 8001)
client = networking.receive_rhostinfo(sockt)
shell()
</code></pre>
<p><strong>networking.py :</strong></p>
<pre><code>import socket
def socket_init(ip_addr, port):
sockt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sockt.bind((ip_addr, port))
return sockt
# to be able to get the data directly - less clutter in main code
def receive_data(sockt):
data, rhost_info = sockt.recvfrom(1024)
return data.decode('utf-8')
# to be able to get the remote host info directly - less clutter in main code
def receive_rhostinfo(sockt):
data, rhost_info = sockt.recvfrom(1024)
return rhost_info
</code></pre>
<p><strong>promp_handler.py</strong></p>
<pre><code>import networking
def pull_sys_info(sockt):
user_str = networking.receive_data(sockt)
cwd = networking.receive_data(sockt)
return user_str, cwd
# i was craving for some color
def pull_prompt(sockt):
user_str, cwd = pull_sys_info(sockt)
user_str = "\u001b[31m" + user_str + "\u001b[0m:"
cwd = "\u001b[34m" + cwd + "\u001b[0m$"
return user_str + cwd
</code></pre>
<p>If needs be you can find the code on <a href="https://github.com/NaNHEX/otherworld" rel="noreferrer">github</a>.</p>
| [] | [
{
"body": "<h1>General style</h1>\n\n<p>Your general code style is good. The methods are named feasibly and you stick to PEP 8.</p>\n\n<h1>Separate client and server shutdown</h1>\n\n<p>Currently your <code>\"quit\"</code> command shuts down both the server and client.\nSince it is a <em>command</em> entered in... | {
"AcceptedAnswerId": "201301",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T11:24:51.940",
"Id": "201276",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"socket",
"udp"
],
"Title": "UDP Reverse Shell"
} | 201276 |
<p>Given an array of integers, find the longest consecutive sequence, where a sequence is defined as being either (strictly) ascending, (strictly) descending, or all-equal.</p>
<p>836926 then has the longest sequence 369, which happens to be ascending. 241455556 has the longest sequence 5555, which happens to be all equal.</p>
<p>Please comment on the algorithm (correct? complexity?) and how it can be improved.</p>
<pre><code>#include <iostream>
#include <vector>
int sign(int someInt)
{
if (someInt > 0) { return 1; };
if (someInt < 0) { return -1; };
return 0;
}
bool isSequence(int a, int b, int c)
{
if (sign(a - b) == sign(b - c))
{
return true;
}
return false;
}
void findSeq(const std::vector<int> &vect)
{
int maxLength = 0;
int startingIndex = 0;
int currentLength = 2;
int findIndex = 0;
for (int i = 0; i < vect.size() - 2; i++)
{
if (isSequence(vect[i], vect[i + 1], vect[i + 2]))
{
currentLength++;
if (currentLength > maxLength)
{
startingIndex = i - findIndex;
maxLength = currentLength;
}
findIndex++;
}
else
{
findIndex = 0;
currentLength = 2;
}
}
for (int j = startingIndex; j < startingIndex + maxLength; j++)
{
std::cout << vect[j];
}
}
</code></pre>
| [] | [
{
"body": "<p>I recently answered a very similar question <a href=\"https://codereview.stackexchange.com/questions/201064/find-the-longest-ascending-subarray-from-a-given-array/201073#201073\">here</a>. When I look at your code, it is very similar to my solution. \nThe only suggestion for improvement I have for... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T11:52:27.153",
"Id": "201277",
"Score": "12",
"Tags": [
"c++",
"algorithm"
],
"Title": "Longest consecutive sequence of ascending, descending, or equal integers"
} | 201277 |
<p>The Fortran program 'MAIN' below calls 3 subroutines. </p>
<ol>
<li>It opens a file if it is not present, (overwrites if it is already present). </li>
<li>writes something on the file using the file identifier integer and </li>
<li>closes the file. </li>
</ol>
<hr>
<pre><code> program MAIN
2001 FORMAT (A,I10)
INTEGER FILEIDS(10)
CHARACTER*64 fname
FILEIDS(1) = 701
write(*,2001) 'opnoutfl', FILEIDS(1)
fname = 'advect1.dat'
CALL OFNFL (FILEIDS(1), fname)
CALL BDEXCH (FILEIDS(1))
CALL CLOOUTFL(FILEIDS(1))
END
SUBROUTINE OFNFL (UNITNO, fname)
LOGICAL EXISTS, OPND
INTEGER UNITNO
CHARACTER*64 fname,dirname,path
2001 FORMAT (A,I10)
write(*,2001) 'opnoutfl', UNITNO
dirname = 'sediment/'
path = trim(dirname) // trim(fname)
INQUIRE (file=path, EXIST=EXISTS)
IF (EXISTS) THEN
OPEN (UNITNO, file=path, status='old')
close(UNITNO, STATUS='DELETE')
OPEN (UNITNO, file=path, status='NEW')
WRITE(UNITNO,2001) 'Alte Dateil ist geloest ',UNITNO
ELSE
OPEN (UNITNO, file=path, status='NEW')
WRITE(UNITNO, 2001) 'Neue Datei ist geoeffnet',UNITNO
END IF
RETURN
END
SUBROUTINE CLOOUTFL (UNITNO)
INTEGER UNITNO
CLOSE(UNITNO)
RETURN
END
SUBROUTINE BDEXCH (MESSU)
INTEGER MESSU
2001 FORMAT (A,I10)
WRITE(MESSU, 2001) 'bdexch schreibt', MESSU+10
RETURN
END
</code></pre>
<p>My question is, at this moment I am passing file identifier as argument. How can I modify/improve this code so that the file identifier created in first subroutine i.e. <code>OFNFL()</code> be automatically seen to subsequent subroutines which uses/writes on the file? The program where I want to use it creates lots of files and then different subroutines writes on different files, so passing file identifier like this will not look very clean!!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T12:45:11.593",
"Id": "387637",
"Score": "0",
"body": "I would advise to have a look at he `MODULE` facilities of Fortran as well as at the `CONTAINS` statement."
}
] | [
{
"body": "<p>If you want to share access to one or more files that are known beforehand, a possible way is to make each file into a singleton and to pack all of them in a module. I illustrate the principle below, after rewriting your code in modern fortran. The example incorporates many feature that should be... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T12:42:23.923",
"Id": "201281",
"Score": "3",
"Tags": [
"reference",
"fortran"
],
"Title": "Passing file identifiers to all subroutines of fortran code"
} | 201281 |
<p>I'm currently developing a simple 2D game engine and I was just wondering, what are some things that I can do to improve my service locator class, at the moment it's very basic.</p>
<p>For example, should I be checking for null objects, if so, what exceptions should I throw?</p>
<p>Here's the code, thatnks in advance!</p>
<pre><code>using System;
using System.Collections.Generic;
namespace GameEngine.Core
{
public sealed class ServiceLocator
{
private static ServiceLocator instance;
private Dictionary<Type, object> services;
public ServiceLocator()
{
this.services = new Dictionary<Type, object>();
}
public void AddService(Type serviceType, object serviceObject)
{
this.services.Add(serviceType, serviceObject);
}
public void RemoveService(Type serviceType)
{
this.services.Remove(serviceType);
}
public object GetService(Type serviceType)
{
return this.services[serviceType];
}
public static ServiceLocator Instance
{
get
{
if (instance == null)
{
instance = new ServiceLocator();
}
return instance;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T13:12:22.957",
"Id": "387640",
"Score": "0",
"body": "Is this just for fun or if you want a simple one why not use the ServiceContainer class that's in .net already?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate"... | [
{
"body": "<p>I think you are reinventing the wheel a bit too much. If you need something simple then go with built in .net ones. If you going to make a simple ServiceLocator then you should implement the <a href=\"https://msdn.microsoft.com/en-us/library/system.componentmodel.design.iservicecontainer(v=vs.11... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T13:08:35.547",
"Id": "201284",
"Score": "1",
"Tags": [
"c#",
"game"
],
"Title": "Service locator for a 2D game"
} | 201284 |
<p>I'm coding a turn-based RPG battle simulator (text based) in Java.</p>
<p>I'm doing this as an exercise/project to learn OOP design. I've coded something similar in C, but just porting that code over to java would, of course,
be rather silly. I'm going to be taking this extremely slow, focusing on getting each element right and learning as much as I can from it, rather than trying to progress as quick as possible.
(I've been programming for about 3 months)</p>
<p>With the above in mind, I'm currently focusing on just:</p>
<ul>
<li>Display input prompt</li>
<li>Get input</li>
<li>Calculate results</li>
<li>Display results</li>
</ul>
<p>So, without any further ado, rip my terrible code to pieces :)</p>
<pre><code>public class Demo
{
public static void main(String[] args){
Combatant syd = new Combatant("Syd",5,3); //name,strength,magic
Combatant goblin = new Combatant("Goblin",5,1);
Battle encounter = new Battle(syd, goblin);
}
}
</code></pre>
<hr>
<pre><code>package packs.rpg;
public class Combatant{
// instance variables //
private final String name;
private int maxHealth;
private int health;
private int strength;
private int magic;
BattleAction battleAction;
// constructor(s) //
public Combatant(String name, int strength, int magic){
this.name = name;
maxHealth = 10;
this.health = maxHealth;
this.strength = strength;
this.magic = magic;
}
// methods //
protected void takeTurn(BattleAction chosenAction, Combatant target){
if(health > 0){
setBattleAction(chosenAction); //strategy pattern
}
else{
setBattleAction(new FaintedAction());
}
performAction(target);
}
private void performAction(Combatant target){
battleAction.execute(this, target);
};
protected void decreaseHealth(int amount){
if(health - amount < 0){health = 0;}
else{health -= amount;}
}
protected void increaseHealth(int amount){
if(health + amount > maxHealth){health = maxHealth;}
else{health += amount;}
}
// accessors / mutators //
public String getName(){
return name;
}
public int getHealth(){
return health;
}
public int getStrength(){
return strength;
}
public int getMagic(){
return magic;
}
public void setBattleAction(BattleAction chosenAction){
battleAction = chosenAction;
}
}
</code></pre>
<hr>
<pre><code>package packs.rpg;
public interface BattleAction{
public void execute(Combatant user, Combatant target);
public String toString();
}
class AttackAction implements BattleAction{
String outcomeText;
public void execute(Combatant user, Combatant target){
int damage = BattleHelper.getRng(user.getStrength())+1; //get randomized damage based on user strength
target.decreaseHealth(damage);
outcomeText = (user.getName() + " hits for " + damage + "\n" + target.getName() + "'s health is now " + target.getHealth() + "\n\n");
}
public String toString(){
return outcomeText; //return the result of the attack (the gnarly string above)
};
}
class HealAction implements BattleAction{
public void execute(Combatant user, Combatant target){
int amount = BattleHelper.getRng(user.getMagic()+1);
user.increaseHealth(amount);
}
public String toString(){
return "placeholder text for heal";
};
}
class FaintedAction implements BattleAction{
String outcomeText;
public void execute(Combatant user, Combatant target){
outcomeText = (user.getName() + " fainted...");
}
public String toString(){
return outcomeText;
};
}
</code></pre>
<hr>
<pre><code>package packs.rpg;
import java.util.*;
public class Battle{
private Combatant player;
private Combatant enemy;
private BattleAction playerAction;
public Battle(Combatant thePlayer, Combatant theEnemy){
player = thePlayer;
enemy = theEnemy;
fight();
}
private void fight(){
while(player.getHealth() > 0 && enemy.getHealth() > 0){
playerAction = BattleHelper.getBattleAction(player); //poll for input to get choie of action
player.takeTurn(playerAction, enemy); //pass the enemy encase decision was to attack
BattleHelper.displayTurnOutcome(player.battleAction.toString()); //toString method returns result of chosen action
}
}
}
</code></pre>
<hr>
<pre><code>package packs.rpg;
import java.util.*;
class BattleHelper{
static Random rng = new Random();
static Scanner in = new Scanner(System.in);
public static BattleAction getBattleAction(Combatant user){
System.out.printf("%s's turn\n",user.getName());
System.out.println("Select an action");
System.out.println("1. Attack | 2. Heal");
int i;
do{
i = in.nextInt();
}
while(i != 1 && i != 2);
if(i == 1){
return new AttackAction();
}
else{
return new HealAction();
}
}
public static void displayTurnOutcome(String outcomeText){
System.out.printf("%s",outcomeText);
};
public static int getRng(int range)
{
return rng.nextInt(range);
}
}
</code></pre>
<p>I'd love to hear how you'd personally accomplish coding the above (simplified down to my level...) the more approaches I have to compare the better. The only pattern I've looked at in depth thus far is the strategy pattern, and I'm having to stop myself from trying to work it into every situation. Handling I/O without bolting/coupling it directly to the logic is proving difficult for me to get my head around. It's so tempting to just put printf statements right after the event has happened in the method that processed it, but from what I've read, that's a big no-no.</p>
<p>I don't have internet at home (posting from the library) so if I don't reply for 24 hours, that's why. Any questions about how the code works, of course just ask (I hope the formatting/structure is easy enough to follow).</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T16:19:04.027",
"Id": "387672",
"Score": "0",
"body": "It looks like your `BattleHelper` class is incomplete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-10T14:58:16.643",
"Id": "387854",
"Sco... | [
{
"body": "<p>I'd say in general, it is quite decent code. Nothing written too complicated, variables are named so that I understand it and 'stuff' which belongs together is mostly separated within classes.</p>\n<h3>Some java coding conventions:</h3>\n<ul>\n<li>spaces after commas (e.g. Demo, creation of Combat... | {
"AcceptedAnswerId": "201300",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T13:50:28.823",
"Id": "201291",
"Score": "4",
"Tags": [
"java",
"beginner",
"object-oriented",
"battle-simulation"
],
"Title": "Java RPG battle simulator"
} | 201291 |
<p>I have around 300 log files in a directory and each log file contains around 3300000 lines. I need to read through each file line by line and count how many hostnames that appear on each line. I wrote basic code for that task, but it takes more than 1 hour to run and takes lots of memory as well. How can I improve this code to make it run faster?</p>
<pre><code>import pandas as pd
import gzip
directory=os.fsdecode("/home/scratch/mdsadmin/publisher_report/2018-07-25")#folder with 300 log files
listi=os.listdir(directory)#converting the logfiles into a list
for file in listi:#taking eaching log file in the list
tt=os.path.join(directory,file)# joining log file name along with the directory path
with gzip.open(tt,'rt') as f: #unzipping the log file
rows=[]#clearing the list after every loop
for line in f: #reading each line in the file
s=len(line.split('|'))
a=line.split('|')[s-3]
b=a.split('/')[0] #slicing just the hostname out of each line in the log file
if len(b.split('.'))==None:
''
else:
b=b.split('.')[0]
rows.append(b) # appending it to a list
df_temp= pd.DataFrame(columns=['hostname'],data=rows) #append list to the dataframe after every file is read
df_final=df_final.append(df_temp,ignore_index=True) #appending above dataframe to a new one to avoid overwriting
del df_temp #deleting temp dataframe to clear memory
df_final=df_final.groupby(["hostname"]).size().reset_index(name="Topic_Count") #doing the count
</code></pre>
<p><strong>Sample log lines</strong></p>
<pre><code>tx:2018-05-05T20:44:37:626 BST|rx:2018-05-05T20:44:37:626 BST|dt:0|**wokpa22**.sx.sx.com/16604/#001b0001|244/5664|2344|455
tx:2018-05-05T20:44:37:626 BST|rx:2018-05-05T20:44:37:626 BST|dt:0|**wokdd333**.sc.sc.com/16604/#001b0001|7632663/2344|342344|23244
</code></pre>
<p><strong>Desired output</strong></p>
<p><a href="https://i.stack.imgur.com/qfaMG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qfaMG.jpg" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T16:05:31.177",
"Id": "387669",
"Score": "0",
"body": "Well, you are searching a huge database. Why did you think it would be faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T17:34:28.853",
... | [
{
"body": "<p>So I think you can improve the efficiency of your code like this.</p>\n\n<p>First, as I said in one comment, you can replace:</p>\n\n<pre><code>s=len(line.split('|'))\na=line.split('|')[s-3]\n</code></pre>\n\n<p>by</p>\n\n<pre><code>a=line.split('|')[-3]\n</code></pre>\n\n<p>as no need to know the... | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T16:00:07.677",
"Id": "201303",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"pandas"
],
"Title": "Reading set of large log files line by line and count how many hostnames appear on each line"
} | 201303 |
<p>I have written this script in Python 2.7 and I was wondering where I could improve it or efficient. This is my first script so I don't now much. The script takes a text file from a folder removes blank spaces with list comprehension and then breaks it into smaller 20 elements and saves it each 20 elements as a definition into a dictionary with iterative numbered keys. Each key is then used to fetch the definition from the dictionary and sends each through the API one by one saving the output into another dictionary. The result dictionary is then converted to text and saved into a text file.</p>
<pre><code>import glob
import os
import json
import paralleldots
api_key = "iyuDsKbgZSsCxVj6Moe37MzdqCUuvkpf33t6qS3X3cH"
paralleldots.set_api_key(api_key)
output = input(r"C:\Users\User\Desktop\trial")
txt_files = os.path.join("D:\\english\\stou\\check", '*.txt')
dic = {} #dictionary for storing list elements
res = {} #results dictionary for api output
def for_high (list_e): #defining a function for taking list elements and putting them into dic
no_keys = list_e / 20
dic = {
1: l[1:21]
}
i = 1
start_key_value = 21
while i <= no_keys:
i += 1
end_key_value = start_key_value + 20
dic.update({i: ''.join(l[start_key_value:end_key_value])})
start_key_value += 20
for x in dic: #creating a for loop for getting and saving the output and creating a new file
output = paralleldots.emotion(dic.get(x))
res.update({x: output})
with open(os.path.join("C:\\Users\\User\\Desktop\\trial", filename), 'w') as text_file:
text_file.write(json.dumps(res))
for txt_file in glob.glob(txt_files): # for loop for going through all the text files in the input directory
with open(txt_file, "r") as input_file:
filename = os.path.splitext(os.path.basename(txt_file))[0] + '.txt'
l = [l for l in input_file.readlines() if l.strip()]
list_e = int(len(l)) #no. of list elements variable
if list_e > 20: #checking if list has more than 20 elements
if list_e % 2 != 0: #checking if list has an odd no. of elements
list_e += 1
for_high(list_e)
else:
for_high(list_e)
else:
in_txt = paralleldots.emotion(l)
filename = os.path.splitext(os.path.basename(txt_file))[0] + '.txt'
with open(os.path.join("C:\\Users\\User\\Desktop\\trial", filename), 'w') as text_file:
text_file.write(str(in_txt))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T16:56:44.290",
"Id": "387676",
"Score": "1",
"body": "Please capitalize correctly. It makes it much easier to read your post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T17:00:31.310",
"Id": "... | [
{
"body": "<p>I understand you are a beginner and you had the guts to post your code. You deserve some feedback and I will try.</p>\n\n<h1>Your code is hard to read</h1>\n\n<p>This is most probably why you didn't get answers till now. There is code repetition, global and reused variables, no clear control flow,... | {
"AcceptedAnswerId": "201381",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T16:48:04.440",
"Id": "201306",
"Score": "0",
"Tags": [
"python",
"beginner"
],
"Title": "Batch processing large text files for sentiment analysis"
} | 201306 |
<p>I created a BFS algorithm in order to solve an 8-puzzle, and while it works, it is awfully slow compared to my DFS implementation. My main point of concern is the puzzleExists() function, which determines whether the created puzzle already exists in the list and should therefore be dropped. Currently the algorithm slows down significantly as it has to check all the previous puzzles for duplicates.</p>
<p>Advice on how to aproach this would be appreciated.</p>
<p>Code for DFS and printing omitted for clarity:</p>
<pre><code>#include <iostream>
#include <vector>
#include <chrono>
using namespace std;
using namespace std::chrono;
const int PUZZLE_LENGTH = 9;
const int EMPTY = 0;
struct Puzzle
{
int state[PUZZLE_LENGTH];
int gapLocation;
};
struct breadthPuzzle
{
Puzzle puzzle;
int parent;
};
const Puzzle SOLVED_PUZZLE = { { 1,2,3,4,5,6,7,8,EMPTY } };
// Check if the provided puzzle is actually solvable or not
// Credit for formula to: http://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html
bool isSolvable(const Puzzle& puz)
{
int inversions = 0;
for ( int i = 0; i < PUZZLE_LENGTH; i++ )
for ( int j = i + 1; j < PUZZLE_LENGTH; j++ )
if ( puz.state[j] > puz.state[i] && puz.state[i] != EMPTY && puz.state[j] != EMPTY )
inversions++;
// If the amount of inversions is even the puzzle can be solved
return inversions % 2 == 0;
}
// Checks if the 2 provided puzzles are the same
bool puzzleTheSame(const Puzzle& puz1, const Puzzle& puz2)
{
for ( int length = 0; length < PUZZLE_LENGTH; length++ )
if ( puz1.state[length] != puz2.state[length] ) return false;
return true;
}
bool puzzleExists(const Puzzle& currentPuzzle, vector<breadthPuzzle>& currentRoute)
{
for ( int i = 0; i < currentRoute.size(); i++ )
if ( puzzleTheSame(currentRoute[i].puzzle, currentPuzzle) )
return true;
return false;
}
// Checks if the provided puzzle is solved
bool isSolved(const Puzzle& solution)
{
return puzzleTheSame(SOLVED_PUZZLE, solution);
}
bool canNorth(int gapLocation)
{
return gapLocation > 2;
}
bool canEast(int gapLocation)
{
return (gapLocation != 2 && gapLocation != 5 && gapLocation != 8);
}
bool canSouth(int gapLocation)
{
return gapLocation < 6;
}
bool canWest(int gapLocation)
{
return (gapLocation != 0 && gapLocation != 3 && gapLocation != 6);
}
int north(int gap)
{
return gap - 3;
}
int east(int gap)
{
return gap + 1;
}
int south(int gap)
{
return gap + 3;
}
int west(int gap)
{
return gap - 1;
}
Puzzle createNextPuzzle(Puzzle currentPuzzle, int pos)
{
int temp = currentPuzzle.state[pos];
currentPuzzle.state[currentPuzzle.gapLocation] = temp;
currentPuzzle.state[pos] = EMPTY;
currentPuzzle.gapLocation = pos;
return currentPuzzle;
}
void solvePuzzle(vector<breadthPuzzle>& currentRoute, int i, int futurePos)
{
Puzzle currentPuzzle = createNextPuzzle(currentRoute[i].puzzle, futurePos);
if ( !puzzleExists(currentPuzzle, currentRoute) )
{
breadthPuzzle candidate{ currentPuzzle, i };
currentRoute.push_back(candidate);
}
}
void breadthFirst(Puzzle initalPuzzle)
{
// Origin has no parent, thus -1 as start.
vector<breadthPuzzle> breadthVector = { { initalPuzzle, -1 } };
int i = 0;
while ( i < breadthVector.size() && !isSolved(breadthVector[i].puzzle) )
{
Puzzle currentPuzzle = breadthVector[i].puzzle;
int gapLocation = currentPuzzle.gapLocation;
if ( canNorth(gapLocation) ) solvePuzzle(breadthVector, i, north(gapLocation));
if ( canEast(gapLocation) ) solvePuzzle(breadthVector, i, east(gapLocation));
if ( canSouth(gapLocation) ) solvePuzzle(breadthVector, i, south(gapLocation));
if ( canWest(gapLocation) ) solvePuzzle(breadthVector, i, west(gapLocation));
i++;
}
}
int main()
{
Puzzle toSolve = { {1,2,3,4,6,5,8,7,EMPTY}, 8 };
//Breadth-First: Duration in seconds = 72;
//Depth-First: Duration in seconds = 15;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
if ( isSolvable(toSolve) )
{
cout << "Puzzle Solvable\n";
breadthFirst(toSolve);
}
else
cout << "Puzzle insolvable, stopping\n";
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto durationSec = duration_cast<seconds>(t2 - t1).count();
cout << "Duration in seconds of function: " << durationSec << endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-10T12:15:03.747",
"Id": "387823",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your ... | [
{
"body": "<p>Here's the code you want to speed up:</p>\n\n<pre><code>// Checks if the 2 provided puzzles are the same\nbool puzzleTheSame(const Puzzle& puz1, const Puzzle& puz2)\n{\n for ( int length = 0; length < PUZZLE_LENGTH; length++ )\n if ( puz1.state[length] != puz2.state[length] ) ... | {
"AcceptedAnswerId": "201315",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T17:09:56.420",
"Id": "201308",
"Score": "9",
"Tags": [
"c++",
"performance",
"algorithm",
"breadth-first-search",
"sliding-tile-puzzle"
],
"Title": "Solve 8-tile sliding puzzle"
} | 201308 |
<p>This function formats the text in each cell of a CSV. The goal of the function is to make sure that the sequence of characters in <code>text</code> will never break the cell's partition. The correct output of this function looks like any of these:</p>
<ul>
<li>"foo"</li>
<li>"123"</li>
<li>"drop table 'chocolate'; -- this is fine, i don't care"</li>
<li><code>"<script>alert(""even scripts are allowed""); /\*notice the use of double double quotes here\*/</script>"</code></li>
</ul>
<pre><code>protected string formatCSVCell(string text)
{
// https://www.owasp.org/index.php/CSV_Injection
// https://stackoverflow.com/questions/4617935/is-there-a-way-to-include-commas-in-csv-columns-without-breaking-the-formatting
// http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm#FileFormat
// https://codereview.stackexchange.com/questions/201313/does-this-method-guarantee-that-cells-in-a-csv-will-be-correctly-partitioned
var doubleQuote = "\"";
text = text.Replace($"{doubleQuote}", $"{doubleQuote}{doubleQuote}"); // escape existing double quotes
text = $"{doubleQuote}{text}{doubleQuote}"; // add double quotes around each value
return text;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T18:31:12.133",
"Id": "387694",
"Score": "2",
"body": "Can any of the three people who downvoted this explain their reasoning please. Please point to some objective violation of the site guidelines."
},
{
"ContentLicense": "C... | [
{
"body": "<p>right now I can only see one thing that I might do differently, but it only shortens the code block a bit.</p>\n\n<p>I might return the second statement, it removes an assignment to the variable, I don't like adding extra steps I don't have to.</p>\n\n<pre><code>protected string formatCSVCell(stri... | {
"AcceptedAnswerId": "203183",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T17:49:13.953",
"Id": "201313",
"Score": "-3",
"Tags": [
"c#",
"security",
"csv"
],
"Title": "Format data for a CSV item"
} | 201313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.