An attempt at a Haskell Servant API - repetition of Left/Right case matching I'm attempting to learn more about Haskell by completing a "hobby" project - a simple API to save/retrieve content for pages - used with Hakyll to generate static sites.

I have got something working for the tasks of retrieving all of the content for a site, and for adding a new page to a site. Hooray!

However, the code suffers from extraordinary verbosity.  I suspect I could improve things by bringing in some kind of monad transformer to deal with the IO (Either String ()), but I am not familiar enough with monad transformers to even be able to work out where to start.

siteServer :: Server SiteAPI
siteServer = site :<|> addPage
    where
          site :: Int -> Handler Site
          site i = do
              s <- liftIO $ loadSite i
              case s of
                  Left err -> throwError err404 { errBody = "Site not found!" `BS.append` (BS.pack err) }
                  Right s' -> return s'

          addPage :: Int -> Page -> Handler ()
          addPage i p = do
              s <- liftIO $ savePage i p
              case s of
                Left err -> throwError err404 { errBody = "Site not found!" `BS.append` (BS.pack err) }
                Right _ -> return ()

          savePage :: Int -> Page -> IO (Either String ())
          savePage i p = do
              s <- loadSite i
              case s of
                Left err -> return $ Left err
                Right s' -> savePage' s' p

              where savePage' :: Site -> Page -> IO (Either String ())
                    savePage' (Site name pages) p = saveSite (Site name (p:pages))

                    saveSite :: Site -> IO (Either String ())
                    saveSite s = catch writeSiteToFile returnError
                              where --returnError :: IOException -> IO (Either String ())
                                    returnError e = return $ Left ("Failed to write to file: " ++ show i ++ ". " ++ show (e :: IOException))
                                    --writeSiteToFile :: IOException -> IO (Either String ())
                                    writeSiteToFile = Right <$> BS.writeFile (getSiteFilename i) (encode s)

Here's how to use ExceptT to brighten the day a little. You may have hoped for a way to do handle only once after combining the Handlers with :<|>... but I also don't know how to do that. If withExceptT went to arbitrary MonadError instances, handle could have been more concise.

import Control.Monad.Trans.Except

siteServer :: Server SiteAPI
siteServer = site :<|> addPage where
  handle :: ExceptT String IO a -> Handler a
  handle = liftIO . runExceptT >=> \case
    Left err -> throwError $ err404 { errBody = "Site not found!" <> BS.pack err }
    Right x -> return x

  site :: Int -> Handler Site
  site i = handle $ ExceptT $ loadSite i

  addPage :: Int -> Page -> Handler ()
  addPage i p = handle $ do
    Site name pages <- ExceptT $ loadSite i
    withExceptT (\e -> "Failed to write to file: " ++ show i ++ ". " ++ show (e :: IOException))
      $ ExceptT $ try $ BS.writeFile (getSiteFilename i) $ encode $ Site name $ p:pages


Repeatedly eliminate a substring I'm trying to pass a programming challenge where we are to replace all instances of a substring in a string until there are none left. So an input like

 Pibabakekezza
 bake

Has output

Pizza

And if there is nothing left say so. I fail an unknown test case because I take longer than 1 second.

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.Runtime;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            GCLatencyMode oldMode = GCSettings.LatencyMode;

            // Make sure we can always go to the catch block,
            // so we can set the latency mode back to `oldMode`
            RuntimeHelpers.PrepareConstrainedRegions();

            try
            {
                GCSettings.LatencyMode = GCLatencyMode.LowLatency;
                //Your code goes here
                string s =Console.ReadLine();
                string b =Console.ReadLine();
                while(s.Contains(b))
                {
                    s=s.Replace(b, "");
                }
                if(s!="")
                {
                    Console.WriteLine(s);
                }
                else
                {
                    Console.WriteLine("FRULA");
                }
            }
            finally
            {
                // ALWAYS set the latency mode back
                GCSettings.LatencyMode = oldMode;
            }
        }
    }
}

Restrictions:

1≤|bigString|≤1 000 000

1≤|substring|≤36

bigString and the substring string consist of uppercase and lowercase letters of the English alphabet and digits 0, 1, …, 9. The characters in the substring are all different.

CPU Time limit: 1 second
Memory limit: 1024 MB

As stated by 200_success +1 string is immutable

StringBuilder also has Replace but getting it to loop is trickier
You would need to time this

string s = "Pibabakekezza";
string r = "bake";
StringBuilder sb = new StringBuilder(s);
while (sb.Length != sb.Replace(r, "").Length) { }
Debug.WriteLine(sb.ToString());

A character can only be:

start of replace
in replace
other

Not real clean code - this is more just the algorithm
I know should use { } on every if else
Store partial matches in a Stack
I tested with a very large hard input and it was 40 milliseconds

public static void QuickReplaceTest()
{
    string s = "Pibabakekezza";
    string r = "bake";
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

    s = "babakekePbakeibabbakeakebakekezbakezabake";
    r = "b";
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

    StringBuilder sb = new StringBuilder();
    sb.Append("piz");
    for (int i = 0; i < 100000; i++)
        sb.Append("qrsuvw");
    //sb.Append("piz");
    for (int i = 0; i < 100000; i++)
        sb.Append("xyz");
    sb.Append("za");
    s = sb.ToString();
    sb.Clear();
    r = "qrsuvwxyz";
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

    s = s.Insert(400000, "pie");
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

}
public static string QuickReplace2(string s, string r)
{
    if(string.IsNullOrEmpty(r))
        return string.Empty;
    if (string.IsNullOrEmpty(s))
        return string.Empty;
    s = s.Trim();
    r = r.Trim();
    if (r.Length > s.Length)
        return string.Empty;
    if (r.Length == 1)
        return(s.Replace(r, ""));

    StringBuilder sb = new StringBuilder(s.Length / 2);
    char[] rArray = r.ToCharArray();
    int rArrayLen = rArray.Length;
    Stack<byte> partialMatches = new Stack<byte>();
    byte curMatchCount = 0;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    foreach(char c in s)
    {
        //Debug.WriteLine(c);
        if (c == rArray[0])
        {
            if (curMatchCount > 0)
                partialMatches.Push(curMatchCount);
            curMatchCount = 1;
        }
        else if (c == rArray[curMatchCount])
        {
            curMatchCount++;
            if (curMatchCount == rArrayLen)
            {
                if (partialMatches.Count == 0)
                    curMatchCount = 0;
                else
                    curMatchCount = partialMatches.Pop();
            }
        }
        else
        {
            //need to unload the stack
            if (partialMatches.Count > 0)
            {
                foreach (int count in partialMatches.Reverse())
                    for (int i = 0; i < count; i++)
                        sb.Append(rArray[i]);
                partialMatches.Clear();
            }
            for (int i = 0; i < curMatchCount; i++)
                sb.Append(rArray[i]);
            curMatchCount = 0;
            sb.Append(c);
        }
    }
    if (partialMatches.Count > 0)
    {
        foreach (int count in partialMatches.Reverse())
            for (int i = 0; i < count; i++)
                sb.Append(rArray[i]);
    }
    for (int i = 0; i < curMatchCount; i++)
        sb.Append(rArray[i]);
    sw.Stop();
    Debug.WriteLine(sw.ElapsedMilliseconds.ToString());
    return sb.ToString();
}
public static string QuickReplace3(string s, string r)
{
    if (string.IsNullOrEmpty(r))
        return string.Empty;
    if (string.IsNullOrEmpty(s))
        return string.Empty;
    s = s.Trim();
    r = r.Trim();
    if (r.Length > s.Length)
        return string.Empty;
    if (r.Length == 1)
        return (s.Replace(r, ""));

    StringBuilder sb = new StringBuilder(s.Length / 2);
    char[] rArray = r.ToCharArray();
    int rArrayLen = rArray.Length;
    Stack<byte> partialMatches = new Stack<byte>();
    byte curMatchCount = 0;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    foreach (char c in s)
    {
        sb.Append(c);
        if (c == rArray[0])
        {
            if (curMatchCount > 0)
                partialMatches.Push(curMatchCount);
            curMatchCount = 1;
        }
        else if (c == rArray[curMatchCount])
        {
            curMatchCount++;
            if (curMatchCount == rArrayLen)
            {
                sb.Length -= rArrayLen;
                if (partialMatches.Count == 0)
                    curMatchCount = 0;
                else
                    curMatchCount = partialMatches.Pop();
            }
        }
        else
        {
            curMatchCount = 0;
            partialMatches.Clear();
        }
    }
    sw.Stop();
    Debug.WriteLine(sw.ElapsedMilliseconds.ToString());
    return sb.ToString();
}


Translating warning codes as messages to be printed I am writing an X application with Xlib in C, and this code is for error handling and error printing.

How to make it simpler and clearer without using a large amount of fprintf?

int XB3DS_Warn_Code (int Warn_Code)
{
  switch(Warn_Code)
  {
    case WARN_Failed_To_Connect_To_Display:
      fprintf(stdout, "[  WARNING  ]: Failed to connect to display.\n");
      break;
    case WARN_Width_Or_Height_Is_Unacceptable:
      fprintf(stdout, "[  WARNING  ]: Width or height is unacceptable.\n");
      break;
    case WARN_No_Visual_Is_Matched_For_Screen:
      fprintf(stdout, "[  WARNING  ]: No visual is matched for screen.\n");
      break;
    case WARN_The_Window_Mode_Is_Unacceptable:
      fprintf(stdout, "[  WARNING  ]: The window mode is unacceptable.\n");
      break;
    case WARN_Insufficient_Memory_To_Allocate:
      fprintf(stdout, "[  WARNING  ]: Insufficient memory to allocate.\n");
      break;
  }
  return Warn_Code;
}

Store the variable part of the message in a variable, and do the printing after the switch, for example:

int XB3DS_Warn_Code (int Warn_Code)
{
  const char * msg;
  switch(Warn_Code)
  {
    case WARN_Failed_To_Connect_To_Display:
      msg = "Failed to connect to display.";
      break;
    case WARN_Width_Or_Height_Is_Unacceptable:
      msg = "Width or height is unacceptable.";
      break;
    case WARN_No_Visual_Is_Matched_For_Screen:
      msg = "No visual is matched for screen.";
      break;
    case WARN_The_Window_Mode_Is_Unacceptable:
      msg = "The window mode is unacceptable.";
      break;
    case WARN_Insufficient_Memory_To_Allocate:
      msg = "Insufficient memory to allocate.";
      break;
    default:
      msg = "Unknown error.";
  }
  fprintf(stdout, "[  WARNING  ]: %s\n", msg);
  return Warn_Code;
}

Now the case statements only have the absolutely necessary code. It's the most basic kind of refactoring: extracting values to variables and filling them in a template later. Another variant would be extracting common logic to a helper function. I also added a default case that was missing: it's always good to have.

Also, instead of fprintf(stdout, ...) why not use simply printf(...) ?

Finally, as @black pointed out, "What's the point to return what you get passed?" Better change the method signature to return void. Even better, return the message instead of printing, so that the rest of your code can do whatever it needs with it, for example:

const char * XB3DS_Get_Warn_Message (int Warn_Code) {
    const char * msg;
    // the switch ...
    return msg;
}

void XB3DS_Handle_Warning (int Warn_Code) {
    const char * msg = XB3DS_Get_Warn_Message(Warn_Code);
    fprintf(stdout, "[  WARNING  ]: %s\n", msg);
}

Change the rest of your code to call XB3DS_Handle_Warning instead of your current XB3DS_Warn_Code. Right now you just want to print to stdout. But maybe someday you will want to log to a file, or show as part of a GUI. Then you won't need to touch XB3DS_Get_Warn_Message anymore, but change the simpler XB3DS_Handle_Warning helper.


Advent of Code 2018 Day 1 in OCaml: Find length of cycles when accumulating deltas I just started Advent of Code 2018. This is exercise 2 of day 1, and I can't understand why my code is so slow (4 minutes 37 seconds, compared to 200ms for a friend who did it in Clojure with the same computer).

Basically, it accumulates integers from a provided list of ints, named input. Whenever the current value of the accumulator is equal to one of its previous values, it is returned. We might have to loop many times over the provided list before we find such an occurrence. Here is the code:

  let main () =
    let rec my_slow_code lst history =
        if lst == [] then my_slow_code input history
        else
          let current = List.hd lst + List.hd history in
          if List.mem current history then current
          else my_slow_code (List.tl lst) (current :: history)
      in
      my_slow_code input [0]

I can't understand what mistake here makes such a slow code, maybe the use of List.mem?

I won't give it all away, since that would take away some of the fun of Advent of Code, but I'll point out:

First, yes, List.mem takes time proportional to the length of your list, which means if you're calling it over and over again it can be quite slow indeed. There might be faster structures you could use if you want to track if a previous value has been seen before, like Sets. Also, you should not be using == for equality here but rather =; I recommend learning the difference between = and ==, you will want to know it.

Second, your code is not very idiomatic OCaml; in general, if you're doing things like nesting lots of ifs and using List.hd instead of pattern matching, you may not be doing things quite right. This won't impact your performance but might impact readability and correctness. (For example, the match l with | [] -> ... pattern will warn you if a pattern match isn't exhaustive, which avoids nasty bugs.)


Upload document to mongodb Simple post and download web app in Bottle:

server.py

import sys
import bottle
from bottle import request, response
import pymongo
import gridfs
from bson.objectid import ObjectId

import mimetypes

mimetypes.init()

# Mongo Connection

connection = pymongo.MongoClient("mongodb://localhost")
db = connection.pacman
test_col = db.test
fs = gridfs.GridFS(db)

# Static Routes
@bottle.get('/<filename:re:.*\.js>')
def javascripts(filename):
    return bottle.static_file(filename, root='static/js')

@bottle.get('/<filename:re:.*\.css>')
def stylesheets(filename):
    return bottle.static_file(filename, root='static/css')

@bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
    return bottle.static_file(filename, root='static/img')

@bottle.get('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
    return bottle.static_file(filename, root='static/fonts')

@bottle.route('/')
def home_page():
    result = db.fs.files.find({"filename": {"$exists": True}})

    return bottle.template('files_test/home', files=list(result))

@bottle.route('/add')
def add_page():
    return bottle.template('files_test/add')

@bottle.route('/upload', method='POST')
def do_upload():
    data = request.files.data
    if data:
        raw = data.file.read()  # This is dangerous for big files
        file_name = data.filename
        try:
            newfile_id = fs.put(raw, filename=file_name)
        except:
            return "error inserting new file"
    print(newfile_id)
    return bottle.redirect('/')

@bottle.route('/download')
def download():
    file_id = ObjectId(bottle.request.query.id)
    if file_id:
        try:
            file_to_download = fs.get(file_id)
        except:
            return "document id not found for id:" + file_id, sys.exc_info()[0]
        file_extension = str(file_to_download.name)[(str(file_to_download.name).index('.')):]

        response.headers['Content-Type'] = (mimetypes.types_map[file_extension])
        response.headers['Content-Disposition'] = 'attachment; filename=' + file_to_download.name
        response.content_length = file_to_download.length
        # print response
        return file_to_download

bottle.debug(True)
bottle.run(host='localhost', port=8080)

add.tpl

<!DOCTYPE html>

    <title>Preformance and Capacity Management</title>
    <link rel="stylesheet" type="text/css" href="style.css">

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="data" />

    <input type="submit"/>
</form>

home.tpl

<!DOCTYPE html>

    <title>Preformance and Capacity Management</title>
    <link rel="stylesheet" type="text/css" href="style.css">

%for fileobj in files:
    Filename: {{fileobj['filename']}}

    Size: {{fileobj['length']}}

    Date Uploaded: {{fileobj['uploadDate']}}

    md5: {{fileobj['md5']}}

    &lt--Download File--&gt

%end

Global

You're hard coding the URL to your Mongo instance; it might be better to load it from a settings file. You're also not performing any authentication, though we'll assume that you have your firewalls properly set up, I guess. Some people prefer opening a new connection per request, up to you I guess. I would say that global variables suck, but if you don't think your program will expand beyond a single script, then it could be OK.

Static views

You could combine all of the static views fairly simply; have one view that captures everything matching <filename:re:.*\.(.+)> (or whatever the correct regexp would be), and then have a dictionary mapping from extensions to directories:

STATIC_DIRS = {
    "jpg": "static/images",
    "gif": "static/images",
    ... # etc
}

That said, I don't see the advantage of being able to do /foo.jpg over /static/images/foo.jpg. Also, you could always eliminate the entire set of views and just serve your static content straight from the Nginx/Apache instance that is reverse proxying your application.

Do Upload

I would strongly suggest you look into reading the file in chunks; as it is, your server would be trivial to DOS.

It might create nicer code if you reversed your if condition, so the code looked more like

@bottle.route('/upload', method='POST')
def do_upload():
    data = request.files.data
    if not data:
        return bottle.redirect("/")

    raw = data.file.read()  # This is dangerous for big files
    file_name = data.filename
    try:
        newfile_id = fs.put(raw, filename=file_name)
    except:
        return "error inserting new file"
    print(newfile_id)
    return bottle.redirect('/')

This is known as a guard statement, and they are very nice.

Avoid using try: ... except: ... without specifying the type of the exception you wish to catch. In this case, it's particularly bad as you are not even logging the error; someone could come along, shoot a bullet through the hard drive of the machine you were running this on, and your service wouldn't note that anything of interest had happened. I'd suggest that when a request fails, you return a non-200 status code; at the moment, your bullet ridden hard drive will not cause a single non-200 status code.

Download

If the file exists in Mongo, but not in the FS, currently you say document id not found for id. However, due to the except statement which doesn't specify exception types, your code also says that no matter what else goes wrong (recall the hard drive with a gun wound). I'd find out what class of errors come under the file not found category, and then treat them differently to others.

Currently, if the user looks up a file that doesn't exist, you return None, which I think bottle will complain about. It'd probably be better to add a guard clause along the lines of

if not file_id:
    # I don't know the bottle api for returning a particular status code, but something like this
    return bottle.abort(404)
... # otherwise serve the file

You don't handle the case that someone gives you a file you don't know the mimetype for, I'd recommend checking before you try and set the header.

General

It's best to include a guard at the bottom of the file so that you can import the file without starting the webserver. I'd modify the last few lines to read

if __name__ == '__main__':
    bottle.debug(True)
    bottle.run(host='localhost', port=8080)


Repetitive then/catch method on Javascript I have this function and looks ugly because there are a lot of "catch" doing the same. Any idea how to make it better?

saveUser: function(){
    let user_id = this.$route.params.user_id;
    let payload = this.user;

    updateUser(user_id, payload).then(response => {
        updateOrCreateAddresses(payload).then(response => {
            updateOrCreateBalances(payload).then(response => {
                this.success();
            }).catch(error => {
                this.showError(error)
            })
        }).catch(error => {
            this.showError(error)
        })
    }).catch(error => {
        this.showError(error)
    })
},

As I am not sure on how your Promises work, this is what I can come up with.

To reduce your catch nesting you could make each promise return another promise. This would force you to have a general .then and a general .catch after your updateUser method.

I stubbed a bit of code here:

var updateUser = new Promise(function(resolve, reject) {
  resolve("Promise one");
});

var updateOrCreateAddresses = new Promise(function(resolve, reject) {
  reject("Promise two"); // e.g. replace reject with resolve to see it "pass"
});

var updateOrCreateBalances = new Promise(function(resolve, reject) {
  resolve("Promise three");
});

var success = () => {
    alert("Success");
}

updateUser.then( x => {
    return updateOrCreateAddresses.then(y => {
        return updateOrCreateBalances.then(z => {
            return success;
        })
    })
})
.then(a => a())
.catch(err => alert(err));

What happens there? Each promise is returning another promise. If one promise fails, the promise will return the "error" to it's parent, where on updateUser the promise get's finally caught.


Binary values in hexidecimal notation written directly to video memory In X86 Legacy boot loader prologue the first seven instructions preserve the state of the 8 general purpose and 6 segment registers. This is where they are displayed, right justified without leading zeros. Most often you'll see this kind of thing formulated as an ASCII string, then displayed with printf or maybe if INT 80 or SYSCALL under Linux.

The addresses are absolute and for those that may be interested in executing the code, you can PM me and I'll send the current version that can be assembled with NASM. Then breakpoints can be set and in my case I use BOCH's.

Here is the result;

SI is already pointing to the beginning of this string

  'AXCXDXBXSPBPSIDIESDSCSSSFSGS'

 700  83C61B            add     si, 27     Point to last character
 703  FD                std                Do things in reverse
 704  6800B8            push    VIDEO_SEG
 707  07                pop     es
 708  BF9C09            mov     di, 0x99c  Row 15 Column 30 (zero indexed)
 70B  B90E00            mov     cx, 14     Values to be displayed
 70E  B407              mov     ah, 0x7    in low intensity white

At this point SP is pointing to the values preserved in proglogue.

that is why this instruction without the corresponding push works. After all, is said and done, SS:SP will be pointing to the far pointer back into the BIOS.

 710  5A                pop     dx      Retrieve registers value

Retain pointer to end of hex value (DI) and in case we change attribute which is in AH, preserve it too.

 711  57                push    di
 712  50                push    ax            AH = White
 713  09D2              or      dx, dx        Is value zero
 715  7502              jnz     719
 717  FEC4              inc     ah            AH = Grey
 719  E8BFFF            call    6db

Now registers mnemonic can be displayed in bright yellow

 71C  B40E              mov     ah, 14        Attribute bright yellow
 71E  AC                lodsb
 71F  AB                stosw
 720  AC                lodsb
 721  AB                stosw

 722  58                pop     ax            AH = White again
 723  5F                pop     di
 724  81EFA000          sub     di, 160       Bump pointer up one line
 728  FEC9              dec     cl
 72A  740A              jz      736           Bail if done ZF=1

As soon as CL = 8, that means all the segment registers have been displayed and we can move over to the next column

 72C  80F908            cmp     cl, 8
 72F  75DF              jnz     710
 731  BF200A            mov     di,0xa20      DI = 5DC
 734  EBDA              jmp     710

One thing I had considered here is adding 444H to DI instead, which in effect does exactly the same and then the left column would stay relative if the word at 709H was changed.

Finally, restore DF

 736  FC                cld

This is where DX will be right justified without leading spaces

 6DB  51                push    cx
 6DC  B105              mov     cl, 0x5

 Converts low nibble in AL to corresponding 0-1 or A-F
 6DE  88D0              mov     al, dl
 6E0  240F              and     al, 0xf
 6E2  3C0A              cmp     al, 0xa
 6E4  7202              jc      6e8
 6E6  0407              add     al, 0x7
 6E8  0430              add     al, 0x30
 6EA  AB                stosw
 6EB  FEC9              dec     cl

 Asserting DX here assures only one zero will be displayed for zero
 values in DX
 6ED  C1EA04            shr     dx, 4
 6F0  75EC              jnz     6de
 6F2  D1E1              shl     cx, 1
 6F4  29CF              sub     di, cx
 6F6  B82D0F            mov     ax, 0xf2d
 6F9  66AB              stosd                  Write bright white hyphen
 6FB  59                pop     cx
 6FC  C3                ret

This is a very nice routine that totally succeeds in using a direction flag set to 1. I've seen others fail at this.

Some observations:

731  BF200A            mov     di,0xa20      DI = 5DC

It's not clear what you mean with "DI = 5DC"

  One thing I had considered here is adding 444H to DI instead, which in effect does exactly the same and then the left column would stay relative if the word at 709H was changed.

I would definitely choose adding 444h to DI in such a specially crafted routine. Relative addressing is so much more flexible to work with.

6F6  B82D0F            mov     ax, 0xf2d
6F9  66AB              stosd                  Write bright white hyphen

This is the only place where your code conceivably could fail. You store the dword from EAX without making sure the high word has any meaningful content. If the high word is empty you're in the clear, if not the screen will get disrupted.
Since modern BIOSes do use 32-bit registers, you can't be sure...

The shortest way to 'correct' this is:

mov     ax, 0x0F2D
stosw
dec     di
dec     di


Simple Object Management System I am attempting to create a fast & robust object management system that allows adding, removing and retrieving objects from a "scene". I am trying to wrap my head around the best way to do this regarding ownership and object lifecycle. Code:

main.cpp:

int main()
{
    r3d::scene main_scene;

    game_object& obj = main_scene.create_object("obj", glm::vec3(0, 0, 0), glm::vec3(-90, 0, -90), glm::vec3(1, 1, 1));

    main_scene.remove_object("obj");

    return 0;
}

scene.hpp:

namespace r3d
{
    class scene
    {
    public:
        scene::scene() { }

        game_object& create_object(std::string name,
                                glm::vec3 position = glm::vec3(0, 0, 0),
                                glm::vec3 euler_angles = glm::vec3(0, 0, 0),
                                glm::vec3 scale = glm::vec3(1, 1, 1));

        void remove_object(std::string);

        game_object& get_object(std::string);

    private:
        std::map<std::string, r3d::game_object> game_objects;
    };
}

scene.cpp:

game_object& scene::create_object(std::string name, glm::vec3 position, glm::vec3 euler_angles, glm::vec3 scale)
{
    game_objects.emplace(name, game_object { name, position, euler_angles, scale });

    return game_objects[name];
}

void scene::remove_object(std::string name)
{
    game_objects.erase(name);
}

game_object& scene::get_object(std::string name)
{
    return game_objects[name];
}

game_object.hpp

namespace r3d
{
    class game_object
    {
    public:
        std::string name;

        game_object() {}

        // constructor
        game_object(std::string name, glm::vec3 position, glm::vec3 euler_angles, glm::vec3 scale)
            : name(name),
            position(position),
            euler_angles(euler_angles),
            scale(scale)
        {
            printf("New game_object: %s [address: %p]\n", name.c_str(), this);
        }

        // destructor
        ~game_object()
        {
            printf("Delete game_object: %s [address: %p]\n", name.c_str(), this);
        }

        // copy constructor
        game_object(const game_object& source)
            : name { source.name },
            position { source.position },
            euler_angles { source.euler_angles },
            scale { source.scale }
        {
            printf("Copy game_object: %s [from: %p  to: %p]\n", source.name.c_str(), &source, this);
        }

        // move constructor
        game_object(game_object&& source)
            : name { source.name },
            position { source.position },
            euler_angles { source.euler_angles },
            scale { source.scale }
        {
            printf("Move game_object: %s [from: %p  to: %p]\n", source.name.c_str(), &source, this);
        }

    protected:
        glm::vec3 position;
        glm::vec3 euler_angles;
        glm::vec3 scale;
    };
}

the idea being that any other class can access a game_object by name if given a reference to main_scene, even if it doesn't hold a reference to the actual object

You've stated that one of your primary goals is speed. Based on your description above, you can still achieve object lookup and avoid the performance hit of a string dictionary.

One of the easiest ways to do this is to add a header file to the application that defines an enum of numeric, sequential object IDs. This will allow for much faster lookup, and depending on how you define and load your data, you wouldn't even need a map - simply a fixed array.


Double checked locking with shared_ptr I have an unordered_map<int, std::shared_ptr<foo>> into which I want to lazily create the instances of foo based on callbacks. These callbacks would come from potentially a pool of threads, so to handle this, at the start I create the map and insert empty shared_ptr<>s into the map for all possible indexes. Now I have the code below which is designed to create the foo instance based on demand.

Is my implementation of double checked locking with shared_ptr<> correct?

void Publish(const bar& data)  {
    auto id = data.get_id();
    auto it = foos_.find(id);
    if (it == foos_.end()) {
      // throw
    }
    // Check if this is present
    auto sp = std::atomic_load_explicit(&(it->second), std::memory_order_relaxed);
    std::atomic_thread_fence(std::memory_order_acquire);
    if (!sp) {
      // Create the instance of the foo for this id
      std::lock_guard<std::mutex> lock(mutex_);
      (void) lock;
      // Check again
      sp = std::atomic_load_explicit(&(it->second), std::memory_order_relaxed);
      if (!sp) {
        // Create new foo
        sp = std::make_shared<foo>(...);
        std::atomic_thread_fence(std::memory_order_release);
        std::atomic_store_explicit(&(it->second), sp, std::memory_order_relaxed);
      } // Someone else created it...
    }

    // Push the data in
    sp->Publish(data);
  }

Your implementation of Double Checked Locking is semantically correct; the acquire and release fences provide minimal necessary ordering.

I am wondering why you are using standalone fences, which is almost never necessary..
It is more common to use memory ordering directly on atomic operations:

auto sp = std::atomic_load_explicit(&(it->second), std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);

...

std::atomic_thread_fence(std::memory_order_release);
std::atomic_store_explicit(&(it->second), sp, std::memory_order_relaxed);

Can be replaced with:

auto sp = std::atomic_load_explicit(&(it->second), std::memory_order_acquire);

...

std::atomic_store_explicit(&(it->second), sp, std::memory_order_release);

Furthermore, I understand why you are using (void) lock;, but I would not use that line just to suppress a compiler warning.
Also I am surprised about that warning since a modern compiler should know that RAII objects have a function. Are you sure there is a warning or is that an assumption ?


Copying data from a table into a two-dimensional array Is it possible to remove the inner loop by assigning data.Data.Tables[0].Rows[i].ItemArray directly?

object[,] arr = new object[52784, 21];

for (int i = 0; i < data.Data.Tables[0].Rows.Count; i++)
{
    for (int j = 0; j < data.Data.Tables[0].Columns.Count; j++)
    {
        arr[i, j] = data.Data.Tables[0].Rows[i][j];
    }
}

The reason why I need this code is because, I want to write to data of this dataTable to Excel using Interop which requires a 2-D array as input.

If you need an object[,] your code is as good as i can see it being since a data table is an object[][] at its base (After digging through several different data structures that make up the DataTable.  DataTable has DataRow[] which has DataColumn[] leading to an object[][] after boxing and pulling the actual data value).

Converting between the array structures will require code and while you may be able to do it with linq it would not be as readable as nested for loops (My personal opinion only).

The only enhancements I would suggest would be to store the row and column counts and limit the size of the array to the actual data size. This means you would not have data.Data.Tables[0].X.Count in multiple places and if you found a better way to figure out the counts would only need to change it in 2 places, one for the rows and one for the columns.

int rowCount = data.Data.Tables[0].Rows.Count;
int columnCount = data.Data.Tables[0].Columns.Count;

object[,] arr = new object[rowCount, columnCount];

for (int i = 0; i < rowCount; i++)
{
    for (int j = 0; j < columnCount; j++)
    {
        arr[i, j] = data.Data.Tables[0].Rows[i][j];
    }
}

You could use a foreach loop on the Row.ItemArray and maintain the count but I dont think it would be any faster


Performance serving static files with Rust and Hyper This seems to be working fine, but it performance testing with wrk is poor compared to what I've come up in other languages. Shouldn't Rust excel in serving static files?

How can I make this faster?
Are there any other potential problems here?

extern crate hyper;
extern crate futures;

use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::ffi::OsStr;
use hyper::StatusCode;
use futures::future::FutureResult;
use hyper::server::{Http, Service, Request, Response};

mod api;

struct Router;
impl Service for Router {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Future = FutureResult<Response, hyper::Error>;

    fn call(&self, req: Request) -> Self::Future {
        futures::future::ok(match req.path() {
            "/json" => api::default::json(req),
            _ => static_file(req.path()),
        })
    }
}

fn main() {
    let addr = "127.0.0.1:5000".parse().unwrap();
    let server = Http::new().bind(&addr, || Ok(Router)).unwrap();
    println!("Listening on http://{} with 1 thread...", server.local_addr().unwrap());
    server.run().unwrap();
}

pub fn static_file(path: &str) -> Response {
    let mut f = match File::open("src/static".to_owned() + path) {
        Ok(f) => f,
        Err(_) => {
            return Response::new().with_status(StatusCode::NotFound)
        },
    };

    let mut data = String::new();
    match f.read_to_string(&mut data) {
        Ok(_) => {},
        Err(_) => {
            return Response::new().with_status(StatusCode::NotFound)
        },
    };

    let mut headers = hyper::header::Headers::new();
    match Path::new(&path).extension().and_then(OsStr::to_str) {
        Some(ext) => match ext {
            "html" => headers.set_raw("Content-Type", "text/html"),
            "css" => headers.set_raw("Content-Type", "text/css"),
            "js" => headers.set_raw("Content-Type", "application/javascript"),
            _ => headers.set_raw("Content-Type", "text/plain"),
        },
        None => headers.set_raw("Content-Type", "text/plain"),
    };

    Response::new()
        .with_status(StatusCode::Ok)
        .with_headers(headers)
        .with_body(data)
}

Initial feedback:

Reading to a string is wasteful if you just want to dump data. A Vec is simpler since you don't care about UTF-8 validity; this will also allow for images to be served.
Returning "Not found" for a failure to read seems like a lie. Should be a HTTP 5xx-series error.
Avoid code duplication by returning the content type from the match and setting it afterward.
text/plain is an unconventional default content type, generally I see application/octet-stream.
Extract a constant for the default content type instead of repeating it.

Turning towards performance, start by performing a base-line performance test of a failure URL:

$ wrk http://127.0.0.1:5000/nothing
Running 10s test @ http://127.0.0.1:5000/nothing
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   290.75us   44.99us   1.50ms   90.46%
    Req/Sec    17.00k   537.99    18.05k    73.76%
  341686 requests in 10.10s, 26.72MB read
  Non-2xx or 3xx responses: 341686
Requests/sec:  33831.33
Transfer/sec:      2.65MB

Then a test with an existing but blank file:

$ wrk http://127.0.0.1:5000/exists
Running 10s test @ http://127.0.0.1:5000/exists
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   432.23us   77.26us   1.67ms   85.00%
    Req/Sec    11.49k   586.77    12.74k    65.84%
  231023 requests in 10.10s, 25.34MB read
Requests/sec:  22874.91
Transfer/sec:      2.51MB

Then a test with a 1 MiB file:

$ wrk http://127.0.0.1:5000/big
Running 10s test @ http://127.0.0.1:5000/big
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    38.58ms    5.60ms  94.66ms   95.67%
    Req/Sec   129.41     16.53   171.00     85.50%
  2595 requests in 10.06s, 2.53GB read
Requests/sec:    257.93
Transfer/sec:    257.96MB

This isn't terrible. The biggest problem I see is that you are using an asynchronous library in a completely synchronous manner. Using a threadpool to offload loading the files increases throughput to ~3x of the previous value:

$ wrk http://127.0.0.1:5000/big
Running 10s test @ http://127.0.0.1:5000/big
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    13.60ms    3.75ms  62.03ms   84.27%
    Req/Sec   370.48     43.96   415.00     89.50%
  7403 requests in 10.04s, 7.23GB read
Requests/sec:    737.26
Transfer/sec:    737.35MB

Its possible caching might help even further, but I didn't attempt it.

extern crate futures;
extern crate futures_spawn;
extern crate futures_threadpool;
extern crate hyper;

use futures::Future;
use futures_spawn::SpawnHelper;
use futures_threadpool::ThreadPool;
use hyper::StatusCode;
use hyper::server::{Http, Request, Response, Service};
use std::ffi::OsStr;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;

struct Router {
    pool: ThreadPool,
}

impl Service for Router {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn call(&self, req: Request) -> Self::Future {
        let full_path = "src/static".to_owned() + req.path();

        let data = self.pool.spawn_fn(move || {
            let mut f = File::open(full_path)?;

            let mut data = Vec::new();
            f.read_to_end(&mut data)?;
            Ok(data)
        });

        let mut headers = hyper::header::Headers::new();

        const UNKNOWN_CONTENT_TYPE: &str = "text/plain";
        let content_type = match Path::new(req.path()).extension().and_then(OsStr::to_str) {
            Some(ext) => match ext {
                "html" => "text/html",
                "css" => "text/css",
                "js" => "application/javascript",
                _ => UNKNOWN_CONTENT_TYPE,
            },
            None => UNKNOWN_CONTENT_TYPE,
        };
        headers.set_raw("Content-Type", content_type);

        let r = data.map(|data| {
            Response::new()
                .with_status(StatusCode::Ok)
                .with_headers(headers)
                .with_body(data)
        });

        Box::new(r)
    }
}

fn main() {
    let addr = "127.0.0.1:5000".parse().unwrap();

    let router = Arc::new(Router {
        pool: ThreadPool::new_num_cpus(),
    });

    let server = Http::new()
        .bind(&addr, move || Ok(Arc::clone(&router)))
        .unwrap();

    println!(
        "Listening on http://{} with 1 thread...",
        server.local_addr().unwrap()
    );
    server.run().unwrap();
}


Getting the individual digits of a number Approach 1:

Repeated division-modulus operations:

long num = 123456789;
int count = 0;
while(num > 0)
{
 int digit = num % 10;
 if(digit == 1)
  count ++;
 num /= 10;
}

Approach 2:

Convert it into an String and get the characters at the position:

long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)
{
 char ch = s.charAt(i);
 if(ch == '1')
    count ++;
}

The second operation doesn't need to get the remainder and the quotient each time. A charAt() method can be enough.

Which approach is considered to be better and why?

Consider taking the input from the console.

1st Case:

long num = scanner.nextLong();

2nd Case:

String s = scanner.nextLine();

Here there would be no overhead on converting the number to string.

Also let us assume it is for positive numbers.

I would suggest a third approach that extends the conversion-to-string approach: conversion to List of Character

The benefits of this is that you can utilise Java 8 collection stream feature to perform filtering, aggregation and other functions on the elements.

for instance, your example can be expressed as such (edited following @h.j.k's comment):

    long num = 123456789;
    String s = String.valueOf(num);
    long count = s.chars()
            .mapToObj(i -> (char)i)
            .filter(ch -> ch.equals('1'))
            .count();


SQL call for a scalar When I work with SqlDataAdapter, I usually follow this pattern. Especially note the using/fill combination, which is basically a one-liner. The other stuff is just the facility around it.

private void PopulateData(DataTable table, long index)
{
  SqlCommand command = new SqlCommand(
    commandText.Replace("{ID}", "" + index), Connection);

  using (SqlDataAdapter adapter = new SqlDataAdapter(command))
    adapter.Fill(table);
}

Now, I'll be getting a number of scalars, so naturally I'm prone to use the appropriate method for that. However, I'm not certain how to make the code shorter without affecting readability.

private String GetString(long index)
{
  String output;
  using (SqlCommand command = new SqlCommand(CommandText, Connection))
  {
    command.Connection.Open();
    output = command.ExecuteScalar() as String;
    command.Connection.Close();
  }
  return output;
}

Preferably I'd like to get using/returning of the scalar value to be done as a one-liner too. Is it at all possible?

Or is the pattern of open-get-close inside the using-scope the best way to go? Perhaps it depends on the different circumstances? In such case - which?

I am not sure about the Private/Public scope of this method, someone else will have to talk about that.  but you can return inside a using statement, so instead of this:

private String GetString(long index)
{
  String output;
  using (SqlCommand command = new SqlCommand(CommandText, Connection))
  {
    command.Connection.Open();
    output = command.ExecuteScalar() as String;
    command.Connection.Close();
  }
  return output;
}

you would just return like this

private String GetString(long index)
{
  using (SqlCommand command = new SqlCommand(CommandText, Connection))
  {
    return (command.ExecuteScalar()).ToString();
  }
}

The Command is automatically taken care of so you don't have to worry about explicitly disposing of it.

I assume that the connection is opened and closed by the piece of code that calls this private method, so I left out the connection open and close.

I am kind of on edge about doing it that way, but it seems like you would only want to open one connection for all the SqlCommands that you need to run during the course of the application run.


Ruby Hangman with JSON to save and load This was an assignment from "The Odin Project". This is my first program using JSON. I've been told I need work on structuring my classes, any advice will be appreciated!

https://github.com/jmooree30/Hangman/upload/master

require 'json'
load 'display.rb'

class Hangman
  attr_accessor :name
  @name = name

  def initialize
    puts "What is your name?"
    @name = gets.chomp
    puts "
################################################
                   HANGMAN
################################################
               _________
              |
              |       |
              |       O
              |      /|\\
              |       |
              |      / \\
              |
              -----------------
Welcome #{@name} to Hangman. The computer will generate
a 5-12 letter random word. You will try to guess
that word one letter at a time. Try to solve the
puzzle before time runs out!
\n
"

  end
end

class Gameplay
  attr_accessor :array, :filestuff, :random_word, :cipher, :random_word2, :counter
  def initialize
  @array = []
  @filestuff = File.foreach('5text.txt') do |x|
      chomped = x.chomp
      @array << chomped if (chomped.length >= 5 and chomped.length <= 12)
    end
  @random_word = @array.sample
  @cipher = @random_word.gsub(/[a-z]/, '*').split(//)
  @random_word2 = @random_word.split(//)
  @counter = 5
  puts "Would you like to load a saved game? Y/N"
  saved_game = gets.chomp
  if saved_game == "Y"
    game_file = File.read("saved.json")
    data = JSON.parse(game_file)
    @filestuff = data["filestuff"]
    @random_word = data["random_word"]
    @cipher = data["cipher"]
    @random_word2 = data["random_word2"]
    @counter = data["counter"]
  end
  puts @cipher.join
  puts "Enter a letter."

  def to_json
    JSON.generate({filestuff: @filestuff, random_word: @random_word, cipher: @cipher, random_word2: @random_word2})
  end

  def save_game(string)
    File.open("saved.json", "w") do |game_file|
  game_file.write(string)
    end
  end

  def choice(n)
    @random_word2.each_with_index do |i,index|
      if i == n
        @cipher[index] = i
      end
    end
      if n == @random_word2.join.to_s
        puts "You win"
        puts "would you like to start another game? Y/N"
        new_game = gets.chomp
        if new_game == "Y"
          Hangman.new
          else exit
        end
      end
      if @random_word2.include?(n) == false
        @counter -= 1
        display
        puts "#{@counter} guesses remaining."
      end
      if @counter == 0
        puts "would you like to start another game? Y/N"
        new_game = gets.chomp
        if new_game == "Y"
          else exit
        end
      end
      if n == "1"
          save_game(to_json)
        end
        puts @cipher.join
        puts "Want to save? Press 1 to save."
  end

  @counter = 5
  while @counter > 0
    choice(gets.chomp)
  end

 end
end
Hangman.new
Gameplay.new

One of the ways to structure your objects is to describe your problem in a sentence or two, then turn the nouns into classes, and the verb phrases into methods.

In this case, you may end up with Hangman (the game), Player, and not really much else. You can choose to put the user interaction in Hangman or you can create a separate class for it, as you did with GamePlay.

There are a couple of things to keep in mind:

Make sure the interface makes sense. For example Hangman.new; GamePlay.new to start a game is a bit awkward. Whenever the interface is awkward it usually means there's a problem with the design. In this case, you have to manage two classes independently and you may have noticed that there's not much more you can do with your Hangman class as it is without managing it with logic external to either class.
Apply the right behavior to the right object. Assuming Hangman represents the game, then it should do all the game stuff: new (begin), save, load, guess, show_word, etc. Then GamePlay would just be user interaction, calling the Hangman game's methods as needed.

So let's think about the interface a bit: instead of

Hangman.new
Gameplay.new

perhaps you want something more like GamePlay.begin, or if you want to specify what game it is, maybe Hangman::GamePlay.begin which means you'd put the classes in an organizing module.

This exercise structures everything around a mental model. Then it's up to you to keep the model clean. Every time you need to add functionality, ask yourself: should this go into Hangman or GamePlay? Make sure that you have the separation of concerns clear.

In your case you have user prompts in two classes which is not a clean separation of concerns and may cause problems (e.g. GamePlay doesn't know the player's name).

Hopefully this makes sense. It tackles just the organizing step, let me know if you want assistance refactoring to a different model.


Populating fields from stored procedure I was just wondering if my code below is a good way of populating data from database. I have had no issues with this really but I am being taught this and just wondering if it is the best practice.

 Public Sub LoadProperty()
    '**Finds the Current Property Data

    'Error Checking
    ' On Error GoTo Err_LoadProperty
    Try

        Dim uRecSnap As ADODB.Recordset

        ' Check For Open Connection
        If uDBase Is Nothing Then
            OpenConnection()
            bConnection = True
        End If

        ' Run Stored Procedure - Load Property Record
        uCommand = New ADODB.Command
        With uCommand
            .ActiveConnection = uDBase
            .CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
            .CommandTimeout = 0
                 uCommand.Parameters.Append(uCommand.CreateParameter("@PropertyID", ADODB.DataTypeEnum.adInteger, ADODB.ParameterDirectionEnum.adParamInput, , Val(lblPropertyIDValue.Text)))
            .CommandText = "PropertyMaster_LoadRecord"

            uRecSnap = .Execute
        End With

        ' Store Data Values
        Do Until uRecSnap.EOF
            lblPropertyIDValue.Text = If(IsDBNull(uRecSnap("PropertyID").Value), "", uRecSnap("PropertyID").Value)
            lblSPMReferenceValue.Text = If(IsDBNull(uRecSnap("SPMReference").Value), "", uRecSnap("SPMReference").Value)
            cmbPropertyManager.Text = If(IsDBNull(uRecSnap("PropertyManager").Value), "", uRecSnap("PropertyManager").Value)
            txtAddress1.Text = If(IsDBNull(uRecSnap("AddressLine1").Value), "", uRecSnap("AddressLine1").Value)
            txtAddress2.Text = If(IsDBNull(uRecSnap("AddressLine2").Value), "", uRecSnap("AddressLine2").Value)
            txtAddress3.Text = If(IsDBNull(uRecSnap("AddressLine3").Value), "", uRecSnap("AddressLine3").Value)
            txtTown.Text = If(IsDBNull(uRecSnap("Town").Value), "", uRecSnap("Town").Value)
            txtPostCode.Text = If(IsDBNull(uRecSnap("PostCode").Value), "", uRecSnap("PostCode").Value)
            chkAvailable.Checked = If(IsDBNull(uRecSnap("Availabilty").Value), "", uRecSnap("Availabilty").Value)
            dtpAvailable.Value = If(IsDBNull(uRecSnap("Available").Value), "1/1/1900", uRecSnap("Available").Value)
            chkFactored.Checked = If(IsDBNull(uRecSnap("Factored").Value), 0, uRecSnap("Factored").Value)
            txtFactorName.Text = If(IsDBNull(uRecSnap("FactorsName").Value), "", uRecSnap("FactorsName").Value)
            txtFactorsEmail.Text = If(IsDBNull(uRecSnap("FactorsEmail").Value), "", uRecSnap("FactorsEmail").Value)
            dtpPropertyBuilt.Value = If(IsDBNull(uRecSnap("PropertyBuilt").Value), "1/1/1900", uRecSnap("PropertyBuilt").Value)
            txtPropertyValue.Text = If(IsDBNull(uRecSnap("PropertyValue").Value), "", uRecSnap("PropertyValue").Value)
            txtMinimumFee.Text = If(IsDBNull(uRecSnap("MimimumFee").Value), "", uRecSnap("MimimumFee").Value)
            txtCostAuthorisationAmount.Text = If(IsDBNull(uRecSnap("CostSuthorisationAmount").Value), "", uRecSnap("CostSuthorisationAmount").Value)
            txtCommision.Text = If(IsDBNull(uRecSnap("Commission").Value), "", uRecSnap("Commission").Value)
            chkVacant.Checked = If(IsDBNull(uRecSnap("Vacant").Value), 0, uRecSnap("Vacant").Value)
            dtpVacant.Value = If(IsDBNull(uRecSnap("VacantDate").Value), "1/1/1900", uRecSnap("VacantDate").Value)
            txtStartingRent.Text = If(IsDBNull(uRecSnap("StartingRent").Value), "", uRecSnap("StartingRent").Value)

            uRecSnap.MoveNext()
        Loop

        ' Close Connection
        uRecSnap.Close()
        If bConnection Then CloseConnection()
        uRecSnap = Nothing

    Catch ex As Exception
        MsgBox(vbCrLf & ex.Message & vbCrLf & "Source---" & vbCrLf & ex.Source & vbCrLf & "Problem---" & vbCrLf & ex.StackTrace, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "SouthSide- Error Reporting")

    End Try

End Sub

It might have been an ok-ish way of doing things... 15 years ago. This code is astonishingly similar to what one would be writing in vba - minus the Try..End Try block.

If you want to learn the .NET way of doing things, I strongly recommend you remove this from every VB.NET module you're writing:

Imports Microsoft.VisualBasic

Things in that namespace exist to make an easier transition between vb6/vba and vb.net - pretty much everything in it has an actual .net-idiomatic equivalent elsewhere in the framework.

ADODB / ActiveX Data Objects is replaced with ado.net, itself rendered obsolete with linq-to-sql, itself a predecessor of entity-framework. But one step at a time - start with ado.net.
MsgBox is replaced with System.Windows.Forms.MessageBox
vbCrLf should have been vbNewLine, and both are replaced with Environment.NewLine

You're not including the module-scope fields, and yet the code you posted seems to use plenty... but I don't understand why. You're opening a module-scoped connection, fetching data, and then closing it. Why would that object ever need to exist beyond that? You don't need that Boolean bConnection.

ADODB being COM / unmanaged, it doens't implement the IDisposable interface. See this Stack Overflow answer for information about proper cleanup of COM objects... which should motivate you to use managed code ;-)

In short:

  Use Marshal.ReleaseComObject to tidy up COM objects. ADODB is a COM library being used through COM Interop.

Now, what you have here is essentially a Smart UI pattern: the UI runs the show, and controls everything. That's good for learning how things work, fiddling around and prototyping things, but it's also one of the best ways to create a spaghetti mess out of production code.

Your form should only be responsible for one thing: being a user interface. Accessing a database is not the job of a UI, it's that of some data service.

You should create a class to act as your Model, that would expose a property for each value you're fetching from a database record.

Then the View (/form) wouldn't need to know about a database or connections or anything - it would simply display what the Model has in store for it. And then when the user makes changes, you can take the modified Model and pass it to the same data service that provided you with it, to write the modified values into the database.

Read up on the Model-View-Presenter pattern for more details.


Optional arguments in a function I'm writing a python script to find restrictionplaces. I was wondering if there is a better way to write the following:

def restrictionplace(string, minLength = '', maxLength = ''):
    if minLength == '': minLength = 4
    if maxLength == '': maxLength = 12

    #rest of script

if there is no min or maxlength given, the script should use 4 or 12.

Python lets you set default values for parameters in the method signature in the way you have done above with minLength=''. This means that if the caller of the function doesn't provide a value for that parameter the default of an empty string will be used instead. Essentially doing the job of your if minLength == '': minLength = 4 line. Here is what you might write instead:

def restriction_place(string, min_length=4, max_length=12):
    pass

I also took the liberty of using snake_case as that's the convention in Python for variable and function names (in most cases).

There is a caveat to default values when using mutables, however. see: http://docs.python-guide.org/en/latest/writing/gotchas/


Project Euler #1 Sum of multiples of 3 and 5 Given:

  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

Solution:

class Main {
  public static int sumMupltiple(int num, int limit) {
      int numOfMulitples = (limit - 1) / num;
      return num * (numOfMulitples * (numOfMulitples + 1) / 2);
  }

  public static void main(String[] args) {
    System.out.println(
        sumMupltiple(3, 1000) + sumMupltiple(5, 1000) - sumMupltiple(15, 1000));

  }
}

Is there a clearer approach for Java?

Meta comments

Is your intention to create a separate Java program for each of the hundreds of Project Euler problems? If you plan on completing more than a handful of them, I would recommend finding a way to consolidate your solutions to all problems into a single program. You will find a significant amount of overlap between certain questions, so being able to create "helper" routines will benefit you greatly. Consider adding in some testing, validation, and timing framework to make sure your results are correct and being solved within a reasonable amount of time (i.e., PE's suggested 1-minute duration).

Algorithmic Comments

As this is a code review, and not an algorithm review, and because I don't want to spoil yours or anyone else's Project Euler experience, I'll keep this brief. Your algorithm is good; you've already used the closed-form equation for these triangle numbers and done some math. You can actually take the math a step further, but then the programming is trivialized and entirely problem #1-specific.

Code Comments

Creating the general sumMultiple() routine is good, as it is general enough to probably prove useful later on.

I would highly recommend factoring this line into its own problem001() subroutine:

 sumMupltiple(3, 1000) + sumMupltiple(5, 1000) - sumMupltiple(15, 1000));

Then in your main() function, you need only do:

System.out.println(problem001());

And the self-documenting nature of that naming scheme makes it pretty clear that you are printing the result of problem 001. It might seem a little silly in this case, but not all problems will be one-liners, and consistency is probably better than brevity in this case.

If you do decide to take some of my "meta comments" advice later, it will be even easier to organize your program.


12 Days of Christmas with F# I've implemented 12 Days of Christmas just by using pattern matching. It's not very efficient as it performs 12 iterations, each performing its own iteration (potentially from 12 down to 1... does tail recursion kick in here though?) but I supposed I can live with that at the moment. I'm more concerned with learning how idiomatic F# is written. Would an F# programmer be more concerned with creating types, etc.?

module Christmas
let getOrdinal num =
    match num with
    | 1 -> sprintf "%ist" num
    | 2 -> sprintf "%ind" num
    | 3 -> sprintf "%ird" num
    | _ -> sprintf "%ith" num

let getPreamble num =
    sprintf "On the %s day of Christmas, my true love gave to me" (getOrdinal num)

let rec getVerse verse num =
    match num with
    | 12 -> getVerse (List.append verse ["12 drummers drumming"]) (num - 1)
    | 11 -> getVerse (List.append verse ["11 pipers piping"]) (num - 1)
    | 10 -> getVerse (List.append verse ["10 lords a-leaping"]) (num - 1)
    | 9 -> getVerse (List.append verse ["9 ladies dancing"]) (num - 1)
    | 8 -> getVerse (List.append verse ["8 maids a-milking"]) (num - 1)
    | 7 -> getVerse (List.append verse ["7 swans a-swimming"]) (num - 1)
    | 6 -> getVerse (List.append verse ["6 geese a-laying"]) (num - 1)
    | 5 -> getVerse (List.append verse ["5 golden rings"]) (num - 1)
    | 4 -> getVerse (List.append verse ["4 calling birds"]) (num - 1)
    | 3 -> getVerse (List.append verse ["3 French hens"]) (num - 1)
    | 2 -> getVerse (List.append verse ["2 turtle doves, and"]) (num - 1)
    | _ -> List.append verse ["A partridge in a pear tree"]

let composeVerse num =
    List.append [getPreamble num] (getVerse [] num)
    |> List.fold (fun r s -> r + s + "\n") ""

[1 .. 12]
|> Seq.iter (fun a -> printfn "%s" (composeVerse a))

You should generally avoid List.append because appending to a singly-linked list is quite inefficient.

I think your getVerse function is probably doing too much. You can have a function to get a line at a time which is just int -> string

Recursion can be avoided here if you switch to a list comprehension (the for...in syntax). Recursion is rarely needed in F#.

Even folding can be avoided here as it's simpler to use String.concat.

With all of these changes and a couple more:

let ordinalSuffix = function 1 -> "st" | 2 -> "nd" | 3 -> "rd" | _ -> "th"

let preamble num =
    sprintf "On the %i%s day of Christmas, my true love gave to me" num (ordinalSuffix num)

let line num =
    match num with
    | 12 -> "12 drummers drumming"
    | 11 -> "11 pipers piping"
    | 10 -> "10 lords a-leaping"
    | 9 -> "9 ladies dancing"
    | 8 -> "8 maids a-milking"
    | 7 -> "7 swans a-swimming"
    | 6 -> "6 geese a-laying"
    | 5 -> "5 golden rings"
    | 4 -> "4 calling birds"
    | 3 -> "3 French hens"
    | 2 -> "2 turtle doves, and"
    | _ -> "A partridge in a pear tree"

let verse num =
    preamble num :: [ for i in num .. -1 .. 1 -> line i ]
    |> String.concat "\n"

[1 .. 12] |> List.map verse |> String.concat "\n\n" |> printfn "%s"


Compare two strings in extended memory - classic 8052 I'm looking for a simpler code that isn't resource hungry that can compare two strings stored in different locations in the extended memory of a classic 8052 (namely the AT89S52 microcontroller) to make sure the characters match exactly.

The error flag can be a bit value, but the only thing that concerns me is that I need scanning to begin at any two 16-bit memory locations of my choice and that the same number of consecutive bytes in each location need to be scanned.

I was considering applying boolean logic to DPH or the DPL variables (example ANL and ORL) but at the same time will I be able to make that programmer friendly? I don't want to make the memory addressing confusing later on. Also, I'm looking for code that can replace this that can provide better performance (meaning fewer instructions required to execute a string comparison code).

Any ideas are welcome.

;Load # bytes to check in R7
mov R7,#BYTESTOCHECK

;R6 = our error status. Assume no error here
mov R6,#0h

;Load first memory pointer address to R2:R3
mov R2,#HIGHBYTE1
mov R3,#LOWBYTE1

;Load second memory pointer address to R4:R5
mov R4,#HIGHBYTE2
mov R5,#LOWBYTE2

checknextbyte:

  mov DPL,R2
  mov DPH,R3
  ;DPTR here = R2:R3
  movx A,@DPTR
  ;Store value at DPTR in B
  mov B,A
  inc DPTR
  mov R3,DPH
  mov R2,DPL

  mov DPL,R4
  mov DPH,R5
  ;DPTR here = R4:R5
  movx A,@DPTR
  ;Store value at DPTR in A
  inc DPTR
  mov R5,DPH
  mov R4,DPL

  CJNE A,B,notsame
    ;Both addresses aren't same so string isn't same
    ;make R7=1 to exit loop faster
    mov R7,#1h
    ;Make R6=1 to show we have error
    mov R6,#1h
  notsame:

djnz R7,checknextbyte

AT89S52 is not a classic 8052. Like all modern 8052 variants I know of, it has one feature which really shines here. Namely, it is dual data pointers. Instead of reloading DPL and DPH every time, initialize them once, and just toggle the AUXR1.DPS bit:

; setup
    clr AUXR1.DPS
    mov DPL, R2
    mov DPL, R3

    cpl AUXR1.DPS
    mov DPL, R4
    mov DPL, R5
    ....

; loop
checknexbyte:
    cpl AUXR1.DPS
    movx A, @DPTR
    mov B, A
    inc DPTR

    cpl AUXR1.DPS
    movx A, @DPTR
    inc DPTR

    cjne mismatch
    djnz R7, checknextbyte
mismatch:

You may spare a register (R6), few cycles, and some bytes by using C flag (set by CJNE) as a match/mismatch indication.
It looks like the exit logic is incorrect. On a mismatch (A != B) the jump is taken, and the loop continues. Correct me if I am wrong.


Angular observables piping I wanted to check and see if this was as efficient as can be. The goal is to get a user's data from a group of documents that contains references to users in Firestore.
ngOnInit
this.links = this.currentUserRef.collection('links', ref => ref.where('pendingRequest', '==', false)).get()
            .pipe(map(querySnap => {
                const ret = [];
                querySnap.forEach(async doc => {
                    const val = await doc.get('otherUser').get().then(async userData => {
                        return {
                            id: userData.id,
                            img: await this.getImage(userData.get('profilepic')),
                            name: userData.get('name'),
                            bio: userData.get('bio')
                        }
                    });
                    ret.push(val);
                });
                return ret;
            }));

HTML
<ion-item *ngFor="let link of links | async">
            <ion-avatar slot="start">

            </ion-avatar>
            <ion-label>

{{link.name}}

{{link.bio}}

            </ion-label>
            <ion-checkbox id="{{link.id}}"></ion-checkbox>
        </ion-item>

What do you mean with "efficient" in this case?
From the performance perspective its slow, because it handles one element after the other and for handling one element it needs to wait for an async call.
As a result the browser will note be able to execute multiple requests at once.
You could try to move the getImage request into the html with the async pipe.
Then the browser will be able to fire multiple requests simultaniously.
Beside that i personaly would divide the code in a few methods. So it would look like this:
__HTML__
<img [src]="getImage(link.img) | async"

__TypeScript__
interface Link{
    id: string,
    img: string,
    name: string,
    bio: string
};

...
this.links = this.getLinks(userRef);
...

private getLinks(userRef: ??? ): Link[] {
    return userRef.collection('links', ref.where('pendingRequest', '==', false)).get()
        .pipe(
            map(querySnap => mapSnapToLinks(querySnap))
        )
}

private mapSnapToLinks(querySnap: ???):Link[]{
    querySnap.forEach(async doc => {
        const val = doc.get('otherUser').get().then(userData => this.mapUserToLink(userData));
        ret.push(val);
    });
}

private mapUserToLink(userData): Link {
    return {
        id: userData.id,
        img: userData.get('profilepic'),
        name: userData.get('name'),
        bio: userData.get('bio')
    }
}


Combine data from array of objects I got this data structure and I am checking to see which properties are true, then I am adding the key for all the properties that are true to that object on a new property called combined

const data = [
  {
    keyword: 'banana',
    yellow: true,
    sweet: true
  },
  {
    keyword: 'pineapple',
    yellow: true,
    sweet: false
  },
  {
    keyword: 'apple',
    yellow: false,
    sweet: false
  },
]

const combined = [...data].reduce((acc, { keyword, ...rest}) => {
  const res = Object.entries(rest).reduce((total, [key, value]) => {
    if (value === true) total.push(key)
    return total
  }, [])
  acc.push(res)
  return acc
}, []).map(entry => ({ combined: entry.join(' ') }))

const output = data.map((entry, index) => ({
  ...entry,
  ...combined[index]
}))

console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }

It seems pretty straight forward but somehow this feels a bit convoluted

From a short review;

Your own answer does read better
map is the right approach
I would go for filter instead of reduce (you only want 'true' values that are not keyword)
I probably would have named total -> keys
I prefer <verb><object> so combined -> addGroups
If you dont use a falsy comparison, then you dont need to check for 'keyword'

const data = [
    {keyword: 'banana', yellow: true, sweet: true},
    {keyword: 'pineapple', yellow: true, sweet: false},
    {keyword: 'apple', yellow: false, sweet: false},
];

function addGroup(o){
  return {
    ...o,
    group: Object.keys(o).filter(key => o[key] === true).join(' ')
  };
}

function addGroups(list){
  return list.map(o => addGroup(o));
}

console.log(addGroups(data))
.as-console-wrapper { max-height: 100% !important; top: 0; }


Simple calculator implemented with lambdas I was searching for a way to exercise the Java 8 concepts I've been learning, especially pertaining to Lambdas. Incidentally, I hadn't used any swing in a while and wanted a refresher. This is the result of these two pursuits.

import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class EquationCalculator {
    static interface Equation {
        double compute(double val1, double val2);
    }

    public static void main(String[] args) {
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> new EquationCalculator());
    }

    public EquationCalculator() {
        JFrame frame = new JFrame("Basic Operations");
        JPanel panel = new JPanel(new GridLayout(1, 3));
        JTextField first = new JTextField("2");
        JTextField second = new JTextField("3");
        JComboBox<String> calculate = new JComboBox<>();

        calculate.addItem("Sum");
        calculate.addItem("Difference");
        calculate.addItem("Product");
        calculate.addItem("Quotient");
        calculate.addItem("Exponent");
        calculate.addActionListener(
            e -> JOptionPane.showMessageDialog(
                null, "The result is " +
                calculate(
                    String.valueOf(calculate.getSelectedItem()),
                    Double.parseDouble(first.getText()),
                    Double.parseDouble(second.getText())
                ),
                "Result", JOptionPane.INFORMATION_MESSAGE
            )
        );

        panel.add(first);
        panel.add(second);
        panel.add(calculate);

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static double calculate(String operation, double val1, double val2) {
        Equation add = (alpha, beta) -> alpha + beta;
        Equation subtract = (alpha, beta) -> alpha - beta;
        Equation multiply = (alpha, beta) -> alpha * beta;
        Equation divide = (alpha, beta) -> alpha / beta;
        Equation exponentiate = (alpha, beta) -> Math.pow(alpha, beta);

        switch(operation) {
            case "Sum":
                return add.compute(val1, val2);
            case "Difference":
                return subtract.compute(val1, val2);
            case "Product":
                return multiply.compute(val1, val2);
            case "Exponent":
                return exponentiate.compute(val1, val2);
        }
        return divide.compute(val1, val2);
    }
}

I recognize it's simple, and I can imagine there's likely a bit of "learned how to use a hammer...everything looks like a nail" going on, but I'd nonetheless appreciate any pinpointing good design choices vs poor ones and where I could improve.

Don't use String labels of GUI elements in flow control

It's not good to use the String labels of GUI elements to make decisions.
It would be slightly better if you made "Sum", "Difference", ... global constants, but only slightly.

An enum would be better for this purpose:

enum Operation {
    Sum("Sum", (x, y) -> x + y),
    Difference("Difference", (x, y) -> x - y),
    Product("Product", (x, y) -> x * y),
    Quotient("Quotient", (x, y) -> x / y),
    Exponent("Exponent", Math::pow)
    ;

    private final String label;
    private final Equation equation;

    private Operation(String label, Equation equation) {
        this.label = label;
        this.equation = equation;
    }

    @Override
    public String toString() {
        return label;
    }
}

With this, you could create the JComboBox with Operation items instead of String:

    JComboBox<Operation> calculate = new JComboBox<>();

    calculate.addItem(Operation.Sum);
    calculate.addItem(Operation.Difference);
    calculate.addItem(Operation.Product);
    calculate.addItem(Operation.Quotient);
    calculate.addItem(Operation.Exponent);

Change the call to calculate to this:

    calculate(
            ((Operation) calculate.getSelectedItem()).equation,
            Double.parseDouble(first.getText()),
            Double.parseDouble(second.getText())
    ),

And simplify calculate itself to this:

public static double calculate(Equation operation, double val1, double val2) {
    return operation.compute(val1, val2);
}

Avoid pointless evaluations

In calculate, you declare all the equation types at the top but only use one of them.
This is pointless and wasteful.

Simplify lambdas with method references

These lambdas can be replaced with method references:

    SwingUtilities.invokeLater(() -> new EquationCalculator());
    // ...
    Equation exponentiate = (alpha, beta) -> Math.pow(alpha, beta);

Like this:

    SwingUtilities.invokeLater(EquationCalculator::new);
    // ...
    Equation exponentiate = Math::pow;

Pointless to print stack trace in main

If an exception is thrown in main,
a stack trace will be printed on the console.
There's no need to catch an exception and do the same manually.

Also beware,
it's not a good practice to catch Exception.
It's recommended to catch specific exceptions,
both to signal to readers the things that can possibly go wrong,
and also to avoid truly unexpected exceptions getting caught by the blanket catch.


Is there any more efficient way to code this “2 Sum” Questions Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2. Please note that your returned answers (both index1 and index2 ) are not zero-based. Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list.

If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.

twoSum : function(A, B){
        var tempA = A;
        var index1 = [];
        var index2 = [];
        var Results = [];

        for(var i = 0; i < A.length - 1; i++){
            var temp = B - A[i];
            for(var j = i; j < A.length - 1; j++){
                if(temp == A[j]){
                    if(j - i > 0){
                        if(j < Results[1] || Results.length == 0){
                            if(A[j] != A[Results[1]-1] && A[i] != A[Results[0]-1]){
                                Results[0] = i + 1;
                                Results[1] = j + 1;
                            }
                        }
                    }
                }
            }
        }
        return Results;
    }```

Variables tempA, index1 and index2 seem to be unused.

Since you are only interested in if(j - i > 0){, you can start right there
for (int j  = i + 1; and omit the conditional.

Further the condition if(j < Results[1] || Results.length == 0){ should be flipped around to if(Results.length == 0 || j < Results[1]){ to avoid accessing undefined index.

But actually the variable Results is uselesss because you can return the pair as soon as you find it. Just iterate in the desired directions.

function twoSum(input, targetSum){
  const limit = input.length;
  for(var j = 1; j < limit; ++j){
    var temp = targetSum - input[j];
    for(var i = 0; i < j; ++i){
      if(temp == input[i]){
        return [i + 1, j + 1];
      }
    }
  }
  return [];
}


Shipping charge based on weight The program here is simply supposed to tell you the shipping charge based off of the weight of the package. I am just wondering if there is any further way to concise it? At the moment, I do not think it can go any further than that. The only place where I'm unsure whether I could improve it, could be Booleans. Possibly use a while statement?

def main():

    weight = eval(input("Please enter the weight of the package: "))

    rate = 0

    if weight <= 2:
        rate += 1.25
    elif weight > 2 and weight <= 5:
        rate += 2.35
    elif weight > 5 and weight <= 10:
        rate += 4.05
    elif weight > 10:
        rate += 5.55

    charge = rate * weight

    print("The shipping charge is: $%s" % charge)

print(main())

You are checking much more than you need to. Consider the first two cases:

if weight <= 2:
    # A
elif weight > 2 and weight <= 5:
    # B

If weight <= 2, we fall into case A. If we're not in case A, only then do we continue onto the next condition checks (because we're using elif and not if). As such, if we're even in the path that checks the condition which leads to B, we already know that weight > 2. Thus, that check is redundant and can be reduced to simply weight <= 5.

The whole body can become:

if weight <= 2:
    rate += 1.25
elif weight <= 5:
    rate += 2.35
elif weight <= 10:
    rate += 4.05
else:
    rate += 5.55

Which isn't just less code, it's easier to reason about since all your bounds are visually in the same column.


Making use of a decorator within a python script I've written a script in python which is able to collect links of posts and then fetch the title of each post by going one layer deep from the target page.

I've applied @get_links decorator which scrapes the titles from its inner page.

However, I wish to get any suggestion to improve my existing approach keeping the decorator within as I'm very new to work with it.

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

url = "https://stackoverflow.com/questions/tagged/web-scraping"

def get_links(func):

    def get_target_link(*args,**kwargs):
        titles = []
        for link in func(*args,**kwargs):
            res = requests.get(link)
            soup = BeautifulSoup(res.text,"lxml")
            title = soup.select_one("h1[itemprop='name'] a").text
            titles.append(title)
        return titles
    return get_target_link

@get_links
def get_info(link):
    ilink = []
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    for items in soup.select(".summary .question-hyperlink"):
        ilink.append(urljoin(url,items.get('href')))
    return ilink

if __name__ == '__main__':
    print(get_info(url))

While decorators are fun to learn about (especially when you get to decorators taking arguments and class decorators) and they can be quite useful, I think this decorator should not be one. Sorry.

Your code becomes much easier to read and understand by making this into two functions, one that gets the links and one that gets the title from a link, which you then apply to each link:

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

def get_title(link):
    """Load a link to get the page title."""
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    return soup.title.text.split(" - ")[1] # Will only work exactly like this  with Stackexchange
    # return soup.select_one("h1[itemprop='name'] a").text

def get_links(link):
    """Get all links from a page."""
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    relative_urls = soup.select(".summary .question-hyperlink")
    return [urljoin(url, items.get('href')) for items in relative_urls]

if __name__ == '__main__':
    url = "https://stackoverflow.com/questions/tagged/web-scraping"
    links = get_links(url)
    link_titles = [get_title(link) for link in links]
    print(link_titles)

If you really want to, you can then make a new function that uses these two functions:

def get_link_titles(url):
    """Get the titles of all links present in `url`."""
    return [get_title(link) for link in get_links(url)]

In addition, you should use requests.Session to reuse the connection to the website (since you are always connecting to the same host).

You could put getting a page and parsing it with BeautifulSoup into its own function:

SESSION = requests.Session()

def get_soup(url):
    res = SESSION.get(url)
    return BeautifulSoup(res.text,"lxml")

You might also want to check the headers for a rate limit, because when I ran your code and tried to time it, Stack Exchange temporarily blocked me after some time because the request rate was too high :).


Checking if val is present in list I pretty sure it should be shoter solution.

(defun modulename-vinlist(val lst)
  "Check if value in list"
  (let ((res "no"))
    (let (vv)
      (dolist (pi lst vv)
        (when (string-equal pi val)
          (setq res "yes")
          (return))
        (setq vv (cons pi vv))))
    (when (string-equal res "yes")
      t)))

You want member:

(member val lst)

For example

(if (member 3 '(1 2 3)) t nil) ; t
(if (member 4 '(1 2 3)) t nil) ; nil


Add comma/and between string array in java i get an array of authors from json response and i have to display authors name in TextView(android) in proper format like =>Viraj, Chetan and George R. R. Martin
my code work fine, but it's a mess....
public class SeprateAuthors {
public static void main(String[] args) {
    String[] authors0 = {"a", "b"};
    String[] authors1 = {"a", "b", "c"};
    String[] authors2 = {"a", "b", "c","d"};
    String[] authors3 = {"a", "b", "c","d","e","f"};

    System.out.println(displayAuthors(authors0));
    System.out.println(displayAuthors(authors1));
    System.out.println(displayAuthors(authors2));
    System.out.println(displayAuthors(authors3));
}
public static String displayAuthors(String[] authors) {
    StringBuilder stringBuilder = new StringBuilder();
    String stringAuthors="";
    String prefixComma = ", ";
    String prefixAnd = " and ";
    if ((authors != null) && (authors.length > 0)) {

        for (int i = 0; i < authors.length; i++) {
            if (i < authors.length - 2) {
                stringBuilder.append(authors[i]).append(prefixComma);
            } else {
                stringBuilder.append(authors[i]).append(prefixAnd);
            }
        }
        //  Java Remove extra Characters("and ") from String
        stringAuthors = stringBuilder.substring(0, stringBuilder.length() - 4);
    }
    return stringAuthors;
}

}

Welcome to Code Review, I have some hints about your code, starting from your main method:
public static void main(String[] args) {
    String[] authors0 = {"a", "b"};
    String[] authors1 = {"a", "b", "c"};
    String[] authors2 = {"a", "b", "c","d"};
    String[] authors3 = {"a", "b", "c","d","e","f"};

    System.out.println(displayAuthors(authors0));
    System.out.println(displayAuthors(authors1));
    System.out.println(displayAuthors(authors2));
    System.out.println(displayAuthors(authors3));
}

You have defined several arrays forcing the multiple print , you can obtain the same result defining an 2d array storing arrays of different dimensions like below :
public static void main(String[] args) {
    String[][] authors = { {"a"},
                           {"a", "b"},
                           {"a", "b", "c"},
                           {"a", "b", "c","d"},
                           {"a", "b", "c","d","e","f"}};

    for (String[] row : authors) {
        System.out.println(displayAuthors(row));
    }
}

About the print of the authors array you can distinguish three cases :

array with zero elements : you will print the "" empty string.
array with one element : you will print the unique element of the
array.
array with more than one element : you will print elements with ", "
as separator except for the penultimate element and the last one
that will be separated by "and".

You can rewrite your displayAuthors method in this way:
public static String displayAuthors(String[] authors) {
    if (authors == null) { return ""; }

    switch (authors.length) {
        case 0: return "";
        case 1: return authors[0];
        default: return helperDisplayAuthors(authors);
    }
}

I defined a new method called helperDisplayAuthors :
private static String helperDisplayAuthors(String[] authors) {
    final int length = authors.length;
    String result = "";

    for (int i = 0; i < length - 2; ++i) {
        result += authors[i] + ", ";
    }

    return String.format("%s%s and %s", result,
            authors[length - 2], authors[length - 1]);
    }

}

The method String.format helps you to compose the final string. Here the code of your class:
public class SeparateAuthors {

    public static void main(String[] args) {

        String[][] authors = {{"a"},
                              {"a", "b"},
                              {"a", "b", "c"},
                              {"a", "b", "c", "d"},
                              {"a", "b", "c", "d", "e", "f"}};

        for (String[] row : authors) {
            System.out.println(displayAuthors(row));
        }
    }

    public static String displayAuthors(String[] authors) {
        if (authors == null) { return ""; }

        switch (authors.length) {
            case 0: return "";
            case 1: return authors[0];
            default: return helperDisplayAuthors(authors);
        }
    }

    private static String helperDisplayAuthors(String[] authors) {
        final int length = authors.length;
        String result = "";

        for (int i = 0; i < length - 2; ++i) {
            result += authors[i] + ", ";
        }

        return String.format("%s%s and %s", result,
                authors[length - 2], authors[length - 1]);
    }

}


User guesses the number generated by computer This is my code, which chooses a random number from 0 to 10 for the user to guess.
//guess the number game
//my code
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
  unsigned int secretNumber;
  int guess;
  int maxNumber = 10;
  int maxTries = 4;
  int numTries = 1;

  srand(static_cast<unsigned int>(time(0)));
  secretNumber = (rand() % 10)+ 1;
  cout << "GUESS A NUMBER FROM 0 TO 10!!\n";
    do {
      cout << "\nGuess: \n";
      cin >> guess;

      if (guess < secretNumber)
      {
          cout << "too low:(:(!!      ";
          numTries++;
          cout << "Guesses Left: " << maxTries - numTries;
      } ***//Would it be better to add a bool in the condition?***

      else if (guess > secretNumber && guess <= maxNumber)
      {
          cout << "Too high:D:D!!      ";
          numTries++;
          cout << "Guesses Left: " << maxTries - numTries;
      }

      else if (guess > maxNumber)
      {
          cout << "Do you know how to count to 10?\n";
          cout << "Only from 0 TO 10!!  ";
          numTries++;
          cout << "Guesses Left: " << maxTries - numTries;
      }

      else {
          cout << "WOW! you GUESSED IT?! AMAZING!!!!";
          cout << "You're right! the number is " << guess;
          cout << "\nYou got it right in " << numTries << " guesses!!!";
      }

      if (numTries == maxTries)
      {
          cout << "\n\nYou LOOSE :( LOL!";
      }

  } while (guess != secretNumber && maxTries != numTries);

  return 0;
}

This is the teacher's code, which is simpler and includes a bool variable. Should my previous code be simpler, just as this one?
int main()
{
  int secretNumber = 7;
  int guess;
  int numTries = 0;
  int maxTries = 3;
  bool outOfGuesses = false;

  while (secretNumber != guess && !outOfGuesses)
  {
      if (numTries != maxTries)
      {cout << "Guess a Number: ";
      cin >> guess;
      numTries++;}

      else
      {
          outOfGuesses = true;
      }
  }

  if (outOfGuesses)
  {
      cout << "You loose!";
  }
  else
  {
      cout << "You win!";
  }
  return 0;
}

Is my code as efficient and simple as the teacher's code? //Is there a simpler way to do what I intended to do in my code?

Preface
I'm going to ignore your teacher's code, at least for the moment, and just review yours.
Based on what you've said, I'm guessing you're still pretty close to the beginning of the learning curve. Based on that, I'm going to go into a little more detail that normal about how to move in a direction I think you'll find beneficial, rather than just talking about where you might like to end up.
Approach
First of all, you currently have all your code in main. It can be extremely helpful to define small, self-contained functions to carry out the overall task, instead of having it all inline in a single function like this.
To do this, I'd start with a really basic outline of what the program is supposed to do:

generate a random number
While they haven't used up their guesses or gotten the right answer:

get a guess at the random number from the user
check whether their guess is high, low, or correct

print out the result

Then I'd consider which of those is easily turned into a separate, self-contained piece of code (hint: most of them).
Then I'd write code in main that worked at pretty much that level, and have it delegate the details to other code. A first stab at it might look something like this:
int main() {
    int secretNumber = generate_random();
    int maxTries = 3;

    for (int guessCount = 0; guessCount < maxTries; guessCount++) {
        int guess = get_guess();
        if (check_guess(guess, secretNumber))
            break;
    }
}

Initially, I wouldn't worry a lot about getting every detail precisely correct. Just try to get something that fits reasonably well with the outline you write in English.
From there, you have a couple of choices. One is to start by writing "mock" versions of most of those. They need to do roughly the right sort of thing, but don't put any effort into really making them do the job correctly. For example, we can write a "mock" "generate a random number" as something like:
int generate_random() {
    return 7;
}

That obviously won't do in the long term, but it's enough that we can use it to write and test the rest of the code. Then do roughly the same with the other functions:
bool check_guess(int guess, int secretNumber) {
    // Todo: add code to print out current result
    return guess == secretNumber;
}

int get_guess() {
    static int guess;

    return guess++;
}

Now we have enough that we can test the basic flow of the program. For example, we can check that when we run it, it doesn't get stuck in a loop; it runs to termination. Once we've established that, we can add enough more to print out each guess, and whether it was right or wrong, and see that as-is, it guesses values for 0 through 10, then quits because it used up the allotted number of guesses. If so, great. If not, we figure out why not and fix that.
Then we change the random number to (say) 5, so it should guess correctly before it runs out of guesses. Then we run that to be sure it does what it should (like, print out the message that you got the right answer, and then quit asking for more guesses once 5 is guessed).
Once we're done verifying that the basic flow of the code in main works correctly, we can expand out those subordinate functions to do their jobs correctly, so generate_random() actually generates a random number, get_guess() really asks the user for input, and do on.
The important point here so to break the large, somewhat complex task down into a number of smaller tasks, each of which is quite simple. This way, it's much easier to define and understand what each piece needs to do, and test the code so we can be sure that it does what it's really supposed to.
Other Points
I think it's worth pointing out that I'm positively impressed with a number of things about your code. You've chosen good, clear variable names, and structured the code so it's really quite clean and understandable. It's longer than your teacher's, but length is rarely a good measure of much of anything, and its length doesn't seem (to me) particularly excessive for what it does. A fair amount of the extra length is simply because your teacher's code is closer to what I've recommended as the first step on the way toward better code--for example, it chooses the same "random" number every time it's run. That's simple and easy to test with, but yours is clearly a more complete program in this regard.
As far as the specific question of whether to use a Boolean variable: it doesn't strike me as necessary in this case, but it's also fairly harmless. I can see writing the code either with or without it, and doubt that either is necessarily much better than the other.