body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I've just started with F# (I'm coming from a mostly OO background) and I'm looking for </p>
<ul>
<li>feedback on the code, particularly: is this the way F# code should be written like?</li>
<li>have I overlooked an existing library function which would make this easier or could replace it completely?</li>
</ul>
<p>The goal is: </p>
<p>Take an input list and sort it according to certain conditions into several bags, keeping also those items not fitting any condition. (Which is why <code>groupBy</code> doesn't do the trick, unless I'm overlooking something).</p>
<p>The function:</p>
<pre><code>let sortIntoBags<'T, 'TBag> (predicate: 'TBag*'T->bool) (bags: 'TBag list)
(lst: 'T list)=
let take (lst: 'T list) (bag: 'TBag)=
let isInBag e = predicate (bag, e)
let (inBag, remaining) = lst |> List.partition isInBag
((bag, inBag), remaining)
let (bagSets, leftOver) = bags |> List.mapFold take lst
(bagSets, leftOver)
</code></pre>
<p>A simple example for usage is:</p>
<pre><code>> let l= [1..25];;
val l : int list =
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21;
22; 23; 24; 25]
> let bags= [2; 3; 5; 7];;
val bags : int list = [2; 3; 5; 7]
> let isDivisorFor (x, y) = 0=y%x ;;
val isDivisorFor : x:int * y:int -> bool
> l |> sortIntoBags isDivisorFor bags;;
val it : (int * int list) list * int list =
([(2, [2; 4; 6; 8; 10; 12; 14; 16; 18; 20; 22; 24]); (3, [3; 9; 15; 21]);
(5, [5; 25]); (7, [7])], [1; 11; 13; 17; 19; 23])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T22:05:46.203",
"Id": "391971",
"Score": "0",
"body": "@graipher why remove the thanks? it's just polite, isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T17:42:31.793",
"Id": "392059",
... | [
{
"body": "<p>Here's another (Subjectively better or worse) way to write this, however it does require comparison unlike yours:</p>\n\n<pre><code>let sortIntoBags<'T,'TKey when 'TKey : comparison > (predicate:'TKey*'T -> bool) (bagKeys:'TKey list) (items:'T list) : ('TKey*'T list) list * 'T list =\n ... | {
"AcceptedAnswerId": "203929",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T18:31:54.860",
"Id": "203358",
"Score": "2",
"Tags": [
"beginner",
"f#"
],
"Title": "Sorting a list into different bags according to predicate"
} | 203358 |
<p>I have an implementation of <code>Linked List</code> with <code>push</code>, <code>pop</code>, <code>size</code>, <code>print</code> and <code>search</code> functionalities. This is also an attempt to learn smart pointers. I have only used <code>shared_pointers</code> in this implementation.</p>
<pre><code>#include <iostream>
#include <memory>
#include <cstddef>
// Class for individual nodes in the list
template<typename T>
class Node
{
T val;
std::shared_ptr<Node<T>> next = nullptr;
public:
Node(T value)
{
val = value;
}
T get_val() const;
void set_next(std::shared_ptr<Node<T>>);
std::shared_ptr<Node<T>> get_next() const;
};
template<typename T>
T Node<T>::get_val() const
{
return val;
}
template<typename T>
void Node<T>::set_next(std::shared_ptr<Node<T>> node)
{
next = node;
}
template<typename T>
std::shared_ptr<Node<T>> Node<T>::get_next() const
{
return next;
}
// Class for the Linked List
template<typename T>
class LinkedList
{
/*std::shared_ptr<Node<T>> head = std::make_shared<Node<T>>(nullptr);
std::shared_ptr<Node<T>> tail = std::make_shared<Node<T>>(nullptr);*/
std::shared_ptr<Node<T>> head;
std::shared_ptr<Node<T>> tail;
std::size_t size_var = 0;
public:
LinkedList()
{
}
void push(T);
T pop();
int search(T) const;
void print() const;
std::size_t size() const;
};
// Insert node at head
template<typename T>
void LinkedList<T>::push(T value)
{
auto new_node = std::make_shared<Node<T>>(value);
// Check if the list already has values and push values at the head accordingly
if(head == nullptr)
{
head = new_node;
tail = new_node;
}
else
{
auto temp = head;
head = new_node;
new_node -> set_next(temp);
}
size_var++;
}
// Remove node at tail
template<typename T>
T LinkedList<T>::pop()
{
T value = tail -> get_val();
auto node = head;
std::shared_ptr<Node<T>> prev;
// Set the tail to second last value and set its next to nullptr.
while(node)
{
if(node -> get_next() == nullptr)
{
//std::cout << "Tail count first: " << node.use_count() << "\n";
tail = prev;
//std::cout << "Tail count second: " << node.use_count() << "\n";
tail -> set_next(nullptr);
//std::cout << "Tail count third: " << node.use_count() << "\n";
break;
}
prev = node;
node = node -> get_next();
}
size_var--;
return value;
}
//Returns the index of the value if found, else returns zero.
template<typename T>
int LinkedList<T>::search(T value) const
{
auto node = head;
int index = 0;
while(node)
{
if(node -> get_val() == value)
{
return index;
}
node = node -> get_next();
index++;
}
return -1;
}
// Print the list
template<typename T>
void LinkedList<T>::print() const
{
auto node = head;
std::cout << "Printing List: \n";
while(node)
{
std::cout << node -> get_val() << "\t";
node = node -> get_next();
}
std::cout << "\n";
}
// Return the size of the list
template<typename T>
std::size_t LinkedList<T>::size() const
{
return size_var;
}
int main()
{
LinkedList<int> ll{};
for(int i = 8; i >= 0; i--)
{
ll.push(i);
}
ll.print();
std::cout << "Size: " << ll.size() << "\n";
std::cout << "Pop: " << ll.pop() << "\n";
std::cout << "Size: " << ll.size() << "\n";
std::cout << "Pop: " << ll.pop() << "\n";
std::cout << "Size: " << ll.size() << "\n";
ll.push(9);
ll.print();
std::cout << "Size: " << ll.size() << "\n";
std::cout << "Search: " << ll.search(10) << "\n";
std::cout << "Search: " << ll.search(5) << "\n";
return 0;
}
</code></pre>
<p>The <code>push</code> inserts a new node or item at the head of the list while <code>pop</code> removes an item from the tail. The <code>search</code> returns an index or position of the item if value being searched for is found.</p>
<ol>
<li><p>Is the usage of smart pointers correct? Are there any leaks, especially in <code>pop</code>?</p></li>
<li><p>Are there any place in this code where I should be using <code>std::unique_ptr</code>? I felt that there is always a possibility of more than one pointer being pointed to any node; hence I avoided <code>std::unique_ptr</code>.</p></li>
<li><p>What should be the return type of <code>search</code>, <code>bool</code> or <code>int</code> or <code>std::size_t</code>? If it is <code>std::size_t</code>, is <code>std::optional</code> the best way to indicate search failure?</p></li>
</ol>
| [] | [
{
"body": "<ol>\n<li><p>I'd recommend avoiding returning the value from <code>pop</code>. If <code>T</code>'s copy constructor throws, you lose the data. So I would introduce <code>T top() const</code> and use it along with non-returning <code>void pop()</code>. This approach is used in <code>STL</code> contain... | {
"AcceptedAnswerId": "203366",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T19:56:42.257",
"Id": "203362",
"Score": "2",
"Tags": [
"c++",
"linked-list",
"generics",
"pointers"
],
"Title": "Linked List using templates and smart pointers"
} | 203362 |
<p>I tried to implement a traffic light system using state pattern, please comment on the OOP/design pattern use. </p>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DesignPatternsQuestions
{
/// <summary>
/// implement a traffic light system
/// </summary>
[TestClass]
public class StatePatternTest
{
[TestMethod]
public void StateTrafficLightTest()
{
TrafficLight light = new TrafficLight(new RedState());
light.ChangeLight();
Assert.IsInstanceOfType(light.State,typeof(GreenState));
light.ChangeLight();
Assert.IsInstanceOfType(light.State, typeof(YellowState));
light.ChangeLight();
Assert.IsInstanceOfType(light.State, typeof(RedState));
light.ChangeLight();
Assert.IsInstanceOfType(light.State, typeof(GreenState));
}
}
public class TrafficLight
{
private State _state;
public TrafficLight(State state)
{
_state = state;
}
// Gets or sets the state
public State State
{
get { return _state; }
set
{
_state = value;
Console.WriteLine("State: " +
_state.GetType().Name);
}
}
//this is the trickS
public void ChangeLight()
{
_state.SetState(this);
}
}
public abstract class State
{
public abstract void SetState(TrafficLight light);
}
public class RedState: State
{
public override void SetState(TrafficLight light)
{
light.State = new GreenState();
}
}
public class YellowState : State
{
public override void SetState(TrafficLight light)
{
light.State = new RedState();
}
}
public class GreenState : State
{
public override void SetState(TrafficLight light)
{
light.State = new YellowState();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T14:47:03.247",
"Id": "392218",
"Score": "0",
"body": "I think `State` class is overkill here when simple `enum` or even declared int constants could be used. I would also consider 2 other states: None (with a value of 0) for when a... | [
{
"body": "<p>First, I see no reason to make the setter of <code>TrafficLight.State</code> public, as there's no reason the client should be able to change it directly.</p>\n\n<p>Second, your solution looks a bit too complicated to me. As long as you're talking about traffic lights where the number of possible ... | {
"AcceptedAnswerId": "203483",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T20:50:16.093",
"Id": "203364",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"state"
],
"Title": "State Pattern for traffic lights"
} | 203364 |
<p>I have this code to save data into some records. It is a little slow, so how can I make it faster?</p>
<p>To the first record (sheet <code>MOV MERCADERIA</code>) it copies 23 columns and from 1 to 29 rows. The problem is when the dispatch note is complete (when the 29 rows are full).</p>
<p>And to the second record (sheet <code>CONCAT</code>) it copies 4 columns and inserts some formulas to other 9 columns from 1 to 29 rows. And then It removes the duplicates from the sheet <code>CONCAT</code> as seemed in the code.</p>
<pre><code> Sub GUARDARREMITO()
Application.ScreenUpdating = False
Sheets("Remito").Select
Range("B11").Select
While ActiveCell.Value <> ""
ActiveCell.Offset(0, 3).Select
If ActiveCell = "" Then
MsgBox "FALTAN INGRESAR CANTIDADES"
Exit Sub
End If
ActiveCell.Offset(1, -3).Select
Wend
Range("B5").Select
FECHA = ActiveCell.Value
ActiveCell.Offset(1, 0).Select
NROREMITO = ActiveCell.Value
ActiveCell.Offset(1, 0).Select
CTIPOREMITO = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
TIPOREMITO = ActiveCell.Value
ActiveCell.Offset(1, -1).Select
CPROVEEDOR = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
PROVEEDOR = ActiveCell.Value
ActiveCell.Offset(1, -1).Select
CRESPONSABLE = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
RESPONSABLE = ActiveCell.Value
ActiveCell.Offset(34, -1).Select
OBSERVACIONES = ActiveCell.Value
ActiveCell.Offset(-2, 3).Select
TOTART = ActiveCell.Value
ActiveCell.Offset(0, 6).Select
CMVTOT = ActiveCell.Value
ActiveCell.Offset(-30, 11).Select
ITEMTOT = ActiveCell.Value
Range("B11").Select
While ActiveCell.Value <> ""
CODART = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
CODCLR = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
TALLE = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
CANTIDAD = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
DESCRIPCION = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
CLR = ActiveCell.Value
ActiveCell.Offset(0, 2).Select
CONCATENAR = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
CMVUNIT = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
CMVCANT = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
PVPUNIT = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
ITEM1 = ActiveCell.Value
ActiveCell.Offset(1, -11).Select
DIREC1 = ActiveCell.Address
Sheets("MOV MERCADERIA").Select
Range("A2").Select
While ActiveCell.Value <> ""
ActiveCell.Offset(1, 0).Select
Wend
ActiveCell.Value = NROREMITO
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = FECHA
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CTIPOREMITO
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = TIPOREMITO
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CPROVEEDOR
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = PROVEEDOR
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CODART
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = DESCRIPCION
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CODCLR
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CLR
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = TALLE
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CANTIDAD
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CONCATENAR
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CMVUNIT
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CMVCANT
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = PVPUNIT
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = ITEM1
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = ITEMTOT
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CMVTOT
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = TOTART
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CRESPONSABLE
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = RESPONSABLE
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = OBSERVACIONES
Sheets("Remito").Select
Range(DIREC1).Select
Sheets("CONCAT").Select
Range("A2").Select
While ActiveCell.Value <> ""
ActiveCell.Offset(1, 0).Select
Wend
ActiveCell.Value = CONCATENAR
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()+1)),ARTICULOS!$A:$D,4,FALSE)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CODART
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = CODCLR
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = TALLE
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=IFERROR(VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()-2)),COLORES!$A:$B,2,FALSE),"""")"
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()-4)),ARTICULOS!$A:$F,6,FALSE)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()-5)),ARTICULOS!$A:$G,7,FALSE)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = 1
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()-7)),ARTICULOS!$A:$H,8,FALSE)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()-8)),ARTICULOS!$A:$I,9,FALSE)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()-9)),ARTICULOS!$A:$B,2,FALSE)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Formula = "=VLOOKUP(INDIRECT(ADDRESS(ROW(),COLUMN()-10)),ARTICULOS!$A:$C,3,FALSE)"
Sheets("Remito").Select
Range(DIREC1).Select
With Sheets("CONCAT")
numFilas = .Cells(.Rows.Count, 1).End(xlUp).Row
For i = numFilas To 1 Step -1
If WorksheetFunction.CountIf(.Range("A:A"), .Cells(i, 1)) > 1 Then
.Rows(i).Delete
End If
Next i
End With
Wend
Sheets("Remito").Select
Range("B13").Select
[B6] = Val([B6]) + 1
End Sub
</code></pre>
| [] | [
{
"body": "<p>First things first - I assume you used the macro recorder to create this. Maybe you recorded one thing and then wrote the rest based on that. I want to congratulate you on trying this out! It's pretty much how we all start. I also want to welcome you to code review and give you more congrats on wa... | {
"AcceptedAnswerId": "203384",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T22:46:39.427",
"Id": "203372",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Sending data from sheet to other sheet in Excel (from a dispatch note to some records)"
} | 203372 |
<p>This is an app wherein you have to find the word that represents the image. It's the same concept as the course app but I did this one myself.</p>
<p><a href="https://i.stack.imgur.com/83Gzi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/83Gzi.png" alt="enter image description here"></a></p>
<p>How can I improve this code (put more commentary, put more space, you can add that, etc.)? I finished the second part of app development with Swift. Please explain why I should do the modification. Commentary are in French but I can translate them.</p>
<p>Game Struct</p>
<pre><code>import Foundation
import UIKit
struct Game
{
var correctWord: String
var image: UIImage
var guessedLetter: [Character]
// création du bon mot par le joueur
var formatedWord: String
{
var formateWord = ""
let word = correctWord.lowercased()
for letter in word
{
if guessedLetter.contains(letter)
{
formateWord += "\(letter)"
}
else
{
formateWord += "_"
}
}
return formateWord
}
// Quand le joueur
mutating func playerGuessed(_ letter: Character)
{
guessedLetter.append(letter)
}
}
</code></pre>
<p>View Controller</p>
<pre><code>import UIKit
//liste de mot et image
var imageAndWord = ["Maison": #imageLiteral(resourceName: "image 1"),"Bateau": #imageLiteral(resourceName: "image2") ,"Train": #imageLiteral(resourceName: "image 3"),"Vase": #imageLiteral(resourceName: "image 4")]
//récupération des clées
var theKey = Array(imageAndWord.keys)
// Nombre de clé
let totalKey = theKey.count + 1
//récupération des valeurs
var theValue = Array(imageAndWord.values)
// comptage d'image trouvé
var imageFindNumber = 0
class ViewController: UIViewController {
// initialisation des vues
@IBOutlet var lettersButtons: [UIButton]!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
//Quand une lettre est pressée
@IBAction func lettersButtonsPressed(_ sender: UIButton)
{
sender.isEnabled = false
let letter = sender.title(for: .normal)!
let lowCasedLetter = Character(letter.lowercased())
currentGame.playerGuessed(lowCasedLetter)
if currentGame.correctWord == currentGame.formatedWord
{
newRound()
}
updateUI()
}
// Actualisation de l'interface
func updateUI()
{
let word = currentGame.formatedWord.map{String($0)}
let spacingWord = word.joined(separator: " ")
wordLabel.text = spacingWord
imageView.image = currentGame.image
scoreLabel.text = "Image: \(imageFindNumber)/\(totalKey)"
}
var currentGame: Game!
// Initialisation de l'image et du mot
func newRound()
{
if !theKey.isEmpty && !theValue.isEmpty
{
enableOrNotButton(true)
let word = theKey.removeFirst().lowercased()
let value = theValue.removeFirst()
currentGame = Game(correctWord:word, image:value, guessedLetter: [])
imageFindNumber += 1
updateUI()
}
else
{
enableOrNotButton(false)
}
}
//Activation ou désactivation de tout les bouttons
func enableOrNotButton(_ enable: Bool)
{
for button in lettersButtons
{
button.isEnabled = enable
}
}
override func viewDidLoad() {
super.viewDidLoad()
newRound()
print(currentGame.correctWord)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
</code></pre>
| [] | [
{
"body": "<p>I would begin with the imports. When importing <code>UIKit</code> you will not need to import <code>Foundation</code> because the contents of <code>UIKit</code> will also include <code>Foundation</code>.</p>\n\n<p>Now to recommend a few things with regards to the <code>Game</code> struct. Now the... | {
"AcceptedAnswerId": "203580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T23:50:00.610",
"Id": "203375",
"Score": "2",
"Tags": [
"image",
"swift"
],
"Title": "Finding a word that represents an image"
} | 203375 |
<p>I am trying out different data structures to learn more about smart pointers. I have created a queue implementation which has <code>push</code>, <code>pop</code>, <code>front</code>, <code>back</code> and <code>size</code> functions.</p>
<pre><code>#include <iostream>
#include <memory>
#include <cstddef>
template<typename T>
class Queue
{
std::unique_ptr<T[]> q_ptr;
int front_idx = -1;
int back_idx = -1;
int capacity = 0;
public:
Queue(std::size_t space)
{
q_ptr = std::unique_ptr<T[]>(new T[space]);
capacity = space;
}
void push(T value);
void pop();
T front() const;
T back() const;
std::size_t size() const;
};
template<typename T>
void Queue<T>::push(T value)
{
if(front_idx == -1)
{
front_idx++;
}
if(back_idx - front_idx + 1 == capacity)
{
std::cerr << "Queue full\n";
return;
}
q_ptr[++back_idx] = value;
}
template<typename T>
void Queue<T>::pop()
{
if(front_idx == -1)
{
std::cerr << "Empty queue\n";
return;
}
q_ptr[front_idx++] = T{};
}
template<typename T>
T Queue<T>::front() const
{
return q_ptr[front_idx];
}
template<typename T>
T Queue<T>::back() const
{
return q_ptr[back_idx];
}
template<typename T>
std::size_t Queue<T>::size() const
{
return back_idx - front_idx + 1;
}
int main()
{
Queue<int> q1{20};
q1.pop();
for(int i = 0; i < 23; i++)
{
q1.push(i);
}
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue front: " << q1.front() << "\n";
std::cout << "Queue back: " << q1.back() << "\n";
q1.pop();
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue front: " << q1.front() << "\n";
q1.pop();
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue front: " << q1.front() << "\n";
q1.push(12);
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue back: " << q1.back() << "\n";
}
</code></pre>
<ol>
<li><p>The attempt is to use <code>unique_ptr</code> as an array similar to a raw pointer. Is the usage and approach correct? Can it be improved?</p></li>
<li><p>As far as I know, I cannot use <code>shared_ptr</code> this way in C++11 or C++14. Is <a href="https://stackoverflow.com/a/44950534/4834108">this</a> the best approach with <code>shared_ptr</code>?</p></li>
</ol>
| [] | [
{
"body": "<p>Yes I think your usage of <code>unique_ptr</code> is correct. The only recommendation I would make is to use <code>make_unique</code> for construction:</p>\n\n<pre><code>explicit Queue(std::size_t space) : \n q_ptr(std::make_unique<T[]>(space)), \n capacity(space) {}\n</code></pre>\n\n... | {
"AcceptedAnswerId": "203382",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T01:03:03.447",
"Id": "203378",
"Score": "1",
"Tags": [
"c++",
"generics",
"queue",
"pointers"
],
"Title": "Queue implementation using unique_ptr"
} | 203378 |
<p>I put together a basic Tic Tac Toe game and would appreciate some feedback/advice on how to make it better.</p>
<p>Specifically, the GUI is kinda awful. I would love to build more tests into this to test the class thoroughly.</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
A classic tic-tac-toe game programmed for
the command line.
"""
import random
class Board():
def __init__(self):
self. spaces = [None] * 9
self.win = False
self.tie = False
def __str__(self):
return ' Y\n 1 2 3 \n 1: %s | %s | %s \n X 2: %s | %s | %s \n 3: %s | %s | %s ' % tuple([s if s else ' ' for s in self.spaces])
def move(self, player, x, y):
loc = 3*(int(x)) +int(y)
self.spaces[loc] = player
self.__check_win(player)
def __check_win_row(self, a_player,a_list):
return all([x==a_player for x in a_list])
def __check_win(self, player):
if self.__check_win_row(player,self.spaces[0:3]) \
or self.__check_win_row(player,self.spaces[3:6]) \
or self.__check_win_row(player,self.spaces[6:9]):
self.win = True
elif self.__check_win_row(player, [self.spaces[i] for i in [0,3,6]]) \
or self.__check_win_row(player, [self.spaces[i] for i in [1,4,7]]) \
or self.__check_win_row(player, [self.spaces[i] for i in [2,5,8]]):
self.win = True
elif self.__check_win_row(player, [self.spaces[i] for i in [0,4,8]]) \
or self.__check_win_row(player, [self.spaces[i] for i in [2,4,6]]):
self.win = True
elif not any([x==None for x in self.spaces]):
self.tie = True
def oponent_move(self, player):
move = random.choice([i for i in range(9) if self.spaces[i]==None])
self.spaces[move] = player
self.__check_win(player)
def PrintHeader():
result = '\n'
result += '\tTic-Tac-Toe Game\t\n\n'
print(result)
def GetResponse():
play = [None, None]
print("How do you want to move? ")
play[0] = int(input("X: "))-1
play[1] = int(input("Y: "))-1
return play
def SwapPlayer(player):
if player =='X':
return 'O'
elif player == 'O':
return 'X'
else:
raise ValueError
def PrintWinner(player):
result = '\n'
result += 'And the Winner is ....\n'
result += 'Player %s has WON THE GAME!!!' % (player)
print(result)
def PrintTie():
result = '\n'
result += 'Womp, Womp ....\n'
result += "It's a Tie!!!"
print(result)
def main():
playing = True
new_game = Board()
player = 'X'
while playing:
PrintHeader()
print(new_game)
play = GetResponse()
new_game.move(player, play[0], play[1])
if new_game.win or new_game.tie:
break
player = SwapPlayer(player)
new_game.oponent_move(player)
player = SwapPlayer(player)
if new_game.win:
PrintWinner(player)
else:
PrintTie()
if __name__=='__main__':
main()
</code></pre>
<p><a href="https://github.com/polkapolka/tictactoe" rel="nofollow noreferrer">GitHub repo link</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T06:03:56.557",
"Id": "203385",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"tic-tac-toe"
],
"Title": "Basic TicTacToe Game Number 1MillionAnd1"
} | 203385 |
<p>I had a simple webscraper with Beautiful Soup 4 which downloaded novel chapters from a website and converted them to an EPUB file. It was straight and simple imperative programming.</p>
<p>Then I thought, why not use asyncio to speed up the process? Well, it works, but surprisingly, the speed is same as the synchronous one. Therefore, I'd like to have the code reviewed to see whether I'm writing asynchronous code properly, and whether there are any other issues.</p>
<pre><code>import requests as req
from ebooklib import epub
from bs4 import BeautifulSoup as bs
import os
import asyncio
from aiostream import stream, pipe
import sys
err, iterList, min_iterList = [], [], []
length, counter, start, end = 0, 0, 0, 0
book = epub.EpubBook()
def html_gen(elem, soupInstance, value, tagToAppend, insert_loc=None):
element = soupInstance.new_tag(elem)
element.string = value
if not insert_loc:
tagToAppend.append(element)
else:
tagToAppend.insert(insert_loc, element)
def get_iterList():
for a in chapLi.findAll('a'):
link = novelURL + a.get('href')
l = (link, a.string)
iterList.append(l)
#titles.append(a.string)
# Remove the starting 3 iterList with href="#bottom" from list
# Remove the starting 3 titles
del iterList[2], iterList[1], iterList[0]#, titles[2], titles[1], titles[0]
def intro():
global length
global start
global end
length = len(iterList)
start = 0
end = length
print("\r\nName : ", title)
print("\r\nTotal No. Of Chapters = ", length)
while True:
print("\r\n---------------------------------------------------")
print("Enter 1 - To Download All Chapters")
print("Enter 2 - To Download A Part, Like 1-100 Or 400-650")
print("Enter 3 - To View Chapter Titles Before Download")
check = int(input("\r\nEnter Your Choice : "))
print("---------------------------------------------------")
if check == 3:
print("\r\nx-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x")
print("Enter 1 - To View All Chapter Titles")
print(" (The List Can Be Very Long When Chapters > 100)")
print("Enter 2 - To View A Specific Title")
temp1 = int(input("\r\nEnter Your Choice : "))
print("x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x")
if temp1 == 2:
temp2 = int(input("\r\nEnter Chapter Number : ")) - 1
print(iterList[temp2][0])
continue
if temp1 == 1:
print(iterList[0:][0])
continue
else:
print("\r\n### Invalid Choice ###")
continue
if check == 2:
print("\r\n===================================================")
print("**Note : \"First Chapter\" Starts From \"1\"")
print(" \"Last Chapter\" Ends At \"{0}\"".format(length))
start = int(input("\r\nEnter First Chapter : "))
end = int(input("Enter Last Chapter : "))
print("===================================================")
if start > 0 and end < length + 1:
if start < end or start == end:
start, end = start - 1, end - 1
return start, end
else:
print("Please Enter start And end Chapters Properly. Swapping start and end.")
print("start =", end, "end =", start)
start, end = end, start
return start, end
else:
print("\r\n**Please Enter start And end Chapters Properly.**\r\n")
continue
elif check == 1:
print("Okay, All Available Chpaters Will Be Downloaded.")
return start, end
else :
print("Invalid Choice. All Available Chapters Will Be Downloaded.")
return start, end
async def download(link, title):
global counter
try:
#####################
# Get, Pass & Select
pageIndividual = req.get(link)
s = bs(pageIndividual.text, "html5lib")
div = s.select_one("#chaptercontent")
# Create new div tag to add chapter title and content
chapter = s.new_tag("div")
chapterTitle = title
html_gen("h4", s, chapterTitle, chapter)
html_gen("hr", s, "", chapter)
# Remove href
for a in div.select("a"):
a['href'] = '#'
# Append to tag
chapter.append(div)
# Creates a chapter
c2 = epub.EpubHtml(title=chapterTitle, file_name=title+'.xhtml', lang='hr')
c2.content = chapter.encode("utf-8")
book.add_item(c2)
# Add to table of contents
book.toc.append(c2)
# Add to book ordering
book.spine.append(c2)
#print(chapter)
# Creates a chapter
print("Parsed Chapter :", title)
counter += 1
except KeyboardInterrupt as e:
print("Keyboard Interrupt")
print(e)
sys.exit()
except IndexError as e:
print(e)
print("Possibly Incorrect Link For Chapter", title)
print("Skipping Chapter", title)
except Exception as e:
print(e)
def save():
# Location Where File Will Be Saved
# Default Location Will Be The Place Where This Script Is Located
# To Change,
# 1 - Add The Location Inside The Empty pathToLocation
# Example 1 - Windows :
# pathToLocation = 'C:\\Users\\Adam\\Documents\\'
# Notice The Extra \ To Be Added Along With Every Original - This Is Compulsory For Every \
# Example 2 - Unix/POSIX Based(OS X, Linux, Free BSD etc) :
# pathToLocation = '/home/Adam/Documents/'
# Notice That No Extra / Are Added Along With Original
# OR
# 2 - Move This Script To, And Run From The Location To Be Saved
pathToLocation = ''
downloadDetails = '"' + title + '_' + str(start) + '_' + str(counter) + '.epub"'
saveLocation = pathToLocation + downloadDetails
print("Saving . . .")
# Saves Your EPUB File
epub.write_epub(saveLocation, book, {})
# Location File Got Saved
if pathToLocation == '':
print("Saved at", os.getcwd(), 'as', downloadDetails)
# Example : Saved at /home/Adam/Documents as "The Strongest System_0_3.epub"
else :
print("Saved at", saveLocation)
async def main():
get_iterList()
global start
global end
global counter
start, end = 1, 100#intro()
if end == length:
min_iterList = iterList[start:]
else:
min_iterList = iterList[start:end+1]
counter = start - 1
print(min_iterList)
#ws = stream.repeat(session)
xs = stream.iterate(min_iterList)
ys = stream.starmap(xs, download, ordered=True, task_limit=20)
#zs = stream.map(ys, process)
await ys
if counter < 0: counter = 0
# Add Navigation Files
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
# Defines CSS Style
style = 'p { text-align : left; }'
nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
# Adds CSS File
book.add_item(nav_css)
# About Novel
about.find('img').decompose() # Remove IMG tags
for a in about.select("a"): # Remove anchor tags
a['href'] = '#'
html_gen("hr", soup, "", about)
html_gen("h3", soup, "Description", about)
syn = synopsis.text.replace("Description","")
html_gen("p", soup, syn, about)
html_gen("hr", soup, "", about)
html_gen("h3", soup, "About This Download : ", about)
html_gen("p", soup, "Total Chapters = " + str(counter), about)
html_gen("p", soup, "No. Of Chapters That Raised Exceptions = " + str(len(err)), about)
if len(err) != 0:
html_gen("p", soup, "And They Are : ", about)
for i in err:
html_gen("li", soup, str(i), about)
html_gen("hr", soup, "", about)
# Create About Novel Page
c1 = epub.EpubHtml(title="About Novel", file_name='About_novel'+'.xhtml', lang='hr')
c1.content = about.encode('utf-8')
book.add_item(c1)
book.toc.insert(0, c1)
book.spine.insert(1, c1)
print("Created \"About Novel\" Page")
save()
if __name__=="__main__":
freeze_support()
book.set_language('en')
# Enter The Novel URL Here
novelURL = 'http://m.wuxiaworld.co/The-Magus-Era/'
novelChapURL = novelURL + 'all.html'
while novelURL == '':
print("Novel URL Not Provided Inside The Script.")
novelURL = str(input("Please Enter Novel URL : "))
print("\r\nNovel URL Set")
# Main Novel Page -- Get, Create Instance & Select
page = req.get(novelURL)
soup = bs(page.text, "html5lib")
about = soup.select_one('.synopsisArea_detail')
synopsis = soup.select_one('.review')
# Novel Chapters Page -- Get, Create Instance & Select
pageChap = req.get(novelChapURL)
so = bs(pageChap.text, "html5lib")
chapLi = so.select_one("#chapterlist")
# Book Title
title = soup.select_one('header span').text
book.set_title(title)
book.spine = ['nav']
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T09:39:31.793",
"Id": "392015",
"Score": "1",
"body": "Hey, welcome to Code Review! This question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for h... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T08:58:26.260",
"Id": "203390",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"web-scraping",
"asynchronous"
],
"Title": "Python3.x Download(async) + Process(bs4) + Save(EPUB)"
} | 203390 |
<p>I decided to make a stopwatch as I decided it would be useful, and also as a challenge to learn more about how forms work. I'd just like some simple advice as to anything I can do better, thank you.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Stopwatch
{
public partial class Form1 : Form
{
Timer timer = new Timer();
int seconds = 0;
int minutes = 0;
int hours = 0;
public Form1()
{
timer.Interval = 1000;
timer.Tick += Timer_Tick;
InitializeComponent();
}
private void Timer_Tick(object sender, EventArgs e)
{
IncrementStopwatch();
UpdateLabels();
}
private void IncrementStopwatch()
{
seconds++;
if (seconds == 60)
{
seconds = 0;
minutes++;
if (minutes == 60)
{
minutes = 0;
hours++;
}
}
}
private void UpdateLabels()
{
Seconds.Text = KeepStyle(seconds);
Minutes.Text = KeepStyle(minutes);
Hours.Text = KeepStyle(hours);
}
private string KeepStyle(int s)
{
if (s <= 9)
return "0" + s.ToString();
return s.ToString();
}
private void StartStopButton_Click(object sender, EventArgs e)
{
timer.Enabled = !timer.Enabled;
if (!timer.Enabled)
StartStopButton.Text = "Start";
else if (timer.Enabled)
StartStopButton.Text = "Stop";
}
private void ResetButton_Click(object sender, EventArgs e)
{
seconds = 0;
minutes = 0;
hours = 0;
UpdateLabels();
timer.Enabled = !timer.Enabled; // Reset timer so it ticks in 1 second.
timer.Enabled = !timer.Enabled;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T09:37:40.900",
"Id": "392013",
"Score": "0",
"body": "Could you add a screenshot?"
}
] | [
{
"body": "<p>Instead of: </p>\n\n<pre><code> private string KeepStyle(int s)\n {\n if (s <= 9)\n return \"0\" + s.ToString();\n return s.ToString();\n }\n</code></pre>\n\n<p>you can do:</p>\n\n<pre><code>s.ToString(\"00\");\n</code></pre>\n\n<p>See <a href=\"https://docs.mi... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T09:32:28.053",
"Id": "203392",
"Score": "2",
"Tags": [
"c#",
"winforms",
"timer"
],
"Title": "A 3 digit stopwatch"
} | 203392 |
<p>I need advise whether the approach I took is the optimal one (not sure whether this is the right 'stackExchange' site).</p>
<p>I have an MVC application, which is supposed to be able to render an HTML page uploaded by a user of the app (this is a 'preview your data' feature).
These HTML files are like templates into which I inject some (XML) data from the MVC app.</p>
<p>The input uploaded by the user is a zip package which contains HTML files, CSS files, images, some javascript etc. This is stored in the 'Resources' repository in my application. The input package is uploaded from time to time (rarely) by a single user, but it will be 'launched for data preview' by multiple users multiple times a day.</p>
<p><strong>Aspect 1:</strong></p>
<p>When the page is supposed to be generated, it hits the method below:</p>
<pre><code> public ActionResult Generate(int previewResourceId)
{
var provider = new TemplateProvider(this.settings, previewResourceId);
//finds the proper uploaded resource in repository
string originalHtml = provider.ProvideTemplateHtml(deployer);
//returns the content of the index.html
string updatedHtml = this.Engine.ProvidePreviewPage(originalHtml);
//injects the data into the page
return this.Content(updatedHtml, "text/html", Encoding.UTF8);
}
</code></pre>
<p>When the zip template is uploaded by the user, it is extracted to a folder. When the page is generated, the some XML data is injected to the content of the index.html and it is rendered.</p>
<p><strong>Question 1:<br>
Is it fine to return this.Content() with a manipulated html string, or are there better approaches?</strong></p>
<p><strong>Aspect 2:</strong></p>
<p>Now, the user's page will have references to the images, css, and scripts provided as relative paths, e.g. <code><script src=\"js/events.js\"></script></code>. Since I am not 'hosting' the page, and just rendering it, the relative paths will not work - therefore I have created an API endpoint which provides a referenced content.<br>
When the users page template zip is uploaded, upon extracting I do some manipulation of the links and simply replace the srcs and hrefs with something like this:
<code><script src=\"/MyPage/GetReferencedContent?rid=69&fn=js/events.js\"></script></code></p>
<p>The action is as follows:</p>
<pre><code> public ActionResult GetReferencedContent(int rid, string fn)
{
TemplateProvider provider = new TemplateProvider(this.settings, templateResourceId);
string filePath = Path.Combine(provider.GetTemplateRootFolder().FullName, referencedFileName);
if (!System.IO.File.Exists(filePath))
{
return this.HttpNotFound($"Resource not found on the server: {fn}");
//bonus question - is the HttpNotFound the proper error in this case, or should it be BadRequest?
}
return new FileStreamResult(fileStream: System.IO.File.Open(filePath, FileMode.Open), contentType: MimeMapping.GetMimeMapping(filePath));
}
</code></pre>
<p><strong>Question 2:<br>
Is it fine to return the referenced files like that? It will result in tens or even hundreds of Get requests for each time the page is rendered, and it will each time read a file from disk, I am a bit concerned with performance...</strong></p>
<p>The page will be accessed by probably not more than 30 users a day, and I expect that 'at peak hours' it will be rendered once every two-three minutes. It's an internal app with a very limited number of users.</p>
<p><strong>Aspect 3:</strong><br>
Since the user's page is not really 'hosted', but simply rendered, I don't see any better way to pass parameters&data to it, other than injecting them to the index.html page prior to rendering.</p>
<p>So, what I am currently doing is I am injecting xml strings into the 'head' section of the index.html as 'script' elements with a certain IDs, like so:</p>
<pre><code><head>
<script id="productId" type="text/plain">AaaaCh0o0!</script>
<script id="pageData" type="text/plain">[500kb - 1mb long xml string]</script>
</code></pre>
<p>And, wherever the users page needs data, their page is expected to call a javascript function <code>loadPageData()</code>. I inject the body of that function when the template is first uploaded, so that it looks as follows:</p>
<pre><code>function loadPageData() {
return $('#pageData').text();
}
</code></pre>
<p><strong>Question 3: Is there any better way of passing the parameters? And is there any significant overhead in injecting large amount of data string to the page header?</strong></p>
<p>It seems to work all OK, I am just concerned about performance (as I said, it is an internal app for limited number of users) and whether there is simpler way.
Any feedback to the design greatly appreciated.</p>
| [] | [
{
"body": "<p>Just a couple suggestions...</p>\n\n<p>It might be easier to setup sub-folders (dynamically) under Resources for each template that gets uploaded to store the associated files in. Then just tweak the links to point to that sub-folder. This way you don't have to serve up files manually and everythi... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T10:11:00.960",
"Id": "203394",
"Score": "0",
"Tags": [
"c#",
"html",
"asp.net-mvc"
],
"Title": "Rendering an html page uploaded by a user into MVC app"
} | 203394 |
<p>I have written a function which finds the largest prime factor of some number. This function works but the problem is that it is too slow. For instance, when I enter 600851475143 as a parameter, the process of finding largest prime factor lasts too long. How can I modify it so that it works faster?</p>
<pre><code>class test {
static addArray(someArray, member) {
for (var i = 0; i <= someArray.length; i++) {
if (i == someArray.length) {
someArray[i] = member;
return someArray;
}
}
}
static someLength(someArray) {
var i = 0;
while (someArray[i] !== undefined) {
var lastItem = i;
i++;
}
return i;
}
static testPrime(i) {
for (var k=2; k < i; k++) {
if (i % k == 0) {
return false;
}
}
return true;
}
}
var primeArray = [];
function largestPrime(n) {
for (var i=2; i < n; i++) {
//var k = n / i;
if (n % i == 0 && test.testPrime(i) == true) {
test.addArray(primeArray, i);
n == n / i;
}
}
return primeArray[test.someLength(primeArray) - 1];
}
document.write(largestPrime(600851475143));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-10T13:15:41.837",
"Id": "396000",
"Score": "0",
"body": "Hmm, is n == n / i; your problem? This statement does nothing, I think you meant n=n/i;"
}
] | [
{
"body": "<p>[Ported from SO]</p>\n\n<p>Alright, before we go into that, let's get a little bit of theory sorted. The way you measure the time a particular piece of code takes to run is, mathematically, denoted by the <code>O(n)</code> notation (big-o notation) where <code>n</code> is the size of the input. </... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T11:18:01.353",
"Id": "203396",
"Score": "0",
"Tags": [
"javascript",
"time-limit-exceeded",
"primes"
],
"Title": "Largest prime factor function"
} | 203396 |
<p>Question- </p>
<blockquote>
<p>In short question says that you have N bus stops and K bus routes.
Every bus routes is linked to two bus stops. Each route has some cost
of travelling. It says one person visit any one bus stop(N-1 bus stop
require N-1 person). Task of person is to start from bus stop 1 and
visit his bus stop stay there for complete day and come back. One
complete journey from bus stop 1 -> bust stop x and return path need
to pay some cost. This cost is payable by one head who appointed these
person. So what is the minimum cost is to be paid by this head.</p>
</blockquote>
<pre><code>Input
</code></pre>
<p>The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case begins with a line containing exactly two integers P and Q, 1 <= P,Q <= 1000000. P is the number of stops including CCS and Q the number of bus lines. Then there are Q lines, each describing one bus line. Each of the lines contains exactly three numbers - the originating stop, the destination stop and the price. The CCS is designated by number 1. Prices are positive integers the sum of which is smaller than 1000000000. You can also assume it is always possible to get from any stop to any other stop</p>
<pre><code>Test Case
2
2 2
1 2 13
2 1 33
4 6
1 2 10
2 1 60
1 3 20
3 4 10
2 4 5
4 1 50
</code></pre>
<p>I am solving the SPOJ question <a href="https://www.spoj.com/problems/INCARDS/" rel="nofollow noreferrer">INCARDS</a>. I am solving this problem using Dijkstra algorithm. According to algorithm I used, I run Dijkstra on directed and reverse of the same directed graph. And at the end I add up the cost array I get from the both.</p>
<pre><code>//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;
import java.math.*;
class Solution{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
public String readLine() throws IOException
{
byte[] buf = new byte[128]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
}
static int[][] arr;
static int[][] rev;
public static void main(String []argh) throws Exception{
Reader br = new Reader();
int t= br.nextInt();
for(int aa=0; aa<t; aa++){
int p= br.nextInt();
int q= br.nextInt();
arr = new int[p+1][p+1];
rev = new int[p+1][p+1];
for(int qq= 1; qq<=q; qq++){
int o= br.nextInt();
int d= br.nextInt();
int pp= br.nextInt();
arr[o][d]= pp;
rev[d][o]= pp;
}
int[] data= dijkstra(arr, p);
int[] data1= dijkstra(rev, p);
int sum =0;
for(int i=2; i<=p; i++){
sum += data[i] + data1[i];
}
System.out.println(sum);
}
}
static Queue<Data> integerPQ;
static int[] currPath;
static int[] distMap;
static int[] visited;
private static int[] dijkstra(int[][] arr, int p) {
currPath = new int[p+1];
distMap = new int[p+1];
visited = new int[p+1];
integerPQ = new PriorityQueue<>();
for(int zz=1; zz<=p; zz++) distMap[zz]= Integer.MAX_VALUE;
integerPQ.add(new Data(1, 0));
while(integerPQ.peek() != null) {
Data dd= integerPQ.poll();
if(distMap[dd.ind] > dd.cost) {
distMap[dd.ind] = dd.cost;
for(int kk= 1; kk<=p; kk++) {
if(arr[dd.ind][kk] != 0) {
int totalPrice= arr[dd.ind][kk] + dd.cost;
if(distMap[kk] > totalPrice && visited[kk] == 0) {
integerPQ.add(new Data(kk, totalPrice));
}
}
}
visited[dd.ind] = 1;
}
}
return distMap;
}
private static class Data implements Comparable<Data>{
int ind;
int cost;
public Data(int ind, int cost){
this.ind= ind;
this.cost= cost;
}
public int compareTo(Data d){
if(d.cost > this.cost)return -1;
else if(d.cost < this.cost) return 1;
else {
if(d.ind > this.ind) return -1;
else if(d.ind < this.ind) return 1;
else return 0;
}
}
}
}
</code></pre>
<p>Now coming to time complexity: it has TC \$O(V+E) \rightarrow O(N)\$ considering. I am getting Time Limit Exceeded when I submit. I tried a lot to figure out the issue. But I could find none. It looks each node is running at most only once. I don't know where it is consuming time, even I am using Fast I/O.</p>
<p>Can someone point out issues prevailing in my solution so that I can learn new facts about optimizing codes and algorithms?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T07:40:43.910",
"Id": "392116",
"Score": "0",
"body": "Welcome to Code Review! Could you please [edit] to add a short summary of the problem statement? You can keep the link as a reference, but your question does need to be complete... | [
{
"body": "<p>Consider using other(sparse) graph representation. You are getting O(V*V) since you check for all possible connections (<code>arr[dd.ind][*]</code>), even when actual edge count is low.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T11:37:48.313",
"Id": "203398",
"Score": "4",
"Tags": [
"java",
"performance",
"algorithm",
"time-limit-exceeded"
],
"Title": "INCARDS SPOJ challenge"
} | 203398 |
<p>I recently started writing REST API, I wanted to have a proper structure of project and an approach which is more readable and make more sense interms of organising in a logical order. I took advantage of namespace and I have put endpoints of each name space into separate python package.</p>
<pre><code>project
|______init__.py
|____api
| |______init__.py
| |____base
| | |______init__.py
| | |____resources.py
| |____hello
| | |______init__.py
| | |____resources.py
| |____routes.py
</code></pre>
<p><strong>project/__init__.py</strong></p>
<pre><code>from flask import Flask
def register_blueprints(app):
# Since the application instance is now created, register each Blueprint
# with the Flask application instance (app)
from project.api import api_blueprint
from project.api import base_api_blueprint
app.register_blueprint(api_blueprint)
app.register_blueprint(base_api_blueprint)
def create_app(config_filename=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile(config_filename)
register_blueprints(app)
return app
</code></pre>
<p><strong>project/api/__init__.py</strong></p>
<pre><code>from flask import Blueprint
api_blueprint = Blueprint('api', __name__, template_folder='templates')
base_api_blueprint = Blueprint('base_api', __name__)
from . import routes
from .hello import resources
from .base import resources
</code></pre>
<p><strong>project/api/routes.py</strong></p>
<pre><code>from flask_restplus import Resource
from . import api_blueprint, base_api_blueprint
base_api = Api(base_api_blueprint, catch_all_404s=True, prefix='/api', version='1.0', title='Sample API',
description='A sample API',
)
base_api.namespaces.pop(0)
base_api_ns = base_api.namespace('todos', description='base api namespace.')
hello_api_ns = base_api.namespace('hello', description='Hello World api.')
</code></pre>
<p><strong>project/api/base/resources.py</strong></p>
<pre><code>from flask_restplus import Resource
from ..routes import base_api_ns
@base_api_ns.route('/base', endpoint='base-endpoint')
class BaseResource(Resource):
def get(self):
return {"from": "base"}
</code></pre>
<p><strong>project/api/hello/resources.py</strong></p>
<pre><code>from flask_restplus import Resource
from ..routes import hello_api_ns
@hello_api_ns.route('/world', endpoint='world-endpoint')
class BaseResource(Resource):
def get(self):
return {"hello": "world"}
</code></pre>
<p>the rest api web app, has api that deals with two different type of tasks <strong>base</strong> and <strong>hello</strong> so I have segregated to a separate package and used different name space for each.</p>
<p>having a second <a href="http://flask-restplus.readthedocs.io/en/stable/api.%E2%80%A6" rel="nofollow noreferrer">API</a> object of <code>api_blueprint</code> would rather make more sense but that seems not work maybe due to a bug in flask restplus.
the swagger finally renders up like this:
<a href="https://i.stack.imgur.com/30zPF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/30zPF.png" alt="enter image description here"></a>
Any input in implementation or improvement will be highly appreciated.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T12:38:13.393",
"Id": "203399",
"Score": "4",
"Tags": [
"python",
"rest",
"flask"
],
"Title": "REST API with flask structure and implementation approach"
} | 203399 |
<p>I was asked this question in an interview. </p>
<blockquote>
<p>You are given an array consisting of N integers. You need to determine whether any permutation of a given array exists such that the sum of all subarrays of length K are equal. N is divisible by K i.e. N mod K = 0.<br>
If the array is [1,2,1,3,2,3] and K = 2, it is False.<br>
If the array is [1,2,1,3,2,3] and K = 3, it is True. </p>
</blockquote>
<p>My logic was this. </p>
<blockquote>
<ol>
<li>If N == K, return True. </li>
<li>Else store each of the distinct element in the array in a
dictionary. If the number of distinct elements in the dictionary
is greater than K, return False. </li>
<li>Else store the count of each distinct element in the dictionary. </li>
<li>If the count of any distinct element is less than (N/K), return False. </li>
<li>Finally return True.</li>
</ol>
</blockquote>
<p>Here is my code in Python: </p>
<pre><code>def check(nums, n, k):
if n == k:
return True
else:
my_dict = {}
for i in nums:
if i not in my_dict:
my_dict[i] = 1
else:
my_dict[i] += 1
if len(my_dict) > k:
return False
count = int(n/k)
for i,j in my_dict.items():
if j < count:
return False
return True
</code></pre>
<p>Am I doing the right approach ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T16:09:43.997",
"Id": "392039",
"Score": "0",
"body": "How about `[1, 2, 3, 4]`, and `K = 2`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T19:37:52.410",
"Id": "392069",
"Score": "0",
"b... | [
{
"body": "<p>Use the <a href=\"https://devdocs.io/python~3.6/library/collections#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> instead of keeping a count yourself.</p>\n\n<p>When you have counted all the elements from the list, check if any of their counts is not a fact... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T13:32:49.790",
"Id": "203401",
"Score": "0",
"Tags": [
"python",
"algorithm",
"array"
],
"Title": "Determine whether any permutation of a given array exists such that the sum of all subarrays of length K are equal"
} | 203401 |
<p>I'm creating a rest api using Spring which utilize javax.crypto as library to do some encryption stuff. While everything works well, I'm curious whether the error handling like this is acceptable or not?<br></p>
<pre><code>@Slf4j
@Component
public class RSAEncryption {
private static final String ENCRYPTION_ALGORITHM = "RSA";
private static final String CHARSET = "UTF-8";
public KeyPair generateKeyPair() {
final int keySize = 2048;
KeyPairGenerator keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance(ENCRYPTION_ALGORITHM);
keyPairGenerator.initialize(keySize);
return keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Invalid algorithm supplied: [{}]", e.getMessage());
return null;
}
}
public PublicKey readPublicKey(byte[] keyBytes)
{
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes);
try {
KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(publicSpec);
return publicKey;
} catch (InvalidKeySpecException e) {
LOGGER.error("Failed to generate public key from spec: [{}]", e.getMessage());
return null;
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Invalid algorithm supplied: [{}]", e.getMessage());
return null;
}
}
public PrivateKey readPrivateKey(byte[] keyBytes)
{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
try {
KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} catch (InvalidKeySpecException e) {
LOGGER.error("Failed to generate private key from spec: [{}]", e.getMessage());
return null;
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Invalid algorithm supplied: [{}]", e.getMessage());
return null;
}
}
public String encrypt(PrivateKey privateKey, String message) {
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] bytes = cipher.doFinal(message.getBytes(CHARSET));
return new String(Base64.getEncoder().encode(bytes));
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Invalid algorithm supplied: [{}]", e.getMessage());
return null;
} catch (NoSuchPaddingException e) {
LOGGER.error("Invalid byte padding: [{}]", e.getMessage());
return null;
} catch (InvalidKeyException e) {
LOGGER.error("Invalid key: [{}]", e.getMessage());
return null;
} catch (UnsupportedEncodingException e) {
LOGGER.error("Invalid encoding: [{}]", e.getMessage());
return null;
} catch (IllegalBlockSizeException e) {
LOGGER.error("Invalid byte's block size: [{}]", e.getMessage());
return null;
} catch (BadPaddingException e) {
LOGGER.error("Bad byte's padding: [{}]", e.getMessage());
return null;
}
}
public String decrypt(PublicKey publicKey, byte[] encrypted) {
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(encrypted);
return new String(bytes);
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Invalid algorithm supplied: [{}]", e.getMessage());
return null;
} catch (NoSuchPaddingException e) {
LOGGER.error("Invalid byte padding: [{}]", e.getMessage());
return null;
} catch (InvalidKeyException e) {
LOGGER.error("Invalid key: [{}]", e.getMessage());
return null;
} catch (UnsupportedEncodingException e) {
LOGGER.error("Invalid encoding: [{}]", e.getMessage());
return null;
} catch (IllegalBlockSizeException e) {
LOGGER.error("Invalid byte's block size: [{}]", e.getMessage());
return null;
} catch (BadPaddingException e) {
LOGGER.error("Bad byte's padding: [{}]", e.getMessage());
return null;
} catch (IllegalBlockSizeException e) {
LOGGER.error("Illegal block size: [{}]", e.getMessage());
return null;
}
}
}
</code></pre>
<p><br>
and then the calling Service :</p>
<pre><code>@Service
@Slf4j
public class CommonService {
@Autowired
private RSAEncryption rsaEncryption;
private RSAKey checkKeysExistence(String key) throws IOException {
boolean exist;
S3Object publicKeyS3 = null;
S3Object privateKeyS3 = null;
try {
publicKeyS3 = s3Client.getObject("bucket", key);
privateKeyS3 = s3Client.getObject("bucket", key);
exist = true;
} catch (AmazonS3Exception e) {
if(e.getStatusCode() == 404) {
exist = false;
} else {
throw e;
}
}
if(exist) {
byte[] publicKeyBytes = publicKeyS3.getObjectContent().readAllBytes(); // should I catch IOException here or add to method signature?
byte[] privateKeyBytes = privateKeyS3.getObjectContent().readAllBytes();
PublicKey publicKey = rsaEncryption.readPublicKey(publicKeyBytes);
PrivateKey privateKey = rsaEncryption.readPrivateKey(privateKeyBytes);
return new RSAKey(publicKey, privateKey);
} else {
KeyPair keyPair = rsaEncryption.generateKeyPair();
if(keyPair == null) {
throw new MyOwnException2();
} else {
addFileToS3(.....)
addFileToS3(.....);
return new RSAKey(keyPair.getPublic(), keyPair.getPrivate());
}
}
}
public String encrypt(String namespace, String appId, String msg) {
try {
RSAKey rsaKey = checkKeysExistence("private.der");
String encrypted = rsaEncryption.encrypt(rsaKey.getPrivateKey(), msg);
return encrypted;
} catch (IOException e) {
throw new MyOwnException();
}
}
public String decrypt(String namespace, String encrypted) {
try {
RSAKey rsaKey = checkKeysExistence("public.der");
String solve = rsaEncryption.decrypt(rsaKey.getPublicKey(), encrypted);
return solve;
} catch (IOException e) {
throw new MyOwnException();
}
}
}
</code></pre>
<p>any advice will be much appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T13:56:05.827",
"Id": "392026",
"Score": "1",
"body": "How do you handle `MyOwnException`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T19:03:29.377",
"Id": "392067",
"Score": "2",
"body... | [
{
"body": "<p>The general principle seems a bit odd and more work than necessary.</p>\n\n<p>Basically, in case of an error, you perform the following steps:</p>\n\n<ul>\n<li>catch and log exception</li>\n<li>return null</li>\n<li>check for null in the caller</li>\n<li>throw MyOwnException in the caller</li>\n<l... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T13:41:15.420",
"Id": "203402",
"Score": "1",
"Tags": [
"java",
"error-handling",
"cryptography",
"spring"
],
"Title": "Spring API that performs RSA encryption with exception handling"
} | 203402 |
<p>Hexadecimal <code>0xdead, 0xbeef</code> are the magic numbers because they're also English words.
I decided to find such words as many as possible. How to do it? We need large English text let's say <a href="http://www.gutenberg.org/ebooks/4300" rel="nofollow noreferrer">Ulysses by James Joyce</a> and a program which extracts all words consists of hexadecimal digits. For simplicity, I decided to drop leet-language support. It dramatically shrinks the range but keeps real words only. </p>
<p>The code below extract magic numbers from given text and prints them to stdout in lower case </p>
<pre><code>#include <ctype.h>
#include <stdio.h>
#define MAX_LEN 256
int process_file(FILE* file);
int main(int argc, char* argv[]) {
if (argc == 1) {
process_file(stdin);
} else {
size_t i = 0;
char* filename;
FILE* file;
int err;
while ((filename = argv[++i]) != NULL) {
file = fopen(filename, "r");
if (!file) {
perror("fopen() failed");
return 1;
}
err = process_file(file);
fclose(file);
if (err) {
return 2;
}
}
}
return 0;
}
int process_file(FILE* file) {
char word[MAX_LEN];
size_t p = 0;
int c;
while (1) {
c = getc(file);
if (isspace(c) || c == EOF) {
/* end of word or end of emptiness */
if (p > 0 && p < MAX_LEN && p % 2 == 0) {
word[p] = 0;
printf("%s\n", word);
}
if (c == EOF) {
break;
}
p = 0;
continue;
}
if (p > MAX_LEN - 1) {
continue;
}
if ((c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { /* abcdef ABCDEF */
word[p++] = tolower(c);
} else {
/* skip this word */
p = MAX_LEN;
}
}
if (feof(file)) {
return 0;
}
if (ferror(file)) {
perror("i/o error occurred");
}
return 1;
}
</code></pre>
<p>Commands </p>
<pre><code>echo "Dead of being fed with beef for a decade" | ./deadbeaf | sort | uniq
</code></pre>
<p>should give</p>
<pre><code>beef
dead
decade
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T13:41:34.637",
"Id": "392197",
"Score": "1",
"body": "\"magic numbers because they're also English words\" --> Why does output not include `\"fed\"`. I see that is because code has `&& p % 2 == 0`, yet my questions is why choose th... | [
{
"body": "<p>It is customary to put helper functions first and <code>main()</code> last, to avoid having to write forward declarations like <code>int process_file(FILE* file);</code>.</p>\n\n<p><code>process_file()</code> is a very generic name. I suggest renaming it to <code>print_hex_words()</code>.</p>\n\n... | {
"AcceptedAnswerId": "203418",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T14:19:10.987",
"Id": "203404",
"Score": "2",
"Tags": [
"c",
"file"
],
"Title": "Deadbeef : finding all words made of hexadecimal digits"
} | 203404 |
<p>I am working on an 2048 AI and this is my code so far.</p>
<p>In the game 2048 you have a 4x4 grid in that some random so named tiles spawn.
Each tile has a number. The lowest number is 2.
By using the left, right, up and down-key you can move all tiles into the specified direction. If two tiles with the same number "collide" they merge into one and sum up there numbers.</p>
<p>Example:</p>
<pre><code> ___ ___ ___ ___
|___|___|___|_2_|
|___|___|_2_|___|
|___|___|___|_2_|
|___|___|___|___|
DOWN
___ ___ ___ ___
|___|___|___|___|
|___|___|___|___|
|___|___|___|___|
|___|___|_2_|_4_|
</code></pre>
<p>You can get all needed files on <a href="https://github.com/codeglow/2048-AI/tree/ff1050a9ae5523edaa1491104de119e685cfc76b" rel="nofollow noreferrer">Github</a>. My AI uses the Minimax-algorithm to calculate the best move.</p>
<p>I've tested it <a href="https://gabrielecirulli.github.io/2048/" rel="nofollow noreferrer">here</a> and got scores around 10,000 Points with getting the 1024-tile.</p>
<pre><code>import pyautogui
import collections
import operator
import math
import time
import cv2
import numpy as np
import random
game = [0] * 16
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
step = 6
def printGame(game=game):
print('')
for i in range(3):
print(end=' ')
for j in range(3):
print(str(game[i * 4 + j] if game[i * 4 + j] else '').center(4), '| ', end='')
print(str(game[i * 4 + 3] if game[i * 4 + 3] else '').center(4))
print('------|------|------|------')
print(end=' ')
for j in range(3):
print(str(game[12 + j] if game[12 + j] else '').center(4), '| ', end='')
print(str(game[12 + 3] if game[12 + 3] else '').center(4))
print('')
def getTiles():
tiles = {}
screen = cv2.cvtColor(np.array(pyautogui.screenshot()), cv2.COLOR_BGR2GRAY)
for tileNumber in [0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
template = cv2.imread('tile' + str(tileNumber) + '.png', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
locations = np.where(res >= .8)
for location in zip(*locations[::-1]):
location = pyautogui.center((location[0], location[1], w, h))
tiles[round(location[0] / 100), round(location[1] / 100)] = tileNumber
od = collections.OrderedDict(sorted(tiles.items()))
i = 0
for k, v in od.items():
game[i % 4 * 4 + math.floor(i / 4)] = v
i += 1
def ij(direction, i, j, offset=0):
if direction == UP:
return (3 - j - offset) * 4 + i
elif direction == DOWN:
return (j + offset) * 4 + i
elif direction == LEFT:
return i * 4 + 3 - j - offset
elif direction == RIGHT:
return i * 4 + j + offset
def move(game, direction, step=step):
tmpgame = game.copy()
for i in range(4):
lj = -1
for j in range(4):
if game[ij(direction, i, j)] != 0:
if lj > -1 and game[ij(direction, i, j)] == game[lj]:
game[lj] = 0
game[ij(direction, i, j)] *= 2
lj = -1
else:
lj = ij(direction, i, j)
for i in range(4):
l = []
for j in range(4):
l.append(game[ij(direction, 3 - i, 3 - j)])
l = [x for x in l if x != 0]
while len(l) < 4:
l.append(0)
for j in range(4):
game[ij(direction, 3 - i, 3 - j)] = l[j]
if tmpgame == game:
return 0
elif step > 0:
return multispawn(game, step)
else:
return sum(game) * game.count(0)
def multimove(game, step):
l = []
for i in range(4):
l.append(move(game.copy(), i, step))
return max(l)
def spawn(game, tile, i, j, step=step):
game[i * 4 + j] = 2
if step > 0:
return multimove(game, step - 1)
else:
return sum(game) * game.count(0)
def multispawn(game, step):
l = []
for i in range(4):
for j in range(4):
if game[i * 4 + j] == 0:
l.append(spawn(game.copy(), 2, i, j, step - 1))
l.append(spawn(game.copy(), 4, i, j, step - 1))
if 0 in l:
return 0
if len(l) == 0:
if step > 0:
return multimove(game, step - 1)
else:
return sum(game) * game.count(0)
else:
return min(l)
def main():
time.sleep(2)
while True:
getTiles()
printGame()
count = {}
count['up'] = move(game.copy(), UP)
print('up', count['up'])
count['down'] = move(game.copy(), DOWN)
print('down', count['down'])
count['left'] = move(game.copy(), LEFT)
print('left', count['left'])
count['right'] = move(game.copy(), RIGHT)
print('right', count['right'])
count = [x for x,y in count.items() if y == max(count.values())]
pyautogui.press(count[random.randint(0, len(count) - 1)])
time.sleep(0.2)
if __name__ == '__main__':
main()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T14:49:35.170",
"Id": "203405",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"ai",
"2048"
],
"Title": "2048 AI in Python 3"
} | 203405 |
<p>I have a function that calculates the biggest number in an array after doing the following:</p>
<pre><code>arrayManipulation(4, [[2, 3, 603], [1, 1, 286], [4, 4, 882]])
</code></pre>
<p>The array initially consists of only zeroes. The first parameter tells what the length of the array of 0s should be. </p>
<p>Here it's 4, so <code>[0,0,0,0]</code></p>
<p>The second parameter is an array of arrays. Each nested array has 3 values. The start index, last index and the value to add to the <code>zeroArray</code> between the two indices. The <code>zeroArray</code> index starts from 1.</p>
<p>For example, in the beginning the zero array is [0,0,0,0]. Then from the nested array <code>[2, 3, 603]</code>, add 603 at indices from 2 to 3. So the zero array becomes <code>[0,603,603,0]</code>. Then the second nested array is used. This is done till all the nested arrays are used.</p>
<p>After that's done, I need to find the biggest number in the zeroArray(its value now is <code>[ 286, 603, 603, 882]</code>) which here is 882.</p>
<p>I am trying this <a href="https://www.hackerrank.com/challenges/crush/problem" rel="nofollow noreferrer">here</a>, but it timed out.</p>
<pre><code>function arrayManipulation(n, operations) {
let zeroArray = Array(n);
zeroArray.fill(0, 0, zeroArray.length);
let biggest = 0;
for (let j = 0; j < operations.length; j++) {
let startIndex = operations[j][0];
let endIndex = operations[j][1];
let number = operations[j][2];
for (let k = startIndex; k <= endIndex; k++) {
zeroArray[k - 1] += number;
if (biggest < zeroArray[k - 1]) {
biggest = zeroArray[k - 1];
}
if (k == endIndex)
console.log(startIndex, endIndex, number, JSON.parse(JSON.stringify(zeroArray)));
}
}
console.log(biggest);
return biggest;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T15:41:04.720",
"Id": "392037",
"Score": "0",
"body": "I tested the code and it didn't timedout. Can you may give an larger example input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T15:46:47.773",... | [
{
"body": "<p>The challenge only asks for the biggest number after all operations.\nPrinting the complete array after each operation might cause it to fail – \neither by the unexpected output or by the time spent for the log operation.</p>\n\n<p>Also, determining the maximum after each operation is inefficient,... | {
"AcceptedAnswerId": "203414",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T14:56:21.443",
"Id": "203406",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Find biggest number in array"
} | 203406 |
<p>I am currently working on the implementation of Event System on a game engine. I have zero experience in Event System implementation or the patterns that are used. What I have done is what I've seen online. This is also the first time I am posting here, so apologies if I've accidentally violated any rules for posting.</p>
<p>Currently the system is capable sending event using <code>EventDispatcher</code>, while <code>EventListener</code> is capable of receiving those events and pass to a function bounded to it. My current focus is to make sure my implementations are exception safe (as much as possible).</p>
<p>Here's the general task of each class:</p>
<ul>
<li><strong><code>EventDispatcher</code></strong>: Dispatch events to the list of <code>EventListeners</code>.</li>
<li><strong><code>EventListener</code></strong>: Receives notification from <code>EventDispatcher</code> and calls a function stored in <code>EventDispatcher</code>.</li>
<li><strong><code>EventHandler</code></strong>: The middle man. Keeps track of a list of <code>EventDispatchers</code> and their attached <code>EventListeners</code>.</li>
</ul>
<h1>Concern</h1>
<p>My biggest concern was that <code>EventListener</code> and <code>EventDispatcher</code> is stored in side other classes as member variables. For example, <code>EventListener</code> can be stored inside an AI class to listen from the dispatcher in Player class. Trouble comes when the AI is destructed, taking out the <code>EventListener</code> with it. Therefore, <code>EventDispatcher</code> would be accessing deleted memory.</p>
<h1>My solution</h1>
<p>So, I created <code>EventHandler</code> to keep track of the <code>EventDispatchers</code> and their <code>EventListeners</code>. If a <code>EventDispatcher</code> is destructed, it will remove all the <code>EventListeners</code> associated with it. If a <code>EventListener</code> is destructed, it will detach itself from the <code>EventDispatcher</code> and <code>EventHandler</code>.</p>
<h1>Questions</h1>
<ol>
<li>Should I do away <code>EventHandler</code> and have <code>EventListener</code> to keep a pointer to <code>EventDispatcher</code>, and move all the functions and list of <code>EventListener</code> to <code>EventDispatcher</code>?</li>
<li>Other than <code>EventHandler</code> being deleted (not very concern of this at the moment), would there still be memory leaked or invalid data access?</li>
<li>When should I delete the fired events? And who should be responsible for it?</li>
</ol>
<h1>Code sample</h1>
<p>I would appreciate if anyone could answer my questions or points out any flaws in my implementation as I am really unsure what would be the underlying issues.</p>
<p>Assuming I have all the necessary class and libraries header, here are my implementations. Also the implementations are likely not following Rule of 3/5 as I need to get the basics to work first.</p>
<p>EventListener.cpp</p>
<pre><code>using FuncCallback = std::function<void(Event*)>;
EventListener::EventListener()
:handler{ nullptr } {}
EventListener::EventListener(EventHandler *h)
:handler{ h } {}
// Detach from the handler
EventListener::~EventListener()
{
if (handler)
handler->RemoveListener(this);
}
void EventListener::AttachHandler(EventHandler *h)
{
// Removes previously bounded handler
if (handler && (handler != h))
handler->RemoveListener(this);
handler = h;
}
void EventListener::DetachHandler()
{
handler = nullptr;
}
void EventListener::Bind(EventListener::FuncCallback f)
{
func = f;
}
void EventListener::OnNotify(Event *e)
{
func(e);
}
</code></pre>
<p>EventDispatcher.cpp</p>
<pre><code>EventDispatcher::~EventDispatcher()
{
handler.ClearDispatcher(this);
}
void EventDispatcher::MessageListener(std::list<EventListener*>& listeners, Event *e)
{
// Dispatch events to the listeners
for (EventListener* listener : listeners)
{
listener->OnNotify(e);
}
}
</code></pre>
<p>EventHandler.cpp</p>
<pre><code>void EventHandler::RegisterListener(EventDispatcher *d, EventListener *l)
{
// Add to the dispatcher
dl_map[d].push_back(l);
// Pass handler to listener
l->AttachHandler(this);
}
void EventHandler::RemoveListener(EventListener *l)
{
for (auto& key_it : dl_map)
{
// Get the listeners
auto& list = key_it.second;
// Find the specific listener
auto val_it = std::find(list.begin(), list.end(), l);
// Remove the listener from the list, if found
if (val_it != list.end())
{
list.erase(val_it);
break;
}
}
}
void EventHandler::ClearDispatcher(EventDispatcher *d)
{
auto& it = dl_map.find(d);
if (it != dl_map.end())
{
for (auto& listener : it->second)
{
listener->DetachHandler();
}
}
}
void EventHandler::QueueEvent(Event *e)
{
waitQueue.push_back(e);
}
void EventHandler::FireAllQueuedEvents()
{
std::cout << "Firing events" << std::endl;
activeQueue.splice(activeQueue.begin(), waitQueue);
for (Event *e : activeQueue)
{
// Send event to each dispatcher
for (auto& key_it : dl_map)
{
// Dispatcher send messages to listeners
auto& dispatcher = key_it.first;
dispatcher->MessageListener(key_it.second, e);
}
}
// TEMP, looking for a way to improve this
for (Event *e : activeQueue)
delete e;
activeQueue.clear();
}
</code></pre>
<p>Sample usage:</p>
<pre><code>struct Position
{
float x, y, z;
};
struct AI
{
EventListener movement_listener;
AI (EventHandler *h)
:movement_listener{ h }
{
movement_listener.Bind(std::bind(&AI::HandleMovement, this, std::placeholders::_1));
}
void HandleMovement(Event *e)
{
Position* pos = static_cast<Position*>(e->GetData());
std::cout << "Position: " << pos->x << ", " << pos->y << ", " << pos->z << std::endl;
}
};
int main(){
EventHandler AI_EVENT_HANDLER;
// Whenever an AI moves, dispatch the event with the movement informations
EventDispatcher ai_movement_dispatcher;
AI normal_ai{ &AI_EVENT_HANDLER };
EventListener independent_listener{ &AI_EVENT_HANDLER };
independent_listener.Bind(
[](Event*e){
Position* pos = static_cast<Position*>(e->GetData());
std::cout << "Position: " << pos->x << ", " << pos->y << ", " << pos->z << std::endl;
}
);
AI_EVENT_HANDLER.RegisterListener(&ai_movement_dispatcher, &normal_ai.movement_listener);
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{1,2,3} });
AI_EVENT_HANDLER.FireAllQueuedEvents();
AI_EVENT_HANDLER.RegisterListener(&ai_movement_dispatcher, &independent_listener);
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 1,2,3 } });
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 3,4,5 } });
AI_EVENT_HANDLER.FireAllQueuedEvents();
AI_EVENT_HANDLER.RemoveListener(&normal_ai.movement_listener);
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 1,2,3 } });
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 3,4,5 } });
AI_EVENT_HANDLER.FireAllQueuedEvents();
{
AI oos_ai{ &AI_EVENT_HANDLER };
AI_EVENT_HANDLER.RegisterListener(&ai_movement_dispatcher, &oos_ai.movement_listener);
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 1,2,3 } });
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 3,4,5 } });
AI_EVENT_HANDLER.FireAllQueuedEvents();
} // oos_ai out of scope, therefore triggers the destructor and detach itself from the handler
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 1,2,3 } });
AI_EVENT_HANDLER.QueueEvent(new Event{ new Position{ 3,4,5 } });
AI_EVENT_HANDLER.FireAllQueuedEvents();
</code></pre>
<p>Sample output</p>
<pre class="lang-none prettyprint-override"><code>Firing event
Position: 1, 2, 3 // normal_ai
Firing event // added independent_listener
Position: 1, 2, 3 // normal_ai
Position: 1, 2, 3 // independent_listener
Position: 3, 4, 5 // normal_ai
Position: 3, 4, 5 // independent_listener
Firing event // normal_ai removed at this point
Position: 1, 2, 3 // independent_listener
Position: 3, 4, 5 // independent_listener
Firing event // added oos_ai within another scope
Position: 1, 2, 3 // independent_listener
Position: 1, 2, 3 // oos_ai
Position: 3, 4, 5 // independent_listener
Position: 3, 4, 5 // oos_ai
Firing event // oos_ai removed as it went out of scope
Position: 1, 2, 3 // independent_listener
Position: 1, 2, 3 // independent_listener
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T22:49:25.130",
"Id": "392452",
"Score": "0",
"body": "Would be nice to also have the h/hpp-files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T23:11:53.633",
"Id": "392454",
"Score": "0",
... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T15:21:26.383",
"Id": "203408",
"Score": "5",
"Tags": [
"c++",
"event-handling"
],
"Title": "C++ game engine event system implementation"
} | 203408 |
<p>I've been trying to understand Dynamic Programming lately, here's the question I just attempted:</p>
<blockquote>
<p>You are given an array A of N positive integer values. A subarray of this array is called an Odd-Even subarray if the number of odd integers in this subarray is equal to the number of even integers in this subarray.</p>
<p>Find the number of Odd-Even subarrays for the given array.</p>
</blockquote>
<p>Solving this on hackerearth, <a href="https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/odd-even-subarrays-72ad69db/description/" rel="nofollow noreferrer">here</a>!</p>
<p>I immediately connected this with Matrix-Chain Multiplication from CLRS, which tries all sub-arrays. To optimise it for this question, I used the <code>numEvens</code> array to track number of even ints from index 0 to i. This takes \$O(n)\$ time. This way I don't have to actually <em>scan</em> every sub-array to see if it's Odd-Even or not. <code>evensIJ</code> tells me how many even ints are in <code>arr[i..j]</code>. I still have to <em>visit</em> every sub-array though, thus the \$O(n^2)\$ nested loops, where <code>l</code> is the length of the sub-array.</p>
<p>Here's the code, it takes as input the array <code>arr</code> of ints and it's size <code>n</code>:</p>
<pre><code>long int numArrs(int arr[], int n)
{
int numEvens[n], l, i, j, evensIJ;
if (arr[0] & 1) numEvens[0] = 0;
else numEvens[0] = 1;
for (i = 1; i < n; i++)
numEvens[i] = (arr[i] & 1) ? (numEvens[i - 1]) : (1 + numEvens[i - 1]);
long int count = 0;
for (l = 2; l <= n; l += 2)
{
if (l > n) break;
for (i = 0; i < n - l + 1; i++)
{
j = i + l - 1;
evensIJ = numEvens[j] - numEvens[i] + ((arr[i] & 1) ? 0 : 1);
if (2*evensIJ == (j - i + 1))
count++;
}
}
return count;
}
</code></pre>
<p>I believe my code is correct but it give a <code>Time Limit Exceeded</code> error on larger test cases, even though it solves all smaller ones correctly. Any way to optimise it? Should I completely abandon this approach or should I optimise on this approach somehow?</p>
<p>Any style advise is also appreciated since I've been coding in Python3 for the last two years and have just shifted to C++14 last week because I need speed for competitive coding and all.</p>
<p>Also, side note, changing</p>
<pre><code>evensIJ = numEvens[j] - numEvens[i] + ((arr[i] & 1) ? 0 : 1);
</code></pre>
<p>to</p>
<pre><code>evensIJ = numEvens[j] - numEvens[i - 1];
</code></pre>
<p>makes the code incorrect. Am I being dumb for not getting why this happens?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T17:47:02.477",
"Id": "392061",
"Score": "0",
"body": "*\"... it give a Time Limit Exceeded ...\"* – so this is from some programming challenge? Can you add the link to the problem description?"
},
{
"ContentLicense": "CC BY-... | [
{
"body": "<p>First, the code review:</p>\n\n<blockquote>\n<pre><code>long int numArrs(int arr[], int n)\n</code></pre>\n</blockquote>\n\n<p>With C++14, you can do better than use built-in arrays (decaying to a pointer in a function, whatever the signature says): use rather <code>std::vector</code>, or <code>st... | {
"AcceptedAnswerId": "203549",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T16:55:05.550",
"Id": "203413",
"Score": "1",
"Tags": [
"c++",
"performance",
"array",
"c++14",
"dynamic-programming"
],
"Title": "Odd Even Subarrays"
} | 203413 |
<p>For learning purpouses I wrote a class that is supposed to find all divisors for a given integer. My class makes use of primes and prime factorization to speed things up a bit.
What can I improve in my class? </p>
<p>Are there any microoptimiztations that could speed up the process? Any bad practices that should be avoided? I am by no means an expert at math, so feel free to be very nit-picky. :)</p>
<p><strong>DivisorFinder Class</strong></p>
<pre><code>public class DivisorFinder
{
/// <summary>
/// The number that is searched for divisors
/// </summary>
private int _number;
/// <summary>
/// Search new divisors for a given integer
/// </summary>
/// <param name="number">Integer that is searched for divisors</param>
public DivisorFinder(int number)
{
_number = number;
}
/// <summary>
/// Find prime numbers up to a given maximum
/// </summary>
/// <param name="upperLimit">The upper limit</param>
/// <returns>All prime numbers between 2 and upperLimit</returns>
private IEnumerable<int> FindPrimes(int upperLimit)
{
var composite = new BitArray(upperLimit);
var sqrt = (int) Math.Sqrt(upperLimit);
for (int p = 2; p < sqrt; ++p)
{
if (composite[p])
continue;
yield return p;
for (int i = p * p; i < upperLimit; i += p)
composite[i] = true;
}
for (int p = sqrt; p < upperLimit; ++p)
if (!composite[p])
yield return p;
}
/// <summary>
/// Search prime factors in a given IEnumerable of prime numbers
/// </summary>
/// <param name="primesList">The IEnumerable of previously calculated prime numbers</param>
/// <returns>IEnumerable of prime factors</returns>
private IEnumerable<(int, int)> FindPrimeFactors(IEnumerable<int> primesList)
{
foreach (var prime in primesList)
{
if (prime * prime > _number)
break;
int count = 0;
while (_number % prime == 0)
{
_number = _number / prime;
count++;
}
if (count > 0)
yield return ((prime, count));
}
if (_number > 1)
yield return (_number, 1);
}
/// <summary>
/// Find all divisors of the target number
/// </summary>
/// <returns>IEnumerable of integers that divide the target without reminder</returns>
public IEnumerable<int> FindDivisors()
{
var primes = FindPrimes((int) (Math.Sqrt(_number) + 1));
var factors = FindPrimeFactors(primes);
var divisors = new HashSet<int> {1};
foreach (var factor in factors)
{
var set = new HashSet<int>();
for (int i = 0; i < factor.Item2 + 1; i++)
{
foreach (int x in divisors)
{
set.Add((int) Math.Pow(x * factor.Item1, i));
}
}
divisors.UnionWith(set);
}
return divisors;
}
}
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>var number = 2147483644;
var divisorFinder = new DivisorFinder(number);
var divisors = divisorFinder.FindDivisors();
Console.WriteLine($"Divisors: [{string.Join(", ", divisors)}]");
</code></pre>
<p>Performance for this example: ~6 milliseconds on a i5-6600K @ 3.50GHz</p>
<p><strong>Credits:</strong></p>
<p>The class was inspired by the <a href="https://stackoverflow.com/questions/171765/what-is-the-best-way-to-get-all-the-divisors-of-a-number">python example</a> from Bruno Astrolino.</p>
<p>Furthermore the prime sieve function was adapted from <a href="https://codereview.stackexchange.com/questions/82863/sieve-of-eratosthenes-in-c">Dennis_E</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T06:57:33.187",
"Id": "392306",
"Score": "3",
"body": "Have you done any testing for correctness or only for performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T07:52:05.493",
"Id": "39260... | [
{
"body": "<h2>Bugs</h2>\n\n<p><code>FindPrimes</code> is one of the better sieve implementations I've seen posted on this site, but it has an out-by-one bug. Here's some test code, which you can tidy up in a unit testing framework if you want to do things properly:</p>\n\n<pre><code> var df = new DivisorFin... | {
"AcceptedAnswerId": "203536",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T18:04:37.643",
"Id": "203416",
"Score": "3",
"Tags": [
"c#",
"primes"
],
"Title": "Calculate divisors using prime factorization"
} | 203416 |
<p>I have never written program in file handling. Help me improve this program.</p>
<p>book.h</p>
<pre><code>#ifndef BOOK_H_
#define BOOK_H_
#include <string>
class Book
{
std::string book_num;
std::string book_name;
std::string author_name;
public:
Book() = default;
Book(const Book&) = delete;
Book &operator=(const Book&) = delete;
~Book() = default;
void new_entry();
void show_book(std::string&, std::string&, std::string&);
std::string get_book_num() const;
void show_record();
};
#endif
</code></pre>
<p>book.cpp</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <fstream>
#include "book.h"
void Book::new_entry()
{
std::cin.ignore();
std::cout << "Enter Book Number : ";
std::getline(std::cin, book_num);
std::cout << "\nEnter Book Name : ";
std::getline(std::cin, book_name);
std::cout << "\nEnter Author Name : ";
std::getline(std::cin, author_name);
std::fstream fp;
fp.open("Books.dat", std::ios::out | std::ios::app);
if (fp)
{
fp << book_num << " " << book_name << " " << author_name << '\n';
}
fp.close();
std::cout << "Entry Successfull!!\n";
}
void Book::show_book(std::string& b_num, std::string& b_name, std::string& a_name)
{
std::cout << "Book Number :" << std::setw(10) << b_num << '\n';
std::cout << "Book Name : " << std::setw(10) << b_name << '\n';
std::cout << "Author Name :" << std::setw(10) << a_name << '\n';
}
std::string Book::get_book_num() const
{
return book_num;
}
void Book::show_record()
{
std::fstream fp;
std::string record;
fp.open("Books.dat", std::ios::in);
if (!fp)
{
std::cerr << "File could not be opened\n";
return;
}
else
{
while (fp >> book_num >> book_name >> author_name)
{
if (fp.eof())
{
break;
}
else
{
std::cout << book_num << std::setw(50) << book_name << std::setw(50) << author_name << '\n';
}
}
}
fp.close();
}
</code></pre>
<p>student.h</p>
<pre><code>#ifndef STUDENT_H_
#define STUDENT_H_
class Student
{
std::string roll_num;
std::string stu_name;
std::string issued_book_num;
unsigned int token;
public:
Student() = default;
Student(const Student&) = delete;
Student &operator=(const Student&) = delete;
~Student() = default;
void new_entry();
void show_stu(std::string&, std::string&, unsigned int, std::string&);
void reset_issued_book_num();
void reset_token();
void show_record();
};
#endif
</code></pre>
<p>student.cpp</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include "student.h"
void Student::new_entry()
{
std::cin.ignore();
std::cout << "Enter Roll Number : ";
std::getline(std::cin, roll_num);
std::cout << "\nEnter Student Name : ";
std::getline(std::cin, stu_name);
token = 0;
issued_book_num = "No";
std::fstream fp;
fp.open("Students.dat", std::ios::out | std::ios::app);
if (fp)
{
fp << roll_num << " " << stu_name << " " << token << " " << issued_book_num << '\n';
}
fp.close();
std::cout << "Entry Successfull!!\n";
}
void Student::show_stu(std::string& r_num, std::string& s_name, unsigned int tkn, std::string& issued_b_num)
{
std::cout << "Roll Number : " << std::setw(10) << r_num << '\n';
std::cout << "Student Name :" << std::setw(10) << s_name << '\n';
std::cout << "Books issued :" << std::setw(10) << tkn << '\n';
if (tkn == 1)
{
std::cout << "Book Number :" << std::setw(10) << issued_b_num << '\n';
}
std::cout << '\n';
}
void Student::reset_issued_book_num()
{
issued_book_num = "";
}
void Student::reset_token()
{
token = 0;
}
void Student::show_record()
{
std::fstream fp;
std::string record;
fp.open("Students.dat", std::ios::in);
if (!fp)
{
std::cerr << "File could not be opened\n";
return;
}
else
{
std::string line;
while (std::getline(fp, line))
{
std::stringstream ss(line);
ss >> roll_num >> stu_name >> token >> issued_book_num;
std::getline(ss, line);
if (fp.eof())
{
break;
}
else
{
std::cout << roll_num << "\t\t\t" << stu_name << "\t\t\t" << token << "\t\t\t" << issued_book_num << '\n';
}
}
}
fp.close();
}
</code></pre>
<p>library.h</p>
<pre><code>#ifndef LIBRARY_H_
#define LIBRARY_H_
#include <fstream>
#include <string>
#include "book.h"
#include "student.h"
class Library : public Book, public Student
{
std::fstream fp;
//std::ifstream ifs;
Book book;
Student student;
public:
Library() = default;
Library(const Library&) = delete;
Library &operator=(const Library&) = delete;
~Library() = default;
void enter_book();
void enter_stu();
void display_book(const std::string&);
void display_stu(const std::string&);
void delete_book();
void delete_stu(std::string&);
void display_all_stu();
void display_all_book();
void book_issue();
void book_deposit();
void menu();
};
#endif
</code></pre>
<p>library.cpp</p>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp> //case insensitive compare
#include <stdlib.h>
#include <iomanip>
#include <sstream>
#include "library.h"
#include "book.h"
#include "student.h"
void Library::enter_book()
{
char choice;
do
{
book.new_entry();
std::cout << "Do you want to add more records? (Y/N)\n";
std::cin >> choice;
}while(choice == 'y' || choice == 'Y');
fp.close();
}
void Library::enter_stu()
{
char choice;
do
{
student.new_entry();
std::cout << "Do you want to add more records? (Y/N)\n";
std::cin >> choice;
}while(choice == 'y' || choice == 'Y');
fp.close();
}
void Library::display_book(const std::string& num)
{
std::cout << "---------------Book Details-------------\n";
bool exist = false;
std::string b_num, b_name, a_name;
fp.open("Books.dat", std::ios::in);
while(fp >> b_num >> b_name >> a_name)
{
if (boost::iequals(b_num, num))
{
book.show_book(b_num, b_name, a_name);
exist = true;
}
}
fp.close();
if (!exist)
{
std::cerr << "Book does not exist\n";
}
}
void Library::display_stu(const std::string& num)
{
std::cout << "--------------Student Details-----------------\n";
bool exist = false;
std::string r_num, s_name, issued_b_num;
std::string line, str;
unsigned int tkn;
fp.open("Students.dat", std::ios::in);
while(std::getline(fp, line))
{
std::stringstream ss(line);
ss >> r_num >> s_name >> tkn >> issued_b_num;
std::getline(ss, str);
if (boost::iequals(r_num, num))
{
student.show_stu(r_num, s_name, tkn, issued_b_num);
exist = true;
}
}
fp.close();
if (!exist)
{
std::cerr << "Student does not exist\n";
}
}
void Library::delete_book()
{
std::string num;
std::cout << "Delete Book\n";
std::cout << "Enter number of the book you want to delete : ";
std::cin.ignore();
std::getline(std::cin, num);
std::cout << '\n';
fp.open("Books.dat", std::ios::in | std::ios::out);
std::fstream fp1;
fp1.open("Temp.dat", std::ios::out);
fp.seekg(0, std::ios::beg);
std::string b_num, b_name, a_name;
while(fp >> b_num >> b_name >> a_name)
{
if (!boost::iequals(b_num, num))
{
fp1 << b_num << " " << b_name << " " << a_name << '\n';
}
}
fp1.close();
fp.close();
std::remove("Books.dat");
std::rename("Temp.dat", "Books.dat");
}
void Library::delete_stu(std::string& num)
{
fp.open("Students.dat", std::ios::in | std::ios::out);
std::fstream fp1;
fp1.open("Temp.dat", std::ios::out);
fp.seekg(0, std::ios::beg);
std::string r_num, s_name, issued_b_num;
int tkn;
while(fp >> r_num >> s_name >> tkn >> issued_b_num)
{
if (!boost::iequals(r_num, num))
{
fp1 << r_num << " " << s_name << " " << " " << tkn << " " << issued_b_num << '\n';
}
}
fp1.close();
fp.close();
std::remove("Students.dat");
std::rename("Temp.dat", "Students.dat");
}
void Library::display_all_stu()
{
std::cout << " ---------------Students List ----------------\n";
std::cout << "Roll No." << "\t\t\t" << "Name" << "\t\t\t" << "Book Issued" << "\t\t\t" << "Issued Book No.\n";
student.show_record();
fp.close();
}
void Library::display_all_book()
{
std::cout << "-----------------Books List------------------\n";
std::cout << "Book No." << std::setw(50) << "Name" << std::setw(50) << "Author\n";
book.show_record();
}
void Library::book_issue()
{
std::string r_num, b_num; // roll num and book num
std::string roll_n, s_name, issued_b_num;
std::string book_n, b_name, a_name;
unsigned int tkn;
std::string line, str;
std::fstream fp1;
bool found_stu = false;
bool found_book = false;
std::cout << "-----------------Book Issue--------------------\n";
std::cout << "Enter student's roll no. : ";
std::cin.ignore();
std::getline(std::cin, r_num);
std::cout << '\n';
fp.open("Students.dat", std::ios::in | std::ios::out);
fp1.open("Books.dat", std::ios::in | std::ios::out);
int oldPos = fp.tellg();
while (std::getline(fp, line) && !found_stu)
{
std::stringstream ss(line);
ss >> roll_n >> s_name >> tkn >> issued_b_num;
std::getline(ss, line);
if (boost::iequals(roll_n, r_num))
{
found_stu = true;
if (tkn == 0)
{
std::cout << "Enter Book No. : ";
std::getline(std::cin, b_num);
while (fp1 >> book_n >> b_name >> a_name && !found_book)
{
if (boost::iequals(book_n, b_num))
{
book.show_book(book_n, b_name, a_name);
found_book = true;
tkn = 1;
student.reset_issued_book_num();
issued_b_num = book_n;
fp.seekg(oldPos);
fp << roll_n << " " << s_name << " " << tkn << " " << issued_b_num << '\n';
std::cout << "Book Issued Successfully\n";
break;
}
}
if (!found_book)
{
std::cerr << "Book does not exist\n";
}
}
}
}
if (!found_stu)
{
std::cout << "Student record does not exist\n";
}
fp.close();
fp1.close();
}
void Library::book_deposit()
{
std::string r_num, b_num; // roll num and book num
std::string roll_n, s_name, issued_b_num;
std::string book_n, b_name, a_name;
unsigned int tkn;
std::string line, str;
std::fstream fp1;
int days, fine;
bool found_stu = false;
bool found_book = false;
std::cout << "-----------------Book Deposit---------------------\n";
std::cout << "Enter student's roll no. : ";
std::cin.ignore();
std::getline(std::cin, r_num);
std::cout << '\n';
fp.open("Students.dat", std::ios::in | std::ios::out);
fp1.open("Books.dat", std::ios::in | std::ios::out);
while (std::getline(fp, line) && !found_stu)
{
std::stringstream ss(line);
ss >> roll_n >> s_name >> tkn >> issued_b_num;
std::cout << "IBN " << issued_b_num << '\n';
std::getline(ss, line);
if (boost::iequals(roll_n, r_num))
{
found_stu = true;
if (tkn == 1)
{
while (fp1 >> book_n >> b_name >> a_name && !found_book)
{
if (boost::iequals(book_n, issued_b_num))
{
book.show_book(book_n, b_name, a_name);
found_book = true;
std::cout << "Book deposited in no. of days : ";
std::cin >> days;
if (days > 15)
{
fine = days - 15;
std::cout << "Fine has to be deposited : " << fine << '\n';
}
student.reset_token();
int pos = -1 * sizeof("Students.dat");
fp.seekp(pos, std::ios::cur);
fp << roll_n << s_name << tkn << issued_b_num;
std::cout << "Book Deposited Successfully\n";
}
}
if (!found_book)
{
std::cerr << "Book does not exist\n";
}
}
}
}
if (!found_stu)
{
std::cout << "Student record does not exist\n";
}
fp.close();
fp1.close();
}
void Library::menu()
{
int choice;
std::cout << "Menu\n";
std::cout << "1. Create Student Record\n";
std::cout << "2. Display all Students Record\n";
std::cout << "3. Display Specific Student Record\n";
std::cout << "4. Delete Student Record\n";
std::cout << "5. Enter Book Record\n";
std::cout << "6. Display all Books\n";
std::cout << "7. Display Specific Book\n";
std::cout << "8. Delete Book\n";
std::cout << "9. Back to Main Menu\n";
std::cout << "Enter your choice\n";
std::cin >> choice;
switch(choice)
{
case 1: enter_stu();
break;
case 2: display_all_stu();
break;
case 3: {
std::string num;
std::cout << "Enter Roll No.\n";
std::cin.ignore();
std::getline(std::cin, num);
display_stu(num);
}
break;
case 4: {
std::string num;
std::cout << "Delete Student\n";
std::cout << "Enter roll number of the student you want to delete : ";
std::cin.ignore();
std::getline(std::cin, num);
delete_stu(num);
}
break;
case 5: enter_book();
break;
case 6: display_all_book();
break;
case 7: {
std::string num;
std::cout << "Enter Book No.\n";
std::cin.ignore();
std::getline(std::cin, num);
display_book(num);
}
break;
case 8: delete_book();
break;
case 10: return;
default: std::cout << "Please enter any of these choices\n";
break;
}
}
</code></pre>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <stdlib.h>
#include "library.h"
int main()
{
Library lib;
char choice;
do
{
std::cout << "1. Book Issue\n";
std::cout << "2. Book Deposit\n";
std::cout << "3. Menu\n";
std::cout << "4. Exit\n";
std::cout << "Enter your option\n";
std::cin >> choice;
switch(choice)
{
case '1': lib.book_issue();
break;
case '2': lib.book_deposit();
break;
case '3': lib.menu();
break;
case '4': exit(0) ;
default: std::cout << "Enter one of these choice\n";
}
} while(choice != '4');
}
</code></pre>
| [] | [
{
"body": "<p>I don't know where to begin... this would be very very long answer. Why would Library class inherit from Book or even Student? Library is not a Student. You should use students inside a library as a member field, or something, not inherit from it. I suggest you to start all over, and read some C++... | {
"AcceptedAnswerId": "203635",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T18:48:25.323",
"Id": "203419",
"Score": "4",
"Tags": [
"c++",
"beginner",
"file",
"database"
],
"Title": "Library Management using File Handling"
} | 203419 |
<p>The code below takes header variables, retrieves the column index, and then, using an Index/Match function, returns data from a matching account number.</p>
<p>The reason it is written this way is because I wanted to make the code "reusable". By being able to change the hard-coded header names, I can update the Macro based on our client.</p>
<p>The code itself is unreasonably slow. It takes 35 secs to pull 4 accounts.</p>
<ul>
<li>I'm looking to make the code more efficient.</li>
<li>Is there a different approach to making "reusable" code, which would be easier to read and look neater.</li>
</ul>
<p></p>
<pre><code> Sub RetrieveData()
Dim Headers(1 To 21, 1 To 2)
Headers(1, 1) = "StockNbr"
Headers(2, 1) = "Customer Last Name"
Headers(3, 1) = "Customer First Name"
Headers(4, 1) = "Date Sold"
Headers(5, 1) = "Amount Financed"
Headers(6, 1) = "Finance Charges"
Headers(7, 1) = ""
Headers(8, 1) = "APR Rate"
Headers(9, 1) = ""
Headers(10, 1) = "Payment Amount"
Headers(11, 1) = "Payment Schedule"
Headers(12, 1) = "Contract Term (Month)"
Headers(13, 1) = "Year"
Headers(14, 1) = "Make"
Headers(15, 1) = "Model"
Headers(16, 1) = "VIN"
Headers(17, 1) = "Odometer"
Headers(18, 1) = "Principal Balance"
Headers(19, 1) = "Cash Down"
Headers(20, 1) = ""
Headers(21, 1) = ""
Dim FundingSheet As Worksheet
Dim AccountNumber As Variant
Dim AccountRange As Range
Dim i As Integer
Dim x As Integer
Set AccountRange = Selection
Debug.Print AccountRange.Address
'B/c there is no naming convention, many different static data names
Set FundingSheet = Sheets("StaticFunding")
i = 1
'looking for the column index and attaching to second dimension
For i = LBound(Headers) To UBound(Headers)
If Headers(i, 1) = "" Then
Headers(i, 2) = ""
Else
Headers(i, 2) = Application.Match(Headers(i, 1), FundingSheet.Rows(3), 0)
End If
Next i
'retrieving information using Index Match
For Each Cell In AccountRange
AccountNumber = Cell.Value
x = 2
i = 1
For i = LBound(Headers) To UBound(Headers)
If Headers(x, 2) = "" Then
x = x + 1
Else
Cell.Offset(0, x).Value = Application.index(FundingSheet.Columns(Headers(x, 2)), Application.Match(CStr(AccountNumber), FundingSheet.Columns(Headers(1, 2)), 0))
x = x + 1
End If
If x = 22 Then Exit For
Next i
Next Cell
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T20:53:06.857",
"Id": "392073",
"Score": "0",
"body": "Honestly, this makes me wonder why you're not using named ranges, (or even data tables) and standard EXCEL formulas. Why does this need a macro? I've just skimmed the code, but t... | [
{
"body": "<p>If you want to make the code \"easier to read and look neater\", the first thing that I would do is to <a href=\"http://rubberduckvba.com/Indentation\" rel=\"nofollow noreferrer\">run it through an indenter</a>. This is currently haphazard at best, and makes it difficult to follow.</p>\n\n<hr>\n\n... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T20:01:08.337",
"Id": "203421",
"Score": "2",
"Tags": [
"performance",
"array",
"vba",
"excel",
"macros"
],
"Title": "Index Match implementation"
} | 203421 |
<p>I am trying to use a dictionary in Odd Occurrence. Any suggestions on how I could optimize the program? Codility is giving me a result of 66%.</p>
<pre><code>var dictionary = new Dictionary<int, short>();
int oddVal = 0; //Collect the number with Odd Occurrence
//Add the numbers in the dictionary with value 1-odd pair or 2-pair
if(A.Length != 0)
{
for (var i = 0; i < A.Length; i++)
{
if (dictionary.ContainsKey(A[i]))
dictionary[A[i]] = 2;
else
dictionary.Add(A[i], 1);
}
//review with the dictionary entry to see which key is the odd occurrence 1
//Once odd occurrence is determined then break out of the loop
foreach (KeyValuePair<int, short> entry in dictionary)
{
if (entry.Value == 1)
{
oddVal = entry.Key;
break;
}
}
return (int)oddVal;
}
else
return 0;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T00:03:08.413",
"Id": "392093",
"Score": "4",
"body": "Could you add an exact problem statement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T10:10:23.043",
"Id": "392154",
"Score": "0",
... | [
{
"body": "<p>For one I don't believe your code will cover all the possible values. If the values passed in are 9,3,9,3,9,7,7 I believe they would want 9 to be the result since there is an odd number of 9. Currently you are checking for a single value. </p>\n\n<p>By using a dictionary you first must add all ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T20:43:13.330",
"Id": "203422",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Odd Occurrence Array"
} | 203422 |
<p>This is my original take on providing an interface for calculating the dimensions of a rectangle, given optional parameters. I also broke out perfect squares in the instance where only area or perimeter are supplied. I output the rectangle as a JSON string because I have designs on also building out a user interface.</p>
<p>This should essentially work just like the Google Search interface to define dimensions of a rectangle. Provide the length, width and get back area, perimeter, etc. Also, I created a base class of <code>Shape</code> as I have plans to add triangle and circle.</p>
<p>Class: <code>Rectangle</code></p>
<pre><code>using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Shapes
{
[DataContract]
public class Rectangle : Shape
{
[DataMember] public double Length { get; private set; }
[DataMember] public double Width { get; private set; }
/// <summary>
/// Enumeration denotes what is to be returned
/// </summary>
public enum RectangleReturns
{
WidthArea = 1,
LengthArea = 2,
WidthPerimeter = 3,
LengthPerimeter = 4
}
/// <summary>
/// Enumeration denotes what is to be returned
/// </summary>
public enum PerfectSquareReturns
{
Perimeter = 0,
Area = 1
}
/// <summary>
/// Provide the appropriate values for what you wish to return
/// </summary>
/// <param name="rectangleName">The name of your rectangle</param>
/// <param name="firstDimension">Either the length or width</param>
/// <param name="secondDimension">Either the width, perimeter or area</param>
/// <param name="dimensions">What to return based on what was provided</param>
public Rectangle(string rectangleName, double firstDimension, double secondDimension, RectangleReturns dimensions = 0)
{
this.ShapeName = rectangleName;
if (firstDimension <= 0 || secondDimension <= 0)
{
this.ShapeException = "Parameters should be greater than zero";
return;
}
switch (dimensions)
{
case RectangleReturns.LengthPerimeter:
this.Width = firstDimension;
this.Area = secondDimension;
this.Length = this.CalculateFromArea(this.Width, this.Area);
this.Perimeter = this.CalculatePerimeter(this.Length, this.Width);
break;
case RectangleReturns.WidthPerimeter:
this.Length = firstDimension;
this.Area = secondDimension;
this.Width = this.CalculateFromArea(this.Length, this.Area);
this.Perimeter = this.CalculatePerimeter(this.Length, this.Width);
break;
case RectangleReturns.LengthArea:
this.Width = firstDimension;
this.Perimeter = secondDimension;
if (secondDimension <= 2 * firstDimension)
{
this.ShapeException =
"Perimeter should be greater than two times the width";
break;
}
this.Length = this.CalculateFromPerimeter(this.Width, this.Perimeter);
this.Area = this.CalculateArea(this.Length, this.Width);
break;
case RectangleReturns.WidthArea:
this.Length = firstDimension;
this.Perimeter = secondDimension;
if (secondDimension <= 2 * firstDimension)
{
this.ShapeException =
"Perimeter should be greater than two times the length";
break;
}
this.Width = this.CalculateFromPerimeter(this.Length, this.Perimeter);
this.Area = this.CalculateArea(this.Length, this.Width);
break;
default:
this.Length = firstDimension;
this.Width = secondDimension;
this.Perimeter = this.CalculatePerimeter(this.Length, this.Width);
this.Area = this.CalculateArea(this.Length, this.Width);
break;
}
}
/// <summary>
/// Return the perfect square dimensions for a perimeter or area
/// </summary>
/// <param name="rectangleName">The name of your rectangle</param>
/// <param name="firstDimension">Either the perimeter or the area</param>
/// <param name="dimensions">Which dimension to return</param>
public Rectangle(string rectangleName, double firstDimension, PerfectSquareReturns dimensions)
{
this.ShapeName = rectangleName;
if (firstDimension <= 0)
{
this.ShapeException = "Parameter must be greater than zero";
return;
}
double side = 0;
// ReSharper disable once SwitchStatementMissingSomeCases
switch (dimensions)
{
case PerfectSquareReturns.Perimeter:
side = this.FromPerfectArea(firstDimension);
this.Perimeter = this.CalculatePerimeter(side, side);
this.Area = firstDimension;
break;
case PerfectSquareReturns.Area:
side = this.FromPerfectPerimeter(firstDimension);
this.Perimeter = firstDimension;
this.Area = this.CalculateArea(side, side);
break;
}
this.Length = side;
this.Width = side;
}
private double CalculateArea(double length, double width) => length * width;
private double CalculatePerimeter(double length, double width) => 2 * (length + width);
private double CalculateFromPerimeter(double side, double perimeter) => perimeter / 2 - side;
private double CalculateFromArea(double side, double area) => area / side;
private double FromPerfectPerimeter(double side) => side / 4;
private double FromPerfectArea(double side) => Math.Sqrt(side);
public string SerializedRectangle() => JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
</code></pre>
<p>Class: <code>Shape</code></p>
<pre><code>using System.Runtime.Serialization;
namespace Shapes
{
[DataContract]
public class Shape
{
[DataMember] public double Perimeter { get; set; }
[DataMember] public double Area { get; set; }
[DataMember] public string ShapeName { get; set; }
[DataMember] public string ShapeException { get; set; }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T23:19:59.957",
"Id": "392090",
"Score": "1",
"body": "I think you should subclass `Square` from `Rectangle`, because a Square actually *is* a Rectangle, and is a perfect candidate for polymorphism. The `Shape` class should in my o... | [
{
"body": "<p>Here is a very rudimentary example of how you can set this up via inheritance. Obviously you'd add in the error checking on the static constructors to sanitize the input, but the intent should be clear.</p>\n<pre><code>public interface IShape\n{\n double Area { get; }\n double Perimeter { ge... | {
"AcceptedAnswerId": "203430",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T22:24:21.460",
"Id": "203425",
"Score": "2",
"Tags": [
"c#",
"beginner"
],
"Title": "Shapes - Rectangle interface/library"
} | 203425 |
<p>I've implemented a simple class for managing a Tic-Tac-Toe game's logic and state in Typescript. This code is intended to be used by a larger program; it doesn't implement any aspects of a UI. I've designed the class to present an immutable API, although it's mutable internally; I'm not using ImmutableJS or other, similar libraries. I'd appreciate review on any aspect of the code, though one thing I'd like to do is figure out a way to condense the setup code in the tests.</p>
<p><strong>TicTacToeGame.ts</strong></p>
<pre><code>export type Player = "PlayerX" | "PlayerO";
export type MoveResult = "Victory" | "WaitingForMove" | "SquareFilled" | "GameOver";
export type CellNumber = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
type CellState = "X" | "O" | "EMPTY";
export class TicTacToeGame {
private _currentPlayer: Player;
private _winningPlayer?: Player;
private board: CellState[];
constructor () {
this.board = new Array<CellState>(9);
this.board.fill("EMPTY");
this._currentPlayer = "PlayerX";
this._winningPlayer = undefined;
}
public get currentPlayer(): Player {
return this._currentPlayer;
}
public get winningPlayer(): Player | undefined {
return this._winningPlayer;
}
public makeMove(cellNum: CellNumber): [MoveResult, TicTacToeGame] {
const updatedGame = new TicTacToeGame();
updatedGame._currentPlayer = this.currentPlayer;
updatedGame._winningPlayer = this.winningPlayer;
updatedGame.board = this.board.map(element => element);
if (updatedGame.board[cellNum] !== "EMPTY") {
return ["SquareFilled", updatedGame];
}
if (updatedGame.winningPlayer) {
return ["GameOver", updatedGame];
}
if (updatedGame.currentPlayer === "PlayerX") {
updatedGame.board[cellNum] = "X";
} else {
updatedGame.board[cellNum] = "O";
}
updatedGame.checkForVictory();
if(updatedGame.winningPlayer) {
return ["Victory", updatedGame];
}
if (updatedGame.currentPlayer === "PlayerX") {
updatedGame._currentPlayer = "PlayerO";
} else {
updatedGame._currentPlayer = "PlayerX";
}
return ["WaitingForMove", updatedGame];
}
private checkForVictory (): void {
const lines = {
"row1": [this.board[0], this.board[1], this.board[2]],
"row2": [this.board[3], this.board[4], this.board[5]],
"row3": [this.board[6], this.board[7], this.board[8]],
"col1": [this.board[0], this.board[3], this.board[6]],
"col2": [this.board[1], this.board[4], this.board[7]],
"col3": [this.board[2], this.board[5], this.board[8]],
"diag1": [this.board[0], this.board[5], this.board[8]],
"diag2": [this.board[3], this.board[5], this.board[7]]
}
for (const line in lines) {
if ((lines[line] as CellState[]).every(cell => cell === "X")) {
this._winningPlayer = "PlayerX";
return;
} else if ((lines[line] as CellState[]).every(cell => cell === "O")) {
this._winningPlayer = "PlayerO";
return;
}
}
this._winningPlayer = undefined; // no winning player detected
return;
}
}
</code></pre>
<p><strong>TicTacToeGame.test.ts</strong></p>
<pre><code>import { TicTacToeGame } from "./TicTacToeGame";
describe ("Tic Tac Toe game class", () => {
it("Recognizes player X's victory correctly", () => {
const game0 = new TicTacToeGame();
// [1] needed to get just updated game; ignore result
const game1 = game0.makeMove(0)[1]; // X moves
const game2 = game1.makeMove(6)[1]; // O moves
const game3 = game2.makeMove(1)[1]; // X moves
const game4 = game3.makeMove(7)[1]; // O moves
const [result, game5] = game4.makeMove(2); // X moves, completing top row
expect(result).toBe("Victory");
expect(game5.winningPlayer).toBe("PlayerX");
});
it("Recognizes player O's victory correctly", () => {
const game0 = new TicTacToeGame();
const game1 = game0.makeMove(0)[1]; // X moves
const game2 = game1.makeMove(6)[1]; // O moves
const game3 = game2.makeMove(1)[1]; // X moves
const game4 = game3.makeMove(7)[1]; // O moves
const game5 = game4.makeMove(5)[1]; // X moves
const [result, game6] = game5.makeMove(8); // O moves, completing bottom row
expect(result).toBe("Victory");
expect(game6.winningPlayer).toBe("PlayerO");
});
it ("Returns an error when attempting to fill an already-filled square", () => {
const game0 = new TicTacToeGame();
const game1 = game0.makeMove(0)[1]; // get updated game, ignore result
const result = game1.makeMove(0)[0]; // get result, ignore updated game
expect(result).toBe("SquareFilled");
});
it ("Returns an error when making a move in a completed game", () => {
const game0 = new TicTacToeGame();
const game1 = game0.makeMove(0)[1]; // X moves
const game2 = game1.makeMove(6)[1]; // O moves
const game3 = game2.makeMove(1)[1]; // X moves
const game4 = game3.makeMove(7)[1]; // O moves
const game5 = game4.makeMove(2)[1]; // X moves, completing top row
const result = game5.makeMove(3)[0];
expect(result).toBe("GameOver");
});
it("Recognizes when it's X's turn", () => {
const game0 = new TicTacToeGame();
const game1 = game0.makeMove(0)[1]; // X moves
const [result, game2] = game1.makeMove(1); // O moves
expect(result).toBe("WaitingForMove");
expect(game2.currentPlayer).toBe("PlayerX");
});
it("Recognizes when it's O's turn", () => {
const game0 = new TicTacToeGame();
const [result, game1] = game0.makeMove(0); // X moves
expect(result).toBe("WaitingForMove");
expect(game1.currentPlayer).toBe("PlayerO");
});
});
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-09T23:01:21.400",
"Id": "203427",
"Score": "3",
"Tags": [
"tic-tac-toe",
"typescript"
],
"Title": "Tic Tac Toe game (Game logic, no UI)"
} | 203427 |
<p>This is a calculator that only sums numbers:</p>
<pre><code>module Data.Calculator where
data Expr = Plus Expr Expr | Value Int
evaluate :: Expr -> Int
evaluate (Value a) = a
evaluate (Plus (Value a) (Value b)) = a + b
evaluate (Plus (Plus left right) (Value b)) = (evaluate left) + (evaluate right) + b
evaluate (Plus (Value a) (Plus left right)) = a + (evaluate left) + (evaluate right)
evaluate (Plus a@(Plus left right) b@(Plus left' right')) = (evaluate a) + (evaluate b)
</code></pre>
<p>The <code>evaluate</code> function seems way to verbose. How do I make this better?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T01:55:12.577",
"Id": "392098",
"Score": "0",
"body": "*Hint:* There are two cases. One for `Value Int` and one for `Plus Expr Expr`. You don't need any more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-... | [
{
"body": "<p>As a general rule, when you are trying to define a recursive function that operates on a data type like this:</p>\n\n<pre><code>data Expr = Plus Expr Expr | Value Int\n</code></pre>\n\n<p>you want to <em>first</em> try to define your function using one pattern per constructor: one pattern for <co... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T01:33:23.843",
"Id": "203433",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Simple calculator that sums numbers"
} | 203433 |
<p>I'm trying to learn functional programming and Scala, following through Project Euler problems. </p>
<p>I'm solving get the sum of multiples x & y in a list. So for a list <code>[1,2,3,4,5,6,7,8,9]</code> get multiples of 3, 5 returns 3, 5, 6 and 9, the sum being 23.</p>
<ol>
<li>I'm accepting two parameters <code>list</code> and <code>multiples</code></li>
<li>Mapping multiples to list of functions, that test if input is a multiple</li>
<li>Filtering anything that returns true in the mapped multiples list</li>
</ol>
<p></p>
<pre><code> def multiplesOf(list: List[Int], multiples: List[Int]): List[Int] = {
def filterMultipleOf(x: Int) : Int => Boolean = (y: Int) => {
y % x == 0
}
val multiplesFilter = multiples.map(filterMultipleOf(_))
list.filter( int => multiplesFilter.exists(mOf => mOf(int)))
}
scala> multiplesOf(List.range(1,10), List(3,5)).sum
res: Int = 23
</code></pre>
<p><strong>My main question: Is this the Scale/FP way?</strong></p>
<p>Is defining <code>filterMultipleOf</code> inside my function still pure? Is there a better way to express this in Scala or FP?</p>
| [] | [
{
"body": "<p>Yes, your function is still pure. A pure function has only two requirements:</p>\n\n<ol>\n<li>The return value will always be the same given the same arguments.</li>\n<li>Evaluation will produce no side effects.</li>\n</ol>\n\n<p>Since <code>filterMultipleOf</code> only uses integers, the second i... | {
"AcceptedAnswerId": "203921",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T01:35:24.180",
"Id": "203434",
"Score": "1",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Project Euler - multiples of numbers"
} | 203434 |
<p><strong>I have addressed the critique for this post and resubmitted it for iterative review;</strong> <a href="https://codereview.stackexchange.com/questions/203518">C++20 multithread pool class</a>.</p>
<p><em>This is an iteration from a prior post; <a href="https://codereview.stackexchange.com/questions/202557">C++ thread pool class</a>.</em></p>
<p>Class for creating thread pools with upcoming C++ standard C++2a (<code>-std=gnu++2a -fconcepts</code>).</p>
<ul>
<li>It does not accept args for functions unless they are bound (<code>std::bind</code>).</li>
<li>Multiple functions may be enqueued via variadic template or stl
vector.</li>
<li>The number of threads created in the pool is relative to the
hardware concurrency by means of a user multiplier. If the hardware
concurrency cannot be determined it will default to four and the
number of threads created will be two, four, or eight depending on
the multiplier used.</li>
</ul>
<p>Please review code correctness, best practices, design and implementation.</p>
<p>Please assume the namespace Mercer is to be used as a cross-platform library.</p>
<p>This code <strong>was</strong> also available on <a href="https://github.com/sixequalszero/C-" rel="nofollow noreferrer">GitHub</a>, but now contains the current iteration.</p>
<p><strong>mercer.h</strong></p>
<pre><code>#ifndef MERCER_H_0000
#define MERCER_H_0000
namespace Mercer
{
enum struct execution: bool {failure, success};
}
#endif //MERCER_H_0000
</code></pre>
<p><strong>multithread.h</strong></p>
<pre><code>#ifndef MULTITHREAD_H_0000
#define MULTITHREAD_H_0000
// GCC Bug 84330 - [6/7 Regression] [concepts] ICE with broken constraint
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84330
#ifndef __cpp_concepts
static_assert(false, "Concepts TS NOT found");
#endif
#include <deque>
#include <queue>
#include <mutex>
#include <vector>
#include <memory>
#include <thread>
#include <atomic>
#include <functional>
#include <condition_variable>
#include "mercer.h"
namespace Mercer
{
//Multithread class
//if !joinable no new routines may be enqueued
class multithread
{
class implementation;
std::unique_ptr<implementation> data;
public:
enum struct concurrency: int {half, full, twofold};
multithread();//concurrency::full
multithread(concurrency quantity);
~multithread();
execution enqueue(std::function<void()>&&) noexcept;
execution enqueue(const std::function<void()>&);
execution enqueue(std::vector<std::function<void()>>&&);
execution enqueue(const std::vector<std::function<void()>>&);
template<typename ... dataType>
execution enqueue(std::function<void()>&& proximate ,
std::function<void()>&& penproximate,
dataType&& ... parameters )
{
if(enqueue(std::move<std::function<void()>&>(proximate))
== execution::failure)
return execution::failure;
else
return enqueue(std::move<std::function<void()>&>(penproximate),
std::forward<dataType >(parameters )...);
}
execution join();
execution detach();
bool thrown() const noexcept;
std::exception_ptr getNextException() const;
//If thrown()==true, will never throw
//If get final exception, thrown() will reset to false
};
}//namespace Mercer
#endif //MULTITHREAD_H_0000
</code></pre>
<p><strong>debug.cpp</strong></p>
<pre><code>#ifndef DEBUG_H_0000
#define DEBUG_H_0000
#include <cstdio>
struct debug
{
template< typename ... params>
void operator()(const char* file, int line, const char* func,
const char* note, int value )
{
fprintf(stdout, "%16s %4d %-16s %-16s %4d %c", \
file, line, func, note, value, '\n');
}
};
#ifdef NDEBUG
#define REPORT(...)
#else
debug REPORT;
#define REPORT(...) REPORT( __FILE__, __LINE__, __func__, __VA_ARGS__);
#endif
#endif //DEBUG_H
</code></pre>
<p><strong>multithread.cpp</strong></p>
<pre><code>#include "multithread.h"
#include "debug.cpp"
using Mercer::multithread;
using Mercer::execution;
using function = std::function<void()>;
template <typename dataType>
struct is_std_vector: std::false_type {};
template <typename dataType>
struct is_std_vector< std::vector<dataType> >: std::true_type {};
template <typename dataType>
concept bool is_vector = is_std_vector<dataType>::value;
template <typename dataType>
concept bool is_invocable = std::is_invocable<dataType>::value;
struct multithread::implementation
{
enum struct close: bool {detach, join};
enum struct init : bool {move , copy};
std::atomic <bool> open ;
std::deque <function> line ;
std::mutex door ;
std::condition_variable guard ;
std::vector <std::thread> pool ;
std::queue <std::exception_ptr> exceptions;
void worker()
{
function next;
bool perpetual = true;
while(perpetual)
{
std::unique_lock lock(door);
guard.wait(lock,
[&] { return !line.empty() || !open; } );
if(!line.empty())
{
next = std::move<function&>(line.front());
line.pop_front();
if(!open && line.empty())
perpetual = false;
lock.unlock();
guard.notify_one();
try
{
next();
}
catch(...)
{
exceptions.emplace(
std::current_exception() );
}
}
else if(!open)
perpetual = false;
}
}
std::vector<std::thread> openPool(concurrency quantity)
{
std::vector<std::thread> temp;
unsigned threads = std::thread::hardware_concurrency();
if(threads==0)
threads=4;
switch(quantity)
{
case concurrency::half : threads /= 2; break;
case concurrency::full : break;
case concurrency::twofold: threads *= 2; break;
}
temp.reserve(threads);
for(auto i=threads; i>0; i--)
temp.emplace_back( [&](){ worker(); } );
return temp;
}
implementation(concurrency quantity) :
open(true), line(), door(), guard(),
pool( openPool(quantity) )
{}
template<close closeType>
execution close()
{
if (open==true)
{
open = false;
guard.notify_all();
for (auto&& thread : pool)
if (thread.joinable())
switch(closeType)
{
case close::join : thread.join() ; break;
case close::detach: thread.detach(); break;
}
pool.clear();
pool.shrink_to_fit();
}
else
return execution::failure;
return execution::success;
}
template<init initType, is_invocable function>
void enqueueSafe(function&& item) noexcept
{
REPORT("move",0);
line.emplace_back(std::move<function&>(item));
}
template<init initType, is_invocable function>
void enqueueSafe(const function& item)
{
REPORT("copy",0);
line.push_back(item);
}
template<init initType, is_vector vector>
void enqueueSafe(vector&& item)
{
REPORT("move",0);
line.insert(line.end(),
make_move_iterator(item.begin()) ,
make_move_iterator(item.end ()));
}
template<init initType, is_vector vector>
void enqueueSafe(const vector& item)
{
REPORT("copy",0);
line.insert(line.end(), item.begin(), item.end());
}
template<init initType, typename function>
execution enqueue(function&& item)
{
if (open==true)
{
std::scoped_lock lock(door);
enqueueSafe<initType>(item);
guard.notify_all();
return execution::success;
}
else
return execution::failure;
}
};
multithread::multithread(concurrency quantity):
data(std::make_unique<implementation>(quantity))
{}
multithread::multithread():
data(std::make_unique<implementation>(concurrency::full))
{}
execution multithread::join()
{
return data->close<implementation::close::join>();
}
execution multithread::detach()
{
return data->close<implementation::close::detach>();
}
multithread::~multithread()
{
join();
}
execution multithread::enqueue(function&& item) noexcept
{
REPORT("function",0);
return data->enqueue<implementation::init::move>(item);
}
execution multithread::enqueue(const function& item)
{
REPORT("const function",0);
return data->enqueue<implementation::init::copy>(item);
}
execution multithread::enqueue(std::vector<function>&& adjunct)
{
REPORT("vector",0);
return data->enqueue<implementation::init::move>(adjunct);
}
execution multithread::enqueue(const std::vector<function>& adjunct)
{
REPORT("const vector",0);
return data->enqueue<implementation::init::copy>(adjunct);
}
bool multithread::thrown() const noexcept
{
return data->exceptions.empty() ? false : true;
}
std::exception_ptr multithread::getNextException() const
{
if(thrown())
{
auto temp = std::move<std::exception_ptr&>(data->exceptions.front());
data->exceptions.pop();
return temp;
}
else
throw std::out_of_range("Thrown() is false, no exception to get");
}
</code></pre>
| [] | [
{
"body": "<p>There's some weird stuff in there; I recommend trying to remove as much weird stuff as possible and then making a new post. Here's some examples:</p>\n\n<hr>\n\n<pre><code>template<init initType, is_invocable function>\nvoid enqueueSafe(function&& item) noexcept\n{\n REPORT(\"move... | {
"AcceptedAnswerId": "203444",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T03:05:42.200",
"Id": "203435",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"design-patterns",
"library",
"c++20"
],
"Title": "C++ multithread pool class"
} | 203435 |
<p>Here, my function is getting four integer values and one CSS class name. Based on their equality I'm creating few more CSS proprties. If all four elements passed are different then I'm using default CSS properties.</p>
<p>How can make this code elegant? I wanted to get rid of <code>if</code> <code>else</code> conditions.</p>
<p>Note: I tried with switch statements too but I felt it's the same as <code>if</code> <code>else</code> loops.</p>
<pre><code>twoEqualElementsCss(cssClass1, cssClass2) {
var dict = {};
dict[cssClass1] = { padding: '12, 17' };
dict[cssClass2] = { padding: '12, 17', offset: '-2' };
return dict;
}
threeEqualElementsCss(cssClass1, cssClass2, cssClass3) {
var dict = {};
dict[cssClass1] = { padding: '12, 30', offset: '1' };
dict[cssClass2] = { padding: '12, 30', offset: '-14' };
dict[cssClass3] = { padding: '12, 30', offset: '-28' };
return dict;
}
fourEqualElementsCss(cssClass1, cssClass2, cssClass3, cssClass4) {
var dict = {};
dict[cssClass1] = { padding: '12, 30', offset: '1' };
dict[cssClass2] = { padding: '12, 30', offset: '-14' };
dict[cssClass3] = { padding: '12, 30', offset: '-28' };
dict[cssClass3] = { padding: '12, 30', offset: '-42' };
return dict;
}
//drawSomething is called this way from other function, which pass four values(integer) and one of the elements css class
drawSomething(23, 26, 26, 26, element2-css);
drawSomething(23, 26, 26, 26, element3-css);
drawSomething(23, 26, 26, 26, element4-css);
drawSomething(23, 26, 26, 26, element1-css);
drawSomething(element1,element2, element3, element4, cssClassName) {
let padding = '5, 3' //default value when all four elements are different
let offset = 100 //default value when all four elements are different
var equalElementDictionary = {}
// when 4 elements are same integer value
if (element1 == element2 && element2 == element3 && element3 == element4)
{
//Note that each element has it's own predefined css class e.g element1 has element1-css class
equalElementDictionary = this.fourEqualElementsCss('element1-css', 'element2-css', 'element3-css', 'element4-css')
}
else if ((element1 == element2 && element2 === element4)) { // when 3 elements are equal.
equalElementDictionary = this.threeEqualElementsCss('element1-css', 'element2-css', 'element4-css')
}
else if ((element1 == element3 && element3 === element4)) {
equalElementDictionary = this.threeEqualElementsCss('element1-css', 'element3-css', 'element4-css')
}
else if ((element2 == element3 && element3 === element4)) {
equalElementDictionary = this.threeEqualElementsCss('element2-css', 'element3-css', 'element4-css')
}
else if (element4 == element1) { // when 2 elements are equal.
equalElementDictionary = this.twoEqualElementsCss('element4-css', 'element1-css')
}
else if (element2 == element1) {
equalElementDictionary = this.twoEqualElementsCss('element2-css', 'element1-css')
}
else if (element4 == element3) {
equalElementDictionary = this.twoEqualElementsCss('element4-css', 'element3-css')
}
else if (element4 == element2) {
equalElementDictionary = this.twoEqualElementsCss('element4-css', 'element2-css')
}
// when dicitionary does not have cssClassName that means all four elements are different and default values are passed to testFunction
if (equalElementDictionary[cssClassName] != undefined) {
padding = equalElementDictionary[cssClassName].padding
if (equalElementDictionary[cssClassName].offset != undefined) {
padding = equalElementDictionary[cssClassName].offset
}
}
testFunction(offset, padding)
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T16:41:59.547",
"Id": "392241",
"Score": "1",
"body": "This looks like off-topic pseudocode: `element2-css` seems like some weird kind of subtraction?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T16... | [
{
"body": "<p>First off, the question. Because some functionality is missing, I can't test my proposed solution. Try to ask self contained questions.</p>\n\n<p>A possible alternative approach is to analyze the 4 integer and keep track.</p>\n\n<pre><code>function keepTrack(info, integer, cssClass){\n info[integ... | {
"AcceptedAnswerId": "203471",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T03:39:15.977",
"Id": "203437",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Getting integer values and one CSS class name"
} | 203437 |
<p>Writing code could be divided into three parts.</p>
<h1>1.Interface structure</h1>
<p>At this stage programmer should describe all the devices used in his project. Of course, only those of them which Arduino programmaticaly interacts with (sensors, chips and <strong>not</strong> intermediate resistors, for example). Each device at this stage is represented by a class - <em>description-class</em>. Description-class has special member functions - <em>pin-functions</em>. Those functions are pure virtual and each is intended to return 8-bit unsigned integer value from the set of Arduino pin numbers. Pin-functions play a role of wires between Arduino and peripherals. Description-class should also contain functions which are Arduino instructions and intended for this concrete device. </p>
<p>Arduino also has a description-class but now it is used as a namespace with constants. No object of this class is needed so far.</p>
<p>Below is an example of using the interface.</p>
<ul>
<li>Controller: Arduino Uno R3</li>
<li>Peripheral: Ultrasonic sensor HC-SR04</li>
</ul>
<h2>1.1 Arduino Uno R3 class-description</h2>
<p>Arduino Uno R3 description-class consists only of static constants that are pin numbers.</p>
<h3>1.1.1 Uno.h</h3>
<pre><code>#ifndef UNO_H
#define UNO_H
#include <inttypes.h>
class Uno
{
public :
//Digital pins
static const uint8_t D0 = 0;
static const uint8_t D1 = 1;
static const uint8_t D2 = 2;
static const uint8_t D3 = 3;
static const uint8_t D4 = 4;
static const uint8_t D5 = 5;
static const uint8_t D6 = 6;
static const uint8_t D7 = 7;
static const uint8_t D8 = 8;
static const uint8_t D9 = 9;
static const uint8_t D10 = 10;
static const uint8_t D11 = 11;
static const uint8_t D12 = 12;
static const uint8_t D13 = 13;
//Analog pins
static const uint8_t A0 = 0;
static const uint8_t A1 = 0;
static const uint8_t A2 = 0;
static const uint8_t A3 = 0;
static const uint8_t A4 = 0;
static const uint8_t A5 = 0;
//SPI
static const uint8_t SS = D10;
static const uint8_t MOSI = D11;
static const uint8_t MISO = D12;
static const uint8_t SCK = D13;
//I2C
static const uint8_t SDA = A4;
static const uint8_t SCL = A5;
//Serial
static const uint8_t TX = D0;
static const uint8_t RX = D1;
};
#endif
</code></pre>
<h2>1.2.Ultrasonic sensor class-description (abstract device)</h2>
<p>For this example I chose to use ultrasonic sensor HC-SR04. It has four pins: <code>VCC</code>, <code>GND</code>, <code>TRIG</code> and <code>ECHO</code>. Though in reality (whatever it is) all four pins are connected to Arduino only <code>TRIG</code> and <code>ECHO</code> are used in program. I don't know what to do with those pins so far. Maybe they should never appear in code.</p>
<h3>1.2.1 HC_SR04.h</h3>
<pre><code>#ifndef HC_SR04_H
#define HC_SR04_H
#include <inttypes.h>
#include <Arduino.h>
class HC_SR04
{
public :
//pin-functions
virtual uint8_t VCC() = 0;//???
virtual uint8_t TRIG() = 0;
virtual uint8_t ECHO() = 0;
virtual uint8_t GND() = 0;//???
//device specific functions
void setup();
long get_distance();
};
#endif
</code></pre>
<h3>1.2.2 HC_SR04.cpp</h3>
<pre><code>#include "HC_SR04.h"
void HC_SR04::setup()
{
pinMode( TRIG(), OUTPUT );
pinMode( ECHO(), INPUT );
}
long HC_SR04::get_distance()
{
digitalWrite( TRIG(), LOW );
delayMicroseconds( 2 );
digitalWrite( TRIG(), HIGH );
delayMicroseconds( 10 );
digitalWrite( TRIG(), HIGH );
return 0.017 * pulseIn( ECHO(), HIGH );
}
</code></pre>
<h2>2.Commutation description</h2>
<p>At this stage programmer should "plug in" all the real devices on the table by overloading pin-funcions in a subclass derived from corresponding class-description.</p>
<h3>2.1 Ultrasonic sensor (real device)</h3>
<p><strong>2.1.1 US.cpp</strong></p>
<pre><code>#include "Uno.h"
#include "HC_SR04.h"
class US : public HC_SR04
{
public :
uint8_t VCC() { return 0; }//What to do with this pin
uint8_t GND() { return 0; }//What to do with this pin
uint8_t TRIG() { return Uno::D10; }//wire between TRIG-pin on US and 10th digital pin on Uno
uint8_t ECHO() { return Uno::D11; }//...
};
</code></pre>
<h1>3. Main file (.ino file)</h1>
<pre><code>#include "US.cpp"//bad line?
US us;//Create ultrasonic device plugged in as descripted in US.cpp file
void setup()
{
Serial.begin( 9600 );
us.setup();
}
void loop()
{
Serial.println( us.get_distance() );
delay( 1000 );
}
</code></pre>
<h1>4. Project directory structure</h1>
<p><a href="https://i.stack.imgur.com/rWEct.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rWEct.png" alt="enter image description here"></a></p>
<h1>5. Discussion</h1>
<p>Here is <em>my</em> sight on the approach above. Of course, could be wrong.</p>
<p>Disadvantages:</p>
<ul>
<li>Additional level of abstraction = (perhaps) bad for low-memory controllers</li>
<li>Whole program is divided into parts. Each part is responsible for the communication with the concrete device. (perhaps) Bad for a project with dependent devices</li>
</ul>
<p>Advantages:</p>
<ul>
<li>Whole program is divided into parts. Each part is responsible for the communication with the concrete device. Good for a project with many independent peripherals</li>
<li>Self-descriptive code</li>
<li>Reusable code for similar devices or other projects with the same devices</li>
</ul>
<p>Please, tell me what do you think. As always any ideas, corrections, critic and etc. would be appreciated.</p>
<p>P.S. To upload program to Arduino I use <a href="https://github.com/sudar/Arduino-Makefile" rel="nofollow noreferrer">Makefile for Arduino</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T05:28:50.613",
"Id": "392107",
"Score": "1",
"body": "You got the wrong site. With how it's currently phrased, the wrong network even. *Discussion* isn't something we do except in questions on Stack Exchange. If you got questions ab... | [
{
"body": "<p>You describe what you did but you did not sufficiently describe why you did it. What problem you are trying to solve by your design?\nI see some major problems in your design.</p>\n\n<h1>Uno.h</h1>\n\n<ul>\n<li>does not need <code>inttypes.h</code>. <code>uint8_t</code> is in <code>stdint.h</code>... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T04:00:27.460",
"Id": "203439",
"Score": "-1",
"Tags": [
"c++",
"interface",
"arduino"
],
"Title": "An interface for designing Arduino code"
} | 203439 |
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/203292/boggle-board-solver-in-ruby">Boggle board solver in Ruby</a></p>
<pre><code>class Trie < Hash
def build(string)
string << '.' # Terminator indicating end of a complete word
string.chars.inject(self) do |h, char|
h[char] ||= {}
end
end
end
# Build the trie from all the words
@trie = Trie.new
File.foreach('wordlist.txt') { |w| @trie.build(w.chomp) }
</code></pre>
<p>Here I use a simplistic Trie structure based on a Hash in Ruby. It does the trick very nicely, but I am wondering whether there is a better way to implement this in Ruby that will consume less memory.
(It lacks lookup methods which is perfectly fine, because I track through the Trie along with the path through letters on a board - the '.' acts as a marker for a complete word).</p>
<p>When I load the file, which contains 270K+ words and is ~2.9MB in size, the memory consumption is over 188 megabytes.</p>
<p>Is there a way to reduce the memory consumption, perhaps, implementing this differently?</p>
| [] | [
{
"body": "<h2>Bloom Filters</h2>\n\n<p>I suggest a new data structure, specifically a <a href=\"https://en.wikipedia.org/wiki/Bloom_filter\" rel=\"nofollow noreferrer\">Bloom Filter</a>. A bloom filter is a boolean array of length <em>m</em>. You will also need <em>k</em> different hashing algorithms (more o... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T05:18:05.770",
"Id": "203441",
"Score": "1",
"Tags": [
"ruby",
"memory-optimization",
"trie"
],
"Title": "Trie structure using Hash in Ruby"
} | 203441 |
<p>I wrote a <code>Counter</code> subclass suitable for anagrams, with a more visually user-friendly <code>__str__()</code> method using alphabetic ordering and Unicode superscripts(/subscripts) for letter-counts, so you can compare at-a-glance if two phrases are anagrams or not:</p>
<pre><code>c1 = LetterCounter("PRESIDENTTRUMP")
print(c1)
D¹ E² I¹ M¹ N¹ P² R² S¹ T² U¹
</code></pre>
<p>Code below. My questions:</p>
<ul>
<li>translating integer to superscript(/subscript) is really clunky. Anything more compact?</li>
<li><code>Counter.items()</code> actually returns a view. It would be more elegant if it was similarly possible to define <code>sorted_items()</code> as a view instead of taking <code>sorted(list(self.items()))</code></li>
<li>leave the subscript code in even though it's not currently used</li>
<li><a href="https://stackoverflow.com/questions/29066606/variadic-arbitrary-number-of-args-or-kwargs-in-str-format-in-python">applying <code>.format()</code> to a variable-length list of tuples is a pain, can't just use *args</a>.
<ul>
<li><code>'{0[0]}{0[1]}'.format(x for x in value_count)</code> fails with <code>'generator' object is not subscriptable</code></li>
<li><code>'{0[0]}{0[1]} '.format([x for x in value_count])</code> is wrong, the format is outside the list comprehension.</li>
<li><code>[ '{0[0]}{0[1]} '.format(x) for x in value_count ]</code> won't allow us call <code>LetterCounter.int_to_superscript()</code> on only the second item of each tuple.</li>
<li>any more elegant approaches?</li>
</ul></li>
<li>in general we're supposed to override <code>__str__()</code> not <code>__repr__()</code>, but if we don't care about pickling why not just override <code>__repr__()</code>, then we can directly see the object just by typing its name, don't need print?</li>
<li>after I independently wrote this I found <a href="https://stackoverflow.com/questions/24391892/printing-subscript-in-python">Printing subscript in python</a></li>
<li>it seems more friendly for general use/reposting to enter Unicode literals in source as '\u2070' rather than '⁰'</li>
</ul>
<p>Code: </p>
<pre><code>import collections
class LetterCounter(collections.Counter):
subscript_digits = ''.join([chr(0x2080 + d) for d in range(10)])
superscript_digits = ''.join(['\u2070','\u00b9','\u00b2','\u00b3','\u2074','\u2075','\u2076','\u2077','\u2078','\u2079'])
trans_to_superscript = str.maketrans("0123456789", superscript_digits)
trans_to_subscript = str.maketrans("0123456789", subscript_digits)
@classmethod
def int_to_superscript(cls, n):
return str(n).translate(cls.trans_to_superscript)
@classmethod
def int_to_subscript(cls, n):
return str(n).translate(cls.trans_to_subscript)
def __str__(self):
value_count = sorted(list(self.items()))
return ' '.join( '{}{}'.format(x[0], LetterCounter.int_to_superscript(x[1])) for x in value_count )
# Test code
c1, c2 = LetterCounter("PRESIDENTTRUMP") , LetterCounter("MRPUTINSREDPET")
print(c1)
D¹ E² I¹ M¹ N¹ P² R² S¹ T² U¹
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T05:42:00.300",
"Id": "392108",
"Score": "1",
"body": "I guess one improvement is to [only call the translation to superscript once, on the concatenated output](https://stackoverflow.com/a/24392215/202229). We can get away with that ... | [
{
"body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>There is no docstring. What kind of object is a <code>LetterCounter</code>?</p></li>\n<li><p>The <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"noreferrer\">Python style guide</a> recommends restricting lines to 79 characters. If you... | {
"AcceptedAnswerId": "203454",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T05:39:35.043",
"Id": "203443",
"Score": "7",
"Tags": [
"python",
"unicode"
],
"Title": "Subclassed Python Counter for a more visually user-friendly __str__() method, for anagrams"
} | 203443 |
<p>I wrote an NLP script for processing Turkish language. Yesterday I added syllabication but I wonder if it could be done better. It is kinda hard-coded, so I would like to know if I can improve it. </p>
<p>Here is the syllabication part.</p>
<pre><code>def syllabicate(self, word):
"""
:param word: The word to be syllabicated
:return: The syllabicated list that contains syllabs
"""
word = word.lower()
syllabs = []
syllab = ""
keep_index = 0
last_was_vowel = False
next_is_vowel = False
for let_ind in range(len(word)):
if let_ind != len(word) - 1:
if word[let_ind + 1] in self.vowels:
next_is_vowel = True
else:
next_is_vowel = False
else:
syllab = word[keep_index:]
syllabs.append(syllab)
break
if next_is_vowel and not last_was_vowel and syllab:
syllabs.append(syllab)
syllab = ""
keep_index = let_ind
elif next_is_vowel and word[let_ind] not in self.vowels and syllab:
syllabs.append(syllab)
syllab = ""
keep_index = let_ind
syllab += word[let_ind]
if word[let_ind] in self.vowels:
last_was_vowel = True
else:
last_was_vowel = False
return syllabs
</code></pre>
| [] | [
{
"body": "<p><s>First of all you should know that the script doesn't syllabize properly for every word. For example if you give the word <strong>authenticated</strong> the function returns <strong>['aut', 'hen', 'ti', 'ca', 'ted']</strong> which is incorrect. The correct case would be <strong>['au','then','ti'... | {
"AcceptedAnswerId": "203457",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T07:30:28.170",
"Id": "203450",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"natural-language-processing"
],
"Title": "Syllabification function for Turkish words"
} | 203450 |
<p>We have <strong>hundreds</strong> of employees and for tracking each employees' data, and I am using this code:</p>
<pre><code><?php
$sqldelivery9 = "SELECT COUNT(*) as count FROM orders WHERE employeename = 'nawaz' AND DATE(reattemptdate) = DATE(NOW() - INTERVAL 2 DAY)";
$resultdeliverys9 = $db_handle->runSelectQuery($sqldelivery9);
$numrowsresultdelivery9 =$resultdeliverys9[0]['count'];
echo $numrowsresultdelivery9;
</code></pre>
<p>Also, I am tracking the <strong>last 7 days</strong> of records of each employee, so it's going to be <strong>100*7= 700 SQL queries</strong>. Is this acceptable? Will it going to affect performance? Is there any better way to do it with <strong>minimal SQL queries</strong>?</p>
| [] | [
{
"body": "<p>Definitely not. You can do that all in a single query.</p>\n\n<pre><code>SELECT employeename, DATE(reattemptdate) as date, COUNT(*) as count\n FROM orders\n WHERE employeename in ('name1', 'name2', 'name3', '...')\n AND DATE(reattemptdate) > DATE(NOW() - INTERVAL 7 DAY)\n GROUP ... | {
"AcceptedAnswerId": "203456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T07:52:23.870",
"Id": "203453",
"Score": "0",
"Tags": [
"performance",
"php",
"mysql",
"mysqli"
],
"Title": "Tracking employee data"
} | 203453 |
<p>I wrote a perl script to import local files with "File-Ending-Versioning" (like file.1.12.pm) into a git repository. I tried to use the concept of roles in this script and I am not shure if I applied the concept right. </p>
<p>The basic idea is, that the script must be able to operate in a so-called "dryrun-mode": If invoked with the dryrun option, it should act as if it were doing an import like print log and error messages, but it should not actually create anything.</p>
<p>As the code is quite long, I shortened it to the relevant sections, but I am willing to expand if I missed something.</p>
<p>First, I have a main script file called <code>git-importer</code>. </p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use version; our $VERSION = qv( '0.3.0' );
use English qw( -no_match_vars );
use lib '/our/special/library/path';
use Utils::Cwd qw(abs_path); # oddity of my workplaces environment
# use lib './lib' but make it independant of the current directory
use File::Basename;
# move local lib folder to top of @INC
BEGIN { my $prog = unshift( @INC,dirname(abs_path($0))."/lib"); }
# those are the modules I use for my scripts behaviour
use Importer;
use Import::Git;
use Import::Git::dryrun;
use Import::Github;
use Import::Github::dryrun;
use Import::File;
use Import::File::dryrun;
use Getopt::Long::Descriptive;
use Getopt::Long::Descriptive::Opts;
my ( $opt, $usage ) = describe_options(
"Import files into Github Repositories\n\n Usage: %c %o [FILE]",
[ 'config|c=s', "path to configuration file", { default => '/common/admin/etc/git-importer' } ],
[ 'sourcefile|s=s@', "required - path to source file. If source is a softlink, this file will be taken as a starting version. ".
"Module names, like Utils::Test::... are supported if --modules is used", { required => 1 } ],
[ 'targetdir|t=s', "optional - path to target directory where local repository will be created" ],
[ 'logfile|l=s', "optional - path to logfile" ],
[ 'remote|r=s', "optional - ssh clone url of the remote repository" ],
[ 'dryrun|d', "optional - only perform read actions" ],
[ 'modules|m ', "optional - Create a module repository", ],
);
my $importer = Importer->new();
my $params = $importer->init_config( $opt->config );
$importer->is_module($opt->modules);
# I did start a code review on a Perlmonks Meetup but we were not able to finish on time. They found it odd that I used a different object for the dryrun.
$importer->check_permissions();
foreach my $file ( @{ $opt->sourcefile } ) {
$file = $importer->test_file( $file, $opt->modules );
my $o_file;
if ( $opt->dryrun ) {
$o_file = Import::File::dryrun->new( rawpath => $file, is_module => $opt->modules );
}
else {
$o_file = Import::File->new( rawpath => $file, is_module => $opt->modules );
}
$importer->add_file( $o_file );
$importer->add_type( $o_file->type );
}
[...]
my $git;
if ( $opt->dryrun ) {
$git = Import::Git::dryrun->new( git_import_user => $params->{ git_import_user }, targetdir => $params->{ targetdir }, tag => '1' );
}
else {
$git = Import::Git->new( git_import_user => $params->{ git_import_user }, targetdir => $params->{ targetdir }, tag => '1' );
}
[...]
</code></pre>
<p>My structure is as follows: I have a lib folder where I placed all my modules in like this:</p>
<pre><code>.
├── Import
│ ├── File
│ │ ├── dryrun.pm
│ │ ├── Role.pm
│ │ ├── Version
│ │ │ └── dryrun.pm
│ │ └── Version.pm
│ ├── File.pm
│ ├── Git
│ │ ├── dryrun.pm
│ │ └── Role.pm
│ ├── Github
│ │ ├── dryrun.pm
│ │ └── Role.pm
│ ├── Github.pm
│ └── Git.pm
└── Importer.pm
</code></pre>
<p>So for all of my modules (except Importer.pm itself) there is a .pm, a dryrun.pm and a Role.pm.</p>
<p>I would like to look at Git.pm. The Role looks like this:</p>
<pre><code> #! /usr/bin/perl
package Import::Git::Role;
use strict;
use warnings;
use Mouse::Role;
use Carp;
use English qw( -no_match_vars );
use File::Path;
use Storable;
use Utils::Log;
# functionality that all classes using this Role must implement
requires qw(commit rmdir mkdir create_repository choose_repo_name push clone_empty_remote );
# attributes of all classes that use this role
has 'local' => ( is => 'rw' );
has 'remote' => ( is => 'rw' );
has 'targetdir' => ( is => 'rw' );
has 'msg_file' => ( is => 'rw', trigger => \&read_msg_file );
has 'messages' => ( is => 'rw' );
has 'author' => ( is => 'rw' );
has 'push_default' => ( is => 'rw' );
has 'git_import_user' => ( is => 'rw', trigger => \&build_author );
has '_repo' => ( is => 'rw' );
has 'name' => ( is => 'rw' );
has 'tag' => ( is => 'rw', default => '1' );
sub rollback {
my ( $self ) = @_;
$self->rmdir();
return;
}
sub choose_repo_name {
my ( $self ) = @_;
print "\nPlease enter a name for your repository: \n";
my $chosen_option = <STDIN>;
chomp $chosen_option;
while ( $chosen_option !~ /[A-Za-z0-9_-]+/xms ) {
print "Invalid characters in $chosen_option. Please try again\n";
$chosen_option = <>;
chomp $chosen_option;
}
report LOG_INFO, "User chose $chosen_option as repository name\n";
return $chosen_option;
}
sub build_author {
my ( $self, $import_user ) = @_;
$self->author( $import_user->{ name } . ' <' . $import_user->{ email } . '>' );
$self->push_default( $import_user->{ push_default } );
return;
}
</code></pre>
<p>It specifies what functionality must be implemented by the other classes and implements common functionality for Git.pm and dryrun.pm. This functionality is performed the same way, no matter if its a productive or a dryrun.</p>
<p>Then there is Git.pm, used when an actual import is performed:
(only sub commit shown for brevity, there are more)
#! /usr/bin/perl </p>
<pre><code> package Import::Git;
use strict;
use warnings;
use Mouse;
with 'Import::Git::Role';
use Carp;
use English qw( -no_match_vars );
use File::Path qw(:DEFAULT make_path);
use Git;
use Utils::Log;
sub commit {
my ( $self, $name, $version ) = @_;
my $message = "$name Version $version\nImported from " . $name . " in version $version";
if ( $self->messages && $self->messages->{ $name }->{ $version } ) {
$message = $self->messages->{ $name }->{ $version };
}
my $rc = $self->_repo->command( 'add', '-A' );
eval {
$rc = $self->_repo->command( 'commit', '-m', $message, '--author', $self->author );
1;
} or do {
#Error 1 = Nothing to commit. We can ignore this, its two versions of our file whichcontain no differences
unless ( $EVAL_ERROR->{'-value'} == '1' ) {
die "Commit failed: $EVAL_ERROR";
}
};
my $msg = "commited file $name in version $version";
if ( $self->tag == 1 ) {
$rc = $self->_repo->command( "tag", "$version" );
$msg = "commited and tagged file $name in version $version";
}
return $msg;
}
[...]
</code></pre>
<p>And there is dryrun.pm for performing the testrun:</p>
<pre><code> #! /usr/bin/perl
package Import::Git::dryrun;
use strict;
use warnings;
use Mouse;
with 'Import::Git::Role';
use Carp;
use English qw( -no_match_vars );
use File::Path;
use Utils::Log;
sub commit {
my ( $self, $name, $version ) = @_;
my $message = "$name Version $version\nImported from " . $name . " in version $version";
if ( $self->messages ) {
$message = $self->messages->{ $name }->{ $version } if $self->messages->{ $name }->{ $version };
}
print "git add -A\n";
print "git commit -m $message --author " . $self->author . "\n";
print "git tag $version\n" if $self->tag == 1;
return "Commited file $name in Version $version";
}
</code></pre>
<p>I wanted to use the Role to share behaviour that is the same between Git.pm and dryrun.pm and to mandate the list of functions that both of them would have to use. I am looking for feedback on my code quality, what I could improve and wheter this is a proper usage of Roles.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T10:20:41.800",
"Id": "392156",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for ... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T09:14:41.607",
"Id": "203462",
"Score": "7",
"Tags": [
"object-oriented",
"perl",
"git"
],
"Title": "Perl Script to import flat-file versioned files into git repositories"
} | 203462 |
<p>I have a two-dimensional array with M rows and N columns, with each element having a value between 0 and 255. </p>
<p>I have a second two-dimensional array with m rows and n columns, m < M, n < N.</p>
<p>The second array is like a box inside the first array, and loops from the top left to bottom right corner of the first array. With each loop, the mean of the elements of the second array is calculated. The purpose of the algorithm is to find the box from the first array that has the greatest mean (it stores the row and column indexes where the window array starts, within minI and minJ variables). </p>
<p>The following is an image which would help you understand better the idea of the algorithm:
<a href="https://i.stack.imgur.com/m72bw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m72bw.png" alt="enter image description here"></a></p>
<p>Here is the code: </p>
<pre><code>for(int i = 0;i <= M - m;i++){
for(int j = 0;j <= N - n;j++){
suma = 0;
for(int k = i;k < i + m;k++){
for(int p = j; p < j + n;p++){
suma += A[k][p];
}
}
if(suma > max){
max = suma;
maxI = i;
maxJ = j;
}
}
}
</code></pre>
<p>I want to know the complexity of this algorithm, and the way you calculate it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T10:22:44.330",
"Id": "392157",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply stat... | [
{
"body": "<p>To calculate the complexity of any algorithm, you have to check how many basic operations that algorithm performs. In your case, your basic operation is <code>suma += A[k][p];</code>. That operation will take up the majority of your runtime.</p>\n\n<p>So, how many times is that line of code execut... | {
"AcceptedAnswerId": "203466",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T10:06:37.457",
"Id": "203464",
"Score": "-1",
"Tags": [
"java",
"performance",
"algorithm"
],
"Title": "Extract a box with pixel values from an image, calculate the mean of each possible box"
} | 203464 |
<p>The problem is the following: I have a list <code>intervals</code> which consists of tuples of the form <code>(start, end</code>) [with <code>start <= end</code>]. Each tuple represents an interval (of the real line). We assume that the intervals in <code>intervals</code> are not overlapping each other. Given a new interval <code>(s,e)</code>, I would like to write a Python function which checks if <code>(s, e)</code> overlaps any of the intervals in <code>intervals</code>. If <code>(s, e)</code> has a non-empty intersection with at least one of the intervals in <code>intervals</code>, the function should return the indices of these intervals in the list <code>intervals</code>. </p>
<p>Say that the function is called <code>find_intersections</code>. Then, given that <code>intervals = [(1, 3.5), (5.5, 8.7), (10.2, 22.6), (22.7, 23.1)]</code>, expected outputs would be: </p>
<ul>
<li><code>find_intersection(intervals, (3.2, 5.))</code> returns <code>array([0])</code></li>
<li><code>find_intersection(intervals, (6.1, 7.3))</code> returns <code>array([1])</code></li>
<li><code>find_intersection(intervals, (9.1, 10.2))</code> returns <code>No intersection.</code></li>
<li><code>find_intersection(intervals, (5.8, 22.9))</code> returns <code>array([1, 2, 3])</code>.</li>
</ul>
<p>The code for <code>find_intersection</code> I have written is:</p>
<pre><code>import itertools
def find_intersection(intervals, new_interval):
_times = sorted(list(itertools.chain.from_iterable(intervals)))
ind = np.searchsorted(_times, np.asarray(new_interval))
parity = np.mod(ind, 2)
if (not np.any(parity)) and ind[1] == ind[0]:
print('No intersection.')
elif parity[0] == 1:
ub = ind[1] if parity[1] == 1 else ind[1] - 1
return np.arange((ind[0] - 1) / 2, (ub - 1) / 2 + 1)
elif parity[1] == 1:
lb = ind[0] if parity[0] == 1 else ind[0] + 1
return np.arange((lb - 1) / 2, (ind[1] - 1) / 2 + 1)
else:
lb = ind[0] if parity[0] == 1 else ind[0] + 1
ub = ind[1] if parity[1] == 1 else ind[1] - 1
return np.arange((lb - 1) / 2, (ub - 1) / 2 + 1)
</code></pre>
<p>I believe that the code does the job.</p>
<p><strong>Is there an easier/smarter way to address this problem?</strong></p>
<p><strong>Edit:</strong> this question was cross-posted on <a href="https://stackoverflow.com/questions/52257119/find-intervals-which-have-a-non-empty-intersection-with-a-given-interval">stackoverflow.com</a>. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T12:35:19.300",
"Id": "392178",
"Score": "0",
"body": "Hello and Welcome to Code Review Stack Exchange. You have a good question here and it's sad to see that it is deleted. I hope that you will bring it back, I know someone who want... | [
{
"body": "<h1>return value</h1>\n<p>In case there is no overlap, it would be cleaner to either return a sentinel value (<code>None</code> for example), or raise an exception, and don't trigger any side effects, like the <code>print</code></p>\n<h1>variable names</h1>\n<p><code>ind</code>, <code>lb</code> and <... | {
"AcceptedAnswerId": "203490",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T10:40:13.797",
"Id": "203468",
"Score": "7",
"Tags": [
"python",
"sorting",
"numpy",
"interval"
],
"Title": "Find the intervals which have a non-empty intersection with a given interval"
} | 203468 |
<p>I have this code to generate symmetric matrices for testing how the design of the canonical correlation analysis I am performing works out. This is a extension of <a href="https://stackoverflow.com/a/50949277/2886003">this solution</a></p>
<p>Each row of the matrix represent a dataset (it is symmetric), and if the value is 0 it means no interaction between the datasets, if it is higher that there is an interaction. The end goal of this code is just to make a grid search of the design that explains better the data I have.
However as I need to come up with different designs adding more datasets or less I would like to know how to improve this into a function that would be more general, specially the nested for loops part (If I test it with 5 datasets I add more <code>for</code> loops and then more <code>unlist</code> at the end).</p>
<p>Initial matrix (I usually work with 4 datasets):</p>
<pre><code>C <- matrix(0,ncol = 4, nrow = 4)
</code></pre>
<p>Weights for the interactions of each dataset (4 to avoid to many combinations):</p>
<pre><code>nweight <- 4
weight <- seq(from = 0, to = 1, length.out = nweight)
</code></pre>
<p>Initiate the list that will contain the matrices</p>
<pre><code>C_list <- vector("list", nweight)
cweight <- as.character(weight)
names(C_list) <- cweight
</code></pre>
<p>Loop for each position I want to change to obtain all the combinations of weights I want to test.</p>
<pre><code>for(i1 in cweight) {
C_list[[as.character(i1)]] <- vector("list", nweight)
names(C_list[[(i1)]]) <- cweight
for (i2 in cweight) {
C_list[[(i1)]][[(i2)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]]) <- cweight
for (i3 in cweight) {
C_list[[(i1)]][[(i2)]][[(i3)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]][[(i3)]]) <- cweight
for(i4 in cweight) {
C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]]) <- cweight
for (i5 in cweight) {
C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]][[(i5)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]][[(i5)]]) <- cweight
for (i6 in cweight) {
C[1, 2] <- as.numeric(i1)
C[2, 1] <- as.numeric(i2)
C[1, 3] <- as.numeric(i2)
C[3, 1] <- as.numeric(i2)
C[1, 4] <- as.numeric(i3)
C[4, 1] <- as.numeric(i3)
C[2, 3] <- as.numeric(i4)
C[3, 2] <- as.numeric(i4)
C[2, 4] <- as.numeric(i5)
C[4, 2] <- as.numeric(i5)
C[4, 3] <- as.numeric(i6)
C[3, 4] <- as.numeric(i6)
C_list[[i1]][[i2]][[i3]][[i4]][[i5]][[i6]] <- C
}
}
}
}
}
}
</code></pre>
<p>Unlist the list of list of list of ... nested matrices to end up with a long list of matrices with the weights for each dataset</p>
<pre><code>C_list2 <- unlist(unlist(unlist(unlist(unlist(C_list, FALSE, FALSE),
FALSE, FALSE), FALSE, FALSE),
FALSE, FALSE), FALSE, FALSE)
</code></pre>
| [] | [
{
"body": "<p>Here you want to move away from <code>for</code> loops for two reasons:</p>\n\n<ol>\n<li>your number of <code>for</code> loops depends on your number of datasets, so using <code>for</code> loops prevents you from generalizing your code to any number of datasets.</li>\n<li>many <code>for</code> loo... | {
"AcceptedAnswerId": "203517",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T12:17:39.427",
"Id": "203473",
"Score": "1",
"Tags": [
"functional-programming",
"matrix",
"statistics",
"r"
],
"Title": "Creating the design matrices for a canonical correlation analysis"
} | 203473 |
<p>I am relatively new to javascript ES6, the code I've written is working fine. However I am curious if this would be the best approach. I am trying to write a reusable module that I can use in multiple projects. On top of an API I've written a simple module to geocode adresses in the Netherlands. The suggest function will provide related adresses to a specific query. The lookup function provides information about a specific adress.</p>
<pre><code>class Geocoder {
// Class to geocode adresses to coordinates or find related adresses
// suggest(), lookup() both return a promise
// geocoder.lookup('adr-54e85361e27f833dd8331fd85bc46ac6').then((data) => {console.log(data)});
constructor() {
this.url = "https://geodata.nationaalgeoregister.nl/locatieserver/v3/";
}
async suggest(query) {
let url = `${this.url}suggest?q=${query}`;
return await this._get(url);
}
async lookup(id) {
let url = `${this.url}lookup?id=${id}`;
return await this._get(url);
}
_get(url) {
return new Promise ((resolve, reject) => {
fetch(url).then((response) => {
return response.json();
}).then((json) => {
resolve(json);
}).catch((err) => {
reject(err);
})
})
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T12:33:05.013",
"Id": "392177",
"Score": "1",
"body": "Maybe code is in an early stage then...let me ask before answering: 1) what's the added value of `this._get(something)` over `fetch(something)`? You're just _saving_ that `.then... | [
{
"body": "<p>Using <code>Promise</code> when <code>async</code>/<code>await</code> is supported is a sign of an anti-pattern. The only case you ever manually build promise in an environment that supports <code>async</code>/<code>await</code> is when the asynchronous operation cannot be written linearly/when yo... | {
"AcceptedAnswerId": "203477",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T12:23:12.293",
"Id": "203474",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"async-await",
"promise",
"geospatial"
],
"Title": "Javascript class to geocode Dutch addresses"
} | 203474 |
<p>Currently i am using 2 queries - one for <strong>reattemptdate</strong> & one for <strong>holddate</strong>.... if we merge both queries & get the results in single query , than will it give better performance? if so how to merge ?</p>
<p><strong>1st query</strong> :</p>
<pre><code>$sql = "SELECT employeename, DATE(reattemptdate) as date,
COUNT(*) as count FROM orders
WHERE DATE(reattemptdate) = CURDATE()
GROUP BY employeename, date";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
foreach ($results as $result)
{
echo $result['employeename'].'|'.$result['date'].'|'.$result['count']."<br>";
}
echo "<br>";
</code></pre>
<p><strong>2nd query</strong> :</p>
<pre><code>$sqla = "SELECT employeename, DATE(holddate) as date,
COUNT(*) as count FROM orders
WHERE DATE(holddate) = CURDATE()
GROUP BY employeename, date";
$resultsa = $db_handle->runSelectQuery($sqla);
$numrowsresulta =$resultsa[0]['count'];
foreach ($resultsa as $resulta)
{
echo $resulta['employeename'].'|'.$resulta['date'].'|'.$resulta['count']."<br>";
}
echo "<br>";
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T13:03:21.293",
"Id": "392185",
"Score": "0",
"body": "what you're looking for is \"UNION\". The benefit might be only marginal, though, soo ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T13:49:19... | [
{
"body": "<blockquote>\n <p>if we merge both queries & get the results in single query , than will it give better performance?</p>\n</blockquote>\n\n<p>No.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T06:24:32.797",
"Id": "392300",... | {
"AcceptedAnswerId": "203512",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T12:47:01.290",
"Id": "203476",
"Score": "1",
"Tags": [
"performance",
"php",
"mysql",
"mysqli"
],
"Title": "Merge both sql queries into one to get the performance"
} | 203476 |
<p>An array is given with 'n' Values ( n <= 10^5 ) ; we have to calculate xor of each pair of elements and count those pairs whose xor can be written as sum of two prime numbers with the same parity(both odd or even). My code is:</p>
<pre><code>#include <iostream>
#include<vector>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int testCases;
cin >> testCases;
for (int i = 0; i < testCases; i++) {
long long n;
cin >> n;
long long input;
vector<long long> even, odd;
for (int j = 0; j < n; j++) {
cin >> input;
if (input % 2 == 0) {
even.push_back(input);
} else {
odd.push_back(input);
}
}
long long answer = 0;
// even traversal
for (auto i = even.begin(); i != even.end(); i++) {
for (auto j = i + 1; j != even.end(); j++) {
if ((*i ^ *j) % 2 == 0 && (*i ^ *j) > 2) {
// cout<<"required pair - "<<*i<<" "<<*j<<endl;
answer++;
}
}
}
// odd traversal
for (auto i = odd.begin(); i != odd.end(); i++) {
for (auto j = i + 1; j != odd.end(); j++) {
if ((*i ^ *j) % 2 == 0 && (*i ^ *j) > 2) {
// cout<<"required pair - "<<*i<<" "<<*j<<endl;
answer++;
}
}
}
cout << answer << endl;
}
return 0;
}
</code></pre>
<p>but this code gives O(n^2) as its complexity ( in the worst case ). Can anyone suggest a better solution ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T13:47:09.457",
"Id": "392202",
"Score": "1",
"body": "The word \"parity\" has two meanings. In the *mathematical* sense it's just odd or even. In the *computer science* sense it's the mathematical parity of the sum of bits of the ... | [
{
"body": "<ul>\n<li><p>An <code>xor</code> of two even numbers is necessarily even. An <code>xor</code> of two odd numbers is necessarily even. Therefore, testing for <code>(*i ^ *j) % 2 == 0</code> is redundant.</p></li>\n<li><p>Do not brute force. Use some math:</p>\n\n<p><em>If</em>, for the sake of simplic... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T13:08:55.027",
"Id": "203478",
"Score": "-1",
"Tags": [
"c++",
"primes",
"c++14"
],
"Title": "For pairs of elements, count the ones whose XOR value is a sum of two primes"
} | 203478 |
<p>I am posting this here because it was suggested that it is the best place by a seasoned user.</p>
<p>This is a project I already submitted, but I never received feedback. All my upcoming assignments will be based on this, so I wanted to make sure it is correct. I got this program to work as far as calculating the information, but I was hoping someone could please let me know if it meets the parameters/requirements?</p>
<p>I did attempt it. It works and adds the items exactly how the example showed in the video. However, I wanted to make sure my code is solid, and not just a mishmash or working because I got lucky, and if there is a better more solid way to do this I want to make sure I can. I do want feedback so I can learn and get better and I am trying my hardest. I always right out all the code I see here and try it and learn what it does piece by piece, because it helps me learn and improve. I also want to make sure it is going to work once I start the code for the next half of the requirements. </p>
<p>**Write a Console program, let users to enter prices calculate subtotal, tax, and total. - Delcare variable data type as decimal (6 variables needed) decimal apple;</p>
<p>Conver string to decimal from input apple = Convert.ToDecimal(Console.ReadLine());
Do addition for subtotal
Multiplication for tax (0.065M) --- M or m stands for money value, read page 94.
Addition for total
You need to show only two digits after decimal point
The class example: </p>
<pre><code>`Console.WriteLine(" Subtotal: ${0}", String.Format("{0:0.00}", subTotal)); blank line: Console.WriteLine("") Console.Write(" Apple: $"); apple = Convert.ToDecimal(Console.ReadLine());`
</code></pre>
<p>My code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorRun
{
class Calculator
{
static void Main(string[] args)
{
decimal FirstOperand, SecondOperand, Result, result;
Console.Write("Addition Calculation");
Console.Write(" \n\n");
Console.Write(" Enter first operand: ");
FirstOperand = Convert.ToDecimal(Console.ReadLine());
Console.Write(" Enter second operand: ");
SecondOperand = Convert.ToDecimal(Console.ReadLine());
Console.Write("-------------------------\n\n");
Result = FirstOperand + SecondOperand;
result = Convert.ToDecimal(Result);
Console.WriteLine("Addition Result: {0}", string.Format("{0}", result));
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
}
}
</code></pre>
<p>The next part of the assignment is this, which is what I need to make sure my code is correct so I can build towards:</p>
<p>Delcare variable data type as decimal (5 variables needed) count, price, subtotal, tax, total</p>
<p>Write a do while loop, if the price is not -1, loop continues show count number enter price get subtotal increase count</p>
<p>Calculate tax, total</p>
<p>Display total count, subtotal, tax, total</p>
<p>Feedback I received I am working on:
What happens if the user enters an invalid number for either operand? (Thanks yo PaulF. I am not quit sure what this means, I think it means if someone enters a number such as -1. However, I will have to research a fix as this is a bit outside my realm).</p>
<p>This line is uncessary: result = Convert.ToDecimal(Result); because Result is already a decimal. You don't need two of them... (Thanks to Rufus L. I have to look into this and understand decimals more.) </p>
<p>This is the book I am using, and what I have to match so if some code seems oddly specific or old, that is why.
<a href="https://cscnt.savannahstate.edu/StudentFiles/Data_Structure/Visual%20C%23%202012%20How%20to%20Program.pdf" rel="nofollow noreferrer">https://cscnt.savannahstate.edu/StudentFiles/Data_Structure/Visual%20C%23%202012%20How%20to%20Program.pdf</a></p>
| [] | [
{
"body": "<p>This isn't bad for a beginner, but there is much room for improvement.</p>\n\n<p><strong>Organization</strong></p>\n\n<p>The app is small enough that everything can fit inside Main, but a more seasoned developer will have Main be more barebones, with calls to other methods.</p>\n\n<p>You would als... | {
"AcceptedAnswerId": "203542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T14:24:07.007",
"Id": "203481",
"Score": "1",
"Tags": [
"c#",
"beginner",
"calculator"
],
"Title": "Console program, let users to enter prices calculate subtotal, tax, and total with C Sharp"
} | 203481 |
<p>I'm relatively new to PHP OOP, currently I'm practising how to use it, however I am not really certain I'm building my classes correctly, I think perhaps I'm missing something out but I'm not entirely sure what, any advice would be appreciated </p>
<p>Class
<pre><code>class Validation
{
private
$password,
$repeatPassword,
$username,
$email;
private static
$minPassword = 7,
$confirmPassword,
$minUsername = 3,
$maxUsername = 14,
$validEmail;
public static function validateEmail($email)
{
return (filter_var($email, FILTER_VALIDATE_EMAIL) != self::$validEmail);
}
public static function validatePassword($password)
{
return(strlen($password) >= self::$minPassword);
}
public static function validatecheckbox($agree)
{
return(!empty($terms) >= self::$checked);
}
public static function validateRepeatPassword($repeatPassword,$password)
{
return $repeatPassword === $password;
}
public static function validateUsername($username)
{
return strlen($username) >= self::$minUsername
&& (strlen($username)) <= self::$maxUsername
&& (filter_var($username , FILTER_VALIDATE_REGEXP,["options"=> [ "regexp" => "/^[\p{L}0-9\s]+$/u"]]) == TRUE);
}
}
</code></pre>
<p>Usage</p>
<pre><code> $errors = array();
$fields = array(
'username' => array(
'validator' => 'validateUsername',
'message' => 'What is your username?'
),
'email' => array(
'validator' => 'validateEmail',
'message' => 'Please enter a valid email',
),
'password' => array(
'validator' => 'validatePassword',
'message' => 'Password must be a minimum of seven characters'
)
);
if(!Validation::validateRepeatPassword($password, $repassword))
{
$errors[] = ["name" => "repassword", "error" => "Passwords must match"];
}
foreach($post as $key => $value)
{
if(isset($fields[$key]))
{
if(!Validation::{$fields[$key]['validator']}($value))
{
$errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T16:35:28.543",
"Id": "392239",
"Score": "0",
"body": "Yes towards the bottom `foreach($post as $key => $value) \n {\n if(isset($fields[$key])) `"
}
] | [
{
"body": "<p>Well, your class is good and does what it is supposed to do, except in <code>validalidatecheckbox()</code> (you are using variables that doesn't exist).</p>\n\n<p>Also I would do this changes:</p>\n\n<ul>\n<li><p>Remove this code (it's unused):</p>\n\n<p><code>private $password,\n $repeatPasswo... | {
"AcceptedAnswerId": "203574",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T15:14:26.380",
"Id": "203485",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"validation"
],
"Title": "PHP validation class for username, email, and password"
} | 203485 |
<p>I am solving a HackerRank problem called <strong>'<a href="https://www.hackerrank.com/challenges/morgan-and-a-string/problem" rel="nofollow noreferrer">Morgan and a String</a>'</strong>. Given two strings, each consisting of up to 10<sup>5</sup> uppercase characters, the task is to form the lexicographically smallest string from those letters by taking the first remaining character from either of the strings at each step. Example, for input strings "ACA" and "BCF", the answer should be "ABCACF":</p>
<pre class="lang-none prettyprint-override"><code>Jack Daniel Result
ACA BCF
CA BCF A
CA CF AB
A CF ABC
A CF ABCA
F ABCAC
ABCACF
</code></pre>
<p>Sample input, with one test case:</p>
<pre class="lang-none prettyprint-override"><code>1
ACEG
BDFH
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>ABCDEFGH
</code></pre>
<p>I've solved it by writing my own code which works perfectly on smaller test cases. But when they run it against test cases which are approx 6000 characters long I get a runtime error. How can I increase the efficiency?</p>
<pre class="lang-python prettyprint-override"><code>n=int(input())#number of pairs to input
for mn in range(n):
a=input()# String1 in the pair
b=input()#String2 in the pair
la=[]
lb=[]
for i in range(max(len(a),len(b))):#creating lists with all possible elements by slicing off the characters
la.append(a[i:])
lb.append(b[i:])
if len(a)>len(b):#removes empty elements
lb=[x for x in lb if x!='']
else:
la=[x for x in la if x!='']
while True:#Create empty list for sorting the 0th elements of 'la' nd 'lb'
temp=[]
temp.append(la[0])
temp.append(lb[0])
temp=sorted(temp)
print(temp[0][0],end='')#print the 1st character
if(temp[0] in la):#removing the element after printing the first character
la.pop(0)
else:
lb.pop(0)
if len(la)==0:#breaks the while loop if a list gets empty
print(temp[1],end='')
break
elif len(lb)==0:
print(temp[1],end='')
break
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T16:00:43.970",
"Id": "392233",
"Score": "0",
"body": "Your creating lists with all possible elements part takes too long on long inputs, code won´t even reach the rest. [here](https://github.com/AnirudhGoel/Hackerrank/blob/master/M... | [
{
"body": "<p><strong>Code organisation</strong></p>\n\n<p>At the moment, the logic handling the output/input and the logic computing the actual result are all mixed up.</p>\n\n<p>This makes things hard to understand, hard to modify and hard to test.</p>\n\n<p>It would be much easier to add a function with 2 pa... | {
"AcceptedAnswerId": "203535",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T15:18:02.007",
"Id": "203486",
"Score": "4",
"Tags": [
"python",
"strings",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Morgan and a String HackerRank challenge"
} | 203486 |
<p>My code in full plus the task scheduler definition: <a href="https://gist.github.com/DaneWeber/0c5e7978bd3927734173e3afdc3d6338" rel="nofollow noreferrer">https://gist.github.com/DaneWeber/0c5e7978bd3927734173e3afdc3d6338</a></p>
<p>This is my first non-trivial PowerShell script. This was a pretty major learning experience. I only went down this path once I discovered that <code>xcopy</code> wouldn't be sufficient.</p>
<p><strong>My Ask:</strong> What do I not know that I don't know? That is, what about this strikes you as weird, clunky, or "not the PowerShell way"?</p>
<p><strong>Problem I am solving:</strong> I want Minecraft worlds sync'ed across two (or more) computers. It doesn't seem like I should have to pay for an additional service to accomplish this.</p>
<p>Other solutions attempted:</p>
<ul>
<li>Symlink/Junction of the Minecraft <code>minecraftWorlds</code> folder with one in OneDrive. Minecraft seemed to be unable/unwilling to see the data.</li>
<li><code>xcopy /d</code> to update files. The problem is that Minecraft renames the files every save, so each save results in another large file, growing out of control.</li>
</ul>
<p>Solution approach:</p>
<ul>
<li>If any world exists in one location (local or cloud) but not the other: copy it.</li>
<li>If one location's world contains a file newer than all other files in the other location, replace the entire world with the newer one. (You have to be careful not to consider folders, since they have a modified date of their creation, even when you copy a folder.)</li>
<li>In case the script runs while the cloud service is still downloading data, copy files from the cloud if there are ones missing locally.</li>
</ul>
<p><strong>The script:</strong></p>
<pre><code>$minecraftSaveFolder = "minecraftWorlds"
$minecraftLocalPath = $env:LOCALAPPDATA + "\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang"
$minecraftLocalSave = $minecraftLocalPath + "\" + $minecraftSaveFolder
$minecraftCloudSave = $PSScriptRoot + "\MinecraftBackup"
$cloudWorlds = Get-ChildItem $minecraftCloudSave
$localWorlds = Get-ChildItem $minecraftLocalSave
$saves = Compare-Object $cloudWorlds $localWorlds -IncludeEqual
switch ($saves) {
( {$PSItem.SideIndicator -eq "<="}) {
Write-Output "Copying from cloud: $($PSItem.InputObject.Name)"
Copy-Item -Path $PSItem.InputObject.FullName -Destination $minecraftLocalSave -Container -Recurse
}
( {$PSItem.SideIndicator -eq "=>"}) {
Write-Output "Copying to cloud: $($PSItem.InputObject.Name)"
Copy-Item -Path $PSItem.InputObject.FullName -Destination $minecraftCloudSave -Container -Recurse
}
( {$PSItem.SideIndicator -eq "=="}) {
$cloudLatest = (( Get-ChildItem ( $minecraftCloudSave + "\" + $PSItem.InputObject) -Recurse -File ).LastWriteTime | Measure-Object -Maximum)
$localLatest = (( Get-ChildItem ( $minecraftLocalSave + "\" + $PSItem.InputObject) -Recurse -File ).LastWriteTime | Measure-Object -Maximum)
if ($cloudLatest.Maximum -eq $localLatest.Maximum) {
if ($cloudLatest.Count -gt $localLatest.Count) {
Write-Output "Adding files from cloud: $($PSItem.InputObject.Name)"
xcopy ($minecraftCloudSave + "\" + $PSItem.InputObject) $minecraftLocalSave /d /e /c /i /h /y
}
else {
Write-Output "Already synchronized: $($PSItem.InputObject.Name)"
}
}
elseif ($cloudLatest.Maximum -gt $localLatest.Maximum) {
$world = $PSItem.InputObject.Name
Write-Output "Over-writing local with $world"
$old = Rename-Item -Path "$minecraftLocalSave\$world" -NewName ($world + "_old") -PassThru
Copy-Item -Path "$minecraftCloudSave\$world" -Destination $minecraftLocalSave -Container -Recurse
Remove-Item -Recurse -Force -Path $old
}
elseif ($cloudLatest.Maximum -lt $localLatest.Maximum) {
$world = $PSItem.InputObject.Name
Write-Output "Updating cloud with $world"
$old = Rename-Item -Path "$minecraftCloudSave\$world" -NewName ($world + "_old") -PassThru
Copy-Item -Path "$minecraftLocalSave\$world" -Destination $minecraftCloudSave -Container -Recurse
Remove-Item -Recurse -Force -Path $old
}
else {
Write-Error "Something went wrong with the folder comparison."
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Looks fine for me. As a note - instead of using <code>Write-Output</code> for display purposes use <code>Write-Host</code> cmdlet. </p>\n\n<p>In a nutshell, <code>Write-Host</code> writes to the console itself. Think of it as a <code>MsgBox</code> in <code>VBScript</code>. <code>Write-Output</code... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T17:38:33.120",
"Id": "203494",
"Score": "2",
"Tags": [
"file-system",
"windows",
"powershell",
"scheduled-tasks"
],
"Title": "Powershell for syncing Minecraft save files"
} | 203494 |
<p>I've tried to do some BDD in Golang using Godog.</p>
<p>File <code>Hello.feature</code>:</p>
<pre><code>Feature: Hello World
Scenario: Hello World
When running hello
Then it prints:
"""
Hello, world!
"""
</code></pre>
<p>File <code>hello_test.go</code>:</p>
<pre><code>package main
import (
"bytes"
"fmt"
"github.com/DATA-DOG/godog"
"github.com/DATA-DOG/godog/gherkin"
)
var InterceptedStdout bytes.Buffer
func runningHello() error {
hello(&InterceptedStdout)
return nil
}
func itPrints(expectedDocString *gherkin.DocString) error {
var actual = InterceptedStdout.String()
var expected = expectedDocString.Content
if expected != actual {
return fmt.Errorf("expected: \"%s\", Actual: \"%s\"", expected, actual)
}
return nil
}
//noinspection GoUnusedExportedFunction
func FeatureContext(s *godog.Suite) {
s.Step(`^it prints:$`, itPrints)
s.Step(`^running hello$`, runningHello)
}
</code></pre>
<p>File <code>main.go</code>:</p>
<pre><code>package main
import (
"fmt"
"io"
"os"
)
func main() {
hello(os.Stdout)
}
func hello(out io.Writer) {
fmt.Fprintln(out, "Hello, world!")
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T17:54:38.670",
"Id": "203496",
"Score": "2",
"Tags": [
"go",
"bdd"
],
"Title": "Hello, World BDD in Golang"
} | 203496 |
<p>This is not an actual administration system. It is just homework. I haven't finished the project yet, but I would like some advice on how to improve what I have done so far.</p>
<p>main.py:</p>
<pre><code>from file import File
from random import choice
class Main:
def __init__(self):
# The file_handler object will be used to read and write to files.
self.file_handler = File()
login_menu_is_running = True
while login_menu_is_running:
print('1 - Sign up')
print('2 - Login')
menu_choice = input('\nEnter menu option: ')
login_menu_is_running = False
if menu_choice == '1':
self.signup()
elif menu_choice == '2':
self.login()
else:
print('Please choose a number from the menu.')
login_menu_is_running = True
menu_is_running = True
while menu_is_running:
print('\n1 - Add a new student to the system.')
print('2 - Display a student\'s details.')
print('3 - Edit a students details.')
print('4 - Log out.')
menu_choice = input('\nEnter menu option: ')
if menu_choice == '1':
self.add_student()
elif menu_choice == '2':
self.print_student_details()
elif menu_choice == '3':
self.edit_student_details()
elif menu_choice == '4':
menu_is_running = False
else:
print('Please choose a number from the menu.')
def signup(self):
username = input('Enter username: ')
password = input('Enter password: ')
if len(password) < 8:
print('Password should contain at lease 8 characters.')
self.signup()
else:
self.file_handler.add_account(username, password)
def login(self):
accounts = self.file_handler.get_accounts()
input_loop = True
while input_loop:
username_attempt = input('Enter username: ')
for account in accounts:
account = account.split(', ')
if username_attempt == account[0]:
password_attempt = input('Enter password: ')
if password_attempt == account[1]:
print('\nLogin successful.')
return
print('Incorrect username or password.')
def add_student(self):
print('Please enter the student\'s details:\n')
surname = input('Surname: ')
forename = input('Forename: ')
date_of_birth = input('Date of birth: ')
home_address = input('Home address: ')
home_phone_number = input('Home phone number: ')
gender = input('Gender: ')
student_id = self.get_new_id()
tutor_group = self.get_tutor_group()
school_email_address = student_id + '@student.treehouseschool.co.uk'
details = [
student_id, surname, forename, date_of_birth,
home_address, home_phone_number, gender,
tutor_group, school_email_address
]
details = ', '.join(details)
self.file_handler.add_student(details)
print('\nThe new student has been added.')
print(('His' if gender.lower() == 'male' else 'Her'), 'student ID is', student_id)
def get_new_id(self):
lines = self.file_handler.get_students()
if len(lines) <= 1:
return '0000'
last_line = lines[-2].split(', ')
new_id = str(int(last_line[0]) + 1)
zeros = '0' * (4 - len(new_id))
new_id = zeros + new_id
return new_id
@staticmethod
def get_tutor_group():
return choice(['Amphtill Leaves', 'London Flowers', 'Kempston Stones', 'Cardington Grass'])
def edit_student_details(self):
print('Sorry, this feature has not been added yet.')
def print_student_details(self):
student_id = input('Enter student ID: ')
lines = self.file_handler.get_students()
details_found = False
for line in lines:
details = line.split(', ')
if details[0] == student_id:
details_found = True
break
if details_found:
print('ID: ', details[0])
print('Surname: ', details[1])
print('Forename: ', details[2])
print('Date of birth: ', details[3])
print('Home address: ', details[4])
print('Home phone number: ', details[5])
print('Gender: ', details[6])
print('Tutor group: ', details[7])
print('School email address: ', details[8])
else:
print('Student ', student_id, ' could not be found.')
if __name__ == '__main__':
Main()
</code></pre>
<p>file.py:</p>
<pre><code>class File:
@staticmethod
def get_accounts():
with open('accounts.txt', 'r') as file:
return file.read().split('\n')
@staticmethod
def add_account(username, password):
with open('accounts.txt', 'a') as file:
file.write(username)
file.write(', ')
file.write(password)
file.write('\n')
@staticmethod
def get_students():
with open('student_details.txt', 'r') as file:
return file.read().split('\n')
@staticmethod
def add_student(student_details):
with open('student_details.txt', 'a') as file:
file.write(student_details)
file.write('\n')
@staticmethod
def remove_student(student_id):
pass
</code></pre>
| [] | [
{
"body": "<p>This isn't a comprehensive review because that's not possible with incomplete code, but I think there's enough here to make a few remarks. First, a few things I like:</p>\n\n<ol>\n<li>The careful control flow, including making sure that menu entries are valid, is good.</li>\n<li>The use of the if ... | {
"AcceptedAnswerId": "203500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T18:17:33.473",
"Id": "203497",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "School Administration System in Python 3"
} | 203497 |
<p>I have an array. Now I want to find the total of, sum of the subarray multiplied by its last element, for all the possible subarrays. This is what I have right now:</p>
<pre><code>n = int(input())
a = []
for _ in range(n):
a.append(int(input()))
total = 0
for i in range(1, n+1):
for j in range(n+1-i):
temp = a[j:j+i]
total += sum(temp)*temp[-1]
print(total)
</code></pre>
<p><strong>Example Input:</strong></p>
<pre><code>3
1
2
3
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>53
</code></pre>
<p><strong>Explanation:</strong></p>
<pre><code>1*1 + 2*2 + 3*3 + (1+2)*2 + (2+3)*3 + (1+2+3)*3 = 53
</code></pre>
<p>My code works fine, but is quite slow. How can I optimise it?</p>
| [] | [
{
"body": "<p>First I would suggest to separate I/O from the computation,\nand define a function to compute the subarray sum. That increases\nthe clarity of the program and allows to add test cases more easily:</p>\n\n<pre><code>def subarray_sum(a):\n \"\"\"Compute sum of all subarrays of a, multiplied by it... | {
"AcceptedAnswerId": "203511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T19:15:20.337",
"Id": "203503",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"array"
],
"Title": "Find sum of all the subarrays of an array"
} | 203503 |
<p>I recently learned Python using the book by <em>Mark Summerfeld</em> and I am now doing a few <em>katas</em> of mine when I learn a new language. This helps to get the “how the language works” and I wrote a simple lexer for Apache logs.</p>
<p>An example of log records are</p>
<pre><code>64.242.88.10 - - [07/Mar/2004:16:05:49 -0800] "GET /twiki/bin/edit/Main/Double_bounce_sender?topicparent=Main.ConfigurationVariables HTTP/1.1" 401 12846
64.242.88.10 - - [07/Mar/2004:16:06:51 -0800] "GET /twiki/bin/rdiff/TWiki/NewUserTemplate?rev1=1.3&rev2=1.2 HTTP/1.1" 200 4523
64.242.88.10 - - [07/Mar/2004:16:10:02 -0800] "GET /mailman/listinfo/hsdivision HTTP/1.1" 200 6291
</code></pre>
<p>and program I wrote reads all values as tokens and output them using <code>|</code> as a separator, as in</p>
<pre><code>64.242.88.10|-|-|07/Mar/2004:16:05:49 -0800|GET /twiki/bin/edit/Main/Double_bounce_sender?topicparent=Main.ConfigurationVariables HTTP/1.1|401|12846
64.242.88.10|-|-|07/Mar/2004:16:06:51 -0800|GET /twiki/bin/rdiff/TWiki/NewUserTemplate?rev1=1.3&rev2=1.2 HTTP/1.1|200|4523
64.242.88.10|-|-|07/Mar/2004:16:10:02 -0800|GET /mailman/listinfo/hsdivision HTTP/1.1|200|6291
</code></pre>
<p>The lexer can be used for more general usage though.</p>
<p>Here is my code and I would love to read your comments and suggestions about how to improve it. I have also raised a few specific questions on certain topics.</p>
<pre><code>import collections
import io
import sys
LEXER_SKIP_WHITESPACE=0
LEXER_READ_QUOTED_STRING=1
LEXER_READ_BRACKETED_STRING=2
LEXER_READ_WORD=3
class Location:
def __init__(self, name=None, pos=0, line=1, col=0):
self.name = name or "<input>"
self.line = line
self.col = col
self.pos = pos
def update(self, c):
self.pos += 1
if c == "\n":
self.line += 1
self.col = 0
else:
self.col += 1
def __repr__(self):
return str.format("Location({}, {}, {}, {})", repr(self.name), repr(self.pos), repr(self.line), repr(self.col))
def __str__(self):
return str.format("{}: {}: line {}, column {}", self.name, self.pos, self.line, self.col)
def readchar(inputchannel, location):
while True:
maybechar = inputchannel.read(1)
if maybechar == '':
return None
else:
location.update(maybechar)
yield maybechar
def readtoken(inputchannel, location):
state = LEXER_SKIP_WHITESPACE
token = ''
for nextchar in readchar(inputchannel, location):
if state is LEXER_SKIP_WHITESPACE:
if nextchar == "\n":
yield "\n"
continue
elif nextchar.isspace():
continue
elif nextchar == '"':
state = LEXER_READ_QUOTED_STRING
continue
elif nextchar == '[':
state = LEXER_READ_BRACKETED_STRING
continue
else:
state = LEXER_READ_WORD
token += nextchar
continue
elif state is LEXER_READ_QUOTED_STRING:
if nextchar == '"':
yield token
token = ''
state = LEXER_SKIP_WHITESPACE
continue
else:
token += nextchar
continue
elif state is LEXER_READ_BRACKETED_STRING:
if nextchar == ']':
yield token
token = ''
state = LEXER_SKIP_WHITESPACE
continue
else:
token += nextchar
continue
elif state is LEXER_READ_WORD:
if nextchar == "\n":
yield token
token = ''
state = LEXER_SKIP_WHITESPACE
yield "\n"
continue
elif nextchar.isspace():
yield token
token = ''
state = LEXER_SKIP_WHITESPACE
continue
else:
token += nextchar
continue
else:
raise Error("Impossible lexer state.")
if state is LEXER_SKIP_WHITESPACE:
return None
elif state is LEXER_READ_QUOTED_STRING:
raise Error("End of character stream in quoted string.")
elif state is LEXER_READ_BRACKETED_STRING:
raise Error("End of character stream in quoted string.")
elif state is LEXER_READ_WORD:
yield token
return None
else:
raise Error("Impossible lexer state.")
class Lexer:
def __init__(self, inputchannel, _location=None):
self.location = _location or Location("<input>", 0, 1, 0)
self.inputchannel = inputchannel
self.buf = ''
self.state = LEXER_SKIP_WHITESPACE
def __iter__(self):
return readtoken(self.inputchannel, self.location)
if __name__ == "__main__":
sep = ''
for token in Lexer(sys.stdin):
if token == '\n':
sys.stdout.write(token)
sep = ''
else:
sys.stdout.write(sep)
sys.stdout.write(token)
sep = '|'
</code></pre>
<h1>Question 1 – How to write lexers in Python?</h1>
<p>I am well aware that there are tools similar to lex and yacc for Python that could have been used here, but that would defeat the purpose of learning how to write such a program in Python. I found it surprisingly hard.</p>
<p>My first misfortune is that Python does not do tail-elimination, so it is essentially forbidden to write a lexer as a set of mutually recursive functions. Mutually recursive functions are one of my favourite tools to do so, because it clearly singles out a specific state of the lexer (the recursive function it is in) and the transitions from this state to the other states, and makes it easy to test-case individually each of the transitions.</p>
<p>Since maybe not everybody is familiar with lexers based on mutually recursive functions here is the equivalent of the readtoken generator in OCaml. The beginning of <code>read_token</code> reads like "If you read a double quote, discard it and do <code>read_quotedstring</code>" and that function itself is defined later and does what on expects: it aggregates characters in a buffer until the next double quote and bless the result as a token.</p>
<pre><code>let rec read_token f ((ax,buffer) as state) s =
match Stream.peek s with
| Some('"') -> Stream.junk s; read_quotedstring f state s
| Some('[') -> Stream.junk s; read_timestamp f state s
| Some(' ')
| Some('\t')-> Stream.junk s; read_token f state s
| Some(c) -> read_simpleword f state s
| None -> ax
and read_simpleword f ((ax,buffer) as state) s =
match Stream.peek s with
| Some('"')
| Some('[')
| Some(' ')
| Some('\t') ->
let current_token = Buffer.contents buffer in
Buffer.clear buffer;
read_token f (f ax current_token, buffer) s
| Some(c) ->
Buffer.add_char buffer c;
Stream.junk s;
read_simpleword f state s
| None ->
ax
and read_quotedstring f ((ax,buffer) as state) s =
match Stream.peek(s) with
| Some('"') ->
Stream.junk s;
let current_token = Buffer.contents buffer in
Buffer.clear buffer;
read_token f (f ax current_token, buffer) s
| Some(c) ->
Stream.junk s;
Buffer.add_char buffer c;
read_quotedstring f state s
| None ->
failwith "End of stream within a quoted string"
and read_timestamp f ((ax,buffer) as state) s =
match Stream.peek(s) with
| Some(']') ->
Stream.junk s;
let current_token = Buffer.contents buffer in
Buffer.clear buffer;
read_token f (f ax (timestamp_to_iso current_token), buffer) s
| Some(c) ->
Stream.junk s;
Buffer.add_char buffer c;
read_timestamp f state s
| None ->
failwith "End of stream within a bracketed string"
</code></pre>
<p>My Python version defines a few states as symbolic constants as I would have done in C and then build a huge while loop keeping track of the transitions. I am not please with that implementation, because it does not give me any tool to manage the complexity of the lexer. Working with functions is very unpleasant because of the details of the scope of variables in Python. So what would be the idiomatic way to break down the lexer in small testable pieces, which would be important if I would decide to write a more complicate parser? Could the idea to represent lexer-states by objects be interesting?</p>
<h1>Question 2. Is it right to treat stdin as a character stream?</h1>
<p>Obviously I somehow did that but Python has no real character type and makes them look like length 1 strings. It feels to me that the approach of reading my input in chunks into “circular expandable buffers” and making copies of substrings of these chunks to generate my tokens would fit much more nicely in the language. Am I right?</p>
<h1>Question 3. What is the all-purpose exception in Python?</h1>
<p>This seems like a rather basic question but I am really failing to find a suitable answer in <a href="https://docs.python.org/3/library/exceptions.html#bltin-exceptions" rel="nofollow noreferrer">the documentation</a> The <code>Exception</code> seems a poor choice, since it very general and make error identification and error handling rather complicated.</p>
<h1>Question 4. Do generators return none?</h1>
<p>Is it good style to return <code>None</code> in generators? Would pass also do?</p>
| [] | [
{
"body": "<p>Note: I'm assuming that this code works and you seek only 'code quality' improvements. Also, you seem like experienced programmer so I will try not to explain trivial things but please, do ask if you think I didn't state my opinion clearly enough. </p>\n\n<h1>Code notes:</h1>\n\n<h3>General</h3>\n... | {
"AcceptedAnswerId": "203893",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T19:19:45.940",
"Id": "203504",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"lexer"
],
"Title": "Lexer for Apache logs in Python"
} | 203504 |
<p>I have two list of tuples:</p>
<pre><code> [[1,8],[2,7],[3,14]]
[[1,5],[2,10],[3,14]]
</code></pre>
<p>and a desired sum 20. I need to find two tuples from two list whose second element either add it to the sum i.e 20 or the next lowest sum. In this case if we consider [3,14] and [1,5] the sum is 14+5=19 hence the output should be <strong>[3,1]</strong></p>
<pre><code>[1,3000],[2,5000],[3,7000],[4,10000]
[1,2000],[2,3000],[3,4000],[4,5000]]
</code></pre>
<p>the sum is 10000. Here we have [2,5000], [4,5000] and [3,7000], [2,3000] so the output should be <strong>[2,4]</strong> and <strong>[3,2]</strong></p>
<pre><code>[[1,2000],[2,4000],[3,6000]]
[[1,2000]]
</code></pre>
<p>the sum is 7000. Here since I don't have a combination that sum up to 7000 I consider all the possible combinations 4000(2000+2000), 6000(4000+2000) and 8000(6000+2000) and consider the next lowest number from the desired sum which is 600. For 6000 my output should be [2,4000] and [1,2000] which is <strong>[2,1]</strong>.</p>
<pre><code>import itertools
def optimalUtilization(maximumOperatingTravelDistance,
forwardShippingRouteList, returnShippingRouteList):
result=[]
t1=[]
t2=[]
for miles in forwardShippingRouteList:
t1.append(miles[1])
for miles in returnShippingRouteList:
t2.append(miles[1])
result.append(t1)
result.append(t2)
total_sum=set()
for element in list(itertools.product(*result)):
if sum(element)<=maximumOperatingTravelDistance:
total_sum.add(sum(element))
total_sum=sorted(total_sum,reverse=True)
return optimalUtilizationhelper(total_sum[0],
forwardShippingRouteList, returnShippingRouteList)
def optimalUtilizationhelper(maximumOperatingTravelDistance,
forwardShippingRouteList, returnShippingRouteList):
dist_dict={}
for carid,miles in forwardShippingRouteList:
dist_dict.update({miles:carid})
result=[]
for carid,miles in returnShippingRouteList:
if (maximumOperatingTravelDistance-miles) in dist_dict:
result.append(list((dist_dict[maximumOperatingTravelDistance-miles],carid)))
return result
</code></pre>
<p>I get the desired result here but the complexity here is \$O(n^2 \log n)\$. What is a better way to do this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T08:22:59.533",
"Id": "392310",
"Score": "0",
"body": "are the tuples ascending?"
}
] | [
{
"body": "<h1>Review</h1>\n\n<ol>\n<li><p>No need for all these intermediate <code>temp</code> variables</p>\n\n<p>You loop over a and b to append to the result which is unnecessary.</p>\n\n<p>Only afterwards you create the products but this can be done before.</p></li>\n<li><p>The <code>sort</code> is not nee... | {
"AcceptedAnswerId": "203551",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T19:53:45.877",
"Id": "203506",
"Score": "3",
"Tags": [
"python",
"performance",
"k-sum"
],
"Title": "Pairwise adding tuples in a list"
} | 203506 |
<p>I'm trying to get and save in an ArrayList Reddit posts and comments.
The code is very similar for both:</p>
<p>The RedditThing is a parent of RedditPost and RedditComment:</p>
<pre><code>class RedditThing {
String author; String subreddit; String body; long score;
public void setAuthor(String authorUsername) {
this.author = author; }
public void setSubreddit(String subreddit) {
this.subreddit = subreddit; }
public void setBody(String body) {
this.body = body; }
public void setScore(long score) {
this.score = score; }
public String getBody() {
return body; }
public String getSubreddit() {
return subreddit; }
public String getAuthor() {
return author; }
public long getScore() {
return score; }
public String toString() {
return subreddit + "=> " + score + "=>" + author + ": " + body; }
}
private class RedditComment extends RedditThing {
}
private class RedditPost extends RedditThing {
String title;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
</code></pre>
<p>Right now I have the getPosts method:</p>
<pre><code>public ArrayList<RedditPost> getPosts(String subreddit, String postsType) {
ArrayList<RedditPost> result = new ArrayList<RedditPost>();
StringBuilder link = new StringBuilder("https://oauth.reddit.com");
link.append("/r/" + subreddit + "/" + postsType);
try {
URL url = new URL(link.toString()); //the same for comment
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //the same for comment
setupGETConnection(connection); //the same for comment
connection.connect(); //the same for comment
System.out.println("Done get posts");
InputStream input = connection.getInputStream(); //the same for comment
String inputString = new Scanner(input, "UTF-8").useDelimiter("\Z").next(); //the same for comment
JSONObject jsonObject = new JSONObject(inputString); //the same for comment
JSONArray posts = (JSONArray) ((JSONObject) jsonObject.get("data")).get("children");
for (int i=0; i<posts.length(); i++) { //the same for comment
JSONObject postObject = (JSONObject) posts.get(i); //the same for comment
JSONObject postData = (JSONObject) postObject.get("data"); //the same for comment
RedditPost post = new RedditPost();
post.setTitle((String) postData.get("title"));
post.setAuthor((String) postData.get("author")); //the same for comment
post.setBody((String) postData.get("selftext"));
post.setScore(((Integer) postData.get("score")).longValue()); //the same for comment
post.setSubreddit((String) postData.get("subreddit")); //the same for comment
result.add(post); //the same for comment
}
System.out.println(inputString); //the same for comment
}
catch (Exception e) {
System.out.println(e); //the same for comment
}
return result; //the same for comment
}
</code></pre>
<p>I have commented the lines that are going to be duplicate if I create a separate getComments method.</p>
<pre><code>public ArrayList<RedditComment> getComments(String thing_id) { //different
ArrayList<RedditComment> result = new ArrayList<RedditComment>(); //different
StringBuilder link = new StringBuilder("https://oauth.reddit.com/r/childfree/comments/"); //different
link.append(thing_id);
try {
URL url = new URL(link.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
setupGETConnection(connection);
connection.connect();
System.out.println("Done get comments"); //different
InputStream input = connection.getInputStream();
String inputString = new Scanner(input, "UTF-8").useDelimiter("\Z").next();
JSONArray jsonArray = new JSONArray(inputString);
JSONArray comments = (JSONArray) ((JSONObject) ((JSONObject) jsonArray.get(1)).get("data")).get("children"); //different
for (int i=0; i<comments.length(); i++) {
JSONObject commentObject = (JSONObject) comments.get(i);
JSONObject commentData = (JSONObject) commentObject.get("data");
RedditComment comment = new RedditComment();
comment.setAuthor((String) commentData.get("author"));
comment.setBody((String) commentData.get("body")); //different
comment.setScore(((Integer) commentData.get("score")).longValue());
comment.setSubreddit((String) commentData.get("subreddit"));
result.add(comment);
}
System.out.println(inputString);
}
catch (Exception e) {
System.out.println(e);
}
return result;
}
</code></pre>
<p>I was wondering if there's a better way than just creating two separate methods with a significant portion of the duplicated code.</p>
| [] | [
{
"body": "<p>Well, the methods are not <em>that</em> similar... basically, the real duplication is just reading a URL and parsing it into a json array, where the only difference is the message you print to stdout. As <code>System.out.println()</code> <em>normally</em> is just a temporaty solution (like: c'mon,... | {
"AcceptedAnswerId": "203526",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T19:59:13.903",
"Id": "203507",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"json",
"generics",
"reddit"
],
"Title": "Saving Reddit posts and comments from JSON into ArrayLists"
} | 203507 |
<blockquote>
<p>I've been working on this probability game that has a gun with 5/6
bullets. When there's a dodge the game removes a bullet and then the
game continues, the goal being to get to 0 bullets.</p>
</blockquote>
<p>I don't use a <code>var</code> to keep the score counts because it's easier to flush it by adding the new sentence in. Are there any big mistakes in my code, or things that should be done better?</p>
<pre><code>import Cocoa
let appWindow = NSWindow()
let gunTrigger = NSButton(frame: CGRect(x: 155, y: 5, width: 210, height: 19))
class ShootMeSomelexhoe: NSObject, NSApplicationDelegate{
func applicationDidFinishLaunching(_ notification: Notification) {
appWindow.setContentSize(NSSize(width: 520, height: 30))
appWindow.titlebarAppearsTransparent = true
appWindow.backgroundColor = NSColor.white
appWindow.isMovableByWindowBackground = true
appWindow.contentView?.addSubview(gunTrigger)
appWindow.title = " = 5/6 ⁍ ☠️ Dodge = 1 less ⁍ Empty without ☠️ = Win!"
appWindow.setFrameAutosaveName(NSWindow.FrameAutosaveName(rawValue: "fun-roulette"))
appWindow.makeKeyAndOrderFront(nil)
gunTrigger.bezelStyle = .roundRect
gunTrigger.title = "⁍⁍⁍⁍⁍"
gunTrigger.action = #selector(clickedTrigger)
}
@objc func clickedTrigger(){
if !(arc4random_uniform(6) + 1 > gunTrigger.title.count){
gunTrigger.title = "⁍⁍⁍⁍⁍"
appWindow.title = "saddly u died :(" + String(appWindow.title.components(separatedBy: "").count) + " attemp(s)." + String(repeating: "", count: appWindow.title.components(separatedBy: "").count) //Adds "U+200B" for attempps count.
}
else{
if gunTrigger.title.count != 1{
gunTrigger.title = String(gunTrigger.title.dropLast())
appWindow.title = "u dodged death! lets keep playing our luck" + String(appWindow.title.components(separatedBy: "").count) + " attemp(s)." + String(repeating: "", count: appWindow.title.components(separatedBy: "").count) //Adds "U+200B" for attempps count.
}
else{
gunTrigger.title = "⁍⁍⁍⁍⁍"
NSSound(named: NSSound.Name(rawValue: "Glass"))?.play()
appWindow.title = "Congradulation u just won the game of life. enjoy!!!!" + String(appWindow.title.components(separatedBy: "").count) + " attempts."
}
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T20:06:04.813",
"Id": "203509",
"Score": "3",
"Tags": [
"game",
"random",
"swift",
"cocoa"
],
"Title": "Probability shooting game"
} | 203509 |
<p>I am trying in R to "center" a matrix (i.e. remove mean) group-wise (i.e. remove group means for each variable).</p>
<p>Input is a matrix (including the grouping variable), and output is the same matrix, where columns are now group-wise centered (possibly excluding now grouping variable).</p>
<p>I tried 3 solutions:</p>
<ol>
<li>Using <code>dplyr</code>: use <code>group_by(cell)</code> and <code>mutate_all(funs(. - mean(.)))</code></li>
<li>Using <code>data.table</code>: <code>dt[, lapply(.SD, function(x) x - mean(x)), by= cell]</code></li>
<li>Using <code>data.table</code>: same as above, but in 2 steps: instead of over-writing variables, 1) add mean variables as new columns, 2) then compute differences, splitting the original matrix as two different matrices.</li>
</ol>
<p>Results in terms of speed are: <code>3 < 2 < 1</code>. (3) being faster than (2) is surprising (as (2) is just overwriting variables, not adding)... I suspect it could be from the fact that using <code>function(x) x - mean(x)</code> prevents <code>data.table</code> to use an optimised version of the mean function. </p>
<p>My questions are:</p>
<ol>
<li>Any way I can speed up some of the code?</li>
<li>How can I understand (3) is faster than (2)? Can I get (2) to be faster?</li>
</ol>
<p></p>
<p><a href="https://i.stack.imgur.com/mibIh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mibIh.png" alt="enter image description here"></a></p>
<pre><code>library(tidyverse)
library(data.table)
## function (1)
center_dplyr <- function(x) {
x %>%
group_by(cell) %>%
mutate_all(funs(. - mean(.))) %>%
ungroup() %>%
dplyr::select(-cell)
}
## function (2)
center_dt_1 <- function(x) {
x <- as.data.table(x)
setkey(x, cell)
res <- x[, lapply(.SD, function(x) x - mean(x)), by= cell][, -"cell"]
as.data.frame(res)
}
## function (3)
center_dt_2 <- function(x) {
x <- as.data.table(x)
x_names <- colnames(x)[colnames(x) !="cell"]
x_names_new <- paste(x_names, "mean", sep="_")
setkey(x, cell)
x[, paste(x_names, "mean", sep="_"):= lapply(.SD, mean, na.rm = TRUE), by = cell]
res <- x[, x_names, with=FALSE] - x[, x_names_new, with=FALSE]
as.data.frame(res)
}
## Data
T = 6;
N = 10^4
set.seed(123)
sim_df <- data.frame(A = sample(c(0,1), N * T, replace = TRUE),
B1 = sample(c(0,1), N * T, replace = TRUE),
B2 = rnorm(N),
cell = rep(1:N, each = T))
ans_dplyr <- center_dplyr(x=sim_df)
ans_dt1 <- center_dt_1(sim_df)
ans_dt2 <- center_dt_2(sim_df)
all.equal(ans_dt1, ans_dplyr, check.attributes = FALSE)
all.equal(ans_dt2, ans_dplyr, check.attributes = FALSE)
### Benchmark:
library(microbenchmark)
## small
sim_df_s <- sim_df[1:1000,]
bench_small <- microbenchmark(ans_dplyr = center_dplyr(sim_df_s),
ans_dt1 = center_dt_1(sim_df_s),
ans_dt2 = center_dt_2(sim_df_s),
times = 10)
bench_large <- microbenchmark(ans_dplyr = center_dplyr(sim_df),
ans_dt1 = center_dt_1(sim_df),
ans_dt2 = center_dt_2(sim_df),
times = 10)
bench_all <- rbind(bench_small %>% summary %>% mutate(data_size = "small"),
bench_large %>% summary %>% mutate(data_size = "large")) %>%
select(data_size)
bench_all
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T03:34:44.777",
"Id": "392282",
"Score": "1",
"body": "Potentially some performance could be gained by avoiding `as.data.frame/as.data.table` and using `setDF/setDT` as the former copy their inputs. That said, you might need the inpu... | [
{
"body": "<p>This answer only goes to how to speed up processing and doesn't get at the intricacies of data.table vs dplyr under the hood.</p>\n\n<p>Below is a slightly faster version (at least for larger datasets).</p>\n\n<p>Rather than create additional columns in the main DT, I created a new DT that had the... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-10T20:24:42.697",
"Id": "203513",
"Score": "4",
"Tags": [
"performance",
"matrix",
"r"
],
"Title": "Group-wise deviations from means / centering with dplyr vs. data.table"
} | 203513 |
<p>Can anyone here comment on the quality of this test case? I am here testing for the exception should be thrown scenario. I mean it works but is it the correct way to unit test for the scenarios where the expectation is that exception should be thrown?</p>
<pre><code>it('should throw exception if config.env.json is malformed', async () => {
// Arrange: beforeEach
const fakeFsStub = sinon.stub(File, 'readFileAsyc');
fakeFsStub.withArgs('./src/configuration/config.json').returns(mockConfig);
fakeFsStub.withArgs('./src/configuration/config.test.json').returns(FakePromise.resolve(`{"key"}`));
try {
// Act
await Configuration.getConfiguration('test');
chai.assert.fail('test case failed: [should throw exception if config.env.json is malformed]');
} catch (e) {
// Assert
chai.assert.equal('SyntaxError: Unexpected token } in JSON at position 6', e + '');
}
});
</code></pre>
| [] | [
{
"body": "<p>You should be using the Chai <code>assert.throws</code> operator instead (<a href=\"http://www.chaijs.com/api/assert/#method_throwsO\" rel=\"nofollow noreferrer\">http://www.chaijs.com/api/assert/#method_throwsO</a> so your code might look like:</p>\n\n<pre><code>it('should throw exception if conf... | {
"AcceptedAnswerId": "203522",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T02:50:08.860",
"Id": "203520",
"Score": "1",
"Tags": [
"javascript",
"unit-testing",
"jasmine"
],
"Title": "Writing unit tests for exception should be thrown case"
} | 203520 |
<p>I have to create a form, which enables users to move stock of items to different statuses. The form will show the current stock(quantity) in a given status and then 5 input fields corresponding to 5 statuses. The user can input into one or more fields as to the quantity that they want to be moved into the new status. Once the user submits the form, based on whether a field has value, I have to put an entry corresponding to that entry into a table which will store some common properties as well as the intended status and the quantity of each.</p>
<p>Consider the following scenario, if total stock in status Purchased is 100. </p>
<ul>
<li>Production - 30</li>
<li>Finished - 20</li>
<li>Finished (Internal Only)</li>
<li>Wastage </li>
<li>Base Stock - 50</li>
</ul>
<p>I will need to create 3 entries corresponding to Production, Finished and Base Stock, respectively from a single object returned from the front end form.</p>
<p>The application is written in AngularJS and C# Web API. The following is what I have written so far. WStockStatus is a single object in which I capture the input values from front end as separate fields.</p>
<p>Does this follow best practices? Is there a better way to go about it? </p>
<pre><code>public bool moveStock(WStockStatus fromStockStatus)
{
const int STATUS_BASE = 1;
const int STATUS_FIN = 2;
const int STATUS_FINI = 3;
const int STATUS_WAST = 4;
const int STATUS_PRGR = 5;
StockStatus stockStatus = new StockStatus();
stockStatus.date = fromStockStatus.date;
stockStatus.location = fromStockStatus.location;
if(fromStockStatus.qtyBase > 0)
{
stockStatus.quantityUOM = fromStockStatus.qtyBase;
stockStatus.status = STATUS_BASE;
createStockStatus(stockStatus); //another function that creates individual entry for stock status
}
if(fromStockStatus.qtyFin > 0)
{
stockStatus.quantityUOM = fromStockStatus.qtyFin;
stockStatus.status = STATUS_FIN;
createStockStatus(stockStatus);
}
if(fromStockStatus.qtyFini > 0)
{
stockStatus.quantityUOM = fromStockStatus.qtyFini;
stockStatus.status = STATUS_FINI;
createStockStatus(stockStatus);
}
if(fromStockStatus.qtyWast > 0)
{
stockStatus.quantityUOM = fromStockStatus.qtyWast;
stockStatus.status = STATUS_WAST;
createStockStatus(stockStatus);
}
if(fromStockStatus.qtyPrgr > 0)
{
stockStatus.quantityUOM = fromStockStatus.qtyPrgr;
stockStatus.status = STATUS_PRGR;
createStockStatus(stockStatus);
}
return true;
}
private void createStockStatus(StockStatus newObj)
{
if (newObj.isValid())
{
newObj.deleted = false;
newObj.submittedId = null;
UserPersonal user = context.UserPersonal.FirstOrDefault(u => u.email == currentUserEmail);
newObj.setCreatedTimeStamp(user); //sets fields CreatedBy, ModifiedBy with value of user
context.StockStatus.Add(newObj);
context.SaveChanges();
}
return null;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T05:05:23.247",
"Id": "392288",
"Score": "0",
"body": "Those are used to indicate other assignment statements which are totally not related to the problem at hand. Do I still need to put the code in place?"
},
{
"ContentLicen... | [
{
"body": "<p>This</p>\n\n<blockquote>\n<pre><code>const int STATUS_BASE = 1;\nconst int STATUS_FIN = 2;\nconst int STATUS_FINI = 3;\nconst int STATUS_WAST = 4;\nconst int STATUS_PRGR = 5; \n</code></pre>\n</blockquote>\n\n<p>screams for an enum like </p>\n\n<pre><code>public enum StockState\n{\n Base = 1,... | {
"AcceptedAnswerId": "203528",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T04:31:40.483",
"Id": "203523",
"Score": "3",
"Tags": [
"c#",
"angular.js",
"asp.net-web-api"
],
"Title": "Create objects corresponding to whichever field has value from among a list of fields"
} | 203523 |
<p>I'm working on my <code>Django</code> project and I'm trying to develop this one with 'Class Based View' (CBV) method in order to keep the code maintainable.</p>
<p>I have a class named <code>FreepubHome</code> with some methods and a very important <code>post</code> method. I would like to split this method into three methods and I don't know how I can do that.</p>
<p>This post method let to:</p>
<ul>
<li>fill and submit the form</li>
<li>create a token</li>
<li>send an e-mail</li>
</ul>
<p>So I would like to get a post function which let to fill and submit my form, call the token method and the sending method.</p>
<p>It's very important for me to understand the process, the methodology and how I can do that in order to simplify others methods that are very important.</p>
<p>This is my class :</p>
<pre><code>from django.template.loader import get_template
from django.core.mail import EmailMultiAlternatives
from django.views.generic import CreateView
import hashlib
from .models import Publication, Document, Download
class FreepubHomeView(CreateView):
""" Render the home page """
template_name = 'freepub/index.html'
form_class = CustomerForm
def get_context_data(self, **kwargs):
kwargs['document_list'] = Document.objects.all().order_by('publication__category__name')
return super(FreepubHomeView, self).get_context_data(**kwargs)
@staticmethod
def create_token(self, arg1, arg2, datetime):
# Create token based on some arguments
plain = arg1 + arg2 + str(datetime.now())
token = hashlib.sha1(plain.encode('utf-8')).hexdigest()
return token
@staticmethod
def increment(model):
model.nb_download = model.nb_download + 1
return model.save()
def post(self, request, *args, **kwargs):
form = self.form_class()
document_choice = request.POST.getlist('DocumentChoice')
if request.method == 'POST':
form = self.form_class(request.POST)
for checkbox in document_choice:
document_edqm_id = Document.objects.get(id=checkbox).edqm_id
publication_title = Document.objects.get(id=checkbox).publication.title
email = request.POST['email']
token = self.create_token(email, document_edqm_id, datetime)
Download.objects.create(email=email, pub_id=checkbox, token=token)
document_link = Document.objects.get(id=checkbox).upload #gives media/file
document_link2 = Download.objects.get(token = token).pub_id #gives document id
print(document_link)
print(document_link2)
context = {'document_link': document_link,
'publication_title': publication_title}
if form.is_valid():
message = get_template('freepub/message.txt').render(context)
html_message = get_template('freepub/message.html').render(context)
subject = 'EDQM HelpDesk and Publications registration'
mail = EmailMultiAlternatives(subject, message, 'freepub@edqm.eu', [email])
mail.attach_alternative(html_message, "text/html")
#mail.attach_file(document_link.path) # Add attachement
mail.send(fail_silently=False)
print('Email envoyé à ' + email)
messages.success(request, str(
publication_title) + '\n' + 'You will receive an e-mail with your access to ' + document_edqm_id)
# Update number of downloads for document and publication
document = Document.objects.get(id=checkbox)
document = self.increment(document)
publication_id = Document.objects.get(id=checkbox).publication.id
publication = Publication.objects.get(id=publication_id)
publication = self.increment(publication)
else:
print('form invalid')
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('freepub-home')
</code></pre>
<p>These are the classes in models.py: (Not for review)</p>
<blockquote>
<pre><code>class Document(models.Model):
FORMAT_CHOICES = (
('pdf', 'PDF'),
('epub', 'ePUB'),
)
LANGUAGE_CHOICES = (
('FR', 'FR'),
('EN', 'EN'),
)
edqm_id = models.CharField(max_length=12, verbose_name=_('publication ID'), unique=True, default='')
language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES, null=False)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False)
title = models.CharField(max_length=512, verbose_name=_('document title'), null=False)
publication = models.ForeignKey(Publication, verbose_name=_('publication title'), null=False, related_name='documents')
upload = models.FileField(upload_to='media/', validators=[validate_file_extension])
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
nb_download = models.IntegerField(verbose_name=_('number of download'), default=0)
class Meta:
verbose_name = _('document')
verbose_name_plural = _('document')
def __str__(self):
return f"{self.edqm_id} : {self.title}"
class Download(models.Model):
email = models.CharField(max_length=150, verbose_name=_('e-mail'), null=False)
pub = models.ForeignKey(Document, verbose_name=_('document'), null=False)
token = models.CharField(max_length=40, verbose_name=_('download token'), unique=True, null=False)
download_date = models.DateTimeField(auto_now_add=True, verbose_name=_('download date'), null=False)
expiration_date = models.DateTimeField(auto_now=True, verbose_name=_('expiration date'), null=False)
nb_download = models.IntegerField(verbose_name=_('usage'), default=0)
class Meta:
verbose_name = _('download')
verbose_name_plural = _('download')
def __str__(self):
return f"{self.email} : {self.token}"
</code></pre>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T08:54:32.093",
"Id": "392316",
"Score": "2",
"body": "Hi! Welcome to Code Review! I’m not sure you’re asking the right kind of question for this site. Are you only asking \"how do I split my method in three?\" in which case this may... | [
{
"body": "<p>(I don't know Django and so some aspects of my review may be wrong)</p>\n\n<ol>\n<li><p>I first removed most of your functions, as things like <code>increment</code> aren't really that helpful.\nIt also leaves your code with everything in one place, so that when you try to improve it you can see e... | {
"AcceptedAnswerId": "203540",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T08:13:10.393",
"Id": "203532",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"django"
],
"Title": "Django post function : split method is a good way?"
} | 203532 |
<p>These string arrays are used to classify whether the incoming feed/message is a driver feed or team feed. </p>
<pre><code>private static final String[] DRIVER_FEED_TYPES = {
"SEBASTIAN_VETTEL", "LEWIS_HAMILTON", "CHARLES_LECLERC", "MAX_VERSTAPPEN",
};
private static final String[] TEAM_FEED_TYPES = {
"FERRARI", "MERCEDES", "SAUBER", "REDBULL"
};
</code></pre>
<p>This method gets the type of feed through the incoming message and determines the corresponding type through the <code>arrayContains</code> method. </p>
<pre><code>private boolean isFeedEnabled(FormulaOneMessage formulaOneMessage) {
String feedType = formulaOneMessage.getFeedType();
if (Helper.arrayContains(DRIVER_FEED_TYPES, feedType)) {
return isDriverFeedEnabled();
} else if (Helper.arrayContains(TEAM_FEED_TYPES, feedType)) {
return isTeamFeedEnabled();
} else {
return false;
}
}
</code></pre>
<p>The <code>arrayContains</code> method basically looks through the <code>Object</code> array to see if the object is there. </p>
<pre><code>public static boolean arrayContains(Object[] list, Object item) {
for (Object s : list) {
if (s.equals(item)){
return true;
}
}
return false;
}
</code></pre>
<p>The challenge is how to manage the growing number of types of String arrays in the class. Should I make it into a map, stream or an enum?</p>
<p>Also, the if else statement would also grow as I continue to add more <code>FEED_TYPES</code>. Should I continue to use them? </p>
<p>Overall, I wanted to improve the maintainability of this code seeing the number of feed types will continue to grow in the future. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T12:32:38.217",
"Id": "392357",
"Score": "3",
"body": "Welcome to Code Review! You asked for an optimization. Optimized in what? Speed? Memory? Lines of code? Readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creation... | [
{
"body": "<p>You should use Sets instead of Arrays and Enums when it makes sense. I would write that as:</p>\n\n<pre><code>enum FeedClass {\n TEAM, DRIVER, OTHER;\n private static final Set<String> DRIVER_FEED_TYPES = new HashSet<>(Arrays.asList(\n \"SEBASTIAN_VETTEL\", \"LEWIS_HAM... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T12:16:17.727",
"Id": "203544",
"Score": "0",
"Tags": [
"java",
"homework"
],
"Title": "Collate a growing number of String arrays and search through them"
} | 203544 |
<p>Currently I have this code</p>
<pre><code>function foo(firstId, secondId){
var boolOne = false;
var boolTwo = false;
for (var i = 0; i < arr.length; i++) {
var current = arr[i];
var id = current.id;
if(firstId == id){
boolOne = true;
}
if(secondId == id){
boolTwo = true;
}
if(boolOne && boolTwo){
break;
}
}
if(boolOne && boolTwo){
bar();
} else {
// throw error
}
}
</code></pre>
<p>I want to check if two objects with the given parameter ids already exist in the array.</p>
<p>I put my code into one for-loop but I could also split the code into two loops and break on a match.</p>
<p>I know I could also use </p>
<p><code>var boolOne = arr.includes(item => item.id == firstId)</code></p>
<p>but <strong>I have to support the Internet Explorer 9+</strong>. Is there something that can be optimized?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T13:26:45.950",
"Id": "392363",
"Score": "0",
"body": "sorry, IE 9 and later"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T14:27:16.097",
"Id": "392373",
"Score": "1",
"body": "What do yo... | [
{
"body": "<p>From a short look</p>\n\n<ul>\n<li><code>foo</code> is a terrible name\n\n<ul>\n<li>If this is not the real name, then please do submit the real code</li>\n</ul></li>\n<li><code>arr</code> seems to be a global, bad practice</li>\n<li>You don't need <code>current</code>, you could just go for <code... | {
"AcceptedAnswerId": "203561",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T12:17:54.390",
"Id": "203545",
"Score": "0",
"Tags": [
"javascript",
"performance"
],
"Title": "check if two elements exist in array with older browser support"
} | 203545 |
<p>I've been implementing a simple Python calculator for learning purposes. Since there are no properties or bindings like in Javafx, I implemented my own MVC pattern. I'm aware of missing logic like checking for division by zero and stuff, but I wanted to keep it simple for this review.</p>
<p>So there are some questions:</p>
<ul>
<li>Is the MVC pattern okay this way?</li>
<li>What's the best way to check passed parameters of methods? (see Model.digit(int))</li>
<li>Is the visibility of fields okay this way?</li>
<li>Are the imports organized correctly?</li>
</ul>
<pre><code>import tkinter as tk
from tkinter import *
import tkinter.font
from abc import ABC, abstractmethod
from enum import IntEnum
class Observer(ABC):
@abstractmethod
def notify(self):
pass
class Observable():
def __init__(self):
self._observers = set()
def register(self, observer: Observer):
self._observers.add(observer)
def notify_all(self):
for observer in self._observers:
observer.notify()
class Operator(IntEnum):
NONE = 0
EQUALS = 1
PLUS = 10
MINUS = 11
MULT = 12
DIV = 13
class Model(Observable):
def __init__(self):
Observable.__init__(self);
self._temp = 0
self._result = 0
self._operator = Operator.NONE
def digit(self, digit: int):
if digit is None:
raise TypeError
if self._operator == Operator.EQUALS:
self.reset()
self._temp = self._temp * 10 + digit
self.notify_all()
def operator(self, operator: Operator):
if operator == Operator.EQUALS:
if self._operator == Operator.PLUS:
self._temp += self._result
self._operator = Operator.EQUALS
elif self._operator == Operator.MINUS:
self._temp = self._result - self._temp
self._operator = Operator.EQUALS
elif self._operator == Operator.MULT:
self._temp *= self._result
self._operator = Operator.EQUALS
elif self._operator == Operator.DIV:
self._temp = self._result / self._temp
self._operator = Operator.EQUALS
elif Operator.PLUS <= operator <= Operator.DIV:
self._result = self._temp
self._temp = 0
self._operator = operator
else:
raise NotImplementedError("unexpected enum")
self.notify_all()
def reset(self):
self._temp = 0
self._result = 0
self._operator = Operator.NONE
self.notify_all()
class Controller():
def __init__(self, model: Model):
self._model = model
def digit(self, digit: int):
self._model.digit(digit)
def operator(self, operator: Operator):
self._model.operator(operator)
class View(tk.Tk, Observer):
CONST_TITLE = "Calculator"
CONST_GEOMETRY = "300x400"
def __init__(self):
tk.Tk.__init__(self)
self.title(self.CONST_TITLE)
self.geometry(self.CONST_GEOMETRY)
self._model = Model()
self._model.register(self)
self._controller = Controller(self._model)
self._frame = tk.Frame(self, bg="white")
self._frame.pack(fill=BOTH, expand=1)
for row in range(6):
self._frame.rowconfigure(row, weight=1)
for column in range(4):
self._frame.columnconfigure(column, weight=1)
self._font = tkinter.font.Font(root=self._frame, family="Helvetica", size="30", weight=tkinter.font.BOLD)
self._text = tk.Label(self._frame, text="INIT", font=self._font, justify=RIGHT, anchor=E, bg="white", padx=20, pady=20)
self._text.grid(row="0", column="0", columnspan="4", sticky="NSWE")
self._button_0 = tk.Button(self._frame, text="0", font=self._font, command=lambda:self._controller.digit(0))
self._button_0.grid(row="5", column="0", columnspan="2", sticky="NSWE")
self._button_1 = tk.Button(self._frame, text="1", font=self._font, command=lambda:self._controller.digit(1))
self._button_1.grid(row="4", column="0", sticky="NSWE")
self._button_2 = tk.Button(self._frame, text="2", font=self._font, command=lambda:self._controller.digit(2))
self._button_2.grid(row="4", column="1", sticky="NSWE")
self._button_3 = tk.Button(self._frame, text="3", font=self._font, command=lambda:self._controller.digit(3))
self._button_3.grid(row="4", column="2", sticky="NSWE")
self._button_4 = tk.Button(self._frame, text="4", font=self._font, command=lambda:self._controller.digit(4))
self._button_4.grid(row="3", column="0", sticky="NSWE")
self._button_5 = tk.Button(self._frame, text="5", font=self._font, command=lambda:self._controller.digit(5))
self._button_5.grid(row="3", column="1", sticky="NSWE")
self._button_6 = tk.Button(self._frame, text="6", font=self._font, command=lambda:self._controller.digit(6))
self._button_6.grid(row="3", column="2", sticky="NSWE")
self._button_7 = tk.Button(self._frame, text="7", font=self._font, command=lambda:self._controller.digit(7))
self._button_7.grid(row="2", column="0", sticky="NSWE")
self._button_8 = tk.Button(self._frame, text="8", font=self._font, command=lambda:self._controller.digit(8))
self._button_8.grid(row="2", column="1", sticky="NSWE")
self._button_9 = tk.Button(self._frame, text="9", font=self._font, command=lambda:self._controller.digit(9))
self._button_9.grid(row="2", column="2", sticky="NSWE")
self._button_plus = tk.Button(self._frame, text="+", font=self._font, command=lambda:self._controller.operator(Operator.PLUS))
self._button_plus.grid(row="2", column="3", rowspan="2", sticky="NSWE")
self._button_plus = tk.Button(self._frame, text="-", font=self._font, command=lambda:self._controller.operator(Operator.MINUS))
self._button_plus.grid(row="1", column="3", sticky="NSWE")
self._button_plus = tk.Button(self._frame, text="*", font=self._font, command=lambda:self._controller.operator(Operator.MULT))
self._button_plus.grid(row="1", column="2", sticky="NSWE")
self._button_plus = tk.Button(self._frame, text="/", font=self._font, command=lambda:self._controller.operator(Operator.DIV))
self._button_plus.grid(row="1", column="1", sticky="NSWE")
self._button_equals = tk.Button(self._frame, text="=", font=self._font, command=lambda:self._controller.operator(Operator.EQUALS))
self._button_equals.grid(row="4", column="3", rowspan="2", sticky="NSWE")
self._button_clear = tk.Button(self._frame, text="C", font=self._font, command=self._model.reset)
self._button_clear.grid(row="1", column="0", sticky="NSWE")
self.notify()
def notify(self):
self._text.config(text=self._model._temp)
if __name__ == "__main__":
View().mainloop()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T12:26:25.033",
"Id": "393045",
"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": "<h2>Don't import tkinter twice.</h2>\n\n<p>You're importing tkinter twice:</p>\n\n<pre><code>import tkinter as tk\nfrom tkinter import *\n</code></pre>\n\n<p>Just import it once, and prefix everything with <code>tk.</code>:</p>\n\n<pre><code>import tkinter as tk\n...\nself._frame.pack(fill=tk.BOTH, .... | {
"AcceptedAnswerId": "216589",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T12:34:34.330",
"Id": "203547",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"mvc",
"calculator",
"tkinter"
],
"Title": "Simple Python calculator applying MVC"
} | 203547 |
<p>I'm looking for an efficient way to validate multiple rows originating from multiple .csv files. Below is the current code to accomplish that.<br>
The validation logic is in the function <code>ValidateRow(DataRow row)</code> (not presented here).</p>
<p>I could think of an alternative with using Linq and performing <code>batch.All( row => ValidateRow(row))</code> and adding the row to the <code>InvalidRow</code> property in <code>ValidateRow</code>. But I don't know if that is more efficient or not.</p>
<pre><code>public bool ValidateBatch( IEnumerable<DataRow> batch, bool exitOnFirstError = false )
{
//return early if we find no datarows
if( batch == null || batch?.Count() == 0 ) { logger.Error( MSG_NO_DATAROWS ); return false; }
bool result = true;
foreach( DataRow row in batch )
{
if( !ValidateRow( row ) )
{
result = false;
// track invalid rows on a property (List<DataRow>)
InvalidRows.Add( row );
if( exitOnFirstError )
{
return result;
}
}
}
return result;
}
</code></pre>
| [] | [
{
"body": "<p>The <code>if</code> condition </p>\n\n<pre><code>if( batch == null || batch?.Count() == 0 ) { logger.Error( MSG_NO_DATAROWS ); return false; } \n</code></pre>\n\n<p>has some flaws: </p>\n\n<ul>\n<li><p>the Null-Conditional operator <code>?</code> on <code>batch?.Count() == 0</code> isn't needed... | {
"AcceptedAnswerId": "203550",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T12:35:56.877",
"Id": "203548",
"Score": "4",
"Tags": [
"c#",
"performance",
"iteration"
],
"Title": "Effieciently validate multiple DataRows with return early option"
} | 203548 |
<p>I currently had a colleague reviewing my code and he had a comment on a factory class I created. It's very simple:</p>
<pre><code>class ResponseFactory
{
public function create(array $curlInfo, array $rawResponse): ResponseInterface
{
return new Response($curlInfo, $rawResponse);
}
}
$responseFactory = new ResponseFactory();
$response = $responseFactory->create(...);
</code></pre>
<p>His comment was that I should use the <code>__invoke()</code>-method of PHP. In that case, the code would look like this:</p>
<pre><code>class ResponseFactory
{
public function __invoke(array $curlInfo, array $rawResponse): ResponseInterface
{
return new Response($curlInfo, $rawResponse);
}
}
$responseFactory = new ResponseFactory();
$response = $responseFactory(...);
</code></pre>
<p>Now I am wondering: is this just a matter of taste? Or is there real benefit in using <code>__invoke()</code> over a public <code>create()</code>-method?</p>
<p>Any thoughts or insights on this matter are more than welcome. I'm really trying to find good use cases for the <code>__invoke()</code>-method, but I'm not sure if a factory is one of them.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T19:20:05.027",
"Id": "392428",
"Score": "0",
"body": "I'd consider not using factory at all in this case, because it doesn't solve any problem. Hard to see any abstraction in it either, because `Response` and factory parameters look... | [
{
"body": "<p>The only benefit of using <code>__invoke()</code> is that you can store the instance of the class in a variable as a callback and then use it without <code>call_user_func_array()</code>. But in my opinion using <code>create()</code> is more readable so you can guess easily what is the code doing.<... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T14:09:10.533",
"Id": "203553",
"Score": "2",
"Tags": [
"php",
"comparative-review",
"factory-method"
],
"Title": "PHP Factory Pattern : Should I use `create()` or `__invoke()`?"
} | 203553 |
<p>This is the first question for this language, and I decided I would do a FizzBuzz.</p>
<p>I used a template literal as a proof of concept, same goes for the pipe (<code>|></code>). The code creates a function that recreates the traditional FizzBuzz in FreezeFlame:</p>
<pre><code>var fizzBuzz = (max) -> {
for(var i = 0; i < max + 1; i++) {
(if i % 3 === 0 || i % 5 === 0 then "#{i % 3 == 0 ? 'Fizz' : ''}#{i % 5 === 0 ? 'Buzz' : ''}" else i) |> console.log
}
}
</code></pre>
<p>This is equivalent to the following in JavaScript:</p>
<pre><code>var fizzBuzz = (max) => {
for(var i = 0; i < max + 1; i++){
console.log((i % 3===0||i % 5===0 ? `${i % 3 == 0 ? 'Fizz' : ''}${i % 5 === 0 ? 'Buzz' : ''}` : i));
};
}
</code></pre>
<p>The following features are used:</p>
<ul>
<li>FreezeFlame ternary (<code>if ... then ... else ...</code>)</li>
<li>FreezeFlame template literals (<code><code>#{...}</code></code>)</li>
<li>JS ternary (<code>... ? ... : ...</code>)</li>
<li>FreezeFlame pipe (<code>... |> ...</code>)</li>
<li>FreezeFlame function (<code>(...) -> { ... }</code>)</li>
</ul>
<p>My main worries are the testing.</p>
<p><a href="https://github.com/FreezePhoenix/freeze-flame" rel="nofollow noreferrer">FreezeFlame GitHub</a></p>
| [] | [
{
"body": "<h1>DRY</h1>\n\n<p>I'm sorry to say this but this solution is needlessly complicated. You are doubling up on your divisibility checks. This is a well known interview question where the goal is to really just to check that you can order your <code>if</code> statements correctly. It is kind of cool tha... | {
"AcceptedAnswerId": "203584",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T14:32:04.957",
"Id": "203556",
"Score": "3",
"Tags": [
"fizzbuzz",
"freezeflame"
],
"Title": "FizzBuzz in FreezeFlame"
} | 203556 |
<p>FreezeFlame was designed by <a href="https://stackexchange.com/users/12513750/freezephoenix">FreezePhoenix</a> and a list of contributors which includes the CoffeeScript team, and bears a similarity to both CoffeeScript and C-like languages. It's project is currently hosted here: <a href="https://github.com/FreezePhoenix/freeze-flame" rel="nofollow noreferrer">https://github.com/FreezePhoenix/freeze-flame</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T14:42:19.367",
"Id": "203558",
"Score": "0",
"Tags": null,
"Title": null
} | 203558 |
This tag is to be used for the language FreezeFlame, or questions that relate to it. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T14:42:19.367",
"Id": "203559",
"Score": "0",
"Tags": null,
"Title": null
} | 203559 |
<p>This is a calculator I created. It can take all basic operators, including brackets. I am a beginner with Python so I want to know what can I do better next time I write something similar.</p>
<pre><code>def eval(expression):
current = 0
while current < len(expression):
x = expression[current]
if x == '(':
levels = 1
inside = ''
while levels:
current+=1
x = expression[current]
if x == ')':
levels -= 1
if not levels:
expression = expression.replace('('+inside+')',str(eval(inside)))
current -= (len(inside)+2)
else:
inside+=')'
elif x == '(':
levels+=1
inside+=x
else:
inside+=x
current+=1
expressions = list(filter(None,expression.replace('+-','-').replace('-','+-').split('+')))
ret = 0
for exp in expressions:
if exp.find('*') == -1 and exp.find('/') == -1:
ret+=int(exp)
continue
op = '*'
expret = 1
exp +='*1'
while exp.find('*') > -1 or exp.find('/') > -1:
next_mult = exp.find('*')
next_div = exp.find('/')
if next_mult > -1 and (next_mult < next_div or next_div==-1):
expret = multdiv(expret,op,float(exp[:next_mult]))
op = '*'
exp = exp[next_mult+1:]
elif next_div < next_mult:
expret = multdiv(expret,op,float(exp[:next_div]))
op = '/'
exp = exp[next_div+1:]
ret += expret
return ret
def multdiv(num1,op,num2):
if op == '*':
return num1*num2
return num1/num2
print(eval(input()))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T17:24:19.430",
"Id": "392416",
"Score": "0",
"body": "Crashes for `1 + -3`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T18:46:15.543",
"Id": "392421",
"Score": "0",
"body": "See [this a... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T14:54:44.147",
"Id": "203562",
"Score": "4",
"Tags": [
"python",
"beginner",
"math-expression-eval"
],
"Title": "Python expression calculator"
} | 203562 |
<p>Ive been sitting here for the past 20 minutes trying to make this simple/tiny function more 'readable' and 'clean'. Am I overthinking this or am I missing some major tips that could help me out?</p>
<pre><code>string findSameSales (int numSold, int salesArray[], string namesArray[])
{
string ssList = " ";
for (int counter = 0; counter <= NUM_OF_POS; counter++)
{
if (numSold == salesArray[counter])
{
if (ssList == " ")
ssList = namesArray[counter];
else
ssList += (", " + namesArray[counter]);
}
else;
}
return ssList;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T20:13:00.920",
"Id": "392385",
"Score": "4",
"body": "You could drop `else;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T20:14:36.190",
"Id": "392386",
"Score": "0",
"body": "You could... | [
{
"body": "<p>Of course that's just subjective and there are many different formatting guidelines (working within a specific company or OSS project just follow theirs), but I personally would format that code like this for better readability and simplification of logic:</p>\n\n<pre><code>string findSameSales (i... | {
"AcceptedAnswerId": "203565",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-08T20:11:55.660",
"Id": "203564",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Listing sales with a matching quantity"
} | 203564 |
<p>I wrote a simple python port scanner today and I would like to get some advice on how to improve on the code in different ways.</p>
<p>I am aware that I can implement threading to reduce runtime but I won't for now as it feels a bit advanced at this time. Rather I would like tips/opinions on how to improve the program in other ways.</p>
<p>You can find the code on my <a href="https://github.com/landizz/Port-scanner/blob/Main-Alterations/main.py" rel="nofollow noreferrer">GitHub</a>.</p>
<p>I am aware that the logging is a bit redundant as it doesn't log anything now, I simply forgot to remove it.</p>
<pre><code># Network port scanner
# Focus first will be on making the functionality of the software.
# Second focus will be on lowering the runtime of the software.
import socket
import logging
import time
class SConnect:
def __init__(self, ip, port=None):
self.ip = ip
self.port = port
self.address = (self.ip, self.port)
self.s_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s_connection.settimeout(0.3)
def portscan(self):
return self.s_connection.connect_ex(self.address)
def main():
logging.basicConfig(filename="errlog.log", format="%(asctime)s : %(message)s")
logging.info("Start")
print("\nHello user and welcome to Network Port Scanner!")
print("Please insert a IP address that you want to scan for open and closed ports.")
print("The range of ports scanned is 1-65535.")
u_ip = input("\nTarget IP: ")
open_pcounter = 0
closed_pcounter = 0
if u_ip is not None:
for p in range(1, 65536):
start_ptime = time.time()
c = SConnect(u_ip, p)
if c.portscan() == 0:
print("Port {} is open".format(p))
open_pcounter += 1
else:
print("Port {} is closed".format(p))
closed_pcounter += 1
print("--- %s seconds ---" % (time.time() - start_ptime))
else:
print("You failed, terminating.\n")
print("Total open ports:%s".format(open_pcounter))
print("Total closed ports:%s".format(closed_pcounter))
logging.info("Finished")
if __name__ == '__main__':
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
</code></pre>
| [] | [
{
"body": "<p>I would move the first conditional in main into a guard statement and lower the flow depth.</p>\n\n<pre><code>if u_ip is None:\n print(\"You failed, terminating.\\n\")\n return\n</code></pre>\n\n<p>Also, if instead of incrementing a counter if you had a dictionary of port to open/closed ma... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T19:28:43.687",
"Id": "203577",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"networking",
"socket"
],
"Title": "Simple port scanner in Python 3"
} | 203577 |
<p>I want to find a quick way to see if a matrix <em>M</em> has at least one value that is, say, 2. In R, I would use <code>any(M==2)</code>. However, this computes first <code>M==2</code> for all values in <code>M</code>, then use <code>any()</code>. <code>any()</code> will stop at the first time a <code>TRUE</code> value is found, but that still means we computed way too many <code>M==2</code> conditions.</p>
<p>I thought one could find a more efficient way, computing <code>M==2</code> only as long as it is not satisfied. I tried to write a function to do this (either column-wise <code>check</code>, or on each element of <code>M</code>, <code>check_2</code>), but it is so far much slower. Any idea on how to improve this?</p>
<p>Results of benchmark, where the value Val is rather at the end of the matrix:</p>
<pre><code>|expr |mean time |
|:------------------|---------:|
|any(M == Val) | 14.13623|
|is.element(Val, M) | 17.71230|
|check(M, Val) | 18.20764|
|check_2(M, Val) | 486.65347|
</code></pre>
<p>Code:</p>
<pre><code>x <- 1:10^6
M <- matrix(x, ncol = 10, byrow=TRUE)
Val <- 50000
check <- function(x, Val) {
i <- 1
cond <- FALSE
while(!cond & i <= ncol(x)) {
cond <- any(M[,i]==Val)
i <- i +1
}
cond
}
check_2 <- function(x, Val) {
x_c <- c(x)
i <- 1
cond <- FALSE
while(!cond & i <= length(x_c)) {
cond <- x_c[i]==Val
i <- i +1
}
cond
}
check_2(x=M, Val)
check(M, Val)
library(microbenchmark)
comp <- microbenchmark(any(M == Val),
is.element(Val, M),
check(M, Val),
check_2(M, Val),
times = 20)
comp
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T08:48:47.527",
"Id": "392482",
"Score": "0",
"body": "I wouldn't expect any performance gains for `check()` if your `Val` is found in the last column. But it makes a different, for example, with `Val <- 1`."
}
] | [
{
"body": "<p><code>any</code> is a primitive, it doesn't loop in <code>R</code> but in <code>C</code>, which is much much faster.</p>\n\n<p>loops in <code>R</code> are quite slow, that's why it's important that you use said vectorized functions if you care about speed (apply functions are still loops however).... | {
"AcceptedAnswerId": "203643",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T01:50:11.407",
"Id": "203586",
"Score": "2",
"Tags": [
"algorithm",
"matrix",
"r"
],
"Title": "Fast algorithm for any(M==2)"
} | 203586 |
<p>I currently have a number factors program that performs the following things: The user enters a number, checks whether it is a perfect square (yes or no), prints the square root if it is a perfect square, determining the number if it is prime or not, and the number factors of that specific number.</p>
<pre><code>import java.util.Scanner;
import java.util.Date;
import java.text.SimpleDateFormat;
public class NumberFacts {
public static void main(String[] args) {
// Initialize the Scanner
Scanner in = new Scanner(System.in);
//Prompt the user to input the number to evaluate
System.out.print("Enter a number (from 1 to 10000): ");
// Store the input number
int myNum = in.nextInt();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date start = new Date();
startProcess(start);
System.out.println("\nNumber\tPerfect Sqr\tSqrt\tPrime\tFactors");
// For each number iteration, we should begin by bringing a pair each
// time until we hit that number.
iterNum(myNum);
in.close();
Date stopTime = new Date();
long diff = stopTime.getTime() - start.getTime();
stopProcess(dateFormat, start, stopTime, diff);
} // end of main method
private static void iterNum(int n) {
for (int iter = 1; iter <= n; iter++) {
// Start the factorPair as an empty string
String factorPair = "";
// Initialize the loop counter.
int i = 1;
// Result returns the number the user entered.
int result = iter;
// Used to store for pairs.
String myPairs = "";
// Main counter for our pairs.
int pairsCounter = 0;
// Initialize square root variable with 0.
int sqrt = 0;
// Initialize factor variables
int factor1;
int factor2;
// Begin factoring pairs
do {
if (iter % i == 0) {
// Starts with the initial number
// until the last number the user
// specified.
factor1 = i;
// We divide each number by 1 and
// truncate each number to have a
// precise number.
factor2 = iter / i;
// If the number is a factor pair, then
// output the number.
if (factor1 <= factor2) {
factorPair = "(" + factor1 +", "+ factor2 + ")";
pairsCounter++;
myPairs += factorPair;
}
// Checks whether the number is a square root
// number that will assume either yes
// or no.
if (factor1 == factor2) {
sqrt = factor1;
}
}
} while (++i <= result); // End of the factoring pair loops.
// Print the expected formatted output for the program.
printOutput(iter, sqrt, pairsCounter, myPairs);
}
}
private static void startProcess(Date s) {
System.out.println("Started processing at " + s);
}
private static void stopProcess(SimpleDateFormat d, Date n1, Date n2, long l) {
System.out.println("\n\nStart processing " + d.format(n1) + "\n\nStop processing: " + d.format(n2) + "\n\nDifference: " + l + " ms");
}
private static void printOutput(int a, int sq, int c, String s) {
System.out.printf("%n %d \t%s\t\t%s\t%s\t%s", a, sq > 0 ? "Yes" : "No", sq > 0 ? Integer.toString(sq) : "", c > 1 ? "No" : "Yes", s);
}
} // end of class
</code></pre>
<p>When compiled and start it, I do the following:</p>
<pre class="lang-none prettyprint-override"><code>Enter a number (from 1 to 10000): 25
Started processing at Tue Sep 11 22:03:30 CDT 2018
Number Perfect Sqr Sqrt Prime Factors
1 Yes 1 Yes (1, 1)
2 No Yes (1, 2)
3 No Yes (1, 3)
4 Yes 2 No (1, 4)(2, 2)
5 No Yes (1, 5)
6 No No (1, 6)(2, 3)
7 No Yes (1, 7)
8 No No (1, 8)(2, 4)
9 Yes 3 No (1, 9)(3, 3)
10 No No (1, 10)(2, 5)
11 No Yes (1, 11)
12 No No (1, 12)(2, 6)(3, 4)
13 No Yes (1, 13)
14 No No (1, 14)(2, 7)
15 No No (1, 15)(3, 5)
16 Yes 4 No (1, 16)(2, 8)(4, 4)
17 No Yes (1, 17)
18 No No (1, 18)(2, 9)(3, 6)
19 No Yes (1, 19)
20 No No (1, 20)(2, 10)(4, 5)
21 No No (1, 21)(3, 7)
22 No No (1, 22)(2, 11)
23 No Yes (1, 23)
24 No No (1, 24)(2, 12)(3, 8)(4, 6)
25 Yes 5 No (1, 25)(5, 5)
Start processing 2018/09/11 22:03:30
Stop processing: 2018/09/11 22:03:30
Difference: 13 ms
</code></pre>
<p>It runs fast with small numbers but when it comes to bigger numbers such as <code>6000</code> to <code>10000</code>, the speed gets slower with the difference from the start to finish. Inputting 10,000 numbers averages around 800 to 900ms each run.</p>
<p>How can I improve the speed of the computation time in each program run?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T14:14:58.783",
"Id": "392524",
"Score": "0",
"body": "If you always fo numbers from 1 to n, using a [sieve](https://stackoverflow.com/questions/586284/finding-prime-numbers-with-the-sieve-of-eratosthenes-originally-is-there-a-bet) w... | [
{
"body": "<p>Seems to me that the program is a good fit for multi threaded processing: </p>\n\n<ol>\n<li>Set up a thread pool with a fixed number of threads. Usually it is connected to the number of processors of your hardware.</li>\n<li>Split the range of iteration by the number of threads in the pool. invoke... | {
"AcceptedAnswerId": "203632",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T03:25:11.443",
"Id": "203587",
"Score": "2",
"Tags": [
"java",
"performance"
],
"Title": "Number factor of a number"
} | 203587 |
<p>I am using 4 queries to get below 4 values , like this i need to use about 14 queries , Is there any way to reduce queries ?</p>
<p><a href="https://i.stack.imgur.com/y3o9E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y3o9E.png" alt="enter image description here"></a></p>
<pre><code><?php
echo " " . date("Y-m-d")." ";
echo "Reattempt : "." ";
$sql =
"SELECT
COUNT(*) as count FROM orders
WHERE DATE(reattemptdate) = CURDATE()
";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;
echo " "." Hold : ";
$sql =
"SELECT
COUNT(*) as count FROM orders
WHERE DATE(holddate) = CURDATE()
";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;
echo "<br>";
?>
<?php
echo date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-1,date("Y")))." ";
echo "Reattempt : "." ";
$sql =
"SELECT
COUNT(*) as count FROM orders
WHERE DATE(reattemptdate) = DATE(NOW() - INTERVAL 1 DAY)
";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;
echo " "." Hold : ";
$sql =
"SELECT
COUNT(*) as count FROM orders
WHERE DATE(holddate) = DATE(NOW() - INTERVAL 1 DAY)
";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T09:05:20.640",
"Id": "392487",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state... | [
{
"body": "<p>You can create one query and select all elements. For example:</p>\n\n<pre><code>select sum(case when DATE(reattemptdate) = CURDATE() THEN 1 ELSE 0 END) as reattemptdate,\n sum(case when DATE(holddate) = CURDATE() THEN 1 ELSE 0 END) as holddate,\n sum(case when DATE(reattemptdate) = DA... | {
"AcceptedAnswerId": "203600",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T07:57:54.213",
"Id": "203598",
"Score": "0",
"Tags": [
"php"
],
"Title": "Fetch Reattempt and Hold Date count in efficient way"
} | 203598 |
<p>I'm implementing a TCP client to read data from a sensor. The sensor sends messages to connected clients framed with a start sequence, messages, checksum and end sum bytes. Because the sensor is installed at a remote location, I'm currently reading previously captured network data from a pcap dump into a MemoryStream. The TCP data is simulated from a capture file using bittwist (not real-time client-server communication).</p>
<p>Please advise on how to improve the method below that reads TCP messages including framing bytes, through a MemoryStream since I can't use NetworkStream? Is my checksum calculation correct? The sensor documentation indicates that to calculate it you must include all payload data except starting and ending sequence.</p>
<p>I have two while loops, one to first check start sequence (frame start), once done. </p>
<p>The second loop checks for the checksum value, end sequence (frame end) and if not, treats this as a message payload and reads from the stream until a valid end sequence (frame end) is found. Each (n) payload starts with a 3 bytes header (2 bytes identifier + 1 byte length of the succeeding data) and then the actual data.</p>
<pre><code>private static void Decode(MemoryStream memoryStream)
{
var frameStartSequenceBuffer = new byte[] { 0xCA, 0xCB, 0xCC, 0xCD };
var frameChecksumBuffer = new byte[1];
var frameEndSequenceBuffer = new byte[] { 0xEA, 0xEB, 0xEC, 0xED };
var startSequenceBuffer = new byte[4];
var endSequenceBuffer = new byte[4];
var messages = new List<byte[]>();
var read = 0;
while (read < startSequenceBuffer.Length)
{
read += memoryStream.Read(startSequenceBuffer, 0, startSequenceBuffer.Length);
if (Helpers.ByteArrayCompare(startSequenceBuffer, frameStartSequenceBuffer))
break;
}
while (memoryStream.Capacity > read)
{
read += memoryStream.Read(frameChecksumBuffer, 0, frameChecksumBuffer.Length);
read += memoryStream.Read(endSequenceBuffer, 0, endSequenceBuffer.Length);
if (Helpers.ByteArrayCompare(endSequenceBuffer, frameEndSequenceBuffer))
break;
var readPayload = frameChecksumBuffer.Concat(endSequenceBuffer).ToArray();
var messageBuffer = new byte[3 + endSequenceBuffer[1]];
readPayload.CopyTo(messageBuffer, 0);
read += memoryStream.Read(messageBuffer, readPayload.Length, messageBuffer.Length - readPayload.Length);
messages.Add(messageBuffer);
}
var calculatedChecksum = Helpers.CalculateChecksumBitwise(messages.SelectMany(o => o).Concat(frameChecksumBuffer).ToArray());
if (calculatedChecksum != frameChecksumBuffer[0])
{
Console.WriteLine("Messages: {0} - Corrupt", messages.Count);
return;
}
Console.WriteLine("Messages: {0} - Valid", messages.Count);
}
</code></pre>
<p>Each TCP packet from the sensor encapsulates an array of (n) messages delimited with a 3 bytes headers.</p>
<p>The checksum is calculated from all data without the start sequence and the end sequence. The Checksum is a simple XOR Assignment of all n data bytes. Below is the checksum calculation method that I've implemented.</p>
<pre><code>public static byte CalculateChecksumBitwise(IList<byte> byteToCalculate)
{
var checksum = 0;
for (var i = 0; i < byteToCalculate.Count - 1; i++)
{
checksum = checksum ^ byteToCalculate[i];
}
return (byte)checksum;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T08:31:53.863",
"Id": "392479",
"Score": "2",
"body": "For us to understand the code we need at the very least to know the types of the variables. Can you edit to give the whole method? And if `dataStream` isn't a `System.IO.Stream` ... | [
{
"body": "<p>I think the first loop is somewhat redundant, because if <code>read < startSequenceBuffer.Length</code> after the first pass, the input <code>memoryStream</code> is shorter than the <code>startSequenceBuffer</code> and then there are no messages to follow anyway. Instead of the first loop you c... | {
"AcceptedAnswerId": "203677",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T08:24:55.797",
"Id": "203599",
"Score": "2",
"Tags": [
"c#",
"stream",
"tcp"
],
"Title": "Read framed nested sensor data from memory stream"
} | 203599 |
<p>I've written a script that semi-automates the process of configuring/creating a new systemd service.</p>
<p>The script is working perfectly well, however, I've had some trouble with the styling and readability, as well as with the argparse logic (argument parsing works well, but there is just too much to handle manually and not automatically with argparse, because I have many arguments and they have different requirements) - I don't know if what I've done is best practice, because to me right now, it looks like a very poor idea. </p>
<p>The script right now loads a default schema (template) and allows the user to interactively configure a service using the options that are present in that template.</p>
<p><strong>Notes:</strong> Version of Python used is <strong>3.5</strong>.<br>
There are some single cases of use where bugs might appear, however, the script is working correctly overall and the existence of such possible bugs should be ignored for the sake of this question, as they are not for here.</p>
<p>Available arguments for the script:</p>
<pre class="lang-none prettyprint-override"><code>-c/--schema: Just loads a different template configuration to use
for the interactive "asking" process. Takes the path to that template.
-s/--short: Uses a default schema (template) that is shorter than the
original one (has less and more basic options)
-x/--extended: Uses a default schema (template) that is longer than the
original one (has more options that are more complex)
-d/--directory: The directory in which the script should
save the service unit file, by default "/etc/systemd/system".
--delete: Deletes the service unit file of the specified service name and
disables/stops that service. If used, should be the only argument used
along with service_name.
--edit: Edits the service unit file (opens an editor)
of the specified service name. If used, should be the only argument used
along with service_name.
-b/--build: Builds a default service configuration unit file as an example.
Should be the ONLY argument used, even the
positional argument service_name should not be used.
--info: Outputs information about the script - purpose, maintainer, etc.
Again should be the ONLY argument used.
service_name: The positional argument which tells what is the name
of the service that has to be configured/edited/deleted.
Doesn't have to be used with --build/--info.
</code></pre>
<p>The script:</p>
<pre><code>#!/usr/bin/env python3
"""
This is a helper script that semi-automates the process
of configuring/editing systemd services.
Examples --
Create a service using a short preset configuration:
sudo ./service-config.py --short some_service_name
Create a service using a custom preset configuration template:
sudo ./service-config.py -c some_schema some_service_name
Edit an existing service:
sudo ./service-config.py --edit some_service_name
# To do list:
1. Document the script.
2. Fix permission issues with some of the arguments.
3. Add a configuration file for the script for
some of the default values and options. (?)
4. Allow the user to choose an editor.
NOTES:
1. This script requires root privileges for most use-cases.
2. Skipping a configuration option (just pressing enter) without
supplying any value will just tell the script to skip that option.
"""
# IMPORTS:
import argparse
import configparser
import datetime
import os
import subprocess
import sys
import time
from collections import OrderedDict
# DEFINING CONSTANTS:
VERSION = "0.4"
MAINTAINER_NICK = "..."
MAINTAINER_EMAIL = "...@gmail.com"
TRACE = True
SCHEMA = "schemas/service-config"
SCHEMA_SHORT = "schemas/short_service-config"
SCHEMA_EXTENDED = "schemas/extended_service-config"
CONFIG = None # for future uses
OUTPUT_DIR = "/etc/systemd/system"
# ERRORS:
USER_ABORT = 5
ARGPARSE_ERR = 6
CONFIGURATION_ERR = 7
GLOBAL_ERR = 8
SCHEMA_ERR = 9
SYSTEMD_ERR = 10
UID_ERROR = 11
FINISH_ERROR = 12
# DEFAULTS:
DEFAULT_EDITOR = "vim"
DEFAULT_BUILD_SCHEMA = "schemas/default-schema"
DEFAULT_DESCRIPTION = "Example"
DEFAULT_AFTER = "network.target"
DEFAULT_TYPE = "simple"
DEFAULT_USER = "root"
DEFAULT_GROUP = "root"
DEFAULT_EXEC_START = "/bin/true"
DEFAULT_EXEC_STOP = "/bin/true"
DEFAULT_KILL_MODE = "control-group"
DEFAULT_KILL_SIGNAL = "SIGTERM"
DEFAULT_PID_FILE = "/run/service.pid"
DEFAULT_RESTART = "on-failure"
DEFAULT_RESTART_SEC = "2"
DEFAULT_TIMEOUT_STOP_SEC = "5"
DEFAULT_DYNAMIC_USER = "no"
DEFAULT_ENVIRONMENT_FILE = "/etc/service/env"
DEFAULT_STANDARD_OUTPUT = "journal"
DEFAULT_STANDARD_ERROR = "journal"
DEFAULT_WANTED_BY = "multi-user.target"
# COLORS AND Formatting:
def tty_supports_ansi():
"""Checks whether the terminal used supports ANSI codes."""
for handle in [sys.stdout, sys.stderr]:
if ((hasattr(handle, "isatty") and handle.isatty()) or
('TERM' in os.environ and os.environ['TERM'] == "ANSI")):
return True
else:
return False
class Formatting:
"""
A class containing constants with most Formatting/basic colors
for Unix-based terminals and vtys.
Does NOT work on Windows cmd, PowerShell, and their varieties!
"""
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
ITALIC = "\033[3m"
UNDERLINE = "\033[4m"
BLINK = "\033[5m" # Doesn't work on some terminals.
INVERT = "\033[7m"
HIDDEN = "\033[8m"
FG_DEFAULT = "\033[39m"
FG_BLACK = "\033[30m"
FG_RED = "\033[31m"
FG_GREEN = "\033[32m"
FG_YELLOW = "\033[33m"
FG_BLUE = "\033[34m"
FG_MAGENTA = "\033[35m"
FG_CYAN = "\033[36m"
FG_LIGHT_GRAY = "\033[37m"
FG_DARK_GRAY = "\033[90m"
FG_LIGHT_RED = "\033[91m"
FG_LIGHT_GREEN = "\033[92m"
FG_LIGHT_YELLOW = "\033[93m"
FG_LIGHT_BLUE = "\033[94m"
FG_LIGHT_MAGENTA = "\033[95m"
FG_LIGHT_CYAN = "\033[96m"
FG_WHITE = "\033[97m"
BG_DEFAULT = "\033[49m"
BG_BLACK = "\033[40m"
BG_RED = "\033[41m"
BG_GREEN = "\033[42m"
BG_YELLOW = "\033[43m"
BG_BLUE = "\033[44m"
BG_MAGENTA = "\033[45m"
BG_CYAN = "\033[46m"
BG_LIGHT_GRAY = "\033[47m"
BG_DARK_GRAY = "\033[100m"
BG_LIGHT_RED = "\033[101m"
BG_LIGHT_GREEN = "\033[102m"
BG_LIGHT_YELLOW = "\033[103m"
BG_LIGHT_BLUE = "\033[104m"
BG_LIGHT_MAGENTA = "\033[105m"
BG_LIGHT_CYAN = "\033[106m"
BG_WHITE = "\033[107m"
def __init__(self):
self.is_supported = tty_supports_ansi()
def ansi(self, ansi_key):
"""
The format method for this class. Returns the proper
chosen formatting if it is supported, else does nothing.
Takes ansi_key as argument, where ansi_key is one of the
defined constants in the class.
"""
if self.is_supported:
return getattr(self, ansi_key)
else:
return ""
# The formatting/color class handler variable
FTY = Formatting()
# Code starts from here:
def printf(text, f="RESET", **kwargs):
"""
A print function with formatting.
Always prints on stdout.
As arguments takes:
1. string (text to print)
2. formatting type (bold, italic, etc.)
3+. kwargs passed to the print function.
"""
f = FTY.ansi(f.upper())
print("{}{}".format(f, text), file=sys.stdout, **kwargs)
def print_info():
"""Print information about the script."""
printf("This is a helper script for configuring systemd services.", f="bold")
printf("{}Maintainer: {}{}".format(FTY.ansi("FG_GREEN"), FTY.ansi("RESET"), MAINTAINER_NICK))
printf("{}Email: {}{}".format(FTY.ansi("FG_GREEN"), FTY.ansi("RESET"), MAINTAINER_EMAIL))
sys.exit(0)
def parse_arg():
"""Get user arguments and configure them."""
parser = argparse.ArgumentParser(description="Systemd services configuration script")
no_pos = parser.add_mutually_exclusive_group()
schema = parser.add_mutually_exclusive_group()
exclus = parser.add_mutually_exclusive_group()
exclus.add_argument("-c",
"--schema",
help="Choose a custom schema and load defaults from it.",
type=str,
default=SCHEMA)
exclus.add_argument("--edit",
help="Directly edit a systemd unit file.",
action="store_true",
default=False)
no_pos.add_argument("--info",
help="Show information about the script.",
action="store_true",
default=False)
no_pos.add_argument("-b",
"--build",
help="Builds a default schema in schemas/default-schema",
action="store_true",
default=False)
schema.add_argument("-s",
"--short",
help="Use a short configuration schema.",
action="store_true",
default=False)
schema.add_argument("-x",
"--extended",
help="Use a long configuration schema.",
action="store_true",
default=False)
exclus.add_argument("-d",
"--directory",
help="Output directory for the service unit file.",
type=str,
default=OUTPUT_DIR)
exclus.add_argument("--delete",
help="Delete the specified service's configuration file.",
action="store_true",
default=False)
no_pos.add_argument("service_name",
help="The name of the service to configure/edit.",
type=str,
nargs='?')
try:
args = parser.parse_args()
check_parser_opts(args)
except argparse.ArgumentError:
print("Error: An error occured while parsing your arguments.", file=sys.stderr)
sys.exit(ARGPARSE_ERR)
return args
def check_parser_opts(args):
"""
Check if all supplied arguments are used correctly.
Returns an error if the combination of
supplied arguments is illegal.
For arguments that are supposed to be
single checks if any other arguments
are used (besides directory and schema,
since they have default values already).
"""
all_args = [
'build',
'service_name',
'info',
'short',
'extended',
'delete',
'directory',
'edit',
'schema'
]
error = False
# --build is supposed to be used alone.
if args.build:
for arg in all_args:
if (arg is not 'build' and
arg is not 'directory' and
arg is not 'schema'):
value = getattr(args, arg)
else:
value = None
if value:
print("The argument -b/--build cannot be used with {}.".format(arg))
error = True
# --info is supposed to be used alone.
if args.info:
for arg in all_args:
if (arg is not 'info' and
arg is not 'directory' and
arg is not 'schema'):
value = getattr(args, arg)
else:
value = None
if value:
print("The argument --info cannot be used with {}.".format(arg))
error = True
# --delete is supposed to be used only with service_name.
if args.delete:
for arg in all_args:
if (arg is not 'delete' and
arg is not 'directory' and
arg is not 'schema' and
arg is not 'service_name'):
value = getattr(args, arg)
else:
value = None
if value:
print("The argument --delete cannot be used with {}.".format(arg))
error = True
# --edit is supposed to be used only with service_name.
if args.edit:
for arg in all_args:
if (arg is not 'edit' and
arg is not 'directory' and
arg is not 'schema' and
arg is not 'service_name'):
value = getattr(args, arg)
else:
value = None
if value:
print("The argument --edit cannot be used with {}.".format(arg))
error = True
if error:
printf("{}Error: wrong argument usage, aborting.".format(FTY.ansi("FG_RED")), f="bold")
sys.exit(ARGPARSE_ERR)
def get_fragment_path(service):
"""
Returns the path of the systemd service's unit configuration file.
"""
# Extremely ugly (imo) multiline statement
sysctl_out = subprocess.check_output("systemctl show {} -p FragmentPath".format(service),
shell=True)
filename = sysctl_out.decode('utf-8').strip().split('=')[1]
return filename
def edit(service, manual=False, finish=True):
"""
Open the service's systemd service
unit configuration file for editing.
"""
# Check if destination is already set to the full path.
if manual:
file = service
else:
file = get_fragment_path(service)
# Open vim to edit the configuration file. This is a TODO.
with subprocess.Popen(["{} {}".format(DEFAULT_EDITOR, file)], shell=True) as command:
subprocess.Popen.wait(command)
if finish:
finish(file, mode="edit")
def delete(service):
"""
Deletes the given service configuration file,
stops and disables the service.
"""
# Get the destination of the service unit file.
destination = get_fragment_path(service)
# Ask the user for confirmation if it's a system service.
if destination.startswith("/lib/systemd/system"):
print("This is not a user-configured service, do you want to delete it anyway? [y/N]: ")
force_delete = input()
if not (force_delete and (force_delete.lower() == 'y' or force_delete.lower() == 'yes')):
print("Aborting...")
sys.exit(0)
# Stop, disable, and delete the service.
print("Deleting service...")
sysctl_service(service, "stop")
sysctl_service(service, "disable")
os.remove(destination)
service_reload()
print("Deleted service.")
def setup(args):
"""
Check systemd version available on the host to confirm compability.
Also checks whether we have permissions to use
most of the script's functionality.
"""
# Get the systemd version to confirm compability. This is for a future update.
try:
systemd_version = subprocess.check_output('systemd --version', shell=True)
systemd_version = int(systemd_version.strip().split()[1])
except subprocess.CalledProcessError:
print("Systemd isn't working on your system. Why even use this script?", file=sys.stderr)
sys.exit(SYSTEMD_ERR)
if os.getuid() > 0 and not args.build and args.directory == OUTPUT_DIR:
# Extremely ugly (imo) multiline statement
printf("{}Insufficient permissions. "
"You have to run the script as root (with sudo).".format(
FTY.ansi("FG_LIGHT_RED")), f="bold", file=sys.stderr)
sys.exit(UID_ERROR)
return systemd_version
def build():
"""
Build a default example unit configuration schema,
using default constants.
"""
if os.path.exists(DEFAULT_BUILD_SCHEMA):
print("Error: {} already exists.".format(DEFAULT_BUILD_SCHEMA), file=sys.stderr)
sys.exit(SCHEMA_ERR)
else:
schema = configparser.ConfigParser()
schema.optionxform = str
schema['Unit'] = OrderedDict(
Description = DEFAULT_DESCRIPTION,
After = DEFAULT_AFTER
)
schema['Service'] = OrderedDict(
Type = DEFAULT_TYPE,
ExecStart = DEFAULT_EXEC_START,
ExecStop = DEFAULT_EXEC_STOP,
Restart = DEFAULT_RESTART,
RestartSec = DEFAULT_RESTART_SEC,
User = DEFAULT_USER,
Group = DEFAULT_GROUP,
PIDFile = DEFAULT_PID_FILE,
EnvironmentFile = DEFAULT_ENVIRONMENT_FILE,
KillMode = DEFAULT_KILL_MODE,
KillSignal = DEFAULT_KILL_SIGNAL,
TimeoutStopSec = DEFAULT_TIMEOUT_STOP_SEC,
StandardOutput = DEFAULT_STANDARD_OUTPUT,
StandardError = DEFAULT_STANDARD_ERROR,
DynamicUser = DEFAULT_DYNAMIC_USER
)
schema['Install'] = OrderedDict(
WantedBy = DEFAULT_WANTED_BY
)
with open(DEFAULT_BUILD_SCHEMA, 'w+') as schemafile:
schema.write(schemafile)
finish(DEFAULT_BUILD_SCHEMA, mode="build")
def load_schema(schema):
"""
Read the service unit configuration file and load it.
"""
config_dict = {}
config = configparser.ConfigParser()
config.optionxform = str
config.read(schema)
return config
def parse_config(cfg):
"""
Parse the configuration file and return it as dictionaries.
"""
config = argparse.Namespace(**OrderedDict(cfg))
config.Unit = OrderedDict(config.Unit)
config.Service = OrderedDict(config.Service)
config.Install = OrderedDict(config.Install)
return config
def write_config(cfg, destination):
"""
Save the unit configuration file to the destination.
"""
config = configparser.ConfigParser()
config.optionxform = str
config['Unit'] = cfg.Unit
config['Service'] = cfg.Service
if cfg.Install:
config['Install'] = cfg.Install
with open(destination, 'w') as unitfile:
config.write(unitfile)
unitfile.write("# Automatically generated by service-config.\n")
def user_configuration(config):
"""
Let the user interactively configure the unit file.
"""
user_config = config
# Ask for the [Unit] section's keys.
printf("{}[Unit] section configuration:".format(FTY.ansi("FG_YELLOW")), f="bold")
for key in config.Unit:
printf("{}{}={}".format(FTY.ansi("FG_GREEN"), key, FTY.ansi("RESET")), f="bold", end="")
value = input()
user_config.Unit[key] = value
# Ask for the [Service] section's keys.
print()
printf("{}[Service] section configuration:".format(FTY.ansi("FG_BLUE")), f="bold")
for key in config.Service:
printf("{}{}={}".format(FTY.ansi("FG_GREEN"), key, FTY.ansi("RESET")), f="bold", end="")
value = input()
user_config.Service[key] = value
# Ask for the [Install] section's keys.
print()
printf("{}[Install] section configuration:".format(FTY.ansi("FG_MAGENTA")), f="bold")
for key in config.Install:
printf("{}{}={}".format(FTY.ansi("FG_GREEN"), key, FTY.ansi("RESET")), f="bold", end="")
value = input()
user_config.Install[key] = value
# Clear the dictionaries from any empty keys.
user_config.Unit = {k: v for k, v in user_config.Unit.items() if v}
user_config.Service = {k: v for k, v in user_config.Service.items() if v}
user_config.Install = {k: v for k, v in user_config.Install.items() if v}
return user_config
def service_reload():
"""
A simple daemon-reload wrapper.
"""
subprocess.call('systemctl daemon-reload', shell=True)
def sysctl_service(service, action):
"""
A simple systemctl wrapper for service management.
"""
subprocess.call('systemctl {} {}'.format(action, service), shell=True)
def finish(destination, mode="create"):
"""
Checks whether the file has been saved successfully and exits.
"""
if os.path.exists(destination):
if mode == "create":
print("{}Service created successfully.".format(FTY.ansi("FG_GREEN")))
elif mode == "edit":
print("{}Service edited successfully.".format(FTY.ansi("FG_YELLOW")))
elif mode == "build":
print("{}Default schema built successfully.".format(FTY.ansi("FG_BLUE")))
sys.exit(0)
else:
print("The script failed to finish successfully.")
sys.exit(FINISH_ERROR)
def main():
"""
The main function that handles the program.
"""
# Get the parsed arguments.
args = parse_arg()
# Check the version of systemd and check permissions.
systemd_version = setup(args)
# Exit if service_name contains illegal characters.
if args.service_name:
if '\x00' in args.service_name or '/' in args.service_name:
print("Service name contains symbols that are not allowed.")
sys.exit(ARGPARSE_ERR)
if args.delete:
delete(args.service_name)
sys.exit(0)
if args.info:
print_info()
if args.build:
build()
if args.edit:
edit(args.service_name)
if args.short:
args.schema = SCHEMA_SHORT
print("Using short schema configuration.")
if args.extended:
args.schema = SCHEMA_EXTENDED
print("Using extended schema configuration.")
# Load and parse the unit configuration schema.
schema = load_schema(args.schema)
config = parse_config(schema)
# Start interactive configuration, aborts on CTRL-C/CTRL-D.
try:
user_config = user_configuration(config)
except (EOFError, KeyboardInterrupt):
print("\nAborting.")
sys.exit(USER_ABORT)
# Check whether the supplied service name ends with .service.
if not args.service_name.endswith('.service'):
args.service_name = args.service_name + '.service'
# Save the configured unit file to the destination directory.
destination = os.path.join(args.directory, args.service_name)
write_config(user_config, destination)
# Interactive section:
print("Do you want to manually edit the new configuration? [y/N]: ", end="")
manual = input()
if manual and manual.lower() == "y":
print("Opening editor...")
edit(destination, manual=True, finish=False)
else:
print("The configuration file won't be edited.")
# Allow these options only if we have permissions for them.
if os.getuid() == 0:
print("Do you want to enable the service? [y/N]: ", end="")
enable = input()
if enable and enable.lower() == "y":
print("Enabling service...")
service_reload()
sysctl_service(args.service_name, "enable")
print("Service enabled.")
else:
print("Service won't be enabled.")
print("Do you want to start the service? [Y/n]: ", end="")
start = input()
if not start or (start and start.lower() == "y"):
print("Starting service...")
service_reload()
sysctl_service(args.service_name, "start")
print("Service started.")
else:
print("Service won't be started.")
elif os.getuid() > 0:
# Extremely ugly (imo) multiline statement
print("{}No permissions to enable/start service. "
"Need to run with root privileges.".format(FTY.ansi("FG_RED")))
finish(destination)
# Name guard for main process.
if __name__ == "__main__":
# Don't use global error handling if TRACE is set to True.
if TRACE:
main()
elif not TRACE:
try:
main()
except Exception as error:
print("A global exception has been caught.", file=sys.stderr)
print(err, file=sys.stderr)
sys.exit(GLOBAL_ERR)
</code></pre>
<p>I want this script to be reviewed for styling/formatting and readability. I do want it to be fairly easy to read it, since I won't be keeping it only to myself.</p>
<h3>Questions:</h3>
<ol>
<li><p>I've had issues with styling. There are some "extremely ugly multiline statements" that I've made in order to comply with the 100 characters limit I've chosen. Such lines are commented, I do believe them to be ugly. Is the way I've made them really best practice or is there a better way?<br>
An example of such a line is the following:</p>
<pre><code># Extremely ugly (imo) multiline statement
printf("{}Insufficient permissions. "
"You have to run the script as root (with sudo).".format(
FTY.ansi("FG_LIGHT_RED")), f="bold", file=sys.stderr)
</code></pre></li>
<li><p>The <code>Formatting</code> class. I have a class that I use to format/colorize the output of my script, however, the ANSI color codes do not work on every terminal, thus I've made the class the way it is. Is it good practice to have such a class with constants and return the values of those constants by using a method (that allows me to check if the terminal supports ANSI)? Is the way I've gone about coloring/formatting the output a good idea at all, having so many constants for that in my main program and also having a variable to initialize such a class?</p></li>
<li>The way I check for the argument usage. Sure, I have mutually exclusive groups, but those aren't nearly enough to help me achieve what I need. So I've made a function <code>check_parser_opts(args)</code> that checks whether the arguments are used correctly with a bunch of <code>if</code> statements. Is the way I've done it proper, how could I go about this? Or should I just try to simplify my arguments and not have this many?</li>
<li>I've always wondered how should my functions be ordered. Which function should be in which part of the file, after which function, and etc. Is there any "proper" way to order your functions? Currently I just have my <code>main()</code> function at the bottom and I just put everything else above it, without really thinking too much.</li>
</ol>
<p><sub><strong>Note:</strong> For enthusiasts that are interested in the progress of this script, you can follow the <a href="https://github.com/Fanatique1337/systemd-configuration-suite" rel="nofollow noreferrer">github repo</a>.</sub></p>
| [] | [
{
"body": "<p>Regarding your questions:</p>\n\n<ol>\n<li><p>I think the readability suffers mostly because of how the nesting\nflips the order of the strings around, it doesn't feel particularly\nnice to read it out of order, essentially.</p></li>\n<li><p>The <code>Formatting</code> class could be\n<a href=\"ht... | {
"AcceptedAnswerId": "204095",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T08:56:48.167",
"Id": "203604",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"console",
"linux",
"installer"
],
"Title": "Systemd service configuration helper script"
} | 203604 |
<p>I have a simple content management system Spring-MVC web app made with spring boot.</p>
<p>I have the following class called data loader that initially creates some objects and stores them in an H2 in-memory database.</p>
<p>The following code works fine but I want to make it better maybe using a pattern or two?</p>
<p>One problem is loadData method for instance, the order of the methods called inside it is important since some objects depend on other to be created. What pattern can solve this problem?</p>
<p>Note: I specifically want to use patterns just for trying out GoF principles in my code... so any suggestion is welcome even if this task is too simple for a pattern. </p>
<pre><code>@Component
public class DataLoader {
private UserRepository userRepository;
private PageRepository pageRepository;
private PostRepository postRepository;
private MainMenuRepository mainMenuRepository;
private SubMenuRepository subMenuRepository;
private Page homePage;
private Page aboutPage;
private Page contactPage;
private MainMenu mainMenu;
@Autowired
public DataLoader(UserRepository userRepo,
PageRepository pageRepo,
PostRepository postRepo,
MainMenuRepository mainMenuRepo,
SubMenuRepository subMenuRepo) {
this.userRepository = userRepo;
this.pageRepository = pageRepo;
this.postRepository = postRepo;
this.mainMenuRepository = mainMenuRepo;
this.subMenuRepository = subMenuRepo;
loadData();
}
public void loadData() {
loadUsers();
loadPages();
loadPosts();
loadMainMenu();
loadSubMenu();
}
public void loadUsers() {
userRepository.save(new User("solujic", "1", true, Arrays.asList(new Role("USER"), new Role("ADMIN"))));
userRepository.save(new User("admin", "1", true, Arrays.asList(new Role("USER"), new Role("ADMIN"))));
userRepository.save(new User("korisnik", "1", false, Arrays.asList(new Role("USER"))));
}
private void loadPages() {
homePage = new Page("Home", "Greetings this is my home page");
aboutPage = new Page("About", "This is my about page");
contactPage = new Page("Contact", "This is my contact page");
pageRepository.save(homePage);
pageRepository.save(aboutPage);
pageRepository.save(contactPage);
pageRepository.save(new Page("Page 1", "Page 1"));
pageRepository.save(new Page("Page 2", "Page 2"));
pageRepository.save(new Page("Page 3", "Page 3"));
pageRepository.save(new Page("Page 4", "Page 4"));
}
private void loadPosts() {
// Home posts:
postRepository.save(new Post("Spring Boot", // title
"Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can just run.", // text
userRepository.findByUsername("solujic"), // user
pageRepository.findByTitle("Home"))); // page
postRepository.save(new Post("What is Thymeleaf?", "Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine able to apply a set of transformations to template files in order to display data and/or text produced by your applications.\r\n" +
"\r\n" +
"It is better suited for serving XHTML/HTML5 in web applications, but it can process any XML file, be it in web or in standalone applications.\r\n" +
"\r\n" +
"The main goal of Thymeleaf is to provide an elegant and well-formed way of creating templates. In order to achieve this, it is based on XML tags and attributes that define the execution of predefined logic on the DOM (Document Object Model), instead of explicitly writing that logic as code inside the template.\r\n" +
"\r\n" +
"Its architecture allows a fast processing of templates, relying on intelligent caching of parsed files in order to use the least possible amount of I/O operations during execution.\r\n" +
"\r\n" +
"And last but not least, Thymeleaf has been designed from the beginning with XML and Web standards in mind, allowing you to create fully validating templates if that is a need for you.",
userRepository.findByUsername("solujic"), pageRepository.findByTitle("Home")));
postRepository.save(new Post("Spring Data", "Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store. \r\n" +
"\r\n" +
"It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services. This is an umbrella project which contains many subprojects that are specific to a given database. The projects are developed by working together with many of the companies and developers that are behind these exciting technologies.",
userRepository.findByUsername("solujic"), pageRepository.findByTitle("Home")));
// About posts:
postRepository.save(new Post("About",
"This is a simple Spring Boot CMS web application made by solujic.",
userRepository.findByUsername("solujic"),
pageRepository.findByTitle("About")));
// Contact posts:
postRepository.save(new Post("Contact Information",
"email: olujic.slaven@gmail.com, solujic@racunarstvo.hr",
userRepository.findByUsername("solujic"),
pageRepository.findByTitle("Contact")));
}
private void loadMainMenu() {
mainMenu = new MainMenu("Home", pageRepository.findByTitle("Home"));
mainMenuRepository.save(mainMenu);
mainMenu = new MainMenu("About", pageRepository.findByTitle("About"));
mainMenuRepository.save(mainMenu);
mainMenu = new MainMenu("Contact", pageRepository.findByTitle("Contact"));
mainMenuRepository.save(mainMenu);
}
private void loadSubMenu() {
subMenuRepository.save(new SubMenu("Sub Page 1", mainMenuRepository.findByLabel("Home"), pageRepository.findByTitle("Page 1")));
subMenuRepository.save(new SubMenu("Sub Page 2", mainMenuRepository.findByLabel("Home"), pageRepository.findByTitle("Page 2")));
subMenuRepository.save(new SubMenu("Sub Page 3", mainMenuRepository.findByLabel("Home"), pageRepository.findByTitle("Page 3")));
subMenuRepository.save(new SubMenu("Sub Page 4", mainMenuRepository.findByLabel("About"), pageRepository.findByTitle("Page 4")));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T12:30:36.643",
"Id": "392516",
"Score": "0",
"body": "Sorry if I don't understand... but why is your class called DataLoader when it actually saves data? P.S. You don't need @Autowired on your constructor if it is the only construct... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T09:39:36.207",
"Id": "203605",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"spring-mvc"
],
"Title": "Populating a CMS's database with some initial data"
} | 203605 |
<p>It is with great difficulty that I resolved to solve my problem, so I allow myself to submit here the solution.</p>
<p>I wanted a playbook that could replace on all hosts the root password with a string containing the last 3 digits of the IP address of the remote host.</p>
<p>Example:
suppose the password is my_password and my LAN is 172.1.1.0/24. I wanted to set my_password@111 on the host with IP 172.1.1.111, my_password@112 on IP 172.1.1.112, and so on.</p>
<p>Here is the solution i propose:</p>
<pre><code>- hosts: test
vars:
shared_string: my_very_secure_password
tasks:
- debug:
msg: "Remote IP host is {{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
- name: Extract last digits of remote host ip
set_fact:
last_digits: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] | regex_search(regexp) }}"
vars:
regexp: '\d{1,3}$'
- debug:
msg: "Last digits are {{ last_digits }}"
- name: Compose and encrypt the password as shared_string@last_digits
command: openssl passwd -crypt "{{ shared_string }}@{{ last_digits }}"
register: crypted_password
- debug:
msg: "clear password is {{ shared_string }}@{{ last_digits }}"
- debug:
msg: "crypted password is {{ crypted_password.stdout }}"
- name: Change root password
user: name=root update_password=always password={{ crypted_password.stdout }}
</code></pre>
<p>what do you think, how to improve it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T10:02:12.350",
"Id": "392494",
"Score": "0",
"body": "Welcome to Code Review! What does [tag:openssl] have to do with this question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T10:57:18.067",
... | [
{
"body": "<p>For starter, I’d remove debug messages: they do nothing except leaking sensitive information. If you want a deeper sense of what is going on when running your playbook, you can always invoke Ansible with the verbose (<code>-v</code>) option.</p>\n\n<p>Second, I would not use <code>vars</code> to s... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T09:43:34.383",
"Id": "203606",
"Score": "0",
"Tags": [
"regex",
"openssl",
"ansible"
],
"Title": "changing root password with an ansible playbook"
} | 203606 |
<p>I must implement thread-safe queue with buffer. According to the advice from the previous post: <a href="https://codereview.stackexchange.com/questions/203225/thread-safe-queue-mechanism">Thread-safe queue mechanism</a> I resigned from Concurent Collections and used lock.
Is it thread safe now? What can I improve?</p>
<pre><code>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Timers;
class Program
{
public class Document : IItem
{
public Guid Id { get; set; }
public Guid MessageId { get; set; }
}
static void Main()
{
var queueProvider = new Provider();
var docs = new List<IItem>
{
new Document { Id = Guid.NewGuid()},
new Document {Id = Guid.NewGuid()},
new Document {Id = Guid.NewGuid()},
new Document {Id = Guid.NewGuid()},
new Document {Id = Guid.NewGuid()},
};
object locker = new object();
try
{
var tasks = new List<Task>();
var task1 = Task.Factory.StartNew(() =>
{
var timer1 = new Timer(1000) { Interval = 5000 };
timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
{
foreach (var doc in docs)
{
if (queueProvider.TryEnqueue(doc))
{
Console.WriteLine("Enqueue: " + doc.Id + "taskId: 1");
Console.WriteLine("Count: " + queueProvider.QueueCount + " Buffor: " + queueProvider.BufforCount);
}
else
{
Console.WriteLine("Not Enqueue: " + doc.Id + "taskId: 1");
}
}
};
timer1.Enabled = true;
timer1.Start();
});
tasks.Add(task1);
var task2 = Task.Factory.StartNew(() =>
{
var timer1 = new Timer(1000) { Interval = 5000 };
timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
{
foreach (var doc in docs)
{
if (queueProvider.TryEnqueue(doc))
{
Console.WriteLine("Enqueue: " + doc.Id + "taskId: 2");
Console.WriteLine("Count: " + queueProvider.QueueCount + " Buffor: " + queueProvider.BufforCount);
}
else
{
Console.WriteLine("Not Enqueue: " + doc.Id + "taskId: 2");
}
}
};
timer1.Enabled = true;
timer1.Start();
});
tasks.Add(task2);
Task.WaitAll(tasks.ToArray());
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
}
public interface IItem
{
Guid Id { get; set; }
}
public interface IProvider
{
}
public class Provider: IProvider
{
private readonly Queue<IItem> queue;
private readonly Dictionary<Guid, DateTime> inputBuffor;
private readonly object locker = new object();
private readonly int maxQueueCount = 3;
public Provider()
{
queue = new Queue<IItem>();
inputBuffor = new Dictionary<Guid, DateTime>();
}
public bool TryEnqueue(IItem feedingItem)
{
lock (locker)
{
if (inputBuffor.ContainsKey(feedingItem.Id) || queue.Count >= maxQueueCount) return false;
inputBuffor.Add(feedingItem.Id, DateTime.Now);
queue.Enqueue(feedingItem);
return true;
}
}
public IItem Dequeue()
{
lock (locker)
{
if (queue.Count <= 0) return null;
var item = queue.Dequeue();
return item;
}
}
public int QueueCount
{
get { lock (locker) return queue.Count; }
}
public int BufforCount
{
get { lock (locker) return inputBuffor.Count; }
}
}
</code></pre>
| [] | [
{
"body": "<h3>Looks pretty good.</h3>\n\n<p>I'm surmising that the console application is just a test/demo driver, and the code you want reviewed is just the <code>Provider</code> class at the bottom. I don't see any problems with its thread safety, or anything egregious in the way of style.</p>\n\n<p>I do hav... | {
"AcceptedAnswerId": "203622",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T10:08:40.033",
"Id": "203608",
"Score": "2",
"Tags": [
"c#",
"thread-safety"
],
"Title": "Thread safe queue with buffer"
} | 203608 |
<p>In my company, we use git as VCS, the main server run under linux but all our code is for Windows and we all develop on Windows.</p>
<p>The git tag system is case sensitive on linux but is case insensitive on windows.
That is:</p>
<ul>
<li>under linux <code>Test/Tag</code> and <code>TEST/Tag</code> are different tags</li>
<li>under windows <code>Test/Tag</code> and <code>TEST/Tag</code> are the same tag</li>
</ul>
<p>We had a lot of issues from that.</p>
<p>So we decided to add a git hook on server side, that is, a script that will test if a pushed tag already exists on the server <strong>case insensitively</strong>.</p>
<p>Here is the content of the pre-receive git hook.</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/sh
process_ref() {
target="$2" # target hash. 0s for a delete command
refname="$3" # the full ref name
#detect tags
case "$refname" in
refs/tags/*)
# use grep to count matching refs in .git/refs/tags folder (case unsensitivly)
count1=`find ./refs/tags -print | grep -ic $refname`
# use grep to count matching refs in packed-refs if present
if [ -e "./packed-refs" ]; then
count2=`grep -ic "$refname" ./packed-refs`
else
count2="0"
fi
# abort if the ref already exist and it's not a delete ref command
if ([ $count1 -ne 0 ] || [ $count2 -ne 0 ]) && [ $target != "0000000000000000000000000000000000000000" ]; then
echo "push failed"
echo "tag already exists: $refname"
echo "please contact dev team"
exit 1
fi
esac
}
# iterate thru all given refs.
while read REF; do process_ref $REF; done
</code></pre>
| [] | [
{
"body": "<h3>Finding existing Git tags</h3>\n\n<p>The files in a Git repository's meta storage,\nsuch as the content of <code>./refs/tags</code>, <code>./packed-refs</code>,\nare not API.\nIt's best to interact with Git through commands.</p>\n\n<p>You can get the list of tags with the <code>git tag -l</code> ... | {
"AcceptedAnswerId": "205850",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T14:17:13.310",
"Id": "203613",
"Score": "5",
"Tags": [
"shell",
"git"
],
"Title": "Git hook to detect existing tag case insensitive"
} | 203613 |
<p>I'm writing a lot of R in my spare time and am trying to get into good habits by using TidyVerse as much as possible. A large part of this has required reading entire directories of dated log files into R for processing. The volumes of data are well into the GBs so I won't post one here and it shouldn't matter so long as you have filenames matching "./accounts_20180217.csv" or "./symbols_20180217.csv" in the working or data directory. </p>
<p>Example file contents is:</p>
<h3>./accounts_20180217.csv</h3>
<pre><code> 16 109=18A
175 109=1FN
10 109=ABP
6 109=ABW
787 109=ACI
226 109=ACL
163 109=AD
644 109=AGM
79 109=AGN
40 109=AIG
2 109=AJT
991 109=ALG
4 109=ALGR
14 109=AM1
17 109=AN1
34 109=AP1
136 109=APA
267 109=APJ
160 109=ARE
64 109=ARX
329 109=AS1
</code></pre>
<p>I've been using the following to read in and categorise the file data: </p>
<pre><code>library(tidyverse)
library(stringr)
all_data <- tibble(
filename = list.files(
"./", pattern = "^(accounts|symbols)_201[7-9][0-9]{2}[0-9]{2}\\.csv$"
, full.names = TRUE
)
) %>%
mutate(
date = str_extract(filename, "201[7-9][0-9]{4}")
, type = str_extract(filename, "(accounts|symbols)")
, data = map2(
filename
, date
, ~read.csv(
.x
, header = FALSE
, sep = "="
, as.is = TRUE
, col.names = c("count", "names")
, colClasses = c("integer", "character") ))
)
</code></pre>
<p>My question is whether this is a good and Tidy way to achieve this or is there a "better" or "Tidier" way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-15T15:57:39.930",
"Id": "392932",
"Score": "0",
"body": "What are you planing to do with these tables after reading them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-17T07:40:43.347",
"Id": "392995"... | [
{
"body": "<p>A consistent <code>tidyverse</code> solution would use <code>readr::read_csv</code> I guess.</p>\n\n<p>You don't need <code>map2</code> if you don't use <code>.y</code>, <code>map</code> is enough.</p>\n\n<p>You can use <code>read.csv</code> as your <code>.f</code> argument, and leave the rest to ... | {
"AcceptedAnswerId": "203640",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T14:18:02.597",
"Id": "203614",
"Score": "2",
"Tags": [
"file",
"csv",
"r"
],
"Title": "Read a directory of CSV files in R"
} | 203614 |
<p>My use case is that I have a list of emails and I need to find if the email is in the chain:</p>
<pre><code>emails = [
[' RE: I just got your test || This is a top level email roughly 300+ words in length on average'],
['RE:RE: Something | RE: Something | This is another entirely distinct email that is the top level'],
['RE: FooBar | A third email that is entirely distinct']
... #performance issues start occurring with emails growing to > 50 items
]
</code></pre>
<p>Now I would search for an email which is a reply:</p>
<pre><code>test_email = """
A third email that is entirely distinct
"""
</code></pre>
<p>Currently I am using a KMP type search but I believe this is inefficient because it searches for multiple copies of the needle. I also believe the <code>in</code> operator is inefficient because it is using the niave method of searching the string.</p>
<p>An implementation of KMP in python I found and modified slightly:</p>
<pre><code>class KMP:
@classmethod
def partial(self, pattern):
""" Calculate partial match table: String -> [Int]"""
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
ret.append(j + 1 if pattern[j] == pattern[i] else j)
return ret
@classmethod
def search(self, T, P):
"""
KMP search main algorithm: String -> String -> [Int]
Return all the matching position of pattern string P in S
"""
partial, ret, j = KMP.partial(P), [], 0
for i in range(len(T)):
while j > 0 and T[i] != P[j]:
j = partial[j - 1]
try:
if T[i] == P[j]: j += 1
except:
return False
if j == len(P):
return True
return False
</code></pre>
<p>Used here:</p>
<pre><code>for choice in choices: #choice[0] is email in the reply chain
if current_email == choice[0]:
incident_type = choice[1]
break
elif len(current_email) > len(choice[0]):
if KMP.search(current_email, choice[0]):
incident_type = choice[1]
break
else:
if KMP.search(choice[0], current_email):
incident_type = choice[1]
break
</code></pre>
<p>Should I fix this implementation or scrap it in favor of another algo?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T14:34:38.247",
"Id": "392529",
"Score": "0",
"body": "Are you just searching Subject lines? And completely ignoring References/In-Reply-To, etc.?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T14:35... | [
{
"body": "<p>In the post you write:</p>\n\n<blockquote>\n <p>I also believe the <code>in</code> operator is inefficient because it is using the naïve method of searching the string.</p>\n</blockquote>\n\n<p>But if you look at the <a href=\"https://github.com/python/cpython/blob/master/Objects/unicodeobject.c#... | {
"AcceptedAnswerId": "203618",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T14:21:22.460",
"Id": "203615",
"Score": "2",
"Tags": [
"python",
"performance",
"search"
],
"Title": "String search algorithm for finding if a long list of long strings string exists in a similarly sized haystack"
} | 203615 |
<p>I've written a script to look for coordinates in KMZ files. I've tried to speed execution up using the ProcessPoolExecutor. I'm quite new to Python, so any recommendations are more than welcome.</p>
<pre><code>#!/usr/bin/env python
from zipfile import ZipFile
from lxml import html
import os
import concurrent.futures
def process_file(filename):
results=[]
try:
saved_file=False;
kmz = ZipFile(filename, 'r')
for kml_name in kmz.namelist():
if 'doc.kml' in kml_name:
continue
kml = kmz.open(kml_name, 'r').read()
doc = html.fromstring(kml)
for pm in doc.cssselect('Document Placemark'):
tmp = pm.cssselect('track')
if len(tmp):
# Track Placemark
tmp = tmp[0] # always one element by definition
for desc in tmp.iterdescendants():
content = desc.text_content()
if desc.tag == 'coord':
lon = float(content.split()[0])
lat = float(content.split()[1])
search_lon = -47
search_lat = 47
if (abs(lat - search_lat) <= 1 and abs(lon - search_lon) <= 1):
if not saved_file:
results.append('\nFile: ' + filename + '\n')
saved_file=True
results.append(content + '\n')
except:
pass
return results
def main():
# Search all files
kmz_files = []
for root, subdirs, files in os.walk('raw/L1B_Catalogue'):
for file in files:
if '.kmz' in file:
filename = os.path.join(root,file)
kmz_files.append(filename)
# Parallel execution
f=open('kmz_search_output.txt', 'wt')
count = 0
with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
for results in executor.map(process_file, kmz_files, chunksize=10):
print("{} / {}".format(count,len(kmz_files)))
count = count + 1
for line in results:
f.write(line);
pass
f.close()
print('Done')
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>There are no docstrings. What does <code>process_file</code> do? What does it return?</p></li>\n<li><p>The name <code>process_file</code> is vague. It's better to use specific names, for example <code>kmz_coordinates</code>.</p></li>\n<li><p>The <code>saved_file</co... | {
"AcceptedAnswerId": "203662",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T16:47:14.667",
"Id": "203623",
"Score": "2",
"Tags": [
"python",
"beginner",
"file",
"concurrency",
"geospatial"
],
"Title": "ProcessPoolExecutor KMZ file search"
} | 203623 |
<p>I'm just starting out in Rust and I find the concept of ownership confusing so I wrote an implementation of the <code>echo</code> command. I would like to know if I could have set the initial value on the <code>echo</code> variable any better or just any general improvements.</p>
<pre><code>use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut echo: String;
if let Some(string) = args.get(1) {
echo = string.to_string();
} else {
return;
}
for arg in &args[2..] {
echo.push(' ');
echo.push_str(arg.as_str());
}
echo.push('\n');
println!("{}", echo);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T17:46:21.280",
"Id": "392561",
"Score": "2",
"body": "Actually this [answer](https://stackoverflow.com/a/36946085/7076153) cover almost all I could say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12... | [
{
"body": "<p>I would not say I am any more proficient but I would make these changes if I wrote it.</p>\n\n<ul>\n<li><code>skip(1)</code> first arg.</li>\n<li><code>join(\" \")</code> instead of iterate though args. </li>\n</ul>\n\n<p>You do not need a mutable value. </p>\n\n<pre><code>use std::env;\n\nfn main... | {
"AcceptedAnswerId": "203649",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T16:51:16.273",
"Id": "203624",
"Score": "8",
"Tags": [
"beginner",
"strings",
"rust"
],
"Title": "Rust Echo Command Implementation"
} | 203624 |
<p>I created a utility class to keep track of all objects inheriting from it. My main motivation here was to have a clean solution to select which entities in a multiplayer game are synced with the server. I tried to make it as hard as possible to make mistakes (eg. inherit from the wrong crtp parameter) and keep things encapsulated. Well, code speaks more than a thousand words so here we go:</p>
<pre><code>#include <unordered_set>
template<typename t_derived, std::size_t reserved_size = 0>
struct tracker_t
{
friend t_derived;
private: // protected:
tracker_t()
{
data::instances().insert(static_cast<t_derived*>(this));
if constexpr(reserved_size > 0)
{
// force initialization of data::s_initialized
(void)data::s_initialized;
}
}
tracker_t(const tracker_t&)
{
data::instances().insert(static_cast<t_derived*>(this));
}
~tracker_t()
{
data::instances().erase(static_cast<t_derived*>(this));
}
template<typename t_func>
static void iterate(t_func func)
{
for(auto it : data::instances())
{
func(it);
}
}
// forward unordered_set methods
static void reserve(std::size_t n)
{
data::instances().reserve(n);
}
static bool empty()
{
return data::instances().empty();
}
static std::size_t size()
{
return data::instances().size();
}
static auto begin()
{
return data::instances().begin();
}
static auto end()
{
return data::instances().end();
}
static auto cbegin()
{
return data::instances().cbegin();
}
static auto cend()
{
return data::instances().cend();
}
static typename std::unordered_set<t_derived*>::iterator find(const t_derived* item)
{
return data::instances().find(item);
}
struct data // private:
{
friend tracker_t;
private:
static bool reserve()
{
instances().reserve(reserved_size);
return true;
}
static std::unordered_set<t_derived*>& instances()
{
static std::unordered_set<t_derived*> s_instances;
return s_instances;
}
static const bool s_initialized;
};
};
// force execution of reserve()
template<typename t_derived, std::size_t reserved_size>
const bool tracker_t<t_derived, reserved_size>::data::s_initialized {tracker_t<t_derived, reserved_size>::data::reserve()};
</code></pre>
<p>A small example:</p>
<pre><code>#include <iostream>
#include <string>
struct animal_t : tracker_t<animal_t>
{
using tracker_t::iterate;
using tracker_t::size;
virtual std::string get_name() const = 0;
};
struct pig_t : animal_t
{
std::string get_name() const override
{
return "Pig";
}
};
struct duck_t : animal_t
{
std::string get_name() const override
{
return "Duck";
}
};
struct guinea_pig_t : pig_t
{
std::string get_name() const override
{
return "Guinea Pig";
}
};
int main()
{
duck_t duck1, duck2;
pig_t pig1, pig2;
guinea_pig_t guinea1;
std::cout << "Number of objects deriving from animal_t: " << animal_t::size() << "\n\n";
animal_t::iterate([](animal_t* animal)
{
std::cout << animal << ' ' << animal->get_name() << '\n';
});
return 0;
}
</code></pre>
<p>I'd like to get some feedback on:</p>
<ul>
<li><p>is there anything broken (ub, performance, ...)</p></li>
<li><p>best practices</p></li>
<li><p>error susceptibility</p></li>
<li><p>code style</p></li>
<li><p>suggestions on how to make it easier to use</p></li>
</ul>
| [] | [
{
"body": "<h2>Creation of the static map</h2>\n\n<p>What immediately cought my eye were these lines:</p>\n\n<pre><code> if constexpr(reserved_size > 0)\n {\n // force initialization of data::s_initialized\n (void)data::s_initialized;\n }\n</code></pre>\n\n<p>and of course these:</p>\n... | {
"AcceptedAnswerId": "204559",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T17:01:16.310",
"Id": "203626",
"Score": "2",
"Tags": [
"c++",
"object-oriented"
],
"Title": "C++ object tracker"
} | 203626 |
<p>You know how whenever you download a file you should really compare the hash of the download to the one provided on the website? This makes absolute sense, but it's a pain to do it letter for letter, digit for digit. So, I wrote this little script to take care of the job. Any comments are welcome.</p>
<pre><code>#!/bin/bash
# hash_checker - program to verify a downloaded file
error_exit()
{
echo "$1" 1>&2
exit 1
}
usage="usage: hash_checker downloaded_file hash_provided -a algorithm"
downloaded_file=
hash_given=
hash_calc=
algo="sha256"
# check if file and hash were provided
if [ $# -lt 2 ]; then
error_exit "$usage"
fi
# parsing the provided hash and file
downloaded_file="$1"
hash_given="$2"
# parsing the algorithm, if provided
if [ "$3" != "" ]; then
if [ "$3" = "-a" ]; then
algo="$4"
else
error_exit "$usage"
fi
fi
# check if input is a valid file
if [ ! -f "$downloaded_file" ]; then
error_exit "Invalid file! Aborting."
fi
# calculate the hash for the file
hash_calc="$($algo'sum' $downloaded_file)"
hash_array=($hash_calc)
hash_calc=${hash_array[0]}
# compare the calculated hash to the provided one
if [ "$hash_calc" = "$hash_given" ]; then
echo "The hashes match. File seems to be valid."
else
echo "The hashes do not match. File does not seem to be valid."
fi
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T07:16:15.437",
"Id": "392597",
"Score": "0",
"body": "Why not just use the `-c` option to `sha1sum` or `md5sum` to do the comparison?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T07:25:22.667",
... | [
{
"body": "<p>Notes:</p>\n\n<ul>\n<li>I'd use <code>getopts</code> for arg parsing -- lots of examples on stackoverflow about how to use it.</li>\n<li><a href=\"https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells\">always quote your variab... | {
"AcceptedAnswerId": "203634",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T19:31:48.523",
"Id": "203633",
"Score": "4",
"Tags": [
"bash",
"hashcode"
],
"Title": "Small script to verify hash of a downloaded file"
} | 203633 |
<p>I've implemented a basic <code>TransactionManager</code> class that manages undoing/redoing of arbitrary <code>Action</code>s which have access to the <code>TransactionManager</code>'s type via template parameter.</p>
<p>Here's the basic usage:</p>
<pre><code>#include "Transaction.h"
TRANSACTION_MANAGER(TestTransactionManager) {
public:
TestTransactionManager() : value(0) {}
int value;
};
class AdditionAction : public Action<TestTransactionManager> {
public:
explicit AdditionAction(int amount) : amount(amount) {}
void perform(TestTransactionManager *transactionManager) noexcept override {
transactionManager->value += amount;
}
void undo(TestTransactionManager *transactionManager) noexcept override {
transactionManager->value -= amount;
}
int amount;
};
int main(int argc, char *argv[]) {
TestTransactionManager manager;
{
auto *transaction = manager.createTransaction<AdditionAction>();
transaction->setAction(AdditionAction(5));
transaction->finalize();
assert(manager.value == 5);
}
{
// create an empty transaction - it should
// not affect the undo/redo behaviour
auto *transaction = manager.createTransaction<AdditionAction>();
transaction->finalize();
assert(manager.value == 5);
}
{
auto *transaction = manager.createTransaction<AdditionAction>();
// modify the action multiple times before finalizing -
// the action should be immediately applied, but undone
// when replaced.
transaction->setAction(AdditionAction(3));
assert(manager.value == 8);
transaction->setAction(AdditionAction(5));
assert(manager.value == 10);
transaction->setAction(AdditionAction(3));
transaction->finalize();
assert(manager.value == 8);
}
manager.undo();
assert(manager.value == 5);
manager.undo();
assert(manager.value == 0);
manager.redo();
assert(manager.value == 5);
manager.undo();
assert(manager.value == 0);
manager.redo();
assert(manager.value == 5);
manager.redo();
assert(manager.value == 8);
}
</code></pre>
<p>To provide such a clean interface, I had to use some tricks to work around the restrictions of templates.<br>
For example, I implemented the <code>ActionPerformer</code> which stores an implementation of <code>Action</code> inside a <a href="https://en.cppreference.com/w/cpp/utility/any" rel="noreferrer"><code>std::any</code></a>. This way, I can store <code>ActionPerformer</code>s containing different kinds of actions inside the same vector, which wouldn't be possible if the type of the <code>Action</code> was a template parameter of the <code>ActionPerformer</code>. The <code>ActionPerformer</code> is able to convert the <code>std::any</code> back into the appropiate <code>Action</code> type because the type is stored inside the lambda functions passed to it during construction, as can be seen around <em>line 185</em>.</p>
<p>In <em>line 176</em>, I take an unused pointer to an instance of the <code>ActionType</code> template class parameter, to be able to implicitly provide the <code>TransactionType</code> class parameter in <em>line 69</em>, as its own type isn't available at to the caller.</p>
<p>Is there an cleaner way to achieve the same results for both these "hacks"?
Here's the source code of the transaction system:</p>
<pre><code>#pragma once
// Transaction.h
#include <cassert>
#include <vector>
#include <memory>
#include <experimental/any>
#include <experimental/optional>
#include <functional>
// for any, any_cast and optional
using namespace std::experimental;
template<class TransactionManagerType>
class TransactionManager;
template<class TransactionManagerType>
class Action {
public:
virtual ~Action() = default;
/**
* Performs the action on the given transaction manager.
* @param transactionManager The transaction manager to perform the transaction on.
*/
virtual void perform(TransactionManagerType *transactionManager) noexcept = 0;
/**
* Undos the action on the given transaction manager.
* @param transactionManager The transaction manager to undo the transaction on.
*/
virtual void undo(TransactionManagerType *transactionManager) noexcept = 0;
};
template<class TransactionManagerType, class ActionType>
class Transaction {
public:
explicit Transaction(TransactionManagerType *transactionManager) :
transactionManager(transactionManager), finalized(false) {}
virtual ~Transaction() = default;
const optional<ActionType> &getAction() const {
return actionOpt;
}
void setAction(ActionType action) {
assert(!finalized);
if (actionOpt) {
// undo the existing action, if any
actionOpt->undo(transactionManager);
}
// perform the new action
action.perform(transactionManager);
// set the existing action
actionOpt = action;
}
void finalize() {
assert(!finalized);
finalized = true;
transactionManager->transactionFinalized(
this,
// implicitly provide the ActionType to transactionFinalized
// using a dummy pointer, to avoid having to explicitly provide
// the transaction's type (which we don't have)
static_cast<ActionType *>(nullptr));
}
private:
TransactionManagerType *transactionManager;
bool finalized;
/**
* The current action, if any.
*/
optional<ActionType> actionOpt;
};
/**
* ActionPerformer is a utility class implicitly remembering
* the type of the action contained in the lambda functions
* it is created with.
* This is required to avoid having to add the action type
* as a template argument, which would make it impossible
* to store ActionPerformers for different action types
* on a TransactionManager's undo and redo stack.
*/
template<class TransactionManagerType>
class ActionPerformer {
public:
ActionPerformer(const std::shared_ptr<any> &action,
const std::function<void(TransactionManagerType *)> &undoAction,
const std::function<void(TransactionManagerType *)> &redoAction) :
action(action), undoAction(undoAction), redoAction(redoAction) {}
void undo(TransactionManager<TransactionManagerType> *manager) {
undoAction(static_cast<TransactionManagerType *>(manager));
}
void redo(TransactionManager<TransactionManagerType> *manager) {
redoAction(static_cast<TransactionManagerType *>(manager));
}
private:
/**
* The action to perform.
*/
std::shared_ptr<any> action;
std::function<void(TransactionManagerType *)> undoAction, redoAction;
};
template<class TransactionManagerType>
class TransactionManager {
public:
TransactionManager() = default;
virtual ~TransactionManager() = default;
template<class ActionType>
Transaction<TransactionManagerType, ActionType> *createTransaction() {
// there must not be a current unfinalized transaction
assert(currentTransaction.empty());
currentTransaction = Transaction<TransactionManagerType, ActionType>(
// cast from TransactionManager<TransactionManagerType> to TransactionManagerType.
static_cast<TransactionManagerType *>(this));
return any_cast<Transaction<TransactionManagerType, ActionType>>(&currentTransaction);
};
/**
* Undos the previous transaction.
*/
void undo() noexcept {
assert(!undoStack.empty());
if (undoStack.empty()) return;
auto &performer = undoStack.back();
// undo the action
performer.undo(this);
// add the action performer to the redo stack
redoStack.push_back(performer);
// remove the transaction from the undo stack
undoStack.pop_back();
}
/**
* Redos the next transaction.
*/
void redo() noexcept {
assert(!redoStack.empty());
if (redoStack.empty()) return;
auto &performer = redoStack.back();
// redo the action
performer.redo(this);
// add the action performer to the undo stack
undoStack.push_back(performer);
// remove the transaction from the redo stack
redoStack.pop_back();
}
/**
* Called by the current transaction when it is finalized.
* @param transaction The transaction that was finalized.
*/
template<class TransactionType, class ActionType>
void transactionFinalized(TransactionType *transaction, ActionType *dummy) {
auto &actionOpt = transaction->getAction();
if (actionOpt) {
// clear the redo stack
redoStack.clear();
// add the transaction's action to the undo stack
auto action = *actionOpt;
// create a shared pointer containing a copy of the action
// as an "any" instance to circumvent the need of a
// template argument for the Action Type in the
// ActionPerformer class, which makes it possible
// to store ActionPerformers of different ActionTypes
// in a vector. The ActionType is retained in the
// lambda function.
auto actPtr = std::make_shared<any>(ActionType(action));
undoStack.emplace_back(actPtr, [actPtr
](TransactionManagerType *manager) {
any_cast<ActionType>(actPtr.get())->undo(manager);
}, [actPtr](TransactionManagerType *manager) {
any_cast<ActionType>(actPtr.get())->perform(manager);
});
}
// clear the current transaction
currentTransaction.clear();
};
private:
/**
* The current unfinalized transaction, if any.
*/
any currentTransaction;
/**
* The stacks of actions to undo and redo.
*/
std::vector<ActionPerformer<TransactionManagerType>> undoStack, redoStack;
};
#define TRANSACTION_MANAGER(className) class className : public TransactionManager<className>
</code></pre>
<p>Here's an <a href="https://ideone.com/LxMJKt" rel="noreferrer">ideone page</a> where you can run the code yourself.</p>
| [] | [
{
"body": "<p>If you want to implement the command manager pattern, you can do something so very much simpler that I don't really understand what you're aiming for.</p>\n\n<p>As you know, the design pattern has a <code>Command</code> class exposing methods with <code>void execute()</code> and <code>void undo()<... | {
"AcceptedAnswerId": "203678",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-12T22:38:54.740",
"Id": "203639",
"Score": "6",
"Tags": [
"c++",
"template-meta-programming",
"transactions"
],
"Title": "Transaction manager, supporting undo/redo, using C++ templates"
} | 203639 |
<p>I have received this question during an interview I did earlier, but I found that my solution might not be correct. And I would like to know whatever there is a better way to solve this.</p>
<p>Question:</p>
<blockquote>
<p>Lots of people are making a reservation for appointments</p>
<p>Writes a function to let people make appointments reservation before
attending the appointment. When a time-slot is reserved
(already booked), do not let any user double-book and make overlap reservation in the same time-slot.</p>
<p>Reservation takes (as an example)</p>
<ul>
<li>personA: 9:00 -> 11:00 tomorrow -> successful</li>
<li>personB: 9:00 -> 10:00 tomorrow -> fail</li>
<li>personC: 13:00 -> 14:00 tomorrow -> successful</li>
<li>personA: 17:00 -> 18:00 tomorrow -> fail because personA already made reservation once</li>
</ul>
<p><strong>Few notes:</strong></p>
<ul>
<li>Assuming reservation only for 1 specific day, 24-hrs only </li>
<li>Assuming the clock is 24-hrs with only integers</li>
</ul>
<p><strong>Additions - v1.1</strong> After launching v1.0, more than half of the users do not attend their appointments. Allow a user to reserve appointments
twice in the same time intervals</p>
</blockquote>
<pre><code>ALLOW_MULTIPLE_RESERVATIONS = 2
users = {
'alice': '1',
'bob': '2',
}
appointments = [[9, 12], [9, 12], [13, 17]]
reservations = {}
def print_error(user, time):
print('Cannot make reservation for user {} at {}'.format(user, time))
return False
def reserve(user, time):
# this case is for double reservation for the same interval
if user in reservations:
user_reservation = reservations[user]
user_count = reservations[user]['count']
user_time = reservations[user]['time']
if user_count < ALLOW_MULTIPLE_RESERVATIONS:
if user_time[0] == time[0] and user_time[1] == time[1]:
reservations[user] = {
'time': time,
'count': user_count + 1,
}
return True
else:
print_error(user, time)
return False
# this is for first time reservation
for t in appointments:
if user not in reservations:
if (time[0] >= t[0] and time[1] <= t[1]):
t[0] = time[1]
t[1] = t[1]
reservations[user] = {
'time': time,
'count': 1,
}
# end-for
# when we cannot find any available time interval for reservation, we simply just return False
if user not in reservations:
print_error(user, time)
return False
return True
reserve(user='alice', time=[9, 10])
reserve(user='alice', time=[9, 10]) # v1.1 this should pass
reserve(user='alice', time=[9, 10]) # v1.1 this should fail
reserve(user='bob', time=[9, 10])
print(reservations)
print(appointments)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-27T06:59:50.807",
"Id": "531553",
"Score": "0",
"body": "what is the `appointments` list used for?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T00:14:05.193",
"Id": "203641",
"Score": "3",
"Tags": [
"python",
"interview-questions"
],
"Title": "Interview: Appointment reservations"
} | 203641 |
<h1>Context</h1>
<p>This program will control a robot. It is written in Java 7 and compiles into an Android app, but these classes are not Android specific. This program was written for <a href="https://www.firstinspires.org/robotics/ftc" rel="nofollow noreferrer">FIRST Tech Challenge</a> and uses some classes from their SDK, available online at <a href="https://github.com/ftctechnh/ftc_app" rel="nofollow noreferrer">https://github.com/ftctechnh/ftc_app</a>.</p>
<h1>Purpose</h1>
<p>These classes are designed to provide event handling capabilities to the robot so that it can more easily react to user input.</p>
<h1>Details</h1>
<p><code>Gamepad.on(ButtonState, Button, EventListener)</code> is called as the program is initializing and allows the user to set an event listener in the case of an event on a button. There is a loop that runs for as long as the robot is running. Before each iteration of this loop, the member variables of the instances of <code>com.qualcomm.robotcore.hardware.Gamepad</code>, such as <code>a</code> and <code>b</code> (<code>public boolean</code>), are updated to reflect if some button is currently being pressed. Then, <code>Gamepad.handleEvents()</code> is called to update the state of the buttons and run user defined event handler code.</p>
<p>Gamepad.java: This is the main class that the user interacts with.</p>
<pre><code>package org.firstinspires.ftc.teamcode.teleop;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Gamepad {
private Map<Button, EventContainer> mButtonEvents = new HashMap<>();
private com.qualcomm.robotcore.hardware.Gamepad mGamepad;
public Gamepad(com.qualcomm.robotcore.hardware.Gamepad gamepad) {
mGamepad = gamepad;
}
public void on(ButtonState event, Button button, EventListener listener) {
if (!mButtonEvents.containsKey(button)) {
mButtonEvents.put(button, new EventContainer());
}
EventContainer eventContainer = mButtonEvents.get(button);
eventContainer.addHandler(event, listener);
}
public void handleEvents() {
Set<Button> buttons = mButtonEvents.keySet();
for (Button button : buttons) {
EventContainer eventContainer = mButtonEvents.get(button);
eventContainer.nextState(button.extract(mGamepad)).handle();
}
}
}
</code></pre>
<p>Button.java: This enum contains every button on the physical controller (all are not listed here, but follow the same pattern that those listed do). It also contains the code needed to get if the button is being pressed from the <code>com.qualcomm.robotcore.hardware.Gamepad</code> instance.</p>
<pre><code>package org.firstinspires.ftc.teamcode.teleop;
import com.qualcomm.robotcore.hardware.Gamepad;
public enum Button {
A(new ExtractButton() {
@Override
public boolean extract(com.qualcomm.robotcore.hardware.Gamepad gamepad) {
return gamepad.a;
}
}),
B(new ExtractButton() {
@Override
public boolean extract(com.qualcomm.robotcore.hardware.Gamepad gamepad) {
return gamepad.b;
}
// More buttons here
});
ExtractButton mExtractor;
Button(ExtractButton extractor) {
mExtractor = extractor;
}
public boolean extract(com.qualcomm.robotcore.hardware.Gamepad gamepad) {
return mExtractor.extract(gamepad);
}
private interface ExtractButton {
boolean extract(com.qualcomm.robotcore.hardware.Gamepad gamepad);
}
}
</code></pre>
<p>EventContainer.java: This class implements a state machine and manages adding and calling event handlers.</p>
<pre><code>package org.firstinspires.ftc.teamcode.teleop;
import java.util.HashMap;
import java.util.Map;
public class EventContainer {
private ButtonState mState;
private Map<ButtonState, EventListener> mEventHandlers = new HashMap<>();
private static ButtonState generateNextState(boolean buttonInput, ButtonState oldState) {
switch (oldState) {
case OFF:
if (buttonInput) {
return ButtonState.PRESSED;
} else {
return ButtonState.OFF;
}
case PRESSED:
if (buttonInput) {
return ButtonState.HELD;
} else {
return ButtonState.RELEASED;
}
case HELD:
if (buttonInput) {
return ButtonState.HELD;
} else {
return ButtonState.RELEASED;
}
case RELEASED:
if (buttonInput) {
return ButtonState.PRESSED;
} else {
return ButtonState.OFF;
}
default:
return ButtonState.OFF;
}
}
public EventContainer addHandler(ButtonState event, EventListener listener) {
mEventHandlers.put(event, listener);
return this;
}
public EventContainer handle() {
if (mEventHandlers.containsKey(mState)) {
mEventHandlers.get(mState).onEvent();
}
return this;
}
public EventContainer nextState(boolean buttonInput) {
mState = generateNextState(buttonInput, mState);
return this;
}
}
</code></pre>
<p>ButtonState.java: This enum contains the four states that a button can be in.</p>
<pre><code>package org.firstinspires.ftc.teamcode.teleop;
public enum ButtonState {
PRESSED, // Button was just pressed
HELD, // The button has been pressed for more than one iteration
RELEASED, // The button was just released
OFF // The button has been released for more than one iteration
}
</code></pre>
<p>EventListener.java: This simple interface is implemented by users and is called when an event occurs.</p>
<pre><code>package org.firstinspires.ftc.teamcode.teleop;
public interface EventListener {
void onEvent();
}
</code></pre>
<p>Example usage:</p>
<pre><code>// Initialization
gamepadInstance.on(ButtonState.PRESSED, Button.A, new EventListener() {
@Override
public void onEvent() {
// Somehow react to the 'A' button being pressed
openRobotClaw();
}
});
// ...
// Repeats in a loop as long as the robot runs
gamepadInstance.handleEvents();
</code></pre>
<h1>My questions</h1>
<ol>
<li>Is there a better way to handle the extraction of the pressed booleans from instances of <code>com.qualcomm.robotcore.hardware.Gamepad</code>? I used the enum method because it ensures that even if a new Button is added, there will still be a way to extract the boolean and without having to update different parts of the code. However, it feels like there is a lot of boilerplate code to perform a simple task.</li>
<li>Are there any ways to simplify my code?</li>
<li>Is there a better way for users to create event handlers?</li>
<li>What best practices am I missing here?</li>
</ol>
| [] | [
{
"body": "<p>nice job!</p>\n\n<p>Some hints:</p>\n\n<p><strong>Gamepad.java</strong></p>\n\n<ul>\n<li>I don't get why do you used same name for <code>Gamepad</code>. Would be better to chose another one (<code>CustomGamepad</code> ?)</li>\n<li>Both variables can be <code>final</code> since you do not expose se... | {
"AcceptedAnswerId": "203681",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T00:18:23.527",
"Id": "203642",
"Score": "1",
"Tags": [
"java",
"event-handling"
],
"Title": "Event Handling Gamepad in Java"
} | 203642 |
<p>I have a connection with my database to show all my records on a webpage, and I'm not sure if this code is safe:</p>
<pre><code>define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', null);
define('DB_DATABASE', 'publicacoes');
define('DB_PREFIX', 'bn');
define('DB_CHARSET', 'utf8');
function DBEscape($dados){
$link = DBConnect();
if(!is_array($dados))
$dados = mysqli_real_escape_string($link, $dados);
else{
$arr = $dados;
foreach ($arr as $key => $value) {
$key = mysqli_real_escape_string($link, $key);
$value = mysqli_real_escape_string($link, $value);
$dados[$key] = $value;
}
}
DBclose($link);
return $dados;
}
function DBclose($link){
@mysqli_close($link) or die(mysqli_error($link));
}
function DBConnect(){
$link = @mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die(mysqli_connect_error());
mysqli_set_charset($link, DB_CHARSET) or die(mysqli_error($link));
return $link;
}
function DBRead($table, $params = null, $fields = '*'){
$table = DB_PREFIX.'_'.$table;
$params = ($params) ? " {$params}" : null;
$query = "SELECT {$fields} FROM {$table}{$params}";
$result = DBExecute($query);
if(!mysqli_num_rows($result))
return false;
else{
while ($res = mysqli_fetch_assoc($result)){
$data[] = $res;
}
return $data;
}
}
function DBExecute($query, $insertId = false){
$link = DBConnect();
$result = @mysqli_query($link, $query) or die(mysqli_error($link));
if($insertId)
$result = mysqli_insert_id($link);
DBClose($link);
return $result;
}
$dadosIDrow1 = DBRead('publicacao', "ORDER BY id DESC LIMIT 2");
<?php foreach ($dadosUN as $UN): ?>
//some html here to display the records
<?php endforeach; ?
</code></pre>
<p>This is the first piece of code that I've written to show the records on my website. At the moment I have 2 connections with my DB. One of them I use PDO prepared statement to a pagination and search box.</p>
<p>I want to know if I should delete this script and make a new one with prepared statements.</p>
| [] | [
{
"body": "<blockquote>\n <p>I want to know if I should delete this script and make a new one with prepared statements.</p>\n</blockquote>\n\n<p>Yes, definitely.<br>\nThis set of functions is just unacceptable, being so bad on so many levels. </p>\n\n<ul>\n<li>There will be <em>dozens to hundreds</em> connecti... | {
"AcceptedAnswerId": "203658",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T00:29:30.807",
"Id": "203644",
"Score": "2",
"Tags": [
"php",
"pdo",
"mysqli",
"sql-injection"
],
"Title": "Showing all records on a webpage"
} | 203644 |
<p>I wanted to create a histogram from a list of positive integers. I want to bin it so that I show all single numbers, say K through N, with more than k elements in the data set, as well as the number of elements greater than N. </p>
<pre><code>'''
The goal is to max a histogram from integer data.
The last bin should represent all cases with at least K elements.
x x x x
x x x x x x x
x x x x x ----> x x x x
____________ __________
1 2 3 4 5 6 1 2 3 >3
'''
import matplotlib.pyplot as plt
import numpy as np
# Insert your favorite integer data here
data = [1, 1, 1, 2, 2, 2, 3, 3, 5, 6]
# Vanilla histogram for reference
hist, bins = np.histogram(data, bins=np.arange(1, 15))
center = (bins[:-1] + bins[1:]) / 2 - 0.5
f, ax = plt.subplots()
ax.bar(center, hist, align='center', edgecolor='k')
ax.set_xticks(center)
ax.set_title('vanilla hist')
plt.savefig('vanillahist')
plt.clf()
# Select the point after the last time we see at least k elements
K = 2
maxnum = bins[1:-1][np.abs(np.diff(hist >= K)) > 0][-1]
# filter the bins from numpy to only contain this point and those prior
center = bins[bins <= maxnum]
# filter frequency data from numpy;
# bins/hist are ordered so that the first entries line up
newhist = hist[(bins[:-1] <= maxnum)]
newhist[-1] += np.sum(hist[(bins[:-1] > maxnum)])
# make the plot, hopefully as advertised!
f, ax = plt.subplots()
ax.bar(center, newhist, align='center', edgecolor='k')
ax.set_xticks(center)
ax.set_xticklabels(list(center[:-1].astype(int)) + ['> %i' % (maxnum - 1)])
plt.savefig('myhist')
plt.clf()
</code></pre>
<p>This involved a lot of trial and error, and I'm still not 100% sure this can handle all cases, though it's passed every test I've tried so far. Could I have made this code more readable? I feel particularly unsure about lines 28-38. My justification for the <code>[:-1]</code> line is that the first entry of <code>bins</code> corresponds to the first entry of <code>hist</code>. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T13:52:14.027",
"Id": "392653",
"Score": "1",
"body": "Maybe you could have used [`numpy.digitize`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html). It returns the bin each event is in, including `0` for und... | [
{
"body": "<p>Nice work! You might also be interested in <a href=\"https://stackoverflow.com/q/26218704/562769\">Matplotlib histogram with collection bin for high values</a>.</p>\n\n<p>I like the ascii-art explanation :-)</p>\n\n<p>Things I see that could improve the code:</p>\n\n<ul>\n<li>Put the histogram bui... | {
"AcceptedAnswerId": "203768",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T02:11:10.150",
"Id": "203646",
"Score": "3",
"Tags": [
"python",
"numpy",
"matplotlib"
],
"Title": "Create histogram with greater than symbol in x axis in pyplot"
} | 203646 |
<p>I have a text file where any name followed with sequence word is considered a dictionary. The task is to go through the keys and values of a particular dictionary, which is already identified, and see if any of the key's values is of dictionary datatype. Then, to identify the value is not a dictionary, I scan the file again and see that value followed with sequence word is not there in the file.</p>
<p>If the value is not a dictionary type then it goes inside the excel sheet, searches for that key in a column, extracts its respective value from excel sheet, and adds the key and value found from excel sheet to <code>new_dict</code> which is an empty dictionary.</p>
<p>If the value of a key is there in the file with a suffix word sequence, then it is considered a dictionary datatype. In that scenario, the function has to jump to that dictionary and start doing the earlier process again, and once everything is completed function has to come back to initial position where it has left and then do the process again to complete checking the entire dictionary which is passed initially.</p>
<p>The function is able to handle up to 4 levels of dictionary of dictionaries. I'd like to have the algorithm reviewed.</p>
<pre><code>import re
# keys fetched from excel sheet.
new_cell_obj_other=['message','fuel','speed','mph','kmph','load','name']
# Values fetched from excel sheet.
new_cell_obj=['Hello','solid',100,55,77,'light','world']
old_keys=[]
old_content=[]
new_keys=[]
newer_content=[]
COUNT=0
# Text extracted from the file.
ge='Rocket ::= SEQUENCE { name UTF8String (SIZE(1..16)),\
message UTF8String DEFAULT , \
fuel ENUMERATED {solid, liquid, gas},\
speed INTEGER,\
mph INTEGER,kmph INTEGER \
payload Hello\
} \
Hello ::= SEQUENCE { name UTF8String (SIZE(1..16)),\
message UTF8String DEFAULT , \
fuel ENUMERATED {solid, liquid, gas},\
speed INTEGER,\
mph INTEGER, \
kmph INTEGER, \
load SEQUENCE OF UTF8String } END'
# Text extracted from the file.
ee='Rocket ::= SEQUENCE { name UTF8String (SIZE(1..16)),\
message UTF8String DEFAULT , \
fuel ENUMERATED {solid, liquid, gas},\
speed INTEGER,\
mph INTEGER,kmph INTEGER \
payload Hello\
} \
Hello ::= SEQUENCE { name UTF8String (SIZE(1..16)),\
message UTF8String DEFAULT , \
fuel ENUMERATED {solid, liquid, gas},\
speed INTEGER,\
mph INTEGER, \
kmph INTEGER, \
term World }\
World ::= SEQUENCE { name UTF8String (SIZE(1..16)),\
message UTF8String DEFAULT , \
} END'
new_dict={'message':'Hello','fuel':'solid','speeed':100,'mph':55,'kmph':77,'load':'light'}
seq_list=['rocket','hello','world']
condition=['message UTF8String DEFAULT' ,
'fuel ENUMERATED {solid, liquid, gas}',
'speed INTEGER',
'mph INTEGER',
'kmph INTEGER',
'term world']
def check(other_dict=None,ee=ee,non_condition=None,
from_condition=condition,key=None,
old_keys=old_keys,
new_keys=new_keys,
new_content=newer_content,
old_content=old_content):
ee=ee.lower()
ee=ee.replace('\n','')
global new_dict
if not non_condition and not new_keys:
# Count is incremented when it finds value of a particular key is a dictionary datatype.
global COUNT
COUNT+=1
# from_condition is passed when called from the main function.
if from_condition:
k=[]
for i in from_condition:
# Removes emty items
i=i.split(' ')
# k will be a list of lists of all keys and values of the dictionary,Each list will have a key and value.
k.append(filter(None, i))
# New dictionary is created.
other_dict={}
else:
other_dict={}
# k will be a list of lists of all keys and values of the dictionary,Each list will have a key and value.
k=[non_condition]
for index_content,content in enumerate(k):
for index,value in enumerate(content[1:]):
new_value=value.replace(',','')
# new_cell_obj_other will have a list of items names which are there in the excel sheet
# and new_cell_obj indicates its respective value from the excel sheet,seq_list indicates list of dictionaries which are there in the file.
# Conditions is true if the value of the key is not a dictionary.
if content[0] in new_cell_obj_other and new_value not in seq_list:
for item,value in zip(new_cell_obj_other,new_cell_obj):
if content[0]==item:
other_dict[item]=value
break
else:
continue
break
else:
# old contents will be storing the remaining keys and values of a dictionary when one of its key's value is a dictionary.
for i in k[index_content+1::]:
old_content.append(i)
if old_keys and not non_condition and not new_keys:
length=len(old_keys)
if length==2:
new_dict[old_keys[0]][old_keys[1]]=other_dict
elif length==3:
new_dict[old_keys[0]][old_keys[1]][old_keys[2]]=other_dict
elif length==3:
new_dict[old_keys[0]][old_keys[1]][old_keys[2]][old_keys[3]]=other_dict
elif not old_keys and other_dict:
new_dict[key]=other_dict
ee=ee.lower()
ee=ee.replace('\n','')
#Finds the whole set of data for the corresponding dictionary from the file where content[-1] is the name of the dictionary which we identified.
reg_value=re.findall(r'{0}\s*::=\s*sequence(.*?)(::=|end)'.format(content[-1]),ee)
if reg_value:
v=reg_value[0][0].split('{')
v=v[1].split('}')[0]
v=v.split(',')
if not old_keys and not non_condition:
# Initially append the key whose value is a dictionary datatype.
old_keys.append(key)
# Appending the subsequent keys whose values are dictionary datatype.
old_keys.append(content[0])
# calling the recursive function.
return check(other_dict=other_dict,ee=ee,
key=new_content,
from_condition=v,
old_keys=old_keys,
old_content=old_content)
if old_keys and not new_keys:
length=len(old_keys)
# Adding the dictionary inside its respective dictionary
if length==2:
new_dict[old_keys[0]][old_keys[1]]=other_dict
elif length==3:
new_dict[old_keys[0]][old_keys[1]][old_keys[2]]=other_dict
elif length==4:
new_dict[old_keys[0]][old_keys[1]][old_keys[2]][old_keys[3]]=other_dict
del old_keys[-1]
if not old_keys and not new_keys and other_dict:
# Adding the dictionary inside the main dictionary directly
new_dict[key]=other_dict
while COUNT>=1 and (old_content or newer_content):
#new_keys is an empty list which is appended with old_keys and newer_content is an empty list which is appended with old_content
COUNT-=1
len_other=len(new_keys)
for i_key in old_keys:
if i_key not in new_keys:
new_keys.append(i_key)
for j_content in old_content:
if j_content not in newer_content:
newer_content.append(j_content)
length_new=len(new_keys)
if length_new==2 and new_keys!=old_keys:
new_dict[new_keys[0]][new_keys[1]]=other_dict
elif length_new==3 and new_keys!=old_keys:
new_dict[new_keys[0]][new_keys[1]][new_keys[2]]=other_dict
elif length_new==4 and new_keys!=old_keys:
new_dict[new_keys[0]][new_keys[1]][new_keys[2]][new_keys[3]]=other_dict
if not len_other==0:
del newer_content[-1]
if not len_other==0:
if len_other!=len(new_keys):
del new_keys[-1]
del new_keys[-1]
if newer_content and new_keys:
check(other_dict=other_dict,
ee=ee,
key=new_keys[-1],
non_condition=newer_content[-1],
old_keys=[],
old_content=[])
return new_dict
print check(from_condition=condition,key='payload')
</code></pre>
<p>Output:</p>
<pre><code>{'load': 'light', 'speeed': 100, 'mph': 55, 'kmph': 77, 'fuel': 'solid', 'message': 'Hello', 'payload': {'term': {'message': 'Hello', 'name': 'world'}, 'mph': 55, 'kmph': 77, 'fuel': 'solid', 'message': 'Hello', 'speed': 100}}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T11:30:36.867",
"Id": "394128",
"Score": "1",
"body": "Could you add a python version tag? I know it might be obvious for some experts which version it is just by seeing the API but probably not for all people ;-]"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T07:00:46.123",
"Id": "203655",
"Score": "1",
"Tags": [
"python",
"recursion",
"hash-map"
],
"Title": "Filling values for nested dictionaries"
} | 203655 |
<p>Each User has a field called id. And I want to create a vector containing all ids of the users returned by the API call.</p>
<blockquote>
<pre><code>vector<int> ids;
Users* users = // API CALL HERE
for (auto i = 0; i < total_users; i++)
{
logins.push_back(users[i].id);
}
</code></pre>
</blockquote>
<p>Is there a way to do this in a more clean way in C++?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T09:26:32.893",
"Id": "392611",
"Score": "1",
"body": "Please edit the question to provide more context to the code that you want reviewed. It would also help if you could specify details such as what version of c++ you are using."
... | [
{
"body": "<p>You can almost always use a standard algorithm. It doesn't always look nicer though, but your intent is easier to read and you can benefit from the library's optimizations (and from parallelized algorithms with some luck)</p>\n\n<pre><code>#include <algorithm>\n#include <iterator>\n\n.... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T08:54:42.457",
"Id": "203659",
"Score": "-2",
"Tags": [
"c++"
],
"Title": "Transforming values from array of an object to vector in C++"
} | 203659 |
<p>We have an event file which I'm processing to get the status of a job (process), whereas a single job contains multiple fields which I want to segregate based on what I required, for example, "<code>JOB_NEW</code>", "<code>JOB_START</code>" etc.</p>
<p>As in my current code I'm processing the file line by line and with a loop and that again processed through multiple conditions, so it works fine but looks to be time taking in case the file is really large (millions of lines). I'm wondering if there is a better nice way to process this in an elegant way to make it really better and faster.</p>
<pre><code>#!/python/v3.6.1/bin/python3
import sys , os , re
from optparse import OptionParser
import numpy as np
import time
import sys
import datetime
import textwrap
wrapper = ''
preferredWidth = 75
def text_format(self,initial):
global wrapper
wrapper = textwrap.TextWrapper(initial_indent=initial, width=preferredWidth,
subsequent_indent=' '*14)
return wrapper
wrapper = text_format('self','Job')
def opt():
parser = OptionParser()
parser.add_option("-l", "--longformat", dest="long",
help="longformat", metavar="LONG")
parser.add_option("-n", "--number", dest="num",
help="number", metavar="NUM")
(options, args) = parser.parse_args()
return(options, args)
(options,args) = opt()
if options.long:
jobid = options.long
check_jobid = re.match("^\d+$",jobid)
if not check_jobid:
print(jobid + ": Illegal job ID.")
sys.exit()
event_file = "/proj/lsb.events"
with open(event_file, "r") as r:
for line in r:
line = line.strip()
match_jobid = line.split(' ')[3]
match_jobid = match_jobid.strip()
var = line.split()
var = [v.replace('\"', '') for v in var]
#===============================JOB_NEW=========================================
#if match_jobid == jobid and "JOB_NEW" in line:
if match_jobid == jobid and var[0] == "JOB_NEW":
print (wrapper.fill("<%s>, Job Name <%s>, User <%s>, Project <%s>, Command <%s>" %(jobid,var[-1],var[11],var[-6],var[-7])))
wrapper = text_format('self','')
var[2] = time.strftime('%a %b %d %H:%M:%S %Y', time.localtime(int(var[2])))
print(wrapper.fill("%s: Submitted from host <%s>, to Queue <%s>, CWD <%s>, Output File <%s>, Requested Resources <%s>;" %(var[2],var[25],var[23],var[26],var[28],var[24])))
#==============================JOB_START========================================
elif match_jobid == jobid and var[0] == "JOB_START":
wrapper = text_format('self','')
var[2] = time.strftime('%a %b %d %H:%M:%S %Y', time.localtime(int( var[2])))
print(wrapper.fill("%s: Dispatched to <%s>;" %(var[2],var[9])))
#=============================JOB_START_ACCEPT=================================
elif match_jobid == jobid and var[0] == "JOB_START_ACCEPT":
wrapper = text_format('self','')
var[2] = time.strftime('%a %b %d %H:%M:%S %Y', \
time.localtime(int(var[2])))
print(wrapper.fill("%s: Starting (Pid %s);" %(var[2],var[4])))
#=============================JOB_EXECUTE=====================================
elif match_jobid == jobid and var[0] == "JOB_EXECUTE":
wrapper = text_format('self','')
var[2] = time.strftime('%a %b %d %H:%M:%S %Y', \
time.localtime(int(var[2])))
print(wrapper.fill("%s: Running with execution home <%s>,\
Execution CWD <%s>,Execution Pid <%s> ;"\
%(var[2],var[7],var[6],var[9])))
#============================JOB_SIGNAL=======================================
elif match_jobid == jobid and var[0] == "JOB_SIGNAL":
wrapper = text_format('self','')
var[2] = time.strftime('%a %b %d %H:%M:%S %Y', \
time.localtime(int(var[2])))
print(wrapper.fill("%s: Signal <%s> requested by user \
or administrator <%s> ;" %(var[2],var[5],var[4])))
</code></pre>
<h2>Sample File</h2>
<pre><code>"JOB_NEW" "1" 1536742813 84 258034 33554482 1 0 1536742813 0 0 "xyz" -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 "lnx64" "" "no-xyz" "/home/xyz/junk" "" "/home/xyz/123a" "cmd.err" "/home/xyz" "1536742813.84" 0 "" "" "sleep 10" "default" 2048 0 -1 "" ""
"JOB_NEW" "1" 1536742813 85 258034 33554482 1 0 1536742813 0 0 "xyz" -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 "lnx64" "" "no-xyz" "/home/xyz/junk" "" "/home/xyz/123a" "cmd.err" "/home/xyz" "1536742813.84" 0 "" "" "sleep 10" "default" 2048 0 -1 "" ""
"JOB_START" "1" 1536742819 84 4 0 0 1.0 1 "no-xyz" "" "" 0 0 ""
"JOB_START" "1" 1536742819 85 4 0 0 1.0 1 "no-xyz" "" "" 0 0 ""
"JOB_START_ACCEPT" "1" 1536742819 84 6702 6702 0 0
"JOB_EXECUTE" "1" 1536742820 84 258034 6702 "/home/xyz/junk" "/home/xyz" "xyz" 6702 0
"JOB_START_ACCEPT" "1" 1536742819 85 6702 6702 0 0
"JOB_EXECUTE" "1" 1536742820 85 258034 6702 "/home/xyz/junk" "/home/xyz" "xyz" 6702 0
"JOB_STATUS" "1" 1536742840 85 64 0 0 0.0000 1536742840 0 0 1996 0
"JOB_NEW" "1" 1536742813 86 258034 33554482 1 0 1536742813 0 0 "xyz" -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 "lnx64" "" "no-xyz" "/home/xyz/junk" "" "/home/xyz/123a" "cmd.err" "/home/xyz" "1536742813.84" 0 "" "" "sleep 10" "default" 2048 0 -1 "" ""
"JOB_START" "1" 1536742819 86 4 0 0 1.0 1 "no-xyz" "" "" 0 0 ""
"JOB_START_ACCEPT" "1" 1536742819 86 6702 6702 0 0
"JOB_EXECUTE" "1" 1536742820 86 258034 6702 "/home/xyz/junk" "/home/xyz" "xyz" 6702 0
"JOB_STATUS" "1" 1536742840 86 64 0 0 0.0000 1536742840 0 0 1996 0
"JOB_START_ACCEPT" "1" 1536742819 24 6702 6702 0 0
"JOB_EXECUTE" "1" 1536742820 14 258034 6702 "/home/xyz/junk" "/home/xyz" "xyz" 6702 0
"JOB_STATUS" "1" 1536742840 84 64 0 0 0.0000 1536742840 0 0 1996 0
</code></pre>
<p><strong>Bit more details:</strong></p>
<p>Here a paricular job goes through different stages (JOB_NEW , JOB_START, JOB_START_ACCEPT , JOB_EXECUTE , JOB_STATUS). Now I want to find all the lines for a paricluar job id.
For example if I want to find job with job id "84", it should show the following output:</p>
<pre><code>"JOB_NEW" "1" 1536742813 84 258034 33554482 1 0 1536742813 0 0 "xyz" -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 "lnx64" "" "no-xyz" "/home/xyz/junk" "" "/home/xyz/123a" "cmd.err" "/home/xyz" "1536742813.84" 0 "" "" "sleep 10" "default" 2048 0 -1 "" ""
"JOB_START" "1" 1536742819 84 4 0 0 1.0 1 "no-xyz" "" "" 0 0 ""
"JOB_START_ACCEPT" "1" 1536742819 84 6702 6702 0 0
"JOB_EXECUTE" "1" 1536742820 84 258034 6702 "/home/xyz/junk" "/home/xyz" "xyz" 6702 0
</code></pre>
<p>One key point is here that job id appears at column 3 (starting count from 0).</p>
<p><strong>Brief context:</strong> We have a in-house tool which is used to run the Jobs or say run the batch process and records the every run with a Job ID with some JOB details as defined above, so in a nutshell it contains the complete chronology of a JOb when it started or executed which is been captured run in time in a form of <code>event</code> file, However the processing can be happen at given point in time by a user to see the status of his JOB with job id. </p>
| [] | [
{
"body": "<h2>General practices</h2>\n\n<p>You have some superfluous <strong>imports</strong> (e.g. <code>numpy</code>) and some duplicate imports (e.g. <code>sys</code>). To help avoid duplication, I suggest that you put the imports in alphabetical order. Also, <a href=\"https://www.python.org/dev/peps/pep-... | {
"AcceptedAnswerId": "203724",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T09:27:44.157",
"Id": "203661",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"parsing",
"logging"
],
"Title": "Processing lines in an event log to trace the status of a job"
} | 203661 |
<p>Tried to make a binary search algorithm, how did I do?</p>
<pre><code>def homogeneous_type(list1):
i_list = iter(list1)
listtype = type(next(i_list))
return True if all(isinstance(x, listtype) for x in i_list) else False
def binSearch(list1, value):
if not list1:
raise ValueError("list is empty")
if not homogeneous_type(list1):
raise ValueError("list must be one type")
left = 0
right = len(list1) - 1
list1 = sorted(list1)
while left <= right:
midIndex, mod = divmod(left + right, 2)
midIndex = midIndex + 1 if mod else midIndex
if list1[midIndex] == value:
return midIndex
elif list1[midIndex] < value:
left = midIndex + 1
elif list1[midIndex] > value:
right = midIndex - 1
raise ValueError("value not in List")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T11:14:31.240",
"Id": "392629",
"Score": "1",
"body": "Is the `homogenous_type` taken from https://stackoverflow.com/a/13252348/1190388 ? If so, give credits as such!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate"... | [
{
"body": "<ol>\n<li><p>There are no docstrings. What do <code>homogeneous_type</code> and <code>binSearch</code> do?</p></li>\n<li><p>In Python we rarely need to insist that lists be homogeneous. It often makes sense to have heterogeneous lists, provided that all elements support the required operations, for e... | {
"AcceptedAnswerId": "203672",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T10:28:05.930",
"Id": "203669",
"Score": "0",
"Tags": [
"python",
"beginner",
"binary-search"
],
"Title": "Binary Search Python"
} | 203669 |
<p>Is there any better and compact way to write this code:</p>
<pre><code> String output = "NAME OS ACTIVE\n" +
"---- -- ------\n" +
"ABCD Windows Yes\n" +
"EFGH Windows Yes\n" +
"1234 Windows No\n" +
"5678 Windows Yes\n" +
"cv Windows Yes";
Pattern pattern = Pattern.compile(String.format(SEARCH_PATTERN, "ABCD"), Pattern.MULTILINE);
Matcher matcher = pattern.matcher(output);
if (!matcher.find()) {
throw new ExceptionA();
}
pattern = Pattern.compile(String.format(SEARCH_PATTERN, "1234"), Pattern.MULTILINE);
matcher = pattern.matcher(output);
if (!matcher.find()) {
throw new ExceptionB();
}
</code></pre>
<p>String.matches() doesn't work well on multiline code, so using Pattern is the only option.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T11:44:47.553",
"Id": "392642",
"Score": "2",
"body": "What's it used for?"
}
] | [
{
"body": "<p>In fact you have keys:</p>\n\n<pre><code>String[] keys = { \"ABCD\", \"EFGH\", \"1234\", ... };\n</code></pre>\n\n<p>And you want to throw an exception when one of them is <em>not</em> found.\nThat is hard in regex. Easier would be to form <code>\"(ABCD|EFGH|1234|...)\"</code> and check having han... | {
"AcceptedAnswerId": "203676",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T11:34:58.540",
"Id": "203673",
"Score": "-1",
"Tags": [
"java",
"regex"
],
"Title": "Java Pattern search with variable string in pattern"
} | 203673 |
<p>I'm making an audio frequency trainer as a learning exercise. It could be useful for audio technicians who need to recognize audio frequencies (eg. when ringing out feedback during a live concert or soundcheck).</p>
<p>A few days ago <a href="https://codereview.stackexchange.com/questions/203209/random-tone-generator-using-web-audio-api">I posted the humble beginnings</a>. I got very useful feedback and went further. <a href="http://jsfiddle.net/MaxVMH/Lbr8okj3/4/" rel="nofollow noreferrer">Here is a working example on JSFiddle</a> & <a href="https://github.com/MaxVMH/frequency-trainer/tree/v.0.0.4-alpha" rel="nofollow noreferrer">here is the full code on GitHub</a>. In case anyone prefers the devtools in their own browser, here is a <a href="http://www.frequencytrainer.com" rel="nofollow noreferrer">working example online</a>.</p>
<p>Before I continue adding more functions, I would like to know what you guys think of this so far. Any feedback is welcome!</p>
<pre class="lang-js prettyprint-override"><code>let toneContext = null;
let toneGenerator = null;
let toneAmplifier = null;
function startFrequencyTrainer(difficultyMode, previousFrequency) {
let frequencies = null;
let frequency = null;
// Create objects
toneContext = new(window.AudioContext || window.webkitAudioContext)();
toneAmplifier = toneContext.createGain();
// Pick a frequency
frequencies = getFrequencies(difficultyMode);
frequency = getNewFrequency(frequencies, previousFrequency);
return {
frequencies,
frequency
};
}
function stopFrequencyTrainer() {
toneContext.close();
}
function startToneGenerator(frequency, volumeControl, startTimer, stopTimer) {
// Create and configure the oscillator
toneGenerator = toneContext.createOscillator();
toneGenerator.type = 'sine'; // could be sine, square, sawtooth or triangle
toneGenerator.frequency.value = frequency;
// Connect toneGenerator -> toneAmplifier -> output
toneGenerator.connect(toneAmplifier);
toneAmplifier.connect(toneContext.destination);
// Set the gain volume
toneAmplifier.gain.value = volumeControl.value / 100;
// Fire up the toneGenerator
toneGenerator.start(toneContext.currentTime + startTimer);
toneGenerator.stop(toneContext.currentTime + startTimer + stopTimer);
}
function stopToneGenerator() {
if (toneGenerator) {
toneGenerator.disconnect();
}
}
function changeVolume(volumeControl) {
toneAmplifier.gain.value = volumeControl.value / 100;
}
function getFrequencies(difficultyMode) {
let frequencies = null;
if (difficultyMode === 'easy') {
frequencies = ["250", "800", "2500", "8000"];
} else if (difficultyMode === 'normal') {
frequencies = ["100", "200", "400", "800", "1600", "3150", "6300", "12500"];
} else if (difficultyMode === 'hard') {
frequencies = ["80", "125", "160", "250", "315", "500", "630", "1000", "1250", "2000", "2500", "4000", "5000", "8000", "10000", "16000"];
} else if (difficultyMode === 'pro') {
frequencies = ["20", "25", "31.5", "40", "50", "63", "80", "100", "125", "160", "200", "250", "315", "400", "500", "630", "800", "1000", "1250", "1600", "2000", "2500", "3150", "4000", "5000", "6300", "8000", "10000", "12500", "16000", "20000"];
}
return frequencies;
}
function getNewFrequency(frequencies, previousFrequency) {
let newFrequency = null;
newFrequency = frequencies[Math.floor(Math.random() * frequencies.length)];
// Avoid getting the same frequency twice in a row
while (newFrequency === previousFrequency) {
newFrequency = frequencies[Math.floor(Math.random() * frequencies.length)];
}
return newFrequency;
}
function frequencyFormatter(frequency) {
let frequencyFormatted = null;
if (frequency > 999) {
frequencyFormatted = frequency / 1000 + ' k';
} else {
frequencyFormatted = frequency + ' ';
}
return frequencyFormatted;
}
</code></pre>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:900" />
</head>
<body>
<div class="body">
<div class="title">
<h1>Frequency Trainer</h1>
</div>
<div class="controls">
<br />
<button type="button" id="start-button" class="control-button">Start</button>
<button type="button" id="stop-button" class="control-button">Stop</button>
<button type="button" id="next-button" class="control-button">Next</button><br />
<br />
Volume:<br />
<input type="range" id="volume-control" class="volume-control" min="0" max="20" value="2" step="0.1" /><br />
<br />
<button type="button" id="difficulty-easy" class="difficulty-button" data-difficulty="easy">Easy</button>
<button type="button" id="difficulty-normal" class="difficulty-button" data-difficulty="normal">Normal</button>
<button type="button" id="difficulty-hard" class="difficulty-button" data-difficulty="hard">Hard</button>
<button type="button" id="difficulty-pro" class="difficulty-button" data-difficulty="pro">Pro</button><br />
<br />
</div>
<div class="grid">
</div>
</div>
<script>
(function () {
let difficultyMode = 'easy'; // default difficulty mode
let frequencyTrainer = startFrequencyTrainer(difficultyMode, null);
let frequency = frequencyTrainer.frequency;
let frequencyContainers = null;
// Control buttons
let startButton = document.getElementById('start-button');
startButton.onclick = function () {
stopToneGenerator();
startToneGenerator(frequency, volumeControl, 0, 3);
};
let stopButton = document.getElementById('stop-button');
stopButton.onclick = function () {
stopToneGenerator();
};
let nextButton = document.getElementById('next-button');
nextButton.onclick = function () {
stopToneGenerator();
stopFrequencyTrainer();
frequency = startFrequencyTrainer(difficultyMode, frequency).frequency;
startToneGenerator(frequency, volumeControl, 0.05, 3);
};
let volumeControl = document.getElementById('volume-control');
volumeControl.oninput = function () {
changeVolume(volumeControl);
};
function fillFrequencyGrid(frequencies) {
let frequencyFormatted = null;
let frequencyGrid = document.getElementsByClassName('grid')[0];
frequencyGrid.innerHTML = '';
frequencies.forEach(function (frequency) {
frequencyFormatted = frequencyFormatter(frequency);
frequencyGrid.insertAdjacentHTML('beforeend', '<div class="frequency-container" data-frequency="' + frequency + '">' + frequencyFormatted + 'Hz</div>');
});
}
function makeFrequencyGridInteractive() {
frequencyContainers = document.getElementsByClassName('frequency-container');
Array.prototype.forEach.call(frequencyContainers, function (frequencyContainer) {
frequencyContainer.onclick = function () {
let frequencyChosen = frequencyContainer.getAttribute('data-frequency');
let frequencyChosenFormatted = frequencyFormatter(frequencyChosen);
stopToneGenerator();
if (frequencyChosen === frequency) {
if (window.confirm(frequencyChosenFormatted + 'Hz is correct!\nLet\'s try another one!')) {
stopFrequencyTrainer();
frequency = startFrequencyTrainer(difficultyMode, frequency).frequency;
startToneGenerator(frequency, volumeControl, 0.05, 3);
}
} else {
window.alert(frequencyChosenFormatted + 'Hz is not correct.\nPlease try again.');
startToneGenerator(frequency, volumeControl, 0.05, 3);
}
};
});
}
// Generate frequency grid
fillFrequencyGrid(frequencyTrainer.frequencies);
makeFrequencyGridInteractive();
// Difficulty buttons
let difficultyButtons = document.getElementsByClassName('difficulty-button');
Array.prototype.forEach.call(difficultyButtons, function (difficultyButton) {
difficultyButton.onclick = function () {
stopToneGenerator();
stopFrequencyTrainer();
difficultyMode = difficultyButton.getAttribute('data-difficulty');
frequencyTrainer = startFrequencyTrainer(difficultyMode, frequency);
frequency = frequencyTrainer.frequency;
fillFrequencyGrid(frequencyTrainer.frequencies);
makeFrequencyGridInteractive();
};
});
}());
</script>
</body>
</html>
</code></pre>
| [] | [
{
"body": "<h1>General Feedback</h1>\n\n<p>This looks like a neat little program. I admit I hadn't explored the audio APIs before reading <a href=\"https://codereview.stackexchange.com/q/203209/120114\">your first post</a> and as a musician I enjoy seeing technology connect audio and visual elements. The colors... | {
"AcceptedAnswerId": "203936",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T13:34:22.910",
"Id": "203680",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"html5",
"audio"
],
"Title": "Audio frequency trainer / tester using Web Audio API"
} | 203680 |
<p>I have been programming about 4 months now and I am looking some way to improve my code. Currently I am using a book "JAVA an introduction to problem solving and programming" to learn programming. I think I understand basics of loops and <code>if</code> statements.</p>
<p>After couple of projects in this book, I feel like I am only using what I know and not trying to use new things to improve my code. I hope you guys can critique my code and help me improve.</p>
<p>My questions are...</p>
<ol>
<li>How is the structure?</li>
<li>What other methods can I use to improve this program?</li>
<li>Any other criticism and advice you wish to tell me.</li>
</ol>
<p><img src="https://i.stack.imgur.com/LSMG9.jpg" alt="Picture of the problem."></p>
<blockquote>
<p>Suppose we can buy a chocolate bar from the vending machine for $1
each. Inside every chocolate bar is a coupon. We can redeem six coupons
for one chocolate bar from the machine. This means that once you have
started buying chocolate bars from the machine, you always have some
coupons. We would like to know how many chocolate bars can be eaten if
we start with <em>N</em> dollars and always redeem coupons if we have enough for
an additional chocolate bar. </p>
<p>For example, with 6 dollars we could consume 7 chocolate bars after
purchasing 6 bars giving us 6 coupons and then redeeming the 6 coupons
for one bar. This would leave us with one extra coupon. For 11 dollars, we
could have consumed 13 chocolate bars and still have one coupon left.
For 12 dollars, we could have consumed 14 chocolate bars and have two
coupons left. </p>
<p>Write a program that inputs a value for N and outputs how many
chocolate bars we can eat and how many coupons we would have left
over. Use a loop that continues to redeem coupons as long as there are
enough to get at least one chocolate bar. </p>
</blockquote>
<pre><code>import java.util.Scanner;
public class chap4num9 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("How much money do you have?");
int userMoney = userInput.nextInt();
int chocoBars = 0;
int userCoupon = 0;
chocoBars =+ userMoney;
if (userMoney >= 6) {
chocoBars = chocoBars + (userMoney / 6);
userCoupon = userMoney / 6;
}
while (userCoupon >= 6) {
chocoBars = chocoBars + 1;
userCoupon = userCoupon - 6;
}
System.out.println("You will have total of " + chocoBars + " bars and " + userCoupon + " coupons left.");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T14:59:44.857",
"Id": "392659",
"Score": "3",
"body": "Please include a transcript of the problem statement instead of a photo."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T15:21:43.833",
"Id": ... | [
{
"body": "<p><code>chap4num9</code> is not a proper Java class name. Java class names begin with a capital letter and each word starts with an uppercase letter. It should be <code>Chap4Num9</code>.</p>\n\n<p>Always close <code>Closeable</code> resources like <code>Scanner</code>. Prefer the use of a <code>try-... | {
"AcceptedAnswerId": "203716",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T14:57:34.693",
"Id": "203684",
"Score": "-1",
"Tags": [
"java"
],
"Title": "Calculating total number of bars"
} | 203684 |
<p>I have submitted the following bit of script as the answer to one of the tasks I was set by a recruiter. My submission has already been made and cannot be altered. However, I am keen to ask how you would improve the solution.</p>
<blockquote>
<h3>Task:</h3>
<p>Using Javascript <strong>and no library or odd ons</strong>, create a script that can take 2 HTML Hex colour strings and return the average (mean) colour, it must show use of ES5 or ES6 (EcmaScript 5 or 6)</p>
</blockquote>
<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>var arrColours = new funColours();
function funColours (){
this.colours = [{
c1:{r:0, g:0, b:0},
c2:{r:0, g:0, b:0},
c3:{r:0, g:0, b:0}
}];
}
function funUpdateTxtColour(intFormElNo){
let elHexColour = document.querySelector("#elFrmColourSelector" + intFormElNo);
let elHexTxt = document.querySelector("#elHexCol" + intFormElNo);
if (typeof(elHexColour) == "undefined" || typeof(elHexTxt) == "undefined" ){
funErrorHandler("Element not detected, please check HTML or JavaScript calls to funUpdateColour", "elHexCol" + intFormElNo + " and elFrmColourSelector" + intFormElNo);
return;
}
elHexTxt.value = elHexColour.value;
let strOutputNode = ("Updated colour: " + intFormElNo + " with the value " + elHexTxt.value + " and applied to both form elements");
funCalculateMeanColour("elAvgColourTxt");
}
function funUpdateColourSelector(intFormElNo){
let strElHexColour = document.querySelector("#elHexCol" + intFormElNo);
let elColourSelector = document.querySelector("#elFrmColourSelector" + intFormElNo);
if (strElHexColour.length != 7 ){
alert("HTML Hex colour codes are 7 characters in length and start with a # symbol");
let intHashCheck = strElHexColour.value.indexOf("#");
if (intHashCheck != 0 ) {
if (strElHexColour.value.length == 6){
funErrorHandler("User inputted a colour code without the # symbol, prefixing entry.", "funUpdateColourSelector");
strElHexColour.value = "#" + strElHexColour.value;
}else{
funErrorHandler("User inputted a colour code without the # symbol.", "funUpdateColourSelector");
return;
}
}
strElHexColour.focus();
}
elColourSelector.value = strElHexColour.value;
funCalculateMeanColour();
return;
}
function funCalculateMeanColour(elMeanColour){
let strHexColour1 = document.querySelector("#elHexCol1").value;
let strHexColour2 = document.querySelector("#elHexCol2").value;
let elColourBox = document.querySelector("#elAvgColour").style;
let elAvgColourLabel = document.querySelector("#elAvgColourTxt");
arrColours.colours[0].c1.r = funHexToDec(strHexColour1, 1,3);
arrColours.colours[0].c1.g = funHexToDec(strHexColour1, 3,5);
arrColours.colours[0].c1.b = funHexToDec(strHexColour1, 5,7);
arrColours.colours[0].c2.r = funHexToDec(strHexColour2, 1,3);
arrColours.colours[0].c2.g = funHexToDec(strHexColour2, 3,5);
arrColours.colours[0].c2.b = funHexToDec(strHexColour2, 5,7);
arrColours.colours[0].c3.r = funReturnHEXAverage(arrColours.colours[0].c1.r, arrColours.colours[0].c2.r);
arrColours.colours[0].c3.g = funReturnHEXAverage(arrColours.colours[0].c1.g, arrColours.colours[0].c2.g);
arrColours.colours[0].c3.b = funReturnHEXAverage(arrColours.colours[0].c1.b, arrColours.colours[0].c2.b);
let strHex = "#" + arrColours.colours[0].c3.r + arrColours.colours[0].c3.g + arrColours.colours[0].c3.b;
elColourBox.background = strHex;
elAvgColourLabel.innerHTML = strHex;
}
function funHexToDec(strHexCode, intStart, intEnd){
return parseInt(strHexCode.substring(intStart,intEnd), 16);
}
function funReturnHEXAverage(intValue1, intValue2){
intAvg = Math.ceil((intValue1 + intValue2) / 2);
return intAvg.toString(16);
}
function funErrorHandler(errString, elName){
console.log("Error:");
console.log(errString);
console.log("Element: " + elName);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Task 1 */
div#frmColorContainer{
padding: 10px;
border-style: inset;
border-width: 1px;
border-color: #C0C0C0;
background: silver;
border-radius: 7px;
width: 300px;
height: 84px;
font-family: arial;
}
div#elAvgColour{
position: absolute;
left: 340px;
top: 10px;
border: 2px solid grey;
background: #808080;
height: 100px;
width: 100px;
}
label#elAvgColourTxt{
position: relative;
top: 6px;
}
label#elAvgColourTxt::before{
content: 'Average Colour: ';
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!HTML>
<head>
<title>Task 1: VueJS Role - Candidate: xxx xxxx</title>
<link href="css/css.css" rel="stylesheet">
<script src="js/task1.js"></script>
</head>
<body>
<form id="frmEls" method="get">
<div id="frmColorContainer">
<label>Colours:</label>
<label>HEX:</label><br>
<label>Colour 1:</label><input type="color" id="elFrmColourSelector1" value="#000000" title = "Colour 1" onchange="funUpdateTxtColour(1)">&nbsp;<input type="text" id="elHexCol1" value="#000000" onchange="funUpdateColourSelector(1)" maxlength=7><br>
<label>Colour 2:</label><input type="color" id="elFrmColourSelector2" value="#FFFFFF" title="Colour 2" onchange="funUpdateTxtColour(2)">&nbsp;<input type="text" id="elHexCol2" value="#FFFFFF" onchange="funUpdateColourSelector(2)" maxlength=7>
<label id="elAvgColourTxt">#808080</span></label>
</div>
</form>
<div id="elAvgColour">
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>First of all I would define a function that takes two valid HTML color strings and returns a valid HTML color string that represents the average of the two.</p>\n\n<p>With this approach you could avoid polluting your \"color library code\" with calls to host objects, which helps for better code re... | {
"AcceptedAnswerId": "203695",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T15:36:01.190",
"Id": "203687",
"Score": "5",
"Tags": [
"javascript",
"interview-questions",
"ecmascript-6"
],
"Title": "Average of two hex colour values"
} | 203687 |
<p>I'm quite new to the language and I just started using async/await. I've written this function for an API that I'm developing. It checks what is sent by the user, specially the status that he wants to set. The function will just update the application if it gets refused but, in case it gets accepted, it will also create an allocation based on the other fields that the user added.</p>
<pre><code>const application_update = async (request, response) => {
try {
const { id } = request.params;
if (!ObjectId.isValid(id)) throw 'invalid objectid';
const { status, garden, start_date, end_date } = request.body;
if (_.isEmpty(status) || !['Aceite', 'Recusado'].includes(status)) throw 'status empty or invalid';
const { user } = await Application.findById(id);
if (!user) throw 'invalid application';
if (status == 'Aceite') {
const now = moment().format();
const a = await Allocation
.findOne({ $or: [{ garden, start_date: { $lt: now }, end_date: { $gt: now } },
{ user, start_date: { $lt: now }, end_date: { $gt: now } }] });
if (a) throw 'invalid request';
const body = { user, garden, start_date, end_date };
const allocation = new Allocation(body);
const all = await allocation.save();
if (!all) throw 'error creating the allocation document';
}
const app = await Application.findByIdAndUpdate(id, { status }, { new: true, runValidators: true });
if (!app) throw 'error updating the application document';
response.status(200).send(app);
} catch (error) {
response.status(400).send({ error });
}
};
</code></pre>
<p>The code doesn't include but Mongoose verifications are in place so I can control if he doesn't fill the fields used for the allocation.</p>
<p>What could be improved? I feel like I'm using way too many <code>if</code>s but I believe they're needed to make sure all the fields exists and to retrieve the response as soon as possible if any of them fail.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T16:20:19.740",
"Id": "203688",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"async-await",
"mongodb",
"mongoose"
],
"Title": "Async API Function with Mongoose"
} | 203688 |
<p>I am just wondering if I need to refactor this code into smaller functions, or if it is OK as it is. I know that code should be as clean as possible, but I don't see a need to declare a new function every time I have more than 5 lines of code. Anyways please tell me what you think.</p>
<p>The code itself is used for file handling. It allows a user to create, append, read, or delete files. This is all based on user input.</p>
<pre><code>def option_two():
#####################################################################
# Option 2, File Creation/Editing: #
# Asks the user what they would like to do #
# They can view, append, write, or delete a file #
#####################################################################
path_exists = bool
try:
USER_INPUT = int(input("""
What would you like to do?\n
1)Read a file
2)Append to an existing file
3)Write to a new file
4)Delete a file
5)Go back/n
>>> """))
if USER_INPUT == 1:
#View a file
user_message(1)
USER_INPUT = input("Is this file located on the desktop? y/n")
if USER_INPUT == "y":
USER_INPUT = input("What is the name of the file?")
path_exists = check_path("//home//alpha//Desktop//{0}".format(USER_INPUT), path_exists)
if path_exists:
open_file("//home//alpha//Desktop//{0}".format(USER_INPUT))
else:
option_two()
elif USER_INPUT == "n":
USER_INPUT = input("Enter the full path for the file")
path_exists = check_path(USER_INPUT, path_exists)
if path_exists:
open_file(USER_INPUT)
else:
option_two()
else:
print("Enter y or n only")
option_two()
return
elif USER_INPUT == 2:
#append to a file
user_message(2)
USER_INPUT = input("Is this file located on the desktop? y/n")
if USER_INPUT == "y":
USER_INPUT = input("What is the name of the file?")
path_exists = check_path("//home//alpha//Desktop//{0}".format(USER_INPUT), path_exists)
if path_exists:
append_file("//home//alpha//Desktop//{0}".format(USER_INPUT))
else:
option_two()
elif USER_INPUT == "n":
USER_INPUT = input("Enter the full path for the file")
if path_exists:
append_file(USER_INPUT)
else:
option_two()
else:
print("Enter a y or n only")
option_two()
return
elif USER_INPUT == 3:
#Write a new file
user_message(3)
USER_INPUT = input("Is this file located on the desktop? y/n")
if USER_INPUT == "y":
USER_INPUT = input("What is the name of the file?")
write_file("//home//alpha//Desktop//{0}".format(USER_INPUT))
elif USER_INPUT == "n":
USER_INPUT = input("Enter the full path for the file")
write_file(USER_INPUT)
else:
print("Enter a y or n only")
option_two()
return
elif USER_INPUT == 4:
#Delete a file
user_message(4)
USER_INPUT = input("Is this file located on the desktop? y/n")
if USER_INPUT == "y":
USER_INPUT = input("What is the name of the file?")
delete_path("//home//alpha//Desktop//{0}".format(USER_INPUT), path_exists)
elif USER_INPUT == "n":
USER_INPUT = input("Enter the full path for the file")
delete_path(USER_INPUT, path_exists)
else:
print("Enter a y or n only")
option_two()
return
elif USER_INPUT == 5:
user_message(5)
print("Moving back to main")
return
except(ValueError):
print("Invalid input, try again\n\n")
option_two()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T17:48:42.473",
"Id": "392680",
"Score": "0",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what your code does](//coderev... | [
{
"body": "<p>In my opinion this can be greatly simplified. First, there is no need for this to be a recursive function (which are seldom the best choice in Python due to the maximum recursion depth). Just make it an infinite loop.</p>\n\n<p>Second, all of your options are almost the same. You ask if the file i... | {
"AcceptedAnswerId": "203697",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T17:43:50.240",
"Id": "203693",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"file"
],
"Title": "View, append, write, or delete a file"
} | 203693 |
<p>I am trying out the following former Google interview question.</p>
<blockquote>
<p>The Challenge Given a string S and a set of words D, find the longest
word in D that is a subsequence of S.</p>
<p>Word W is a subsequence of S if some number of characters, possibly
zero, can be deleted from S to form W, without reordering the
remaining characters.</p>
<p>Note: D can appear in any format (list, hash table, prefix tree, etc.</p>
<p>For example, given the input of S = "abppplee" and D = {"able", "ale",
"apple", "bale", "kangaroo"} the correct output would be "apple"</p>
<p>The words "able" and "ale" are both subsequences of S, but they are
shorter than "apple". The word "bale" is not a subsequence of S
because even though S has all the right letters, they are not in the
right order. The word "kangaroo" is the longest word in D, but it
isn't a subsequence of S. Learning objectives This question gives you
the chance to practice with algorithms and data structures. It’s also
a good example of why careful analysis for Big-O performance is often
worthwhile, as is careful exploration of common and worst-case input
conditions</p>
</blockquote>
<p>My approach uses a greedy algorithm.</p>
<ol>
<li><p>Sort D in descending order(longest word first)</p></li>
<li><p>Find the index of first character in a word</p></li>
<li><p>Scan S from <code>indexOfFirstCharacter</code> to find other characters in the word</p></li>
<li><p>If we reach to the end of string and there are still characters remaining to be seen in a word then the word is not found</p></li>
<li><p>Repeat 2-4 until we find a word</p></li>
</ol>
<pre><code>from collections import deque
D = ["able","ale", "apple", "bale", "kangaroo"]
"""
TC : DlogD
"""
if len(D) > 1:
D.sort(key=len,reverse=True)
S = "abppplee"
s_dict_first = {}
"""
TC : O(S)
"""
for i,s in enumerate(S):
if s not in s_dict_first: s_dict_first[s] = i
"""
TC : O(1)
"""
#return first index of char
def getindex(char):
if char in s_dict_first:
return s_dict_first[char]
return -1
"""
TC : O(w + w +S) = O(w + s)
"""
def isSubstringPresent(startIndex,word):
#word is too big to be found in S
if len(word) - 2 > len(S) - 1 - startIndex:
return False
remaining_chars = list(word[1:])
char_queue = deque()
for char in remaining_chars:
char_queue.append(char)
for i in range(startIndex,len(S)):
if len(char_queue) == 0:return True
if S[i] == char_queue[0]:
char_queue.popleft()
return len(char_queue) == 0
"""
TC : O(DlogD + D(w + s))
"""
for word in D:
first_char = word[0]
indexStart = getindex(first_char) + 1
if indexStart == 0:continue
if isSubstringPresent(indexStart,word):
print(word)
break;
</code></pre>
<p>I am open to suggestion in improving the code / any bug in my time/space complexity analysis or any other useful comments.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T20:19:19.833",
"Id": "392696",
"Score": "4",
"body": "If I set `D = ['abcd', 'bcd']` and `S = 'abcd'` then this code prints `bcd`. But the problem says that it should print the *longest* word that is a substring of the target, so it... | [
{
"body": "<p>The code can be made quite a bit more readable by moving parts of the logic into a separate class. Also, sorting the candidates by length is not helpful, even harmful in certain situations. If the shortest candidate word is the only valid subsequence, you still need to test all others. The only th... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T19:12:07.663",
"Id": "203696",
"Score": "4",
"Tags": [
"python",
"algorithm",
"strings"
],
"Title": "Longest word in dictionary that is a subsequence of a given string"
} | 203696 |
<p>I have a <code>SELECT</code> query I'm executing which has a <code>MAX()</code> column and a <code>GROUP BY</code> clause, and in addition to the results of this query that I need to return to the client, I also need to return the total count of all results as well.</p>
<p>Essentially my query is this:</p>
<pre><code>SELECT id, col1, col2, MAX(col3) as col3
FROM tbl
GROUP BY col1, col2
</code></pre>
<p>It'll usually have a <code>WHERE</code> clause too.</p>
<p>When returning this data to the client, I also specify <code>LIMIT</code> and <code>OFFSET</code> clauses to limit the number of results being retrieved and displayed on the UI at one time. For a good UX, I also return and display the total number of results that the above <code>SELECT</code> query would produce if it didn't have the <code>LIMIT</code> and <code>OFFSET</code> clauses, so that the UI can display e.g. "41-60 of 6500 results".</p>
<p>Currently, I use a <code>WITH</code> temporary table to get what I want:</p>
<pre><code>WITH temp AS (
SELECT id, col1, col2, MAX(col3) as col3
FROM tbl
GROUP BY col1, col2
)
SELECT COUNT(*) FROM temp
</code></pre>
<p>But I'm concerned about the efficiency of this. The sans-<code>LIMIT</code>-and-<code>OFFSET</code> query could return hundreds of thousands of rows, so I'm thinking that the <code>WITH</code> approach to getting the total count isn't the best way to do this.</p>
<p>Is there a more efficient way, which I'm not thinking of? Either a more efficient way to get the <code>COUNT</code> I need or some thoughts on reusing a previous <code>COUNT</code> value?</p>
<hr />
<h3>Example data</h3>
<p>Assume this is the data in my table:</p>
<pre><code>id col1 col2 col3
______________________
1 5 8 30
2 5 8 33
3 5 9 40
4 6 8 30
5 6 8 31
6 6 8 32
7 6 9 39
8 7 8 33
9 7 8 32
10 8 8 34
</code></pre>
<p>So my <code>SELECT</code> query would return this (assume the client specified <code>LIMIT 4 OFFSET 0</code>):</p>
<pre><code>SELECT id, col1, col2, max(col3) as col3
FROM tbl
GROUP BY col1, col2
LIMIT 4
OFFSET 0;
id col1 col2 col3
______________________
2 5 8 33
3 5 9 40
6 6 8 32
7 6 9 39
</code></pre>
<p>And then I'd use that query <em>without</em> the <code>LIMIT</code> and <code>OFFSET</code> clauses as a subquery and <code>SELECT COUNT(*)</code> from it, which would return <code>6</code>, and I'd return both the <code>6</code> and the results to the client. The client runs this query automatically every 10 or so seconds to keep the UI refreshed, and every time the client presses the arrows at the bottom of the table on the UI to go to the next page (i.e. specify a new <code>OFFSET</code>).</p>
<hr />
<p>The exact schema of this stripped-down case is this:</p>
<pre><code>CREATE TABLE test (id INT NOT NULL, col1 TEXT, col2 TEXT, col3 INT, PRIMARY KEY (id));
</code></pre>
<p>The only difference between my schema and this is that I also join on another table based on the <code>id</code>, and there are more than just 2 columns in the <code>GROUP BY</code> clause. I kept this example minimal because the <code>WITH</code> part is what's really important here.</p>
<hr />
<p><code>EXPLAIN</code> reports that it's indeed creating a temporary table of all 10 rows, hence my concern:</p>
<pre><code>> EXPLAIN WITH temp AS ( SELECT id, col1, col2, MAX(col3) AS col3 FROM test GROUP BY col1, col2 ) SELECT COUNT(*) FROM temp;
+------+-------------+------------+------+---------------+------+---------+------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+-------------+------------+------+---------------+------+---------+------+------+---------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 10 | |
| 2 | DERIVED | test | ALL | NULL | NULL | NULL | NULL | 10 | Using temporary; Using filesort |
+------+-------------+------------+------+---------------+------+---------+------+------+---------------------------------+
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T20:41:35.623",
"Id": "392697",
"Score": "0",
"body": "What is the real-world problem your code addresses? Please fill in the context of *why* we're doing this, and the question will be much improved."
},
{
"ContentLicense":... | [
{
"body": "<p>To determine the number of distinct groups a distinct query over the grouping columns is sufficient. No temp table is needed.</p>\n\n<p><code>SELECT COUNT(DISTINCT col1, col2) FROM tbl</code></p>\n\n<p>Depending on the data type of your grouping columns it might be beneficial to define a <a href=\... | {
"AcceptedAnswerId": "203900",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-13T20:01:20.370",
"Id": "203698",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "Calculating COUNT(*) of a MAX() + GROUP BY query"
} | 203698 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.