texts: Improve mixin that outputs page-specific CSS

texts:
As part of this answer, I created a mixin to generate some page-specific CSS for me.

I need to style an element based on a class I assign to the html-element. I do this for four different classes on the root-element, which gives me four similar CSS rules.

I'm looking for suggestions for the mixin itself. This is not limited to its function, also naming and the general idea may have so room for improvements.

Usage:

Pass the $element you want to style...
...and the $property (needs to hold a color value) you want to style i with
optionally, pass true as a third argument, if the light color variation should be used

@include themify(".page-title", background-color, true);

Example Output:

.page--blog .page-title {
    /* $blog-color-light */
    background-color: #6fbf00;
}

.page--portfolio .page-title {
    /* $portfolio-color-light */
    background-color: #ffaa10;
}

.page--profil .page-title {
    /* $profil-color-light */
    background-color: #6d91da;
}

.page--impressum .page-title {
    /* $impressum-color-light */
    background-color: #e04345;
}

Mixin:

@mixin themify($element, $property, $light-colors: false) {
    $pages: null;
    @if $light-colors == true {
        $pages: blog      $blog-color-light,
                portfolio $portfolio-color-light,
                profil    $profil-color-light,
                impressum $impressum-color-light;
    } @else {
        $pages: blog      $blog-color,
                portfolio $portfolio-color,
                profil    $profil-color,
                impressum $impressum-color;
    }

    @each $page in $pages {
        .page--#{nth($page, 1)} #{$element} {
            #{$property}: nth($page, 2);
        }
    }
}


texts: Modern OpenGL wrapper abstractions (shaders)

texts:
I am experienced with other languages, but not so much with the latest C++ standards. I was wondering if anyone had any tips on how to improve my code or any critique on my implementation. This is not designed to be used as an external or public library and I hope my use of the initializer lists are suitable (unwrapped pointers as they have no owner and aren't copied or stored).

I'm using spdlog and the Logger typedef is a typedef std::shared_ptr<spdlog::logger> Logger; in another (common) header.

program.cpp

#include <render/program.h>

Program::Program(Logger logger) :
    logger(std::move(logger)) {}

Program::operator GLuint() const {
    return program_id;
}

void Program::create(std::initializer_list<Shader *> shaders) {
    program_id = glCreateProgram();

    for (const Shader *shader : shaders) {
        glAttachShader(program_id, (GLuint) *shader);
    }

    glLinkProgram(program_id);

    GLint link_status;
    glGetProgramiv(program_id, GL_LINK_STATUS, &link_status);

    if (!link_status) {
        logger->error("Failed to link program");

        GLint log_length;
        glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &log_length);

        if (log_length > 0) {
            GLchar info_log[log_length - 1];
            glGetProgramInfoLog(program_id, sizeof(info_log), nullptr, info_log);

            logger->error((const char *) info_log);
        }
    }

    for (const Shader *shader : shaders) {
        glDetachShader(program_id, (GLuint) *shader);
    }
}

void Program::destroy() const {
    glDeleteProgram(program_id);
}

void Program::use() const {
    glUseProgram(program_id);
}

program.h

#pragma once

#include <engine.h>
#include <render/shader.h>
#include <initializer_list>

class Program {
public:
    explicit Program(Logger logger);

    explicit operator GLuint() const;

    void create(std::initializer_list<Shader *> shaders);

    void destroy() const;

    void use() const;

private:
    const Logger logger;
    GLuint program_id;
};

shader.cpp

#include <render/shader.h>
#include <fstream>

Shader::Shader(Logger logger, std::string path) :
    logger(std::move(logger)), path(std::move(path)) {}

Shader::operator GLuint() const {
    return shader_id;
}

void Shader::create(GLenum type) {
    std::ifstream input_stream(path);

    if (!input_stream) {
        logger->error("Unable to open shader file");

        return;
    }

    std::string source;
    char buffer;

    source.reserve(120);

    while (input_stream.get(buffer)) {
        source += buffer;
    }

    shader_id = glCreateShader(type);

    const GLchar *sources[] = {source.c_str()};
    glShaderSource(shader_id, 1, sources, nullptr);
    glCompileShader(shader_id);

    GLint compile_status;
    glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compile_status);

    if (!compile_status) {
        logger->error("Failed to compile shader: {}", path);

        GLint log_length;
        glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);

        if (log_length > 0) {
            GLchar info_log[log_length - 1];
            glGetShaderInfoLog(shader_id, sizeof(info_log), nullptr, info_log);

            logger->error((const char *) info_log);
        }
    }
}

void Shader::destroy() const {
    glDeleteShader(shader_id);
}

shader.h

#pragma once

#include <engine.h>
#include <string>

class Shader {
public:
    Shader(Logger logger, std::string path);

    explicit operator GLuint() const;

    void create(GLenum type);

    void destroy() const;

private:
    const Logger logger;
    const std::string path;
    GLuint shader_id;
};


texts: increase speed & lower memory consumption of text normalization function

texts:
I'm trying to preprocess a large text document. I've written a text normalization function which takes a disproprtionate amount of time and memory. How can I format the function to lower these two?

The time result below was for this example.

t = "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. Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst."

This is the script.

import time
import string
import nltk
import numpy as np

# text preprocessing module, use boolean flags to customize function
def normalize_text(text, lowercase=True, punctuation=True):

    # Step 1: Tokenize
    output = nltk.word_tokenize(text)

    # Step 2: Convert to lowercase (optional)
    if lowercase:
        output = [word.lower() for word in output]

    # Step 3: Remove punctuation:
    if punctuation:
        output = [str(token).translate(str.maketrans('', '', string.punctuation)) for token in output]
        output = [token for token in output if token != '']

    return(output)

Removing all filters and the corresponding if-statements sped up processing by a mere 0.7%.

def normalize_text2(text):

    # Step 1: Tokenize
    output = nltk.word_tokenize(text)

    # Step 2: Convert to lowercase (optional)
    output = [word.lower() for word in output]

    # Step 3: Remove punctuation:
    output = [str(token).translate(str.maketrans('', '', string.punctuation)) for token in output]
    output = [token for token in output if token != '']

    return(output)

Here is the bagged comparison.

times1 = []

for i in range(1000):
    start = time.time()
    tokens = normalize_text(t)
    end = time.time()
    times1.append(end - start)

time1 = np.mean(times1)
print(time1)

times2 = []

for i in range(1000):
    start = time.time()
    tokens = normalize_text2(t)
    end = time.time()
    times2.append(end - start)

time2 = np.mean(times2)
print(time2)

print(time2/time1)

Here are the results:

0.0021646411418914796
0.0021491129398345946
0.9928264312470212

Any advice on how to improve further? For example, how could I reduce the number of different list comprehensions, so that the same sequence of text does not need to crunched anew this many times?


texts:
I'd like to obtain a dict of the following form (not strict):

{65: ['Fresh', 'Frozen'],
 66: ['Fresh', 'Delicatessen'],
 75: ['Grocery', 'Detergents_Paper'],
 128: ['Fresh', 'Delicatessen'],
 154: ['Milk', 'Grocery', 'Delicatessen']}

when I have an input which is list of dicts. Their keys may be intersected and values - not. For example in our case we have the same key 65 in two dicts with value Fresh and Frozen.

This is my solution and I'd like to improve it:

outliers = [
    {65: 'Fresh', 66: 'Fresh', 81: 'Fresh', 95: 'Fresh', 96: 'Fresh',
     128: 'Fresh', 171: 'Fresh', 193: 'Fresh', 218: 'Fresh', 304: 'Fresh',
     305: 'Fresh', 338: 'Fresh', 353: 'Fresh', 355: 'Fresh', 357: 'Fresh',
     412: 'Fresh'},

    {86: 'Milk', 98: 'Milk', 154: 'Milk', 356: 'Milk'},

    {75: 'Grocery', 154: 'Grocery'},

    {38: 'Frozen', 57: 'Frozen', 65: 'Frozen', 145: 'Frozen', 175: 'Frozen',

     264: 'Frozen', 325: 'Frozen', 420: 'Frozen', 429: 'Frozen', 439: 'Frozen'},

    {75: 'Detergents_Paper', 161: 'Detergents_Paper'},

    {66: 'Delicatessen', 109: 'Delicatessen', 128: 'Delicatessen',
     137: 'Delicatessen', 142: 'Delicatessen', 154: 'Delicatessen',
     183: 'Delicatessen', 184: 'Delicatessen', 187: 'Delicatessen',
     203: 'Delicatessen', 233: 'Delicatessen', 285: 'Delicatessen',
     289: 'Delicatessen', 343: 'Delicatessen'}
]

common_outliers = {}
for outlier in outliers:
    for idx, feature in outlier.items():
        if idx not in common_outliers:
            common_outliers[idx] = [feature]
        else:
            common_outliers[idx].append(feature)
common_outliers = {idx: features for idx, features in common_outliers.items()
                   if len(features) > 1}
print(common_outliers)


texts: find the longest sequence of consecutive numbers in decreasing order


texts:
I've been working around a solution to easily manage LTR and RTL on the same interface.

The different solutions I knew at first:

Override CSS according to direction.
Use a program to transform your CSS in LTR to a new RTL file.
Start from a body { transform: rotateY(180deg) }.

1. Override CSS according to direction

This solution is painful for developers.
You have to think of overriding ever CSS that will not flip properly.

Such as:

.title {
  float: left;
  margin-left: 10px;
}

body[dir="rtl"] .title {
  float: right;
  margin-left: 0;
  margin-right: 10px;
}

Note: Adding an attribute dir="rtl" on the <body> flips the whole interface, but you'll still need to override margins, floats, etc.

2. Use a program to transform your CSS in LTR to a new RTL file

This implies using an external program you didn't control to run on all your style files and then you have to make sure to send the LTR or RTL version accordingly to the client.

To me it felt quite unsafe to rely on this. I can't be sure it works 100% fine and it can be quite complex (from my point of view, I didn't dive into it).

3. Start from a body { transform: rotateY(180deg) }

This is the option I went for.

It felt a lot more pleasant. Almost everything is already working fine (in my test cases). I only need to work on text elements.

Here is what I came up with so far:

#app[x-dir="rtl"] {
  transform: rotateY(180deg);
}

#app[x-dir="rtl"] input,
#app[x-dir="rtl"] textarea,
#app[x-dir="rtl"] img,
#app[x-dir="rtl"] video,
#app[x-dir="rtl"] iframe,
#app[x-dir="rtl"] h1,
#app[x-dir="rtl"] h2,
#app[x-dir="rtl"] h3,
#app[x-dir="rtl"] h4,
#app[x-dir="rtl"] h5,
#app[x-dir="rtl"] h6,
#app[x-dir="rtl"] p,
#app[x-dir="rtl"] label {
  display: inline-block;
  transform: rotateY(180deg);
  direction: rtl;
}

#app[x-dir="rtl"] label input {
  transform: rotateY(0);
}

#app[x-dir="rtl"] .rtl {
  display: inline-block;
  transform: rotateY(180deg);
  direction: rtl;
}

Explanation

The only thing missing after flipping the whole interface is:

I have to flip texts back, because they are wrong(flipped with the page).
Add a direction: rtl; on each tag containing content that needs to be display as RTL.

What I'm doing:

Generalizing as much as possible tags that for sure need to have RTL behavior and flipped back.
Give the developer access to a class .rtl, for edge cases (eg: I can't guess if <span> and <div> contain text or not).

Note: I use an attribute x-dir="", because dir="" flips the interface. I want full control.

Drawbacks:

The only one I can think of: You can't add .rtl to an element that already has a transform because it'd override. It is not additive.

Feel free to test around: DEMO

Questions

Can you think of any edge case I haven't thought of?

Is it a good way to go?

Any optimization?

Helpful links

https://alfy.me/2014/07/26/lets-talk-about-rtl.html


texts: Concise way of "updating" element in nested collections

texts:
Imagine simple game:

type Combatant = {
    hp : int
    attack : int
}

type CombatantGroup = Combatant list
type CombatantGroups = CombatantGroup list

type Battle = {
    combatantGroups : CombatantGroups
}

there is some battle, in which some amount groups participate. In each group there is several combatants. Now I want to implement a function for one combatant  to attack another. Due to immutability, I have to replace whole attacked target, and whole group and whole battle. If the battle was just between two participants, I could write code like this:

if target = battle.combatant1 then
    { battle with combatant1 = { battle.combatant1 with hp = battle.combatant1.hp - attacker.attack }}
else
    { battle with combatant2 = { battle.combatant2 with hp = battle.combatant2.hp - attacker.attack }}

which is also terrible code, I would appreciate any advice on it. But with nested collections it gets even more complicated, and event doesn't look functional to me anymore:

let containsTarget = List.contains target
let transformCombatant combatant = if combatant = target then { combatant with hp = combatant.hp - attacker.attack } else combatant
let transformGroup = List.map transformCombatant
let checkGroup group =
    if group |> containsTarget then
        group |> transformGroup
    else
        group
let transformGroups = List.map checkGroup

{ battle with combatantGroups = transformGroups battle.combatantGroups }

Can you please give me advise on how can I use features of F# and functional programming, to make given code more pretty and concise?


texts:
I implemented a Karatsuba algorithm in Python but it doesn't give me the exact answer.

def karatsuba(x, y):
    if x < 10 or y < 10:
        return x*y

    #making the two numbers strings here
    str_x = str(x)
    str_y = str(y)

    #finding the mid point for each number here
    n = max(len(str(x)), len(str(y)))
    n_2 = int(n / 2)

    #higher bits of each number
    x_h = int(str_x[:n_2])
    y_h = int(str_y[:n_2])

    #lower bits for each number here
    x_l = int(str_x[n_2:])
    y_l = int(str_y[n_2:])

    a = karatsuba(x_h, y_h)
    d = karatsuba(x_l, y_l)
    e = karatsuba(x_h + x_l, y_h + y_l) - a - d

    return a*10**len(str_x) + e*10**(len(str_x) // 2) + d

result = karatsuba(1234, 8765)
print(result)

I think its because I am taking integer values and ignore decimals of floating point values.

When I run the above program my answer is 10,402,010 whereas the actual answer is 10,816,010

How can I improve this?


texts:
So I wrote this to simulate a program that would have a start and stop feature, and has a tab design. Right now there is a tab that has a RichEdit object intended to be a running log.

As you can see, after we "start" the program I put just some milliseconds of sleep to simulate running instructions. I created a function to check for requests that would be called on a larger scale randomly throughout code to ping the GUI per say.

#include <GUIConstantsEx.au3>
#include <GuiRichEdit.au3>
#include <WindowsConstants.au3>

Global Const $h_numOfTabs = 2
Global Enum $H_TAB_1, $H_TAB_2, $H_TAB_END
Global $hGui, $h_logRichEdit, $iMsg,  $h_tabs, $h_startButton, $h_stopButton

Example()

Func Example()
    $hGui = GUICreate("Example (" & StringTrimRight(@ScriptName, StringLen(".exe")) & ")", 400, 550, -1, -1)

    ; ADD START AND STOP BUTTONS
    $h_startButton = GUICtrlCreateButton( "Start", 50, 450 )
    $h_stopButton = GUICtrlCreateButton( "Stop", 150, 450 )

    $h_tabs = GUICtrlCreateTab( 5, 5, 390,375 )

    ; LOG TAB
    GUICtrlCreateTabItem( "Log" )
    $h_logRichEdit = _GUICtrlRichEdit_Create ( $hGui, "", 8, 30, 384, 347, BitOR( $ES_MULTILINE, $WS_VSCROLL, $ES_AUTOVSCROLL, $ES_READONLY ) )

    ; STATS TAB
    GUICtrlCreateTabItem( "Stats" )

    ; Close TABS
    GUICtrlCreateTabItem( "" )

    GUISetState( @SW_SHOW ) ; initialize the gui

    While True
        CheckRequests()
    WEnd
EndFunc   ;==>Example

Func Start()
    while true
        Sleep(100)
        CheckRequests()
    WEnd
EndFunc

Func Stop()

EndFunc

Func CheckRequests()
    $iMsg = GUIGetMsg()
    while $iMsg <> 0
        Select
            Case $iMsg = $GUI_EVENT_CLOSE
                _GUICtrlRichEdit_Destroy($h_logRichEdit) ; needed unless script crashes
                ; GUIDelete()   ; is OK too
                Exit
            Case $iMsg = $h_tabs
                Switch GUICtrlRead( $h_tabs )
                    Case $H_TAB_1
                        ControlShow( $hGui, "", $h_logRichEdit )
                    Case Else
                        ControlHide( $hGui, "", $h_logRichEdit )
                EndSwitch
            Case $iMsg = $h_startButton
                Start()
            Case $iMsg = $h_stopButton
                Stop()
        EndSelect
        $iMsg = GUIGetMsg()
    WEnd
EndFunc

At about 500ms sleep, the lag when switching tabs is visible.

My question: On a larger scale, is this how we would handle/update things that are specific to a tab while running a larger program? If not, what would be a more efficient way of updating tab specific properties while running a larger overall program.

I have also seen a design recently where all the tabs and related components were their own GUI's but I am not sure the relevance of everything being its own GUI and if it pertains to this question.

Any help or clarification is greatly appreciated, I am new to AutoIT and trying to figure out some do's and dont's as well as efficiency.


texts: Is this a safe way to parse out HTML tag attributes?

texts:
I needed a super simple parser to get HTML attributes and their values. I didn’t want to load a big library or anything so I made this.

I realize I am making assumptions here, mainly:

Attribute values will be surrounded with either single or double
quotes.
The input string will end with > or />.

Besides those assumptions are there any other glaring issues here?

Dictionary<string, string> HTMLAttributes(string tag)
{
    Dictionary<string, string> attr = new Dictionary<string, string>();

    MatchCollection matches =
        Regex.Matches(tag, @"([^\t\n\f \/>""'=]+)(?:=)('.*?'|"".*?"")(?:\s|\/>|\>)");

    foreach (Match match in matches)
    {
        attr.Add(match.Groups[1].Value,
            match.Groups[2].Value.Substring(1, match.Groups[2].Value.Length - 2)
            );
    }

    return attr;
}

Running:

HTMLAttributes("<body class=\" something \" hello='world' />");

Returns:

{
    class: " something ",
    hello: "world"
}

Sample:

http://ideone.com/ZBaBhB


texts:
I am new to programming, python and raspberry-pi, but I am keen to learn more. After doing a few basic tutorials I though it might be best to give it a shot and just come up with a task in which I could practice my current skills.
I prepared a csv file with morse-code and wrote a little script to access the csv and translate it into a blinking LED.
It works! Now I would like to learn a bit more and improve my code. How would a simpler/faster/neater solution look like?

I would appreciate any kind of constructive criticism. (I made a few comments for myself. I hope it is not too annoying)

import RPi.GPIO as GPIO
import time
import csv

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

#cleaning out the csv

with open('Morse.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

    letters = [] #a new list with letters only
    codes = [] #a new list with morse code only

    next(readCSV) #jump over the column description line and an empty line
    next(readCSV)

    for row in readCSV: #fill up the new lists

        letter = row[0]
        code = row

        code.remove(row[0])

        letters.append(letter) #append letters only
        codes.append(code) #append everything but letters

LetterInput = input('what do you want to morse? ')

MorseCode = [] #a new list where the final code for the LED input is saved

for SingLetter in LetterInput: #iterate through the input

    SingLetUp = SingLetter.upper() #capitalize letters so they can be found in csv

    if SingLetUp not in letters: #jump over spaces and special characters
        continue

    MorseDex = letters.index(SingLetUp) #find code that corresponds with letter by matching indices
    SingCode = codes[MorseDex]
    MorseCode.append(SingCode) #fill up list

#iterate through list in list to seperate single words

for pos in MorseCode:
    for sing in pos:
        print(sing)

        x = 'short'
        y = 'long'
        z = 'none'

#LED blinks while parsing through the list

        if sing == x:
            GPIO.output(18, GPIO.HIGH)
            time.sleep(0.2)
            GPIO.output(18, GPIO.LOW)
            time.sleep(0.5)

        if sing == y:
            GPIO.output(18, GPIO.HIGH)
            time.sleep(1)
            GPIO.output(18, GPIO.LOW)
            time.sleep(0.5)

        if sing == z:
            GPIO.output(18, GPIO.LOW)
            time.sleep(1)

GPIO.output(18, GPIO.LOW)
GPIO.cleanup()

And here is the csv file

letter,position 1,position 2,position 3,position 4,position 5
,,,,,
A,short,long,none,none,none
B,long,short,short,short,none
C,long,short,long,short,none
D,long,short,short,none,none
E,short,none,none,none,none
F,short,short,long,short,none
G,long,long,short,none,none
H,short,short,short,short,none
I,short,short,none,none,none
J,short,long,long,long,none
K,long,short,long,none,none
L,short,long,short,short,none
M,long,long,none,none,none
N,long,short,none,none,none
O,long,long,long,none,none
P,short,long,long,short,none
Q,long,long,short,long,none
R,short,long,short,none,none
S,short,short,short,none,none
T,long,none,none,none,none
U,short,short,long,none,none
V,short,short,short,long,none
W,short,long,long,none,none
X,long,short,short,long,none
Y,long,short,long,long,none
Z,long,long,short,short,none
1,short,long,long,long,long
2,short,short,long,long,long
3,short,short,short,long,long
4,short,short,short,short,long
5,short,short,short,short,short
6,long,short,short,short,short
7,long,long,short,short,short
8,long,long,long,short,short
9,long,long,long,long,short
0,long,long,long,long,long


texts: Checking and returning Xml from a byte array

texts:
I have a byte array in a C# program.

I want to determine as quickly as possible if the content is Xml. If it's the case, I also want to return the Xml itself.

By now I have this method :

    protected bool TryGetXElement(byte[] body, out XElement el)
    {
        el = null;
        // if there is no data, this is not xml :)
        if (body == null || body.Length == 0)
        {
            return false;
        }

        try
        {
            // Load the data into a memory stream
            using (var ms = new MemoryStream(body))
            {
                using (var sr = new StreamReader(ms))
                {
                    // if the first character is not <, this can't be xml
                    var firstChar = (char)sr.Peek();
                    if (firstChar != '<')
                    {
                        return false;
                    }
                    else
                    {
                        // ultimately, we try to parse the XML
                        el = XElement.Load(sr);
                        return true;
                    }
                }
            }
        }
        catch
        {
            // if it failed, we suppose this is not XML
            return false;
        }
    }

Is there potential improvement?


texts: Usage of global variable for dynamic value that must be declared compile time

texts:
I've been trying to make a work-around for global usage; however, I can't seem to find an alternative.

I'd like to create a C++ suffix function which converts pixels to millimeters. A custom gui library I've been developing separates OS calls and the actual widget system in two separate headers (IoC); therefore, I do not have access to system-level DPI calls when creating widgets (which is when I'd want to use the suffix function). A kludgey work-around I've considered is maintaining a global variable / singleton. For example:

// widgets.h

...

class SystemProperties { // ! << SINGLETON CLASS HERE
  std::pair<double, double> dpi = {1, 1};

  SystemProperties() {}

  static auto self() -> SystemProperties& {
    static SystemProperties system_properties;
    return system_properties;
  }

 public:
  static auto set_dpi(const decltype(dpi)& dpi) {
    SystemProperties::self().dpi = dpi;
  }

  static auto get_dpi_x() { return SystemProperties::self().dpi.first; }
  static auto get_dpi_x() { return SystemProperties::self().dpi.second; }
};

double operator"" _inch_x(long double value) {
  return value * SystemProperties::get_dpi_x(); // ! << GLOBAL USAGE HERE
}

double operator"" _inch_y(long double value) {
  return value * SystemProperties::get_dpi_y(); // ! << GLOBAL USAGE HERE
}

...

// win32_implementation.h

#include "widgets.h"

...

auto init() {
  UINT dpiX, dpiY;
  GetDpiForMonitor(
      ::MonitorFromWindow(::GetDesktopWindow(), MONITOR_DEFAULTTOPRIMARY),
      MDT_EFFECTIVE_DPI, &dpiX, &dpiY);
  SystemProperties::set_dpi({dpiX, dpiY}); // ! << GLOBAL USAGE HERE
}

...

Of course I could implement some kind of additional IoC that does dpi conversion, but that would miss the point of being able to use the suffix operator. Perhaps I am getting too hung up on that function? What are some other work-arounds if possible?


texts: Project Euler # 15 Lattice paths in Python

texts:
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down,

there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?

from time import time
from functools import lru_cache

def make_grid(grid_size):
    """Return a list of lists containing grid."""
    grid = tuple((0,) * (grid_size + 1) for _ in range(grid_size + 1))
    return grid

@lru_cache(None)
def count_lattice_paths(matrix, row, column):
    """Return number of all possible paths from top left to bottom right of n * n grid."""
    if row == 0 or column == 0:
        return 1
    return count_lattice_paths(matrix, row - 1, column) + count_lattice_paths(matrix, row, column - 1)

if __name__ == '__main__':
    start_time = time()
    g = make_grid(20)
    length = len(g) - 1
    print(count_lattice_paths(g, length, length))
    print(f'Time: {time() - start_time} seconds.')


texts: Clean Code attempt of HOLES problem on codechef.com

texts:
The problem asks you to take read an integer (number of words to read) and then process words entered counting the number of "HOLES" exist.  Letters with HOLES are A B D O P Q and R.  Of those B has 2 holes A D O P Q R have 1 and any other letter not listed counts as 0 even lowercase equivalents.

The scope is fairly limited so try to just assess the code based on the problem listed.

Full problem description: here

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

class LetterEvaluator {
public:
    LetterEvaluator()
    :   letterValues(createMap())
    {}

    int getValueOf(const char letter) const {
        if(retrieveValueOfLetter(letter) == letterValues.end())
            return 0;
        else{
            return retrieveValueOfLetter(letter)->second;
        }
    }

private:
    const std::map<char,int> letterValues;

    std::map<char,int> createMap() const {
        std::map<char,int> initializedMap;
        initializedMap['A'] = 1;
        initializedMap['B'] = 2;
        initializedMap['D'] = 1;
        initializedMap['O'] = 1;
        initializedMap['P'] = 1;
        initializedMap['Q'] = 1;
        initializedMap['R'] = 1;
        return initializedMap;
    }

    std::map<char,int>::const_iterator retrieveValueOfLetter(const char letter) const {
        return letterValues.find(letter);
    }
};

class HolesInCapitalizedWordFinder {
public:
    HolesInCapitalizedWordFinder()
        :   numberOfHoles(0)
        ,   letterEvaluator()
    {}

    void processWord() {
        evaluate(readWord());
        printNumberOfHolesInWord();
    }

private:
    LetterEvaluator letterEvaluator;
    int             numberOfHoles;

    std::string readWord() const {
        std::string wordToEvaluate;
        std::cin >> wordToEvaluate;
        return wordToEvaluate;
    }

    void evaluate(const std::string& wordToEvaluate ) {
        numberOfHoles = 0;
        for(auto& character : wordToEvaluate) {
            if(isNotAnUpperCaseLetter(character)){
                numberOfHoles = -1;
                break;
            }
            numberOfHoles += letterEvaluator.getValueOf(character);
        }
    }

    bool isNotAnUpperCaseLetter(const char character) const{
        return character < 65 || character > 90;
    }

    void printNumberOfHolesInWord() const {
        if(numberOfHoles == -1) {
            std::cout << "Not all characters in that word are uppercase letters!\n";
        }
        else {
            std::cout << numberOfHoles << '\n';
        }
    }
};

int main() {
    std::ios::sync_with_stdio(false);

    int timesToRun = 0;
    std::cin >> timesToRun;

    HolesInCapitalizedWordFinder holesInCaptilizedWordFinder;

    for(int numberOfTimesRan = 1; numberOfTimesRan <= timesToRun; ++numberOfTimesRan) {
        holesInCaptilizedWordFinder.processWord();
    }
    return 0;
}


texts: A* path finding getting the node neighbors

texts:
Is there any way I can minimise this code.The code will get the neighbours of the current node and point the arrow to the current node

private boolean isDiagonal(int x, int y, Node node) {
    if (x == -1 && y == 1) {
        node.arrow.setDrawable("bottom-right");
        return true;
    } else if (x == 1 && y == 1) {
          node.arrow.setDrawable("bottom-left");
        return true;
    } else if (x == -1 && y == -1) {
          node.arrow.setDrawable("top-right");
        return true;
    } else if (y == -1 && x == 1) {
         node.arrow.setDrawable("top-left");
        return true;
    }
    // Determine here if it's cross
    else if (x == -1 && y == 0) {
        node.arrow.setDrawable("right");
        return true;
    } else if (x == 1 && y == 0) {
        node.arrow.setDrawable("left");
        return true;
    } else if (x == 0 && y == -1) {
        node.arrow.setDrawable("up");
        return true;
    } else if (y == 1 && x == 0) {
        node.arrow.setDrawable("down");
        return true;
    }
    return false;
}

output


texts:
I wrote this as an exercise. I think that I have some repetitive code in the "winner" function but I don't know exactly how to reduce it. Any other general advice would be welcome too.

#include<iostream>
#include<iomanip>

char table[3][3];
int turn=1;

void print_table()
{
    for (int i=0;i<3;i++)
    {
        for (int j=0;j<3;j++)
            std::cout<<std::setw(3)<<table[i][j];
    std::cout<<std::endl;
    }
}

void create_table()
{
    for (int i=0;i<3;i++)
        for (int j=0;j<3;j++)
            table[i][j]='*';
}

void input(int turn)
{
    int x=0,y=0;
    std::cin>>x>>y;
    if(turn%2==1)
        table[x][y]='X';
    else
        table[x][y]='O';
}

char winner()
{
    for(int i=0;i<3;i++)
        if(table[0][i]==table[1][i]&&table[1][i]==table[2][i]&&table[0][i]=='X')
        {
            return 'X';
        }

    for(int i=0;i<3;i++)
        if(table[i][0]==table[i][1]&&table[i][1]==table[i][2]&&table[i][0]=='X')
        {
            return 'X';
        }

        for(int i=0;i<3;i++)
        if(table[0][i]==table[1][i]&&table[1][i]==table[2][i]&&table[0][i]=='O')
        {
            return 'O';
        }

    for(int i=0;i<3;i++)
        if(table[i][0]==table[i][1]&&table[i][1]==table[i][2]&&table[i][0]=='O')
        {
            return 'O';
        }

      if(table[0][0]==table[1][1]&&table[0][0]==table[2][2]&&table[0][0]=='O')
      {
            return 'O';
      }

      if(table[0][0]==table[1][1]&&table[0][0]==table[2][2]&&table[0][0]=='X')
      {
            return 'X';
      }

      return '\0'; ///default
}

int main(){

create_table();
print_table();

while (turn<=9&&winner()=='\0')
{
input(turn);
print_table();
winner();
turn++;
}

if(winner()!='\0')
    std::cout<<std::endl<<"winner:"<<winner();
else
    std::cout<<"Draw.";
}


texts:
In a plugin that I am currently authoring, I am using a function to check whether the device provides gyroscopic data. Although intuitively this can be easily resolved by checking the value of window.DeviceOrientationEvent, i.e.:

if (window.DeviceOrientationEvent) {
    // Ok, device orientation event listening is supported!
}

…this statement also resolves true when on a device with no functional gyroscope, i.e. Google Chrome on a laptop. The event data returned for alpha, beta and gamma are, however, null. Basically, the window.DeviceOrientationEvent does not tell me if there is gyroscopic data available, but only informs me if the browser/user-agent supports the event.

Therefore, not only do I have to check for support for the event, but also have to cross verify the value of alpha, beta or gamma such that they are not null. The best way I could check is using promises, which I feel a bit cumbersome and long-winded:

var check = {
    // Does it have a working gyroscope?
    gyroscope: function() {
        var d = new $.Deferred(),
            handler = function(e) {
                d.resolve({
                    alpha: e.alpha,
                    beta: e.beta,
                    gamma: e.gamma
                });
                // Listen to device orientation once and remove listener immediately
                window.removeEventListener('deviceorientation', handler, false);
            };
        window.addEventListener('deviceorientation', handler, false);
        return d;
    }
}

// Wait for gyroscope data
$.when(check.gyroscope()).done(function(r) {
    if(r.alpha === null && r.beta === null && r.gamma === null) {
        console.log('Device has no functional gyroscope.');
    } else {
        console.log('Device has functional gyroscope.')
    }
});

I am wondering if there is a cleaner way to write this code?


texts:
I'm new to JavaScript, and wrote this little animation in canvas. I'm wondering if anyone has any suggestions as for how to improve it.

When running the code, the JavaScript draws a scene of three pyramids, a sun, and a sky. The sun and gradient of the sky animate over time.

The code is working perfectly, but I would like to improve it and make it more efficient.

//render the canvas at 2x dpi
var canvas = document.getElementById('myCanvas');
canvas.width = 1920;
canvas.height = 816;
canvas.style.width = "960px";
canvas.style.height = "408px";
//rescale the grid system for 2xdpi
var ctx = canvas.getContext('2d');
ctx.scale(2, 2);

//start drawing the scene
var canvasElement = document.querySelector("#myCanvas");
var ctx = canvasElement.getContext("2d");

var skyY = 100;
var skyYDirection = 1;

function drawsky() {
    //generate the sky gradient
    var sky = ctx.createLinearGradient(0, skyY, 0, 0);
    sky.addColorStop(0, "#a7bde0");
    sky.addColorStop(1, "#3c68b1");

    //draw the sky
    ctx.fillStyle = sky;
    ctx.fillRect(0, 0, 960, 408);
}

function animateSky() {
    //animate the sky
    skyY += skyYDirection;
}

function drawground() {
    //draw the ground
    ctx.fillStyle = "#e9bf83";
    ctx.fillRect(0, 297, 960, 111);
}

function drawpyr1() {
    //draw pyramid1
    //walla
    ctx.beginPath();
    ctx.moveTo(516, 297);
    ctx.lineTo(595, 297);
    ctx.lineTo(632, 182);
    ctx.closePath();
    //fill
    ctx.fillStyle = "#3b230b";
    ctx.fill();
    //wallb
    ctx.beginPath();
    ctx.moveTo(595, 297);
    ctx.lineTo(764, 297);
    ctx.lineTo(632, 182);
    ctx.closePath();
    //fill
    ctx.fillStyle = "#d49c5f";
    ctx.fill();
}

function drawpyr2() {
    //draw pyramid2
    //walla
    ctx.beginPath();
    ctx.moveTo(322, 297);
    ctx.lineTo(410, 297);
    ctx.lineTo(497, 100);
    ctx.closePath();
    //fill
    ctx.fillStyle = "#3b230b";
    ctx.fill();
    //wallb
    ctx.beginPath();
    ctx.moveTo(410, 297);
    ctx.lineTo(695, 297);
    ctx.lineTo(497, 100);
    ctx.closePath();
    //fill
    ctx.fillStyle = "#d49c5f";
    ctx.fill();
}

function drawpyr3() {
    //draw pyramid3
    //walla
    ctx.beginPath();
    ctx.moveTo(179, 297);
    ctx.lineTo(245, 297);
    ctx.lineTo(324, 122);
    ctx.closePath();
    //fill
    ctx.fillStyle = "#3b230b";
    ctx.fill();
    //wallb
    ctx.beginPath();
    ctx.moveTo(245, 297);
    ctx.lineTo(541, 297);
    ctx.lineTo(324, 122);
    ctx.closePath();
    //fill
    ctx.fillStyle = "#d49c5f";
    ctx.fill();
}

function clearCanvas() {
    //clear the canvas
    ctx.clearRect(0, 0, 960, 408);
}

function drawsun(x, y) {
    //draw the sun
    ctx.beginPath();
    ctx.arc(x, y, 80, 0, 2 * Math.PI, false);
    ctx.fillStyle = "#fff1dc";
    ctx.fill();
}

var sunX = 700;
var sunY = 100;
var xDirection = -1;
var yDirection = 0.2;

function animateSun() {
    //animate the sun
    sunX += xDirection;
    sunY += yDirection;
}

//render the scene

function render() {
    //clear canvas
    clearCanvas();

    //layer / animate objs
    drawsky();
    animateSky();
    drawsun(sunX, sunY);
    animateSun();
    drawground();
    drawpyr1();
    drawpyr2();
    drawpyr3();

    //loop the render process
    window.requestAnimationFrame(render);
}

render();
/*nightfall*/

@keyframes nightfall {
    from {
        filter: brightness(1);
    }
    to {
        filter: brightness(0);
    }
}

canvas {
    animation: nightfall 20s forwards cubic-bezier(0.730, 0.010, 1.000, 0.300);
}
<html>
<body>
    <canvas id="myCanvas"></canvas>
    <script src="js/script.js" type="text/javascript"></script>
</body>

</html>


texts: Generating a random string of 6 characters long in Python 3.6.2

texts:
I am learning Python, so pardon me if this is the very crude approach.
I am trying to generate a random string using alphanumeric characters.
Following is my code:

#Generating random 6 character string from list 'range'.
def code():
    # List of characters [a-zA-Z0-9]
    chars = ['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','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','0','1','2','3','4','5','6','7','8','9']
    code = ''
    for i in range(6):
        n = random.randint(0,61)    # random index to select element.
        code = code + chars[n]      # 6-character string.
    return code

What I am trying to do is pick six random elements from the list of characters and append them.

Is there any better approach?


texts: Select multiple minimum items in an Array

texts:
I have an array and need to identify minimum value in the array - This is easy. However, this array can have duplicates and there exist multiple minimum values and we need to identify them.

The following code works and is done through 2 loops. First loop identifies the minimum value and the second loop all values which equate to the minimum value.

Please let me know your thoughts and if any other efficient way is possible.

public static List<Integer> getMinIndex(double... arrayList){
    int minIndex = 0;
    int i = 0;
    int len = arrayList.length;
    while(i < len){
        if(arrayList[i] < arrayList[minIndex]  )
            minIndex = i;
        i++;
    }

    //Below is specifically for case where are multiple minimums and we want all of them
    i=0;
    List<Integer> minList = new ArrayList<Integer>();
    while(i < len){
        if(arrayList[i] == arrayList[minIndex]  )
            minList.add(i);
        i++;
    }
    logger.debug("Postition of min-item in arraylist {}",Arrays.toString(minList.toArray()));
    return minList;
}


texts: Getting a sum of added cells in an ultragridview

texts:
The objective of this code is to add the first 3 cells of a column
  with the next 9 in another column and then to total out in 2
  currencyeditor control (which is like a textbox).

Here is a demonstration of what I am adding.

For the 1st control it's going to be the actual + adjusted (left square).
For the 2nd control value will be the actual + original (right square).

I've never added different rows of an ultragridrow before this.  It works right now but doesn't look neat or professional, and I really hate the saying "at least it works" .  I was just wondering if you could help me write this code neater or more efficiently?

private void doMath()
{
    decimal actualsum = 0m;
    decimal adjustedsum = 0m;
    decimal totalsum = 0m;

    for (int i = 0; i < 2; i++)
    {
        var row = dgvBudget.Rows[i];
        actualsum += Convert.ToDecimal(row.Cells["Actual_c"].Value);
    }
    for (int i = 3; i < 12; i++)
    {
        var row = dgvBudget.Rows[i];
        adjustedsum += Convert.ToDecimal(row.Cells["PrevFY"].Value);
    }
    totalsum = (adjustedsum + actualsum);
    nbrAdjustedTotal.Value = totalsum;
    adjustedsum = 0;
    actualsum = 0;
    totalsum = 0;

    for (int i = 0; i < 2; i++)
    {
        var row = dgvBudget.Rows[i];
        actualsum += Convert.ToDecimal(row.Cells["Actual_c"].Value);
    }
    for (int i = 3; i < 12; i++)
    {
        var row = dgvBudget.Rows[i];
        adjustedsum += Convert.ToDecimal(row.Cells["BudgetAmt"].Value);
    }
    totalsum = (adjustedsum + actualsum);
    nbrOriginalTotal.Value = totalsum;
}


texts: Is there a better way than lambda to filter on attributes/methods of objects?

texts:
Is there a better (more pythonic?) way to filter a list on attributes or methods of objects than relying on lamda functions?

contexts_to_display = ...
tasks = Task.objects.all()
tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)
tasks = filter(lambda t: not t.is_future(), tasks)
tasks = sorted(tasks, Task.compare_by_due_date)

Here, matches_contexts and is_future are methods of Task.  Should I make those free-functions to be able to use filter(is_future, tasks)?

Any other comment?


texts: Writing to an HttpURLConnection in a loop

texts:
I have this method which sends binary data to server. The code works fine, but still, it's structure is kinda stupid: output and input connections are opened like thousands times (depends on data size), closed only once.

I cannot move the code that opens connection outside of the loop because I'm getting strange errors, like the data was never sent to server.

Please help me to restructure this code so it could still work and have a correct structure:

OutputStream os = null;
StringBuffer messagebuffer = new StringBuffer();
HttpURLConnection huc = null;
DataInputStream dis = null;
InputStream in = null;
Path path = null;
byte[] buf = new byte[64 * 1024];
int bytesRead = 0;

try {
  path = Paths.get("D:\\testfile.rar");
  in = Files.newInputStream(path);

  int i = 0;
  URL u = new URL(defaultURL);

  while ((bytesRead = in.read(buf)) != -1) {

    huc = (HttpURLConnection) u.openConnection(); // wrong
    huc.setRequestMethod("POST");
    huc.setRequestProperty("chunk-number", i + "");
    huc.setDoOutput(true); // wrong
    huc.setDoInput(true); // wrong
    os = huc.getOutputStream(); // wrong
    os.write(buf, 0, bytesRead);
    os.flush();
    System.out.println(i++ + " " + bytesRead);

    int ch;
    dis = new DataInputStream(huc.getInputStream()); // wrong

    long len = huc.getContentLength();
    if (len != -1) {
      for (int k = 0; k < len; k++)
        if ((ch = dis.read()) != -1)
          messagebuffer.append((char) ch);
        else {
          // if the content-length is not available
          while ((ch = dis.read()) != -1)
            messagebuffer.append((char) ch);
          }
    }
    Thread.sleep(16);
  }
  dis.close();
  huc.disconnect();

  int statusCode = huc.getResponseCode();
  String message = huc.getResponseMessage();
  messagebuffer.append("status code=" + statusCode + "\n");
  messagebuffer.append("response message=" + message + "\n");

} catch (Exception ex) {
  // throw errors
} finally {
  // closing stuff
}
return messagebuffer.toString();


texts: Android sharing selected text to other apps

texts:
I am somewhat new to Java.  I want to know if this is the proper way to share text with other Android applications, and if I am properly determining if the text is selected.  Is there a better way to share the selected text?  Is my decision statement proper?  The app works just fine.

package com.kylelk.sharedemo;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;

public class MainActivity extends Activity
{
    private Button shareBtn;
    private EditText textToShare;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        shareBtn = (Button) findViewById(R.id.shareText);
        shareBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v){

                //Get the selected text
                EditText et=(EditText)findViewById(R.id.textToShare);
                int startSelection=et.getSelectionStart();
                int endSelection=et.getSelectionEnd();
                String selectedText = et.getText().toString().substring(startSelection, endSelection);

                //if no text is selected share the entire text area.
                if(selectedText.length() == 0){
                    textToShare = (EditText) findViewById(R.id.textToShare);
                    String dataToShare = textToShare.getText().toString();
                    selectedText = dataToShare;
                }

                //Share the text
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, selectedText);
                sendIntent.setType("text/plain");
                startActivity(sendIntent);

            }
        });
    }
}

Here is the complete project: https://github.com/kylelk/ShareDemo


texts:
For a project, I need to write a basic template manager who will be responsible to load the requested HTML or PHP template when the user clicks on a menù link. It's like a page loader since that all the loaded templates are static HTML pages. I want to improve it if is it possible. Here is the code.

on the main index of the project I have a jQuery code like this:

<script>
$(document).ready(function(){

$('.contents').load('templates/home.php');

$(document).on('click','a',function(e){
    e.preventDefault();
    $('#nav-modal').modal('hide');
    var url = $(this).attr('href');
    if(url == 'booking/'){
        window.location.href= 'booking/';
    } else {

    $.ajax({
        type: 'GET',
        url: 'templates/TemplateController.php'+url,
        cache: false,
        dataType: 'html',
        success: function(response){
             $('.contents').empty()
             .html(response);
        }
        });
    }

    });

});
</script>

on the PHP 'controller' side I have this code who will only call a class to obtain the needed files. The URL passed from AJAX to the controller is something like this: ?tpl=atemplate

<?php
require_once 'Autoloader.php';

if(isset($_GET['tpl'])){
    $tpl = new TemplateLoader;
    echo $tpl->render($_GET['tpl']);
}

?>

And then in the simple class, I have only a switch control that will select what is the requested template to load on the index

<?php

class TemplateLoader{

    public function __construct(){
        #$this->path = $path;
    }

    public function render($tpl){

        switch($tpl){
            case 'home':
                echo file_get_contents('home.php');
                break;
            case 'about':
                echo file_get_contents('about.php');
                break;
            case 'services':
                echo file_get_contents('services.php');
                break;
            case 'contacts':
                echo file_get_contents('contacts.php');
                break;
            case 'prices':
                echo file_get_contents('prices.php');
                break;
        }
    }
}

?>


texts: Load bitmap object data into array of byte values

texts:
I'm building this as part of a larger class to rapidly search for smaller images inside larger images. This is my first serious F# project so comments especially concerning style and organization are appreciated.

module imagesearch =
    type BitmapSearchClass() =
        // Largely inspired by this article
        // http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.aspx
        static member loadBitmapIntoArray (pBitmap:Bitmap) =
            let tBitmapRectangle = Rectangle(0, 0, pBitmap.Width, pBitmap.Height)

            let tLockMode = ImageLockMode.ReadOnly
            let tImageFormat = PixelFormat.Format24bppRgb

            let tBitmapData = pBitmap.LockBits(tBitmapRectangle, tLockMode, tImageFormat)
            let tIntPtr = tBitmapData.Scan0

            let tImageByteLength = Math.Abs(tBitmapData.Stride) * pBitmap.Height

            // Zerocreate creates the "empty" array
            let tImageRGBValues : byte array = Array.zeroCreate tImageByteLength

            do Marshal.Copy(tImageRGBValues, 0, tIntPtr, tImageByteLength)

            do pBitmap.UnlockBits(tBitmapData)

            tImageRGBValues, pBitmap.Width, pBitmap.Height

Current state of the module is below

module ImageSearch =
    type BitmapSearch() =
        // Largely inspired by this article
        // http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.aspx
        static member LoadBitmapIntoArray (pBitmap:Bitmap) =
            let tBitmapData = pBitmap.LockBits( Rectangle(Point.Empty, pBitmap.Size),
                                                ImageLockMode.ReadOnly,
                                                PixelFormat.Format24bppRgb )

            let tImageArrayLength = Math.Abs(tBitmapData.Stride) * pBitmap.Height
            let tImageDataArray = Array.zeroCreate<byte> tImageArrayLength

            Marshal.Copy(tImageDataArray, 0, tBitmapData.Scan0, tImageArrayLength)
            pBitmap.UnlockBits(tBitmapData)

            tImageDataArray, pBitmap.Width, pBitmap.Height


texts: Right-justifying a number with dot leaders

texts:
I'm working on a small library to help me format numbers easier as my current project deals with a lot of them.  I want to be able to just supply the value, precision, width, and fillchar to a method and have it do all the work for me.

Based on the standard way of doing things with rjust()…

print '{:.2f}'.format(123.456).rjust(10, '.')
# ....123.46

… I could write:

def float_rjust(value, width, precision=2, fillchar=' ', separator='', sign=''):
    #[sign][#][0][width][,][.precision][type]
    spec = '{{:{1}{2}{3}.{4}f}}'.format(
        sign,
        width,
        separator,
        precision
    )
    return spec.format(value).rjust(width, fillchar)

However, I have found that the format() method actually allows for justifications in it:

print '{:.>10.2f}'.format(123.456)
# ....123.46

… so I could also write it this way:

def float_rjust(value, width, precision=2, fillchar=' ', separator='', sign=''):
    #[[fill]align][sign][#][0][width][,][.precision][type]
    spec = '{{:{0}>{1}{2}{3}.{4}f}}'.format(
        fillchar,
        sign,
        width,
        separator,
        precision
    )
    return spec.format(value)

My main question is, should I used the [[fill]align] formatting spec in format() to do justification, or is it more Pythonic to use format().rjust()?


texts: Are fetchAll() and for() good choices for my code?

texts:
I use the following code: fetchAll and for($mich=0;$mich<10;$mich++).

Is this the best way?

Is there a better way, either to optimize or replace this code?

<?php
include("cache/phpfastcache.php");
phpFastCache::setup("storage","auto");
$cache = phpFastCache();
$products = $cache->get("product_page");
if($products == null) {
    $akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
    $akhbarkotah1->execute();
    $products = $akhbarkotah1->fetchAll();
    $cache->set("product_page", $products,30);
}
for($mich=0;$mich<10;$mich++){
    $text1 =$products[$mich][0];
    $time1 =$products[$mich][1];
    ?>

<?php echo $text1; ?>

                <?php echo timeTonow($time1); ?>

    <?php
}
?>


texts: Circular Queue in C for an embedded project

texts:
I wrote a simple circular queue. (in order to store characters because of the fact, that I am using UART through the DMA and sometimes my printf's override each other)
I am looking for some review, though my testfile was successful I have the feeling I've overseen something and the queue might be buggy at some point.
I appreciate any kind of critics, ideas or improvements

Header File:

#ifndef __QUEUEH
#define __QUEUEH

typedef struct queue {

    unsigned int head;
    unsigned int tail;
    unsigned char* buf;
    unsigned int bufSize;
    unsigned int freeSpace;
    unsigned int occuSpace;
    unsigned char initialized;

} queue_t;

extern int queue_init(queue_t* q, unsigned char* buf, unsigned int bufSize);
extern int enqueue(queue_t* q, unsigned char* element, unsigned int size);
extern int dequeue(queue_t* q, unsigned char* str, int strMaxSize);
// change to static
extern int printQueue(queue_t* q);
#endif

C-File:

#include "queue.h"
#if !defined bool
typedef unsigned char bool;
#endif

extern int queue_init(queue_t* q, unsigned char* buf, unsigned int bufSize) {
    q->head = -1;
    q->tail = 0;
    q->buf = buf;
    q->bufSize = bufSize;
    q->freeSpace = bufSize;
    q->occuSpace = 0;
    q->initialized = 1;
    return 0;
}

static inline bool moveTail(queue_t* q) {
    q->occuSpace = q->occuSpace - 2 - (q->buf)[q->tail];
    q->freeSpace = q->freeSpace + 2 + (q->buf)[q->tail];
    q->tail = (q->tail + (q->buf)[q->tail]+2) % (q->bufSize);
    return 0;
}

static inline bool enoughSpaceAvailable(queue_t* q, unsigned int size) {
    if(q->freeSpace < size+2)
        return 0;
    return 1;
}

extern int enqueue(queue_t* q, unsigned char* element, unsigned int size) {

    if(size==0)
        return -5;
    else if(size>q->bufSize-2)
        return -8;

    while(!enoughSpaceAvailable(q,size))
            moveTail(q);

    q->occuSpace = q->occuSpace + 2 + size;
    q->freeSpace = q->freeSpace - 2 - size;
    q->head = (q->head+1)%(q->bufSize);
    (q->buf)[q->head] = size;
    for(int i = 0; i<size; i++) {
        q->head = (q->head+1)%(q->bufSize);
        (q->buf)[q->head] = element[i];
    }
    q->head = (q->head+1)%(q->bufSize);
    (q->buf)[q->head] = size;
    return 0;
}

extern int dequeue(queue_t* q, unsigned char* str, int strMaxSize) {

    int len = q->buf[q->tail];
    if(q->freeSpace == q->bufSize) return -6; else if(strMaxSize<len) return -7;

    for(int j=0; j<len; j++) {
        str[j] = q->buf[(q->tail+1+j)%(q->bufSize)];
    }
    moveTail(q);
    return 0;
}


texts:
I am new to C# and have tried to solve a problem statement from CodeChef:

Problem statement

  You are given an array A of N integers. You are to fulfill M queries.
  Each query has one of the following three types:

  C d : Rotate the array A clockwise by d units.
  A d : Rotate the array A anticlockwise by d units.
  R d : Query for the value of the element, currently being the d-th in the array A.

  Input

  The first line contains two numbers - N and M respectively.

  The next line contains N space separated Integers, denoting the array
  A.

  Each of the following M lines contains a query in the one of the forms
  described above.

  Output

  For each query of type R output the answer on a separate line.

  Constraints

  \$1 \le N \le 100000\$
  \$1 \le M \le 100000\$
  \$1 \le d \le N\$, in all the queries
  \$1 \le \$ elements of A \$ \le 1000000\$

  The array A and the queries of the type R are 1-based.

  Example

  Input:

5 5
5 4 3 3 9
R 1
C 4
R 5
A 3
R 2

  Output:

5
3
3

My Code:

using System;
using System.Collections;
using System.Text;

namespace RotationSeptChallenge
{

class Program
{
    public static void Main(string[] args)
    {

        string nm = Console.ReadLine();
        string n = nm.Split(' ')[0];
        string m = nm.Split(' ')[1];
        int loopvar = int.Parse(m);
        string[] arr = new string[int.Parse(n)];
        var temp = Console.ReadLine().Split(' ');
        for (int i = 0; i < temp.Length; i++)
        {
            arr[i] = temp[i];
        }
        for (int loop = 0; loop < loopvar; loop++)
        {
            var optionanddistance = Console.ReadLine();
            char option = char.Parse(optionanddistance.Split(' ')[0]);
            int distance = int.Parse(optionanddistance.Split(' ')[1]);

            if (option == 'C')
            {
                ArrayList tempAL = new ArrayList();
                tempAL.AddRange(arr);
                tempAL.CopyTo(distance, arr, 0, arr.Length - distance);
                tempAL.CopyTo(0, arr, arr.Length - distance, distance);
            }

            if (option == 'A')
            {
                ArrayList tempAL = new ArrayList();
                tempAL.AddRange(arr);
                tempAL.CopyTo(arr.Length - distance,arr,0,distance);
                tempAL.CopyTo(0,arr,distance,arr.Length - distance);
            }

            if (option == 'R')
            {
                Console.WriteLine(arr[distance - 1]);
            }

        }

    }
  }
}

My solution seems to be right when I tried with a few sample outputs. However, Time Limit Exceeded was the result of my Submission. The time Limit is set to 1 sec and my solution takes >1sec. What seems to be the problem? How can I optimize this code to perform better?


texts: Producing excerpts from a file at specified positions within long lines (>1 M characters)

texts:
I'm trying to read a file containing over 10.000 lines and each line contains an ID for an individual and a very long string composed of more than 1 million characters (numbers as example: 2200500200...205 until 1 million characters long).

I need to go through this long string and retrieve a subset based on flag information formed by 0 or 1s coming from a string called flagArray01String in the sample code, so I'm checking one string of the same length and printing the subset in a file.

I'm in doubt if I should convert the long strings (string from file and string composed of flags) to char and perform the loop after that.  I'm looking forward to receiving any comments that could help me obtaining a better performance.

Should I load all the strings in memory for some individuals?  Are there any other performance tricks?

Example of a sample file:

ID1 2020205000200200202020
ID2 2020205000200200202020
ID3 2020205000200200202020

...
ID10000 2020205000200200202020

Example of flag:
flag = 1000001111111111111100, where all the positions with 1´s should be retrieved and printed in a separated file.

if (IN_file.is_open())
{
    getline(IN_file, headerFileOriginal);
    while (IN_file >> idOriginal >> longString)
    {
        sizeTemp = longString.size();
        if (sizeTemp > 0)
            numbIdsOriginal++;
        for (int p = 0; p < flagArray01String.size(); p++)
        {
            if ((flagArray01String[p] == '1'))
            {
                subsetString = subsetString + longString[p];
            }
        }
        OUT_FILE << idOriginal << '\t' << subsetString << endl;
        subsetString = "";
    }
}
else
{
    myfileLog << "Problems to open file " << IN_file_StringName << endl;
    cout << "Problems to open file " << IN_file_StringName << endl;
}

IN_file.close();
OUT_FILE.flush();
OUT_FILE.close();


texts:
After a conversation with my math teacher about a base algebra (base 43 using all the algebra symbols) and finding it more than the 30 min of work I was looking for, I decided to make this instead.

import math

letters = ["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"]

def print_bases(base: int, num: int) -> None:
    new_num = []
    div = num
    while div != 0:
        if len(str(div % base)) > 1:
            new_num.insert(0, letters[((div % base) - 10)])
        else:
            new_num.insert(0, str(div % base))
        div = math.floor(div / base)
    new_num = "".join(new_num)
    print(f"{num} in base {base} is {new_num}")

while True:
    while True:
        try:
            num = int(input("Please enter a number in base 10: "))
            break
        except (NameError, ValueError):
            print("Please use numbers only")
    for base in range(35):
        print_bases(base + 2, num)

As this was made for fun I forgot to add any comments (doing that is still new for me), so I hope it makes sense. My main problem is I want to know if I can get rid of letters. Also print_bases seems messy and I wonder if that can be cleaned up. Any other small fixes would be appreciated.

;)


texts:
I'm making a prime number scanning algorithm in Java. It uses the concept of the Sieve of Eratosthenes to efficiently find the prime numbers.

It works well and can calculate all the prime numbers under 1,000,000 in less than a second on my laptop, but I was wondering how the algorithm could be further improved.

public static void eratoImproved(long max){

    long start = System.currentTimeMillis();

    ArrayList<Long> invalidated = new ArrayList<>(); // where invalidated numbers will be stored.

    // prepare
    double maxFac = Math.sqrt(max);
    int f = 2;
    while(f <= maxFac){
        boolean isNew = true;
        for(long l : invalidated){
            if(f % l == 0){
                isNew = false;
            }
        }
        if(isNew) {
            invalidated.add(Math.round(f + 0.0));
        }
        f++;
    }

    ArrayList<Long> primes = new ArrayList<>();

    long i = 3; // current test

    for(long l : invalidated){
        primes.add(l);
    }

    while(i <= max){
        boolean v = true;
        for(long s : invalidated){
            if(i % s == 0){
                v = false;
                break;
            }
        }

        if(v){
            primes.add(i);
            long m = 2*i;
            if(primes.size() >= 150){
                String s = Math.round(((i + 0.0)/max)*100) + "%: ";
                for(long l : primes){
                    s += l + "/";
                }
                System.out.println(s);
                primes.clear();
            }

        }
        i += 2;
    }
    System.out.println("Completed search!");
    String s = "Remaining primes: ";
    for(long l : primes){
        s += l + "/";
    }
    System.out.println(s);
    primes.clear();

    System.out.println("Conducted search in " + (System.currentTimeMillis() - start)/1000 + " seconds.");
}

I've optimized everything I can think of, but I wanted to get a second opinion.


texts: Check “five in a row” for a 15x15 chess board (part 2)

texts:
This is a follow-up from here. I have a further optimization for space complexity by store only direction status data for one row for each directions (refer to variable stats). Any advice on algorithm time complexity improvement, code bugs or code style advice is highly appreciated.

  Problem:

  For a given board, judge who had complete a continuously line (could
  be horizontal, vertical or diagonal) of 5 pieces. Input is a 15×15
  chess board, could be white (1), black (2) or empty (0). Return if
  white win, if black win, if both win or if none of them win.

import random
import pprint
def check_five(matrix):
    directions = [(0,-1),(-1,0),(-1,-1),(-1,1)] # (row, col)
    stats = [[0] * len(directions) for _ in range(len(matrix[0]))]
    WHITE = 1
    BLACK = 2
    EMPTY = 0
    WIN = 5
    BLACK_WIN = False
    WHITE_WIN = False
    # init first row
    for i in range(len(matrix[0])):
        if matrix[0][i] != EMPTY:
            for j in range(len(directions)):
                stats[i][j] = 1
    for row in range(1, len(matrix)):
        for col in range(0, len(matrix[0])):
            for d_i, d_v in enumerate(directions):
                if matrix[row][col] == EMPTY:
                    stats[col][d_i] = 0
                elif len(matrix)>row+d_v[0] >= 0 and len(matrix[0])>col+d_v[1] >= 0 and matrix[row][col] == matrix[row+d_v[0]][col+d_v[1]]:
                    stats[col][d_i] += 1
                else:
                    stats[col][d_i] = 1
                if stats[col][d_i] == WIN:
                    if matrix[row][col] == WHITE:
                        WHITE_WIN = True
                    else:
                        BLACK_WIN = True
                    if WHITE_WIN and BLACK_WIN:
                        return (True, True)

    return (WHITE_WIN, BLACK_WIN)

if __name__ == "__main__":
    matrix = [[random.choice([0,1,2]) for _ in range(15)] for _ in range(15)]
    pprint.pprint(matrix, indent=4)
    print check_five(matrix)


texts: Efficiently generating HTML CSS table using Java

texts:
I am trying to generate an HTML table using Java. I have an object which I am iterating to make an HTML table.

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append("");
sb.append("");
sb.append("
");
sb.append(" ClientName");
sb.append("	");
sb.append(" SyncCount");
sb.append("	");
sb.append(" SyncPercentile");
sb.append("	");
sb.append(" SyncAvg");
sb.append("	");
sb.append(" SyncMax");
sb.append("	");
sb.append(" AsyncCount");
sb.append("	");
sb.append(" AsyncPercentile");
sb.append("	");
sb.append(" AsyncAvg");
sb.append("	");

for (DataMetrics metrics : dataMetricsList) {
    sb.append("
");
    sb.append(" " + metrics.getName());
    sb.append("	");
    sb.append(" " + metrics.getSyncCall());
    sb.append("	");
    sb.append(" " + metrics.getSyncPercent());
    sb.append("	");
    sb.append(" " + metrics.getSyncAvg());
    sb.append("	");
    sb.append(" " + metrics.getSyncMax());
    sb.append("	");
    sb.append(" " + metrics.getAsyncCall());
    sb.append("	");
    sb.append(" " + metrics.getAsyncPercent());
    sb.append("	");
    sb.append(" " + metrics.getAsyncAvg());
    sb.append("	");
    sb.append("
");
}
sb.append("
");
sb.append("");
sb.append("");

System.out.println(sb.toString());

Somehow, the code looks pretty ugly to me in the way HTML and CSS are being used within StringBuilder. I am opting for code review to see whether we can improve anything here.  Is there any better way of writing this code?


texts:
I have been working with Java for a little more than a year. I recently have built a Tic Tac Toe game as an assignment for my Java class. After my instructor graded it, he wrote a comment around my validation method logic. Even though I got 100%, he said that the logic in my validation method is too cumbersome. He stated that I should look into a for orwhile` statement in order to clean out some code in my validation method.

Is there really a way to put all my conditional if statements in to a for or while loop? And if so, I would like to know what logic goes behind that. This program had a set of five arrays but in this validation method I worked only with the JButton array.

JButton [] button = new JButton [9];
public void validate()
    {
        if(button[0].getText().equals(button[1].getText()) && button[1].getText().equals(button[2].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText());
            gameOver();
            return;
        }
        else if(button[3].getText().equals(button[4].getText()) && button[4].getText().equals(button[5].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[3].getText());
            gameOver();
            return;
        }
        else if(button[6].getText().equals(button[7].getText()) && button[7].getText().equals(button[8].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[6].getText());
            gameOver();
            return;
        }
        else if(button[0].getText().equals(button[3].getText()) && button[3].getText().equals(button[6].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText());
            gameOver();
            return;
        }
        else if(button[1].getText().equals(button[4].getText()) && button[4].getText().equals(button[7].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[1].getText());
            gameOver();
            return;
        }
        else if(button[1].getText().equals(button[4].getText()) && button[4].getText().equals(button[7].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[1].getText());
            gameOver();
            return;
        }
        else if(button[2].getText().equals(button[5].getText()) && button[5].getText().equals(button[8].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[2].getText());
            gameOver();
            return;
        }
        else if(button[0].getText().equals(button[4].getText()) && button[4].getText().equals(button[8].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText());
            gameOver();
            return;
        }
        else if(button[2].getText().equals(button[4].getText()) && button[4].getText().equals(button[6].getText()))
        {
            JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[2].getText());
            gameOver();
            return;
        }

        int i;

        for(i=0;i<button.length;i++)
        {
            if(button[i].isEnabled())
            {
                break;
            }
        }

        if(i == button.length)
        {
            JOptionPane.showMessageDialog(null,"This was a Draw");
        }
    }


texts: Reducing memory consumption for Numpy array

texts:
I'm running the following code using numpy arrays, I get a MemoryError in Ubuntu, while the same code runs on Mac OSX. (Pagination is automatically setup in Mac) This process consumes around 30 GB. Original post here.

I'm trying to replace numpy array with another structure which doesn't consume so much memory and improve the for loops.
Original code here.

The following function: create_sequences

Given the tokenizer, a maximum sequence length, and the dictionary of all descriptions and photos, will transform the data into input-output pairs of data for a training model. There are two input arrays to the model: one for photo features and one for the encoded text. There is one output for the model which is the encoded next word in the text sequence.

The input text is encoded as integers, which will be fed to a word embedding layer. The photo features will be fed directly to another part of the model. The model will output a prediction, which will be a probability distribution over all words in the vocabulary.

The output data will therefore be a one-hot encoded version of each word, representing an idealized probability distribution with 0 values at all word positions except the actual word position, which has a value of 1.

def create_sequences(tokenizer, max_length, descriptions, photos):
    """Creates sequences of images, input sequences and output words for an image.

    X1,     X2 (text sequence),                         y (word)
    photo   startseq,                                   little
    photo   startseq, little,                           girl
    photo   startseq, little, girl,                     running
    photo   startseq, little, girl, running,            in
    photo   startseq, little, girl, running, in,        field
    photo   startseq, little, girl, running, in, field, endseq

    :param tokenizer:
    :param max_length:
    :param descriptions:
    :param photos:
    :return:
    """
    X1, X2, y = [], [], []
    # Walk through each image identifier.
    for desc_key, desc_list in descriptions.iteritems():
        # Walk through each description for the image.
        for desc in desc_list:
            # Encode the sequence.
            seq = tokenizer.texts_to_sequences([desc])[0]
            # Split one sequence into multiple X,Y pairs.
            for i in range(1, len(seq)):
                # Split into input and output pair.
                in_seq, out_seq = seq[:i], seq[i]
                # Pad input sequence.
                in_seq = pad_sequences([in_seq], maxlen=max_length)[0]
                # Encode output sequence
                out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]
                # Store.
                X1.append(photos[desc_key][0])
                X2.append(in_seq)
                y.append(out_seq)
    print len(X1), len(X2), len(y)
    print type(X1[0])
    return array(X1), array(X2), array(y)

Output:

Dataset: 6000 train images.
Descriptions: train=6000
Vocabulary Size: 7579
Photos: train=6000
Description Length: 34
Preparing text sequences for training.
306404 306404 306404
<type 'numpy.ndarray'>

Memory utilization

Using sys.getsizeof() for the arrays I get:

print sys.getsizeof(X1), sys.getsizeof(X2), sys.getsizeof(y)
2678104 2678104 2678104

CProfile:

https://pastebin.com/raw/UkAEaAjq


texts:
This may be a naive question, but what are the dangers of the following code (allocate more memory in the new operator for the info struct)?

struct Info
{
        Info():nLineNo(0){memset(cFile, 0, 256);}
        ~Info(){}
        char cFile[256];
        unsigned int nLineNo;
};

void *operator new(size_t Size, const char *pcFile, const unsigned int nLine)
{
        Info *pData = 0;

        pData = (Info*)malloc(Size + sizeof(Info));

        strcpy(pData->cFile, pcFile);

        pData->nLineNo = nLine;

        return (void*)pData;
}

void operator delete(void *pData)
{
        Info *pInfo = (Info*)pData;
    // could use pInfo->nLineNo to check for it within hash table of allocated blocks - just an example
        free(pData);
}


texts: Comparing information to a directory of active enployees

texts:
The code is doing everything that I need it to. It's taking much too long though upwards of a couple minutes to complete the macro. Does anyone know how I code optimize this VBA code to run quicker? I'm new to VBA and I'm not quite sure how to proceed. This code will be running on roughly 35,000 lines of data.

Public Sub matchRow()

    Dim dumpSheet, referencesheet, outputSheet As Worksheet
    Dim startRow, outputRow, tempDumpRow, tempActiveRow, referenceRowCount, finishedreferenceIndex As Integer
    Dim finishedreference() As String
    Dim isExist As Boolean

    'Set sheets
    Set dumpSheet = Sheets("Dump")
    Set referencesheet = Sheets("Active Directory")
    Set outputSheet = Sheets("Output")

    'Set start row of each sheet for data
    startRow = 5
    outputRow = 5

    'Get row count from Active Depository sheet
    referenceRowCount = referencesheet.Range("B5:D5").End(xlDown).Row

    'Set index
    finishedreferenceIndex = 5

    'Re-define array
    ReDim finishedreference(5 To referenceRowCount - 1)

    'Set the start row
    tempDumpRow = startRow

    'Here I looped with OR state, you can modify it to AND start if you want
    Do While dumpSheet.Range("B" & tempDumpRow) <> "" Or dumpSheet.Range("C" & tempDumpRow) <> "" Or dumpSheet.Range("D" & tempDumpRow) <> ""

        'Reset exist flag
        isExist = False

        'loop all row in Active Depository sheet
        For tempActiveRow = 5 To referenceRowCount Step 1

            'If row is not finished for checking.
            If UBound(Filter(finishedreference, tempActiveRow)) < 0 Then

                'If all cell are equal
                If dumpSheet.Range("B" & tempDumpRow) = referencesheet.Range("B" & tempActiveRow) And _
                   dumpSheet.Range("C" & tempDumpRow) = referencesheet.Range("C" & tempActiveRow) And _
                   dumpSheet.Range("D" & tempDumpRow) = referencesheet.Range("D" & tempActiveRow) Then

                    'Set true to exist flag
                    isExist = True

                    'Store finished row
                    finishedreference(finishedreferenceIndex) = tempActiveRow

                    finishedreferenceIndex = finishedreferenceIndex + 1

                    'exit looping
                    Exit For

                End If

            End If

        Next tempActiveRow

        'Show result
        outputSheet.Range("B" & outputRow) = dumpSheet.Range("B" & tempDumpRow)
        outputSheet.Range("C" & outputRow) = dumpSheet.Range("C" & tempDumpRow)
        outputSheet.Range("D" & outputRow) = dumpSheet.Range("D" & tempDumpRow)

        If isExist Then
            outputSheet.Range("E" & outputRow) = ""
        Else
            outputSheet.Range("E" & outputRow) = "Item found in ""Dump"" but not in ""Active Directory"""
        End If

        'increase output row
        outputRow = outputRow + 1

        'go next row
        tempDumpRow = tempDumpRow + 1

    Loop

    'loop all row in Active Depository sheet
    For tempActiveRow = 5 To referenceRowCount Step 1

        'If row is not finished for checking.
        If UBound(Filter(finishedreference, tempActiveRow)) < 0 Then

            'Show result
            outputSheet.Range("B" & outputRow) = referencesheet.Range("B" & tempActiveRow)
            outputSheet.Range("C" & outputRow) = referencesheet.Range("C" & tempActiveRow)
            outputSheet.Range("D" & outputRow) = referencesheet.Range("D" & tempActiveRow)
            outputSheet.Range("E" & outputRow) = "Item found in ""Active Directory"" but not in ""Dump"""

            'increase output row
            outputRow = outputRow + 1

        End If

    Next tempActiveRow

End Sub


texts: Check field values against a preset object

texts:
I want to check some fields values in a form against an existing object's values. If the values match, change a class value (it will add a sign). The following code is working, but I would like to know if it can be improved.

Preset obj:

var obj = {
    preset_a:{
        input:{
            field_a:"value",
            ...
            field_b:"value",
        },
        select:{
            ...
        },
        radio:{
            ...
        }
    },
    preset_b:{
        input:{
            field_a:"value",
            ...
            field_b:"value",
        },
        select:{
            ...
        },
        radio:{
            ...
        }
    }
};

The script:

$(document).ready(function(){
    for (var preset in obj){
        $.each(obj[preset], function(type){
            var flag = true;
            $.each(obj[preset][type], function(k, v){
                if (type == 'radio'){
                    flag = ((v) == $('#'  + k + ' > input[type="radio"]:checked').val());
                } else {
                    flag = ((v) == $(type + '#' + k).val());
                }
                if (flag == false){
                    return false;
                }
            });
            if (flag == false){
                $(preset + ' i#id').attr('class', 'radio-unchecked');
                return false;
            } else {
                $(preset + ' i#id').attr('class', 'radio-checked on');
            }
        });
    }
});


texts: Verify two numbers from a list will add up to a number in the same list using Python

texts:
I am trying to solve this question:

Given a list of integers, verifies if any two numbers from this list add up to another number in the same list.

I came up with:

def func(l):
    sum_set = set() # using a set to store sums of two numbers.
    for index in range(len(l)-1):
        counter = 1
        while counter + index < len(l):
            sum = l[index] + l[index+counter]
            sum_set.add(sum)
            counter += 1
    for number in l:
        if number in sum_set:
            return True
    return False

print(func([1,2,3,4]))
print(func([1,2,1,4]))
print(func([1,1,1]))
print(func([1]))
print(func([1,2,5,9]))
print(func([2,1,1]))
print(func([1,-1,0]))

From the tests I ran above, my function is working. But there is at least one way I can think of my approach is lacking of:

I should filter the original list to get rid of duplicate numbers. If a number appears more than 2 times, its rest of appearance should be disregarded. E.g. l = [1,1,1,1,2] should be optimised to l = [1,1,2]

Is there any other aspect that I can improve my code snippet on to make it more Pythonic / more efficient?


texts:
I'm trying to mimic classes. Is there anything with this code that I should not do with C or any ways that I can improve it at all, such as best practices or anything?

structs.h

#ifndef PLAYER_H
#define PLAYER_H

typedef struct  {
    char name[30];
    int damage;
    int durability;
} weapon;

typedef struct {
    int health;
    int armor_level;
    int currency;
    weapon player_weap;
} player;

#endif

main.c

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

player new_player();
void print_player(player user);

int main(void) {

    player user = new_player();
    print_player(user);

    return 0;
}

player new_player() {

    player new_player;
    new_player.health = 100;
    new_player.armor_level = 0;
    new_player.currency = 0;
    strcpy(new_player.player_weap.name, "Starter Sword");
    new_player.player_weap.damage = 1;
    new_player.player_weap.durability = 100;

    return new_player;

}

void print_player(player user) {
    printf("The players health is %d.\n", user.health);
    printf("The players armor is %d.\n", user.armor_level);
    printf("The players currency is %d.\n", user.currency);
    printf("The players weapon is the %s.\n", user.player_weap.name);
    printf("The players weapon does %d damage and has %d durability.\n", user.player_weap.damage, user.player_weap.durability);
}


texts: Swift lazy observe and mutate pattern for arrays

texts:
I am using the following pattern in my code.
It works. But, it feels as though it is on the edge of what should work!

Should I consider an alternative?

I have an array in my class that maps an underlying data array. This is the sort of thing for which I could use a lazy sequence. However, I don't want to re-evaluate every time an element is accessed. So, I lazily load my array, then track the data array with KVO. I also want my top-level array to be observable. I mutate that with a mutableArrayValue.

I have mocked up a simple working example of the pattern below.

mutableArrayValue would usually cause a lazy var to initialise, but it seems OK to call it during an initialisation.

Setting up an observation on a lazy var does not cause it to initialise. I don't get a call here even though the effective setting of the array comes after the observation is created.

import Cocoa

class LazyData: NSObject
{
    @objc dynamic lazy var units: [Int] = {
        print("Loading units")
        return [1,2,3,4,5,6] }()
}

class Lazy: NSObject
{
    let data: LazyData

    init(with data: LazyData) {
        self.data = data
    }

    var unitsObservation: NSKeyValueObservation?

    func tenTimes(_ input: Int) -> Int { return 10 * input }

    @objc dynamic lazy var tens: [Int] = {
        print("Loading tens")

        let tenProxy = mutableArrayValue(forKeyPath: #keyPath(Lazy.tens))

        unitsObservation = data.observe(\.units) { object, change in
            if change.kind == .insertion {
                for insertionIndex in change.indexes! {
                    let ten = self.tenTimes(object.units[insertionIndex])
                    tenProxy.insert(ten, at: insertionIndex)
                }
            }
        }

        return data.units.map { tenTimes($0) }
    }()
}

var lazyData = LazyData()
var lazy = Lazy(with: lazyData)

print(lazy.tens)

let lazyDataProxy = lazyData.mutableArrayValue(forKeyPath: #keyPath(LazyData.units))
lazyDataProxy.insert(9, at: 0)

print(lazy.tens)


texts: Creating a dictionary with a path name and SHA-256 hash

texts:
The purpose is just to create a dictionary with a path name, along with the file's SHA-256 hash.

I'm very new to Python, and have a feeling that there's a much better way to implement the following code. It works, I'd just like to clean it up a bit.
    fnamelst = [r'C:\file1.txt',
                r'C:\file2.txt']

[fname.replace('\\', '\\\\') for fname in fnamelst]

diction = [{fname: hashlib.sha256(open(fname, 'rb').read()).digest()} for fname in fnamelst]

for iter in range(0,len(fnamelst)):
    dic2 = {fnamelst[iter]: hashlib.sha256(open(fnamelst[iter], 'rb').read()).digest()}


texts:
I have a HashMap<Token, Integer>, which counts occurrences of Token. Each time Token is found, the value in the map should be incremented.

Map<Token, Integer> occurrences = new HashMap<Token, Integer>();
// ...

public void tokenFound(Token token) {

    Integer numberOfOccurs = occurrences.get(token);
    Integer newNumberOfOccurs = new Integer((numberOfOccurs == null) ? 1 : numberOfOccurs.intValue() + 1);
    occurrences.put(token, newNumberOfOccurs);
}

Is there a more elegant way to do this?


texts: Filtering Arrays by values in a specific Column

texts:
The following function, as evidenced by its name KeepOrRemoveArrayRowsWhereComparisonIsTrue is probably trying to do too much.

How can I better structure/refactor/split it to be cleaner whilst retaining the original intent: "Here's an array, filter it based on the values in this column"?

Public Function KeepOrRemoveArrayRowsWhereComparisonIsTrue(ByRef sourceArray As Variant, ByVal colIndex As Long, ByVal operator As ComparisonOperator, ByVal comparisonValue As Variant, ByVal hasHeaders As Boolean, ByVal keepOrRemoveOnTrue As KeepOrRemove, Optional ByRef arrayOfRemovedRows As Variant) As Variant

        Dim LB1 As Long, UB1 As Long
        AssignArrayBounds sourceArray, LB1, UB1

        Dim rowsToBeRemoved As Variant, removeCounter As Long
        rowsToBeRemoved = Array()
        ReDim rowsToBeRemoved(1 To 1)

        Dim ix As Long, startRow As Long
        If hasHeaders Then startRow = LB1 + 1 Else startRow = LB1

        Dim sourceValue As Variant

        Select Case keepOrRemoveOnTrue

            Case KeepOrRemove.keep
                removeCounter = 0
                For ix = startRow To UB1
                    sourceValue = sourceArray(ix, colIndex)
                    If IsNull(sourceValue) Then sourceValue = 0
                    If IsNull(comparisonValue) Then comparisonValue = 0
                        If Not ComparisonIsTrue(sourceValue, operator, comparisonValue) Then
                            removeCounter = removeCounter + 1
                            ReDim Preserve rowsToBeRemoved(1 To removeCounter)
                            rowsToBeRemoved(removeCounter) = ix
                        End If
                Next ix

            Case KeepOrRemove.Remove
                removeCounter = 0
                For ix = startRow To UB1
                    sourceValue = sourceArray(ix, colIndex)
                    If IsNull(sourceValue) Then sourceValue = 0
                    If IsNull(comparisonValue) Then comparisonValue = 0
                        If ComparisonIsTrue(sourceValue, operator, comparisonValue) Then
                            removeCounter = removeCounter + 1
                            ReDim Preserve rowsToBeRemoved(1 To removeCounter)
                            rowsToBeRemoved(removeCounter) = ix
                        End If
                Next ix

        End Select

        sourceArray = Remove2DArrayRows(sourceArray, rowsToBeRemoved, arrayOfRemovedRows)

        KeepOrRemoveArrayRowsWhereComparisonIsTrue = sourceArray

End Function


texts:
This is actually a hackerrank interview question I have already solved but I need guidance on how to optimize it for the

Time
Space

  Given an array of integers, your task is to count the number of duplicate array elements. Duplicate is defined as two or more identical elements. For example, in the array [1, 2, 2, 3, 3, 3], the two twos are one duplicate and so are the three threes.

  Function Description

  Complete the function countDuplicates in the editor below. The function must return an integer denoting the number of non-unique (duplicate) values in the numbers array.

  countDuplicates has the following parameter(s):

  numbers[numbers[0],...numbers[n-1]]:  an array of integers to process

  Constraints

  1 ≤ n ≤ 1000
  1 ≤ numbers[i] ≤ 1000, 0 ≤ i < n

  Sample Input: [1, 3, 1, 4, 5, 6, 3, 2]
  Sample Output: 2
  Explanation: The integers 1 and 3 both occur more than once, so we return 2 as our answer.

function countDuplicates(original) {

  let counts = {},
    duplicate = 0;
  original.forEach(function(x) {
    counts[x] = (counts[x] || 0) + 1;
  });

  for (var key in counts) {
    if (counts.hasOwnProperty(key)) {
      counts[key] > 1 ? duplicate++ : duplicate;
    }
  }

  return duplicate;

}


texts: Record status of http call to show in the UI

texts:
What I am wanting to do, is record the status of a HTTP call, so that I can give the user some feedback in the UI, rather than either succeeding silently, or showing a grim error.
What I have done is created a Result class. For ease, I will show the simple class, but I also have this as a generic class, so it can also contain data.
The Result class:
public class Result
    {
        public bool IsSuccess { get; set; }

        public string Error { get; set; }

        public HttpStatusCode HttpStatusCode { get; set; }

        public Result() { }

        public Result(bool isSuccess)
        {
            IsSuccess = isSuccess;
        }

        public Result(string errors, bool isSuccess)
        {
            IsSuccess = isSuccess;
            Error = errors;
        }

        public Result(string errors, bool isSuccess, HttpStatusCode statusCode)
        {
            Error = errors;
            IsSuccess = isSuccess;
            HttpStatusCode = statusCode;
        }
    }

When I make a call to the API I am using, I use the Result class, as below:
public async Task<Result> UpdateColour(GrapeColour grapeColour)
        {
            var body = new StringContent(JsonConvert.SerializeObject(grapeColour), Encoding.UTF8, "application/json");
            var client = _httpClient.CreateClient(ApiNames.WineApi);

            var response = await client.PutAsync(_grapeColourUrl, body).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                return new Result(true);
            }
            else
            {
                return await HttpResponseHandler.HandleError(response).ConfigureAwait(false);
            }
        }

Where my HttpResponseHandler does some stuff, but fundamentally writes the bool isSuccessful to false, give an error message, and set the status code.
This all lives in my Domain layer.
I then pass this over to the web side of my project, here is the controller method:
[HttpPost]
        public async Task<IActionResult> EditColour(Result<EditableGrapeColourViewModel> model)
        {
            if (!ModelState.IsValid)
            {
                return View(new Result<EditableGrapeColourViewModel>(model.Data));
            }

            var domainGrapeColour = _grapeMapper.Map<Domain.Grape.GrapeColour>(model.Data);

            var saveResult = await _grapeService.SaveColour(domainGrapeColour, SaveType.Update).ConfigureAwait(false);
            if (saveResult.IsSuccess)
            {
                return RedirectToAction("EditColour", "Grape", new { id = model.Data.Id, IsSuccess = true });
            }

            var viewModel = new Result<EditableGrapeColourViewModel>(saveResult.IsSuccess, saveResult.Error, model.Data);

            return View(viewModel);
        }

So the model I use in for the viewmodel and the view has to be the Result<T> so I can access the isSuccessful and the error message to show the user.
I use automapper to map from my domain object, to an object in the web project, but I use the domain Result.
So my question is two fold; Is what I am doing a decent solution for what I want to do? And if it is, should I be using the domain Result object as I am?


texts:
I wrote the following script and php code for long-polling architecture by googling references, I would like to know if this is long-polling or short-polling, ...because I am not sure:

bc_test.js

jQuery(function($) {

  var data = [];
  function pullNotification() {
    var params = {};
    new RPC.Call({
        'method': 'users.getJsonUsers',
        'params': params,
        'timeout': 30000,
        'onSuccess': success,
        'onFailure' : error,
    });
  };

  function error() {
    alert('Error occured');
  }

  function success(result) {
    if (data.length !== 0) {
        for (var i = 0, item; item = result[i]; i++) {
           for (var k = 0; k < data.length; k++) {
               if (item.userid === data[k]) {
                   this.found = true;
               }
            }
            if (!this.found) {
               data.push(item.userid);
               $('
\n\\n\
                            ' + item.userid + '	\n\
                            ' + item.alias + '	\n\
                            ' + item.surname + '	\n\

').insertAfter('.nilar');
            }
            this.found = false;
        }
    } else {
        for (var j = 0; j < result.length; j++) {
            data.push(result[j].userid);
        }
    }
}

window.setTimeout(function() {
   window.setInterval(function() {
      pullNotification();
   }, 3000);
   pullNotification();
}, 1000);
});

PHP

function getJsonUsers() {
   $timeStart = time();
   $newData = false;
   $users_data = array();

   $sql = 'SELECT * FROM users';

   while (!$newData && (time() - $timeStart) < 10) {
         usleep ( 10000000 );
         $db_res = DBselect($sql);
         while ($user = DBfetch($db_res)) {
               $users_data[] = $user;
               $newData = true;
         }
   }
   return $users_data;
}


texts:
Followup to this

I have created a simple HTML5/CSS3/JS website with a navbar and no content.

index.html:

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>SigmaCubes - Home</title>
  <meta name="author" content="Julian Lachniet,Simon Kwilinski,Jacob Wysko" />
  <meta name="description" content="SigmaCubes is the best website on the internet." />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
  <link href="https://fonts.googleapis.com/css?family=Lato|Noto+Sans|Nunito:600|Material+Icons" rel="stylesheet" type="text/css" />
  <link href="/lib/css/reset.css" rel="stylesheet" type="text/css" />
  <link href="/lib/css/sigmacubes.css" rel="stylesheet" type="text/css" />
  <link href="/favicon.ico" rel="shortcut icon" />

Error:

JavaScript

Error:

Resolution

        About Us
        Projects
        Contact
        Donate

      About Us
      Projects
      Contact
      Donate

reset.css:

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p,
blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img,
ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i,
center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption,
tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section,
summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav,
section {
  display: block;
}

body {
  line-height: 1;
}

ol, ul {
  list-style: none;
}

blockquote, q {
  quotes: none;
}

blockquote:before, blockquote:after, q:before, q:after {
  content: "";
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

main.js:

var navEnabled = false;

document.addEventListener('DOMContentLoaded', main);

function main() {
  setDisplay("wrapper", "block");
}

function toggleNav() {
  if (navEnabled) {
    setDisplay("nav-small-links", "none");
  } else {
    setDisplay("nav-small-links", "block");
  }
  navEnabled = !navEnabled;
}

function setDisplay(id, state) {
  document.getElementById(id).style.display = state;
}

What can I try to improve?