texts: Surely there's a better way to write this statement?

texts:
I have the following, quite ugly statement - is there a better way to write something of this nature?

if (!item["Created By"].ToString().Contains("System Account") &&
    !item.Url.Contains("_catalogs") &&
    !item.Url.Contains("Style Library") &&
    !item.Url.Contains("Cache Profiles") &&
    !item.ContentType.ToString().Contains("Theme Gallery") &&
    !item.ContentType.ToString().Contains("Converted Forms") &&
    !item.ContentType.ToString().Contains("Page Output Cache") &&
    !item.ContentType.ToString().Contains("Master Page"))
{
    query.RecordItems(item.ID.ToString(), item.ContentType.Name,
                        item.DisplayName, item.Name,
                        "", item.Url, item["Created By"].ToString(),
                        "",
                        Convert.ToDateTime(item["Modified"]),
                        item["Modified By"].ToString(),
                        Convert.ToDateTime(item["Created"]),
                        item["Created By"].ToString());
}

For a frame of reference, here's the proceeding code:

using (var web = activeSiteCollection.OpenWeb())
{
    foreach (SPList list in web.Lists)
    {
        query.RecordLists(list.ID.ToString(), list.Author.ToString(), list.Title,
                            list.DefaultViewUrl,
                            list.ParentWeb.Title, list.ParentWebUrl, list.ItemCount,
                            list.LastItemModifiedDate, list.LastItemDeletedDate);

        // check if files exist in the document library, if they don't break out to next level
        if (list.ItemCount <= 0) continue;

        for (int i = 0; i < list.Items.Count; i++)
        {
            try
            {
                SPListItem item = list.Items[i];

                if (!item["Created By"].ToString().Contains("System Account") &&
                    !item.Url.Contains("_catalogs") &&
                    !item.Url.Contains("Style Library") &&
                    !item.Url.Contains("Cache Profiles") &&
                    !item.ContentType.ToString().Contains("Theme Gallery") &&
                    !item.ContentType.ToString().Contains("Converted Forms") &&
                    !item.ContentType.ToString().Contains("Page Output Cache") &&
                    !item.ContentType.ToString().Contains("Master Page"))
                {
                    query.RecordItems(item.ID.ToString(), item.ContentType.Name,
                                        item.DisplayName, item.Name,
                                        "", item.Url, item["Created By"].ToString(),
                                        "",
                                        Convert.ToDateTime(item["Modified"]),
                                        item["Modified By"].ToString(),
                                        Convert.ToDateTime(item["Created"]),
                                        item["Created By"].ToString());
                }
            }
            catch (NullReferenceException)
            {
                SPListItem item = list.Items[i];

                Logger.Error(
                    "[{0}] Filed moving on file {1} as not all content was present",
                    item.Name);
            }

        }


texts: Trending Machine Learning topics for Alexa

texts:
I've created a small Flash Briefing Alexa skill that reports the top 5 trending topics in Machine Learning from the My Bridge service.

The feed for the Flash Briefing skill can be pointed to an external endpoint, but the response has to be in a certain format.

Sample:

[
    {
        mainText: "Posted by Hui Fang, Software Engineer, Machine Perception Machine learning (ML) excels in many areas with well defined goals. Tasks where ...",
        redirectionUrl: "https://research.googleblog.com/2017/07/using-deep-learning-to-create.html",
        titleText: "Using Deep Learning to Create Professional-Level Photographs",
        uid: "200561",
        updateDate: "2017-07-13T20:11:59.000000Z"
    },
    ...
]

To expose an endpoint I've created a small Flask app (deployed to Heroku, runs on gunicorn), that interacts with a My Bridge API via the requests module:

from datetime import datetime
import logging

from flask import Flask, jsonify
import requests

ML_ID_URL = "https://mybridge-backend.herokuapp.com/api/v1/skills/mapping/machine-learning"
ML_TOP_URL = "https://mybridge-backend.herokuapp.com/api/v1/knowledge/skills/{id}?offset=0&limit=5&sort="

logger = logging.getLogger()
logger.setLevel(logging.INFO)

app = Flask(__name__)

@app.route("/")
def main():
    with requests.Session() as session:
        session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"}

        # get topic ID
        response = session.get(ML_ID_URL)
        data = response.json()

        ml_topic_id = data["body"]["id"]

        # get top 5 trending topics
        response = session.get(ML_TOP_URL.format(id=ml_topic_id))
        data = response.json()

        return jsonify([
            {
                "uid": str(topic["id"]),
                "updateDate": datetime.strptime(topic["reg_date"], "%Y-%m-%d %H:%M:%S.%f").strftime("%Y-%m-%dT%H:%M:%S.%fZ"),  # "2016-04-10T00:00:00.0Z"
                "titleText": topic["title"],
                "mainText": topic["excerpt"],
                "redirectionUrl": topic["externalURL"]
            }
            for topic in data['body']
        ])

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

What would you improve code style and code organization wise?


texts: python: generate a 'diff' dictionary out of two nested dictionaries

texts:
I have written a function diff that takes two nested dictionaries and it computes a difference of their content (what is inside the list) returning a new dictionary. To better explain what I mean by difference here is an example of two input dictionaries:

dep={'cl1': {'to_do': ['bill', 'ann 46.0.1']},
     'cl2': {'to_do': ['ann 2.2.3']},
     'cl3': {'to_do': ['bill 2.4']}}

ins={'cl1': {'present': ['bill', 'ann 46.0.1', 'ann 2.2.3']},
     'cl2': {'present': ['ann 2.2.3','joy 6.9','matt 6.9']},
     'cl3': {'present': ['bill 2.4']}}

The diff function compares, for each key (cl1 with cl1,cl2 with cl2 and so on...), the present list of ins with the to_do list of dep. If an item of the present list does not appear in the to_do list for a specific key than this item will be added to a list in the output dictionary. If the item found in the present is already in to_do than None will be added to the list. The function returns a dictionary having the same structure as the input dictionaries. Only the names appearing in the list are taken, i.e. no numbers after the names.

For instance the diff function applied to the case above will give:

out = diff(ins,dep)
out = {'cl1': {'to_uninstall': ['ann']},
       'cl2': {'to_uninstall': ['joy', 'matt']},
       'cl3': {'to_uninstall': [None]}}

Below is the function I am using:

def diff(installed, deploy):
    answer = {}
    #ls_uninst=[]
    for ki,vi in installed.iteritems():
        for kd, vd in deploy.iteritems():
            if ki == kd:
                for ki1, vi1 in vi.iteritems():
                    for kd1, vd1 in vd.iteritems():
                        ls_uninst = []
                        # check if the list is empty
                        if not vi1 :
                            answer[ki] = {}
                            answer[ki]['to_uninstall'] = [None]
                        # non empty list
                        else:
                            for i in vi1:
                                if i not in vd1:
                                    # this gives only the name of the package (not the version)
                                    ls_uninst.append(i.split()[0]) # use i only to get the full name
                                elif i in vd1:
                                    ls_uninst.append(None)
                                # Check if lists contains only None
                                if all(x is None for x in ls_uninst):
                                    answer[ki] = {}
                                    answer[ki]['to_uninstall'] = [None]
                                else: # If at least one package is found
                                    ls_final = [x for x in ls_uninst if x is not None]
                                    answer[ki] = {}
                                    answer[ki]['to_uninstall'] = ls_final
    return answer

It works but I guess this could improved..how? Thanks


texts: Shifting event times to and from time zones

texts:
I have getOffseSeconds method:

private int getOffsetSeconds(LocalDateTime localDateTime, ZoneId zoneId) {
    return ZonedDateTime.of(localDateTime, zoneId).getOffset().getTotalSeconds();
}

This method is used in shifted LocalDateTime calculation

private void shiftEventDateTimeToOriginalZone(EventDto event) {
    event.setStartDateTime(event.getStartDateTime().plusSeconds(
            getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone())));
    event.setEndDateTime(event.getEndDateTime().plusSeconds(
            getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone())));
}

Now I need similar method to last one but with small change:

private void shiftEventDateTimeToDefaultZone(EventDto event) {
    event.setStartDateTime(event.getStartDateTime().minusSeconds(
            getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone())));
    event.setEndDateTime(event.getEndDateTime().minusSeconds(
            getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone())));
}

As you can see, the difference is in using methods: plusSeconds and minusSeconds. I want replace 2 last methods with another one with same first parameter and second should be lambda operation plusSecondsOperation or minusSecondsOperations. But I do not know how to do it in Java (Java 8).


texts: Checking in four directions for board game win

texts:
I have the following code which I would like to simplify in Haskell, although I'm not sure how. I recall that I can use monads to simplify a case chain when the result of the case leads onto a next bit of code but in my example, I return from the function when I get a value, and continue to the next bit of code if I don't get a value (Nothing).

checkWon :: Board -> Maybe Col
checkWon board = let moves = pieces board
                     n     = target board
                     col   = snd (moves !! 0) in
    case east moves col n of
        Just c  -> Just c
        Nothing ->
            case west moves col n of
                Just c -> Just c
                Nothing ->
                    case north moves col n of
                        Just c -> Just c
                        Nothing ->
                            case south moves col n of
                                Just c -> Just c
                                Nothing -> Nothing

The only other thing I've tried is using if statements where I calculate all the values of the functions before-hand and test against them in a if-else branch; but this still feels verbose. Is there any syntactic sugar in Haskell to simplify this, or is my current solution the best option? Maybe I would need to structure my code so I don't fall into this example?


texts:
I was given a file of size 46KB full of names (around ~5000), in the format as shown below:

"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"..."DARRELL","ALONSO"

I wonder if my code below is optimal in doing what I want, which is to translate this txt file into an array of names.

array = []
File.readlines('names.txt').each do |l|
  array << l.delete("\"").split(",")
end

array.flatten


texts:
I have written the following implementation of the Caesar cipher for an old Linux computer with a Pentium MMX chip.  The code has been written with the following design goals in mind:

the code should perform well
to avoid timing side-channel attacks, the runtime should be independent of the data used
the code should run on a Pentium MMX

Please let me know of possible improvements and performance pitfalls I fell in.

    # MMX caeasar cipher implementation
    # for i586 with MMX
    # signature:
    # caesar(out, in, len, key)
    # key is between 0 and 25

    .section .text
    .globl caesar
    .type caesar,@function
    .align 16
caesar:
    push %ebp
    mov %esp,%ebp
    push %ebx
    push %edi
    push %esi

    mov 8(%ebp),%edi        # edi: destination
    mov 12(%ebp),%esi       # esi: source
    mov 16(%ebp),%edx       # edx: length
    and $~7,%edx            # only process full qwords
    test %edx,%edx
    jz 1f

    xor %ecx,%ecx           # ecx: index
    movd 20(%ebp),%mm5
    punpcklbw %mm5,%mm5
    punpcklwd %mm5,%mm5
    punpckldq %mm5,%mm5     # mm5: key bytes

    movq %mm5,%mm4
    psubb twentysix,%mm4        # mm4: key - 26

    movq Amask,%mm6
    psubb %mm4,%mm6         # mm6: 'A' - 1 - (key - 26)

    .align 16
0:  movq (%esi,%ecx),%mm0
    movq %mm0,%mm1
    pand ucmask,%mm1        # mm1: xmm0 in upper case

    movq %mm1,%mm3
    movq %mm1,%mm2

    pcmpgtb Amask,%mm2      # mm2: 0xff where 'A' <= buf[i]
    pcmpgtb Zmask,%mm3      # mm3: 0xff where 'Z' < buf[i]
    pcmpgtb %mm6,%mm1       # mm1: 0xff where 'A' + key <= buf[i]

    pandn %mm1,%mm3
    pand %mm4,%mm3          # mm3: key-26 where 'A' + (26 - key) <= buf[i] <= 'Z'

    pandn %mm2,%mm1
    pand %mm5,%mm1          # mm1: key where 'A' <= buf[i] < 'A' + (26 - key)

    por %mm3,%mm1           # mm1: 0/key/key-26
    paddb %mm1,%mm0
    movq %mm0,(%edi,%ecx)

    add $8,%ecx
    cmp %edx,%ecx
    jb 0b
    emms
    add %ecx,%edi
    add %ecx,%esi

1:  mov 16(%ebp),%edx       # length
    mov 20(%ebp),%ecx       # key
    and $7,%edx         # loop tail

    # process remaining bytes
    add %edx,%edi       # end of output buffer
    add %edx,%esi       # end of input buffer
    neg %edx        # index counts up to 0

    lea -26(%ecx),%eax  # al: key - 26
    mov $'A'+26-1,%ah
    sub %cl,%ah     # ah: threshold ('A' - 1 - (key - 26))

    .align 16
0:  mov (%esi,%edx),%bl
    and $~0x20,%bl      # bl: uppercase c
    cmp $'Z'+1,%bl      # cf: uc <= 'Z'
    sbb %ch,%ch     # ch: 0xff if uc <= 'Z'
    cmp %bl,%ah     # cf: thresh < uc
    sbb %bh,%bh     # bh: 0xff if thresh < uc
    and %bh,%ch
    and %al,%ch     # ch: key - 26 & isleZ & isgttthres
    not %bh         # bh: ~isgtthresh
    cmp $'A',%bl
    cmc         # cf: 'A' <= uc
    sbb %bl,%bl     # bl: 0xff if 'A' <= uc
    and %bh,%bl
    and %cl,%bl     # bl: key & isgeA & ~isgtthresh
    or %ch,%bl
    add (%esi,%edx),%bl
    mov %bl,(%edi,%edx)
    inc %edx
    jnz 0b

1:  pop %esi
    pop %edi
    pop %ebx
    leave
    ret
    .size caesar,.-caesar

    .section .rodata.cst8,"aM",@progbits,8
    .align 8
    .type ucmask,@object
ucmask: .fill 8, 1, ~0x20
    .size ucmask, 8
    .type Amask,@object
Amask:  .fill 8, 1, 'A' - 1
    .size Amask, 8
    .type Zmask,@object
Zmask:  .fill 8, 1, 'Z'
    .size Zmask, 8
    .type twentysix,@object
twentysix:
    .fill 8, 1, 26
    .size twentysix, 8

You can use this harness to test the code:

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern void caesar(const char *out, char *in, size_t len, int key);

extern int
main(int argc, char *argv[])
{
    char *buf = NULL;
    size_t len = 0;
    ssize_t count;
    int key = 13;

    if (argc > 1)
        key = atoi(argv[1]) % 26;

    while (count = getline(&buf, &len, stdin), count != EOF) {
        caesar(buf, buf, strlen(buf), key);
        fputs(buf, stdout);
    }

    return (EXIT_SUCCESS);
}


texts:
I'm scraping some comments from Reddit using Reddit JSON API and R. Since the data does not have a flat structure, extracting it is a little tricky, but I've found a way.

To give you a flavour of what I'm having to do, here is a brief example:

x = "http://www.reddit.com/r/funny/comments/2eerfs/fifa_glitch_cosplay/.json" # example url
rawdat   = readLines(x,warn=F) # reading in the data
rawdat   = fromJSON(rawdat) # formatting
dat_list = repl = rawdat[[2]][[2]][[2]] # this will be used later
sq       = seq(dat_list)[-1]-1 # number of comments
txt      = unlist(lapply(sq,function(x)dat_list[[x]][[2]][[14]])) # comments (not replies)

# loop time:

for(a in sq){
  repl  = tryCatch(repl[[a]][[2]][[5]][[2]][[2]],error=function(e) NULL) # getting replies all replies to comment a

  if(length(repl)>0){ # in case there are no replies
    sq  = seq(repl)[-1]-1 # number of replies
    txt    = c(txt,unlist(lapply(sq,function(x)repl[[x]][[2]][[14]]))) # this is what I want

    # next level down
    for(b in sq){
      repl  = tryCatch(repl[[b]][[2]][[5]][[2]][[2]],error=function(e) NULL) # getting all replies to reply b of comment a

      if(length(repl)>0){
        sq  = seq(repl)[-1]-1
        txt    = c(txt,unlist(lapply(sq,function(x)repl[[x]][[2]][[14]])))
      }
    }
  }
}

The above example gets all comments, the first level of replies to each of these comments and the second level of replies (i.e. replies to each of the replies), but this could go down much deeper, so I'm trying to figure out an efficient way of handling this. To achieve this manually, what I'm having to do is this:

Copy the following code from the last loop:

for(b in sq){
  repl  = tryCatch(repl[[b]][[2]][[5]][[2]][[2]],error=function(e) NULL)

  if(length(repl)>0){
    sq  = seq(repl)[-1]-1
    txt = c(txt,unlist(lapply(sq,function(x)repl[[x]][[2]][[14]])))
  }
}

Paste that code right after the line that starts with txt = ... and change b in the loop to c.
Repeat this procedure approximately 20 times or so, to make sure everything is captured, which as you can imagine creates a huge loop. I was hoping that there must be a way to fold this loop somehow and make it more elegant.


texts:
When using MVC 4 Razor (I am new to web development), I get concerned about my understanding of interactions between the database and the client. Much like all appilications these days, there is a lot of data that is presented to the user and in different fashions. I have looked around, and I can't find a concrete C# example, as they're mostly PHP.

Below is an example of loading data into a jQuery DataTables plugin.

Is this the correct way of formatting data to JSON  and loading it into a jQuery function?
If I wanted to update/delete/insert to the database from the client, is there a way to do that within JavaScript, or should I be doing it within C# somehow? (I have looked around and really, there isn't a ton of documentation)

Note: If it is easier to answer my question without concerning the use of jQuery DataTables, that's completely fine. I'm looking for a broader spectrum of information.

HTML

            Sequence
            ID
            Name
            Ticker #
            Salary
            Bonus
            Allocation
            Begin Date
            End Date

Home Controller - C#

    public string GetAssociateFromDb()
    {
        var dt = new DataTable();
        string connString = ConfigurationManager.ConnectionStrings["DEFCOMP"].ConnectionString;
        using (var connection = new SqlConnection())
        {
            connection.ConnectionString = connString;
            using (var cmd = new SqlCommand("SELECT * FROM FUND", connection))
            {
                connection.Open();
                var myAdapter = new SqlDataAdapter(cmd);
                myAdapter.Fill(dt);
                return JsonConvert.SerializeObject(dt);
            }
        }
      }

In the _Layout

        <link href="../../Content/jQueryDataTables1.10.css" rel="stylesheet" type="text/css" />


texts:
I've just downloaded a script and would like to use it as a contact form on my site. The problem is I'm a front-end dev with little knowledge of securing PHP code. So, could you please have a look and let me know if there are any glaring problems with security with this script that uses phpMailer to send?

As you can see, I haven't done much with the SMTP setting at the bottom, but it still seems to work ok on my server.

<?php

$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];

$site_owners_email = 'email@someemail.com'; // Replace this with your own email address
$site_owners_name = 'Name'; // replace with your name

if (strlen($name) < 2) {
    $error['name'] = "Please enter your name";
}

if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
    $error['email'] = "Please enter a valid email address";
}

if (strlen($comments) < 1) {
    $error['comments'] = "Please leave a comment.";
}

if (!$error) {

    require_once('class.phpmailer.php');
    $mail = new PHPMailer();

    $mail->From = $email;
    $mail->FromName = $name;
    $mail->Subject = "Website Contact Form";
    $mail->AddAddress($site_owners_email, $site_owners_name);
    $mail->AddAddress('email@someemail.com', 'Name');
    $mail->Body="
    Name: $name
    Email: $email
    Comments: $comments";

    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->Username = "email@someemail.com"; // SMTP username
    $mail->Password = ""; // SMTP password

    $mail->Send();

    echo "
 Congratulations, " . $name . " We've received your email. We'll be in touch as soon as we possibly can!

close

return to home page
";

} # end if no error
else {

    $response = (isset($error['name'])) ? "
" . $error['name'] . "
 \n" : null;
    $response .= (isset($error['email'])) ? "
" . $error['email'] . "
 \n" : null;
    $response .= (isset($error['comments'])) ? "
" . $error['comments'] . "
" : null;

    echo $response;
} # end if there was an error sending

?>


texts: Adding a timeout to an UDP socket server

texts:
I use a thread to read from a UDP socket. Afterwards the string gets parsed.
In another thread I send to every connected client via this socket. I would like to keep latency  and resources for running the script as low as possible.

It would be nice to add a time-out.

Every attempt to read should be cancelled if longer than e.g. 20 ms, to keep the response time for other clients low, because I believe that the current attempt to read from this socket is blocking the loop. I was reading that some people use select() is there an advantage?

def trnm_thr():                                                         # trnm_thr() sends commands to Arduino
  global udp_clients
  udp_client = None

  while pySerial is not None:
    if not pySerial.writable():
      continue

    try:
      udp_msg, udp_client = udp_sock.recvfrom(512)                      # Wait for UDP packet from ground station
      if udp_client is not None: udp_clients.add(udp_client)            # Add new client to client list
      if not udp_msg: continue                                          # If message is empty continue without parsing
    except socket.timeout:
      logging.error("Write timeout on socket")                          # Log the problem
    else:
      try:
        p = json.loads(udp_msg)                                         # parse JSON string from socket
      except (ValueError, KeyError, TypeError):
        logging.debug("JSON format error: " + udp_msg.strip() )
      else:
        # Serial device stuff ..


texts: A scala implementation of the Java trim method

texts:
I'm a Scala beginner and looking at the trim() method of the Java API.  I noticed side effects, so I attempted to implement a functional version in Scala.

Here is the Java version:

public String trim() {
int len = count;
int st = 0;
int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid getfield opcode */

while ((st < len) && (val[off + st] <= ' ')) {
    st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
    len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}

My Scala version iterates over a string, and when it encounters a space char, the tail of the string is returned. The entire string is then reversed, so it can access the trailing whitespace. This new string is iterated over until a space char is encountered and the tail of this string is returned. This new string is then reversed again to maintain the original string order:

def trim(stringToTrim : String) : String = {
    def removePreString[String](list : List[String]) : java.lang.String = list match {

        case head :: tail => {
            if(head.toString.equals(" ")){
                removePreString(tail)
            }
            else {
                head.toString + tail.mkString
            }
        }
    }//end removePreString

    val preString =    removePreString(stringToTrim.toList)
    val reveresedString = preString.toList.reverse
    val reveresedPostString = removePreString(reveresedString)
  reveresedPostString.reverse

}//end trim

How can this code be improved?  Does it seem wasteful reversing the string twice?


texts:
I recently found my first program I wrote using Logo and was wondering if it could have been improved:

to gnome
    repeat 180 [bk 1 rt 1] repeat 180 [bk 1 rt 1/4]
    rt 97 repeat 180 [bk 1 rt 1/4] pu lt 90 fd 50
    lt 90 fd 25
    rt 90 pd repeat 90 [fd 1/2 rt 1/4]
    repeat 180 [bk 1/2 lt 1/4] pu rt 60 fd 50 pd
    repeat 360 [fd 1/4 rt 1] lt 60 pu fd 25 pd
    repeat 360 [fd 1/4 rt 1] pu rt 90 fd 50 lt 90 fd 12 rt 180
    pd pu bk 20 pd lt 10 repeat 240 [fd 1/2 rt 1/2] pu
    fd 50 rt 90 fd 90 rt 180 pd pu lt 30 fd 110 lt 45 fd 10 setfillcolour [0 204 0]
    fill pu lt 45 fd 40 setfillcolour [243 143 133] fill
end

I think the only thing I do not remember the reason for is the repeats of pu pd but I think it was to ensure that the pen is up.


texts: Multi-tiered sorting using custom IComparer

texts:
I have this custom IComparer I use to sort a list of SurveyResponse objects, but it seems really inefficient, both in terms of runtime performance, and code elegance and maintainability. I thought of implementing IComparable for each of these components, and each CompareTo knowing its "parent" to compare, but the sort order for this report I'm making won't necessarily be the same as other sort orders, so that may not work.

It looks like the sort of problem that should be solvable using recursion, but maybe I'm just over-analyzing it?

Are there any best practices that would make this faster and more maintainable?

private class CommentComparer : IComparer<SurveyResponse>
{
  public int Compare(SurveyResponse x, SurveyResponse y)
  {
    // Sort by Application Name...
    int result = x.Question.Survey.Feature.Application.Name.CompareTo(
      y.Question.Survey.Feature.Application.Name);
    if (result != 0) { return result; }
    // ...then Feature Name...
    result = x.Question.Survey.Feature.Name.CompareTo(
      y.Question.Survey.Feature.Name);
    if (result != 0) { return result; }
    // ...then SurveyTime...
    result = x.Question.Survey.TimeTaken.CompareTo(y.Question.Survey.TimeTaken);
    if (result != 0) { return result; }
    // ...then ID...
    result = x.Question.Survey.ID.CompareTo(y.Question.Survey.ID);
    if (result != 0) { return result; }
    // ...then Position.
    return x.Question.Position.CompareTo(y.Question.Position);
  }
}


texts: Project Euler 92: count sum-squared-digits chains that reach 89

texts:
A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.
For example:
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?

My solution doesn't finish in under a minute. I'm already caching the results of arrivesAt89, including all permutations. Any help is welcomed.
#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>

int sumOfDigitsSquared(int n) {
    auto digits = std::to_string(n);
    int sum = 0;

    for (auto c : digits) {
        sum = (c - '0') * (c - '0');
    }

    return sum;
}

std::vector<int> permutations(int n) {
    auto digits = std::to_string(n);
    std::vector<int> res;
    res.push_back(n);

    do {
        res.push_back(stoi(digits));
    } while (std::next_permutation(digits.begin(), digits.end()));

    return res;
}

bool arrivesAt89(int n) {
    static auto cache = std::unordered_map<int,bool>();

    int m = n;
    while (m != 1) {
        if(cache.find(m) != cache.end()) {
            return cache.find(m)->second;
        }
        if (m == 89) {
            auto perms = permutations(m);
            for (auto p : perms) {
                cache.insert({p, true});
            }
            return true;
        }
        m = sumOfDigitsSquared(m);
    }

    auto perms = permutations(n);
    for (auto p : perms) {
        cache.insert({p, false});
    }
    return false;
}

int main() {
    int numberOf89s = 0;

    for (int i = 1; i< 10000000; i++) {
        if (arrivesAt89(i)) numberOf89s++;
    }

    std::cout << numberOf89s << std::endl;
}


texts: Implement selection from array by 'random' or 'if/elif conditionals'

texts:
I'm working on some code examples in 'Automate the boring stuff in python...' to prepare for my first year of CS. I want to know if its better to use an array with random selection below or rather multiple if/elif conditionals to generate output. Any and all suggestions are welcome.

import sys
import random
import time

answer = ['It is certain', 'It is so', 'Try later', 'Ask Again', 'Not good', 'Doubtful']
r = random.randint(0,5)

def getAnswer():
    print (answer[r])

def Main():
    try = input('Try your luck. Yes or no.\n')
    if try == 'yes':
        getAnswer()
        sys.exit()
    else:
        print('May luck be on your side.')
        sys.exit()

if __name__ == '__main__':
    Main()


texts:
I have written multi producer single consumer code with bounded buffer. Please review the code for any improvements or mistakes.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>
#define SIZE 50
#define PRODUCERS 5
#define TOTAL 2
#define ENTER printf("\n-- %s -- %d --", __func__, __LINE__);

char (*buf_write)[20], (*buf_read)[20];
char act_buf[2][SIZE][20];

pthread_mutex_t  lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t     mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t      cond  = PTHREAD_COND_INITIALIZER;

pthread_barrier_t barrier;

int write_index = 0, writer_cnt = 0;
void init();

/*
 * Consumer
 */

void *consumer(void *vargp)
{

    int i = 0, index = 0;

    while (1) {

        pthread_mutex_lock(&mutex);
        if (writer_cnt != PRODUCERS)
            pthread_cond_wait(&cond, &mutex);
        pthread_mutex_unlock(&mutex);

        writer_cnt = 0;
        write_index = 0;
        buf_read = &act_buf[index];
        index = index + 1;
        index = index % TOTAL;

        buf_write = &act_buf[index];
        pthread_barrier_wait(&barrier);

        i = 0;
        while (i < SIZE) {
            printf("%s\t",buf_read[i]);
            i++;
            if (i%10 == 0)
                printf("\n");
        }
        printf("\n");
        memset(buf_read, 0, sizeof(act_buf) / 2);
    }
}

/*
 * Producer
 */
void *producer(void *vargp)
{
    int i = 0;
    char *str = (char *) vargp;

    while (1) {

          i = 0;
        while (i < 10) {
            pthread_mutex_lock(&lock);
            str[0] = '0' + i;
            strcpy(buf_write[write_index], str);
            ++write_index;
            pthread_mutex_unlock(&lock);
            ++i;
        }

        pthread_mutex_lock(&mutex);
            writer_cnt++;
            if (writer_cnt == PRODUCERS)
                pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);

        pthread_barrier_wait(&barrier);
    }
}

int main()
{

    int i = 0;
    pthread_t prouder_tid[PRODUCERS], consumer_tid;

    char str[5][20] = {" -producer1"," -producer2"," -producer3"," -producer4"," -producer5"};

    buf_write = &act_buf[0];

    init();

    for (i = 0; i < PRODUCERS; i++) {
        pthread_create(&prouder_tid[i], NULL, producer, &str[i]);
    }

    pthread_create(&consumer_tid, NULL, consumer, NULL);

    pthread_join(consumer_tid, NULL);

    for (i = 0; i < PRODUCERS; i++) {
        pthread_join(prouder_tid[i], NULL);
    }

    return 0;
}

void init()
{
    //pthread_mutex_init(&lock, NULL);
    //pthread_mutex_init(&writer_lock, NULL);
    int s = 0;

    s = pthread_barrier_init(&barrier, NULL, PRODUCERS + 1);

    if (s != 0) {
            printf("pthread_barrier_init failied");
        exit(-1);
    }
}


texts:
When creating objects to be added to a list in Python, we can avoid the if statement by changing our create_object function to return a list.

Is this a good idea or not? Why?

(assume create_object is called in multiple places and is always added to a list)

def _create_object(self, data):
  if data:
    return Object(data)

if _create_object(data):
  mylist.append(_create_object(data))

or

def _create_object(self, data):
  if data:
    return [Object(data)]
  return []

# Now we no longer need the if
mylist += _create_object(data)

or (late addition) should we be using exceptions:

def _create_object(self, data):
  if data:
    return Object(data)
  raise BadDataException()

try:
  mylist.append(_create_object(data))
except BadDataException:
  pass


texts: Google Sheet with a column of names merged with Google Doc

texts:
I wrote my first script for google apps, but I am just learning how this all works.  The script works fine, but I am sure there are things that are not done properly.  Any advice is appreciated.

The code creates awards from a Google Sheet where a column of names (last name, first name) is separated and text is replaced on a doc template accordingly.

function createAward() {

var myDoc ='ID';
var mySheet ='ID';
var mySourceFolder ='ID';
var myNewFolder ='ID';
var date = Utilities.formatDate(new Date(), "GMT", "MM-dd-yyyy"); // "yyyy-MM-    dd'T'HH:mm:ss'Z'"

//Data
var ss = SpreadsheetApp.openById(mySheet);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A:A");
var colNum = 1; //just 1 col
var rowNum = 2; //start at 2 because there is a header
var numRows = 1; //process data 1 row at a time

//Splitting names
for (rowNum = 2; rowNum <= lastRow; rowNum ++){
  var cell = range.getCell(rowNum,colNum).getValues()[0];
  var sCell = cell[0].split(",");
  sheet.getRange(rowNum,colNum +1,1,sCell.length).setValues([sCell]);
}

//Loop to make doc for each student
for (rowNum = 2; rowNum <= lastRow; rowNum ++){
  var dataRange = sheet.getRange(rowNum, 1, numRows, 3)
  var data = dataRange.getValues();

// Data loop --
for (i in data) {
  var row = data[i];
// columns to use for variables
  var fName = row[2];
  var lName = row[1];

// make copy of doc and save as student name.
  var docTemplate = DriveApp.getFileById(myDoc);
  var newFile = docTemplate.makeCopy(fName + lName);
  var newDoc = DocumentApp.openById(newFile.getId());
  DriveApp.getFolderById(myNewFolder).addFile(newFile);
  DriveApp.getFolderById(mySourceFolder).removeFile(newFile);

// replace text
  var doc = DocumentApp.getActiveDocument();
  var body = newDoc.getBody();
  body.replaceText('{first name}', fName);
  body.replaceText('{last name}', lName);
  body.replaceText('{date}' , date)
  }
 }
}


texts: Removing duplicates from a linked list without a buffer

texts:
I am practicing a problem in "Cracking the Coding Interview". The problem is to remove duplicates in a linked list without the use of a buffer. I interpreted this as not using a list or any large data structure such as a hash to store unique nodes.

My algorithm is inefficient I think. It iterates an anchor across the linked list. From that anchor, a second sub-iteration occurs which removes any nodes that is the same as the anchor. Thus, there are a total of two loops. I think the time complexity is either O(n^2) or O(nlogn)

Any better algorithms are welcome. Since I am a novice in Python, please give me suggestions on my coding style.

class Node(object):

    def __init__(self, data):
        self.data = data
        self.next = None

    def getData(self):
        return self.data

    def setNext(self, node):
        self.next = node

    def getNext(self):
        return self.next

class LinkedList(object):

    def __init__(self, dataList):
        assert len(dataList) > 0
        self.head = Node(dataList[0])
        iterNode = self.head

        for i in range(1, len(dataList)):
            iterNode.setNext(Node(dataList[i]))
            iterNode = iterNode.getNext()
        iterNode.setNext(None)

    def printList(self):
        iterNode = self.head

        while iterNode is not None:
            print(iterNode.getData())
            iterNode = iterNode.getNext()

    def removeDuplicates(self):
        assert self.head is not None
        anchor = self.head

        while anchor is not None:
            iterator = anchor
            while iterator is not None:
                prev = iterator
                iterator = iterator.getNext()
                if iterator is None:
                    break
                if iterator.getData() == anchor.getData():
                    next = iterator.getNext()
                    prev.setNext(next)

            anchor = anchor.getNext()

dataList = ["hello", "world", "people", "hello", "hi", "hi"]

linkedList = LinkedList(dataList)
linkedList.printList()
linkedList.removeDuplicates()
print("\n")
linkedList.printList()

Output:

hello
world
people
hello
hi
hi

hello
world
people
hi


texts:
I'm studying SVMs and wrote a demo in MATLAB (because I couldn't get a quadratic programming package to work correctly in Python). Right now it's simple and can only do linearly-separable cases (nonlinear kernels will be implemented later). This is the first MATLAB program I've written outside of a MATLAB seminar I'm taking, so any thoughts would be appreciated.

% simple SVM demo
clc;clear all;

% input data; y's are labels for data
y = [ -1; -1; -1; -1; -1; 1; 1; 1; 1; 1; 1 ];
data = [
    0 3;
    1 2;
    2 1;
    3 3;
    5 1;
    5 5;
    6 5;
    6 7;
    7 3;
    8 6;
    8 1;
];

% separate positive and negative datapoints
posDps = data(find(y == 1), :);
negDps = data(find(y == -1), :);

% space is number of dimensions (n-space)
% right now, b/c being plotted in 2D, can only be 2-space
space = size(data, 2);
% n is number of input variables
n = length(data);
[ y1, y2 ] = meshgrid(y, y);
[ i, j ] = meshgrid(1:n, 1:n);

% generate matrices for minimization
P(i, j) = y1(i, j) .* y2(i, j) .* (data(i,:) * data(j,:)');
q = -1 * ones(n, 1);

% generate matrices for inequality constraint (alpha >= 0)
% also can use LB parameter
A = -1 * eye(n);
b = zeros(n, 1);

% generate matrices for equality constraint
Aeq = y';
beq = [ 0 ];

% use quadprog package to generate alphas
alpha = quadprog(P, q, A, b, Aeq, beq, [], [], [], optimoptions('quadprog', 'Display', 'off'));
% calculate w from alpha
w = (data' .* repmat(y', [space 1])) * alpha;

% finding b parameter
% (y_n)(x_n * w + b) = 1 for support vector, so b = y_n - w * x_n
threshold = 1e-5;
svIndices = find(alpha > threshold);
b = y(svIndices(1)) - data(svIndices(1),:) * w;

% display points
figure;
hold on;
scatter(posDps(:,1), posDps(:,2));
scatter(negDps(:,1), negDps(:,2));

% draw line (only 2D for now)
margin = 1;
domain = (min(data(:,1)) - margin):(max(data(:,1)) + margin);
plot(domain, (w(1) .* domain + b)/(-w(2)));

% plotting gutters
plot(domain, (-1 + w(1) .* domain + b)/(-w(2)), 'g:');
plot(domain, (1 + w(1) .* domain + b)/(-w(2)), 'g:');

I'd like any feedback, but here are some specific questions I had in mind:

For storing one-dimensional data (arrays), is there usually a preference between column and row matrices?
Is there an easy way to deal with nested matrices? I tried to combine the labels and attribute vectors like so:

data = [
    -1 [ 0 3 ];
    -1 [ 1 2 ];
    % ...
]

and use more indices (e.g., data(1,2,2)) but that didn't work.
There are a ton of different ways to create matrices, and I'm not sure if the ones I am using are the most appropriate (e.g., via literals, find(), meshgrid(), ones() and zeros(), repmat(), etc.).
What is there to do about arbitrary imprecision? For example, I had to put in an arbitrary value threshold to find non-zero values because using find(A > 0) wasn't working. (Since the values were on the magnitude of about 1e-12, this was larger than the value of eps() so that function didn't seem very helpful.)
Naming conventions -- is there one for MATLAB? I don't believe I've seen a consistent style.


texts: Simplifying Macro-Generating Racket Macro

texts:
I'm trying to write a small macro library in Racket that extends a few of the racket/match functions I use, by printing which clause was expanded.

While this seems to be decent practice for learning macros in Racket, I still find them incredibly daunting.  At some point, I wind up just trying everything with no real sense of direction until it works how I want, and that's partially how I built my macros up to their current state, as seen here:

#lang racket

(require
  (for-syntax
   racket/string
   racket/list
   racket/syntax
   syntax/parse
   syntax/parse/experimental/template
   syntax/parse/lib/function-header))

;; From answer to my question here:
;; http://stackoverflow.com/a/38577121/1017523
(begin-for-syntax
  (define (clauses->numbers stx)
    (range (length (syntax->list stx)))))

(define-syntax (generate-debug-version stx)
  (syntax-case stx ()
    [(_ function-name)
     (with-syntax ([new-name (format-id stx "~a/debug" #'function-name)])
       #'(define-syntax (new-name stx)
           (...
            (syntax-parse stx
              [(_ id [pattern value] ...)
               (with-syntax ([(n ... )
                              (clauses->numbers #'([pattern value] ... ))])
                 (syntax/loc stx
                   (function-name
                    id
                    [pattern
                     (begin
                       (displayln (format "Matched case ~a" (add1 n)))
                       value)]
                    ...)))]))))]))

(generate-debug-version match)
(generate-debug-version match*)

The small first macro, clauses->numbers, determines which clause is expanded in racket/match functions
The main macro, generate-debug-version, is what I'm trying to simplify.

This macro currently takes one function name (for example, match or match*), and generates a macro that defines a new function with a /debug suffix that prints the expanded clause number.

Before asking this question, I was trying to add the ability to supply multiple function names to this macro using ellipses (making the last two lines (generate-debug-versions match match*)), but I can't figure out how in my macro's current state.

Can someone give me advice on how to simplify/clarify my generate-debug-version macro, so I can ultimately rewrite it to accept multiple arguments?

I'm aware of the simpler define-syntax-rule macro tool, but it didn't work in the circumstances I attempted.


texts: Extracting numbers in specific ranges from a slice

texts:
Consider a slice with some floating point numbers:
nums := []float64{0.17898, 0.25512, 1.98123, 1.35902, 0.97642}

Suppose I want to extract the numbers lying in between the range from 1 to 1.99 and ones lying in between the range from 0.0 to 0.99 (inclusive of both limits) from this slice and append it into two new separate slices each, then what would be the best possible way to do so?
I have the following code:
package main

import (
    "fmt"
)

func main() {
    nums := []float64{0.17, 0.25, 2.19, 0.98, 1.35, 5.97, 1.21}
    var oneSlice, zeroSlice []float64
    for _, num := range nums {
        if num <= 1.99 && num >= 1.0 {
            oneSlice = append(oneSlice, num)
        } else if num <= 0.99 && num >= 0.0 {
            zeroSlice = append(zeroSlice, num)
            }
    }
    fmt.Print("1.0-1.99 values:", oneSlice, "\n0.0-0.99 values:", zeroSlice)
}

1.0-1.99 values:[1.35 1.21]
0.0-0.99 values:[0.17 0.25 0.98]

Are there any better approaches than this? (such as avoiding the if & else, or a function that can be used, which I'm not aware of? - for e.g.: a function which can compare slice elements with a given value or range of values?)
I'm new to Go, so am just wondering if there could be a possibly better approach to this! Any help is appreciated :)


texts: Script to generate documents based on conditionals and CSV data

texts:
I wrote this script a while back to generate press releases. It consumes a csv of data where each row contains the data for a country and fills in values in pre-written text based on the data. In its current state, it's basically a mad libs implementation with some hard coded conditionals. I'd like to refactor it to make it a bit smarter. I had the following ideas:

create separate methods for static text paragraphs, paragraphs with conditionals and paragraphs with complex conditionals. How would I do this without constructing methods that take too many complicated arguments?
use the NLTK for parsing plurals and verb tenses.
Put this entire script into a Django app so that I don't have to do the tweaks myself every time they want new press releases.

An abbreviated version of the script is below. I also welcome any changes to make it more Pythonic.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
import sys
import csv
from docx import Document

def generate_documents():
    with open(sys.argv[1], 'rb') as csvdata:
        reader = csv.DictReader(csvdata)
        timestamp = "output/" + datetime.datetime.now().strftime('%d-%m-%Y_%H-%M-%S')
        os.makedirs(timestamp)
        os.chdir(timestamp)
        for row in reader:
            document = Document()
            name = row['country'].decode('cp1252') + ".docx"

            embargo = u"EMBARGOED FOR RELEASE UNTIL {0}, DECEMBER {1} at {2} ({3})".format(row['weekday'], row['day'], row['time'], row['capital'].decode('cp1252').upper())

            headline = "Colored Walls Gain International Popularity"

            subheadline = u" {0} walls become common in {1}, citiznes think this development is {2}".format(row['color'], row['country'].decode('cp1252'), row['adjective'])

            if row['country'].decode('cp1252') == "Andorra" or row['country'].decode('cp1252') == "Canada" or row['country'].decode('cp1252') == "Zimbabwe" or row['country'].decode('cp1252') == "Qatar" or row['country'].decode('cp1252') == "Gabon":
                cond_para_1 = u"{0} – Today, fewer people are painting walls {1} in {2}, according to a new, comprehensive analysis of trend from 188 countries.".format(row['capital'].decode('cp1252').upper(), row['color1'], row['country'].decode('cp1252'))
            else:
                cond_para_1 = u"{0} – Today, fewer people are painting walls {1} and {2} in {3}, according to a new, comprehensive analysis of trend from 188 countries. ".format(row['capital'].decode('cp1252').upper(), row['color1'], row['color2'], row['country'].decode('cp1252'))

            static = "Everyone thinks this is very exciting"

           if row['bestColor'] == "yellow":
               cond_para_2 = "Shockingly, residents of {0} prefer yellow walls.".format(row['country'].decode('cp1252'))
           else:
               cond_para_2 = "Most of the world likes white walls."

            # add the content to the document
            document.add_paragraph(embargo)
            document.add_paragraph().add_run(headline).bold = True
            document.add_paragraph().add_run(subheadline).italic = True
            document.add_paragraph(cond_para_1)
            document.add_paragraph(static)
            document.add_paragraph(cond_para_2)
            document.save(name)

generate_documents()


texts: Finding consecutive occurrences of a value in an array

texts:
Given an array, return True if the array contains consecutive values:

has22([1, 2, 2]) - True
has22([1, 2, 1, 2]) -False
has22([2, 1, 2]) - False

I do aware of a quick solution by iterating the list in a for loop and comparing current and next items for equality until it reaches the end, also using modules like itertools as pointed out by @syb0rg. However, I am asking this to learn algorithmic approach

Current Solution:

def has22(nums):
    total_occurrences = nums.count(2)

    if total_occurrences >= 2:

        forward_start = 0
        backward_start = 0
        reversed_nums = nums[::-1]
        last_item_index = len(nums) - 1

        for _ in xrange(total_occurrences/2 ):

            next_forward_occurrence = nums.index(2,forward_start)
            next_backward_occurrence=  last_item_index - reversed_nums.index(2, backward_start)

            if nums[next_forward_occurrence] == nums[next_forward_occurrence+1]:
                return True
            elif nums[next_backward_occurrence] == nums[next_backward_occurrence - 1]:
                return True

            forward_start = next_forward_occurrence
            backward_start = next_backward_occurrence

    return False

I would like to know if there is any other efficient algorithm (using only built-in methods, no modules/lib please)


texts:
I use the following functions to encrypt my $_GET variables (whenever I can't easily get away with using $_POST or some other way of passing information between pages).

function decryptStringArray ($stringArray, $key = "Your secret salt thingie")
{
    $s = unserialize(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode(strtr($stringArray, '-_,', '+/=')), MCRYPT_MODE_CBC, md5(md5($key))), "\0"));
    return $s;
}

function encryptStringArray ($stringArray, $key = "Your secret salt thingie")
{
    $s = strtr(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), serialize($stringArray), MCRYPT_MODE_CBC, md5(md5($key)))), '+/=', '-_,');
    return $s;
}

function prepareUrl($url, $key = "Your secret salt thingie")
{
    $url = explode("?",$url,2);
    if(sizeof($url) <= 1)
        return $url;
    else
        return $url[0]."?params=".encryptStringArray($url[1],$key);
}

function setGET($params,$key = "Your secret salt thingie")
{
    $params = decryptStringArray($params,$key);
    $param_pairs = explode('&',$params);
    foreach($param_pairs as $pair)
    {
        $split_pair = explode('=',$pair);
        $_GET[$split_pair[0]] = $split_pair[1];
    }
}

Obviously I replace the "Your secret salt thingie" with other strings. Here is how I use it:

On the page where I need a URL:

$url = prepareUrl("http://someurl.com?variable1=1314&variable2=1851&variable3=stringstuff", "algjalgjalgjal");

Then I put the new $url in a href or a tag or something (I use $smarty templates but that isn't relevant).

On the page someurl.com where I need to decrypt the params I just use:

setGET($_GET['params'],"algjalgjalgjal");

This all works fine for me.  Is there anything inherently terrible about this way of doing things?  I'm asking this because I posted this as an answer on Stack Overflow to a question someone asked about hiding their $_GET parameters and it was immediately down-voted. That made me curious about whether it was somehow bad code or insecure in some way.


texts: Using jQuery to set the class of an element corresponding to the selected radio button

texts:
I'm a bit of a newb with jQuery but can get it working to perform the functionality that I'm after.

The below function checks the value of the radio input and then adds a class, depending on the selection. But it feels like there is a more efficient way of writing this.

$('input[name=choice]').change(function(){
 var inputVal = $('input[name=choice]:checked').val();

 if(inputVal == 'Option A') {
  $(".img-wrapper").addClass('option-a');
 } else {
  $(".img-wrapper").removeClass('option-a');
 }

 if(inputVal == 'Option B') {
  $(".img-wrapper").addClass('option-b');
  $(".img-wrapper").removeClass('option-a');
 } else {
  $(".img-wrapper").removeClass('option-b');
 }

 if(inputVal == 'Option C') {
  $(".img-wrapper").addClass('option-c');
  $(".img-wrapper").removeClass('option-a');
 } else {
  $(".img-wrapper").removeClass('option-c');
 }

 if(inputVal == 'Option D') {
  $(".img-wrapper").addClass('option-d');
  $(".img-wrapper").removeClass('option-a');
 } else {
  $(".img-wrapper").removeClass('option-d');
 }
});

   <input type="radio" name="choice" value="Option A">
   <input type="radio" name="choice" value="Option B">
   <input type="radio" name="choice" value="Option C">
   <input type="radio" name="choice" value="Option D">

https://jsfiddle.net/fhaLztL6/


texts: Creating a simple 52-card data structure for Blackjack in Python

texts:
I am fairly new to Python so I am trying to learn more about its conventions and ways to make my codes more efficient.
I am making a Blackjack game and so far have this class that draws, organizes, and scores a hand of cards.

class Hand (object):
    def __init__(self, card=[], card2=[], score=0):
        self.card = card
        self.card2 = card2
        self.score = score
    def roll(self):
        # picks two cards and stores in card and card2 respectively as [0rank, 1suit]
        ranks = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
        suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
        pick = []
        pick2 = []
        pick.append(ranks[randint(0, 12)])
        pick.append(suits[randint(0, 3)])
        pick2.append(ranks[randint(0, 12)])
        pick2.append(suits[randint(0, 3)])
        self.card = pick
        self.card2 = pick2
    def playerScore(self):
        # scores player's hand, prompting ace choice
        value = self.card[0]
        value = str(value)
        points = 0
        if value.isdigit():
            points += int(value)
        elif value != "Ace":
            points += 10
        else:
            aceChoice = input("Play ace as 11 or 1? ")
            while not aceChoice.isdigit():
                try:
                    aceChoice = input("Play ace as 11 or 1? ")
                except TypeError:
                    print("Invalid response.")
            if aceChoice == "11":
                points += 11
            else:
                points += 1
        self.score += points
    def dealerScore(self):
        # scores dealer's hand and automates ace choice
        value = self.card[0]
        value = str(value)
        points = 0
        if value.isdigit():
            points += int(value)
        elif value != "Ace":
            points += 10
        elif value == "Ace" and self.score >= 11:
            points += 1
        elif value == "Ace" and self.score < 11:
            points += 11
        self.score += points

I was wondering if I am using classes correctly, and if I should put the card list to draw from or .pop() in the class initializer, As well as the best type of data structure to store the unused cards in.
Ignore the fact that I called one method roll(). I just finished a Yahtzee game haha.


texts:
There are three scenarios only for when the sign up validations fail, so is there a better way of representing them rather than having 4 scenarios? I don't want to create a model folder so please don't suggest that.

Is there a better way of representing this RSpec code on Rails using Capybara?

feature 'Login' do
  before do
    FactoryGirl.create(:user)
  end

  scenario "success login", js: true do
    # set_speed(:slow)
    visit root_path
    click_link 'Login'

    fill_in 'email', :with => 'test@example.com'
    fill_in 'password', :with => 'password'
    click_button 'Login'

    expect(page).to have_content('Logged in successfully')
  end

  scenario "failed login", js: true do
    # set_speed(:slow)
    visit root_path
    click_link 'Login'

    fill_in 'email', :with => 'failed@login.com'
    fill_in 'password', :with => 'something failed'
    click_button 'Login'

    expect(page).to have_content('Invalid login/password combination')
  end
end

feature "Sign Up" do
  scenario "success sign up", js:true do
    visit root_path
    click_link 'Login'
    click_link 'Sign Up'

    fill_in 'user[email]', :with=>'signup@example.com'
    fill_in 'user[password]', :with=> 'password'
    fill_in 'user[password_confirmation]', :with=> 'password'
    click_button 'Create User'
    expect(page).to have_content('User successfully added.')
  end

  scenario "failed sign up/Wrong email format", js:true do
    visit root_path
    click_link 'Login'
    click_link 'Sign Up'
    fill_in 'user[email]', :with=>'signup.example.com'
    fill_in 'user[password]', :with=> 'password'
    fill_in 'user[password_confirmation]', :with=> 'password'
    click_button 'Create User'
    expect(page).to have_content('is invalid')
  end

  scenario "failed sign up/Short Email address", js:true  do
    visit root_path
    click_link 'Login'
    click_link 'Sign Up'
    fill_in 'user[email]', :with=>'sign'
    fill_in 'user[password]', :with=> 'password'
    fill_in 'user[password_confirmation]', :with=> 'password'
    click_button 'Create User'
    expect(page).to have_content('is too short (minimum is 5 characters)')
  end

  scenario "failed sign up/Long Email address", js:true  do
    visit root_path
    click_link 'Login'
    click_link 'Sign Up'
    fill_in 'user[email]', :with=>'fillinginwritingwronglongpasswordstogetanerror@gmail.com'
    fill_in 'user[password]', :with=> 'password'
    fill_in 'user[password_confirmation]', :with=> 'password'
    click_button 'Create User'
    expect(page).to have_content('is too long (maximum is 50 characters)')
  end

end


texts: Changing look and feel for all current frames

texts:
I am using JGoodies Looks to change the look and feel of the application I'm currently working on.

I've just created a JMenu with some different themes options for the user to choose.

The thing is, I want to make sure the changes affect the program instantly, on all current windows, so I did this:

@Override
public void doActionPerformed(ActionEvent event) {
    PlasticLookAndFeel lookAndFeel = new PlasticXPLookAndFeel();
    lookAndFeel.setPlasticTheme(new SkyBlue());
    try {
        UIManager.setLookAndFeel(lookAndFeel);
        for(Frame f: Frame.getFrames()) {
            SwingUtilities.updateComponentTreeUI(f);
        }
    } catch (UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }
}

It works perfectly, like magic. But I don't know if it is a good practice or not, or if there is a better or easier (if possible) way.

I didn't even know that Frame had that method. I've just tried (thanks to IntelliJ magic code completion) and it worked so easy on the first try. So maybe that's why I'm concerned about it.

Also, what is the difference between the code above and this one (as they appear to work the exact same way):

for(Window window : JFrame.getWindows()) {
    SwingUtilities.updateComponentTreeUI(window);
}

I mean, when and why should I be using Frame over JFrame, Frame over Window, or vice versa?


texts:
Here is the database query needed to create the database:

create table Area
(
AreaId int primary key identity(1,1),
Name nvarchar(64) not null
)

create table Level
(
LevelId int primary key identity(1,1),
Name nvarchar(32) not null,
Principle nvarchar(512) not null
)

create table Subject
(
SubjectId int primary key identity(1,1),
AreaId int foreign key references Area(AreaId),
LevelId int foreign key references Level(LevelId),
Name nvarchar(32) not null,
Abbreviation nvarchar(16)
)

create table StaffType
(
StaffTypeId int primary key identity(1,1),
Name nvarchar(64) not null
)

create table Staff
(
StaffId int primary key identity(1,1),
StaffTypeId int foreign key references StaffType(StaffTypeId),
Name nvarchar(128) not null,
LastNameFather nvarchar(256) not null,
LastNameMother nvarchar(256) not null,
DateOfBirth datetime,
PlaceOfBirth nvarchar(256),
Sex nvarchar(8) not null,
Carnet nvarchar(64),
Telephone nvarchar(64),
MobilePhone nvarchar(64),
Address nvarchar(256),
FatherName nvarchar(256),
MotherName nvarchar(256),
FatherContactNumber nvarchar(64),
MotherContactNumber nvarchar(64),
FatherPlaceOfWork nvarchar(64),
MotherPlaceOfWork nvarchar(64),
DateOfHiring datetime,
YearsOfService int,
Formation nvarchar(128)
)

create table Grade
(
GradeId int primary key identity(1,1),
Name nvarchar(32) not null,
LevelId int foreign key references Level(LevelId),
Observation nvarchar(256)
)

create table GradeInstance
(
GradeInstanceId int primary key identity(1,1),
StaffId int foreign key references Staff(StaffId),
GradeId int foreign key references Grade(GradeId),
Name nvarchar(32) not null,
Year datetime
)

create table Student
(
StudentId int primary key identity(1,1),
RUDE int,
Name nvarchar(64) not null,
LastNameFather nvarchar(256) not null,
LastNameMother nvarchar(256) not null,
DateOfBirth datetime not null,
PlaceOfBirth nvarchar(128),
Sex nvarchar(8),
Carnet nvarchar(32),
Telephone nvarchar(64),
MobilePhone nvarchar(64),
Address nvarchar(256),
FatherName nvarchar(512),
MotherName nvarchar(512),
FatherMobilePhone nvarchar(64),
MotherMobilePhone nvarchar(64),
FatherProfession nvarchar(64),
MotherProfession nvarchar(64),
FatherPlaceOfWork nvarchar(256),
MotherPlaceOfWork nvarchar(256),
Observations nvarchar(3000)
)

create table StudentInstance
(
StudentInstanceId int primary key identity(1,1),
GradeInstanceId int foreign key references GradeInstance(GradeInstanceId),
StudentId int foreign key references Student(StudentId)
)

create table StudentGradeReport
(
StudentGradeReportId int primary key identity(1,1),
StudentInstanceId int foreign key references StudentInstance(StudentInstanceId),
SubjectId int foreign key references Subject(SubjectId),
FirstTrimester int,
SecondTrimester int,
ThirdTrimester int,
FinalGrade int
)

If you find an attribute that should be null checked, please disregard it. I've gone over this with the client and they want certain things to left blank if so chosen by the end user.

My main concern when designing this database was how to associate a student with a grade here and now, yet keep a record for previous years and manage to see what grade he got back in 2009. See?

I think I've done a good job but you never know - the hivemind here will probably find a flaw and I'd love some feedback.


texts: Project Euler 91 (via HackerRank): Right triangles with integer coordinates

texts:
This is my code to solve HackerRank's version of Project Euler Problem 91: on an N × N grid, find the number of possible right triangles where one vertex is (0, 0) and the other two vertices are integer grid points.

I know its an open challenge, but it is not for any job related coding, and I have also partially solved the problem and just need more optimized code.

#checks if the input 2 points, along with 3rd point as Origin, forms a right angle triangle
def righttri(a,b):
    temp=[]
    temp.append(((a[0]**2)+(a[1]**2))**(1/2))
    temp.append(((b[0]**2)+(b[1]**2))**(1/2))
    temp.append((((a[0]-b[0])**2)+((a[1]-b[1])**2))**(1/2))
    temp=sorted(temp)
    if temp.count(0)>0:
        return False
    elif round((temp[0]**2 )+ (temp[1]**2)) == round(temp[2]**2):
        done.append(sorted([a,b]))
        return True
    else:
        return False

n=int(input())+1
count=0
#coor stores all the 1-increment possible combination of points.
#ex:- for n=2, coor stores [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
#
#done stores the 2points data for all those val which forms right angle with origin
coor,done=[],[]
a,b=0,0
while a<n:
    while b<n:
        coor.append([a,b])
        b+=1
    b=0
    a+=1
for x in coor:
    for y in coor:
        if sorted([x,y]) not in done:
            if righttri(x,y)==True:
                count+=1

print(count)

Now, this code is tested on 9 different test cases, out of which 3 are showing OK. The rest 6 timeout. It means either my algorithm is faulty or I can just implement this algorithm efficiently. I would like to know how this code can be made fast.


texts: Determine whether a word appears in a sentence

texts:
Given an array of words representing a sentence and a word to search for, the method must determine whether the word appears in the sentence.

Specifications

Case insensitive.
The arguments are never null.
The sentence is in the English language.

/**
 * A case-insensitive search on a sentence to find whether a given word can be found in it. It
 * keeps certain punctuation in mind.
 *
 * @param  aSentence An array of words forming a sentence. Cannot be {@code null}.
 * @param  aWord     The word to search for. Cannot be {@code null}.
 *
 * @return {@code true} if the word appeared at least once in the sentence, {@code false}
 *         otherwise.
 */
public boolean sentenceContainsWord(final String[] aSentence, String aWord)
{
  // The search is case-insensitive
  aWord = aWord.toLowerCase();

  // Loop through the words in the sentence
  for (int i = 0; i < aSentence.length; i++)
  {
    String sentenceWord = aSentence[i];

    // If the word in the sentence matches, return immediately
    if (sentenceWord.toLowerCase().equals(aWord))
    {
      return true;
    }

    // The word could end with punctuation like a comma or a dot
    int lastSentenceWordIndex = sentenceWord.length() - 1;
    String lastCharacter = Character.toString(sentenceWord.charAt(lastSentenceWordIndex));
    if (lastCharacter.matches("[.,:;]") && sentenceWord.substring(0, lastSentenceWordIndex).equals(aWord))
    {
      return true;
    }
  }

  return false;
}


texts:
My needs are to manage DTO in a php5.3 application. I've written few lines of code in TDD with phpunit 6. The scenario I want to implement is a request with following fields:

name
surname
password
alias
email
address
civic_number
country

And I need to create DTO's with

credentials
info
address

Provide DTO properties

Each DTO should provide its own properties.

public function testProvideDtoPropertyNames()
{
    $propertyNames = Person::getPropertyNames();

    $expectedProperties = array(
        'name',
        'surname',
    );

    $this->assertEquals(
        $expectedProperties,
        $propertyNames
    );
}

Getters

I also want that all properties are available via getters:

public function testProvidePropertyViaGeneralGetter()
{
    $dto = Person::createFromArray(array(
        'name' => 'Simone',
    ));

    $this->assertEquals(
        'Simone',
        $dto->get('name')
    );
}

Filtering

The main purpose here is to filter all fields and just keep consideration of the DTO's properties:

public function testDTOAcceptOnlyItsOwnProperties()
{
    $dto = Person::createFromArray(array(
        'name' => 'Simone',
        'sfadfsa' => 'Simone',
    ));

    $expectedProperties = array(
        'name' => 'Simone',
        'surname' => null,
    );

    $this->assertEquals(
        $expectedProperties,
        $dto->asArray()
    );
}

Serialization

Serializing and un serializing I want that my code works fine and without side effect.

public function testSerializationKeepSameProperties()
{
    $dto = Person::createFromArray(array(
        'name' => 'Simone',
        'surname' => 'Gentili',
        'sadfasdrname' => 'Gentili',
    ));

    $serialized = serialize($dto);
    $unserialized = unserialize($serialized);

    $this->assertEquals(
        $dto->asArray(),
        $unserialized->asArray()
    );

    $this->assertEquals(
        array(
            'name' => 'Simone',
            'surname' => 'Gentili',
        ),
        $unserialized->asArray()
    );
}

Are those tests good? I hope yes but any suggestions are welcome.

Finally, ... the code:

A DTO can be easily done with a simple class with public properties:

class Person extends Dto
{
    public $name;
    public $surname;
}

Here the production code:

abstract class Dto
{
    private $properties;

    private function __construct(array $properties)
    {
        $this->properties = $properties;
    }

    public static function createFromArray($properties)
    {
        return new static($properties);
    }

    public function set($propertyName, $propertyValue)
    {
        $this->$propertyName = $propertyValue;
    }

    public function get($propertyName)
    {
        return isset($this->properties[$propertyName])
            ? $this->properties[$propertyName]
            : null;
    }

    public static function getPropertyNames()
    {
        $reflected = new ReflectionClass(new static(array()));

        $properties = $reflected->getProperties(
            ReflectionProperty::IS_PUBLIC
        );

        return array_map(function ($item) {
            return $item->getName();
        }, $properties);
    }

    public function asArray()
    {
        $properties = array();

        foreach (static::getPropertyNames() as $itemValue) {
            $properties[$itemValue] = $this->get($itemValue);
        }

        return $properties;
    }

    public function __sleep()
    {
        foreach (self::getPropertyNames() as $propertyName) {
            $this->set(
                $propertyName,
                $this->get($propertyName)
            );
        }

        return self::getPropertyNames();
    }

    public function __wakeup()
    {
        foreach (self::getPropertyNames() as $propertyName) {
            $this->properties[$propertyName] = $this->$propertyName;
            $this->$propertyName = null;
        }

        return self::getPropertyNames();
    }
}


texts: Utilizing idle socket server to do meaningful thing (timeout after sleep on epoll_wait)

texts:
I write an app server that uses TCP socket on Linux. When there is no traffic (no data is sent by client, no client connect() or close()), the process sleeps on epoll_wait() while waiting for events hit the socket file descriptors.
What is a good thing to do while the process is sleeping?
So my initiative is to make the sleep time short and force the process to read from memory again and again until the events come.
Reason for doing this is that to keep critical (for performance) data hot in the cache.

Is that a worthwhile thing to do?
Or better I let the process sleeping until events come?

My understanding
While the process is sleeping on epoll_wait() for too long, the kernel will schedule to run other processes.
If my app is scheduled away for too long, then its data on memory will be evicted from the cache, as cache is shared across multiple processes, then other processes' data will take place in the cache.
epoll_wait documentation

https://man7.org/linux/man-pages/man2/epoll_wait.2.html
Can also be read from man 2 epoll_wait.

Relevant Part of Code (event_loop and exec_epoll_wait)
struct srv_tcp_state {
    int                 epoll_fd;
    int                 tcp_fd;
    int                 tun_fd;

    bool                stop;
    struct_pad(0, 3);

    struct cl_slot_stk  client_stack;
    struct srv_cfg      *cfg;
    struct client_slot  *clients;
    uint16_t            *epoll_map;

    /*
     * We only support maximum of CIDR /16 number of clients.
     * So this will be `uint16_t [256][256]`
     */
    uint16_t            (*ip_map)[256];

    /* Counters */
    uint32_t            read_tun_c;
    uint32_t            write_tun_c;

    struct bc_arr       bc_arr_ct;
    utsrv_pkt_t         send_buf;
    struct iface_cfg    siff;
    bool                need_iface_down;
    bool                aff_ok;
    struct_pad(1, 4);
    cpu_set_t           aff;
};

static int exec_epoll_wait(int epoll_fd, struct epoll_event *events,
                           int maxevents, struct srv_tcp_state *state)
{
    int err;
    int retval;
    int timeout = 50; /* in milliseconds */

    retval = epoll_wait(epoll_fd, events, maxevents, timeout);
    if (unlikely(retval == 0)) {
        /*
         * epoll_wait() reaches timeout
         *
         * TODO: Do something meaningful here.
         */

        /*
         * Force the process to read critical data so
         * it is always hot (at least in L2 or L3?)
         */
        memcmp_explicit(state, state, sizeof(*state));
        return 0;
    }

    if (unlikely(retval < 0)) {
        err = errno;
        if (err == EINTR) {
            retval = 0;
            prl_notice(0, "Interrupted!");
            return 0;
        }

        pr_err("epoll_wait(): " PRERF, PREAR(err));
        return -err;
    }

    return retval;
}

static int event_loop(struct srv_tcp_state *state)
{
    int retval = 0;
    int maxevents = 64;
    int epoll_fd = state->epoll_fd;
    struct epoll_event events[64];

    /* Shut the valgrind up! */
    memset(events, 0, sizeof(events));

    while (likely(!state->stop)) {
        retval = exec_epoll_wait(epoll_fd, events, maxevents, state);

        if (unlikely(retval == 0))
            continue;

        if (unlikely(retval < 0))
            goto out;

        retval = handle_events(state, events, retval);
        if (unlikely(retval < 0))
            goto out;
    }

out:
    return retval;
}

memcmp_explicit
This code is located in different file, this prevents compiler to inline or optimize or remove the memcmp call (which happens when epoll_wait reaches its timeout).
int memcmp_explicit(const void *s1, const void *s2, size_t n)
{
    return memcmp(s1, s2, n);
}

likely and unlikely macros
#define likely(EXPR)   __builtin_expect(!!(EXPR), 1)
#define unlikely(EXPR) __builtin_expect(!!(EXPR), 0)

About __builtin_expect

https://stackoverflow.com/questions/7346929/what-is-the-advantage-of-gccs-builtin-expect-in-if-else-statements


texts:
I would like to convert the following procedure to use Linq, but I'm not sure how to accomplish it, ForEach or Sum?

    public int GetBalance()
    {
        int balance = 0;

        foreach (IDenomination denomination in Account)
        {
            balance += denomination.Currency * denomination.BillCount;
        }

        return balance;
    }

Account is a property in the class:

public List<IDenomination> Account { get; set; }


texts: Check if list contains 3 elements with predefined sum

texts:
I have 2 solutions about puzzle I mentioned in title:

solution 1( O(n^3) ):

public static boolean sumOfThree_1(List<Integer> list, int sum) {
        for (int i = 0; i < list.size() - 2; i++) {
            for (int k = i + 1; k < list.size() - 1; k++) {
                for (int m = k + 1; m < list.size(); m++)
                    if ((list.get(i) + list.get(k) + list.get(m)) == sum) {
                        return true;
                    }
            }
        }
        return false;
    }

solution 2( O(n^2) ):

public static boolean sumOfThree_2(List<Integer> list, int sum) {
        for (int i = 0; i < list.size() - 2; i++) {
            int expectedSumOfTwo = sum - list.get(i);
            if (sumOfTwo_2(list.subList(i+1, list.size()), expectedSumOfTwo)) {
                return true;
            }
        }
        return false;
    }

public static boolean sumOfTwo_2(List<Integer> list, int sum) {
    Set<Integer> set = new HashSet<>();
    for (int element : list) {
        if (set.contains(sum - element)) {
            return true;
        }
        set.add(element);
    }
    return false;
}

Any suggestions about solutions?

Better solutions?


texts: Adding vector functionality to TI Calculators

texts:
Although TI-83/84 calculators support multiple data types, such as real numbers, complex numbers, 1D and 2D lists, fuctions, etc., there is no data type for vectors. This program is my attempt to take the sequence three sequence functions (u v w), which are rarely used for their intended function, and transform them into two-dimensional vectors that can be expressed in terms of I and J.

In addition to adding vectors in terms of I and J, which can be operated on by most functions (including + - * / ^ and many more), functions have been added to determine (1) the angle between vectors, (2) the dot product of two vectors, and (3) the magnitude of a vector. The use of angle( has been altered to return the angle between to vectors, e.g. by angle(u,v. Also, * is now dot product (so uv is still implicit multiplication, but u*v is dot product). Finally, to get the magnitude of a vector, instead of absolute value notation ||u||, which only works with MathPrint, you should use brackets, for example, [u].

prgmVECTORS

ClrHome
1->I
While 1
 {e->K
 Input "",Str3
 "I"+Str3"I·Ans·K
 prgmQ
 Ans->Str3
 "?->Str4
 If 2<length(Str3
  sub(Str3,2,2->Str4
 Str3+"·J·i
 prgmQ
 If inString("u=v=w=",Str4
  "I"+sub(Ans,4,length(Ans)-3
 If Str4="u=
  Ans->u
 If Str4="v=
  Ans->v
 If Str4="w=
  Ans->w
 Ans+"·angle(·cos¹(cos(abs(ΔList(angle({
 prgmR
 If "I["=sub(Ans,1,2) and "]I"=sub(Ans,length(Ans)-1,2
 Then
  expr(sub(Ans,3,length(Ans)-4
  real(sqrt(Ansconj(Ans
  prgmS
 End
 If inString(Ans,"*
 Then
  Ans+"·*·,
  prgmR
  expr("{"+Ans
  prod(real(Ans))+prod(imag(Ans
  prgmS
 End
 expr(Ans->K
 If e≠LK(1
  Ans(1->K
 imag(Ans
 If Ans
 Then
  prgmS
  Ans->Str4
  real(K
  prgmS
  Ans+"I+"+Str4+"J
  If "0I"=sub(Ans,1,2
   sub(Ans,4,length(Ans)-3
  Ans+"·+~·-
  prgmR
  Disp sub("               ",1,16-length(Ans))+Ans
 Else
  Disp K
 End
End

-> represents the arrow (0x04), · represents 0x81,  ~ represents negation (0xB0), and L represents the list token (0xEB).

Also, prgmVECTORS calls on three subprograms. prgmS converts a real number to a string, prgmR replaces the first instance of one string with another, and prgmQ replace all instances of one string with another. They are shown below:

prgmQ

Ans→Str9
inString(Ans,"~
sub(Str9,Ans,length(Str9)-Ans+1→Str8
Str9
prgmR
Repeat Str9=Ans+Str8
Ans+Str8→Str9
prgmR
End

prgmR

Ans→Str0
inString(Ans,"~→Z
inString(Str0,"~",Ans+1→Y
inString(sub(Str0,1,Z-1),sub(Str0,Z+1,Ans-Z-1→X
sub(Str0,1,-1+inString(Str0,"~
If X
sub(Str0,1,X-1)+sub(Str0,Y+1,length(Str0)-Y)+sub(Str0,X+length(sub(Str0,Z+1,Y-Z-1)),Z-X-length(sub(Str0,Z+1,Y-Z-1

prgmS

{0,Ans->L2
{0,1->L1
LinReg(ax+b) r6
Equ>String(r6,Str1
sub(Str1,1,length(Str1)-3


texts: Using reflection to connect to an arbitrary backend

texts:
A little background first - I'm working on a server application that requires the ability to use multiple data access class libraries based on the resources available on the server it is installed on (MySQL, SQL Server, XML, etc.).  The are currently implemented as modular plugins, where the executable is paired with the appropriate class library on the server and interacts with it through a defined interface (IDataAccess).

The following code is the constructor for a singleton class on the server that exposes the backend:

private IDataAccess mDB;

private MudData()
{
    List<String> files = new List<String>(Directory.GetFiles(".", "*.dll"));
    List<Type> accessors = new List<Type>();

    foreach (String file in files)
    {
        try
        {
            Assembly test = Assembly.UnsafeLoadFrom(file);
            System.Type[] types = test.GetTypes();

            //See if any of the located types implement IDataAccess.
            foreach (System.Type candidate in types)
            {
                if (candidate.GetInterface("IDataAccess") != null)
                {
                    accessors.Add(candidate);
                }
            }
        }
        catch
        {
            //Eat this on purpose - still need to check the rest of the matches.
        }
    }

    if (accessors.Count == 0)
    {
        throw new ApplicationException("No supported data access .dll was found.");
    }

    //TODO: Select from multiples if found, but for now just take the first match.
    PropertyInfo target = accessors.First().GetProperty("Instance");
    MethodInfo getter = target.GetGetMethod();

    //Create a delegate for the reflected assembly so any exceptions propagate correctly.
    Func<IDataAccess> dataDelegate = (Func<IDataAccess>)Delegate.CreateDelegate(typeof(Func<IDataAccess>), null, getter);
    Object found = dataDelegate();
    if (found != null)
    {
        mDB = (IDataAccess)found;
    }
    else
    {
        throw new ApplicationException("Attempt to load an instance of IDataAccess failed.");
    }
}

Any exceptions at this point will be fatal, and are trapped and logged in the calling code before a (hopefully) graceful exit. This code is only called once at startup and the object it obtains isn't released until the application exits. I've been having a hard time finding information about the performance implications of using an object reference obtained this way, so I'd especially welcome comments from that direction. My assumption is that the main performance penalty is in obtaining the reference, but I haven't been able to find out whether or not that is true in practice.

I'm mainly looking for feedback on my method of connecting with the back-end, but am certainly open to comments/criticism of code style, practices, etc.

Thoughts?


texts:
I just started getting into the Less CSS framework and I am wondering if I'm doing it right and how the code can be improved if possible.

global.less

//variables
@themeRed: #cc1111;
@themeColor: @themeRed;
@marginBottom: 10px;
@contentRadius: 5px;

//mixins
.border-radius(@args) {
  -webkit-border-radius: @args;
  -moz-border-radius: @args;
  border-radius: @args;
}

//styles
body {
    font: 12px Arial;
    color: #333;
    background: #e9eaed;
}

a {
    &:link, &:visited {
        color: @themeColor;
        text-decoration: none;
    }
    &:hover {
        border-bottom: solid 1px;
    }
    &:active {
        //color: lighten(@themeColor, 10%);
    }
}

#topbar {
    background: @themeColor;
    width: 100%;
    height: 2px;
}

#container {
    width: 750px;
    margin: 0 auto;
    padding: 10px 0;
}

#header {
    display: table;
    height: 100px;
    width: 100%;
    margin-bottom: @marginBottom;
    .wrapper {
        vertical-align: middle;
        display: table-cell;
        text-align: center;
    }
}

#sitename {
    font-size: 50px;
    font-weight: bold;
    text-transform: uppercase;
    text-shadow: 2px 2px @themeColor;
    a {
        color: #fff;
        border: none;
        text-decoration: none;
    }
}

.section-heading {
    font-size: 1.1em;
    padding-left: 10px;
    margin-bottom: @marginBottom;
    text-transform: uppercase;
    font-weight: bold;
    color: @themeColor;
    border-bottom: 1px solid #e5e5e5;
    line-height: 29px;
}

p {
    line-height: 1.5em;
    margin-bottom: 1em;
}

.last {
    margin-bottom: 0;
}

#nav {
    position: absolute;
    width: 90px;
    text-align: right;
    margin-top: @contentRadius;
    li {
        border-right: 2px solid lighten(@themeColor, 30%);
        padding: 2px 5px 2px 0;
        margin-bottom: 2px;
        &:hover {
            border-color: @themeColor;
        }
        &.active {
            border-color: @themeColor;
            font-weight: bold;
        }
    }
}

.content {
    width: 518px;
    padding: 15px;
    margin: 0 auto;
    margin-bottom: @marginBottom;
    background: #fff;
    border: 1px solid;
    border-color: #e5e6e9 #dfe0e4 #d0d1d5;
    border-bottom: solid 2px @themeColor;
   .border-radius(@contentRadius);
    box-shadow: 0 1px 5px #d1d1d1;
    a {
        border-bottom: 0;
        &:hover {
            text-decoration: underline;
        }
    }
}

#advertisement {
    margin-bottom: @marginBottom;
    .adsbygoogle {
        display: block;
        margin: 0 auto;
    }
}

#footer {
    text-align: center;
    p {
        margin-bottom: 0;
    }
}


texts: How to put my functions outside a class to get organized, Design pattern

texts:
I'm using Symfony 4, I have a class named Fiche, it contains the attributes and by default the getters and setters functions of course.
Inside this Class, I have created over than 107 others functions to make calculations and then create the lines (over 40) of the pay slip of an employee and get gross salary and net salary.
The Fiche class becomes very big and it's no more organized, so how can I put each collection of functions in others classes and when I render the Fiche object inside twig I can access to those function ?
This is part of my class :
class Fiche
{

 // attributes
 // ............

 public function calculTotalSalaireBrut()

 final public function netAPayer()

 public function calculPrimesDiverses()

 public function statutSalarie()

 final public function calculTauxSalaireMensuel()

 final public function calculTauxSalHeuresSupp()

 final public function calculMontantSalHeuresSupp()

 // over than 100 others functions

}

In the controller:
/**
 * @Route("/voir/{token}", name="front_fiche_voir")
 * @Security("has_role('ROLE_ENTREPRISE')")
 */
public function show(Fiche $fiche)
{
    $this->denyAccessUnlessGranted('VIEW', $fiche);

    return $this->render('front/fiche/show.html.twig', array(
        'fiche' => $fiche,
    ));
}

a part of code inside twig template :
 {{ fiche.totalHeuresMaj }}
 {{ fiche.calculTauxSalHeuresSuppN|number_format(2, '.', '') }}
 {{ fiche.calculMontantSalHeuresSuppN|number_format(2, '.', '') }}

How can I organize my class ? How can I put each collection of functions in others classes and have the possibility to access to them via the Object, either in PHP or in twig


texts:
I'm trying to optimize performance for recursive directory listing with some exceptions:

function listdir($basedir) {
    global $root, $ignore_dirs, $ignore_files, $filetypes, $ignore_starts_with;
        if ($handle = @opendir($basedir)) {
            while (false !== ($fn = readdir($handle))) {
                if ($fn != '.' && $fn != '..') {

                    $s = true;
                    foreach ($ignore_starts_with as $pre) if (strpos($fn, $pre) === 0) $s = false;

                    $dir = $basedir."/".$fn;
                    if ($s && is_dir($dir) && !in_array($fn, $ignore_dirs)) {
                        listdir($dir);
                    } else {

                        if ($s && !in_array($fn,$ignore_files) && preg_match("/[^.\/].+\.($filetypes)$/",$dir,$fname)) printlink($fname[0]);
                    }
                }
            }
        closedir($handle);
    }
}


texts:
I want to create a datastructure for network communication (TCP),  where I can build up a byte array from small tagged pieces (like in serialized class). And of course I need a reverse behavior of this, I need a pieces from a byte array that is why a I put a constructor to the union.

typedef union message {

    struct {
        int header;
        int payload;
    } pieces;
    int whole[2];

    message (int* arr) {
        for (int i = 0; i < 2; i++) {
            whole[i] = arr[i];
        }
    }
    message ():iVal(){}
} Message ;

main() {
    int a[2] = {10, 2};
    Message msg(a);
}

This snippet is working. I'm just curious is there any other or better solution?


texts: Sequential learning function running slowly

texts:
I'm new to Python and made this Sequential Learning function but it runs slowly. Do you know why this runs slowly and how to improve it?

def Seqlearn(y, dfhessian, gamma, eps, c, itermaxsvr):
    #    =  − (α_i^* − a_i) * Rij
    d=len(dfhessian.index)
    #   d=391
    a = [[0] * d]
    a_s = [[0] * d]
    la = [[0] * d]
    la_s = [[0] * d]
    E = np.array([], dtype=np.float64).reshape(0,d)
    Etemp = [[0] * d]
    da_s = np.array([], dtype=np.float64).reshape(0,d)
    da = np.array([], dtype=np.float64).reshape(0,d)
    dat_s = [[0] * d]
    dat = [[0] * d]
    tempas = [[0] * d]
    tempa = [[0] * d]
    #   itermax=1000, c=200, eps=0.0013, gamma=0.004
    #   dfhesian is dataframe with 391 columns and 391 row
    #   y is dataframe/series with 391 row in 1 column
    for i in range(itermaxsvr):
    #   Ei= y - (a_s - a) * dfhessian[i]
        for j in range(d):
            Rijhelp=0
            for k in range(d):
                Rijhelp = Rijhelp + ((a_s[i][k] - a[i][k])*(dfhessian.iloc[j][k]))
            Etemp[0][j]= y.iloc[j] - Rijhelp
        E=np.vstack([E, Etemp])
        #   Min(Max(gamma*(E-epsilon), -(as)), (C-as))
        #   Min(Max(gamma*(-E-epsilon), -(a)), (C-a))
        for l in range(d):
            dat_s[0][l]=min(max(gamma*(E[i][l] - eps), -1*(a_s[i][l])), (c - a_s[i][l]))
            dat[0][l]=min(max(gamma*(-(E[i][l]) - eps), -1*(a[i][l])), (c - a[i][l]))
            tempas[0][l]= a_s[i][l] + dat_s[0][l]
            tempa[0][l]= a[i][l] + dat[0][l]
        da_s=np.vstack([da_s, dat_s])
        da=np.vstack([da, dat])
        a=np.vstack([a, tempa])
        a_s=np.vstack([a_s, tempas])
        la=tempa
        la_s=tempas
        #   (|da|<eps and |das|<eps ) or max iterasi
        dat_abs=max([abs(xdat) for xdat in dat[0]])
        dat_s_abs=max([abs(xdats) for xdats in dat_s[0]])
        if (dat_abs < eps) and (dat_s_abs < eps):
            break
    return la, la_s


texts: Populate dropdown B on selection in dropdown A

texts:
On selection from drop-down A (HTML select) I need to populate another "sub"-dropdown with a different list of values. For instance, on selection of country in dropdown A, dropdown B should be filled with the list of cities of selected country.

This is my first attempt of writing such a thing in jQuery. Please point out areas for improvement, like more idiomatic or shorter way of achieving this result (without losing much readability if possible).

HTML:

<select id="Parentlist">
</select>

<select id="Sublist">
</select>

JavaScript + jQuery:

function populateParentlist(choice) {
       $('#choices').find('tr').each(function() {
           trowid = $(this).attr('id');
           $("#Parentlist").append('<option>' +trowid + '</option>');
       });
}

function populateSublist(choice) {
    $('#Sublist').find('option').remove();
    $('#choices').find('tr').each(function() {
        trowid = $(this).attr('id');
        $(this).find('td').each(function() {
           tdid = $(this).attr('id');
            if(trowid != choice)
                return;
           $('#Sublist').append('<option>' + tdid + '</option>');
        });
    });
}

populateParentlist('Poland')
populateSublist('Poland')

$(function() {
    $("#Parentlist").change(function() {
        var parsel = $(this).val();
        populateSublist(parsel);
    });
});

jsfiddle


texts: Regular Expression for text that validates IPV4 or Hostname followed by a port number eg: 127.0.0.1:8080 or localhost:8080

texts:
An attempt with regular expression to do a foolproof validation of an IV4 or Hostname:port Number.

Example texts that can be validated for any of the following:

www.google.com:8080
127.0.0.1:8000
localhost:65535
codereview.stackexchange.com:9000
www.n-plus-t.com:4000
30my_domain.test-ng.com:754

((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d]) | ([\\p{Alnum}+ && [.{1}-_*[\p{Alnum}+]]]){1,253}:(6553[0-5]|655[0-2][0-9]\d|65[0-4](\d){2}|6[0-4](\d){3}|[1-5](\d){4}|[1-9](\d){0,3})

The IPv4 address validations are mainly to ensure that the tuples are between the range 0 to 255.  Also the hostname is validated against the valid names which can be alphanumeric, starting with number, subdomains separated by a single . and - and _ allowed in between, though not at end.  Port range is validated from 0 to 65535


texts: Update join table using list of checkboxes in Rails

texts:
I have Gig and Singer Active Record models (standard--no customization just yet) with a many-to-many relationship through a generic join table which holds nothing but the respective ids of Gig and Singer.  My form sends a given gig id and all the singers who will be attending, denoted with check boxes.  I need to have the ability to check or uncheck singers.  The following code works, but it does so by removing all the singers from a gig and re-adding them.  This feels hacky... is there a better way?  (I think this is all the code necessary but let me know if you need me to add anything)

class GigSingersController < ApplicationController

    def create
        gig = Gig.find(params[:gig_id])
        singer_ids = params[:singer_ids] # [1, 4, 5,]
        gig.singers = []
        singer_ids.each do |id|
            singer = Singer.find(id)
            gig.singers << singer
        end
        redirect_to gigs_path
    end
end

EDIT:

As requested in the comments, here are the schema and relevant models, although as I said, they are completely generic.  Perhaps I didn't do a good job of making my question clear:  Is the best way to create these relationships when using a checkbox to remove all existing ones and recreate them from the boxes currently checked, thereby removing any that the user unchecked on an edit?

ActiveRecord::Schema.define(version: 2019_07_19_195106) do

  create_table "gig_singers", force: :cascade do |t|
    t.integer "gig_id"
    t.integer "singer_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "gigs", force: :cascade do |t|
    t.string "name"
    t.text "notes"
    t.datetime "datetime"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "singers", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "active"
  end

class Gig < ApplicationRecord
    has_many :gig_singers
    has_many :singers, through: :gig_singers
end

class GigSinger < ApplicationRecord
    belongs_to :gig
    belongs_to :singer
end

class Singer < ApplicationRecord
    has_many :gig_singers
    has_many :gigs, through: :gig_singers

end


texts: Validating user's input before creating graph using TChart

texts:
The user enters coefficients into input boxes on a form, called GetFunction. Upon clicking an OK button on said form, the input is validated using TryStrToFloat. If all the input boxes are valid,CreateGraphis called. As soon as an invalid input box is found,CreateGraph` should not be called and the user should be able to fix their error.

procedure TfrmGetFunction.btnAddFunctionClick(Sender: TObject);
  var
    i : integer; // Loop counter.
  begin
    for i := 1 to 7 do
      begin
        CoefficientEdit[i].CoValid := CheckCoefficientBoxesValidInput(CoefficientEdit[i].CoEditBox);
        if not CoefficientEdit[i].CoValid then // If any input box is invalid.
          Exit;
      end;
    frmGraphingMode.CreateGraph; // Finally if all input boxes valid.
    frmGetFunction.Visible := false;
    frmGraphingMode.Visible := true;
  end;

Any improvements that I could make? Perhaps removing the Exit may not be a bad idea?


texts: condensing a list of lists with 'description' lines in Python

texts:
I have a long list of data pulled in from a csv file that has comments / descriptions scattered throughout the document. I'd like to collapse the descriptions into the last element of each row of data, and my current solution seems slow and overly complex. Rows with data have values in the first index and description rows are empty strings. This gives me a list of lists like so:

data = [
    ['a', 'this', 'is', 'data', 1, 2, 3, ''],
    ['', '', '', 'this is a description', '', '', '', ''],
    ['', '', '', 'that carries onto two lines', '', '', '', ''],
    ['another', 'row', 'with', 'data', 0, 3, 1, ''],
    ['', '', '', 'this is a description', '', '', '', ''],
    ['', '', '', 'that carries onto three lines', '', '', '', ''],
    ['', '', '', 'like so', '', '', '', ''],
    ['data', 'with', 'no', 'description', 9, 2, 0, ''],
    ['b', 'this', 'is', 'data', 1, 2, 3, ''],
    ['', '', '', '', 'sometimes the description', 'is offset', '', '']
]

Here's what I'd like to see:

desired_data = [
    ['a', 'this', 'is', 'data', 1, 2, 3,
     'this is a description that carries onto two lines'],
    ['another', 'row', 'with', 'data', 0, 3, 1,
     'this is a description that carries onto three lines like so'],
    ['data', 'with', 'no', 'description', 9, 2, 0, None],
    ['b', 'this', 'is', 'data', 1, 2, 3, 'sometimes the description is offset']
]

My current solution requires creating whole new lists, one with data and one with descriptions, and then iterating over the data and searching through the descriptions each iteration:

# get numbered rows with data (first element is not '')
actual_data = [(i, x) for i, x in enumerate(data) if x[0] != '']

# get numbered rows with descriptions (first element is '')
descriptions = [(i, ' '.join([j for j in x if j != '']))
                   for i, x in enumerate(data) if x[0] == '']

# get just the indices of the rows with descriptions
description_indices = {i[0] for i in descriptions}

desired_data_attempt = []
for d in actual_data:
    # get data to insert
    x = d[1][:]

    # get first index to check
    n = d[0] + 1

    description = []
    while n in description_indices:
        # keep adding consecutive descriptions
        description.append([i[1] for i in descriptions if i[0] == n][0])
        n += 1

    # set empty descriptions to None; othewise create one string from list
    if description == []:
        x[-1] = None
    else:
        x[-1] = ' '.join(description)

    # insert data with description
    desired_data_attempt.append(x)

assert desired_data_attempt == desired_data

Ideally, I'd love to be able to construct this new object in one pass through the original data. Any suggestions would be appreciated!