texts:
I've done the difficult dailyprogrammer challenge #2:

  Your mission is to create a stopwatch program. this program should have start, stop, and lap options, and it should write out to a file to be viewed later.

I wanted to see from you guys if what I did was correct. I'm looking for shortcuts or better coding practices I could have missed. This is a Windows Form Application.

namespace _Hard0002_StopWatch {
public partial class StopWatchForm : Form {
    StateEnum state;
    Stopwatch stopWatch;
    TimeSpan timeSpan;
    string elapsedTime;
    List<string> times = new List<string>();

    public StopWatchForm() {
        InitializeComponent();
        state = StateEnum.Stoped;
    }

    private void StartAndLapButton_Click(object sender, EventArgs e) {
        if (state == StateEnum.Stoped) {
            stopWatch = Stopwatch.StartNew();
            state = StateEnum.Started;
            ChangeButtonText(StartAndLapButton, "Lap");
            ChangeFormTittle("Started");
            timer1.Enabled = true;
        } else if (state == StateEnum.Started) {
            times.Add(elapsedTime);
        }
    }

    private void StopButton_Click(object sender, EventArgs e) {
        if (state == StateEnum.Started) {
            ChangeButtonText(StartAndLapButton, "Start");
            ChangeFormTittle("Stop Watch");
            stopWatch.Stop();
            times.Add(elapsedTime);
            state = StateEnum.Stoped;
            timer1.Enabled = false;
        }
    }

    private void FileButton_Click(object sender, EventArgs e) {
        saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        saveFileDialog1.FilterIndex = 2;
        saveFileDialog1.RestoreDirectory = true;

        if (times.Count > -1) {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
                string path = saveFileDialog1.FileName;
                System.IO.File.WriteAllLines(path + ".txt", times);
                times.Clear();
            }
        }
    }

    void ChangeButtonText(Button button, string text) {
        button.Text = text;
    }

    private void ChangeFormTittle(string text) {
        this.Text = text;
    }

    private void timer1_Tick(object sender, EventArgs e) {
        timeSpan = stopWatch.Elapsed;
        elapsedTime = String.Format("{0:00}:{1:00}:{2:00}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
        TimeKeeperText.Text = elapsedTime;
    }

    ///Your mission is to create a stopwatch program.
    ///this program should have start, stop, and lap options,
    ///and it should write out to a file to be viewed later.
    ///

    ///Nouns:
    ///Start
    ///lap
    ///stop
    ///file (txt)
    ///
    ///Verbs:
    ///Keeps time
    ///Writes file
    ///
}
}


texts:
I am new in haskell and for start I choosed to write simple grep. Now I want to ask if there is some simplier/shorter way to write it. For example if there is any way to avoid recursion.

parseLines :: String -> [String] -> Int -> IO ()
parseLines _ [] _ = return ()
parseLines pattern (x:xs) line = do
    when (isInfixOf pattern x) $ putStrLn $ (show line) ++ ": " ++ x
    parseLines pattern xs (line+1)

processFile :: String -> String -> IO ()
processFile _ [] = return ()
processFile pattern file = do
    exists <- doesFileExist file
    if not exists
        then putStrLn $ file ++ ": file does not exists"
        else do
            putStrLn file
            content <- readFile file
            parseLines pattern (lines content) 0

processFiles :: String -> [String] -> IO ()
processFiles _ [] = return ()
processFiles pattern (x:xs) = do
    processFile pattern x
    processFiles pattern xs

main = do
    args <- getArgs
    processFiles (head args) (tail args)


texts:
I am trying to pick up Haskell!

But I feel like my code is a bit painful to write and read.

Do you have any pointers on how to improve its readability / style?

main = do
    contents <- fmap tail . fmap lines . readFile $ "testInput"
    let input = map pair_to_tuple .(map (map read)) . map words $ contents :: [(Int,Int)]
    let result = map (uncurry waffles) $ input
    let decorated_result = ["Case #" ++ show i ++ ": " ++ show s | (i,s) <- zip [1..length result] result]
    writeFile "output.txt" $ unlines $ decorated_result

waffles row col = (row - 1)*(col - 1)

pair_to_tuple [a,b] = (a,b)

This script reads a file whose first line is a title, then every line is a couple of numbers. Then it drops the first line, and processes every pair of numbers using the function waffles, then it writes it back to an output file.


texts:
I'm having fun with Java's Stream library and lambdas.

The following code looks for persons within a list that have the same ID (which might indicate that something's wrong with the data) and prints out each group of people that share one ID.

I'm not sure if I'm doing this the most concise way, though.

This is the Person class:

public class Person {
    private String name;
    private String id;

    public Person(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public String getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", id=" + id + "]";
    }
}

This is the code I'd love to get feedback on:

// Set up test data
List<Person> people = Arrays.asList(new Person("Michael", "1"),
        new Person("Tobias", "2"), new Person("Nicole", "3"),
        new Person("Sarah", "3"));

// Group persons by their ID
Map<String, List<Person>> peopleById = people.stream().collect(
        Collectors.groupingBy(Person::getId));

// Print out groups of people that share one ID
peopleById
        .values()
        .stream()
        .filter(peopleWithSameId -> peopleWithSameId.size() > 1)
        .forEach(
                peopleWithSameId -> System.out
                        .println("People with identical IDs: "
                                + peopleWithSameId));

The code does what I want and I think it's readable but I doubt that this is the most I can get out of Java's functional features.

I wonder if you know a more elegant way to solve the problem.


texts: Webservice class with parser using generics

texts:
I'm currently building a small web stack in swift for use in my iOS apps. It consists of multiple components and I want to make it resource specific;
To that end, I have a WebService class composed of two parts; a part that handles the request logic, and a part that handles the parsing.

The catch here is that the parsing is defined by a ParserType protocol with an associated type ModelType, which needs to be specified by the adopter. It parses Any? to that ModelType:

public protocol ParserType {

    associatedtype ModelType

    func parse(_ data: Any?) throws -> ModelType
}

This is no problem on its own; a concrete parser could look like this (just forgive me the force casting here):

public class SimpleJSONParser<T: Codable>: ParserType {

    public typealias ModelType = T
    private let jsonDecoder: JSONDecoder

    public init(jsonDecoder: JSONDecoder = JSONDecoder()) {
        self.jsonDecoder = jsonDecoder
    }

    open func parse(_ data: Any?) throws -> T {
        let response = try jsonDecoder.decode(T.self, from: data as! Data)
        return response
    }
}

Now we have a concrete JSON parser that tries to parse Any? to T. That's cool, so we want to inject it into WebService, so it can be used. It looks like this:

public class WebService<ModelType, Parser: ParserType> {

    public typealias ModelType = Parser.ModelType
    public typealias WebServiceCompletion = (Result<ModelType>) -> Void

    private let endpoint: String
    private let parser: Parser
    private let transport: ServiceTransport

    public init(transport: ServiceTransport, endpoint: String, parser: Parser) {
        self.transport = transport
        self.endpoint = endpoint
        self.parser = parser
    }

    @discardableResult
    open func fetch(path: String? = nil, headers: [String: String]? = nil, parameters: [String: String]? = nil, autoResumeTask: Bool = true, completion: @escaping WebServiceCompletion) -> ServiceTransportTask {

        let endpointToUse = endpoint + (path ?? "")

        let task = transport.perform(action: .get, path: endpointToUse, parameters: parameters, headers: headers, body: nil)
                .completion { response in
                    switch response {
                    case .failure(let error):
                        completion(.failure(error))
                    case .success(let data):
                        do {
                            let result: ModelType = try self.parser.parse(data)
                            completion(.success(result))
                        } catch let error {
                            completion(.failure(error))
                        }
                    }
                }

        if autoResumeTask {
            task.resume()
        }

        return task
    }
}

The issue I have is that when I want to use this, I have to specify to the WebService that I want to use it for a type CategoryArray for example, with a parser that parses JSON to CategoryArray, i.e. JSONParser<CategoryArray>, and then also inject such a parser into the WebService:

let transport = HTTPTransport(baseURL: URL(string: baseURLString)!)
let parser = JSONParser<CategoryArray>()
let webService: WebService<CategoryArray, JSONParser<CategoryArray>> webService = WebService(transport: transport, endpoint: endPoint, parser: parser)

It feels a bit weird to me in the sense that I have to define the model type to use in both WebService and Parser, and also define the parser type.

Is my approach too generic, or can I factor out something here?


texts:
I think this code cannot be shortened much, especially because I only consider two cases. But maybe there's a language construct that I don't know that would help.

if (subControl.inverted) {
    newValue = subControl.value+(float)(1.0f/(float)subControl.decorator.ticks);
    if (newValue > 1)
        newValue = 0;
} else {
    newValue = subControl.value-(float)(1.0f/(float)subControl.decorator.ticks);
    if (newValue < 0)
        newValue = 1;
}

Some of the (floats) are gratuitous, which is irrelevant.

Edit: The code could look like this, which helps. However, I guess this is the result of reading the answers already ;)

if (subControl.inverted) {
    newValue = subControl.value+(float)(1.0f/(float)subControl.decorator.ticks);
} else {
    newValue = subControl.value-(float)(1.0f/(float)subControl.decorator.ticks);
}

if (newValue > 1)
    newValue = 0;
if (newValue < 0)
    newValue = 1;


texts:
I'm relatively new to Haskell and I'd like to get feedback on the style of my program. Specifically:

Coding Style: Can any parts be written in a more concise or more readable way?
Misuse: Are there any parts that are generally should be avoided, or any typical beginner mistakes? (Basically the do's and don't's)

The game

The program solves a puzzle that is also known as binoxxo: There is a 2n x 2n square grid that is partially filled with X and O. The goal filling each cell of the grid with an X or O such that the result satisfies three conditions:

In each column and each row, the same symbol cannot occur more than twice in a row. (I.e. OXXOXO is ok, however OXXXOO is not.)
Each row and each column have exactly n Xs and n Os.
No two rows are equal and no two columns are equal.

(An online version can be found here.)

The program

The following module consists of three parts: First we define the new type to describe the grid, with the type constructors X,O and finally E (for an empty cell). Then we have two functions: isValid checks whether all three rules hold so far, and backtrack which actually solves the puzzle. It does so by placing an X and O in the first E spot of the given puzzle checking the validity of the new grids, and if that succeeds, recursing a step deeper. This function finds all the possible solutions, but due to the lazy evaluation we can use take 1 $ backtrack myBoard to get only one and finish a little bit quicker.

module Binoxxo (isValid, backtrack, exampleBoard, Cell (..), Board) where

import Control.Applicative
import Data.List

data Cell = E | X | O -- E = empty
  deriving (Eq,Show)

type Board = [[Cell]]

exampleBoard = -- for solving: call "backtrack exampleBoard"
  [[X,X,E,E],
   [E,E,E,E],
   [O,E,E,X],
   [O,O,E,X]]

-- backtracking
backtrack :: Board -> [Board]
backtrack b
  | isFull b = [b] --board has no more empty cells
  | otherwise = nub $ concat $ map backtrack validBoards
  where
    isFull b = not $ E `elem` concat b
    newBoards = generateAllBoards b :: [Board]
    validBoards = filter isValid newBoards

    generateAllBoards :: Board -> [Board] -- adds one new X/O in the position of a E
    generateAllBoards b = concat $ map assembleBoards (prefixRowSuffix b)
      where
        prefixRowSuffix :: [a] -> [([a],a,[a])]-- [1,2,3,4] ->  [([],1,[2,3,4]), ([1],2,[3,4]), ([1,2],3,[4]), ([1,2,3],4,[])]
        prefixRowSuffix b = zip3 (inits b) b (drop 1 $ tails b)

        assembleBoards :: ([[Cell]],[Cell],[[Cell]]) -> [Board]
        assembleBoards (front,m,back) = take 2 -- we only need to place X and O in the first occurence of E, because one of them MUST be correct
          [front ++[f++[x]++b]++ back |
            (f,E,b)<-prefixRowSuffix m,x<-[X,O]]

-- validity check (implement the three rules)
isValid :: Board -> Bool
isValid b = and $
    [and . map checkNeighbours, checkDupli, and . map checkCount] -- each of these get applied to all normal and transposed board
     <*> [rows, cols]
  where
    rows = b :: Board
    cols = transpose b :: Board

    -- we cannot have three consecutive X or O
    checkNeighbours :: [Cell] -> Bool
    checkNeighbours (a:b:c:xs) =
       let this = not $ any ((&& a==b && b==c) . (c==)) [X,O]
           rest = checkNeighbours (b:c:xs)
       in this && rest
    checkNeighbours _  = True

    -- we cannot have two equal rows/columns
    checkDupli :: Board -> Bool
    checkDupli b = check $ filter (all (/=E)) b -- only check full rows for duplicates
      where check (x:xs) =
              (not $ x `elem` xs)  && check xs
            check [] = True

    -- if row is of length n, we can have at most n/2 X and O
    checkCount :: [Cell] -> Bool
    checkCount xs = notTooMany O && notTooMany X
      where
        len = length xs
        notTooMany xo = len >= 2 * length (filter (==xo) xs)


texts:
I wrote this code to list contents of an XPI file and then read the contents in it.

I was thinking of these areas of improvement:

I put the zr.open in the try because if the file does not exist it will throw exception, and if zip reader is left open it usually crashes the add-on.
I'm reusing the input stream create instance. How is it not safe? Is there an async version of this?
Should I close the input stream instance after I am all done or each time after init?
Is Cu.forceGC needed? I'm not sure I thought it might be.
My exception checking is weird; I check the .name I'm not sure if this is the recommended way

var zr = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(Ci.nsIZipReader);
Cu.import('resource://gre/modules/osfile.jsm');
Cu.import('resource://gre/modules/FileUtils.jsm');

var reusableStreamInstance = Cc['@mozilla.org/scriptableinputstream;1'].createInstance(Ci.nsIScriptableInputStream);

var pathToXpiToRead = OS.Path.join(OS.Constants.Path.profileDir, 'extensions', 'PortableTester@jetpack.xpi');
var nsiFileXpi = new FileUtils.File(pathToXpiToRead);

try {
  zr.open(nsiFileXpi); //if file dne it throws here
  var entries = zr.findEntries('*');
  while (entries.hasMore()) {
    var entryPointer = entries.getNext(); //just a string of "zip path" (this means path to file in zip, and it uses forward slashes remember)
    var entry = zr.getEntry(entryPointer); // should return true on `entry instanceof Ci.nsIZipEntry`
    if (!entry.isDirectory) {
        var inputStream = zr.getInputStream(entryPointer);
        reusableStreamInstance.init(inputStream);
        var fileContents = reusableStreamInstance.read(entry.realSize);
        console.log('contenst of file=', fileContents);
    } else {
        console.log('is directory, no stream to read');
    }
  }
} catch (ex) {
  console.warn('exception occured = ', ex);
  if (ex.name == 'NS_ERROR_FILE_NOT_FOUND') {
    Services.ww.activeWindow.alert('XPI at path does not exist!\n\nPath = ' + pathToXpiToRead);
  }
} finally {
  zr.close();
  console.log('zr closed');
  //Cu.forceGC(); //im not sure shoud i do this here?
}


texts: Generic parameter class with HasChanged functionality

texts:
I have designed a class that allows the client to set an initial value. The idea is that if later on we wish to update this value then we can use the Update method and pass in the new value. We can then use the HasChanged() method to do something with the new value if it is different than the initial value.

public class UpdatableParam<T>
{
    private readonly T m_initialValue;
    private T m_updatedValue;

    public T InitialValue
    {
        get { return m_initialValue; }
    }

    public T UpdatedValue
    {
        get { return m_updatedValue; }
    }

    public UpdatableParam(T initialValue)
    {
        m_initialValue = ObjectCopier.Clone(initialValue);
        m_updatedValue = ObjectCopier.Clone(initialValue);
    }

    public UpdatableParam(T initialValue, T updatedValue)
    {
        m_initialValue = ObjectCopier.Clone(initialValue);
        m_updatedValue = ObjectCopier.Clone(updatedValue);
    }

    public void Update(T updatedValue)
    {
        m_updatedValue = ObjectCopier.Clone(updatedValue);
    }

    public virtual bool HasChanged()
    {
        return !EqualityComparer<T>.Default.Equals(m_initialValue, m_updatedValue);
    }
}

To ensure that the values cannot be changed from outside of the class after being added I have deep copied from the values passed in, both from the constructor and the update method.

The HasChanged() method works for most types I care about and I have one overloaded version of the class for lists. The implementation is as follows:

public class UpdatableListParam<T> : UpdatableParam<List<T>>
{
    public UpdatableListParam(List<T> initialValue)
        : base(initialValue)
    {

    }

    public override bool HasChanged()
    {
        var initialValue = InitialValue;
        var updatedValue = UpdatedValue;

        if (initialValue == null && updatedValue == null) return false;
        if (initialValue == null || updatedValue == null) return true;

        return !initialValue.SequenceEqual(updatedValue);
    }
}

I understand I could use IEnumerable rather than lists but have not yet implemented that change.

Is there anything fundamentally wrong with the above code? Is there any design change I could make to improve functionality? Or better yet has someone already beat me to this and is there anything already available perhaps in a NuGet package that does the above for me?

Edit - Adding Use Case

class SomeSourceInfo
{
    private SomeSource m_someSource;
    private UpdatableParam<string> m_name;

    public SomeSourceInfo(ISomeSource someSource)
    {
         m_someSource = someSource;
    }

    public void PopulateFromSource()
    {
        // Query from a source(could be a db etc.)
        m_someSource.Refresh();
        var srcName = m_someSource.Name;
        m_name = new UpdatableParam<string>(srcName);
    }

    public void UploadToSource()
    {
        if(m_name.HasChanged())
        {
             // Upload back to source
             m_someSource.Name = m_name.UpdatedValue;
        }

        PopulateFromSource();
    }

    public void UpdateSourceName(string newName)
    {
        // Allow changing of the name through UI calls or API etc.
        m_name.Update(newName);
    }
}

This only shows one potential param but in real life we may have hundreds of real params we can update and we only want them to upload back to the source when the user tells us to through the  UploadToSource() method and therefore need to cache the values in the mean time.


texts: Calculate hat, waist, and jacket size when given age, height, and weight

texts:
Intro to Computer Science project here. Calculates the hat, waist, and jacket size of the user when given age, height, and weight. Seems to output correctly.

Here are the guidelines for the assignment.

  Write a program that asks for the user’s height, weight, and age, and
  then computes clothing sizes according to the formulas:

  Hat size = weight in pounds divided by height in inches and all multiplied by 2.9
  Jacket size (chest in inches) = height times weight divided by 288 and then adjusted by adding 1/8 of an inch for each 10 years over the age of 30.  (Note
  that the adjustment only takes place after a full 10 years.  Thus, there is no adjustment for ages 30 through 39, but 1/8 of an inch is added for age 40.)
  Waist in inches=weight divided by 5.7 and then adjusted by adding 1/10 of an inch for each 2 years over age 28.  (Note that the adjustment only takes place after a full 2 years. Thus, there is no adjustment for age 29, but 1/10 of an inch is added for age 30.)

  Use functions for each calculation. (Thus, write 3 functions.)

I did this a tad hastily so pardon any messiness.

I am required to use namespace stdas it makes it easier for the teacher to read.

#include <iostream>

using namespace std;

double hat(double,double);

double jacket(double,double,int);

double waist(double,double,int);

int main ()
{
    double height, weight;
    int age;
    char answer;

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    do
    {
        cout<< "Enter the user's height in inches: ";
        cin>>height;
        cout<< "Enter the user's' weight in pounds: ";
        cin>>weight;
        cout<< "Enter the user's' age: ";
        cin>>age;
        cout<< "\tThe user's Hat size: " << hat(weight ,height) << "\tThe user's Jacket size: "<< jacket( height, weight, age) << "\tThe user's Waist size: "<< waist( height, weight, age)<< "\n \nWould you like to continue (y/n)? ";
        cin>>answer;
    }
        while(toupper(answer) == 'Y');
        return 0;
    }

    double hat(double weight ,double height)

    {
        return ((weight/height) * 2.9);
    }

    double jacket(double height,double weight,int age)
    {
        double size;
        int j;
        if (age>=30)
        {
        if((age % 10) !=0)
        age = age-(age%10);
        j= (age-30)/10;
        size =((height * weight) / 288)+((1.0/8)*j);
        }
        else
        size =((height * weight) / 288);
        return size;
    }

    double waist(double height,double weight,int age)
    {
        double size2;
        int k;

        if(age >= 28)
        {
            if((age % 2) !=0)
            age = age-(age%2);
            k = (age-28)/2;
            size2 = (weight/(5.7))+( (1.0/10)*k);
        }
        else
        size2 = weight / (5.7);
        return size2;
    }


texts: Store, retrieve and delete settings in C# Registry

texts:
My code writes, reads, and removes program settings in the registry. I'm using Visual Studio 2019 and my target Framework is .NET Framework 4.8.
I'm looking for more elegant functions.
Is there error handling I missed in these functions?
How can I optimize the code?
I have the following functions at the moment:
public static class Settings
{

    public static void SaveSetting(string sCompanyName, string sAppName, string sSection, string sValueName, string sValue)
    {
        RegistryKey softKey = Registry.CurrentUser.OpenSubKey("Software", true);
        RegistryKey compKey = softKey.CreateSubKey(sCompanyName);
        RegistryKey appKey = compKey.CreateSubKey(sAppName);
        RegistryKey secKey = appKey.CreateSubKey(sSection);
        secKey.SetValue(sValueName, sValue);
    }

    public static string GetSetting(string sCompanyName, string sAppName, string sSection, string sValueName, string sDefault)
    {

        RegistryKey softKey = Registry.CurrentUser.OpenSubKey("Software", true);
        RegistryKey compKey = softKey.CreateSubKey(sCompanyName);
        RegistryKey appKey = compKey.CreateSubKey(sAppName);
        RegistryKey secKey = appKey.CreateSubKey(sSection);

        return (string)secKey.GetValue(sValueName, sDefault);
    }

    public static void DeleteSetting(string sCompanyName, string sAppName, string sSection, string sValueName)
    {
        RegistryKey softKey = Registry.CurrentUser.OpenSubKey("Software", true);
        RegistryKey compKey = softKey.CreateSubKey(sCompanyName);
        RegistryKey appKey = compKey.CreateSubKey(sAppName);
        RegistryKey secKey = appKey.CreateSubKey(sSection);

        if (secKey.GetValue(sValueName) != null)
        {
            secKey.DeleteValue(sValueName);
        }

    }

}


texts:
I have several 3D items in listOri. For this example:

listOri has A,B,C,D,E.

A overlaps with C.
B overlaps with D.
D overlaps with E.

I have a recursive function which accepts listOri, check if each item overlaps with each other, and generates a final listNew which has AC, BDE.

Iteration 1:
Loop through each item in listOri, generates listNew containing AC,B,D,E

Iteration 2:
Loop through AC,B,D,E in listNew, generates (new) listNew containing, AC,BD,E

Iteration 3: and so on.

Here is the snippet code which check if each 3D object in a list overlaps, and produces a new list recursively.

 Private Function SimplifyModel2(ByVal listOri As List(Of Mesh3D)) As List(Of Mesh3D)
    Dim listNew As New List(Of Mesh3D)(listOri)
    Dim indexOut, indexIn, indexInner, PercentProgressCurrent As Integer
    Dim currentMeshOutter, currentMeshInner As Mesh3D
    Dim isExitForCalled As Boolean = False

    totInnerLoops = totInnerLoops + 1   ' increment total number of inner loops

    For indexOut = 0 To (listOri.Count - 1)
        currentMeshOutter = listOri(indexOut)

        indexInner = indexOut + 1
        For indexIn = indexInner To (listOri.Count - indexInner)
            currentMeshInner = listOri(indexIn)

            If Is3DOverlap(currentMeshInner, currentMeshOutter) = True Then
                currentMeshOutter.CombineMerge(currentMeshInner)
                listNew.Remove(currentMeshInner)
                listNew.Remove(currentMeshOutter)
                listNew.Insert(0, currentMeshOutter)

                listNew = SimplifyModel2(listNew) ' recursively call the function
                isExitForCalled = True
                Exit For
            End If
        Next

        If isExitForCalled = True Then
            Exit For
        End If
    Next

    indLoopExit = indLoopExit + 1

    Return listNew
End Function

The function works well with listOri with very few items.
However, when there are thousands of 3D items in listOri, the functions takes very long time to produce the listNew.

How do I increase the speed of the recursive function?
Is there another way to write an algorithm which performs the same task above?

Let me know if you need any information.

Thank you.


texts: Naïve Bayes classifier to group questions by intent

texts:
I am trying to train a question-answer system, where I am trying to group similar questions, and identify the most apt response. The program should identify the intent/focus.

To do it, I have tagged the questions as NER so that I may know which intent it has, like PERSON or LOCATION etc. I am trying to group similar questions in a classifier, where NE tagged questions are X, and answers are Y.

I tried to write the following code. I am trying to paste the .pos file data in Pastebin. The code is running on toy-sized data thus I could not keep proper training/testing  data partitions. But it seems giving me satisfactory results.

Please suggest how I can write the code beautifully.

import nltk
import collections
import nltk.metrics
from nltk.corpus.reader import TaggedCorpusReader
from nltk.tokenize import word_tokenize
from itertools import chain
from nltk.classify import NaiveBayesClassifier as nbc
from itertools import chain

#HMM
reader = TaggedCorpusReader('.', r'.*\.pos')
f1=reader.fileids()
print f1
sents=reader.tagged_sents(fileids='Monishnew1.pos')
ls=len(sents)
print ls
train_sents=sents[:7]
test_sents=sents[7:]
class_sents=reader.sents(fileids='Monishnew1.pos')
appli_sent1=class_sents[5]
print "Sentence Is:",appli_sent1
hmm_tagger=nltk.HiddenMarkovModelTagger.train(train_sents)
test=hmm_tagger.test(test_sents)
print test
classf1=hmm_tagger.tag(appli_sent1)
print classf1
joiner1 = "/".join
classf2=map(joiner1, classf1)
print classf2
classf3=" ".join(classf2)
print classf3

#NBC
#CLASSIFYING THE ANSWER
training_data=[('Hello/GREET',
' How can I assist you'),
               ('Hi/GREET','How can I assist you'),
               ('want/NA to/NA speak/NA to/NA customer/GREET care/GREETC','How can I assist you'),
               ('issue/NA with/NA the/NA report/REPORT',
' Please tell me your exact problem'),
('want/NA to/NA see/NA my/NA test/REPORTP report/REPORT','Sure Please share the lab number'),
('know/NA my/NA report/REPORT test/REPORTC done/NA today/NAgot/NA the/NA message/NA for/NA the/NA report/REPORT generation/REPORTC but/NA unable/NA to/NA see/NA','Apologies for the inconvenience caused Please share the lab number'),
('the/NA report/REPORT 224622415/REPVW  231223456/REPVW how/REPVW to/NA check/REPVW it/NA','please share you lab number to check this'),
('thanks/CLOSEok/CLOSEthank/CLOSE you/CLOSEC When/CLOSE will/NA I/NA get/NA the/NA call/CLOSE','is there anything else I can help you with'),
('I/NA will/NA wait/NA for/NA the/NA call/CLOSE','is there anything else I can help you with'),
('when/CLOSE call/CLOSE me/NA back/NA','you will get a call in the next 12 hours Is there anything else I can help you with')]

print training_data
vocabulary = set(chain(*[word_tokenize(i[0].lower()) for i in training_data]))
feature_set = [({i:(i in word_tokenize(sentence.lower())) for i in vocabulary},tag) for sentence, tag in training_data]
train_set, test_set = feature_set[:5], feature_set[5:]
classifier = nbc.train(train_set)
refsets = collections.defaultdict(set)
testsets = collections.defaultdict(set)
for i, (feats, label) in enumerate(test_set):
    refsets[label].add(i)
    observed = classifier.classify(feats)
    testsets[observed].add(i)

test_sentence=classf3
featurized_test_sentence = {i:(i in word_tokenize(test_sentence.lower())) for i in vocabulary}
cat1=classifier.classify(featurized_test_sentence)
print "The Answer Is:",cat1


texts: Partitioning an array based on a condition in Javascript

texts:
Using the array.filter function, I can efficiently pull out all elements that do or do not meet a condition:

let large = [12, 5, 8, 130, 44].filter((x) => x > 10);
let small = [12, 5, 8, 130, 44].filter((x) => !(x > 10));

However, in the example above, I'm iterating over the array twice and performing the same test each time. Is there a simple way to generate both 'large' and 'small' in a single pass over the array? In particular, if the callback to evaluate whether an element should be kept is expensive, I'd like to avoid calling it twice.


texts:
This program should convert a file containing Mana, Hashcat or John the Ripper NTLMv1 hashes to another file containing Hashcat or John the Ripper hashes. Do you have any suggestions on how to make the code cleaner? The hash format selection code feels kinda dirty.

#!/usr/bin/env python3

# Takes a file of NTLMv1 hashes in mana format and spits out a
#  file of hashes in JtR or hashcat format.

import sys
import re

class Hash():
    pass

class HashcatHash(Hash):
    @staticmethod
    def parse(line):
        m = re.match("(.*?)::::([0-9a-f]{48}):([0-9a-f]{16})", line)
        if m:
            return {"username": m.group(1), "response": m.group(2), "challenge": m.group(3)}
        else:
            raise ValueError("Couldn't find hash in line")

    @staticmethod
    def format(d):
        return "{username}::::{response}:{challenge}".format(
            username=d["username"],
            response=d["response"],
            challenge=d["challenge"])

class JohnHash(Hash):
    @staticmethod
    def parse(line):
        m = re.match("(.*?):\$NETNTLM\$([0-9a-f]{16})\$([0-9a-f]{48})", line)
        if m:
            return {"username": m.group(1), "response": m.group(3), "challenge": m.group(2)}
        else:
            raise ValueError("Couldn't find hash in line")

    @staticmethod
    def format(d):
        return "{username}:$NETNTLM${challenge}${response}".format(
            username=d["username"],
            response=d["response"],
            challenge=d["challenge"])

class ManaHash(Hash):
    @staticmethod
    def parse(line):
        m = re.match("CHAP\|(.*?)\|([0-9a-f:]{23})\|([0-9a-f:]{71})", line)
        if m:
            return {"username": m.group(1), "response": remove_colons(m.group(3)), "challenge": remove_colons(m.group(2))}
        else:
            raise ValueError("Couldn't find hash in line")

    @staticmethod
    def format(d):
        raise NotImplementedError

def print_usage():
    print("Usage:")
    print("exportlog.py <informat> <infile> <outformat> <outfile>")

def remove_colons(hexstr):
    return ''.join(hexstr.split(':'))

if __name__ == '__main__':
    if (len(sys.argv) != 5) or (sys.argv[1] not in ['john', 'hashcat', 'mana']) or (sys.argv[3] not in ['john', 'hashcat']):
        print_usage()
        quit()
    import_format = sys.argv[1]
    export_format = sys.argv[3]
    with open(sys.argv[2], 'r') as infile, open(sys.argv[4], 'w') as outfile:
        for line in infile:
            if import_format == 'john':
                d = JohnHash.parse(line)
            elif import_format == 'hashcat':
                d = HashcatHash.parse(line)
            elif import_format == 'mana':
                d = ManaHash.parse(line)
            if export_format == 'john':
                outline = JohnHash.format(d)
            elif export_format == 'hashcat':
                outline = HashcatHash.format(d)
            outfile.write(outline + "\n")


texts: Writing multiple if tags that compare two variables

texts:
I am a beginner in C# coding, and I was trying to compare two int variables:

void CompareNumber() {
    int oneNumber;
    int secondNumber;

    if (oneNumber > secondNumber)
        {
        DoSomething();
        }

    else if (oneNumber < secondnumber)
        {
        DoSomethingElse();
        }

    else if (oneNumber == secondnumber)
         {
         DoSomethingDifferent();
         }
}

While this does work, it looks kinda messy, especially because I compare variables in this manner many times. Is there a more concise way of doing this, making it look neater? (Except for omitting the curly brackets)

Here is my actual code for a simple game that thinks of a number, and you need to guess what it said:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuessName
    {
    class Program
        {
        static void Main(string[] args)
            {
            int previousNumber = 0;
            AskNumber(previousNumber);
            }

        static void AskNumber(int previousNumber)
            {
            Console.Clear();

            int numberTyped;
            int randomNumber = new Random().Next(1, 11);

            while (previousNumber == randomNumber)
                randomNumber = new Random().Next(1, 11);

            Console.WriteLine("I am thinking of a number between 1 and 10. What do you think it is?");

            if (int.TryParse(Console.ReadLine(), out numberTyped) == true)
                CheckNumber(numberTyped, randomNumber);
            else
                InvalidNumber();
            }

        static void CheckNumber(int numberTyped, int randomNumber)
            {
            if (numberTyped < 0 || numberTyped > 10)
                {
                InvalidNumber();
                }
            else if (numberTyped > randomNumber)
                {
                Console.Clear();
                Console.WriteLine("Sorry, but your number is bigger than what I thought");
                Console.WriteLine("Try again, just type what you think:");
                }
            else if (numberTyped < randomNumber)
                {
                Console.Clear();
                Console.WriteLine("Sorry, but your number is smaller than what I thought");
                Console.WriteLine("Try again, just type what you think:");
                }
            else
                {
                Console.Clear();
                WonGame(randomNumber);
                }
            if (int.TryParse(Console.ReadLine(), out numberTyped) == true)
                CheckNumber(numberTyped, randomNumber);
            else
                InvalidNumber();
            }

        static void WonGame(int randomNumber)
            {
            Console.WriteLine("Great job, You did it!");
            Console.WriteLine("Would you like to try again? (y) or would you like to quit? (n)");

            string wantToPlay = Console.ReadLine();
            if (wantToPlay == "y")
                AskNumber(randomNumber);
            else
                Environment.Exit(0);
            }

        static void InvalidNumber()
            {
            Console.Clear();

            Console.WriteLine("Your number is invalid. Would you like to try again? (y)");
            Console.WriteLine("Or would you like to quit? (n)");

            string wantToPlay = Console.ReadLine();
            if (wantToPlay == "y")
                AskNumber(0);
            else
                Environment.Exit(0);
            }
        }
    }


texts: Program to generate Armstrong like numbers (java)

texts:
Armstrong like numbers are those which are equal to the sum of the cubes of their 1/3rd parts. For example:

  \$165033 = 16^3 + 50^3 + 33^3\$
  \$166500333 = 166^3 + 500^3 + 333^3\$

Here is my code, works fine, but I want to know how I can improve it:

Method check() checks if the number is armstrong like and generate() generates 6 digit armstrong like numbers.

class Armstronglike
{
    static boolean check(long n)
    {
        String s = Long.toString(n);
        int l = s.length();
        if(l%3 !=0 )
        {
            return false;
        }
        else
        {
            long sum =0;
            long num = n;
            long k = (long)Math.pow(10, s.length()/3);
            for(int i = 1; i<= 3; i++)
            {

                sum  = sum + (long)Math.pow((num%k), 3);
                num  = num/k;
            }
            if(sum == n)
            {
              return true;
            }
            else
            return false;
        }
    }
    static void generate() //to generate 6 digit armstrong numbers
    {
        System.out.println("6 digit armstrong numbers are: ");
        for(long i = 100000; i<1000000 ; i++)
        {
            if(check(i)== true)
            {
                System.out.println(i);
            }
        }
    }
}


texts:
This ObjectSet container adds new Objects with lowest possible unique ID. My implementation uses std::set for its sorting, but this convenience may not be required.

My two main questions are:

Is std::set generally a good and preferred solution for this problem?
In case of using std::set, can ObjectSet::minId be implemented with use of standard algorithms?

Code:

#include <iostream>
#include <set>
#include <string>

class Object
{
    std::uint32_t id_;

public:
    explicit Object(std::uint32_t id) : id_(id) {}

    std::uint32_t const& id() const
    {
        return id_;
    }

    std::string name() const
    {
        return "Object" + std::to_string(id_);
    }

    bool operator<(Object const& other) const
    {
        return id_ < other.id_;
    }
};

class ObjectSet : std::set<Object>
{
public:
    void addObject()
    {
        insert(Object(minId()));
    }

    void removeObject(std::uint32_t id)
    {
        erase(Object(id));
    }

    std::uint32_t minId() const
    {
        if(empty())
            return 1;

        for(auto it1 = begin(), it2 = it1++; it1 != end(); ++it1, ++it2)
            if(it1->id() != it2->id() + 1)
                return it2->id() + 1;

        return rbegin()->id() + 1;
    }

    using Base = std::set<Object>;

    using Base::begin;
    using Base::cbegin;
    using Base::rbegin;
    using Base::crbegin;

    using Base::end;
    using Base::cend;
    using Base::rend;
    using Base::crend;
};

int main()
{
    ObjectSet objects;
    objects.addObject();
    objects.addObject();
    objects.addObject();
    objects.removeObject(2);
    objects.addObject();

    for(auto const& object : objects)
        std::cout << object.name() << std::endl;
}


texts:
I have made a login system where the inserted_id and inserted_password are sent to the login.inc.php via the XMLHttpRequest. I'm not sure if my PHP script is secure. I need some securing advice for my script.

login.inc.php:

<?php
    session_start();
    $conn = mysqli_connect("localhost", "root", "", "users");
    $params = json_decode(file_get_contents('php://input'), true);
    $inserted_id = $params['inserted_id'];
    $inserted_password = $params['inserted_password'];

    $stmt = mysqli_stmt_init($conn);
    if (mysqli_stmt_prepare($stmt, "SELECT * FROM user WHERE account_name=? OR email=?;")) {
        mysqli_stmt_bind_param($stmt, "ss", $inserted_id, $inserted_id);
        mysqli_stmt_execute($stmt);
        $row = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
        if ($row == null) {
            echo ("DOESNT EXISTS");
        } else {
            if (password_verify($inserted_password, $row['password'])) {
                $_SESSION['user_id'] = $row['id'];
                echo("SUCCESS");
            } else {
                echo("PASSWORD_FAIL");
            }
        }
    }
?>

signup.inc.php:

<?php
    $conn = mysqli_connect("localhost", "root", "", "users");
    $params = json_decode(file_get_contents('php://input'), true);
    $inserted_first_name = $params['first_name'];
    $inserted_last_name = $params['last_name'];
    $inserted_dob = $params['dob'];
    $inserted_email = $params['email'];
    $inserted_account_name = $params['account_name'];
    $inserted_password = $params['password'];

    $stmt = mysqli_stmt_init($conn);
    if (mysqli_stmt_prepare($stmt, "SELECT * FROM user WHERE email=?;")) {
        mysqli_stmt_bind_param($stmt, "s", $inserted_email);
        mysqli_stmt_execute($stmt);
        if (mysqli_num_rows(mysqli_stmt_get_result($stmt)) > 0) {
            echo("EMAIL_TAKEN");
        } else {
            $hashed_password = password_hash($inserted_password, PASSWORD_DEFAULT);
            $created_id = rand(111111111, 999999999);
            $stmt = mysqli_stmt_init($conn);
            if (mysqli_stmt_prepare($stmt, "INSERT INTO user(id, first_name, last_name, dob, email, account_name, password) VALUES (?, ?, ?, ?, ?, ?, ?);")) {
                mysqli_stmt_bind_param($stmt, "issssss", $created_id, $inserted_first_name, $inserted_last_name, $inserted_dob, $inserted_email, $inserted_account_name, $hashed_password);
                $result = mysqli_stmt_execute($stmt);
                echo ($result ? "SUCCESS" : "FAIL");
            }
        }
        mysqli_stmt_close($stmt);
    }
?>


texts: Pythonic way to find duplicate objects in a set

texts:
I have tons of location points with several attributes like time_stamp, latitude, longitude, accuracy, velocity etc. Now I want to remove duplicate location points on these conditions:

Latitude is same
Longitude is same
Month is same
Day is same

The other attributes dont matter at all for comparison. My strategy is to modify __hash__, __eq__ and __ne__ methods to include the above conditions and feed them into set function to remove the duplicates.

item1 = Location(1510213074679, 286220203, 772454413, 1414, None, None, None, 78, None)
item2 = Location(1510213074679, 286220203, 772454413, 5, 6, 80, 226, None, None)
item3 = Location(1523620644975, 286265651, 772427842, 65, None, None, 193, 10, None)

x = set()
x.add(item1)
x.add(item2)
x.add(item3)
print(x)
{<__main__.Location at 0x7fd725559eb8>, <__main__.Location at 0x7fd725604dd8>}

Length of set is as expected i.e 2 (two elements with same attributes).

The result which I expect, can be obtained as follows

[f.data() for f in x]

Is there any other pythonic way to achieve the same result?

class Location(object):
    def __init__(self, time_stamp, latitude, longitude, accuracy, velocity,
                 heading, altitude, vertical_accuracy, activity):
        self.time_stamp = float(time_stamp) / 1000
        self.latitude = float(latitude) / 10000000
        self.longitude = float(longitude) / 10000000
        self.accuracy = accuracy
        self.velocity = velocity
        self.heading = heading
        self.altitude = altitude
        self.vertical_accuracy = vertical_accuracy
        self.activity = activity

        self.timestamp, self.year, self.month = month_aware_time_stamp(
            self.time_stamp)
        self.hash = self.hashed()

    def data(self):
        return self.__dict__

    def hashed(self):
        string = str(self.latitude) + str(self.longitude)
        return hashlib.sha3_224(string.encode()).hexdigest()

    def __hash__(self):
        string = str(self.latitude) + str(self.longitude)
        return hash(string.encode())

    def __eq__(self, other):
        """Override the default Equals behavior"""
        if isinstance(other, self.__class__):
            return self.hash == other.hash and self.month == other.month and self.year == other.year
        return False

    def __ne__(self, other):
        """Override the default Unequal behavior"""
        return self.hash != other.hash or self.month != other.month or self.year != other.year


texts:
Currently the class takes a json file and retrieves data from it, and i'd like to improve this class.
ConfigLoader.h
#ifndef LEVELEDITOR_CONFIGLOADER_H
#define LEVELEDITOR_CONFIGLOADER_H

#include <string>
#include <json/json.h>
#include <stdexcept>
#include <fstream>

namespace Editor
{
    class JsonInit
    {
    public:
        JsonInit()
        {
            std::ifstream inputFile("config.json");
            if (inputFile.bad())
            {
                throw std::runtime_error("could not load config file");
            }

            inputFile >> _root;
        }

        inline Json::Value& getRoot() { return _root; }

    private:
        Json::Value _root;
    };

    class ConfigLoader
    {
    public:
        inline static int loadInt(const std::string key) {return json.getRoot().get(key, -1).asInt(); }
        inline static std::string& loadString(const std::string key) {return json.getRoot().get(key, -1).asString();}

    private:

        static JsonInit json;
    };
}

#endif // LEVELEDITOR_CONFIGLOADER_H

ConfigLoader.cpp
#include "configloader.h"

Editor::JsonInit Editor::ConfigLoader::json;

Edit: forgot to say the "config.json" path is temporary, as i wish to make it possible to let the user choose


texts:
I created this custom binding handler:

ko.bindingHandlers.line = {
    update: function (element, valueAccessor, allBindings) {
        // First get the latest data that we're bound to
        var value = valueAccessor();

        // Next, whether or not the supplied model property is observable, get its current value
        var valueUnwrapped = ko.unwrap(value);

        // Now manipulate the DOM element
        if (valueUnwrapped) {
            $(element).after('<br />');   // Make the element invisible
        }
        return ko.bindingHandlers.text.update(element, function () {
            return valueUnwrapped;
        })
    }
};

I'm wondering about the part where I do ko.bindingHandlers.text.update.  Is there a better way to solve this?

Is it the only way to update the DOM with ko.bindingHandler.text.update, or is there any more straightforward way to do it?


texts: Evaluating a polynomial at a given value of x and n

texts:
To solve a polynomial equation I have written following program, is there any way to optimize this program.

Following code is working code:

Program takes input n,x where n is the deg of polynomial and x is the point at which the polynomial is to be evaluated.

   #include<stdio.h>

   int power(int x, int y);

   int main()
  {
  // n is the deg of polynomial
  // x is the value of polynomial for which it is to be evaluated
  int x=0,n=0,A[10],sum=0,i=0,M=0,y=0;

  printf("Enter value of n,x \n");
  scanf("%d %d",&n,&x);

  printf("Enter the coeficients\n");

  for(i=0;i<=n;i++)          //Taking coefiecent values
  {
     scanf("%d",&A[i]);
  }

  y=n;
  for(i=0;i<=n;i++)
  {
    M=power(x,y);
    sum=sum+(A[i]*M);
    y--;
   }

  printf("\nSum of polynomial is %d",sum);

  return 0;
 }

 int power(int x, int y)
 {
  int result = x;
  int i;
  if(y == 0) return 1;
  if(x < 0 || y < 0) return 0;

  for(i = 1; i < y; ++i)
  result *= x;

  return result;
}


texts:
I'm new to Python and I came to the following excercise:

  Write a function named printTable() that takes a list of lists of
  strings and displays it in a well-organized table with each column
  right-justified. Assume that all the inner lists will contain the same
  number of strings. For example, the value could look like this:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

  Your printTable() function would print the following:

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

My solution is this:

table_printer.py

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

def printTable(tableData):
    """
    Print table neatly formatted:
    e.g:

    [['apples', 'oranges', 'cherries', 'banana'],
    ['Alice', 'Bob', 'Carol', 'David'],
    ['dogs', 'cats', 'moose', 'goose']]

    becomes:

      apples Alice  dogs
     oranges   Bob  cats
    cherries Carol moose
      banana David goose
    """
    # make list of ints to store later max len element of each list
    colWidths = [0] * len(tableData)

    # Store maxlen of each list
    i = 0
    while i < len(tableData):
        colWidths[i] = len(max(tableData[i], key=len))
        i = i + 1

    # Print formatted
    for x in range(len(tableData[0])):
        for y in range(len(colWidths)):
            print(tableData[y][x].rjust(colWidths[y]), end=' ')
        print(end='\n')

printTable(tableData)

I wonder if this is a good solution or if there is an easier/better way. It took me quite some time to come up with a solution. Still I feel its probaly not very elegant. Maybe I'm overcomplicating it because I came from C/C++ where you oftenly have to do stuff by hand.

I read that it's often not a good idea in python to write loops like in other languages with explicit indices (what I basically did here). Are there any alternatives?


texts: Solving maze problem with backtracking solution using stack

texts:
I solved the maze backtracking question using a stack however could not find any other solution like that anywhere (to validate my solution is actually a valid one).
The problem statement is as follows -

  Imagine a robot sitting on the upper left corner of grid with r rows
  and c columns. The robot can only move right or down but certain cells
  are "off limit" such that the robot cannot step on them. design an
  algorithm to find a path for the robot from the top left to the bottom
  right

My Solution (java) is as follows -

public static boolean solve(boolean[][] maze) {
        int maxY = maze.length-1;
        int maxX = maze[0].length-1;
        int[] end = new int[]{maxY, maxX};
        int[] currentPosition = new int[]{0, 0};
        Stack<int[]> lastPosition = new Stack<>();
        lastPosition.push(currentPosition);
        while ( (currentPosition[0] != end[0] || currentPosition[1] != end[1])
                && !lastPosition.isEmpty()) {
            // get current position coordinates
            int y = currentPosition[0];
            int x = currentPosition[1];

            // Try moving right
            if(x+1 <= maxX && maze[y][x+1]) {
                currentPosition = new int[]{y,x+1}; // Move one step right
                lastPosition.push(currentPosition);
            } else if(y+1 <= maxY && maze[y+1][x]) { // Try moving down
                currentPosition = new int[]{y+1,x}; // Move one step down
                lastPosition.push(currentPosition);
            } else {
                maze[y][x] = false; // Mark as dead end (so we will not try to reach here again)
                currentPosition = lastPosition.pop();
            }
        }

        return !lastPosition.isEmpty();
    }

It looks like it works well (I tested it against several mazes to make sure), it should also run in O(rc) time at worst case (which is fine for the a maze of rc size) but everything else I've seen uses recursion or other methods to solve this problem. Am I missing something?

Will appreciate any kind of guidance.


texts:
Here is a solution to the SPOJ's JPESEL problem. Basically the problem was to calculate cross product of 2 vectors modulo 10. If there is a positive remainder, it's not a valid PESEL number; (return D) if the remainder equals 0, it's a valid number (return N).

import re, sys
n = input()
t = [1,3,7,9,1,3,7,9,1,3,1]
while(n):
    p = map(int, re.findall('.',sys.stdin.readline()))
    # Another approach I've tried in orer to save some memory - didn't help:
    # print 'D' if  sum([int(p[0]) * 1,int(p[1]) * 3,int(p[2]) * 7,int(p[3]) * 9,int(p[4]) * 1,int(p[5]) * 3,int(p[6]) * 7,int(p[7]) * 9,int(p[8]) * 1,int(p[9]) * 3,int(p[10]) * 1]) % 10 == 0 else 'N'
    print 'D' if ( sum(p*q for p,q in zip(t,p)) % 10 ) == 0 else 'N'
    n-=1

The solution above got the following results at SPOJ:

Time: 0.03s
Memory: 4.1M

where the best solutions (submitted in Python 2.7) got:

Time: 0.01s
Memory: 3.7M

How can I optimize this code in terms of time and memory used?

Note that I'm using different function to read the input, as sys.stdin.readline() is the fastest one when reading strings and input() when reading integers.


texts: Replace part of the string with n size with string of m size

texts:
I wanted to understand memory and pointers better before I endeavour into file path manipulations for larger project. This is simple replace part of the string test function that I need to rewrite into struct to call upon. I used scopes to test for memory leaking and changes, I work on Windows 7, CygWin and notepad++.

I am using std::size_t as an size representation due to:

  A type whose size cannot be represented by std::size_t is ill-formed mentioned by cppreference with "std::size_t is commonly used for array indexing and loop counting".

I decided to go for the c-style null terminated character array since arguments passed through main(int argc, char **argv) are null terminated characters and system calls accept those best. It seemed beneficial to code parts that i need myself instead of relying on another library, and it is tiresome to keep track what is converted with c_str() and what isn't.

As mentioned above, this function is part of project that manipulates, changes and makes full or relative paths to the files. The character array helps me use stat that comes with CygWin to be able to automatically test if path is not accessible, directory or file. I could use std::string but that is an extra header and i plan serious expansions of file paths to include some custom behaviour - which isn't tied to this function.

#include <iostream>

size_t get_str_size(const char* temp){
            size_t s=0;
            while( temp[s] != '\0' )s++;
            return s;
        }

int main(int argc, char **argv){

    const char * temp = "sublime/subliminal/sfit.exe"; // example string
    std::cout << &temp << "\t" << temp << std::endl; // prints out address and value
    { // wild scope to help me navigate and debug
        const char* shitcake = "sfitcake"; // string to be put in place of sfit
        size_t ldelim = 0;  // / last delimiter
        size_t edelim = 0;  // . end delimiter
        size_t original_size = get_str_size(temp);

        // finding the necessary indexes of charachters
        for( int i =0 ; i <= original_size; i++ ){
                if( temp[i]=='/' ){ldelim=i;}
                if( temp[i]=='.' ){edelim=i;}
            }

        // calculating size that influences the char array
        size_t old_size = edelim - ldelim -1;  // current char array size(-1 to remove last delimiter)
        size_t new_size = get_str_size(shitcake); // new char array size

        // char array duplication , since original string is const
        char* tempcopy = new char[original_size]; // holds the copy of the temp
        for( int i =0 ; i < original_size; i++ ){ tempcopy[i] = temp[i]; }

        // value to be constructed
        char *new_version = new char[ original_size + (new_size-old_size) ];

        // filling the part before replacement happen
        for( int i =0 ; i <=ldelim; i++ )               { new_version[i] = tempcopy[i]; }
        // filling replaced char array
        for( int i =0 ; i <= new_size;i++ )             { new_version[i+1+ldelim] = shitcake[i]; }
        // the rest of original string
        for( int i =edelim ; i < original_size;i++ )    { new_version[i+old_size] = tempcopy[i];}

        //conversion back to const char* with expanded size and new value
        temp = (const char*)new_version;

        //deleting pointers
        delete tempcopy;
        delete new_version;
    }
    std::cout << &temp << "\t" << temp << std::endl;

    return 0;
}

The output i am getting is:

0xffffcbb8  sublime/subliminal/sfit.exe
0xffffcbb8  sublime/subliminal/sfitcake.exe

Which means it works, but i am afraid of pointer not changing memory address even though the size and value changed.

Main concerns and desires for code:

Removing chance of dangling pointer and memory issue
Fast and readable code


texts:
I wrote a function that iterates over 3 parameters to spot out-of-stock items. To illustrate this I'll draw an example: suppose that the product 10 in store 2 for an offer named "super5" is following this trend

day | qty

1     50
2     70
3     55
4     67
5     13
6     0

Offer finished at day 6, the product was potentially out of stock at day 5. In order to spot this and verify it I find the index of 0 qty and look 2 back i took the mean of that two day (67 + 13) / 2 = 40 if the mean is >  first decile then tag "out-of-stock" else "ko"

I tried:

def flag_out_of_stock(dataframe, sku, store, offer) :
    ffl = []
    sku_store_offer = dataframe[["id_sku", "id_store", "id_offer"]].drop_duplicates(["id_sku", "id_store", "id_offer"])
    for sku, store, offer in tqdm(zip(sku_store_offer["id_sku"], sku_store_offer["id_store"], sku_store_offer["id_offer"])):
        cond1 = dataframe["id_sku"] == sku
        cond2 = dataframe["id_store"] == store
        cond3 = dataframe["id_offer"] == offer
        timeseries = dataframe[np.logical_and.reduce((cond1, cond2, cond3))][["f_qty_recalc", "id_day"]]\
        .set_index("id_day")\
        .sort_index()
        mu = timeseries.mean()[0]
        if mu >= 6 :
            sigma = timeseries.std()[0]
            q1 = timeseries.quantile(0.1)[0]
            # index where qty == 0
            likely_out_of_stock_index = np.where(timeseries ==0)[0]
            # if there more that one value where qty == 0
            if len(likely_out_of_stock_index) > 1 :
                # for each index where qty == 0
                for i in likely_out_of_stock_index :
                    # if the day before or day after are superior to the first decile
                    #then flag out of stock
                    day_before_2 = timeseries.iloc[i-2:i].mean()[0]
                    if day_before_2 >= q1 :
                        ffl.append("out_of_stock")
                    elif day_before_2 >= mu - sigma  :
                        ffl.append("likely_out_of_stock")
                    else :
                        ffl.append("KO")
            else :
                try :
                    day_before_2 = timeseries.iloc[likely_out_of_stock_index-2:likely_out_of_stock_index].mean()[0]
                    if day_before_2 >= q1 :
                        ffl.append("out_of_stock")
                    elif day_before_2 >= mu - sigma  :
                        ffl.append("out_of_stock")
                    else :
                        ffl.append("KO")
                except TypeError :
                    ffl.append("KO")
        else :
            ffl.append("KO")
    return pd.Series(ffl)

The issue there that this code running on ~600k row of parameters and took ~1.3seconds per iteration.  Of that, 0.9sec is that operations…

timeseries = dataframe[np.logical_and.reduce((cond1, cond2, cond3))][["f_qty_recalc", "id_day"]]\
.set_index("id_day")\
.sort_index()

so I would like to find a faster way.


texts: Clearing the screen using FillConsoleOutputAttribute()

texts:
I'm currently clearing my console window with this piece of code:

void clrScr()
{
    COORD cMap =
    {
        0, 3
    };
    if(!FillConsoleOutputAttribute(hCon, 0, 2030, cMap, &count))
    {
        std::cout << "Error clearing the console screen." << std::endl;
        std::cout << "Error code: " << GetLastError() << std::endl;
        std::cin.get();
    }
}

, which I call once in the main loop.
But since my window is quite large (70x35), it's flickering quite a bit.

I was wondering if there are any faster methods of doing this?


texts: Excel VBA: Set the background-color & border for a user-defined range of rows

texts:
On my work I've got to maintain an Excel-sheet. Documenting the incident-tickets I've dealt with.

For to be able to distinguish between single days easily I mark every second day with a light cyan-background. So the sheet gets a Zebra-stripe look.

Because I've got to do this every second day (by marking the concerning row-range with the mouse) I've made myself a VBA procedure.

It is started from the Excel-GUI.

An input box appears in which I enter the start- and the end-row. Separated by a colon.
The VBA then marks the range between start inclusive and end inclusive. Moreover it adds a bottom-border to the last row.

Here the VBA-code:

' Sets the background of a user-given range to
'  a defined color.
' Sets the bottom-border of the last row within
'  the range.

Public Sub SetBackgroundColorAndBorder()
    Dim StartEnd As Variant ' Becomes an array with the startRow as first element and the lastRow as second element.
    Dim VerticalIndex As Integer
    Dim HorizontalIndex As Integer

    Const COLOR_INDEX As Integer = 34

    On Error GoTo ErrorHandler

    ' Process the user-given instruction.
    StartEnd = Split( _
                    Trim( _
                        InputBox("Please use a colon for separation." _
                            & vbCrLf & "E.g.: 21:28", _
                            "Please insert start- and endrow!")), _
                     ":")

    ' Set the background-color.
    For VerticalIndex = StartEnd(0) To StartEnd(1)
        For HorizontalIndex = 2 To 6
            Cells(VerticalIndex, HorizontalIndex).Interior.ColorIndex = COLOR_INDEX
        Next
    Next

    ' Set the bottom-border of the last row within the given range.
    For HorizontalIndex = 1 To 6
        Cells(StartEnd(1), HorizontalIndex).Borders(xlEdgeBottom).LineStyle = xlDouble
    Next

    Exit Sub

ErrorHandler:
    MsgBox "Please restart the macro." & vbCrLf _
        & "Please take care to give a correct instruction.", _
        vbExclamation, "AN ERROR HAS OCCURED."
End Sub

It works fine. But I would like to know:

What do you think?

Could it be improved concerning stability and efficiency?

What do think about asking the range from the user via input box?

Could one accomplish the same task in an easier perhaps more robust way?

General hints and comments concerning my coding welcomed too.


texts:
After some research I found the following information: In this closed question I found a solution which does not work well when pop-up has height bigger than screen (and some jquery solution). Here is a question about showing outside page in popup. And here are some theoretical and angularJS solutions. However, those answers do not satisfy me.
I want to show a pop-up to user which contains my content (not loaded from URL) e.g. an editor. I am interested in only pure JS/HTML/CSS solutions (no jQuery or other libs). This is the code which I regularly use, and which was tested on Chrome, Safari, Firefox and Edge:

toggle = q => document.querySelector(q).classList.toggle('hide');
body { margin: 0; padding: 0; }
.btn { padding: 10px; background: #BADA55; border-radius: 5px; cursor: pointer}

.popupBg {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  min-height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items:center;
  background: rgba(255,0,0,0.5)
}

.popup {
  width: 100px;
  min-height: 200px;
  border: 1px solid black;
  background: #88f;
  margin: 40px;
}

.hide {
  display: none;
}

Some content

PopUP

      My popup

Here is a JSfiddle version.
Question1: Is there simpler way to show popup (similar to this in snipped and easy to modify) to user?
Question2: Does approach have any drawbacks?


texts: Finding the prime factors of a positive number

texts:
I have an assignment to write on the standard output the prime factors of a positive number displayed in ascending order and separated by '*'. My code works, but I need help reviewing it before I submit my work. Allowed functions: write, printf, atoi.

void    find_factors(int n)
{
    int i;
    int separated;

    i = 3;
    separated = 0;
    if (n <= 1)
        return ;
    while (n % 2 == 0)
    {
        if (separated)
            printf("*");
       printf("%d", 2);
       separated = 1;
        n = n / 2;
    }
    while (i <= n)
    {
        while(n % i == 0)
        {
            if (separated)
                printf("*");
            printf("%d", i);
            separated = 1;
            n = n / i;
        }
        i += 2;
    }
    if (n > 2)
    {
      if (separated)
            printf("*");
      printf("%d", n);
    }
}


texts: Efficient LC3 assembly code to print the numbers leading up to any digit

texts:
I'm using an LC3 microarchitecture simulator to write assembly code. I've only been writing assembly for about three weeks, so I am still very new.

My goal is to print all the numbers leading up to a set value, so for example, if the user selects '6' the console prints 012345. My code works, but the unit test says my code is inefficient or has an infinite loop.

I set the value by manually setting R1 in my simulator to any value. The rest is automated with the code, starting at 0x3000.

LD, R0, X3001 ;Load R0 with 0
0 ;I did this b/c I don't know how to load a register with ascii values
AND R2, R2, #0 ; Set R2=0
NOT R3, R1 ;invert R1, store in R3
ADD R3, R3, #1 ;Add 1 to R3, now R3=-R1
ADD R4, R0, R3 ; better way to perform loop? added these to maintain loop
BRz X300b ; if previous math ever produces 0, skip to halt
OUT ; print single char
ADD R0, R0, #1 ; R0++
ADD R1, R1 #-1 ; R1--
BRnzp X3006 ;Always branch back to the above BR instruction
HALT

Hex:

3000
2000
0030
54a0
967f
16e1
1803
0404
f021
1021
127f
0ffb
f025

So my question is, is there any way to make this more efficient?


texts:
I am trying to write a small python code,where
I am reading a text file-which contains both Multiwords (MWEs)
and singular words (NMWEs).

I am trying to tag each one, as follows.

I have a dictionary of entries, containing the MWE and tagged MWE.
I am tagging them as replace, and whichever I could not tag as MWE
-the NMWE I am marking them so.

I wrote the following code

def rule_disc():
    corp=open("/python27/MWETagtext1.txt","r").read().lower()
    print "The Text file given Is:",corp
    mwedict={'prime minister':'prime/MWE minister/MWE','new delhi':'new/MWE    delhi/MWE','reserve bank':'reserve/MWE bank/MWE'}
    dict=mwedict
    mwetag=reduce(lambda x, y: x.replace(y, dict[y]), dict, corp)
    print "MWE Tagged String Is:",mwetag
    mwetagw=mwetag.split()
    list1=[]
    for word in mwetagw:
        if "/" in word:
            list1.append(word)
        else:
            word1=word+"[NMWE]"
            list1.append(word1)
    nlist=list1
    nstring=" ".join(nlist)
    print "The Tagged Text File Is:",nstring

on the given sample data, which is producing me the result.

My question is, is there a smarter way to do it?
Actual data size may run on millions of files.

I am using Python2.7.12 on MS-Windows 7


texts:
I have a PRNG-Class called Generator. Now, after creating a new instance of it:

var g:Generator = new Generator();

Custom function: set_seed()  -  Please review this approach.

I call g.set_seed(); which has the following logic:

public function set_seed(s:Number = 0):void
{
    seed = (s > 0) ? s : new Date().getTime();
}

Pro: I can call it without any arguments, looks more beautiful in the classes I'm using it.
Con: set_seed looks awful and I feel I should be using Flash's Getter/Setter approach.

(I'm getting the seed with: get_seed();)


texts: Finding duplicate files using md5sum Unix command

texts:
This is an exercise from Think Python: How to Think Like a Computer Scientist

Here's its description:

  In a large collection of MP3 files, there may be more than one copy of
  the same song, stored in different directories or with different
  filenames. The goal of this exercise is to search for duplicates.

  Write a program that searches a directory and all of its subdirectories, recur‐ sively, and returns a list of complete paths
  for all files with a given suffix (like .mp3). Hint: os.path provides
  several useful functions for manipulating fileand path names.
  To recognize duplicates, you can use md5sum to compute a “checksum” for each files. If two files have the same checksum, they probably
  have the same contents.
  To double-check, you can use the Unix command diff.

Here's my solution:

import os

def run_command(cmd):
    """Runs a command in a shell.

       cmd: a string specifies a Unix command.

       Returns: a string specifies the result
       of executing the command.
       """
    filepipe = os.popen(cmd)
    result = filepipe.read()
    status = filepipe.close()

    return result

def md5_checksum(filepath):
    """Returns a string specifies the MD5 checksum of
       a given file using md5sum Unix command.

       filepath: a string specifies a file.
       """
    command = 'md5sum ' + filepath

    return run_command(command)

def md5_checksum_table(dirname, suffix):
    """Searches a directory for files with a given
       file format (a suffix) and computes their
       MD5 checksums.

       dirname: a string specifies a directory.

       suffix: a file format (e.g. .pdf or .mp3).

       Returns: a dictionary mapping from string
       works as a MD5 checksum to list of strings
       work as pathes of files have this checksum.
       """
    table = {}

    for root, sub, files in os.walk(dirname):
        for file in files:
            if file.endswith(suffix):
                filepath = os.path.join(root, file)
                checksum, filename = md5_checksum(filepath).split()
                table.setdefault(checksum, []).append(filename)

    return table

def are_identical(files_names):
    """Returns whether files in files_names
       are identical using diff Unix command.

       files_names: a list of strings specify pathes of files.
       """
    index = 1

    for filename1 in files_names:
        for filename2 in files_names[index:]:
            command = 'diff %s %s' % (filename1, filename2)
            result = run_command(command)

            if result:
                return False

        index += 1

    return True

def print_duplicates(checksums):
    """Prints pathes of files have the same MD5 checksum.

       checksums: a dictionary mapping from MD5 checksum (string) to
       list of pathes of files (strings) have share this checksum.
       """
    for checksum, filepathes in list(checksums.items()):
        if len(filepathes) > 1:
            print('Files have the checksum %s %s' % (checksum, 'are: '))

            for filepath in filepathes:
                print(filepath)

            if are_identical(filepathes):
                print('\nThey are indentical. \n')

def main():
    table = md5_checksum_table('/media/sf_Shared/', '.pdf')
    print_duplicates(table)

if __name__ == '__main__':
    main()

How can it be refactored and optimized?

Notes:

It wasn't like that, but it worked. After reading the author's solution I refactored it and edited a lot of it.
I'm no expert at MD5, just got the basic idea.
I'm no expert at Unix or Linux. I use Windows, and I've tested this script using a virtual machine running Ubuntu.
I'm a hobbyist and beginner in Python and programming.


texts: script- loop through files and directories

texts:
I have written the script, which unzips a zip file (passed as argument to the bash), loops through directory and files, then perform different actions based on directory or file. It is working fine.

However I would like to know some things:

Is it possible to do this without the unzip command? I somehow feel like that step can be avoided and we can directly use the zip file to perform the task.
I have used three temporary files/directories(tmp.txt - to store the directory and file lines, out.xml - for the curl command, DIREC - for finding the files and directories). I have removed those three files at the end of the script. Is there a way to optimize this? may be using variables instead of files.

Here is the bash script, with comments:

#!/bin/bash
#The below line unzips the zip file as passed as argument
unzip $1
length=${#1}
const=4
count=$((length-const))
DIREC=$(echo $1 | cut -b 1-$count)
OUTPUTFIL=out.xml
#The below line will find the directory, which was created by the unzip command. Creation of tmp.txt here.
find $DIREC -exec echo {} \; >tmp.txt
exec<tmp.txt
   while read line
   do
if [ -d "${line}" ] ; then
    echo "$line is a directory";
else
    if [ -f "${line}" ]; then
BASE=$(base64 $line);
        echo "${line} is a file";
{
    echo "<inpu>${BASE}</inpu>"
} > ${OUTPUTFIL}
curl -u admin:secret --data-binary @out.xml http://dp1-l2.com; echo
    else
        echo "${line} is not valid";
        exit 1
    fi
fi
   done
rm -f tmp.txt
rm -rf $DIREC
rm -f out.xml


texts:
I have the need to search a directory containing 1000+ files on remote servers where I only have access to SQL Server Management Studio and Explorer. I have written the below SQL statement which does what I need, only incredibly slowly. I fear using this many temp tables and the cursor is the main issue. Any ideas on how I can speed this up?

EDIT: I forgot to mention that I need to keep this query based.  I will not necessarily have full permissions regarding jobs and/or SSIS packages.

--Drop temp table if it already exists
IF OBJECT_ID('tempdb..#tempFileContents') IS NOT NULL
DROP TABLE #tempFileContents

DECLARE @FindText AS VARCHAR(255)
DECLARE @FileDir AS VARCHAR(255)

--Directory to search
SET @FileDir = 'C:\Users\*********\Desktop\TEMP\'
--Text to search
SET @FindText = '1234'
----------------------
----------------------

--Crete temp table to store output lines from text file
CREATE TABLE #tempFileContents
(
    lineText TEXT
)

--Create declared table to store found file names in the directory
DECLARE @files table
(
    filename VARCHAR(255)
    ,depth INTEGER
    ,files BIT
)

--Create declared table to store the text the string ws found in along with the filpath              of the file.
DECLARE @foundText table
(
    LineNum INT
    ,foundText TEXT
    ,filename VARCHAR(255)
)

--Create table of files in the directory
INSERT INTO @files
EXEC xp_dirtree @FileDir, 10, 1

--Update file names to include filepath
UPDATE @files SET filename = @FileDir + filename

--Varchar used to store the derived SQL string
DECLARE @sql NVARCHAR(1000);

--Create cursor for file searching
DECLARE @text VARCHAR(255)
DECLARE @ID VARCHAR(255)
DECLARE IDs CURSOR LOCAL FOR select filename from @files

--Open cursor
OPEN IDs
FETCH NEXT FROM IDs into @ID
WHILE @@FETCH_STATUS = 0
BEGIN
    --Truncate temp table prior to searching a file
    TRUNCATE TABLE #tempFileContents
    SET @sql = 'BULK INSERT #tempFileContents FROM "' + @ID + '"'
    EXEC(@sql);

    --Insert into results table
    INSERT INTO @foundText
    (LineNum, foundText, filename)
    SELECT ROW_NUMBER() OVER( ORDER BY @ID ) AS 'rownumber', lineText, @ID FROM #tempFileContents

    DELETE FROM @foundText
    WHERE foundText NOT LIKE '%' + @FindText + '%'
    OR foundText IS NULL

    FETCH NEXT FROM IDs into @ID
END

--Close off and dispose of unneeded resources
CLOSE IDs
DEALLOCATE IDs
DROP TABLE #tempFileContents

--Display results
SELECT * FROM @foundText


texts: Reading String data into a Tree like nested grid structure (like Sudoku Board)

texts:
Context

The original idea is to create an efficient grid structure for a Sudoku like board but this can be applied to many such grid structures (like wavelet transform on images, JPEG2000 etc). This particular one is basically a 9x9 Board which is made up of 3x3 Blocks where each Block is made up of 3 x Axis a a a type. You may think Axis type like a list limited to having only 3 elements (no more no less) and no empty or identiy element.

I have defined the Axis, Block and Board types as;

data Axis a =  Axis { _0 :: a
                    , _1 :: a
                    , _2 :: a
                    } deriving (Eq, Functor)
type Block a = (Axis(Axis a))
type Board a = (Axis(Axis (Block a)))

instance Show a => Show (Axis a) where
  showsPrec _ (Axis x y z) = shows x . (' ':) . shows y . (' ':) . shows z

As you notice, polymorphic Axis type is like a ternary tree with no leaves where the nodes can either be another Axis a type or an a type value. Does anybody know a general name for such data types in Haskell literature?

Anyways, by doing so, once i have a Board then i can easily access any Block or Cell quite efficiently. To access one of the 9 Blocks i can now simply do

_0 . _1 $ myBoard -- like (row 0, col 1) from myBoard

where to gain access to any cell within the Board all i have to do is to get to the Block and then to the cell like

_2 . _1 . _0 . _1 $ myBoard --  coord of cell . coord of Block => (_2 . _1) . (_0 . _1)

Problem

The problem arose when building up my Board type from a provided String. Since i post this here, I have done it but it smells like a fish and i think there must be a better way.

So the input data comes in the form of a string of 81 numeric characters among 0..9. The string should fill up the board line by line. So if my board supposed to be a 2D list, then a chunksOf 9 . map ((read :: String-> Int) . pure) would be sufficient. However the Board type is a 4 fold nested Axis type.

To start with, I couldn't even find a way to write a Read instance for the Board type at all. My solution is to first convert the flat list into a nested list of proper structure like.

nestList :: [a] -> [[[[a]]]]
nestList = map transpose . chunksOf 3 . chunksOf 3 . chunksOf 3

and then after a 2 days war with GHC infinite type errors and whatnot, i could finally come up with this stinky part.

axify :: [[[[a]]]] -> Board a
axify ([a,b,c]) = Axis (Axis (axify' $ a !! 0) (axify' $ a !! 1) (axify' $ a !! 2))
                       (Axis (axify' $ b !! 0) (axify' $ b !! 1) (axify' $ b !! 2))
                       (Axis (axify' $ c !! 0) (axify' $ c !! 1) (axify' $ c !! 2))
                  where
                  axify' ([a,b,c]) = Axis (Axis (a !! 0) (a !! 1) (a !! 2))
                                          (Axis (b !! 0) (b !! 1) (b !! 2))
                                          (Axis (c !! 0) (c !! 1) (c !! 2))

Now this works. I can fill the Board properly from a flat string and the Show instance just gives back a stringified version of the nestedList.

Question

Could anybody please help me with a proper Read instance or at least an axify function that is idiomatic (generalized to n fold Axis a type)?

Many thanks in advance.


texts: Categorize & sub categorize from contents of one row and more execute even more queries in results

texts:
I have a table called sales and it has below columns:

'id'
'product_type'
'soldDate'
'text'

'product_type' examples are: Tshirt-XL, Tshirt-L, Tshirt-M, Trousers-XL, Trousers-L, Trousers-M etc.

I have an array called products which is;

$products = array('Tshirt','Trausers');

My output is after executing below code:

Tshirt

Tshirt-L

lorem impsum dolat

Tshirt-XL

lorem impsum.
another text. ball.

Trousers

Trousers-M

text for this one.

And the code itself:

$products = array('Tshirt','Trousers');

foreach ($products as $product) {
    echo "";
    echo $product;
    echo "
";

    $q = "
    SELECT      *,
    SUBSTRING_INDEX(product_type, '-', 1) AS product_typeMain
    FROM        sales
    WHERE       SUBSTRING_INDEX(product_type, '-', 1) = '".$product."'";
    $statement = $db->prepare($q);
    $results = $statement->execute();
    $results = $statement->fetchAll();

    $unique_product_types = array();

    foreach($results as $filter_result){
        if ( in_array($filter_result->product_type, $unique_product_types) ) {
            continue;
        }
        $unique_product_types[] = $filter_result->product_type;

        echo $filter_result->product_type;
        echo "
";

        $q = "
        SELECT      *
        FROM        sales
        WHERE       product_type = '".$filter_result->product_type."'
             ";
        $statement = $db->prepare($q);
        $results = $statement->execute();
        $results = $statement->fetchAll(PDO::FETCH_OBJ);

        foreach ($results as $value) {
            echo "
".$value->text."
";
        }

    }

}

I know there are so many foreach loops, so many queries. Also I have worries about performance (more than 100.000 rows, and more than 100 product_type.) Plus I will need to add another query in last foreach loop to make searches (multiple, not one).

I am looking forward to hear best practices to improve. Thanks in advance.


texts: Suggestions for optimising this front end code

texts:
I've stumbled across some UI (React.js) code that I've worked out to have a time complexity of O(n^4) (I hope that's right, if not please do correct me). I was interested in how one might go about optimising something like this.

I know that for() loops do perform slightly better than array.forEach() and I'd assume const uses a bit less memory than let due to not needing to support re-allocation.

Would using functional operators like map and filter improve performance?

I'd be really interested to see some suggestions to this, and maybe the ideal optimisation for it?

The code:

animate () {
  let movingScreens = {}
  if (this.animationsDisabled()) {
    movingScreens = {}
  } else {
    for (let i in scrollAnimationDefs.movingScreens) {
      if (i !== 'appsTop' && i !== 'appsBottom') movingScreens[i] = scrollAnimationDefs.movingScreens[i]
    }
  }

  for (let shape in movingScreens) {
    if (movingScreens[shape].scrolls) {
      for (let scroll of movingScreens[shape].scrolls) {
        const from = scroll.from * this.scrollMax
        const to = scroll.to * this.scrollMax
        if (from <= this.scrollTop && to >= this.scrollTop) {
          const styles = scroll.styles(
            (this.scrollTop - from) / (to - from)
          )

          for (let style in styles) {
            let newStyle = styles[style]

            const els = scrollAnimationDefs.movingScreens[shape].els.map(
              ref => {
                if (ref === 'screen1IfContainer') return this.animations.screen1IfContainer.current.container.current
                return this.animations[ref].current
              }
            )

            for (const i in els) {
              if (els[i]) {
                els[i].style[style] = newStyle
              }
            }
          }
        }
      }
    }
  }
}


texts: Give the variable length permutations (combinations) of a set of strings

texts:
This code is a proof-of-concept which I intend to convert into a static utility / helper class. I'm looking at this review from a structure or performance viewpoint. Small detail such as whether it prints or returns something, or whether the output is well-formatted, don't concern me too much.

The purpose of this code sample is:

Given an input of an arbitrary set of strings, such as A B C, return all the sets of permutations or combinations of these, where each is used only once; in this example, it would return (or print) the following 7 sets:

ABC (Use all 3)
AB, BC, AC (Combinations of pairs)
A, B, C (Each item individually)

The sequence of each doesn't matter (They happen to be alphabetical in the output)
If we have AB we don't also need BA (These can be permutated later by such libraries as Guava's Collections2.permutations()

import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class PermutationTest {

  private String[] strings;
  private int t;
  private int[] i;
  private Set<String> unique = new TreeSet<>();

  private PermutationTest(int t, String... strings) {
    this.strings = strings;
    this.t = t;
    this.i = new int[t];
    for(int x = 0 ; x < this.t ; x++ ) {
      i[x] = x;
    }
  }

  private boolean permutate() {
    return permutate(this.t - 1);
  }

  private boolean permutate(int c) {
    if(c < 0) {
      return false;
    }
    this.i[c]++;
    int m = this.strings.length - (this.t - c - 1);
    if(this.i[c] >= m) {
      if(permutate(c - 1)) {
        this.i[c] = this.i[c - 1] + 1;
      } else {
        return false;
      }
    }
    return true;
  }

  private void print() {
    System.out.println(Arrays.toString(this.i));
    StringBuilder sb = new StringBuilder();
    for(int x = 0 ; x < this.t ; x++ ) {
      sb.append(this.strings[i[x]]);
    }
    this.unique.add(sb.toString());
  }

  public static void main(String[] args) {
    String[] strings = (args.length > 0) ? args : new String[] {"A", "B", "C"};
    Set<String> total = new TreeSet<>();
    for(int z = 0 ; z < strings.length ; z++ ) {
      total.addAll(outer(z + 1, strings));
    }
    System.out.println(total.size());
    System.out.println(total);
  }

  private static Set<String> outer(int z, String[] strings) {
    PermutationTest p = new PermutationTest(z, strings);
    int c = 0;
    boolean running = true;
    while(running && c < 200) {
      p.print();
      running = p.permutate();
      c++;
    }
    System.out.println(String.format("Total %d permutation count", c));
    System.out.println(String.format("Total %d unique strings", p.unique.size()));
    System.out.println(p.unique);
    return p.unique;
  }
}


texts:
I solved a problem which you can read about here, but it gives me "time limit exceeded" even though it runs in 4 seconds. I really don't understand why.

I don't think my code can be any simpler, basically it has as many functions as there are solutions I think. At the start of my code I find the first letter matching the first letter of the word I am searching for, then when it finds it, it checks in 8 directions if it can make the whole word without going out of the crossword.

program ideone;
var
kar:array[1..1000, 1..1000] of char;
konacno:int64;
i2,i3,n,xx,yy:integer;
s:string;
procedure trag(y:integer; x:integer; y1:integer; x1:integer; i:integer);
        var
        x2,y2:integer;
    begin
    x2:=x+x1;
    y2:=y+y1;
    while (x2<=n) and (x2>0) and (y2<=n) and (y2>0) do begin
        if kar[y2,x2]=s[i+1] then
            if i=length(s)-1 then
            konacno:=konacno+1
            else
            trag(y2,x2,y1,x1,i+1);

    x2:=x2+x1;
    y2:=y2+y1;
    end;
    end;
begin
readln(n,s);
delete(s,1,1);
xx:=1;
yy:=1;
for i2:=1 to n do begin
for i3:=1 to n do
read(kar[i2,i3]);
readln();
end;
konacno:=0;

for i2:=1 to n*n do begin
    if kar[yy][xx]=s[1] then begin
        trag(yy,xx,-1,-1,1);
        trag(yy,xx,-1,0,1);
        trag(yy,xx,-1,1,1);
        trag(yy,xx,0,1,1);
        trag(yy,xx,1,1,1);
        trag(yy,xx,1,0,1);
        trag(yy,xx,1,-1,1);
        trag(yy,xx,0,-1,1);
    end;
    xx:=xx+1;
    if xx>n then begin
    xx:=1;
    yy:=yy+1;
    end;

end;

writeln(konacno);

end.

If you have any tips please tell me, I am new to Pascal, so I don't know all the tricks for speeding up the program, and I don't want to use C or C++.


texts: Buidling classes with user input and calling methods

texts:
Learned alot in this first week, following PCC, but biggest leaps came from the community and others giving their time to help, thank you!

All input appreciated!

ObjectiveGoals were to fill a class with user inputs from multiple users and then be able to call methods to each user input created class. (... did I say that right O.o)

Code

class User():
    def __init__(a, first_name, last_name, city, age):
        a.first_name = first_name.title()
        a.last_name = last_name.title()
        a.city = city.title()
        a.age = age

    def describe_user(a):
        print("-----")
        print("First Name" + " : " + a.first_name)
        print("Last Name" + " : " + a.last_name)
        print("City" + " : " + a.city)
        print("Age" + " : " + a.age)

def ask_user(message=''):
    user_input = ''
    while not user_input:
        user_input = input(message)
    return user_input

def form_complete(values, placement, length):
    placement = []
    while len(placement) < length:
        first_name = ask_user("Enter First Name: ")
        last_name =  ask_user("Enter Last Name: ")
        city = ask_user("Enter City: ")
        age = ask_user("Enter Age: ")
        values = User(first_name, last_name, city, age)
        placement.append(values)
    return placement

if __name__ == '__main__':

    users = form_complete('user', 'users', 3)
    for a in range(len(users)):
        users[a].describe_user()

Output

xenial)vash@localhost:~/pcc/9$ python3 3.py
Enter First Name: vash
Enter Last Name: the stampede
Enter City: gunsmoke
Enter Age: 131
Enter First Name: spike
Enter Last Name: spiegel
Enter City: mars
Enter Age: 27
Enter First Name: holden
Enter Last Name: caulfield
Enter City: new york city
Enter Age: 16
-----
First Name : Vash
Last Name : The Stampede
City : Gunsmoke
Age : 131

Greetings Vash!
-----
First Name : Spike
Last Name : Spiegel
City : Mars
Age : 27

Greetings Spike!
-----
First Name : Holden
Last Name : Caulfield
City : New York City
Age : 16

Greetings Holden!
(xenial)vash@localhost:~/pcc/9$


texts: Handling a text field and submit button with Ajax

texts:
There's this Ajax-heavy, jQuery-based site which I'm about to work on. There hasn't been much structure in the JavaScript code so far (lots of functions at global scope, hard-coded in the HTML onclick="something(args);".  How can I improve upon that and introduce some structure?

Here's what I've tried. This part is supposed to handle a single element which consists of a text field (span) which is replaced by an input on focus and runs an AJAX update call when a submit button is clicked or enter is pressed.

$(function() {
    var box = $('.foobar-info'),
        input = box.find('input'),
        label = box.find('span#name'),
        button = box.find('button');

    label.click(start_edit);
    button.click(submit);
    input.keypress2(KEYS.enter, submit);

    function start_edit() {
        box.addClass('is-edit');
    }
    function submit() {
        MyAjaxModule.edit_foobar(save_success,
            {'id': GLOBAL_FOO_ID, 'value': input.val()});
    }
    function save_success(data) {
        label.text(input.val());
        box.removeClass('is-edit');
    }
});

Showing and hiding of parts is driven by the CSS:

.foobar-info .state-display {display: inline;}
.foobar-info .state-edit {display: none;}
.foobar-info.is-edit .state-display {display: none;}
.foobar-info.is-edit .state-edit {display: inline;}

So far this achieves:

keeps the behaviour away from the markup
keeps relevant behaviour together in one block

On the other hand, I don't think it's testable or particularly easy to re-use with different configurations.

I've attempted to rewrite this to use objects and this. lookups instead of the big closure, but didn't end up in a code that would please me. For example, this part

label.click(start_edit);

would look like

this.label.click(this.start_edit.bind(this));

which looks really verbose plus it's super-easy to forget the unwieldy .bind(this) part.

This article served some inspiration, but felt rather hacky to me, mostly because relying on global name lookups.

Questions:

Any particular problems with my approach except what I've mentioned so far? How can I solve it?
Is there a canonical way to structure the code which I'll be happy to incorporate?


texts:
I would like to ask how I can make my code more simple and effective. I know that this code can be 100% better. I am supposed to load number for each array and then take the 2 arrays (4*3 and 3*4) and multiply them into 3*3 array.

The main point is making thescanf_s for both int a and int b in one "piece of code."

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int a[3][4];
    int b[4][3];
    int c[3][3] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };

    for (int j = 0; j != 4; j++)
    {
        for (int l = 0; l != 4; l++)
        {
            cout << "Zadej a[" << j << "," << l << "]: ";
            scanf_s("%d", &a[j][l]);
        }
    }

    for (int j = 0; j != 4; j++)
    {
        for (int l = 0; l != 4; l++)
        {
            cout << "Zadej b[" << j << "," << l << "]: ";
            scanf_s("%d", &b[j][l]);
        }
    }

    for (int j = 0; j != 3; j++)
    {
        for (int l = 0; l != 3; l++)
        {
            ;
            printf(" |%d| ", c[j][l] += a[j][l] * b[j][l]);
        }
        printf("\n");
    }

    return 0;
}


texts: Split download file buffer by any number of threads

texts:
This is my first attempt at splitting the download buffer into several threads by the number provided.  I want to improve on performance and better implementation approach.

import os
import requests
import threading
import urllib2
import time

url = "http://www.nasa.gov/images/content/607800main_kepler1200_1600-1200.jpg"
# url = 'http://pymotw.com/2/urllib/index.html'
# url = 'http://megaboon.com/common/preview/track/786203.mp3' # size cannot be determined.
# url = 'http://broadcast.lds.org/churchmusic/MP3/1/2/nowords/271.mp3'

def buildRange(value, numsplits):
    lst = []
    for i in range(numsplits):
        if i == 0:
            lst.append('%s-%s' % (i, int(round(1 + i * value/(numsplits*1.0) + value/(numsplits*1.0)-1, 0))))
        else:
            lst.append('%s-%s' % (int(round(1 + i * value/(numsplits*1.0),0)), int(round(1 + i * value/(numsplits*1.0) + value/(numsplits*1.0)-1, 0))))
    return lst

class SplitBufferThreads(threading.Thread):
    """ Splits the buffer to ny number of threads
        thereby, concurrently downloading through
        ny number of threads.
    """
    def __init__(self, url, byteRange):
        super(SplitBufferThreads, self).__init__()
        self.__url = url
        self.__byteRange = byteRange
        self.req = None

    def run(self):
        self.req = urllib2.Request(self.__url,  headers={'Range': 'bytes=%s' % self.__byteRange})

    def getFileData(self):
        return urllib2.urlopen(self.req).read()

def main(url=None, splitBy=3):
    start_time = time.time()
    if not url:
        print "Please Enter some url to begin download."
        return

    fileName = url.split('/')[-1]
    sizeInBytes = requests.head(url, headers={'Accept-Encoding': 'identity'}).headers.get('content-length', None)
    print "%s bytes to download." % sizeInBytes
    if not sizeInBytes:
        print "Size cannot be determined."
        return

    dataLst = []
    for idx in range(splitBy):
        byteRange = buildRange(int(sizeInBytes), splitBy)[idx]
        bufTh = SplitBufferThreads(url, byteRange)
        bufTh.start()
        bufTh.join()
        dataLst.append(bufTh.getFileData())

    content = ''.join(dataLst)

    if dataLst:
        if os.path.exists(fileName):
            os.remove(fileName)
        print "--- %s seconds ---" % str(time.time() - start_time)
        with open(fileName, 'w') as fh:
            fh.write(content)
        print "Finished Writing file %s" % fileName

if __name__ == '__main__':
    main(url)

I hope this is not a challenging one to suggest or comment on improvement.


texts: Conversion of hexadecimal string to string

texts:
Given a C# string which is a set of hexadecimal numbers such as:

string HexString = "202048656c6c6f20576f726c64313233212020";

Where those hexadecimal numbers represent the ASCII text:

"  Hello World123!  "

I need to convert the HexString to a String and I have the following code which works, but looks so excessive!

string HexStringToString(string HexString) {
    string stringValue = "";
    for (int i = 0; i < HexString.Length / 2; i++) {
        string hexChar = HexString.Substring(i * 2, 2);
        int hexValue = Convert.ToInt32(hexChar, 16);
        stringValue += Char.ConvertFromUtf32(hexValue);
    }
    return stringValue;
}

Am I missing some elegant method?