texts: Duplicates in array elements and sorting

texts:
I've been given this little test exercise for an interview as php developer, and I'd like to hear from you if my solution is good (enough) or if the problem could have been solved in a better way. Please keep in mind that I've no academic training in CS or equivalent (rather the opposite) and my career started as a self-taught developer.

Given the array:

$numbers = array(
   1,  68,86, 52, 35, 86, 1, 24, 13, 72, 1
);

Take the duplicates and print them out in a string separated by a comma (ex. "a,b,c,d"), ordered in ascendent way.

$holder = [];  // holder for the duplicates
$prev = 0; // previous number
sort($numbers); // sorted them now, so the loop is one-time only

foreach($numbers as $num) {
   if ($prev == $num) {
      $holder[$num] = $num;
      /*I put the $num as index of the array so any double occurrence will overwrite any similar one, to avoid dupes on the $holder that would have compelled me to scan it again.*/
   }
   $prev = $num;  // assign the current number so on the next iteration
                  // i will compare with the next
}

echo implode(',', $holder); //print them out comma separated

I'm not sure if this is an optimal way or could be optimized / made better further. I'm guessing it's an \$O(n)\$ algorithm but again, I admit I have poor theoretical knowledge...

EDIT

My mistake, the requirements were for results sorted, I'm sorry for not pointing it out (I thought I did)


texts: there are a better solutions to set FIELDS as data at ADODB query from xls file (exported from SAP)

texts:
My excel program import from another workbook, exported from SAP, some columns to update my dashboard.

To do this I use ADODB, the code run right and fast (26K rows and 32 columns on 00:00:26:1226).

But I see that some columns with data/time aren't correctly formatted, the poblem is that not all date columns just some, I think are a Sap problem, but i get this file from customer and it will my problem.

So, this are my query without any custom format, just extraction:

cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & WsFrom.FullName & "; Extended Properties=""Excel 8.0;HDR=Yes;"";"

SELECT '1.1' as IdKpi, [(06)-Data creazione]*1 as DateCreation,  '' as Divisione,
[(01-A)-Ordine d'acquisto] as Orders,
switch([(07)D-Modalità Trasp] = 'AOG','AOG',
[(07)D-Modalità Trasp] <> 'AOG','STD') as Trasporto,
[(07)-Fine carico att] as StartDateSap,
[(07)-Ora attfine car] as StartTimeSap,
[(01-A)-Data di reg] as EndDateSap, [(01-A)-Ora di acquisizione] as EndTimeSap,
[(07)-Inizio trasp att] as StartDateBlock,
[(07)-Ora attinizio trasp] as StartTimeBlock,
[(07)-Data FINE Sdoganamento] as EndDateBlock,
[(07-A)-Sdogan-Fine-EffOra] as EndTimeBlock,
[(02)-Utente] as Users, [(06-A)-Blocco-In-Data] as DateBlockIn,
[(07)-Tipo di trasporto] as DoganaTax1,
[(09-A)-Controllo conferma] as DoganaTax2,
from [Sheet1$];

rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdText
rs.MoveFirst
dbSh.Range("A2").CopyFromRecordset rs

this is the 1th test, I updated code (I change [data/time_Field] as customName to Cdate([data/time_Field]) as customName.
the update show me all data/time fields like as data/time the qry run on 00:01:08:128

cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & WsFrom.FullName & "; Extended Properties=""Excel 8.0;HDR=Yes;"";"

SELECT '1.1' as IdKpi, [(06)-Data creazione]*1 as DateCreation,  '' as Divisione,
[(01-A)-Ordine d'acquisto] as Orders,
switch([(07)D-Modalità Trasp] = 'AOG','AOG',
[(07)D-Modalità Trasp] <> 'AOG','STD') as Trasporto,
[(07)-Fine carico att]*1 as StartDateSap,
[(07)-Ora attfine car] as StartTimeSap,
[(01-A)-Data di reg]*1 as EndDateSap, [(01-A)-Ora di acquisizione] as EndTimeSap,
[(07)-Inizio trasp att]*1 as StartDateBlock,
[(07)-Ora attinizio trasp] as StartTimeBlock,
[(07)-Data FINE Sdoganamento]*1 as EndDateBlock,
[(07-A)-Sdogan-Fine-EffOra] as EndTimeBlock,
[(02)-Utente] as Users, [(06-A)-Blocco-In-Data]*1 as DateBlockIn,
[(07)-Tipo di trasporto]*1 as DoganaTax1,
[(09-A)-Controllo conferma]*1 as DoganaTax2,
from [Sheet1$];

rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdText
rs.MoveFirst
dbSh.Range("A2").CopyFromRecordset rs

this is the 2th test, I updated code (I change [data/time_Field] as customName to [data/time_Field]*1 as customName.
the update show me all date fields like as data/time the qry run on 00:00:44:1244

cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & WsFrom.FullName & "; Extended Properties=""Excel 8.0;HDR=Yes;"";"

SELECT '1.1' as IdKpi, [(06)-Data creazione]*1 as DateCreation,  '' as Divisione,
[(01-A)-Ordine d'acquisto] as Orders,
switch([(07)D-Modalità Trasp] = 'AOG','AOG',
[(07)D-Modalità Trasp] <> 'AOG','STD') as Trasporto,
[(07)-Fine carico att]*1 as StartDateSap,
[(07)-Ora attfine car] as StartTimeSap,
[(01-A)-Data di reg]*1 as EndDateSap, [(01-A)-Ora di acquisizione] as EndTimeSap,
[(07)-Inizio trasp att]*1 as StartDateBlock,
[(07)-Ora attinizio trasp] as StartTimeBlock,
[(07)-Data FINE Sdoganamento]*1 as EndDateBlock,
[(07-A)-Sdogan-Fine-EffOra] as EndTimeBlock,
[(02)-Utente] as Users, [(06-A)-Blocco-In-Data]*1 as DateBlockIn,
[(07)-Tipo di trasporto]*1 as DoganaTax1,
[(09-A)-Controllo conferma]*1 as DoganaTax2,
from [Sheet1$];

rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdText
rs.MoveFirst
dbSh.Range("A2").CopyFromRecordset rs

So, my workaround work fine, for me is slow and I'm not sure that is a good code, there are a better way?


texts: How to prevent SQL injection PHP and MySQL?

texts:
I have been reading about SQL injection and I want to secure my code.

I am not asking anyone to write me a code, but I just want to learn it in simple terms.  The best way for me to learn is to edit my code so I can compare them.

<?php
if (isset ($_POST['email']))  {
    //Connect to the database through our include
    include_once "config/connect.php";
    $email = stripslashes($_POST['email']);
    $email = strip_tags($email);
    $email = mysqli_real_escape_string($db_conx, $email);
    $password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
    $password = md5($password);
    // Make query and then register all database data that -
    // cannot be changed by member into SESSION variables.
    // Data that you want member to be able to change -
    // should never be set into a SESSION variable.
    $sql = "SELECT * FROM members WHERE email='$email' AND password='$password'";
    $query = mysqli_query($db_conx, $sql);
    $login_check = mysqli_num_rows($query);
    if($login_check > 0){
        while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
            // Get member ID into a session variable
            $id = $row["id"];
            session_register('id');
            $_SESSION['id'] = $id;
            // Get member username into a session variable
            $username = $row["username"];
            $email = $row["email"];
            $password = $row["password"];
            $firstname = $row["firstname"];
            $lastname = $row["lastname"];
                    session_register('username');
            session_register('firstname');
            session_register('lastname');
            // Update last_log_date field for this member now
            $sql = "UPDATE members SET lastlogin=now() WHERE id='$id'";
            $query = mysqli_query($db_conx, $sql);
            // Print success message here if all went well then exit the script
            header("location: members/index.php?id=$id");
            exit();
        } // close while
    } else {
    // Print login failure message to the user and link them back to your login page
    header("location: login.php");
        exit();
    }
}
?>


texts:
I have a simple task of creating a simple lotto game to practice python. I had some troubles with return of functions so i dropped few because of not understanding the scopes maybe.

In my next version i want to try to make it fully in functions, and in the next version i want to do it in OOP principles.

By posting this code I would like to hear maybe some suggestions where my logic was wrong and some PEP comments.

Game rules

Each player is given 15 numbers, in increasing order. This is why i use sorted() on the lists of player and computer. Also there is a common list with numbers in it from 1 to 90.

A random number is picked and removed from this list and printed to players. The player who has this number in his card crosses it out or skips its turn.  This continues until either player or computer crosses out all his numbers, or for some strange reason they are out of numbers :) I think in other parts of the world it is also called BINGO but I might be wrong.

import random

number_pool = list(range(1, 91))
computer_card = random.sample(number_pool, 15)
computer_card_sorted = sorted(computer_card)
player_card = random.sample(number_pool, 15)
player_card_sorted = sorted(player_card)

def display_cards():
    print("Computer card:\n")
    print(computer_card_sorted)
    print("====================================")
    print("Player card:\n")
    print(player_card_sorted)

def lotto_choice():
    choice = random.choice(number_pool)
    number_pool.remove(choice)
    return choice

def the_game():
    while number_pool:
        choice = lotto_choice()
        print("The random lotto is: " + str(choice))
        display_cards()
        cross_number = input("Do you want to cross out a number")
        cross_number.lower()
        if cross_number == "y":
            if choice in player_card_sorted:
                player_card_sorted.remove(choice)
            elif choice in computer_card_sorted:
                computer_card_sorted.remove(choice)
        if cross_number == "n":
            if choice in computer_card_sorted:
                computer_card_sorted.remove(choice)
            else:
                continue
    else:
        if len(player_card_sorted) == 0:
            print("Congratulations Player ! You won")
        elif len(computer_card_sorted) == 0:
            print("The computer have won, too bad !")
        else:
            print("It is a tie you both ran out of numbers, very straange !")

the_game()


texts:
I had time measuring pretty much figured out when I ended up using this structure.

#include <iostream>
#include <chrono>

template<typename TimeT = std::chrono::milliseconds>
struct measure
{
    template<typename F>
    static typename TimeT::rep execution(F const &func)
    {
        auto start = std::chrono::system_clock::now();
        func();
        auto duration = std::chrono::duration_cast< TimeT>(
            std::chrono::system_clock::now() - start);
        return duration.count();
    }
};

a use case would be

struct functor
{
    int state;
    functor(int state) : state(state) {}
    void operator()() const
    {
        std::cout << "In functor run for ";
    }
};

void func()
{
    std::cout << "In function, run for " << std::endl;
}

void func(int arg) {}

int main()
{
    int dummy(1);

    std::cout << measure<>::execution( [&]() {
        func(dummy);
    }) << std::endl;

    std::cout << measure<>::execution(functor(dummy)) << std::endl;
std::cout << measure<>::execution(func);

    return 0;
}

But since I started using my struct in various posts on Stack Exchange sites, I've had remarks and comments about the code (like on func being a const ref or not etc).

I'd like a review on the above and your suggestions on how I can approve this code (or leave it alone at last).


texts: Generating absolute URIs behind a reverse proxy

texts:
In my ASP.NET MVC application there are occasions where I need to generate an absolute URI, such as when sending an email confirmation link to a user. The most straightforward approach is to use UrlHelper.Action() with the protocol parameter, and this has worked well for me.

However, now my server is behind a reverse proxy, so the absolute URIs that I'm generating are pointing to backendserver.myorg.local instead of publicsite.example.com, and that's not good for business.

So, I wrote this method to inspect the Origin header. Do you see any security problems or other reasons this might not be a good solution?

static class UrlHelperExtensions
{
    private const string OriginHeader = "Origin";

    /// <summary>
    /// Generates a full absolute URI, with HTTP(S), host name, and everything. Is reverse-proxy-aware,
    /// so will generate public URIs in the event that our server is behind a reverse proxy.
    /// </summary>
    /// <param name="urlHelper"></param>
    /// <param name="actionName"></param>
    /// <param name="controllerName"></param>
    /// <param name="routeValues"></param>
    /// <returns></returns>
    public static string AbsoluteAction(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues = null)
    {
        if (urlHelper == null)
            throw new ArgumentNullException(nameof(urlHelper), $"{nameof(urlHelper)} is null.");

        var protocol = urlHelper.RequestContext.HttpContext.Request.Url.Scheme; // Should be "http" or "https"
        var localUriString = urlHelper.Action(actionName, controllerName, routeValues, protocol);

        var originValues = urlHelper.RequestContext.HttpContext.Request.Headers.GetValues(OriginHeader)
            .Where(x => !String.IsNullOrWhiteSpace(x))
            .ToList();

        if (!originValues.Any())
            return localUriString; // We are NOT behind a reverse proxy. Easy peasy, return local URI.

        var originUriString = originValues.First(); // There should only be only 1 Origin header, but theoretically it's possible to have more than 1.
        var originUri = parseOriginUri(originUriString);

        var uriBuilder = new UriBuilder(localUriString);
        uriBuilder.Scheme = originUri.Scheme; // AKA "protocol" (http or https)
        uriBuilder.Host = originUri.Host;
        uriBuilder.Port = originUri.Port;

        return uriBuilder.ToString();
    }

    private static Uri parseOriginUri(string originText)
    {
        try
        {
            return new Uri(originText);
        }
        catch (UriFormatException ex)
        {
            throw new UriFormatException($"{OriginHeader} header URI is in an invalid format: \"{originText}\"", ex);
        }
    }
}

Note: Right now I don't have any requirements to actually manipulate the URL path.


texts: Multi-client TCP server with a thread for each client and DB connection pool

texts:
I'm creating a Qt TCP (with SSL) server to which multiple clients should connect and use the DB, and this is the main task. So, I think I can use this architecture: each client has its own thread, and clients use DB via DB connection pool.

Client connection part

main.cpp:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyServer server;

    server.listen(QHostAddress::Any, 1234);

    return a.exec();
}

myserver.h:

class MyServer : public QTcpServer
{
    Q_OBJECT

    explicit MyServer(QObject *parent = 0);
    ~MyServer();

protected:
    void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;

signals:
    void stopAll();
};

myserver.cpp:

MyServer::MyServer(QObject *parent) : QTcpServer(parent)
{
    //...
}

MyServer::~MyServer(){
    emit stopAll();
}

void MyServer::incomingConnection(qintptr socketDescriptor){
    QThread* clientThread = new QThread;
    MyClient *client = new MyClient(socketDescriptor, this);

    client->moveToThread(clientThread);

    connect(clientThread, SIGNAL(started()), client, SLOT(process()));

    connect(client, SIGNAL(finished()), clientThread, SLOT(quit()));
    connect(this, SIGNAL(stopAll()), client, SLOT(stopFromServer()));
    connect(client, SIGNAL(finished()), client, SLOT(deleteLater()));
    connect(clientThread, SIGNAL(finished()), clientThread, SLOT(deleteLater()));

    clientThread->start();
}

myclient.h:

class MyClient : public QObject
{
    Q_OBJECT
public:
    explicit MyClient(int socketDescriptor, MyServer *server);
    ~MyClient();

private:
    QSslSocket* socket = NULL;

public slots:
    void process();
}

myclient.cpp:

void MyClient::process(){
    //typical connection things
    connect(this->socket, SIGNAL(encrypted()), this, SLOT(ready()));
}

void MyClient::ready(){
    connect(socket,SIGNAL(readyRead()),this, SLOT(newData()));
}

DB connection pool part

DAO which will be executed in the client threads:

.cpp:

//DAO method

QList<QMap<QString, QString>> sqlResult = DatabaseService::executeQuery(sqlCommand);

//sqlResult processing

DatabaseService:

.h:

class DatabaseService
{
public:
    //...
    static QMap<QString, QString> executeQuery(QString command);

private:
    static QThreadStorage<QSqlDatabase> mDatabasePool;
    static QSqlDatabase getDatabase();

};

.cpp:

//...
QThreadStorage<QSqlDatabase> DatabaseService::mDatabasePool;

QSqlDatabase DatabaseService::getDatabase()
{
    if(DatabaseService::mDatabasePool.hasLocalData()) {
        return DatabaseService::mDatabasePool.localData();
    } else {
        auto database = QSqlDatabase::addDatabase("QPSQL", QUuid::createUuid().toString());
        database.setHostName("hostName");
        database.setDatabaseName("databaseName");
        database.setUserName("user");
        database.setPassword("password");
        database.open();
        DatabaseService::mDatabasePool.setLocalData(database);
        return database;
    }
}

QMap<QString,QString> DatabaseService::executeQuery(QString command){

    QSqlQuery query (DatabaseService::getDatabase());
    query.exec(command);

    //...

    return result;
}

//...

This is all the code related to the subject.

You also can check my SO question about DB connection pool (please note that the code is not exactly the same).

So, how good is this architecture? What could be fixed and improved and how?


texts:
In my code, I need to flatten a two-dimensional std::array into a one-dimensional one at compile time. While writing the code I realized, that I am unsure about several aspects of my implementation (as far as readability is concerned).
Therefore I would really appreciate your input!
I am especially unsure, if

There is a more obvious / simpler version in which I can achieve my goal (I previously thought of expanding multiple parameter packs with one ... or the like)
if using a nested lambda is a good idea (I do this in order to obtain access to the parameter pack created by the integer_sequence and not expose this API)
If using the requires expression is really more readable than using a std::enable_if_t in this use case
and, even if I kind of like my solution to this problem, whether there is a cleaner way of

having automatic template parameter deduction for the "exposed" API
having access to sizes and type of the nested array

If there are other things I can improve with my code

#include <array>
#include <iostream>

/// Helper struct, which is std::false_type if the type is not a nested array, and otherwise holds
/// inner and outer array sizes.
template<typename Arr> struct NestedArray : std::false_type{};
template <std::size_t sizeOuter, std::size_t sizeInner, typename T>
struct NestedArray<std::array<std::array<T, sizeInner>, sizeOuter>> : std::true_type{
  static constexpr auto outer = sizeOuter;
  static constexpr auto inner = sizeInner;
  using type = T;
};

/// Return #nestedArray.flatten()[#index].
template <auto nestedArray, std::size_t index,
          typename = std::enable_if_t<NestedArray<std::decay_t<decltype(nestedArray)>>::value>>
consteval auto getValueByIndex() noexcept {
  using NestedArrayHelper = NestedArray<std::decay_t<decltype(nestedArray)>>;
  constexpr std::size_t innerIndex = index % NestedArrayHelper::inner;
  constexpr std::size_t outerIndex = index / NestedArrayHelper::inner;
  static_assert(NestedArrayHelper::inner > innerIndex &&
                    NestedArrayHelper::outer > outerIndex, "Index out of bounds.");
  return std::get<innerIndex>(std::get<outerIndex>(nestedArray));
}

/// Return 1-dimensional array #nestedArray.flatten() from 2-dimensional array #nestedArray.
/// @param nestedArray:   two-dimensional std::array (std::array<std::array<T, I>, O>)
/// @return               flat representation of #nestedArray (std::array<T, I * O>) with
///                       nestedArray[o][i] = result[i + I * o]
template <auto nestedArray>
requires requires() { requires NestedArray<std::decay_t<decltype(nestedArray)>>::value; }
consteval auto flattenNestedArray() noexcept {
  using NestedArrayHelper = NestedArray<std::decay_t<decltype(nestedArray)>>;
  using ContainedType = typename NestedArrayHelper::type;

  constexpr std::size_t flatSize = NestedArrayHelper::outer * NestedArrayHelper::inner;
  return []<std::size_t... ix>(std::index_sequence<ix...>) consteval noexcept {
    return std::array<ContainedType, flatSize> {getValueByIndex<nestedArray, ix>()...};
  }(std::make_index_sequence<flatSize>());
}

// Test, only for demonstrating the purpose of the code.

/// 2d array
constexpr std::array<std::array<int, 2>, 3> arrayOfPairs{{{1, 2}, {3, 4}, {15, 16}}};

/// Resulting 1d array
constexpr auto flatArray = flattenNestedArray<arrayOfPairs>();

// Test: Print out the resulting 1d array
int main () {
  for (std::size_t i = 0; i < 6; ++i) { std::cout << flatArray[i] << " "; } std::cout << std::endl;
}

I hope that this is appropriate for a Code Review, I linked the code in compilerExplorer. Note that it can only be compiled with gcc trunk, as clang trunk does not allow std::array as non-type template argument.
Thanks a lot :)


texts: Data flow anomaly: how to do it correct?

texts:
I am modifying Volley for Android a bit and Findbugs complains about the data flow and I am a bit lost. First the code:

String userAgent;
try {
    String packageName = getPackageName();
    PackageInfo info = getPackageManager().getPackageInfo(packageName, 0);
    userAgent = packageName + "/" + info.versionCode; // DD
} catch (PackageManager.NameNotFoundException e) {
    userAgent = "volley/0";
}

HttpStack stack;
if (Build.VERSION.SDK_INT >= 9) {
    stack = new HurlStack();
} else {
    stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}

So I thought that findbugs would differ between definition and declaration of a variable which should make the DD gone.

I also tried to predefine the userAgent with the content from the catch but an empty catch is bad practice as well. Also findbugs just complains with the data flow anomalies just on different places...

So what would be a good solid way to prevent the findbugs reports?


texts:
I'm a beginner and I have a question (somehow silly and stupid :) ).  Today I decided to challenge myself and I came around the challenge that wanted me to create a program that ciphers (or encrypts) the message using the substitution cipher method.  I solved the challenge by myself but mine is way different than the solution itself. I just want to know which one is better and why? And also is there anything I missed in my own code?

So here is the code I've written:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string secretMessage {};
    string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    string key {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
    cout << "Enter your secret message: ";
    getline(cin, secretMessage);
    //Encryption
    for(size_t i{0}; i<secretMessage.length(); ++i){
        for(size_t j{0}; j<alphabet.length(); ++j){
            if (secretMessage.at(i) == alphabet.at(j)){
                secretMessage.at(i) = key.at(j);
                break;
            }
        }
    }
    cout << "Encrypting The Message..." << endl;
    cout << "Encrypted Message: " << secretMessage << endl;
    //Decryption
    for(size_t i{0}; i<secretMessage.length(); ++i){
        for(size_t j{0}; j<key.length(); ++j){
            if (secretMessage.at(i) == key.at(j)){
                secretMessage.at(i) = alphabet.at(j);
                break;
            }
        }
    }
    cout << "\nDecrypting The Encryption..." << endl;
    cout << "Decrypted: " << secretMessage << endl;
    return 0;
}

And here is the solution:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string secretMessage {};
    string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    string key {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
    string encryptedMessage {};
    string decryptedMessage {};
    cout << "Enter your secret message: ";
    getline(cin, secretMessage);
    cout << "\nEncrypting Message..." << endl;
    //Encryption
    for(char c:secretMessage){
        size_t position = alphabet.find(c);
        if (position != string::npos){
            char newChar {key.at(position)};
            encryptedMessage += newChar;
        } else{
            encryptedMessage += c;
        }
    }
    cout << "Encrypted Message: " << encryptedMessage << endl;
    //Decryption
    cout << "\nDecrypting Message..." << endl;
    for(char c:encryptedMessage){
        size_t position = key.find(c);
        if (position != string::npos){
            char newChar {alphabet.at(position)};
            decryptedMessage += newChar;
        } else{
            decryptedMessage += c;
        }
    }
    cout << "Decrypted Message: " << decryptedMessage << endl;
    return 0;
}

Note:I have also included the decryption part too


texts: Processing selected and deselected elements

texts:
I think that this code is very bad because it does not agree with DRY principle. Can you advise me how to improve it?

public void WhatSelected(object paramaters)
    {
        string ElementToProcess = BASM.FindElement(paramaters, true);

        SeleсtedCurrent.Add(ElementToProcess);

        int i = (from x in AssetSelectorCollection where x.IsChecked == true select x).Count();
        if (i >= state)
        {
            foreach (BinaryAssetSelector item in AssetSelectorCollection)
            {
                if (item.IsChecked == false) { item.IsEnable = false; item.IsChecked = false; }
            }
        }
        if (state != 1)
        {
            foreach (BinaryAssetSelector item in AssetSelectorCollection)
            {
                if (item.IsChecked == true && item.IsEnable == false)
                {
                    item.IsEnable = true;
                }
            }
        }
        Messenger.Default.Send<BinarySelectorCommunicator>(new BinarySelectorCommunicator { SelectedIN = SeleсtedCurrent });
    }

    public void WhatDeSelected(object param)
    {
        string ElementToProcess = BASM.FindElement(param, false);

        SeleсtedCurrent.Remove(ElementToProcess);

        int i = (from x in AssetSelectorCollection where x.IsChecked == true select x).Count();
        if (i <= state)
        {
            foreach (BinaryAssetSelector item in AssetSelectorCollection)
            {
                if (item.IsEnable == false)
                {
                    item.IsEnable = true;
                }
            }
        }
        if (state != 1 && i == 1)
        {
            foreach (BinaryAssetSelector item in AssetSelectorCollection)
            {
                if (item.IsChecked == true)
                {
                    item.IsEnable = false;
                }
            }
        }
        Messenger.Default.Send<BinarySelectorCommunicator>(new BinarySelectorCommunicator { SelectedIN = SeleсtedCurrent });
    }


texts:
I solved this leetcode problem.

The question is.

  Implement pow(x, n).

This is my solution.

class Solution {
public:
    double doPow(double x, unsigned int n)
    {
        double result = 1;
        while(n > 0)
        {
            if(n & 1) // if bit is set
            {
                result = result * x;
            }
            n = n >> 1;
            x = x * x;
        }
        return result;
    }
    double myPow(double x, int n) {
        unsigned int temp = abs(n);
        if(n < 0)
        {
            return 1/doPow(x, temp);
        }
        return doPow(x,n);
    }

};

Although this solution gets accepted, it converts n to unsigned to make sure that INT_MIN doesn't overflow when it is converted to it's positive values and then computed.

Is there a better way to handle negative exponents?


texts: Sorting cards by suit and value using Shell Sort

texts:
The question description: put a deck of cards in order by suit (in the order spades, heart, clubs, diamonds) and by rank within each suit, with the restriction that the card must be laid out face down in a row, and the only allowed operations are to check the values of two cards and to exchange two cards (keeping them face down).

My solution:

from enum import Enum
import random

class Suit(Enum):
    __order__ = "spade heart club diamond"
    spade = 1
    heart = 2
    club = 3
    diamond = 4

class Card(object):
    def __init__(self, suit, value):
        assert type(suit) == Suit
        assert value > 0 and value < 14
        self._suit = suit
        self._value = value
        self.value = self._get_value()

    def _get_value(self):
        return self._suit.value * 13 + self._value

    def __lt__(self, other):
        return self.value < other.value

    def __str__(self):
        return str((self._suit.name, self._value))

cards = []

for s in Suit:
    for i in range(13):
        cards.append(Card(s, i+1))

random.shuffle(cards)

def shell_sort(cards):
    h = 1
    while(h<52/3):
        h = 3*h + 1
    # h = 30
    # should be more than 29?
    while(h>0):
        for k in range(h, 52):
            j = k
            while(j >= h and cards[j] < cards[j-h]):
                cards[j], cards[j-h] = cards[j-h], cards[j]
                j -= h
        h = int(h / 3)
    return cards

sorted_cards = shell_sort(cards)

for c in sorted_cards:
    # how to consider the suit, can the suit decrease the compare times?
    print(c)

I think this can be further optimized since there should be no compares among different suits. Can that be integrated in the shell sort without firstly rank the suits (then the values inside)?


texts:
I'm newbie in Python and I wrote a tool called Caesar Encryption Tool. At the moment it only encrypts. It takes a plain text and a key from the user then encrypts the plain text using the key. How can this code be improved?

# This is version 1.0 Caesar Encryption Tool and it will be improved.
# This tool is written by Mahmoud Naguib.
# My facebook account is at : https:\\www.facebook.com\naguibarea
# This is letters table.
lettersTable = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# This line takes the user's key it's 3 by default.
key = int(input('Enter your key : '))
# This line takes the user's plain text and converts it
#  to uppercase to search for it in the English alphabet.
plainText = input('Enter your plain text : ').upper()
for letter in range(len(plainText)):
    # If there is a letter which isn't alphabet like numbers,
    #  special characters and spaces it will be appended to the list.
    if plainText[letter] not in lettersTable:
        lettersTable.append(plainText[letter])
    # This line locates the plain letter's numeric value in other words its    position.
    position = lettersTable.index(plainText[letter])
    # This line adds the key entered by the user to the plain letter's
    #  numeric value to reach the new encrypted letter.
    step = position + key
    # if the encrypted letter's numeric value is greater than 25
    #  then its new numeric value is the old numeric valuu %
    #  the number of English alphabet letters.
    if step > 25:
        step %= 26
    # If position is greater than 25 that means it's not an alphabet
    #  value and it will be printed without adding the key.
    if position > 25:
        step = position
    # This line locates the encrypted letter's numeric value in other words
    #  its position and prints the encrypted letter.
    # end is a keyword argument to combine all letters together.
    print(lettersTable[step], end='')


texts:
I have the following code where I need to execute 2 Linq-to-SQL statements. If I do not have the Any() in the if statement, then I receive error when the result is no data. However, I am not sure if my approach is efficient enough. Do you have any suggestions?

My goal is to achieve the following with single Linq statement. I need to get the Sum, and get 0 if there are no results.

 if (db.BadgeAssignments.Any(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId))
 {
      currUserScore = db.BadgeAssignments
                        .Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)
                        .Sum(bba => bba.BadgeAssociated.Points);
 }


texts: Does my Game class have too many responsibilities?

texts:
I've been working on a game so as to fill out something that I can put on a CV and I was writing the main Game class. This shouldn't be a god class, but it should simply be a class that ties together the "wiring" of the game, i.e, it should start listening for input events and should start the game loop and wire any inputs to the associated handlers.

/**
 * The main class for the Game.
 * This class should start the game loop as well as display updates.
 * @author Dan
 *
 */
public class Game implements Disposable {
    private final DisplayWindow _display;
    private final Disposable _displayUpdates;
    private final Scheduler _scheduler;

    /**
     * Create the Game.
     * @param displayService - the service to use for the Display
     * @param width - the initial width of the display
     * @param height - the initial height of the display
     */
    public Game(Scheduler gameScheduler, DisplayWindow displayWindow) {
        _display = displayWindow;
        _scheduler = gameScheduler;

        // Wait for the display to open correctly
        try {
            if(!_display.isOpen().get(500, TimeUnit.MILLISECONDS)) {
                System.err.println("failed to initialize OpenGL display!");
                System.exit(2);
            }
        } catch (Exception e) {
            System.err.println("OpenGL took too long to respond!");
            e.printStackTrace(System.err);
            System.exit(1);
        }

        // schedule display to update @ 60 fps
        int frameInterval = (int) ((1f / displayWindow.getTargetFramesPerSecond()) * 1000f);
        _displayUpdates = _scheduler.schedule(() -> displayWindow.update(), frameInterval);

    }

    public void startGameLoop() throws InterruptedException {
        while(true) {

            // Check to see if the window is closed
            // Bear in mind it's OK to wait here because
            // if it takes way too long we can assume that
            // openGL has stopped responding
            try {
                if(_display.isClosing().get(500, TimeUnit.MILLISECONDS)) {
                    break;
                }
            } catch (Exception e) {
                // Terminate
                System.err.println("OpenGL took too long to respond!");
                e.printStackTrace(System.err);
                System.exit(1);
            }
            Thread.sleep(1);
        }
    }

    public void dispose() {
        _display.dispose();
        _displayUpdates.dispose();
    }
}

Here are a few signatures you might want to know while reviewing:

Future<bool> _display.isOpen()
Future<bool> _display.isClosing()
Disposable _scheduler.schedule(...)

Obviously the while(true) { Thread.sleep(1); } needs some changing so it actually has a legitimate timestep.

I just wanted to get this out of the way before writing an entire application based on this class doing the functionality it does.


texts:
i just wanted to confirm if my codes below is correct. Feel free to make corrections.

<?php
class createConnection
{
var $host="localhost";
var $username="root";
var $password="";
var $database="wilbert";
var $myconn;

function connectToDatabase()
{
$conn = mysql_connect($his->host,$this->username,$this->password);
if (!$conn)
{
    die ("Cannot connect to the database");
}

else
{
    $this->myconn = $conn;
    echo "Connection established!";
}
return $this->myconn;

}
function selectDatabase()
{
mysql_select_db($this->database);
if(mysql_error())
{

    echo "Cannot find the database ".$this->database;
}
else
{
echo "Database selected..";
}

}
function selectData()
{
mysql_select_db($this->database);

$result = mysql_query(" SELECT a.student_id, a.FirstName, b.First_Name FROM Student a        LEFT JOIN teacher b ON a.student_id = b.student_id");

echo "

Student_ID
First_Name
First_Name

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['student_id']. "	";
  echo "" . $row['FirstName'] . "	";
  echo "" . $row['First_Name'] . "	";
  //echo "" . $row['student_id'] . "	";
  echo "
";
  }
echo "
";
}

function closeConnection()
{
mysql_close($this->myconn);
echo "connection closed!";
}

}
?>

and here is my object.

<?php

include ('phpclass.php');

$connection = new createConnection(); //i created a new object

$connection->connectToDatabase(); // connected to the database

echo "
"; // putting a html break

$connection->selectDatabase();

echo "
";

$connection->selectData();
//$connection->closeConnection();// closed connection
?>


texts: How object oriented is my Crazy Eights game?

texts:
I have this Crazy Eights game (which at the moment does not include crazy cards):

class Card(object):
    RANKS = ("2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A")
    SUITS = ("c", "d", "h", "s")

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return self.rank + self.suit

    def __eq__(self, other):
        return self.rank == other.rank and self.suit == other.suit

    def canPlayOn(self, other):
        return self.rank == other.rank or self.suit == other.suit

class Hand(object):
    def __init__(self):
        self.cards = []

    def __str__(self):
        return " ".join([str(card) for card in self.cards])

    def __bool__(self):
        return bool(self.cards)

    def give(self, other, card):
        self.remove(card)
        other.add(card)

    def add(self, card):
        self.cards.append(card)

    def remove(self, card):
        self.cards.remove(card)

class Pile(Hand):
    @property
    def topCard(self):
        return self.cards[-1]

class DrawPile(Pile):
    def populate(self):
        for rank in Card.RANKS:
            for suit in Card.SUITS:
                self.add(Card(rank, suit))

    def deal(self, others, cards = 7):
        import random
        random.shuffle(self.cards)
        for _ in range(cards):
            for hand in others:
                self.give(hand, self.topCard)

class Player(Hand):
    def playMove(self, discardPile, drawPile):
        card = self.getCard(discardPile.topCard)
        self.give(discardPile, card) if card else \
                               drawPile.give(self, drawPile.topCard)

    def getCard(self, topCard):
        card = input("This is your hand: " + str(self) +
                     ". The is the top card: " + str(topCard) +
                     ". Enter your card (enter PU to pick up a card): ")
        while self.isInvalid(card, topCard):
            card = input("Invalid input. Enter your card: ")
        return Card(card[0], card[1]) if card != "PU" else None

    def isInvalid(self, card, topCard):
        if card == "PU":
            return False
        elif len(card) != 2 or card[0] not in Card.RANKS or \
           card[1] not in Card.SUITS or \
           Card(card[0], card[1]) not in self.cards or \
           not Card(card[0], card[1]).canPlayOn(topCard):
            return True
        return False

class Computer(Hand):
    def playMove(self, discardPile, drawPile):
        card = self.getCard(discardPile.topCard)
        if card:
            self.give(discardPile, card)
            print("Computer plays " + str(card), end = ". ")
        else:
            drawPile.give(self, drawPile.topCard)
            print("Computer picks up.", end = " ")
        print("Computer has " + str(len(self.cards)) + " cards remaining.")

    def getCard(self, topCard):
        for card in self.cards:
            if card.canPlayOn(topCard):
                return card
        return None

def main():
    drawPile = DrawPile()
    drawPile.populate()
    player = Player()
    computer = Computer()
    playerList = [player, computer]
    drawPile.deal(playerList)
    discardPile = Pile()
    drawPile.give(discardPile, drawPile.topCard)
    playerIndex = 0
    while isStillPlaying(playerList):
        playerList[playerIndex].playMove(discardPile, drawPile)
        if playerIndex < len(playerList) - 1:
            playerIndex += 1
        else:
            playerIndex = 0
    print("Computer wins!" if player else "You win!")

def isStillPlaying(playerList):
    for player in playerList:
        if not player:
            return False
    return True

if __name__ == "__main__":
    main()

Can someone provide a code review (particularity on my OOP skills)? Also, what would be the most object oriented way to implement "crazy cards"?


texts:
I have created some code to split strings. The code will split the given string by the given delimiter into an array which is inside a struct it returns.

I am using strtok to do the actual tokenizing, but in my code the original string will not be changed.

split.h

#ifndef SPLIT_H
#define SPLIT_H

#ifdef __cplusplus
extern "C" {
#endif

    struct splitString {
        char **tokens;
        unsigned total;
        unsigned size;
    };

    struct splitString *split(const char *, const char *);
    void splitFree(struct splitString **);

#ifdef __cplusplus
}
#endif

#endif /* SPLIT_H */

split.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "split.h"

#define DEFAULT_TOKEN_SIZE 10

static struct splitString* initSplitString() {
    struct splitString *s = malloc(sizeof (struct splitString));

    if (s) {
        s->total = 0;
        s->size = DEFAULT_TOKEN_SIZE;
        s->tokens = malloc(sizeof (char *) * DEFAULT_TOKEN_SIZE);

        for (int i = 0; i < DEFAULT_TOKEN_SIZE; i++) {
            s->tokens[i] = NULL;
        }

        return s;
    }

    return NULL;
}

/**
 * Adjust the size of the tokens variable if necessary
 * @param s
 */
static void adjustSize(struct splitString *s) {
    if (s->total == s->size) {
        s->size += DEFAULT_TOKEN_SIZE;

        char **temp_tokens = realloc(s->tokens, sizeof (char *) * s->size);

        if (temp_tokens) {
            s->tokens = temp_tokens;
        }
    }
}

static void clearAndCopy(char *destination, const char *source, unsigned size) {
    memset(destination, 0, size);
    memcpy(destination, source, size);
}

struct splitString* split(const char *string, const char *delimiter) {
    unsigned size = strlen(string) + 1;
    char tmp[size];
    char *token = NULL;
    struct splitString *s = initSplitString();

    if (s == NULL) {
        goto error;
    }

    clearAndCopy(tmp, string, size);

    token = strtok(tmp, delimiter);

    while (token != NULL) {
        int bsize = strlen(token) + 1;

        s->tokens[s->total] = malloc(bsize);

        if (s->tokens[s->total]) {
            clearAndCopy(s->tokens[s->total], token, bsize);
        }
        else {
            splitFree(&s);
            goto error;
        }

        s->total++;

        adjustSize(s);
        token = strtok(NULL, delimiter);
    }

    return s;

error:

    return NULL;
}

/**
 * Clear all token and the splitString
 * @param s
 */
void splitFree(struct splitString **s) {
    for (int i = 0; i < (*s)->total; i++) {
        free((*s)->tokens[i]);
        (*s)->tokens[i] = NULL;
    }

    free(*s);
    *s = NULL;
}

Here is just some code I am using to test:

#include <stdio.h>
#include <stdlib.h>
#include "split.h"

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

    char *test_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    struct splitString *test = split(test_string, ",");

    printf("Total: %d\n", test->total);

    for (int i = 0; i < test->total; i++) {
        printf("String: %s\n", test->tokens[i]);
    }

    splitFree(&test);

    return EXIT_SUCCESS;
}


texts: Perl script to print multi line log entries which has a match for given pattern

texts:
I am a Java programmer and very new to Perl. I decided to work on a simple script that could solve a problem I encounter in my day to day work. This script will search the log file for a pattern and print the complete potentially multi line log statement that has a match for this pattern. Additionally, the matched pattern should be displayed in color for highlighting purpose.

I've used very basic features of Perl and as you can see, the code very verbose (like Java some might say ;) ) and there are two main areas I'm aiming to improve:

I want to see Perl's idiomatic ways to make the program less verbose without sacrificing too much readability.
Any poor practice is that I have used. I purpose fully left out "strict" and "warnings" as I want to use Perl for loose and less verbose features.

I'd be really grateful for some feedback to make this more elegant. I'll only be using Perl 5.8 as that is what available on most systems at my place.

#!/usr/bin/env perl

use Term::ANSIColor;

my $pattern = qr"[.a-zA-Z0-9]*Exception";
my $hilight = 'black on_yellow';
my $timestamp = qr"\d\d:\d\d"; #To identify beginning of new log entry.

my $begin = qr/^$timestamp/;

open(my $fn, '<', $ARGV[0]) or die "Could not open file '$ARGV[0]' $!";
while (<$fn>) {
    if ( $_ =~ m/($begin)/ ) {
        if($found) {
            foreach(@fh) {
                if ( $_ =~ m/($pattern)/ ) {
                    $matched = $1;
                    @parts = split /($pattern)/, $_;
                    foreach(@parts) {
                        if ($_ eq $matched) {
                            print colored($matched, $hilight);
                        } else {
                            print $_;
                        }
                    }
                } else {
                    print $_
                }
            }
        }

        if(defined @fh) {
            undef @fh;
        }
        $found = 0;
    }
    if ( $_ =~ m/($pattern)/ ) {
        $found = 1;
    }
    push (@fh, $_);
}

close $fn;


texts:
I often find in codebases something on the order of if (sprockets.Count() > 0) which is easily replaced with LINQ's if (sprockets.Any()). This keeps the entirety of sprockets from having to be iterated over completely (to get the count) then comparing to zero. Further, the business logic often reads something like "if there are any sprockets, inform the user of the subtotal". I also often see similar logic for exactly one of something: if (sprockets.Count() == 1) which doesn't have an easy, low-cost LINQ alternative. So I've created one here:

public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source)
{
    if (source is null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        return enumerator.MoveNext() && !enumerator.MoveNext();
    }
}

Usage is if (sprockets.ExactlyOne()) Here are unit tests. There is one helper method called Infinite() which is a never-ending enumerable, which will baffle sprockets.Count(), but not sprockets.ExactlyOne():

[TestClass]
public sealed class ExactlyOneTests
{
    [TestMethod]
    [ExpectedException(typeof(ArgumentNullException))]
    public void TestNull()
    {
        int[] nullArray = null;

        Assert.IsFalse(nullArray.ExactlyOne());
    }

    [TestMethod]
    public void TestZero()
    {
        int[] zero = Array.Empty<int>();

        Assert.IsFalse(zero.ExactlyOne());
    }

    [TestMethod]
    public void TestOne()
    {
        int[] one = { 1 };

        Assert.IsTrue(one.ExactlyOne());
    }

    [TestMethod]
    public void TestTwo()
    {
        int[] two = { 1, 2 };

        Assert.IsFalse(two.ExactlyOne());
    }

    [TestMethod]
    public void TestInfinite()
    {
        IEnumerable<int> infinite = Infinite();

        Assert.IsFalse(infinite.ExactlyOne());
    }

    private static IEnumerable<int> Infinite()
    {
        while (true)
        {
            yield return 0;
        }
    }
}

Looking for overall review - is the code readable, maintainable, performant. Do the tests cover the expected cases or are there more to consider?


texts: Generate two random primes and find their totient

texts:
I am supposed to make a basic RSA encryption/decryption code, where I am only given e.

I wrote this code to randomly generate two primes and then find their totient.  But the totient is supposed to not be co-prime with e which is given as 65537.  So this code would technically return a good value eventually, but in reality it would take ages.  Please help me speed it up and/or make suggestions on how it can be improved in general.

def primeGen(lim):
    """Generates all primes up to a certain limit (lim)"""
    fnl=[]
    primes=[2]
    p=0
    for n in range(2,lim+1):
        fnl.append(n)
    for v in fnl:
        p=0
        for i in range(2,v):
            if (v%i==0):
                p=1
                break
            if p==0 and i==(v-1):
                primes.append(v)
    return primes

import random
def randomPrimeGen(lim):
    """Generates a single random prime number using primeGen(lim)"""
    M=(len(primeGen(lim))-1)
    randomPrime=(primeGen(lim)[random.randint(int(M/10),M)])
    return randomPrime

def modtot():
    e=65537
    totient=1
    GCD=gcd(e,totient)
    while GCD==1:
        p=randomPrimeGen(30000)
        q=randomPrimeGen(30000)
        n=p*q
        totient=((p-1)*(q-1))
        GCD=gcd(e,totient)
        print(GCD, totient)
    return n, totient


texts: Find max number you can create from an array of numbers

texts:
Was asked this in an interview yesterday:

You are given an array of numbers (not digits, but numbers: e.g. 9, 23, 184, 102, etc.) - you need to construct the largest number from it. For example: you get 21, 2, 10 - the largest number is 22110.

This is my solution, I wonder if you can improve this?

def maximum_number(a):
    work_dict = {
        0: 0,
        1: 0,
        2: 0,
        3: 0,
        4: 0,
        5: 0,
        6: 0,
        7: 0,
        8: 0,
        9: 0
    }

    for ai in a:
        # if ai is a single digit number, just add it
        if ai in work_dict:
            work_dict[ai] += 1
            continue

        # otherwise, decompose it to it's digits
        while ai > 0:
            number = ai % 10
            work_dict[number] = work_dict[number] + 1
            ai = int(ai/10)

    max_num = int('9'*work_dict[9] + '8'*work_dict[8] + '7'*work_dict[7] + '6'*work_dict[6] +
                    '5'*work_dict[5] + '4'*work_dict[4] + '3'*work_dict[3] + '2'*work_dict[2] +
                    '1'* work_dict[1] + '0'*work_dict[0])

    return max_num


texts: Check if multiple lists contain an element from a large external list

texts:
I have a list of lists (many tokenised sentences). For anyone who doesn't know what tokenised sentences are, my list is like so:

list1 = [['hello', 'my', 'name'], ['this', 'is', 'stack', 'exchange'], ... ]

I have a list of key words as well, key_words.

For every sentence in list, I want to check if it is in key_words. Moreover, I want a single method to be applied to each sentence. Below is my working (but inefficient) code:

list1 = [['hello', 'my', 'name'], ['this', 'is', 'stack', 'exchange']]
key_words = ['hello', 'name', 'stack']

def get_features(sentence, key_words):
    return [word for word in sentence if word in key_words]

f = []
for sent in list1:
    f.append(get_features(sent, key_words))

This is fine, but my dimensions are like so:

len(list1) = 45,000
len(key_words) = 35,000

This is of course inefficient, and I would like to find a faster way of doing this. Could dictionaries be utilised in some way? I was thinking of changing key_words from a list to a dictionary of key:value = word:1. Then I could do something like

return [word for word in sentence if key_words[word] does not give error]

but I'm unsure how if does not give error would be implemented. Doing this would allow O(1) access to words in key_words if they are actually in there, rather than having to search the whole list until it is found, with O(n).


texts: LeetCode: Binary Tree Level Order Traversal C#

texts:
Please review for performance. and also naming convention

https://leetcode.com/problems/binary-tree-level-order-traversal/

  Given a binary tree, return the level order traversal of its nodes'
  values. (ie, from left to right, level by level).

  For example:

Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

using System.Collections.Generic;
using System.Linq;
using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/binary-tree-level-order-traversal/
    /// </summary>
    [TestClass]
    public class BinaryTreeLevelOrderTraversalTest
    {

        //      3
        //     / \
        //    9  20
        //   /  \
        //  15   7
        [TestMethod]
        public void TreeTest()
        {
            TreeNode root = new TreeNode(3);
            root.left = new TreeNode(9);
            root.right = new TreeNode(20);
            root.left.left = new TreeNode(15);
            root.left.right = new TreeNode(7);
            IList<IList<int>> res = BinaryTreeLevelOrderTraversalClass.LevelOrder(root);
            CollectionAssert.AreEqual(res[0].ToList(), new List<int>{3});
            CollectionAssert.AreEqual(res[1].ToList(), new List<int>{9,20});
            CollectionAssert.AreEqual(res[2].ToList(), new List<int>{15,7});
        }

        [TestMethod]
        public void OneNodeTreeTest()
        {
            TreeNode root = new TreeNode(3);
            IList<IList<int>> res = BinaryTreeLevelOrderTraversalClass.LevelOrder(root);
            CollectionAssert.AreEqual(res[0].ToList(), new List<int> { 3 });
        }
    }

    public class BinaryTreeLevelOrderTraversalClass
    {
        public static IList<IList<int>> LevelOrder(TreeNode root)
        {
            List<IList<int>> res = new List<IList<int>>();
            if (root == null)
            {
                return res;
            }
            Queue<TreeNode> Q = new Queue<TreeNode>();

            Q.Enqueue(root);

            int counter = 0; // which level
            while (Q.Count > 0)
            {
                int children = Q.Count;
                res.Add(new List<int>());
                for (int i = 0; i < children; i++)
                {
                    var temp = Q.Dequeue();
                    res[counter].Add(temp.val);
                    if (temp.left != null)
                    {
                        Q.Enqueue(temp.left);
                    }
                    if (temp.right != null)
                    {
                        Q.Enqueue(temp.right);
                    }
                }
                counter++;
            }
            return res;
        }
    }

}


texts: Reversing each word of a string while keeping the case index

texts:
I was given a simple requirement for reversing a string. The requirement is as follows:

In any programming language, create an input that accepts "My name is Albert McDonald." and outputs the reversed value "Ym eman si Trebla DlAnodcm."

I got it to work like this:

string expectedInput = "My name is Albert McDonald.";

//Prompt the user to enter "My name is Albert McDonald."
Console.WriteLine("Please enter the sentence \"" + expectedInput + "\"");
Console.WriteLine();

//Wait for the users input.
string inputText = Console.ReadLine();

//Convert the input to a char array.
List<char> characters = inputText.ToList<char>();

//Get the list of uppercase indexes
List<int> upperIndexes = new List<int>();
for (int index = 0; index < characters.Count; index++)
{
    if (Char.IsUpper(characters[index]))
        upperIndexes.Add(index);
}

//Remove the period at the end
inputText = inputText.Substring(0, inputText.Length - 1);

//Get the reversed array of words.
string[] words = inputText.Split(' ').Reverse().ToArray();

//Join the array back to a string.
string revesedWords = string.Join(" ", words);

//Reverse the entire string and make it all lower case.
string result = new string(revesedWords.Reverse().ToArray()).ToLower();
StringBuilder sb = new StringBuilder(result);

//Change the case of the original index
foreach (int index in upperIndexes)
{
    char newCharacter = char.Parse(result.Substring(index, 1).ToUpper());
    sb[index] = newCharacter;
}

//Output the resutlt
Console.WriteLine("Your name in reverse by word is: \"" + sb.ToString() + ".\"");
Console.WriteLine();

//Inform the user how to close the screen.
Console.WriteLine("Press any key to close the screen.");
Console.ReadLine();

Is there a better way in terms of lines of code and performance-wise?


texts: Cleaning up repeated calls to NSMakeRange()

texts:
In Objective-C, many of the NSString or NSMutableString methods for comparing or manipulating strings require a range argument--that is, an argument of data type NSRange (a struct containing a starting position and a length).  This applies outside of NSString (NSArray for example), but NSString is where I see it most frequently.

There does exist a convenience function for creating an NSRange struct:

NSRange range = NSMakeRange(position, length);

But the problem for me happens when I'm manipulating a string.  I'll sometimes write a method in which I will make several different manipulations on the string within the same method.  And the range I need to cover will be the entire length of the string.  It's not acceptable to simply declare an NSRange variable, set it, and use this throughout, because if the length of the string changes, the previously set range will be incorrect.

For example, suppose we're working with strings representing file paths.  We want to manipulate the string in a few ways to make sure the path looks how we want it to look:

- (NSString *)cleanPath:(NSString *)originalPath inRoot:(NSString *)rootPath {
    NSString *returnPath = [originalPath stringByReplacingOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveCompare:NSMakeRange(0,[originalPath length])];

    while ([returnPath rangeOfString:@"./"].location != NSNotFound) {
        returnPath = [returnPath stringByReplacingOccurrencesOfString:@"./" withString:@"/" options:NSCaseInsensitiveCompare:NSMakeRange(0,[returnPath length])];
    }

    if ([returnPath rangeOfString:rootPath options:NSCaseInsensitiveCompare range:NSMakeRange(0,[returnPath length])] != NSNotFound) {
        return returnPath;
    } else {
        return rootPath;
    }
}

As you can see, we have three calls to NSMakeRange just to make a range that encompasses the length of the string we're working on.  We want to look at the whole range.  Giving a range too short will mean we're not looking at every character, and giving a range too long will result in an out of bounds exception.  We also can't know what the range will be.

We know that the first range will be the longest range, because we're only removing characters.

Also, even though the call only shows up in code once in the while loop, it could be called any number of times in actuality, so we can't even preset a range before the loop and use that number every time.

The other annoying thing is that NSMakeRange(0,[myString length]) doesn't offer a ton of autocomplete help.

I also don't want to simply #define a macro that could accidentally have unintended consequences outside of this method.

What are my options to clean this up?

This is tagged C because even though the code here is Objective-C, NSRange is a C-style struct and NSMakeRange is a C-style function.  Any C techniques for cleaning up something like this will definitely apply here.


texts: Recursive flatten with lazy evaluation iterator

texts:
I'm trying to rewrite this:

def flatten(lst):
    flat = []
    for x in lst:
        if hasattr(x, '__iter__') and not isinstance(x, basestring):
            flat.extend(flatten(x))
        else:
            flat.append(x)
    return flat

In [21]: a=[1, [2, 3, 4, [5, 6]], 7]

In [22]: flatten(a)
Out[22]: [1, 2, 3, 4, 5, 6, 7]

..into a version that would flatten the iterable, but return values in a lazy manner. Now, this works:

def flat_fugly(s):
    if iterable(s):
        for x in s:
            yield chain.from_iterable(flat_fugly(x))
    else:
        yield takewhile(lambda x: True, [s])

list(islice(chain.from_iterable(flat_fugly(a)), 0, 6))
Out[34]: [1, 2, 3, 4, 5, 6]

But, as the name suggests... Is there a cleaner/better way?

Not to mention that I have to apply chain.from_iterable to flat_fugly anyway while I'd prefer to have plain iterator (I could wrap it in another function that would use chain.from_iterable of course, but still if it could be all made to fit in one more elegant function that would be preferable).


texts: Transform an object into another object structure

texts:
I've got such an input object, which I should modify in order to use it with some charts library.

const input = {
  foo: {
    bar: 'biz',
  },
  statistic: {
    "2019-11": {
      A: 11,
      B: 11,
      C: 11,
      D: 11,
      E: 11,
    },
    "2019-12": {
      A: 12,
      B: 12,
      C: 12,
      D: 12,
      E: 12,
    },
    ....
  }
};

My library expects an input like this:

[
  { subject: 'A', '2019-11': 11, '2019-12': 12 },
  { subject: 'B', '2019-11': 11, '2019-12': 12 },
  { subject: 'C', '2019-11': 11, '2019-12': 12 },
  { subject: 'D', '2019-11': 11, '2019-12': 12 },
  { subject: 'E', '2019-11': 11, '2019-12': 12 }
]

And this is my current solution:

const transform = arg => {
  const keys = ['A', 'B', 'C', 'D', 'E'];
  return _.map(keys, key => {
    const data = _.reduce(arg.statistic, (result, value, k) => {
      result[k] = value[key];
      return result;
    }, {});
    return {
      subject: key,
      ...data
    }
  });
}

Any improvements would be very welcome!


texts:
I wrote a C++ PEG packrat parser generator and would love to get some feedback on the code and/or syntax. I currently use the << operator for defining grammar expressions and linking the handler functions that are called when a rule is matched. These functions can then store a value of an arbitrary C++ type in the corresponding node of the parse tree using the value<type>() function.

For example, a very simple math parser can be generated through the following source code:

#include "IO.h"
#include "parserTools.h"
#include <cmath> //pow

using namespace llib;

std::map<std::string, double> variables;

void op(parser::info &lhs,parser::info &rhs,parser::info &r,const std::string &op){
  if(op[0]=='+')      r.value() =     lhs.value<double>() + rhs.value<double>() ;
  else if(op[0]=='-') r.value() =     lhs.value<double>() - rhs.value<double>() ;
  else if(op[0]=='*') r.value() =     lhs.value<double>() * rhs.value<double>() ;
  else if(op[0]=='/') r.value() =     lhs.value<double>() / rhs.value<double>() ;
  else if(op[0]=='^') r.value() = pow(lhs.value<double>() , rhs.value<double>());
}

void variable(parser::info &s){ s.value<double>()=variables[s.string()];             }
void negate(parser::info &s)  { s.value()=-s[0].value<double>();                     }
void set(parser::info &s)     { variables[s[0].string()]=s[1].value<double>();       }

int main(){
  peg::grammar math("Math");

  math << "Math"        << "Set | Expression"                           << parserTools::show("%v0\n");
  math << "Set"         << "Variable '=' Sum"                           << set << parserTools::pass(1);
  math << "Expression"  << "Sum"                                        << parserTools::pass();
  math << "Sum"         << "Product  ([+-] Product )*"                  << parserTools::leftbinary(op);
  math << "Product"     << "Exponent ([*/] Exponent)*"                  << parserTools::leftbinary(op);
  math << "Exponent"    << "Atomic   ('^'  Atomic  )*"                  << parserTools::leftbinary(op);
  math << "Atomic"      << "Parentheses | Number | Negate | Variable"   << parserTools::pass();
  math << "Parentheses" << "'(' Expression ')'"                         << parserTools::pass();
  math << "Negate"      << "'-' Atomic"                                 << negate;
  math << "Variable"    << "[a-zA-Z] [a-zA-Z0-9]*"                      << variable;
  math << "Number"      << parserTools::doubleGrammar()                 << parserTools::pass();

  math.ignored=" \t";
  math.setStart("Math");

  parser p(math);

  p.error=parserTools::genericError;
  p.warning=parserTools::genericWarning;

  while (1) {
    std::string str;
    IO << "> " >> str << str << " -> ";
    if(str=="q") break;
    else if(str!="") p.parse(str);
    else IO << clearline << endl;
  }

  return 0;
}

The full code and documentation is available on GitHub (though LParser is probably pretty boring name).

So any thoughts on the project? Is it something you would actually use?


texts: Generic menu class for console applications

texts:
Expanding the title: my goal (for hobby project) was to create simple, generic (customizable) and cross-platform menu class for console applications (mostly simple, text-based games). That's what I came up with:

#include <functional>
#include <iostream>
#include <map>
#include <string>

class ConsoleMenu {
  public:
    ConsoleMenu(const std::string& message,
        const std::string& invalidChoiceMessage,
        const std::string& prompt,
        const std::map<std::string, std::function<void()>>& commandsByChoice) :
            message_(message), invalidChoiceMessage_(invalidChoiceMessage),
            prompt_(prompt), commandsByChoice_(commandsByChoice) {}
    void use() {
      std::string userChoice;
      std::cout << '\n';
      // Based on https://isocpp.org/wiki/faq/input-output#istream-and-ignore {
      while ((std::cout << message_) && printChoices() &&
          (std::cout << prompt_) && (!(std::getline(std::cin, userChoice)) ||
          !validChoice(userChoice))) {
        std::cout << '\n' << invalidChoiceMessage_;
        // Should there be calls to std::cin::clear and std::cin::ignore, even
        // if I'm using std::getline?
      }
      // }
      commandsByChoice_[userChoice]();
    }
  private:
    bool printChoices() {
      bool successful = false;
      for (auto commandByChoice : commandsByChoice_) {
        successful = static_cast<bool>(
            std::cout << '[' << commandByChoice.first << ']' << '\n');
      }
      return successful;
    }
    bool validChoice(const std::string& choice) {
      return commandsByChoice_.find(choice) != commandsByChoice_.end();
    }
    std::string message_; // label_?
    std::string invalidChoiceMessage_;
    std::string prompt_;
    std::map<std::string, std::function<void()>> commandsByChoice_;
};

int main() {
  bool running = true;
  do {
    ConsoleMenu menu("What should this program do?\n", "Invalid operation; ", "> ", {
      {"run", [&running] {
        running = true;
      }},
      {"stop", [&running] {
        running = false;
      }}
    });
    menu.use();
  } while (running);
}

As you can see, while the general look of the menu is hard-coded, user can (and have to) specify the message (label) of the menu, list of choices, commands that are keyed to these choices, and even error message, and input prompt. "Generic"? Check!

If someone would like to suggest improvement requiring C++17, please, include also some non-standard equivalent(s) with similar interface, for example from The Boost library.


texts: Sh script to reduce version number in opkg status file

texts:
I have written a script to reduce/lower the version number stored in opkg status file using small shell script, This will enable us to force the opkg to install same version of a Debian package again.

Versions stored in the opkg files are as follows,

Version: 00.03.00a002
Version: 2013.07.001
Version: 2013.07.001
Version: 3.12.002

And my script is as shown below, This script would run on the embedded board which is having busybox based sh shell. I have put bash tag to reach more people.

Script edits either 1st version number or 2nd version number..I didn't take third because sometimes that would contain alphanumeric value and I am uncomfortable with handling hex subtraction.

#!/bin/sh

#Small script to Lower firmware version

OPKG_STATUS_FILE="/var/lib/opkg/status"
stamp=$(date +%s)
BACKUP_OPKG_STATUS_FILE="/var/lib/opkg/status_${stamp}"

#Creating backup file so that we can get back actual version if we want
cp ${OPKG_STATUS_FILE} ${BACKUP_OPKG_STATUS_FILE}
echo "${BACKUP_OPKG_STATUS_FILE} file created"

#clear original status file
:> ${OPKG_STATUS_FILE}

while IFS=' ' read -r line || [ -n "${line}" ];do
    ver_found=""
    ver_found=$(echo "${line}" | grep -i "Version")

    if [ ! -z "${ver_found}" ];then
        ver_extracted=""
        new_line=""
        for i in 1 2;do
            ver_extracted=$(echo "${line}" | grep -i "Version" | cut -d ':' -f 2 | cut -d '.' -f ${i})
            if [ ! -z "${ver_extracted}" ];then
            {
                #reduce version number
                if [ "${ver_extracted}" -gt 0 ];then
                    new_version=$(printf "%02d %02d" "${ver_extracted}" "01" | awk '{ printf "%.0f", $1 - $2 }')
                    new_line=$(echo ${line} | sed -e "s:${ver_extracted}:${new_version}:I")
                    line="${new_line}"
                else
                    continue
                fi
                break
            }
            fi
        done
    fi
    echo "${line}" >> "${OPKG_STATUS_FILE}"
done < "${BACKUP_OPKG_STATUS_FILE}"

I wanted to ask

if there is a better method for doing this.
One problem what I observed with my script is 03 is reduced and replaced with 2 instead of 02
I need to keep versions digits same, any suggestion for that ?


texts: Method that return related entities using OData

texts:
There is method GetFull that should use OData return related entities.

When I call GetFull(12, "entity1,entity2") then I will get to current object with id = 12 and related entity1 and entity2 (http://.../api/City/12?$expand=Region)

When I call GetFull(12, "0") then I want to automatical find and get all related entities from current object (http://.../api/City/12?$expand=Region,Country). For that I'm using reflections.

How can I improve this method?
It's working but I'm sure that I implemented it not properly.

P.S : It was done  for user-friendly link
before:http://.../api/City/12?$expand=Region,Country
now:http://.../api/City/12/GetFull or http://.../api/City/12/GetFull/Region

public virtual HttpResponseMessage GetFull(int id, string entities)
{
    string propertyList = string.Empty;

    if (!entities.Equals("0"))
    {
        propertyList = entities;
    }
    else
    {
        foreach (var prop in typeof(T).GetProperties().Where(p => p.GetGetMethod().IsVirtual))
        {
            if (prop.PropertyType.IsClass && !prop.PropertyType.FullName.StartsWith("System."))
            {
                propertyList += prop.Name + ",";
            }
        }

        propertyList = propertyList.Remove(propertyList.Length - 1);
    }

    string entityName = typeof(T).Name;
    var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
    var response = Request.CreateResponse(HttpStatusCode.Found);

    StringBuilder sb = new StringBuilder();
    sb.Append(baseUrl);
    sb.Append("/api/");
    sb.Append(entityName);
    sb.Append("/");
    sb.Append(id);
    sb.Append("?$expand=");
    sb.Append(propertyList);

    response.Headers.Location = new Uri(sb.ToString());
    return response;
}

Sorry for my English and if I have to add more informations, please let me know. Thanks


texts:
Problem:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Problem from here.
This is my code:
/*
 * Code by Clint
 */

public class FizzBuzz {
    public static void main(String[] args) {
        for (int numbers = 1; numbers <= 100; numbers++) {
            if (numbers % 3 == 0 && numbers % 5 == 0) {
                System.out.println("Fizz Buzz");
            } else if (numbers % 3 == 0) {
                System.out.println("Fizz");
            } else if (numbers % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(numbers);
            }
        }
    }
}

Here's the output:


texts: Handling multiple uploaded images in JavaScript

texts:
function uploadImages(uploader,callback1,callback2){
    uploader.onchange=function(){
        callback1()
        var reader=new FileReader()
        var i=0
        reader.onload=function(){
            var image=new Image()
            image.onload=callback2
            image.src=this.result
            if(++i < uploader.files.length) reader.readAsDataURL(uploader.files[i])
        }
        reader.readAsDataURL(uploader.files[i])
    }
}

uploader is the <input> element
callback1 is called when the user uploads something (to reset things before handling the images)
callback2 is called once per image, when it loads.

This function is being used here.

I feel like there might be a simpler way to do this.


texts: JS composition - Components depend on others

texts:
NOTE: I am not familiar with a lot of terminology. If I am naming things incorrectly, please correct me!

Making small game engine for learning. Mostly using inheritance, but the more my project grows, the more I feel like objects are inheriting to much.

Example of inheriting classes:

Body // Base for x/y and width/height
  ↪Moveable
    ↪Drawable
      ↪Collidable

Not very clean. Parents are interchangeable with their children. Basically using inheritance primarily to organize my code and dump all the functionality into a big monster class.

Sometimes, inheriting everything makes sense, but not always. For example:

A "Player" would inherit everything. It can move, it needs to be drawn
and it collides with other objects in the game
A "Tree" would only need "Body", "Drawable" and "Collidable" since it does      not move
An "Area" would need "Body" and "Collidable" since it is invisible, static and only needs to know if something comes within its range

After researching, composition seems to be a good solution. Saw examples, but not exactly like the one I opted for where instances require on other instances from the parent. Child instances also have references to their parent.

function Tree(x, y){
    this.body = new Body(this, x, y, 100, 100);
    this.draw = new Drawable(this);
}

function Body(parent, x, y, width, height){
    this.parent = parent;

    this.x = x;
    this.y = y;

    this.width = width;
    this.height = height;

    this.getPosition = function(){ /* Returns x and y */ };
    this.getDimensions = function(){ /* Returns width and height */ };
}

function Drawable(parent){
    this.parent = parent;

    this.image = function(image){
        var position = this.parent.body.getPosition();
        var dimensions = this.parent.body.getDimensions();
        // Use image, position and dimensions to draw an image on a canvas
    }
}

Now if I wanted to draw the tree, I would do something like

tree = new Tree(500, 500);
tree.draw.image('tree.jpg');

I'm not sure if I am abusing the fact that JS objects are passed by reference to create my objects. The main drawback I see if that you need to know what requires what, but that doesn't seem hard to overcome. For example, "Drawable" needs the parent to have an instance of "Body" to work.

Is there something I'm missing or is this a good solution to implement?


texts:
I have the following method which calculates average days on market for a sale type segment:

def average_days_on_market_sale_type_segment
    # on market days
    on_market_days = {}

    # 1. get last year sales - note that the dates need to be sequential in time (oldest in time comes first, most recent in time commes last)
    last_year_sales = self.real_property_sale_projects.where(status: 'reviewed')
      .where('deal_date between ? and ?', Time.at(Time.now - 1.years), Time.now)
      .map(&:real_property_sale)

    # 2. loop each sale type, convert sale description string to symbol
    last_year_sales.each do |sale|
      sd = sale.sale_description.parameterize.underscore.to_sym

      on_market_days[sd] ||= { count: 0, days: 0 }

      on_market_days[sd][:count] += 1

      # get the days on market value
      on_market_days[sd][:days] += sale.real_property_sale_project.days_on_market
    end

    # 3. summarize average
    summary = {}

    on_market_days.each do |k, v|
      summary[k.to_s.humanize] = (v[:days].to_f / v[:count].to_f).round
    end

    # 4. return summarized result
    # it should contain each sale description type as a key and average day as a number
    summary
  end

Is there a more elegant way to achieve the same thing? Does the solution contain any performance issues/gotchas?


texts:
I've created a very basic date data type in C simply to practice writing my own data type. Please critique.

#include <stdio.h>
#include <stdlib.h>
enum DATE_FORMAT{DASHES,SLASHES};
typedef enum DATE_FORMAT DFORMAT;
typedef struct {
    unsigned char day;
    unsigned char month;
    unsigned short year;
} DATE;

/* Allocates new DATE with specified values and returns a ptr to it. User must NULL-check */
DATE *create_date(unsigned char month, unsigned char day, unsigned short year)
{
    if((month > 12) || (month < 1))
        return NULL;
    if((day > 31) || (day < 1))
        return NULL;
    if((year > 9999) || (year < 0))
        return NULL;
    DATE *the_date = malloc(sizeof(DATE));
    if(the_date == NULL)
        return NULL;
    the_date->day = day;
    the_date->month = month;
    the_date->year = year;
    return the_date;
}
void printf_date(DATE *input, DFORMAT format)
{
    if(input == NULL)
        printf("Invalid DATE.\n");
    if(format == DASHES)
        printf("%hhu-%hhu-%hu\n",input->month,input->day,input->year);
    if(format == SLASHES)
        printf("%hhu/%hhu/%hu\n",input->month,input->day,input->year);
    return;
}
void free_date(DATE *dtf)
{
    if(dtf == NULL)
    {
        printf("Date free failed.\n");
    }
    else
    {
        free(dtf);
        printf("Date freed successfully\n");
    }
    return;
}

int main()
{
    DATE *my_date = create_date(3,17,2017);
    if(my_date == NULL)
    {
        printf("Please provide a valid date next time... exiting.\n");
        return(EXIT_FAILURE);
    }
    printf_date(my_date, SLASHES);
    printf_date(my_date, DASHES);
    free_date(my_date);
    return(EXIT_SUCCESS);
}


texts:
Is there a cleaner way of checking a dataset for tables/rows before attempting to read them?

If ds.Tables.Count > 0 Then
    If ds.Tables(0).Rows.Count > 0 Then

        'do something with the the rows at this point

    End If
End If

Edit to clarify - I am talking specifically about the two bool checks to see if the dataset acutally contains any data in table(0).


texts:
Below is the code I have written for counting perfect squares between a given lower and upper bound.

I am using the following concept to solve this:

  Starting with 1, there are \$\sqrt{m}\$ square numbers up to and including \$m\$.

public static int CountPerfectSquares(long A, long B)
{
    int count = 0;

    //Proceed if lowerbound is less than upperbound
    if (A < B)
    {
        //negative numbers are not perfect squares
        if (A < 0 && B < 0) return count;

        //Reset lowerbound if required
        if (A <= 0) A = 1;

        //Find number of squares between A & B (INCLUSIVE lower and upperbound)
        //count = (int)Math.Sqrt(B) - (int)Math.Sqrt(A);  //Giving wrong count when LowerBound value is a whole square (For exp. CountPerfectSquares(1, 25))

        int sqrtA = (int)Math.Sqrt(A);
        int sqrtB = (int)Math.Sqrt(B);
        count = sqrtB - sqrtA;
        //To handle the case when lowerbound value is a perfect square number
        if (A == sqrtA * sqrtA)
        {
            count++;
        }
    }

    return count;
}

Can you please help me make this more efficient, if possible?

Is there any other way of handling the case when the lower bound value is a perfect square number, so that I don't have to do an extra count++?


texts:
I have made a REST web service using the Express framework. Here is my snippet of code, which has repeated code. I am creating a currencyItem object in two blocks and push it into an array.

I think it is not bad practice. Can anyone suggest if it is OK? If not, how can I improve it?

/** API to get all currency price */
router.get("/:ticker?", function(req, res, next) {
  var currencyList = [];

  // it can be null as ticker is optional parameter
  let reqCurrencyName = req.params.ticker;

  rp(baseUrl)
    .then(body => {
      const $ = cheerio.load(body);
      $("tr").each(function name(i, elem) {
        // currency name
        var currencyName = $(this)
          .find("td")
          .eq(1)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // market cap value
        var marketCap = $(this)
          .find("td")
          .eq(2)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // currency price
        var price = $(this)
          .find("td")
          .eq(3)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // date supply value
        var dataSupply = $(this)
          .find("td")
          .eq(4)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim()
          .replace(/ /g, "");

        // volume value
        var volume = $(this)
          .find("td")
          .eq(5)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // negative change value
        var negativeChange = $(this)
          .find("td")
          .eq(6)
          .text()
          .replace(/\r?\n|\r/g, " ")
          .trim();

        // first item is empty in response so lets not push it into an array
        if (currencyName !== "") {
          if (reqCurrencyName !== undefined) {
            if (currencyName === reqCurrencyName) { // execute single time
              const currencyItem = {
                currencyName: currencyName,
                marketCap: marketCap,
                price: price,
                dataSupply: dataSupply,
                volume: volume,
                negativeChange: negativeChange
              };

              currencyList.push(currencyItem);
            }
          } else {
            const currencyItem = {
              currencyName: currencyName,
              marketCap: marketCap,
              price: price,
              dataSupply: dataSupply,
              volume: volume,
              negativeChange: negativeChange
            };

            currencyList.push(currencyItem);
          }
        }
      });
      res.send(currencyList);
    })
    .catch(err => {
      rollbar.log(err);
      res.send({ error: err });
    });
});


texts:
I'm trying to measure how many CPU cycles a mutex lock takes. Can you find any problems in my mutex lock benchmark?

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <string>

std::mutex twiceMutex;
typedef std::int64_t i64;

i64 twice(i64 x)
{
    return 2 * x;
}

i64 twiceM(i64 x)
{
    std::lock_guard<std::mutex> lock(twiceMutex);
    return 2 * x;
}

const i64 I = 100'000'000; // number of iterations

struct Benchmark
{
    i64 (*fn)(i64);

    i64 operator()()const
    {
        namespace chrono = std::chrono;
        auto startTime = chrono::steady_clock::now();
        i64 res = 0;
        for (i64 i = 0; i < I; i++)
        {
            res += fn(i);
        }
        auto endTime = chrono::steady_clock::now();

        auto elapsed = chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime).count();
        return elapsed;
    }
};

int main()
{
    const double T = Benchmark{ twice }(); // total nanoseconds without mutex
    const double TM = Benchmark{ twiceM }(); // total nanoseconds with mutex

    const double K = 3.7; //GHz of my CPU
    const double t = T / I; // nanoseconds per iteration, without mutex
    const double tm = TM / I; // nanoseconds per iteration, with mutex
    const double m = tm - t; // difference nanoseconds per iteration, this should be the cost of locking a mutex in nanoseconds

    // print the results in cycles
    std::cout << t * K << std::endl;
    std::cout << tm * K << std::endl;
    std::cout << m * K << std::endl;

    {
        std::string _;
        std::getline(std::cin, _);
    }
}

I'm intentionally not taking into account thread contention; just interested in the best case cost.

The results are:

9.25905
80.1517
70.8926

So ~71 CPU cycles for locking a mutex


texts: How to make this special binary-search algorithm more rusty?

texts:
I am solving one binary search problem in LeetCode.
I have accomplished such code:
struct Solution;
impl Solution {
    pub fn search(nums: Vec<i32>, target: i32) -> i32 {
        if nums.is_empty() {
            return -1;
        }
        if nums.len() == 1 {
            return if nums[0] == target { 0 } else { -1 };
        }
        let mut l = 0;
        let mut r = nums.len() - 1;

        while l <= r {
            let mid = (l + r) / 2 as usize;
            if nums[mid] == target {
                return mid as i32;
            }
            if nums[0] <= nums[mid] {
                if nums[0] <= target && target < nums[mid] {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            } else {
                if nums[mid] < target && target <= nums[n - 1] {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
        }
        return -1;
    }
}

I have searched the standard library and found that it has an API: binary_search_by.  But since this is not a traditional binary search algorithm, I can't directly call the API.  I have also googled to try to find a more elegant Rust code but found nothing special.  Is there any idea to make this code rusty?


texts: Function for obtaining the 3 latest patient vital signs

texts:
I'm just putting together a small project, checking to see if this would be the fastest/cleanest way to write out a function that grabs the 3 latest vital signs.

Edit: I am thinking GetRecentVitalSigns should be in the domain model.

Also, if I wanted to grab all the vital signs, I would just call the VitalSigns list, but I was thinking I could make that as private and create a GetAllVitalSigns, but that seems redundant. Any advice would be excellent (on anything related).

public class Patient
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime AdmissionDate { get; set; }
    public List<string> Allergies { get; set; }
    public List<VitalSign> VitalSigns { get; set; }

    public List<VitalSign> GetRecentVitalSigns()
    {
        if(VitalSigns.Count > 0)
        {
            var results = VitalSigns
                .Take(3)
                .OrderBy(x => x.DateTimeChecked)
                .ToList();

            return results;
        }
        return null;
    }
}
public class VitalSign
{
    public decimal BodyTemperature { get; set; }
    public int Pulse { get; set; }
    public int BloodPressure { get; set; }
    public int RespiratoryRate { get; set; }
    public DateTime DateTimeChecked { get; set; }
}

New structure

public class Patient
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime AdmissionDate { get; set; }
    public List<string> Allergies { get; set; }
    private List<VitalSign> vitalSigns;

    private IEnumerable<VitalSign> VitalSigns
    {
        get { return vitalSigns; }
    }

    public IEnumerable<VitalSign> GetRecentVitalSigns(int vitalSignsCount = 3)
    {
        var recentVitalSigns = new IEnumerable<VitalSign>();
        if (recentVitalSigns.Any())
        {
            recentVitalSigns = vitalSigns
                .OrderBy(vs => vs.DateTimeChecked)
                .Take(vitalSignsCount);
        }
        return recentVitalSigns;
    }
}
public class VitalSign
{
    public decimal BodyTemperature { get; set; }
    public int Pulse { get; set; }
    public int BloodPressure { get; set; }
    public int RespiratoryRate { get; set; }
    public DateTime DateTimeChecked { get; set; }
}


texts: SpamAssassin spam analyzer script in PHP based on sa-learn command

texts:
I wrote a small script to analyse spam messages that are spam false negative; meaning that they are spam messages in nature but that happened to be in your INBOX folder because your spam filter failed to detect it correctly (I personally use SpamAssassin and unfortunately it rarely happens).

The goal is to have a chance to analyse spam messages that are put in spam folder manually by running a script in cron jobs.

Obviously, all spam messages will be analysed regardless of which email client you're using (Thunderbird, Kaiten Mail or Roundcube), because all you need is to have a message moved in spam folder.

Example of my well working PHP script:

<?php
// Check if there is messages in SPAM folder that don't have [SPAM] lable (e.g.: manually moved from INBOX)
exec("grep -L '\[SPAM\]' /home/domainexample.ru/Maildir/.Junk/cur/* 2> /dev/null", $spam_messages);

if (!empty($spam_messages)) {

    $sa_learn = '/usr/bin/sa-learn --spam';
    foreach ($spam_messages as $spam_message) {
        //Learn a message that we believe is spam
        $sa_learn .= ' ' . $spam_message;
        $marked_as_spam = file_get_contents($spam_message);
        // Adding [SPAM] flag to message's subject of analyzed message
        $marked_as_spam = str_replace("Subject:", "Subject: [SPAM] ", $marked_as_spam);
        file_put_contents($spam_message, utf8_encode($marked_as_spam));
    }
    // Logging the results
    $sa_learn .= ' > ' . '/home/domainexample.ru/.spamassassin/logs/' . date('d.m.Y-G:i') . '_analyzer.log';
    //Executing analyzer in background
    shell_exec("nohup $sa_learn 2> /dev/null & echo $!");
    // Cleaning cached messages in Dovecot
    shell_exec("rm -f /var/lib/dovecot/index/domainexample.ru/.Junk/*");
}
?>

I would like to have (in case there are) few ideas for improving this already working PHP script but most importantly, I would like to learn of how to write the same script using PERL or/and BASH scripting.

Could you please suggest some ideas for improving current PHP script, along with providing pure and fully working examples of the same scenarios in PERL or/and BASH?


texts: Listing words from text, provide lines where appears, count them

texts:
I applied for Junior Java Developer in some company.
Got a task:"Listing words (without duplicates) from text, provide lines where appears, count them."
Output should looks like:

Alphacoronavirus - 3 - pozycje -> [1,3,2]

gatunki - 4 - pozycje -> [1,3,2,7]

Koronawirusy - 2 - pozycje -> [3,2]

Wirusów - 1 - pozycje -> [1]

Did not receive any feedback form them for two weeks so i will ask for judgment here.
Waiting for roast

Data structure:

import java.util.ArrayList;
import java.util.List;

public class PatternStats implements Comparable<PatternStats>{
    private String word;
    private int amountOfAppearances = 1;
    private List<Integer> linesContains = new ArrayList<>();

    public PatternStats(String word){
        this.word = word;
    }

    public String getWord() {
        return word;
    }

    public int getAmountOfAppearances() {
        return amountOfAppearances;
    }

    public List<Integer> getLinesContains() {
        return linesContains;
    }

    public void increaseAOA(){
        this.amountOfAppearances++;
    }

    public void addLineToList(int lineNO){
        this.linesContains.add(lineNO);
    }

    @Override
    public int compareTo(PatternStats o) {
        int compareInt = this.word.toLowerCase().compareTo(o.word.toLowerCase());
        if(compareInt < 0) return -1;
        if(compareInt > 0) return  1;
        return 0;
    }
}

WordLister

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordListingWithMap {

    private Map<String, PatternStats> patternStatsMap = new HashMap<>();

    public List<PatternStats> listWords(String filePath) {
        patternStatsMap.clear();
        String regex = "\\b[^\\d\\P{L}]+\\b";
        try {
            FileInputStream fis = new FileInputStream(filePath);
            Scanner sc = new Scanner(fis);
            scanTextCollectWords(sc, regex);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<PatternStats> patternStats = new ArrayList<>(patternStatsMap.values());
        Collections.sort(patternStats);
        return patternStats;
    }

    private void scanTextCollectWords(Scanner sc, String regex) {
        int lineCounter = 0;
        while (sc.hasNextLine()){
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(sc.nextLine());
            lineCounter++;
            while (m.find()) {
                if (patternStatsMap.containsKey(m.group(0))) {
                    increaseExist(m.group(0), lineCounter);
                } else {
                    createNewAddToMap(m.group(0), lineCounter);
                }
            }
        }
    }

    private void createNewAddToMap(String word, int line) {
        PatternStats tempPatternStats = new PatternStats(word);
        tempPatternStats.addLineToList(line);
        patternStatsMap.put(word, tempPatternStats);
    }

    private void increaseExist(String word, int line) {
        if (!patternStatsMap.get(word).getLinesContains().contains(line))
            patternStatsMap.get(word).addLineToList(line);

        patternStatsMap.get(word).increaseAOA();
    }
}

and Main

import java.util.List;

public class Main {

    public static void main(String[] args) {
        final String filePatch = "C:\\vaTast\\src\\zadanie.txt";

        WordListingWithMap wlwm = new WordListingWithMap();
        toPrint = wlwm.listWords(filePatch);
        for (PatternStats each : toPrint){
            System.out.println(each.getWord() + " - " +
                    each.getAmountOfAppearances() + " - pozycje - > " +
                    each.getLinesContains());
        }
    }
}

repo: https://github.com/krukarkonrad/vaRepo/


texts: Python get UTC offset for when only naive date time objects are available

texts:
The function below is designed to return a UTC offset string, in the form used widely by timestamps, of the user's current time for when only naive date time objects are available (no time zone information).

I've tested it on two systems, which are in different time zones, and it works perfectly. However I'd like confirmation that it will work on all systems running Python versions >= 2.6. Can anyone see any potential problems?

Note: The function will only ever be used with the user's current time and so present or past dates and times are not an issue.

import time
from datetime import datetime

def get_utc_offset_str():
    """
    Returns a UTC offset string of the current time suitable for use in the
    most widely used timestamps (i.e. ISO 8601, RFC 3339). For example:
    10 hours ahead, 5 hours behind, and time is UTC: +10:00, -05:00, +00:00
    """

    # Calculate the UTC time difference in seconds.

    timestamp = time.time()
    time_now = datetime.fromtimestamp(timestamp)
    time_utc = datetime.utcfromtimestamp(timestamp)
    utc_offset_secs = (time_now - time_utc).total_seconds()

    # Flag variable to hold if the current time is behind UTC.
    is_behind_utc = False

    # If the current time is behind UTC convert the offset
    # seconds to a positive value and set the flag variable.
    if utc_offset_secs < 0:
        is_behind_utc = True
        utc_offset_secs *= -1

    # Build a UTC offset string suitable for use in a timestamp.

    if is_behind_utc:
        pos_neg_prefix = "-"
    else:
        pos_neg_prefix = "+"

    utc_offset = time.gmtime(utc_offset_secs)
    utc_offset_fmt = time.strftime("%H:%M", utc_offset)
    utc_offset_str = pos_neg_prefix + utc_offset_fmt

    return utc_offset_str


texts: Getting the KML color code from colordialog box more efficiently

texts:
Kml uses an 8 digit HEX color format. The traditional Hex format for red looks like #FF0000. In Kml, red would look like this FFFF0000. The first 2 digits are for opacity (alpha). Color format is in AABBGGRR. I was looking for a way to set the color as well as the opacity and return it in a string to be placed in an attribute of a KML.

string color
string polyColor;
int opacity;
decimal percentOpacity;
string opacityString;

//This allows the user to set the color with a colorDialog adding the chosen color to a string in HEX (without opacity (BBGGRR))
private void btnColor_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
    {
        btnColor.BackColor = colorDialog1.Color;
        Color clr = colorDialog1.Color;
        color = String.Format("{0:X2}{1:X2}{2:X2}", clr.B, clr.G, clr.R); //Color returned in Hex format
    }
}

//This method takes the Opacity (0% - 100%) set by a textbox and gets the HEX value. Then adds Opacity to Color and adds it to a string.
private void PolyColor()
{
    percentOpacity = ((Convert.ToDecimal(txtOpacity.Text) / 100) * 255);
    percentOpacity = Math.Floor(percentOpacity);  //rounds down
    opacity = Convert.ToInt32(percentOpacity);
    opacityString = opacity.ToString("x");
    polyColor = opacityString + color;
}