texts: How would you better organize/code this basic HTML and CSS?

texts:
I'm curious to see what any of the more experienced programmers would do instead of methods I took as a learning tool. Any tips/tricks/fixes and reasoning is appreciated!!

http://www.jacobweyer.com

This is the result of the code so far:

<!DOCTYPE html>

<title>Alpha Tau Omega | Theta Omega</title>
<link rel="stylesheet" type="text/css" href="ATOStyle.css" />

Home

Rush

History

Alumni

Calendar

Media

CSS

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,
time, mark, audio, video {
margin:0px;
padding:0px;
border:0px;
outline:0px;
font-size:100%;
vertical-align:baseline;
background:transparent;
}

#navbar ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}

#navbar ul li a {
text-decoration: none;
color: black;
}
#navbar ul li a:hover {
color: white;
}

#navbar ul li {
font-family: Arial, Helvetica, sans-serif;
text-decoration: none;
color: #000000;
display: inline-block;
width: 70px;
height: 40px;
margin: 10px;
}

#banner {
background:url(./pieces/banner.png);
position: absolute;
margin-left: 0px;
min-height: 193px;
min-width: 183px;
background-repeat: no-repeat
}

#title {
position: absolute;
background: url(./pieces/name.png);
margin-left: 190px;
min-height: 75px;
min-width: 285px;
}

#navbar {
position: relative;
top: 80px;
left: 210px;
margin-left: inherit;
}
#social ul li{
display: inline-block;
width: 35px;
height: 35px;
margin: 5px;
}
#social {
position: absolute;
float: left;
right: 180px;
top: -5px;
}
#social ul {
list-style-type: none;
}

#innerheader {
height: 139px;
width: 750px;
margin-right: auto;
margin-left: auto;
position: relative;
}

#header {
background:url(./pieces/headerBar.png);
position: static;
width:100%;
height:139px;
padding:0;
border:0;
z-index: 10000;
}

#pagecenter {
position: static;
margin-right: auto;
margin-left: auto;
height: 50px;
width: 750px;
min-height: 1000px;
background:url(./pieces/mainBG.png);
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
margin-top: -19px;
z-index:50
}
body {
width: 100%;
margin: 0px 0px 0px 0px;
background-color: #808080
}
#footer {
margin-top: 20px;
padding-top: 30px;
background: url(./pieces/footerbar.png);
height: 77px;
width: 100%;
margin-right: auto;
margin-left: auto;
clear: both;
bottom: 0px;
position: static;
}

#footerbanner {
background: url(./pieces/footerbanner.png);
position: absolute;
min-height: 95px;
min-width: 90px;
background-repeat: no-repeat;
margin-top: -30px;
}


texts: Optimize sorting of Array according to Distance (CLLocation)

texts:
Currently my below code takes an average 9.27300 every time I run it. This is an iOS application and I can't expect the user to sit there for roughly 10 seconds.

This code takes an array (originalData) of placeObjects and calculates the distance from the selected location (CLLocation* searched). It does by [searched distanceFromLocation:currentLoc];
Each time the distance is calculated, the distance is stored into keysArray.
After the first for loop the numbers are then sorted from ascending order.

After that another for loop is made to line up the originalData to follow the same ascending order as the keysArray.

A side note: I am currently doing this for 500 objects in originalData.

I am calling this method [self sortLocations]; from viewDidLoad.

-(void)sortLocations{
    NSLog(@"Start");
    [keysArray removeAllObjects];
    //originalData is an NSMutableArray
    for (int i = 0; i < [originalData count]; i++) {
        /* f is global but its:
         * f = [[NSNumberFormatter alloc] init];
         * [f setNumberStyle:NSNumberFormatterDecimalStyle];
         */
        NSNumber* cLat = [f numberFromString:[[originalData objectAtIndex:i] latitude]];
        NSNumber* cLng = [f numberFromString:[[originalData objectAtIndex:i] longitude]];
        CLLocation* currentLoc = [[CLLocation alloc] initWithLatitude:[cLat doubleValue] longitude:[cLng doubleValue]];
        //searched is a CLLocation
        CLLocationDistance distance = [searched distanceFromLocation:currentLoc];
        NSNumber* num = [NSNumber numberWithInt:distance];
        [keysArray addObject:num];
    }
    //lowToHight is this:
    // lowToHigh = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
    [keysArray sortUsingDescriptors:[NSArray arrayWithObject:lowToHigh]];
    [orderedArray removeAllObjects];
    for (int i = 0; i < [keysArray count]; i++) {
        NSNumber* keyNum = [keysArray objectAtIndex:i];
        for (placeObjects* x in originalData){
            NSNumber* cLat = [f numberFromString:[x latitude]];
            NSNumber* cLng = [f numberFromString:[x longitude]];
            CLLocation *currentLoc = [[CLLocation alloc] initWithLatitude:[cLat doubleValue] longitude:[cLng doubleValue]];
            CLLocationDistance distance = [searched distanceFromLocation:currentLoc];
            NSNumber* num = [NSNumber numberWithInt:distance];
            if ([num intValue] == [keyNum intValue]) {
                [orderedArray addObject:x];
            }
        }
    }
    NSLog(@"End");
}


texts:
I have some data which I want to filter. I have a collection of things to include and a second one of things to exclude.

Currently I'm looping my data and filter once for the including and a second time for the excluding.

Example coding:

#[derive(Debug)]
pub struct Dataset {
    pub data: Vec<String>
}

fn main() {
    //setup test data
    let mut ds1_data : Vec<String> = Vec::with_capacity(2);
    ds1_data.push("a".to_string());
    ds1_data.push("b".to_string());
    let ds1 = Dataset{data: ds1_data};

    let mut ds2_data : Vec<String> = Vec::with_capacity(2);
    ds2_data.push("a".to_string());
    ds2_data.push("c".to_string());
    let ds2 = Dataset{data: ds2_data};

    let mut datasets : Vec<Dataset> = Vec::with_capacity(2);
    datasets.push(ds1);
    datasets.push(ds2);

    let mut include : Vec<String> = Vec::with_capacity(2);
    include.push("a".to_string());

    let mut exclude : Vec<String> = Vec::with_capacity(1);
    exclude.push("b".to_string());

    //filter datasets
    for ds in datasets {
        if ds.data.iter().find(|d| include.contains(d)).is_none() {
            //skip not included
            continue;
        }
        if ds.data.iter().find(|d| exclude.contains(d)).is_some() {
            //skip excluded
            continue;
        }

        println!("{:?}", ds);
    }
}

Also available in the rust playground:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=29c13f2b7ab3a50fbcd12b88b59f4b74

Is there way to combine the filter statements so I don't need to iterate ds.data two times?

To clarify:
The above coding is working as expected. I get datasets containing at least one element of include but no element of exclude


texts:
I'm a first year computer engineering student who's learning about algorithms and data structures. I've implemented a parallel merge sort algorithm in C++ and would like constructive criticism. This was done in Visual Studio on Windows.

Some thoughts:

portability isn't a concern I have atm.
merge_sort isn't using tail recursion, which I would like it to do

includes:
#include <thread>

function merge:

template<typename T>
void merge(T sequence[], int size)
{
    T* sorted = new T[size];
    int middle = size / 2;

    int index_left = 0;
    int index_right = middle;
    int index_sequence = 0;

    while (index_left < middle && index_right < size)
    {
        if (sequence[index_left] < sequence[index_right])
            sorted[index_sequence++] = sequence[index_left++];
        else
            sorted[index_sequence++] = sequence[index_right++];
    }

    while (index_left < middle)
        sorted[index_sequence++] = sequence[index_left++];

    while (index_right < size)
        sorted[index_sequence++] = sequence[index_right++];

    for (int i = 0; i < size; i++)
        sequence[i] = sorted[i];

    delete[] sorted;
}

function merge_sort:

template<typename T, int min_size_to_thread = 10000>
void merge_sort(T sequence[], int size)
{
    if (size > 1)
    {
        int middle = size / 2;
        if (size > min_size_to_thread)
        {
            std::thread left(merge_sort<T, min_size_to_thread>, &sequence[0], middle);
            std::thread right(merge_sort<T, min_size_to_thread>, &sequence[middle], size - middle);
            left.join();
            right.join();
        }
        else
        {
            merge_sort<T, min_size_to_thread>(&sequence[0], middle);
            merge_sort<T, min_size_to_thread>(&sequence[middle], size - middle);
        }
        merge<T>(sequence, size);
    }
}

For those who are interested: I Did some performance testing on a i5-2530M 2.50Ghz (2 cores).
The sequence to merge sort is int[100000]

Edit:

I made merge_sort and merge take a T tmp[]. And I made a "wrapper" function around merge_sort like this:

template<typename T>
void merge_sort(T* sequence, int size)
{
    T* tmp = new T[size];
    _merge_sort(sequence, tmp, size);
    delete[] tmp;
}

Now new is only called once. The "old" merge_sort is renamed to _merge_sort.


texts: Variadic templates to generate SQL string

texts:
We have this old MFC code here which uses CString and format specifiers to generate an SQL statement and then execute that SQL.

Something like this:

CString SQL;
SQL.Format(
        "INSERT INTO vehicleData (\
            vehicleData_Id, engineCapacity, engineType) \
        VALUES (%d, %s, %s, %s)",
        strtoDB( id                                     ),
        strtoDB( Vehicle->getEngineCapacity()           ),
        lngtoDB( Vehicle->getEngineType()               ),
        strtoDB( Vehicle->getEngineNo()                 ),
    );

But then with WAY more fields. This code is dependant on the types of the properties added to the DB and it is error prone when you have more than 20 properties to add. You can easily mistake a %d for a %s etc.

So this screams for templates. Specialize the behaviour depending on the type and make the number of parameters to add variable....variable....variadic.

So yeah, this screams variadic templates and I came up with this:

template<typename... Args>
CString generate_sql_insert(const char *s, Args... args)
{
    std::stringstream ss;

    ss << s << " (";

    interpolate_direct(ss, args...) << ")";

    return ss.str().c_str();
}

template<typename T, typename... Args>
std::stringstream &interpolate_direct(std::stringstream &s, T value, Args... args)
{
    interpolate_direct(s, value) << ",";
    interpolate_direct(s, args...);

    return s;
}

template<typename T>
std::stringstream &interpolate_direct(std::stringstream &s, T value)
{
    if constexpr (std::is_pointer<T>::value &&
        is_char_type<std::remove_cv_t<std::remove_pointer<T>::type>>::value)
    {
        s << "'" << value << "'";
    }
    else if constexpr (std::is_same<T, CString>::value)
    {
        if (isDefault(value))
            s << "NULL";
        else
            s << "'" << value.GetBuffer(0) << "'";
    }
    else if constexpr (std::is_same<T, COleDateTime>::value)
    {
        if (isDefault(value))
            s << "NULL";
        else
            s << "'" <<
                 std::setfill('0') << std::setw(4) << value.GetYear()   << '-' <<
                 std::setfill('0') << std::setw(2) << value.GetMonth()  << '-' <<
                 std::setfill('0') << std::setw(2) << value.GetDay()    << ' ' <<
                 std::setfill('0') << std::setw(2) << value.GetHour()   << ':' <<
                 std::setfill('0') << std::setw(2) << value.GetMinute() << ':' <<
                 std::setfill('0') << std::setw(2) << value.GetSecond() << "'";
    }
    else if constexpr (std::is_same<T, bool>::value)
    {
        s << value;
    }
    else if constexpr (std::is_floating_point<T>::value)
    {
        if (isDefault(value))
            s << "NULL";
        else
            s << "'" << std::fixed << std::setprecision(6) << value << "'";
    }
    else
    {
        if (isDefault(value))
            s << "NULL";
        else
            s << value;
    }

    return s;
}

This code basically loop unrolls all the writes to the stream and you use it like this:

CString SQL = generate_sql_insert(
            "INSERT INTO vehicleData ("
            "vehicleData_Id, engineCapacity, engineType, engineNo,"
        ") VALUES",
        id,
        Vehicle->getEngineCapacity(),
        Vehicle->getEngineType(),
        Vehicle->getEngineNo(),
        Vehicle->getOwner());

generate_sql_insert will loop unroll all the writes to the stream:

ss << "INSERT INTO..... VALUES";
ss << "(";
ss << 1;
ss << "2";
ss << 3.101;
//etc
ss << ")";

Is there any room for improvement on this system? Are there "better" options available for generating huge SQL query strings?


texts:
I have built a "reset and confirm password" section on a site. It works great. I just have this suspicion that maybe it isn't the most efficient way. I am relatively new to
jQuery but I can usually make things work well. I am just wanting to make sure I am doing them right.

Any suggestions are appreciated.

/////////////// RESET PASSWORD  /////////////////////
$('#reset_password').click(function reset_password(){
    //Enter a password input field a button
    $('#new_pass_field').html('<input type="text" id="new_password" name="new_password"><button id="submit_new_pass">Submit New Password</button>');
    // Bind a click to the button
    $('#submit_new_pass').bind('click', function submit_new_pass (){
        // When clicked get val of the new_password field.
        $get_val = $("#new_password").val();
        // Hide the new_pass field and button so the confirm field and button can be entered.
        $('#new_pass_field').hide("fast").html('<input type="text" id="password" name="password"><button id="confirm_new_pass">Confirm New Password</button>');
        // Bind click to that confirm button
        $('#confirm_new_pass').bind('click', function confirm_new(){
            // Get val of the confirm pass field
            $get_confirm_val = $("#password").val();
            // Check valdation if 2 passwords match
            if($get_val == $get_confirm_val){
                // If they match send to DB and encrypt.
                $.get(uri_base +'/AJAX/update_password/admin_users/'+$get_confirm_val+'/'+Math.random(), function(msg){
                    //If returns true then send msg password changed. and hide the password row.
                    if(msg){
                        $("#err_password").html("Your Password has been changed.").queue(function(){
                            setTimeout(function(){
                                $("#err_password").dequeue();
                            }, 3000);
                        })
                        $('#reset_pass_results').slideUp("slow");
                        $('#new_pass_field').hide("fast").html('');
                    }else{
                        // Error in the DB
                        $("#err_password").html("There was an error. Your password was not changed.");
                    }
                });
            }else{
                // Passwords didn't match now reset the clicks to try again and hide the error
                $("#err_password").html("Your Passwords didn't match!").delay(3000).fadeOut("slow");
                $('#confirm_new_pass').bind('click', confirm_new);
                $('#reset_password').bind('click', reset_password);
            }
            return false;
        });
        // Show the password field
        $('#new_pass_field').show("fast");
        return false;
    });
    // Show initial field and button.
    $('#reset_pass_results').slideDown("slow", function(){
        $('#new_pass_field').show("fast");
    });
    return false;
});


texts: Preferred implementation of `Array::operator=(const Array & rhs)`

texts:
I have a custom template class Array<T>, and am currently implementing the assignment operator.

However, I've come across a design decision: When assigning two arrays, must I require them to have the same size, or adjust the LHS Array size to the RHS?

Pros and Cons of Requiring Equal Size

Pro

Most of the time, the array is often thought of as a static container (there are std::vector, etc. for dynamic containers).
It's more efficient, because I do not have to reallocate; rather, I overwrite each element of the LHS.

Con

It's a hassle for the user to do the work himself if he does intend to have a variable-length Array, plus it would be inefficient.

Code

Here are the implementations of the two versions I'm considering.

Equal Size

template <typename T>
bool JKArray<T>::operator=(const JKArray<T> & rhs)
{
    if (this == *rhs) { return true; }
    else
    {
        if (size_ != rhs.size_) { return false; }
        else
        {
            for (int i = 0; i < size_; i++) { array_[i] = rhs.array_[i]; }
        }
    }
}

Unequal Size

template <typename T>
void JKArray<T>::operator=(const JKArray<T> & rhs)
{
    if (this == *rhs) { }
    else
    {
        if (size_ != rhs.size_)
        {
            delete [] array_;
            size_ = rhs.size_;
            array_ = new T[size_];
        }
        for (int i = 0; i < size_; i++) { array_[i] = rhs.array_[i]; }
    }
}

Note

Regarding the implementation of Equal Size: I return false if the size is not equal, and true otherwise. Of course, I could use exceptions, however this is satisfactory for now.

I'm leaning towards making operator= fail* if RHS is a different length than LHS.

I'd like to know what other's have done, and what the prefer. To avoid closing this on the basis of opinion-based, please give explanations as to why one might be preferred over the other.

*See 'Note' under 'Code'.


texts: Inner Join only if satisfies If condition

texts:
I'm looking for code review, and optimizations.

I have two tables ItemCategory and ShopItemCategory

ItemCategory

--------------------------------------------------
| No | ItemCategoryId  |      CategoryName       |
--------------------------------------------------
| 1  |    1233         |      Cement             |
--------------------------------------------------
| 2  |    1200         |      Drinks             |
--------------------------------------------------

ShopItemCategory

--------------------------------------------------
| No | ItemCategoryId  |        ShopId           |
--------------------------------------------------
| 1  |    1233         |           25            |
--------------------------------------------------
| 2  |    1200         |           32            |
--------------------------------------------------

I have an sp (stored procedure) to get ItemCategory list for dropdown,

CREATE PROCEDURE [dbo].[spGetItemCategory]

AS
BEGIN

    SET NOCOUNT ON;

    SELECT ItemCategoryId ,CategoryName
    FROM ItemCategory

End

This one works fine, and now I have new requirement. I need to send ShopId to the sp and return ItemCategory list that satisfies the condition, and if the receiving shopid equals 0 then I need to return all the ItemCategory.

My sp :

CREATE PROCEDURE [dbo].[spGetItemCategory]
(
    @ShopID INT
)

AS
BEGIN

     SET NOCOUNT ON;

     if @ShopID <> 0
         BEGIN

              SELECT ItemCategory.ItemCategoryId,CategoryName
              FROM ItemCategory
              inner join ShopItemCategory on
                     ShopItemCategory.ShopId = @ShopID AND
                     ShopItemCategory.ItemCategoryId = ItemCategory.ItemCategoryId

          END
     else
     BEGIN

          SELECT  ItemCategoryId,CategoryName
          FROM aItemCategory

     END
 END

This works well in my code. But in the two conditions only the inner join part is different, So is there a way to reduce the code and improve performance?

I got other stored procedures with larger codes in if conditions, so this method will make it bigger and bigger. Is there any alternate way to do this? or to simplify this?


texts: Showing a tooltip on hover based on a tooltip attribute

texts:
I'm showing a tooltip when you hover an element with the tooltip attribute. E.g.
Hover me.

I also have to set the position of the tooltip based on its width, and because I use width: max-content for the element, I have to do something like shown in the code example.

Is there any way I can make my code more efficient? I feel like I'm making it unnecessarily complicated.

(function() {
    var tooltip = document.querySelectorAll("[tooltip]");

    callback = (element, index, array) => {
        tooltip[index].onmouseenter = () => {
            let data = element.getAttribute("tooltip");
            let child = document.createElement("div");

            child.className = "tooltip";
            child.innerHTML = data;

            element.appendChild(child);

            child.style.left = "50%";
            child.style.marginLeft = - (child.offsetWidth / 2) + "px";

        }

        tooltip[index].onmouseleave = () => {
            if(element.getElementsByClassName("tooltip")[0] != undefined) {
                element.removeChild(element.getElementsByClassName("tooltip")[0]);
            }
        }
    }

    tooltip.forEach(callback);
})();
/* Don't review this CSS; it was added just for the demo. */
div[tooltip] { width: max-content; margin: auto; }

Hover me.


texts:
I read user input from stdin in plain C.
The problem is that I want a sane implementation that is robust to errors and restricts the user to a certain input and doesn't suck in terms of complexity.
The function get_strings() reads input char by char as long there is no new line (\n), no EOF and all chars are passing the isalpha() test. But I want to keep spaces.

Some points that (I think) deserve special attention during the review:

- I would love to get rid of the outer while loop which is basically testing wether the user just pressed Enter without any meaningful input.

 - Do I even need to use ferror()? fgetc already returns EOF when something did go wrong, but I will just stop reading from the stream instead of telling the user something went wrong.

- It doesn't happen everytime but it happens: A \n stays in the stdin stream and the next time I want to get meaningful input fgetc() just gets skipped. It doesn't matter here, but it does when I am asking single character Yes/No questions. I can only get rid of this problem with a construct that clears out all previous things that are left in stdin. See the second codeblock for this.

So, am I handling this totally wrong? Are there better practices to embrace? It looks really clunky to me, and clunky is always bad.

/** @brief Contains the dictionary */
static char **strings = NULL;

/** @brief Helps with containing the dicionary */
static char *string;

/* Reads input char by char with fgetc() */
static char *get_strings()
{
    char *string = NULL;
    char ch;
    size_t len = 0;
    while (string == NULL && ch != EOF) {
    while (EOF != (ch = fgetc(in_stream)) && ch != '\n') {
        if (ch != ' ' && isalpha((int)ch) == 0) {
            fprintf(stderr, "Only [a-z] is a valid input. | \t"
                                "| Input another or end with CTRL+D: ");
            continue;
        }
        string  = (char*) realloc(string, len+2);
        if (string == NULL) {
            bail_out(EXIT_FAILURE, "realloc(3) failed");
        }
        string[len++] = toupper(ch);

        if (len >= MAX_DATA) {
            bail_out(EXIT_FAILURE, "Input too long\n");
        }
    }
    if (ferror(in_stream)) {
        bail_out(EXIT_FAILURE, "Error while reading from stream");
    }
    }

    if(string) {
        string[len] = '\0';
    } else {
        printf("\nFinished dictionary...\n");
    }
    printf("Added string: %s | Input another or end with CTRL+D: ", string);
    return string;
}

/* Saves the returned strings from get_strings() in a linked list */
static void read_dict()
{
    int index;
    for (index = 0; (string = get_strings()); ++index) {
        if (string[0] == '\0') continue;
        strings = (char**) realloc(strings, (index+1)*sizeof(*strings));
        if (strings == NULL) {
            bail_out(EXIT_FAILURE, "realloc(3) failed");
        }
        strings[index] = string;
    }

    /* Take a note of how many entries we have yet. */
    dict_size = index;
}

Second CodeBlock with a more simple case:

while(1) {
    char tmp;
    printf("Please enter your guess [a-z]: ");
    guess = fgetc(stdin);
    /* Jump back to start of loop */
    if (guess == '\n') {
        continue;
    }

    /* HERE IS THE CLEAR FOR STDIN
       This part really just eats all remaining \ns from the user,
       so that later inputs can start uninterrupted. Can I get rid of
       it in some better way? */
    while((tmp = getchar()) != '\n' && tmp != EOF);

    if(!isalpha(guess)) {
        fprintf(stderr, "Enter a valid letter [a-z]!\n");
        continue;
    }
}


texts:
I needed to write my own lightweight GO multi-output logger for a work project and I've come up with https://github.com/asticode/go-logger.

Basically the projects works like this:

// Create the logger
l, e := logger.NewLogger("myproject", logger.LevelDebug, "%message%")

// Add a stream handler
h, e := logger.NewHandlerStream("")
l.AddHandler("stream", h)

// Add a syslog handler
h, e = logger.NewHandlerSyslog("[%level%]%message%", "syslog_id")
l.AddHandler("syslog", h)

// Add a file handler
h, e = logger.NewHandlerFile("", "/path/to/file")
l.AddHandler("file", h)

// Log a warning message
l.Warning("This is a warning message")

And this will output the message to the specified handlers :)

I'm not here to advertise at all and I'm rather looking for Gopher's opinions (good or bad) on my code and my implementation since I'd like to know whether I've done things right or whether I've gone completely off tracks.

My points of emphasis would be:

Have I made good use of interfaces?
Have I made good use of const and global vars?
Have I made good use of GO project structure?
Have I made good use of GO unit testing package?
...

For instance here's how I expose the main logger (https://github.com/asticode/go-logger/blob/master/logger/logger.go):

type Logger interface {
    ID() int
    SetID(id int)
    Prefix() string
    SetPrefix(p string)
    Level() Level
    SetLevel(l Level)
    Format() string
    SetFormat(f string)
    Handlers() map[string]Handler
    AddHandler(k string, h Handler)
    GetHandler(k string) (Handler, error)
    DelHandler(k string)
    Emergency(message string) error
    Critical(message string) error
    Error(message string) error
    Warning(message string) error
    Notice(message string) error
    Info(message string) error
    Debug(message string) error
}

type logger struct {
    id       int
    prefix   string
    level    Level
    format   string
    handlers map[string]Handler
}

And I use a global func to create a new logger such as:

func NewLogger(prefix string, level Level, format string) (Logger, error) {
    // Check level
    if _, ok := levelToInt[level]; !ok {
        return nil, ErrUndefinedLevel
    }

    // Check Format
    if len(format) == 0 {
        format = defaultFormat
    }

    // Increment count
    count++

    // Return
    return &logger{
        id:       count,
        prefix:   prefix,
        level:    level,
        format:   format,
        handlers: make(map[string]Handler),
    }, nil
}

Is this the proper way to do it ?


texts: Project Euler 12 (triangle numbers), solved using functools.reduce() and looping

texts:
I have solved problem 12 on Project Euler website, which reads:

  The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
  = 28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

  1: 1
  3: 1,3
  6: 1,2,3,6
  10: 1,2,5,10
  15: 1,3,5,15
  21: 1,3,7,21
  28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five
  divisors.

  What is the value of the first triangle number to have over five
  hundred divisors?

And I've solved this in two ways:

1.functools.reduce()

import math
from functools import reduce
import time

def primeFactors(n):
    i = 2
    factors = {}
    num = 0
    while i ** 2 <= n:
        if n % i:
            i += 1
        else:
            n //= i
            num = factors.get(i, None)
            if num is None:
                factors[i] = 1
            else:
                factors[i] = num+1
    if n > 1:
        num = factors.get(n, None)
        if num is None:
            factors[n] = 1
        else:
            factors[n] = num+1
    return factors

start_time = time.time()
numOfDivisors = 500
n = 2

while True:
    t = int(n*(n+1)/2)
    factors = primeFactors(t).values()

    if reduce(lambda x, y: x*y, [t+1 for t in factors]) >= numOfDivisors:
        print(t)
        break
    else:
        n += 1

print("----%s seconds ----" % (time.time() - start_time))

2.for-loop

import math
import time

def primeFactors(n):
    i = 2
    factors = {}
    num = 0
    while i ** 2 <= n:
        if n % i:
            i += 1
        else:
            n //= i
            num = factors.get(i, None)
            if num is None:
                factors[i] = 1
            else:
                factors[i] = num+1
    if n > 1:
        num = factors.get(n, None)
        if num is None:
            factors[n] = 1
        else:
            factors[n] = num+1
    return factors

start_time = time.time()
numOfDivisors = 500
n = 2

while True:
    t = int(n*(n+1)/2)
    factors = primeFactors(t).values()

    k = 1
    for i in factors:
        k *= (i+1)

    if k >= numOfDivisors:
        print(t)
        break
    else:
        n += 1

print("----%s seconds ----" % (time.time() - start_time))

I tested out which one was faster, found that there was a fine line only:

1.670 secs and 1.678 secs

I attempted to calculate the average computing time by making the given number bigger from 500 to 1000, repeating this process 10 times.

But both solutions were done almost simultaneously:

functools.reduce

[13.616845607757568, 13.67394757270813, 13.623621225357056, 13.596383094787598, 13.657264471054077, 13.694176197052002, 13.669324398040771, 13.65349006652832, 13.66620421409607, 13.57088851928711, 13.686619901657104]
for-loop

[13.56181812286377, 13.686477422714233, 13.548126935958862, 13.565587759017944, 13.562162637710571, 13.556873798370361, 13.562631845474243, 13.572312593460083, 13.57419729232788, 13.567578315734863, 13.611796617507935]

Question: Are there any insignificant or significant differences between the two from a practical view and in a normal case, Or is this just a matter of behavior of two functions to use?


texts: Get module entry by name from external program via WinAPI

texts:
I'm asking myself if there's any better/shorter way of getting a module entry by its name from an external process.

This is the code I have so far:

MODULEENTRY32 GetModule(const char* ModuleName) {

    HANDLE Module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
    MODULEENTRY32 Entry;
    Entry.dwSize = sizeof(Entry);

    WCHAR *ModuleNameChar;
    int Chars = MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, NULL, 0);
    ModuleNameChar = new WCHAR[Chars];
    MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, (LPWSTR)ModuleNameChar, Chars);

    while (Module32Next(Module, &Entry)) {
        if (!wcscmp((wchar_t*)Entry.szModule, ModuleNameChar)) {
            CloseHandle(Module);
            return Entry;
        }
    }

    /*
        Return the module base 0x0 if we don't find any module
    */
    CloseHandle(Module);
    Entry.modBaseAddr = 0x0;
    return Entry;
}

It should work but it's quite complicated. Is there any useful function or method I can make use of to simplify this whole thing?


texts: Finding the count of all repeats in an array of integers

texts:
The problem is about finding the sum of all repeating groups from an integer array as explained below and here.

Problem statement:

  Say that a "clump" in an array is a series of 2 or more adjacent
  elements of the same value. Return the number of clumps in the given
  array.

countClumps({1, 2, 2, 3, 4, 4}) → 2
countClumps({1, 1, 2, 1, 1}) → 2
countClumps({1, 1, 1, 1, 1}) → 1

  Conditions for solving:

  No other helper methods.
  Do not use Java.util.Arrays.copyOf or any other utility under Arrays
  Do not use collections.

Can I solve it using 1 loop with or with a better time complexity?

Any other nitpicks about my solutions are also welcome.

public int countClumps(int[] nums) {
    final int len=nums.length;
    int  count=0;

    for(int i=0;i<len;i++)
    {
        int j=i+1;
        if(nums[i]==nums[j])
        {
            count++;
            while((nums[i]==nums[j]))
            {
                if(j==len-1)
                    break;
                j++;
            }
        }
        i=j-1;
        if(i==len-2)
            break;
    }

    return count;
}


texts: Speed up code based on map with vectors as values

texts:
Following is the piece of code which represents the bottleneck of my application:

#include <iostream>
#include <chrono>
#include <unordered_map>
#include <vector>
#include <memory>
#include <cassert>
#include <thread>
#include <random>
#include <utility>
using namespace std;
using namespace chrono;

static const size_t len = 30;
static const size_t nGraphics = 0xfffff;
static const size_t nIndexes = 600000;

static default_random_engine generator;
static normal_distribution<float> distribution(len / 2.f, 2);

struct Graphic
{
    Graphic()
        : lnum ((short)distribution(generator))
    {
        // common scenario
        // most of my graphics elements belong to few layers
        assert(lnum < len);
    }

    short lnum;
    unsigned char data[200];
};

static vector<short> order;
static vector<unique_ptr<Graphic>> graphics;
static vector<size_t> indexes;

static void init()
{
    order.reserve(len);
    for (short i = 0; i < len; i++)
        order.push_back(i);

    graphics.reserve(nGraphics);
    for (size_t i = 0; i < nGraphics; i++)
        graphics.emplace_back(new Graphic);

    assert(nGraphics >= nIndexes);

    indexes.reserve(nIndexes);
    for (size_t i = 0; i < nIndexes; i++)
        indexes.push_back(i);
}

static bool is_selected(short lnum)
{
    // worst case scenario (everything has been selected)
    return true;
}

static bool is_valid(Graphic* g)
{
    // worst case scenario (everything is valid)
    return (g != nullptr);
}

static void benchmarks()
{
    unordered_map<short, vector<Graphic*>> selected;
    selected.reserve(len);

    for (size_t i = 0; i < len; i++)
    {
        const auto lnum = order[i];

        if (!is_selected(lnum))
            continue;

        selected.emplace(lnum, vector<Graphic*>());
    }

    for (const auto idx : indexes)
    {
        assert(idx < graphics.size());
        const auto g = graphics[idx].get();

        if (!is_valid(g))
            continue;

        const auto it = selected.find(g->lnum);

        if (it != selected.end())
            it->second.emplace_back(g);
    }

    for (size_t i = 0; i < len; i++)
    {
        const auto lnum = order[i];

        if (!is_selected(lnum))
            continue;

        assert(selected.find(lnum) != selected.end());

        for (const auto g : selected[lnum])
        {
            assert(g);

            if (g->lnum != lnum)
                throw runtime_error("error");

            // perform slow operation on g (third party library)...
            // must follow a specific order
        }

        // simulate operations
        this_thread::sleep_for(microseconds{ selected[lnum].size() });
    }
}

int main()
{
    init();

    const auto t0 = high_resolution_clock::now();
    benchmarks();
    const auto t1 = high_resolution_clock::now();
    const auto elapsed = duration_cast<milliseconds>(t1 - t0).count();
    cout << "Elapsed: " << elapsed << endl;
    cin.get();

    return 0;
}

Most of the work is done inside the third party library (the elapsed time well represents the actual application), but my code, used to prepare the data structure, last more than 50ms on my machine.

Is there any way to reduce this time?


texts:
This code is a project that I am working on to eventually analyze some images but right now I am purely trying to read an image and convert it to black and white.  The input should be either white or something else which would end up as black so it is easy to check for this.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

img = mpimg.imread('./Training/Image1.png')

imgplot = plt.imshow(img)

width = img.shape[1]
height = img.shape[0]

def generateArray():
    arr = []
    for y in range(img.shape[0]):
        arr.append([])
        for x in range(img.shape[1]):
            if img[y][x][0] != 1:
                arr[y].append(1)
            else:
                arr[y].append(0)
    return arr

arr = generateArray()

plt.show()

To be clear, I desire to create an array arr that contains either a 0 if the corresponding pixel in the inputted image is white or 1 if it is anything other than white.

I am somewhat of a beginner with Python but I am confused as to why this code takes so long to run (>19 seconds on my older Mac).  Is there something that I am missing that would speed it up significantly?


texts: Python program to calculate the area of two-dimensional shapes

texts:
This is the first mini-project I have completed by myself with Python 2.7. I wrote a simple program that calculates the area of different two-dimensional shapes and it works. I want to know what you think of it and also want to know how it can be improved and if I did something wrong, so this is my code:

def circle(pi,radius):
    area_circle = pi * (radius ** 2)
    print " the area of your circle equals %s" % (area_circle)
def rectangle(length, width):
    area = length * width
    print "The area of your rectangle equals %s" %(area)
def triangle(height, base):
    area_triangle = height * base * 0.5
    print "the area of your triangle equals %s" % (area_triangle)
def square(length):
    area_square = length ** 2
    print "the area of your square equals %s" % (area_square)
shapes = ["square", "rectangle", "triangle", "circle"]
print "Area calculator!"
print "Made by Ahmed Fawzy"
print "-------------------------------"
def calculation():
    print "please type the name of your shape"
    print "(Square, Rectangle, Triangle, Circle)"
    user_shape = raw_input()
    if user_shape == shapes[0]:
        square(length = float(raw_input("please type the length of the square.")))
    elif user_shape == shapes[1]:
        rectangle(length = float(raw_input("please type the length of the rectangle.")), width = float(raw_input("please type the width of the rectangle.")))
    elif user_shape == shapes[2]:
        triangle(height = float(raw_input("please type the height of the triangle.")), base = float(raw_input("please type the base length of the triangle.")))
    elif user_shape == shapes[3]:
        circle(3.14, radius = float(raw_input("please type the radius of the circle.")))
    else:
        print "That's not in the choices!, Try again."
        calculation()
calculation()
choice = raw_input("Would you like to calculate the area of a different shape?(yes/no)")
while choice == "yes":
    print "---------------------"
    calculation()
    choice = raw_input("Wanna go again?")

There's one more thing I'd like to add but don't know how, I want to make it infinite loop when the user types an answer different than 'yes' or 'no' to the "would you like to calculate the area of a different shape?" , until the user types the correct answer which is yes or no then the loop breaks and it calculates again, any tips?


texts:
I have been writing a small particle plugin since I want to learn how physics works for games. Now I have tried to get this as clean as I possible could but  It feels something is missing. Am I repeating too much code? Could this be improved in any way such as in performance?

https://jsfiddle.net/zdufwLv6/

new explodeLayer({
  particles: 17, xSpread: 5, ySpread: 20, colorIndex: 3, radius: 0, radiusMax: 100, x: 0, y: 0
})

function explodeLayer(obj) {
  var self = this;
  this.elem = document.getElementsByTagName('div');
  this.particle = [];
  this.radius = obj.radius;
  this.color = ['red', 'yellow', 'cyan', 'orchid']
  this.interval = 2 * Math.PI / obj.particles;

  this.init = function() {
    this.create();
    this.blast();
  }

  this.create = function() {
    for(var i = 0;  i < obj.particles; i++) {
      document.body.appendChild(document.createElement('div'));
      this.elem[i].style.background = this.color[obj.colorIndex];
      this.particle.push(new this.Properties(this.interval * i, obj.x, obj.y));
      this.updatePosition(i);
    }
  }

  this.Properties = function(angle, x, y) {
    this.angle = angle;
    this.x = x;
    this.y = y;
    this.vy = y;
    this.vx = y;
  }

  this.updatePosition = function(index) {
    this.elem[index].style.left = this.particle[index].x + 'px';
    this.elem[index].style.top = this.particle[index].y + 'px';
  }
    this.move = function() {
    for(var i = 0;  i < this.particle.length; i++) {
      this.particle[i].vy += 0.4;
      this.particle[i].x += this.particle[i].vx;
      this.particle[i].y += this.particle[i].vy;
      this.updatePosition(i);
     }
    requestAnimationFrame(function() {
      self.move.call(self);
    });
  }
  this.blast = function() {
    for(var i = 0;  i < this.particle.length; i++) {
      this.particle[i].x = Math.round(window.innerWidth) / 2 + this.radius * Math.cos(this.particle[i].angle);
      this.particle[i].y = Math.round(window.innerHeight) / 2 + this.radius * Math.sin(this.particle[i].angle);
      this.particle[i].vx = obj.xSpread * Math.cos(this.particle[i].angle);
      this.particle[i].vy = obj.ySpread * Math.sin(this.particle[i].angle);
      this.updatePosition(i);
    }
    requestAnimationFrame(function() {
      self.move.call(self);
    });
  }

  this.init();
}
html, body { background: rgb(30, 30, 30)}
div { padding: 8px; position: absolute; border-radius: 100%}


texts:
I want to standardise the CSS I use, and am leaning towards bem — I know I'll get a lot of benefit from the predictability of its pattern.

I have hacked their formula ever so slightly - I don't include the B part of the classname on child elements. For me this makes the html easier to write, and maintain.

Pure BEM

.Slideshow {}
.Slideshow__slide {}
.Slideshow__image {}

My Modified BEM

.Slideshow {}
.Slideshow .slide {}
.Slideshow .image {}

The only advantage I see to using 'pure' BEM over my modified version is the avoidance of conflict between child elements of different blocks (e.g. .Slideshow .image and .AdvertBanner .image).

This is not a problem for me, because I use LESS, nesting block level rules automatically.

Can anybody suggest other advantages to using 'pure' BEM over my modified version?


texts: Foreach with the aim of removing the need for a $global

texts:
Below is a function (part of a procedurally written Wordpress plugin) which iterates through a multi dimensional array of regions, adding them to a custom hierarchical taxonomy. In the spirit of globals are generally bad practice I'd like to see how one could achieve the same ends without one.

The function calls upon itself as it iterates through the array. The global in question is $last_region which does not appear anywhere else in the application but here, hence my desire to see if it can be avoided. It previously had been defined just prior to the function, but I found this was unnecessary, as defining it within the function itself was sufficient. I assume this is because once the function has run once, it has been created in memory, and therefore exists for subsequent iterations.

If I understand the loop correctly here, global $last_region fires the function $last_region = wp_insert_term($name, 'test', array('slug' => $slug, 'parent' => $parent_id));, which creates the taxonomy entry for WordPress. I must admit I'm a bit unclear on how this string now stored in $last_region enables the function to operate on its next loop.

function do_insert_region($regions= array(), $parent_id = 0)
{
    global $last_region;

    foreach ($regions as $slug => $name) {
        if (is_array($name) && $slug != 'child') {
            do_insert_region($name, $parent_id);
        } else {
            if ($slug == 'child') {

                do_insert_region($name, $last_region['term_id']);
            } else {
                $last_region = wp_insert_term($name, 'test', array('slug' => $slug, 'parent' => $parent_id));
            }
        } //if(is array and not child)
    } //foreach
}

Where $region = get_regions(); which returns an array like this one.


texts: Method to count interior nodes of a binary tree

texts:
I'm not a programmer, but am playing around with a binary tree Class in Python and would like help with a recursive method to count interior nodes of a given tree.

The code below seems to work, but is this solution the clearest, in terms of logic, for counting interior nodes? I'm keen that the code is the cleanest and most logical solution, whilst remaining recursive.

The qualifier for being an interior node, as far as I'm aware here is, that an interior node should have a parent, and at least one child node.

def count_interior_nodes(self, root):
    """Return number of internal nodes in tree"""
    if(root.parent == None):
        # Root node so don't count, but recurse tree
        return self.count_interior_nodes(root.left) + self.count_interior_nodes(root.right) + 0
    elif (root.left != None or root.right != None):
        # Has parent, but isn't leaf node, so count and recurse
        return self.count_interior_nodes(root.left) + self.count_interior_nodes(root.right) + 1
    else:
        # Leaf node, so return zero
        return 0


texts: Factory / Builder Design Pattern in Python

texts:
Situation: I have implemented a factory design pattern in Python as below. There are different screens which have different configurations. One can register the screen in the factory and get the screen in case correct configuration is passed to respective factory class method.
Question: I am wondering if this is a clean solution as each screen class (Screen1, Screen2, ..) has a main-method which calls in a specific order the respective private class methods. Is there a better/cleaner way to handle the main methods in each class? Is it cleaner to implement a combination of factory and builder design pattern?
Highly appreciate any comments and improvements!!
Code:
import numpy as np
import pandas as pd

from abc import ABCMeta, abstractmethod

df = pd.DataFrame({"ident": ["A1", "A2", "B3", "B4"], "other_col": np.random.randint(1, 6, 4)})

class IScreens(metaclass=ABCMeta):

    @abstractmethod
    def main(self):
        pass

class Screen1(IScreens):

    def __init__(self, data, config):
        self.data = data
        self.batch = config["cfg1"]

    def __get_letter(self):
        self.data["campaign"] = self.data[self.batch].str[:1]

        return self.data

    def __get_number(self):
        self.data["num"] = self.data[self.batch].str[1:]

        return self.data

    def __some_other_stuff(self):
        self.data["other_stuff"] = self.data["num"].astype(int) * 100 / 2

        return self.data

    def main(self):
        self.data = self.__get_letter()
        self.data = self.__get_number()
        self.data = self.__some_other_stuff()
        # some more processing steps follow

        return self.data

class Screen2(IScreens):

    def __init__(self, data, config):
        self.data = data
        self.batch = config["cfg1"]

    def __some_cool_stuff(self):
        self.data["cool_other_stuff"] = self.data[self.batch] + "_COOOOL"

        return self.data

    def main(self):
        self.data = self.__some_cool_stuff()
        # some more processing steps follow

        return self.data

class ScreenFactory:

    def __init__(self):
        self._screens = {}

    def register_screen(self, screen_name, screen_class):
        self._screens[screen_name] = screen_class

    def get_screen(self, data, config):

        if "screen_indicator" not in config:
            raise AssertionError("Your config file does not include 'screen_indicator' key")

        screen = self._screens.get(config["screen_indicator"])
        if not screen:
            raise AssertionError("screen not implemented")
        return screen(data=data, config=config)

factory = ScreenFactory()

factory.register_screen(screen_name="s1", screen_class=Screen1)
config = {"screen_indicator": "s1", "cfg1": "ident"}
factory.get_screen(data=df, config=config).main()

factory.register_screen(screen_name="s2", screen_class=Screen2)
config = {"screen_indicator": "s2", "cfg1": "ident"}
factory.get_screen(data=df, config=config).main()
```


texts:
I had written following page object class which represents user profile page. The profile contains department, teams, email and login labels and corresponding values. Initially I wrote a page object class as  -

public class MyProfilePage extends PageObject{

public MyProfilePage() throws Exception {
    super(departmentLabel);
    throw new IllegalStateException("This is not My Profile page");
}

private static final LabelElement departmentLabel = new LabelElement("Department Label",
        locateByCSSSelector(".department"));
private static final LabelElement teamLabel = new LabelElement("Teams Label",
        locateByCSSSelector(".teams"));
private static final LabelElement emailLabel = new LabelElement("Emails Label",
        locateByCSSSelector(".email"));
private static final LabelElement loginLabel = new LabelElement("Login Label",
        locateByCSSSelector(".login"));

public String getDepartment() {
    return departmentLabel.getText();
}

public String getTeam() {
    return teamLabel.getText();
}

public String getEMail() {
    return emailLabel.getText();
}

public String getLogin() {
    return loginLabel.getText();
}
}

Then I decided to use enum and reduce the number of class variable and methods -

public class MyProfilePage extends PageObject{

public MyProfilePage(ProfileAttribute profileAttribute) throws Exception {
    super(getProfileAttributeElement(profileAttribute));
    throw new IllegalStateException("This is not My Profile page");
}

public enum ProfileAttribute {
    DEPARTMENT("department"), TEAM("teams"), EMAIL("email"), LOGIN("login");

    private String attribute;

    ProfileAttribute(String attribute) {
        this.attribute = attribute;
    }

    public String getAttribute() {
        return attribute;
    }
}

private static HtmlElement getProfileAttributeElement (ProfileAttribute profileAttribute) {
    return new LabelElement("Profile Attribute", locateByCSSSelector("."+
            profileAttribute.getAttribute()));
}

public String getAttributeValue(ProfileAttribute profileAttribute) {
    return getProfileAttributeElement(profileAttribute).getText();
}
}

A curtailed version of TopHeader class which gets to the Myrofile page -

public class TopHeader extends PageObject {

public MyProfilePage goToManageYourAccount() throws Exception {
    manageYourAccountLink.click();
    return new  MyProfilePage(MyProfilePage.ProfileAttribute.DEPARTMENT);
}

}

This is how a test uses it -

public class MyProfileTest extends SelTestCase {

LoginUserNavigation loginUserNavigation = new LoginUserNavigation();

@Test(groups = "shouldDisplayProfileAttributesOnMyProfilePage")
public void shouldDisplayProfileAttributesOnMyProfilePage() throws Exception {
    MyProfilePage myProfilePage = loginUserNavigation
            .loginAsDefaultUser(getEnvironment())
            .getTopHeader()
            .goToManageYourAccount();
    assertThat("department is wrong", myProfilePage.getAttributeValue
            (MyProfilePage.ProfileAttribute.DEPARTMENT), is(equalTo("Technology")));
}

}

Have I made it any better? Could I improve it further?


texts: Optimizing O(m n) solution for longest common subsequence challenge

texts:
Given two strings string X of length x1 and string Y of length y1, find the longest sequence of characters that appear left to right (but not necessarily in contiguous block) in both strings.

  e.g. if X = ABCBDAB and Y = BDCABA, the LCS(X,Y) = {"BCBA","BDAB","BCAB"} and LCSlength is 4.

I used the standard solution for this problem, whichever is greater:

if(X[i]=Y[j]) :1+LCS(i+1,j+1)
if(X[i]!=Y[j]) :LCS(i,j+1)
LCS(i+1,j)

and then I used memorization, making it a standard DP problem.

#include<iostream>
#include<string>
using namespace std;
int LCS[1024][1024];
int LCSlen(string &x,int x1,string &y,int y1){
    for(int i = 0; i <= x1; i++)
    LCS[i][y1]=0;

    for(int j=0;j<=y1;j++)
    LCS[x1][j]=0;

    for(int i = x1 - 1; i >= 0; i--){
    for(int j = y1 - 1; j >= 0; j--){

    LCS[i][j] = LCS[i+1][j+1];

    if(x[i] == y[j])
    LCS[i][j]++;

    if(LCS[i][j+1]>LCS[i][j])
    LCS[i][j]=LCS[i][j+1];

    if(LCS[i+1][j]>LCS[i][j])
    LCS[i][j]=LCS[i+1][j];

    }
    }
return LCS[0][0];
}

int main()
{
string x;
string y;
cin >> x >> y;
int x1 = x.length() , y1 = y.length();
int ans = LCSlen( x, x1, y, y1);
cout << ans << endl;
return 0;
}

Running here, this solution I used in SPOJ and I got a time limit exceeded and/or runtime error.

Only 14 solutions are yet accepted.  Is there a smarter trick to decrease the time complexity of this question?


texts: Fastest method of randomly swapping array indexes / generating random alphabets in C++

texts:
std::array < char, 27 > new_alphabet() {
  std::array < int, 26 > a;

  static std::random_device rd;
  static std::mt19937 mte(rd());

  std::uniform_int_distribution < int > dist(0, 25);

  std::generate(a.begin(), a.end(), [ & ]() {
    return dist(mte);
  });

  std::array < char, 27 > alpha = {
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  };

  for (int x = 0; x < 26; x++) {
    std::swap(alpha[x], alpha[a[x]]);
  }

  return alpha;
}

int main() {
  for (int i = 0; i < 10000000; i++) {
    new_alphabet();
  }

  return 0;
}

The above code works fine and creates randomised alphabets, each loop would generate for example:
Y G T X R P D U L H I M V O B E F Z Q W J K A C S N
G Q I J F O P L A K M B D T R C H V Y X S U Z E N W
B O N U C Y K T H Q J F V W L M E S X A P R D Z I G
Q B D C V Z R E W O P L M S N X T H A I K U J Y G F
R J B G M E Z P V Q D Y C H I S O F X L N K T U A W
A M E S D H Q J R K Y P N X G T F B L O U W I Z V C
H E L G M F Q K J A X R S I V N W P T D O Y Z U B C
V S O B F R K A J D H Q T P N E I M X U Y Z C L W G
D E M R P Y S K G O C B A Q I H L J T U F N V X Z W
...

Generating 10,000,000 alphabets takes ~5 seconds on my 2.6 GHz i7. Compiling with g++ -std=c++11 -O3.
Is this the most efficient approach to this, and if there any optimisations, how can I improve or speed up this code?
The above uses the Mersenne Twister engine for generating 26 random values used to swap the array indexes.
Would it be possible to use an xorshift generator here?


texts: Abstracting out two lines of code in Coffeescript

texts:
I am currently working on refactoring two methods that exist in directives into a service.

This is method one:

scope.computeStyle = (component) ->
  elementHash = {}
  if component.element.type == 'table'
    elementHash.height = 600
    if component.height?
      elementHash.height = component.height * 50
  else if component.element.type == 'single_value'
    elementHash.height = 200
    elementHash.width = 800
  return elementHash

This is method two:

scope.computeStyle = (element, rowComponent) ->
  elementHash = {}
  if element.type == 'table'
    elementHash.height = 600
    if rowComponent?.height?
      elementHash.height = rowComponent.height
  else if element.type == 'single_value'
    elementHash.height = 200
    elementHash.width = 800
  return elementHash

They both do the same thing (a little differently). They take an element/component (which are objects containing data about an object in my application), checks what type of object they are (in this case, a table or a single value), and applies a height and/or width transformation.

Within my service, this is what I have done:

angular = require "angular"

angular.module("myapp.dashboards.layouts").service("DashboardLayoutComputeStyle" ->

  @computeStyle = (componentElement, height) ->
    elementHash = {}
    if componentElement.type == 'table'
      elementHash.height = 600
      if height?
        elementHash.height = height
    else if element.type == 'single_value'
      elementHash.height = 200
      elementHash.width = 800
    return elementHash

  @
)

Here's where my question comes in:

I am not sure what to do at this line in my abstracted method:

  if height?
    elementHash.height = height

In method one, this is what it looks like:

    if component.height?
      elementHash.height = component.height * 50

In method two, this is what it looks like:

    if rowComponent?.height?
      elementHash.height = rowComponent.height

I have three constraints to the refactoring of these two lines:

I must check whether both rowComponent and height exist in method two
I don't need to check whether component exists, but I must check whether height exists in method one
In method one, I must set the elementHash,height to component.height * 50, while in method two, I can simply assign rowComponent.height to elementHash.height

How would I abstract these two lines out?


texts:
I am a newbie in stack exchange code review. I just wrote a C function where the function checks if the given string is numeric or not. What do you think about my way of doing this? And could this be done in other ways?
#include <stdio.h>
#include <stdbool.h>

bool is_numeric(const char* str)
{
    while (isspace(*str))
       str++;

    if (*str == '-' || *str == '+')
       str++;

    while (*str)
    {
        if (!isdigit(*str) && !isspace(*str))
            return false;
        str++;
    }

    return true;
}

int main(int argc, char** argv)
{
  printf("%s\n", is_numeric("123436")  ? "true" : "false"); // should be true
  printf("%s\n", is_numeric("123.436") ? "true" : "false"); // should be false
  printf("%s\n", is_numeric("    567") ? "true" : "false"); // should be true
  printf("%s\n", is_numeric("235   ")  ? "true" : "false"); // should be true
  printf("%s\n", is_numeric("794,347") ? "true" : "false"); // should be false
  printf("%s\n", is_numeric("hello")   ? "true" : "false"); // should be false
  printf("%s\n", is_numeric("-3423")   ? "true" : "false"); // should be true
}

Thanks in advance!


texts:
This is my first Java program to print out the Armstrong numbers.

  An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.

I want to get better, so be harsh and straightforward.

public class Armstrong {

    public static void main (String arg[]){

        int Max=2000000000;
        for (int i=0; i<Max; i++){
            if (isarmstrong(i)){
                System.out.println(i);
            }

        }
    }

    private static boolean isarmstrong(int x) {
        int n=x;
        if (n == getdig(n)){
            return true;
        }
        else return false;

    }

    private static int getdig(int sp){

        int d=sp;
        int r=0, dg=0;
        int length = String.valueOf(sp).length();
     if (length>1){
        for (int count=length; count>=0; count--){

            dg = (int) (d/(Math.pow(10, count)));
            d= (int) (d % (Math.pow(10, count)));
            dg =(int) Math.pow(dg, length);
            r = r + dg;
        }

        }
     else {
         r=sp;
     }
     return r;

        }
}


texts:
Our teacher doesn't give much feedback on our code itself. Was just looking for some feedback on how I could improve on this. This is the method that tests the string against the Turing machine that is built from a file.

The entire project is on GitHub.

public boolean run(String input) {
    String currentState = startState;
    ArrayList<Transition> pT;
    ArrayList<Character> chars = new ArrayList<>();
    int i = 0;

    for (char c : input.toCharArray()) {
        if (!inputAlphabet().contains(c)) {
            return false;
        } else {
            chars.add(c);
        }
    }
    tape.setCells(chars);
    tape.setHeadPosition(i);
    System.out.println(currentState);

    while (i != tape.getCells().size()) {
        pT = new ArrayList<>();
        for (Transition t : transitions) {
            if (t.getFromState().equals(currentState)) {
                pT.add(t);
            }
        }

        for (int j = 0; j < pT.size(); j++) {
            if (tape.getCells().get(i) == pT.get(j).getInputSymbol()) {
                if (pT.get(j).getWriteSymbol() != EMPTY_SYMBOL) {
                    ArrayList<Character> temp;
                    temp = tape.getCells();
                    temp.set(i, pT.get(j).getWriteSymbol());

                    tape.setCells(temp);
                }

                if (pT.get(j).getDirection().charAt(0) == DIRECTION_RIGHT) {
                    i++;
                    tape.setHeadPosition(i);
                } else if (pT.get(j).getDirection().charAt(0) == DIRECTION_LEFT) {
                    i--;
                    tape.setHeadPosition(i);
                }
                currentState = pT.get(j).getToState();
                System.out.println(currentState);
                j = pT.size();
            }
        }
        if (rejectStates.contains(currentState)) {
            return false;
        }
    }

    pT = new ArrayList<>();
    for (Transition t : transitions) {
        if (t.getFromState().equals(currentState)) {
            pT.add(t);
        }
    }

    for (int k = 0; k < pT.size(); k++) {
        if (pT.get(k).getInputSymbol() == EMPTY_SYMBOL) {
            currentState = pT.get(k).getToState();
            System.out.println(currentState);
            if (pT.get(k).getDirection().charAt(0) == DIRECTION_RIGHT) {
                i++;
                tape.setHeadPosition(i);
            } else if (pT.get(k).getDirection().charAt(0) == DIRECTION_LEFT) {
                i--;
                tape.setHeadPosition(i);
            }
            k = pT.size();
        }
    }

    return acceptStates.contains(currentState);
}


texts: Calculating set difference of lists with or without intermediate variables

texts:
Which form of the method do you find more readable?

Version with local variables:

public void checkRetrievedIds( List<Integer> expectedIds, List<Integer> retrievedIds ) {
    Set<Integer> expected = new HashSet<>( expectedIds );
    Set<Integer> retrieved = new HashSet<>( retrievedIds );

    Set<Integer> difference = Sets.difference( expected, retrieved );
    createInvalidationEvents( difference );
}

Or the version without local variables:

public void checkRetrievedIds( List<Integer> expectedIds, List<Integer> retrievedIds ) {
    createInvalidationEvents( Sets.difference(
        new HashSet<>( expectedIds ),
        new HashSet<>( retrievedIds )
    ) );
}

I'm considering the second version as more readable as it reveals the method intent more clearly.


texts: Sliding window of entire length of the file

texts:
I have a tab delimited file which contains about 2207 rows with 4 columns of floats or int types:

Id    pos    value1    value2
01    1123   0.76483   0.9001
02    1124   0.20      0.9800

Another file is to be compared with which contains about 27041 rows with also 4 columns:

name    Id    pos1    pos2
s13e    01    234     800
zz12    01    800     866

Now, my goal is to find all possible consecutive rows of 3 or higher in which:

Their contents of the first column of the first file (Id) are equal to the second column of the second file (Id).
Their contents of the second column of the first file (pos) is in between the range of column 3 and column 4 of the second file.

My approach is to do the following:

Loop through a sliding window of length 3 to the entire length number of rows of the first file (that's my outer loop)
Second loop is to iterate and take each element of the sliding window of some specific length like 3 for instance and then
Check if that element satisfy the conditions above if it is satisfy then break the loop to take the next element of the first file
Otherwise, continue searching for the second file to find the target

For a length 300 rows of the first file the whole sliding window thing with the checking to the second file takes about 5 minutes. However, I am looking for a faster and more efficient way to do that.

An example of a satisfied result is the following:

let's say we have performed a window sliding of a length 3, Note that I have to iterate over the entire length of the file (number of rows) and the length of 3 for the sliding window is just an example!

From file 1:

idW = (01,01,01)
posW = (127, 192,199)
val1W = (.9,.01,.23)
val2W = (.2,.03,.43)

From file 2:

name    Id    pos1    pos2
s13e    01    120     200

For a successful result, the following will have to be met:

Consecutive rows of 3 rows and (true)
Id of file1 are equal file2 and (true)
posW from the first file are in between the values of pos1 and pos2 (true)

The result is satisfy because all conditions above are true and met.

This code is working fine but I want it to be the fastest possible and more efficient:

# borrowed from one answer from stack overflow
def sliding_window (s, n):
 it = iter(seq)
 result = tuple(islice(it, n))
 if len(result) == n:
    yield result
 for elem in it:
    result = result[1:] + (elem,)
    yield result

Ids, pos, val1, val2 = zip(*Data)
# len_Data is the entire length of the file
for windwCounts in range(3,len_Data):
    file2count = 0
    swindow_id = sliding_window(Ids, windwCounts)
    swindow_pos = sliding_window(pos, windwCounts)
    swindow_val1 = sliding_window(val1, windwCounts)
    swindow_val2 = sliding_window(val2, windwCounts)
    slidingWindws = zip(swindow_id, swindow_pos,
                        swindow_val1, swindow_val2)
    for idW, posW, val1W, val2W in slidingWindws:
     while (file2count <= len_file2):
            name,id2,pos1,pos2 = file2[file2count]
            # No point of moving down if the pos of file1 is less than pos2 of file2
            if any(int(ps) < pos2 for ps in posW):
                    break
            # All conditions must be met:-
            ids_cond = all(a_id == id2 for a_id in idW)
            within_data = all(pos1 <= int(ps) <= pos2
                                       for ps in posW)
            if ids_cond and within_data:

                  print "satisfy"
                  break

            else:
                  print "not satisfy"
            file2count += 1


texts: JavaScript Good Patterns - Is this a good example?

texts:
I have been trying various formats of namespaces and modules patterns, however I have not come across a solution that I would use for all my projects.

I've been developing the following, that would allow me to separate my application through applications, modules, functions and global variables. Possibly I'm going to add the possibility to have public and private variables and methods.

/*--------------------------------------------------------------------------
 * Project name
 *
 * Created      : 01/01/2014
 * Modified     : 01/01/2014
 * Version      : 0.1
 * Developer    : Developer Name
 *
---------------------------------------------------------------------------*/
/**
 * @class mainClassName
 * @constructor
 */
window.APP_NAME = window.APP_NAME || {};
window.APP_NAME.moduleName = window.APP_NAME.moduleName || {};
window.APP_NAME.deepExtend = window.APP_NAME.deepExtend || {};

window.APP_NAME.moduleName.globalVariableAvailableForEveryModuleFunctions = 0;

window.APP_NAME.moduleName.functionInsideModule1 = function (options) {

    "use strict";
    /*jslint nomen: true*/
    /*global $, jQuery*/

    // Check for arguments here.
    if (arguments.length !== 1) {
        throw new Error('[ClassName here] Please provide your options.');
    } // if

    // Increase global variable.
    window.APP_NAME.moduleName.globalVariableAvailableForEveryModuleFunctions += 1;

    // Store module defaults.
    window.APP_NAME.moduleName.config = {
        name: 'John',
        age: 29
    };

    // Parse incoming object that stores config files.
    window.APP_NAME.deepExtend(window.APP_NAME.moduleName.config, options);

    // Rest of the application here.
    alert(window.APP_NAME.moduleName.config.name);

    // Call function in same module, to alert the age
    window.APP_NAME.moduleName.functionInsideModule2();

};

window.APP_NAME.moduleName.functionInsideModule2 = function () {

    "use strict";
    /*jslint nomen: true*/
    /*global $, jQuery*/

    // Store global in local var.
    var age = window.APP_NAME.moduleName.config.age;

    // Alert age stored in Module config.
    alert(age);

};

// Helper function to change config defaults.
window.APP_NAME.deepExtend = function (destination, source) {
    for (var property in source) {
        if (source[property] && source[property].constructor &&
            source[property].constructor === Object) {
            destination[property] = destination[property] || {};
            arguments.callee(destination[property], source[property]);
        } else {
            destination[property] = source[property];
        }
    }
    return destination;
};

// Let's run the application!
(function () {

    new window.APP_NAME.moduleName.functionInsideModule1({
        name: 'Mary'
    });

}());

I would like to receive some feedback on this kind of approach, and what you would change.

Variable and method names are long to provide a better understand of context.


texts: Shortest and most efficient way for an endless image/content rotation in Vanilla JS and jQuery

texts:
I wanted to create the most shortest JavaScript code for an endless rotation of elements, without any controls. The elements can be images or SVG-elements (only the Vanilla JS version will work here) or text-container. It doesn't matter. I came up with this:

HTML

CSS

.container > img {
    opacity: 0;
    position: absolute;
     -webkit-transition: all 1s linear;
    transition: all 1.5s linear;
}

.container > img.active {
    opacity: 1;
}

Vanilla JS

var e = document.getElementById('container');
if (e) {
    setInterval(function() {
        var current = container.getElementsByClassName('active')[0];
        current.classList.remove('active');
        var next = current.nextElementSibling || container.firstElementChild;
        next.classList.add('active');
    }, 2000);
}

Try it here

jQuery

var images = $('.container > img');

if (images.length) {
    setInterval(function() {
        var current = images.filter('.active');
        current.removeClass('active');
        var next = ( current.next().length ? current.next() : images.eq(0) );
        next.addClass('active');
    }, 2000);
}

Try it here

Is there anything that can be improved? I'm especially curious about the first line within each interval which involve a request (getElementsByClassName, Vanilla JS) or a loop (.filter, jQuery).


texts: Takes a string array and searches for two words that are anagrams of each other

texts:
Looking for some advice on whether or not this can be improved in terms of efficiency and speed, it would need to work on large data sets.

public class Anagrams {

    public static boolean isAnagram(String str1, String str2) {
    String s1 = str1.replaceAll("\\s", "");
    String s2 = str2.replaceAll("\\s", "");
    boolean status = true;
    if (s1.length() != s2.length()) {
        status = false;
    } else {
        char[] ArrayS1 = s1.toLowerCase().toCharArray();
        char[] ArrayS2 = s2.toLowerCase().toCharArray();
        Arrays.sort(ArrayS1);
        Arrays.sort(ArrayS2);
        status = Arrays.equals(ArrayS1, ArrayS2);
    }
    if (status) {
        return true;
    } else {
        return false;
    }
    }

    public static String searchAnagram(String[] array)
    {

        String anagramsList = "";
        Arrays.sort(array, (str1, str2) -> str1.length() - str2.length());
        for(int i=0;i<(array.length -1); i++)
        {
            int j=0;
            while(array[i].length() == array[i+j].length())
            {

                if(isAnagram(array[i],array[i+j]))
                {
                    anagramsList += (array[i] + " " + array[i+j] + ", ");
                    System.out.println(array[i] + " " + array[i+j] + ", ");
                }
                j++;
            }

        }
        if(anagramsList == "")
        {
            anagramsList = "No anagrams foud";
        }
        return anagramsList;
    }

}


texts: Find the word in a string that has the most repeated characters

texts:
The problem: I want to find the word in a string that has the most repeats of a single letter, each letter is independent. Does not need to be consecutive.

Currently I am jumping each character and checking, which doesn't seem very efficient. Do you have any ideas that might improve the number of processes that are required to find which word has the most repeats?

function LetterCountI(str) {

  var repeatCountList = [];
  var wordList = str.split(/\W/); //regular expression \W for non word characters split at.
  var wordCount = wordList.length; // count the number of words
  for (var i=0; i< wordCount ; i++)
  { var mostRepeat = 1;                 // set the default number of repeats to 1
    var curWord = wordList[i];             // set the current word to the ith word from the list

   for(var ii=0; ii<curWord.length ; ii++)
    { var repeatCount = 1;                   // set default repeat count to 1
      var curChar = curWord[ii];               //set the current character to the iith
     for (var iii=0; iii<curWord.length; iii++)  //judge if it is the same as the iiith
     {var against = curWord[iii];
      if (iii!=ii)                               // if it is Not the same referenced postion
      {if(curChar==against)                      // see if the string values match
      {repeatCount=repeatCount+1}}}               // increase counter if match against
       if (repeatCount>=mostRepeat)              // record repeat for the highest only
       {mostRepeat=repeatCount}

    }
   repeatCountList = repeatCountList.concat(mostRepeat)    // take the highest from each word
     }

  mostRepeat = 0;                     // set the repeats value to -
  for (j=0;j<wordCount; j++)            // go through the repeats count list
  { if(repeatCountList[j]>mostRepeat)       // if it has more repeats than the highest So FAR
       { mostRepeat = repeatCountList[j];        // record if higher than last
        var x = j;}}                      // record the index of the most repeat that is the new high
  var ans = [];
  if (mostRepeat == 1)              // check if there are no repeats at all.
  {ans=-1}                // question want to return -1 if there are no repeats
  else
  {ans=wordList[x]}          // display the word from the list with the most repeat characters

  // code goes here
  return ans;

}

Any help is appreciated.


texts:
I have just written a simple program to implement the Caesar cipher using lists. The program assumes the input will be all capital letters. I'm quite new to Python and am just curious of some more efficient ways to write this code. Honestly I just want to work on defining functions and all that jazz.

print("This encryption program uses the Caesar cipher to encrypt your message.")
mode = input("E to Encrypt or D to Decrypt")
if mode == "E":
    string = input("Input your message to encrypt in all capital letters: ")
    key = int(input("Create your encryption key (remember this)"))
    length = len(string)

    old_values = [0]*length
    new_values = [0]*length

    olds_position = 0
    news_position = 0

    for char in string:
        old_values[olds_position] = ord(char)
        olds_position += 1

    for value in old_values:
        if value != 32:
            new_values[news_position] = (value + key)
        else:
            new_values[news_position] = value
        news_position += 1

    for newvalue in new_values:
        if newvalue != 32:
            if newvalue > ord('Z'):
                newvalue -= 26
            elif newvalue < ord('A'):
                newvalue += 26
            print(chr(newvalue)+"", end="")
        else:
            print(" ", end="")

if mode == "D":
    key = int(input("Enter your encryption key: "))
    string = input("Input your encrypted message to descrypt it: ")
    length = len(string)

    old_values = [0]*length
    new_values = [0]*length

    olds_position = 0
    news_position = 0

    for char in string:
        old_values[olds_position] = ord(char)
        olds_position += 1

    for value in old_values:
        if value != 32:
            new_values[news_position] = (value - key)
        else:
            new_values[news_position] = value
        news_position += 1

    for newvalue in new_values:
        if newvalue != 32:
            if newvalue > ord('Z'):
                newvalue -= 26
            elif newvalue < ord('A'):
                newvalue += 26
            print(chr(newvalue)+"", end="")
        else:
            print(" ", end="")


texts: Iterator producing unique random numbers in a specified range

texts:
I needed an iterator that produced random numbers, never repeating them, in a specified range of 0..max-1 (index for a collection). When the numbers are exhausted it should not have a next anymore.

The simplest way might be to shuffle an ArrayList and make an iterator. But in typical usage, I will want only 4-5 unique random numbers, from a total in the region of 100. So shuffle seemed too CPU-heavy. And here is the class I came up with. It is written in Java 8 (the requirement of version 8 is acceptable in my case).

import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class NonRepeatingRandom implements Iterator<Integer> {

    private List<Integer> unused;
    private Random random;

    public NonRepeatingRandom(int max) {
        unused = IntStream.range(0, max).boxed().collect(Collectors.toList());
        random = new Random();
    }

    @Override
    public boolean hasNext() {
        return ( unused.size() > 0 );
    }

    @Override
    public Integer next() {
        int size = unused.size();
        if ( size==0 ) {
            throw new java.util.NoSuchElementException();
        }
        int idx = random.nextInt(size);
        int result = unused.get(idx);
        unused.remove(idx);
        return result;
    }

}

I would appreciate comments on this code.


texts:
The request below takes very long on slower internet connections and Heroku is throwing a Request Timeout error for many users. The API request is being made by many different users hundreds of times per 30-60 seconds. Here's how it works

There is Cars collection in MongoDB that contains an array of csv_files
A user makes a POST API request to my Node.js server

Their POST request contains a very long CSV string

The server first finds the Car the user is posting their new CSV data to and then loops over every file in csv_files

If there is an existing file that matches the name of the user's POST request file, then we replace mark that we found an existing CSV file and replace it
If we don't find an existing file then we just push the CSV string into the Car csv_files array

When we're done, we save our newly updated Car to MongoDB and return a 204 response

Here is the code:

router.post('/cars/:url/upload-csv/', async (req, res) => {
  let csv = req.body.csv_string.split('$');

  let csv_name = csv[0];
  let csv_string = csv_name+csv[1];

  let car = await Car.findOne({ url: req.params.url });

  if (!car)
    return res.status(400).json({ msg: 'No car found. Could not upload CSV' });

  if (car.csv_files.length === 0) {
    car.csv_files.push(csv_string);
  } else {
    let foundExistingCSV = false;
    for (let i = 0; i < car.csv_files.length; i++) {
      if (car.csv_files[i].includes(csv_name)) {
        foundExistingCSV = true;
        car.csv_files[i] = csv_string;
        break;
      }
    }

    if (!foundExistingCSV) {
      car.csv_files.push(csv_string);
    }
  }

  car.markModified('csv_files');
  car.save();

  return res.status(204).json({ msg: 'All good!' });
});


texts: Scraping titles and links from a site using python

texts:
I've written a script which when I run parses the link of the item from the left sided menu,then it tracks down each individual links to it's main page. Some links spread through pagination some end in a single page. Whatever the case is, the crawler scrapes name and href of each item. While doing so I came across some duplicates which eventually I shook off using got_already function. The site contains 251 videos and my crawler is able to parse them all. Here is what I have done:

import requests
from lxml import html

got_already=[]
Page_link="http://www.wiseowl.co.uk/videos/"
Blink="http://www.wiseowl.co.uk"

def startpoint(page):
    req=requests.Session()
    response = req.get(page)
    tree = html.fromstring(response.text)
    titles = tree.xpath("//ul[@class='woMenuList']//li[@class='woMenuItem']/a/@href")
    for title in titles:
        if "author" not in title and "year" not in title:
            GrabbingData(Blink + title)
            midpoint(Blink + title)

def midpoint(links):
    req=requests.Session()
    response = req.get(links)
    tree = html.fromstring(response.text)
    for links in tree.xpath("//a[@class='woPagingItem']/@href"):
        GrabbingData(Blink + links)

def GrabbingData(url):
    req=requests.Session()
    response = req.get(url)
    tree = html.fromstring(response.text)
    for item in tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']"):
        title = item.xpath('.//a/text()')[0]
        link = item.xpath('.//a/@href')[0]
        if title not in got_already:
            got_already.append(title)
            got_already.append(link)
            print(title,link)

startpoint(Page_link)


texts: Finding total values for each day - Postgresql

texts:
I wrote an SQL query to find how many leases were "active" for each day of 2018. So if a contract began on 27/12/18 and ended on 27/12/18 and another one began on 27/12/18 and ended on 28/12/18, the number for 27/12/18 is 2 and the number for 28/12/18 is 1.

My query works fine but while trying to write this query I learned new functions like coalesce() and generate_series() but I am not sure if I used them in a decent way.

  Registrationform(PK plate:varchar, PK period_begin:timestamp, PK
  period_end:timestamp, FK email:varchar)

SELECT TO_CHAR(ts::date, 'DD/MM/YYYY') AS date, coalesce(count, 0) AS number
FROM
  (SELECT date::date, count(*)
   FROM registration_form
   cross join generate_series(period_begin, period_end, '1day'::interval) date
   where period_end between '2018-01-01' and '2018-12-31'
   GROUP BY 1
   order by date) as m
  RIGHT JOIN
  (SELECT *
   FROM generate_series(timestamp '2018-01-01',
                        timestamp '2018-12-31',
                        interval '1 day')) AS series(ts)
  ON m.date = series.ts


texts: VBA - new built-in enumerations and backwards compatibility

texts:
msoGraphic is an MsoShapeType enumeration that is available in Office PowerPoint 2016 and later (versions which can handle svg graphics). If you attempt to check an MsoShapeType against msoGraphic in earlier versions of Office you will get a compile error - as msoGraphic is not defined (in any module containing Option Explicit). I am handling this by putting this property in a module where Option Explicit is NOT declared - and calling it from anywhere that needs the value of the constant. The module only contains this property (and any other properties that need to handle any other constants in this way).

Public Property Get myMsoGraphic() As Long

  If msoGraphic = 0 Then
    myMsoGraphic = 28
  Else
    myMsoGraphic = msoGraphic
  End If

End Property

I could of course have just re-declared msoGraphic as a constant with value 28, but best practice seems to be that you should avoid using the actual value and use the enumerate constant instead - in case the value gets changed at some point in the future (which I guess is probably highly unlikely).

Does this seem like the best way to handle this situation?


texts:
I found myself in a need of a function that checks whether a string is a sub-string of another string, in a case-insensitive manner. I found that there's no standard function to do this, so I wrote my own.

Please review for bugs / improvements:

char *istrstr(char *str, const char *substr)
{
    size_t n = 0;
    while (*str) {
        while (str[n] && substr[n]) {
            if (tolower(str[n]) != tolower(substr[n])) {
                break;
            }
            n++;
        }
        if (!substr[n]) {
            return str;
        }
        else if (!str[n]) {
            return substr[n] ? str : NULL;
        }
        n = 0;
        str++;
    }
    return NULL;
}


texts: Add lines from files to corresponding dictionaries

texts:
I have to iterate through multiple text files. For each file I read its contents and append each line to its corresponding dictionary to then build a JSON file.
Each text file has the following structure:

Line 1: The title key.
Line 2: The name key.
Line 3: The date key.
Line 4: The feedback key.

Here is an example of two of these files:
001.txt

Great Customer Service
John
2017-12-21
The customer service here is very good. They helped me find a 2017 Camry with good condition in reasonable price. Compared to other dealers they provided the lowest price. Definitely recommend!

002.txt

You will find what you want here
Tom
2019-06-05
I've being look around for a second handed Lexus RX for my family and this store happened to have a few of those. The experience was similar to most car dealers. The one I ended up buying has good condition and low mileage. I am pretty satisfied with the price they offered.

My approach is successful but I wonder if there is a better and faster approach of joining each line to its corresponding dictionary.
Additionally do I need to write with open('file', 'r') for each file? Even when I use os.listdir() I still have the same issue.
import json

l1 = []
l2 = []

with open("C:/Users/user/Desktop/001.txt") as file1, open("C:/Users/user/Desktop/002.txt") as file2:
    for line1, line2 in zip(file1, file2):
      if not line1.isspace() and not line2.isspace():
        l1.append(line1.rstrip())
        l2.append(line2.rstrip())

Dict = {}

Dict['dictio1'] = {'title': "", "name": "", "date": "", "feedback": ""}

Dict['dictio2'] = {'title': "", "name": "", "date": "", "feedback": ""}

Dict['dictio1']["title"] = l1[0]
Dict['dictio1']["name"] = l1[1]
Dict['dictio1']["date"] = l1[2]
Dict['dictio1']["feedback"] = l1[3]

Dict['dictio2']["title"] = l2[0]
Dict['dictio2']["name"] = l2[1]
Dict['dictio2']["date"] = l2[2]
Dict['dictio2']["feedback"] = l2[3]

with open('file.json', 'w') as file_json:
    json.dump(Dict, file_json, indent=2)

{
  "dictio1": {
    "title": "Great Customer Service",
    "name": "John",
    "date": "2017-12-21",
    "feedback": "The customer service here is very good. They helped me find a 2017 Camry with good condition in reasonable price. Campared to other dealers they provided the lowest price. Definttely recommend!"
  },
  "dictio2": {
    "title": "You will find what you want here",
    "name": "Tom",
    "date": "2019-06-05",
    "feedback": "I've being look around for a second handed Lexus RX for my family and this store happened to have a few of those. The experience was similar to most car dealers. The one I ended up buying has good condition and low mileage. I am pretty satisfied with the price they offered."
  }
}


texts: Alternative to starting enum values with a number

texts:
I have an enum like the following:

enum MeasurementBandwidth
{
    Hz1 = 1,
    Hz3 = 3,
    Hz10 = 10,
    ...
}

But I do not like the Hz1, and 1Hz is not valid as it starts with a number.

Does anyone have an idea how to solve this "more elegant"?

Why I am doing this:

I have an API, which offers a method like the following:

public double MeasureInput(double frequency, MeasurementBandwidth bandwidth) { /*...*/ }

And the bandwidth only has a few possible values which can be used and I want to make it as easy as possible for the "user" to choose a valid one. Using an enum was the best solution I came up with, as it is directly visible from the parameter type, what values are valid.


texts:
I have the following radix sort implementation:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstddef>
#include <algorithm>

void radix_sort(std::vector<int>& arr)
{
    int radix = 1;
    // Largest element in unsorted array
    int max = *(std::max_element(arr.begin(), arr.end()));
    while(max / radix)
    {
        // Buckets used for sorting. Each bucket representing a digit.
        std::vector<std::vector<int>> buckets(10, std::vector<int>());
        for(const auto& num : arr)
        {
            int digit = num / radix % 10;
            buckets[digit].push_back(num);
        }
        std::size_t k = 0;
        // Take the elements out of buckets into the array
        for(std::size_t i = 0; i < 10; i++)
        {
            for(std::size_t j = 0; j < buckets[i].size(); j++)
            {
                arr[k] = buckets[i][j];
                k++;
            }
        }
        // Change the place of digit used for sorting
        radix *= 10;
    }

}

// Function to print array
void print_arr(std::vector<int>& arr)
{
    for(auto elem : arr)
    {
        std::cout << elem << "\t";
    }
    std::cout << "\n";
}

int main()
{
    std::vector<int> arr;
    std::string s;
    std::cout << "Enter the elements: " << std::endl;
    std::getline(std::cin, s);
    std::istringstream ss(s);
    int val;
    while(ss >> val)
    {
        arr.push_back(val);
    }
    std::cout << "Before sorting: \n";
    print_arr(arr);
    radix_sort(arr);
    std::cout << "After sorting: \n";
    print_arr(arr);
    return 0;
}

I pass an array to the radix_sort function. It uses a variable called radix to identify the digit in a particular place (unit, ten, hundred etc.) in the number. Based on this digit, we sort elements into buckets. Once this sorting is done, the elements are taken out based on the order of bucket (The elements in zeroth bucket comes out first, followed by those in first bucket, second bucket and so on). This is repeated until all the digits in the largest element are visited.

1) I would like to know if there is a better data structure for buckets?

2) Is there a more efficient method to find largest element in the unsorted array?

3) If possible, please provide an overall review of the code.


texts: Counting business days in a month, ignoring holidays

texts:
This table simply contains date information. I went ahead and used what I currently have since this is a one-time operation. However, since I only recently started working with Oracle, I would like to learn about all its different features and such.

The code is trying to establish if it is a business day or not while ignoring holidays. Essentially, we want a running total of business days for each day in a month. This value does need to be stored in the main table in the end.

Is there a better way to write this?

DECLARE
    Cursor MyCursor IS
        select  cc.calendar_dt,
                cc.CALENDAR_DT_ID,
                calendar_month_abbreviation,
                calendar_year_number,
                to_char(cc.calendar_dt,'MM') as m
        from    CALENDAR_DT cc
        order   by cc.calendar_dt ;

    entry MyCursor%ROWTYPE;

    new_number NUMBER := 1;
    curr_month NUMBER := 0;
begin

    FOR entry IN MyCursor LOOP

        if (curr_month != (entry.m)) then
            new_number := 1;
            curr_month := entry.m;
        else
            new_number := new_number + (case when to_char(entry.CALENDAR_DT,'D') in (1,7) then 0 else 1 end);
        end if;

        DBMS_OUTPUT.PUT_LINE(entry.calendar_dt || '    ' || new_number || '   ' || to_char(entry.CALENDAR_DT,'DAY') );

        --UPDATE CALENDAR_DT
        --        SET  business_day_number = new_number
        --        WHERE  CALENDAR_DT_ID = ENTRY.CALENDAR_DT_ID;

    END LOOP;

END;

Output with year=2014 and month in nov, dec and it is what I expect:

01-NOV-2014    1   SATURDAY
02-NOV-2014    1   SUNDAY
03-NOV-2014    2   MONDAY
04-NOV-2014    3   TUESDAY
05-NOV-2014    4   WEDNESDAY
06-NOV-2014    5   THURSDAY
07-NOV-2014    6   FRIDAY
08-NOV-2014    6   SATURDAY
09-NOV-2014    6   SUNDAY
10-NOV-2014    7   MONDAY
11-NOV-2014    8   TUESDAY
12-NOV-2014    9   WEDNESDAY
13-NOV-2014    10   THURSDAY
14-NOV-2014    11   FRIDAY
15-NOV-2014    11   SATURDAY
16-NOV-2014    11   SUNDAY
17-NOV-2014    12   MONDAY
18-NOV-2014    13   TUESDAY
19-NOV-2014    14   WEDNESDAY
20-NOV-2014    15   THURSDAY
21-NOV-2014    16   FRIDAY
22-NOV-2014    16   SATURDAY
23-NOV-2014    16   SUNDAY
24-NOV-2014    17   MONDAY
25-NOV-2014    18   TUESDAY
26-NOV-2014    19   WEDNESDAY
27-NOV-2014    20   THURSDAY
28-NOV-2014    21   FRIDAY
29-NOV-2014    21   SATURDAY
30-NOV-2014    21   SUNDAY
01-DEC-2014    1   MONDAY
02-DEC-2014    2   TUESDAY
03-DEC-2014    3   WEDNESDAY
04-DEC-2014    4   THURSDAY
05-DEC-2014    5   FRIDAY
06-DEC-2014    5   SATURDAY
07-DEC-2014    5   SUNDAY
08-DEC-2014    6   MONDAY
09-DEC-2014    7   TUESDAY
10-DEC-2014    8   WEDNESDAY
11-DEC-2014    9   THURSDAY
12-DEC-2014    10   FRIDAY
13-DEC-2014    10   SATURDAY
14-DEC-2014    10   SUNDAY
15-DEC-2014    11   MONDAY
16-DEC-2014    12   TUESDAY
17-DEC-2014    13   WEDNESDAY
18-DEC-2014    14   THURSDAY
19-DEC-2014    15   FRIDAY
20-DEC-2014    15   SATURDAY
21-DEC-2014    15   SUNDAY
22-DEC-2014    16   MONDAY
23-DEC-2014    17   TUESDAY
24-DEC-2014    18   WEDNESDAY
25-DEC-2014    19   THURSDAY
26-DEC-2014    20   FRIDAY
27-DEC-2014    20   SATURDAY
28-DEC-2014    20   SUNDAY
29-DEC-2014    21   MONDAY
30-DEC-2014    22   TUESDAY
31-DEC-2014    23   WEDNESDAY

Other than style changes (this was a really quick, one-time-only thing so sloppy doesn't truly matter, no one will ever see it but me and you guys - function does always matter)...

Is this approach the best (only?) one for this kind of operation in Oracle?


texts:
Project Euler problem 78:

  Let \$p(n)\$ represent the number of different ways in which \$n\$ coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so \$p(5)=7\$.

  Find the least value of \$n\$ for which \$p(n)\$ is divisible by one million.

I used Euler's recurrence relation for the partition of \$n\$, together with the fact that modular addition is distributive: $$(a + b) \bmod n = ((a \bmod n) + (b \bmod n)) \bmod n.$$

#include <iostream>
#include <vector>
using namespace std;

int main()
{
  // generalized pentagonal numbers
  vector<int> g = vector<int>({1, 2}); // g_1 = 1, g_-1 = 2
  // integer partitions
  vector<int> p = vector<int>({1}); // p_0 = 1
  for (int n = 1; n ; n++) {
    if (g.back() <= n) {
      int k = g.size()/2 + 1;
      g.push_back(k*(3*k - 1)/2);
      k *= -1;
      g.push_back(k*(3*k - 1)/2);
    }
    int p_n = 0;
    for (vector<int>::iterator g_k = g.begin(); *g_k <= n; ++g_k) {
      if ((g_k - g.begin())/2 % 2 == 0) {
        p_n += p[n - *g_k];
      } else {
        p_n -= p[n - *g_k];
      }
    }
    p.push_back(p_n % 1000000);
    if (p.back() < 0) p.back() += 1000000;
    if (p.back() == 0) {
      cout << n << endl;
      break;
    }
  }
  return 0;
}

My i7 handles this in ~25ms, but my circa 2008 32-bit centrino needs 600ms. Is there any way that I can squeeze more performance out of the above code? Also, with the exception of removing using namespace std;, is there anything I can do to make the code cleaner/more readable/more presentable?


texts:
Given an array, A=[a0,a1,a2...an], perform queries in the form left
  right x y. For each query, print the number of elements satisfying
  the following criteria:

  left < i < right
  a[i] = y(mod x)

  Note: We can write a[i] = y(mod x) as a[i] % x == y in most popular
  programming      languages.

  Input Format

  The first line contains two space-separated integers describing the
  respective values of (the size of ) and (the number of queries). The
  second line has space-separated integers describing the respective
  values of . Each of the subsequent lines describes a query in the form
  left right x y.

  Output Format

  For each query, print an integer denoting the number of array elements
  satisfying the given criteria on a new line.

  Sample Input 0

5 3
250 501 5000 5 4
0 4 5 0
0 4 10 0
0 4 3 2

  Sample Output 0

3
2
2

Can this code be optimized in any way?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int n,q;
    cin>>n>>q;
    int A[n];
    for(int i=0;i<n;i++)
        cin>>A[i];
    while(q--)
        {
       int a,b,x,y,c=0;
        cin>>a>>b>>x>>y;
        for(int i=a;i<=b;i++)
            {
            int t=A[i];
           if(t%x==y)
                c++;
        }
        cout<<c<<endl;
    }
    return 0;
}


texts: Copying sections of one picture to another

texts:
I have two solutions (in Jython) to take two pictures and copy and paste alternate sections of one picture to the other, like so:

for x in range (0,w):
  for y in range (0,h):
    sourcePx=getPixel(pic1,x,y)
    targetPx=getPixel(pic2,x,y)
    if (y>=0 and y<20) or (y>=40 and y<60)or (y>=80 and y<=100):
      setColor(targetPx, getColor(sourcePx))
repaint (pic2)

for y in range(0,h):
  leaf = (y>=0 and y<20) or (y>=40 and y<60)or (y>=80 and y<=100):
  if leaf:
    for x in range(width):
      sourcePx = getPixel(pic1, x, y)
      targetPx = getPixel(pic2, x, y)
      setColor(targetPx, getColor(sourcePx))
  repaint(pic2)

I have been trying to work this out and have two questions about this:

Which is the more efficient way to loop through the pixels and why?
Does it make any difference to efficiency (and if so how), creating the variable leaf and then using that in the if statement?