Your code formatting needs a lot of work, I couldn't even read through the code because I kept getting lost.

Be consistent with your bracing style

pick one and stick to it

Get rid of unnecessary whitespace

too many extra lines

Don't comment out code and leave it there

if you aren't using it, delete it

Then you end up with something like this this

package com.Example.application;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.MailTo;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  implements OnClickListener {

    final Context context = this;
    private WebView webView;
    private ImageButton btnrefresh;
    private TextView txtrefresh;
    private Menu optionsMenu;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private View mCustomView;

    @SuppressWarnings("deprecation")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //define button
        btnrefresh = (ImageButton) findViewById(R.id.imageButton1);

        btnrefresh.setOnClickListener(this);
        btnrefresh.setVisibility(View.GONE);

        //define textView
        txtrefresh = (TextView)findViewById((R.id.textView1));
        txtrefresh.setVisibility(View.GONE);

        if(isConnected())
        {

            webView = (WebView) findViewById(R.id.webView1);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setAppCacheEnabled(true);

            webView.getSettings().setRenderPriority(RenderPriority.HIGH);
            webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
            webView.getSettings().setSaveFormData(true);
            webView.setWebViewClient(new WebViewClient()
            {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.startsWith("mailto:")) {
                        sendEmail(url.substring(7));
                        return true;
                    }
                    return false;
                }
            });

            initWebView(webView);
            webView.loadUrl("http://Example.com/");
        }
        else
        {
            RelativeLayout rel = (RelativeLayout)findViewById(R.id.relativelayout1);
            rel.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    refresh();
                }
            });
            btnrefresh.setVisibility(View.VISIBLE);
            txtrefresh.setVisibility(View.VISIBLE);
            Toast.makeText(getBaseContext(), "No Internet Connection !!", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendEmail(String add) {
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("text/plain");
        i.putExtra(Intent.EXTRA_EMAIL, new String[] { add });
        try {
            startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(MainActivity.this,
                "There are no email clients installed.", Toast.LENGTH_SHORT)
                .show();
        }

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        this.optionsMenu = menu;
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.airport_menuRefresh:
                webView.reload();
                Toast.makeText(getBaseContext(), "Refeshing...", Toast.LENGTH_SHORT).show();
                // Complete with your code
                return true;
            case R.id.goBack:
                if(webView.canGoBack()) {
                    webView.goBack();
                }
                return true;
            case R.id.goForward:
                if(webView.canGoForward()) {
                    webView.goForward();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void refresh()
    {
        if (isConnected()) {
            btnrefresh.setVisibility(View.GONE);
            txtrefresh.setVisibility(View.GONE);
            webView = (WebView) findViewById(R.id.webView1);

            webView.setWebViewClient(new WebViewClient()
            {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.startsWith("mailto:")) {
                        sendEmail(url.substring(7));
                        return true;
                    }
                    return false;
                }

            });
            initWebView(webView);
            webView.loadUrl("http://Example.com/");

            Toast.makeText(getBaseContext(), "Connected !!", Toast.LENGTH_LONG).show();
            Toast.makeText(getBaseContext(), "Loading....", Toast.LENGTH_SHORT).show();
            Toast.makeText(getBaseContext(), "Please wait....", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getBaseContext(), "No Internet Connection !!", Toast.LENGTH_SHORT).show();
        }
    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
        {
            return true;
        }
        else
            return false;
        }
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK)) {
                AlertDialog.Builder alertbox = new AlertDialog.Builder(MainActivity.this);

                alertbox.setTitle("Do You Want To Exit ?");
                alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        // finish used for destroyed activity
                        exit();
                    }
                });

                alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        // Nothing will be happened when clicked on no button
                        // of Dialog
                    }
                });

                alertbox.show();
            }
            return super.onKeyDown(keyCode, event);
        }
        public void exit()
        {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        public void onClick(View v)
        {
            //refresh ImageButton function
            if (v == btnrefresh)
            {
                refresh();
            }
        }

        private final static Object methodInvoke(Object obj, String method, Class<?>[] parameterTypes, Object[] args) {
            try {
                Method m = obj.getClass().getMethod(method, new Class[] { boolean.class });
                m.invoke(obj, args);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        private void initWebView(WebView webView) {
            WebSettings settings = webView.getSettings();

            settings.setJavaScriptEnabled(true);
            settings.setAllowFileAccess(true);
            settings.setDomStorageEnabled(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            settings.setLoadWithOverviewMode(true);
            settings.setUseWideViewPort(true);
            settings.setRenderPriority(RenderPriority.HIGH);

            methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
            methodInvoke(settings, "setPluginState", new Class[] { PluginState.class }, new Object[] { PluginState.ON });
            methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
            methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
            methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });

            webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            webView.clearHistory();
            webView.clearFormData();
            webView.clearCache(true);
            webView.setWebChromeClient(new MyWebChromeClient());
        }

        UploadHandler mUploadHandler;
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == Controller.FILE_SELECTED) {
                // Chose a file from the file picker.
                if (mUploadHandler != null) {
                    mUploadHandler.onResult(resultCode, intent);
                }
            }
            super.onActivityResult(requestCode, resultCode, intent);
        }

        @SuppressLint("NewApi")
        class MyWebChromeClient extends WebChromeClient {
            public MyWebChromeClient() {

            }
            @SuppressLint("NewApi")
            private String getTitleFromUrl(String url) {
                String title = url;
                try {
                    URL urlObj = new URL(url);
                    String host = urlObj.getHost();
                    if (host != null && !host.isEmpty()) {
                        return urlObj.getProtocol() + "://" + host;
                    }
                    if (url.startsWith("file:")) {
                        String fileName = urlObj.getFile();
                        if (fileName != null && !fileName.isEmpty()) {
                            return fileName;
                        }
                    }
                } catch (Exception e) {
                    // ignore
                }

                return title;
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                String newTitle = getTitleFromUrl(url);

                new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                }).setCancelable(false).create().show();
                return true;
                // return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {

                String newTitle = getTitleFromUrl(url);

                new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                }).setCancelable(false).create().show();
                return true;

                // return super.onJsConfirm(view, url, message, result);
            }

            // Android 2.x
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, "");
            }

            // Android 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooser(uploadMsg, "", "filesystem");
            }

            // Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadHandler = new UploadHandler(new Controller());
                mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
            }
        };

        class Controller {
            final static int FILE_SELECTED = 4;

            Activity getActivity() {
                return MainActivity.this;
            }
        }

        class UploadHandler {
            /*
            * The Object used to inform the WebView of the file to upload.
            */
            private ValueCallback<Uri> mUploadMessage;
            private String mCameraFilePath;
            private boolean mHandled;
            private boolean mCaughtActivityNotFoundException;
            private Controller mController;
            public UploadHandler(Controller controller) {
                mController = controller;
            }
            String getFilePath() {
                return mCameraFilePath;
            }
            boolean handled() {
                return mHandled;
            }
            void onResult(int resultCode, Intent intent) {
                if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
                    // Couldn't resolve an activity, we are going to try again so skip
                    // this result.
                    mCaughtActivityNotFoundException = false;
                    return;
                }
                Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
                        : intent.getData();
                // As we ask the camera to save the result of the user taking
                // a picture, the camera application does not return anything other
                // than RESULT_OK. So we need to check whether the file we expected
                // was written to disk in the in the case that we
                // did not get an intent returned but did get a RESULT_OK. If it was,
                // we assume that this result has came back from the camera.
                if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
                    File cameraFile = new File(mCameraFilePath);
                    if (cameraFile.exists()) {
                        result = Uri.fromFile(cameraFile);
                        // Broadcast to the media scanner that we have a new photo
                        // so it will be added into the gallery for the user.
                        mController.getActivity().sendBroadcast(
                                new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                    }
                }
                mUploadMessage.onReceiveValue(result);
                mHandled = true;
                mCaughtActivityNotFoundException = false;
            }
            void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                final String imageMimeType = "image/*";
                final String videoMimeType = "video/*";
                final String audioMimeType = "audio/*";
                final String mediaSourceKey = "capture";
                final String mediaSourceValueCamera = "camera";
                final String mediaSourceValueFileSystem = "filesystem";
                final String mediaSourceValueCamcorder = "camcorder";
                final String mediaSourceValueMicrophone = "microphone";
                // According to the spec, media source can be 'filesystem' or 'camera' or 'camcorder'
                // or 'microphone' and the default value should be 'filesystem'.
                String mediaSource = mediaSourceValueFileSystem;
                if (mUploadMessage != null) {
                    // Already a file picker operation in progress.
                    return;
                }
                mUploadMessage = uploadMsg;
                // Parse the accept type.
                String params[] = acceptType.split(";");
                String mimeType = params[0];
                if (capture.length() > 0) {
                    mediaSource = capture;
                }
                if (capture.equals(mediaSourceValueFileSystem)) {
                    // To maintain backwards compatibility with the previous implementation
                    // of the media capture API, if the value of the 'capture' attribute is
                    // "filesystem", we should examine the accept-type for a MIME type that
                    // may specify a different capture value.
                    for (String p : params) {
                        String[] keyValue = p.split("=");
                        if (keyValue.length == 2) {
                            // Process key=value parameters.
                            if (mediaSourceKey.equals(keyValue[0])) {
                                mediaSource = keyValue[1];
                            }
                        }
                    }
                }
                //Ensure it is not still set from a previous upload.
                mCameraFilePath = null;
                if (mimeType.equals(imageMimeType)) {
                    if (mediaSource.equals(mediaSourceValueCamera)) {
                        // Specified 'image/*' and requested the camera, so go ahead and launch the
                        // camera directly.
                        startActivity(createCameraIntent());
                        return;
                    } else {
                        // Specified just 'image/*', capture=filesystem, or an invalid capture parameter.
                        // In all these cases we show a traditional picker filetered on accept type
                        // so launch an intent for both the Camera and image/* OPENABLE.
                        Intent chooser = createChooserIntent(createCameraIntent());
                        chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
                        startActivity(chooser);
                        return;
                    }
                } else if (mimeType.equals(videoMimeType)) {
                    if (mediaSource.equals(mediaSourceValueCamcorder)) {
                        // Specified 'video/*' and requested the camcorder, so go ahead and launch the
                        // camcorder directly.
                        startActivity(createCamcorderIntent());
                        return;
                } else {
                        // Specified just 'video/*', capture=filesystem or an invalid capture parameter.
                        // In all these cases we show an intent for the traditional file picker, filtered
                        // on accept type so launch an intent for both camcorder and video/* OPENABLE.
                        Intent chooser = createChooserIntent(createCamcorderIntent());
                        chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
                        startActivity(chooser);
                        return;
                    }
                } else if (mimeType.equals(audioMimeType)) {
                    if (mediaSource.equals(mediaSourceValueMicrophone)) {
                        // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
                        // recorder.
                        startActivity(createSoundRecorderIntent());
                        return;
                    } else {
                        // Specified just 'audio/*',  capture=filesystem of an invalid capture parameter.
                        // In all these cases so go ahead and launch an intent for both the sound
                        // recorder and audio/* OPENABLE.
                        Intent chooser = createChooserIntent(createSoundRecorderIntent());
                        chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
                        startActivity(chooser);
                        return;
                    }
                }
                // No special handling based on the accept type was necessary, so trigger the default
                // file upload chooser.
                startActivity(createDefaultOpenableIntent());
            }
            private void startActivity(Intent intent) {
                try {
                    mController.getActivity().startActivityForResult(intent, Controller.FILE_SELECTED);
                } catch (ActivityNotFoundException e) {
                    // No installed app was able to handle the intent that
                    // we sent, so fallback to the default file upload control.
                    try {
                        mCaughtActivityNotFoundException = true;
                        mController.getActivity().startActivityForResult(createDefaultOpenableIntent(),
                                Controller.FILE_SELECTED);
                    } catch (ActivityNotFoundException e2) {
                        // Nothing can return us a file, so file upload is effectively disabled.
                        Toast.makeText(mController.getActivity(), R.string.uploads_disabled,
                                Toast.LENGTH_LONG).show();
                    }
                }
            }
            private Intent createDefaultOpenableIntent() {
                // Create and return a chooser with the default OPENABLE
                // actions including the camera, camcorder and sound
                // recorder where available.
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),
                        createSoundRecorderIntent());
                chooser.putExtra(Intent.EXTRA_INTENT, i);
                return chooser;
            }
            private Intent createChooserIntent(Intent... intents) {
                Intent chooser = new Intent(Intent.ACTION_CHOOSER);
                chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
                chooser.putExtra(Intent.EXTRA_TITLE,
                        mController.getActivity().getResources()
                                .getString(R.string.choose_upload));
                return chooser;
            }
            private Intent createOpenableIntent(String type) {
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType(type);
                return i;
            }
            private Intent createCameraIntent() {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File externalDataDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_DCIM);
                File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
                        File.separator + "browser-photos");
                cameraDataDir.mkdirs();
                mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
                        System.currentTimeMillis() + ".jpg";
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
                return cameraIntent;
            }
            private Intent createCamcorderIntent() {
                return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            }
            private Intent createSoundRecorderIntent() {
                return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
            }
        }
    }

But when I had done all this I saw that you had things like this.

webView.loadUrl("http://Example.com/");

// Complete with your code

webView.loadUrl("http://Example.com/");

These tell me that this isn't code that you have written yourself.


Wrong memory management

gethostbyname() returns a pointer to an internal structure. You don't
have initialized that memory and don't own it, therefore you must not
call destroy().

Things that can be improved

var hostinfo: UnsafeMutablePointer<hostent>
// ...
hostinfo = gethostbyname(...)

can be combined to

let hostinfo = gethostbyname(...)

There is no need to declare the variable in advance, and the type
can be inferred automatically. Also you can define it as a constant
with let because it is not modified subsequently.

let hostString: String = "youtube.com"
var hostname = (hostString.cStringUsingEncoding(NSUTF8StringEncoding))!
let hostinfo = gethostbyname(hostname)

can be simplified to

let hostname = "youtube.com"
let hostinfo = gethostbyname(hostname)

because a Swift string is automatically converted to a C string when
passed to a C API taking a const char * parameter.

Finally, since the destroy() has been removed,

if (hostinfo == nil) {
    return false
} else {
    return true
}

can be simplified to

return hostinfo != nil

So your function is now

func isNetworkAvailable() -> Bool {
    let hostname = "youtube.com"
    let hostinfo = gethostbyname(hostname)
    return hostinfo != nil
}

BUT: This does not what you expect it to do!

gethostbyname() "only" resolves a host name to an IP address.
That does not necessarily involve any network communication, as
the local DNS resolver might have cached the information.

Better: Use the SCNetworkReachability framework.

From the documentation:

  The SCNetworkReachability programming interface allows an application
  to determine the status of a system's current network configuration
  and the reachability of a target host. A remote host is considered
  reachable when a data packet, sent by an application into the network
  stack, can leave the local device. Reachability does not guarantee
  that the data packet will actually be received by the host.

Other Resources:

Apple provides Objective-C sample code at https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
A Swift wrapper can be found here: https://github.com/ashleymills/Reachability.swift
And perhaps you can use the code from https://stackoverflow.com/questions/25623272/working-with-c-structs-in-swift.


This could definitely be easier to follow.

Here are some suggestions:

Add some comments and docstrings.

The single English sentence in your questions is a big help to understanding the purpose of these functions, and where I might find more information, but it’s not attached to the code.

Something as simple as:

def hex_to_guid(hex):
    """Convert a hex string to a Microsoft GUID"""
    ...

would be a big improvement. If you ever look back over this code, it’ll be easier if you have this reference alongside the function.
Label the parts of the GUID.

In hex_to_guid, you’re packing too much into that final line, and it’s not obvious what any of the components mean. Working from Microsoft’s specification, I think I was able to work out what all the slices were, and then I put them in named variables:

# The Microsoft GUID format has four named fields.  Split the
# bytes into the four fields.  Since the fields are big-endian,
# we need to reverse the stream returned by unhexlify().
# https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx
data1 = reversed(h[0:4])
data2 = reversed(h[4:6])
data3 = reversed(h[6:8])
data4a = h[8:10]
data4b = h[10:]

return '-'.join(map(bytes.decode, map(
    binascii.hexlify, (data1, data2, data3, data4a, data4b))))

Now it’s much easier to check whether the implementation matches the spec.

(I’m not confident I’ve got this right, but it’s much easier to check when the parts are named and referenced than before.)
Prefer list comprehensions to map().

They’re much more Pythonic, and generally much easier to read. You should also split your code into intermediate steps – it makes it easier to disentangle and debug the individual parts. Something like this seems more natural to me:

components = [data1, data2, data3, data4a, data4b]

hex_bytes = [binascii.hexlify(d) for d in components]
decoded = [bytes.decode(b) for b in hex_bytes]

return '-'.join(decoded)

There’s a single logical operation per line of code. You don’t have to unpack complicated map() expressions to read it.

(My variable names are terrible; you can probably think of something better.)
Don’t do too much on a single line.

You should never do too much on a single line of code. Readability is much improved by splitting operations over multiple lines, and assigning your intermediate results to variables with meaningful names.

The first line of guid_to_hex could easily be split across two or three lines (possibly with interspersed comments to explain what’s going on). Here’s how I might do it:

# Remove all dashes from the guid string
# @@AWLC: I don't know why you went via translate() and maketrans()
# for something that it seems like replace() would handle.
guid = guid.replace('-', '')

g = binascii.unhexlify(guid)

You can then name and unpack the components as before.

For what it’s worth, this is what I was left with when I finished writing this answer. It’s substantially longer (although a lot of it is whitespace and prose), but I also claim that a new reader will find my version substantially easier to read, understand and debug:

def hex_to_guid(hex):
    """Convert a hex string to a Microsoft GUID"""
    h = binascii.unhexlify(hex)

    # The Microsoft GUID format has four named fields.  Split the
    # bytes into the four fields.  Since the fields are big-endian,
    # we need to reverse the stream returned by unhexlify().
    # https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx
    data1 = reversed(h[0:4])
    data2 = reversed(h[4:6])
    data3 = reversed(h[6:8])
    data4a = h[8:10]
    data4b = h[10:]

    components = [data1, data2, data3, data4a, data4b]

    hex_bytes = [binascii.hexlify(d) for d in components]
    decoded = [bytes.decode(b) for b in hex_bytes]

    return '-'.join(decoded)

def guid_to_hex(guid):
    """Convert a Microsoft GUID to a hex string"""
    guid = guid.replace('-', '')
    g = binascii.unhexlify(guid)

    # As in hex_to_guid, we split the GUID into four named fields.
    data1 = reversed(g[0:3])
    data2 = reversed(g[3:5])
    data3 = reversed(g[5:7])
    data4 = g[8:]

    components = [data1, data2, data3, data4]

    hex_bytes = [binascii.hexlify(d) for d in components]
    decoded = [bytes.decode(b) for b in hex_bytes]

    return '-'.join(decoded)

This is still by no means perfect: there’s still a lot of code repetition in these two functions. Brevity and cleanliness are good, but they’re on a sliding scale with readability: you should find a balance, not an extreme.


You could use multiple inheritance:

@functools.total_ordering
class SubtitleOrdering(object):
    def __eq__(self, other): return self.start == other.start
    def __lt__(self, other): return self.start <  other.start

class Subtitle(SubtitleOrdering, namedtuple('Subtitle', ['index', 'start', 'end', 'content'])):
    pass

total_ordering works normally on SubtitleOrdering, and making it the first base class overrides the comparison methods of the namedtuple.


C program to read data from text file and write it to a binary one

I am getting a warning in line 73, but I don't think it's an issue as null is converted into 0, right?
 while(((fread((char*)&student, 1, sizeof(student), binary_file)) != NULL)){

Well, if you look at the fread() reference documentation, you see that the return value is a simple size_t, not a pointer. NULL is meant to be a void* pointer and may be probably implemented like #define NULL ((void*)0) according to this.
C is still a strongly statically typed language, a ((void*)0) isn't the same as a ((size_t)0) hence the warning. And you should fix that, it actually is an issue.

Another thing you should look into is

 while(!feof(text_file)){

Why is iostream::eof inside a loop condition considered wrong?
It's merely the same problem in plain C code. You should rather check the streams state from the results of the fscanf() operations.


Implementation of Linux cp in modern C++

I see some things that may help you improve your code.

Fix the bug

The program loops infinitely (actually, as @CrisLuengo correctly points out in a comment, it's not actually infinite.  However, it loops \$2^{54}\$ times for each 1024 bytes in the input file on a 64-bit machine, so it will certainly feel infinite for any human being waiting for the copy to complete!) if the output file already exists or can't be created.  That's a bug that should be fixed.  Generally, when a call can fail (as with open) it is important to test the result for failure before acting on the result.

Use std::fstream for portability

This could be a completely portable program using only standard C++ libraries.  To do that, you'd omit <fcntl.h> and <unistd.h> and just use fstream.  I'm guessing you may have chosen to use the low-level functions for speed, but it's important to measure rather than assume.  The results may surprise you!

Delete file before writing for speed

On several Linux platforms, overwriting an existing program is slower than creating one.  For that reason, one way to make sure that the program is as fast as possible is to call std::remove before doing the copy.

Return valid error codes

A value of 0 as an error indicates no error on Linux and many other platforms.  If you execute cp with no arguments, it returns with a value of 1.  If your program is intended to be an exact replacement, I'd recommend returning 1 instead of 0 if there are missing arguments.

Check for arguments using argc

We can determine if there are the correct number of arguments by examining argc.  The way you're doing it has a problem:

if ( argv[1] == nullptr || argv[2] == nullptr ){

The problem is that if there are zero arguments, argv[1] and argv[2] might not be pointing to anything, so dereferencing them is undefined behavior and therefore not good programming practice.  In particular, you should be aware that argc might be zero which would make testing argv[1] undefined behavior.

Don't use std::string if what you need is a char *

In this case, both of the command line arguments are turned into std::strings but then used exclusively with c_str() to turn them back int char *.  Better would be to simply use char * without conversions to and from std::string.

Prefer std::array to std::vector

If the bounds of your std::vector are known at compile-time (as in this case), then it's generally better to use std::array rather than std::vector.  The std::vector has provisions for resizing that this program doesn't use and doesn't need.  In fact, for this program, there's actually not much difference between a plain C-style array and a std::array.

Name your constant

The buffer size is 1024 bytes, which is probably a bit on the small size.  I think it would be a slight improvement to increase the size and also to name that constant.

Think about non-file files

Under Linux, we have not just files but also devices and named pipes.  Think about whether your program does what you intend if the input is a named pipe.  What happens if we try to copy to /dev/null ?

An alternative version

Using most of those suggestions, here's an alternative:

#include <iostream>
#include <fstream>
#include <cstdio>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        std::cout << "Usage: moderncp srcfile destfile\n";
        return 1;
    }
    std::ifstream in{argv[1]};
    std::remove(argv[2]);
    std::ofstream out{argv[2]};
    if (!out) {
        std::cerr << "Could not create output file " << argv[2] << '\n';
        return 1;
    }
    static constexpr std::size_t buffsize{1024};
    char buffer[buffsize];
    while (in.read(buffer, buffsize)) {
        out.write(buffer, buffsize);
    }
    out.write(buffer, in.gcount());
}

Note that because we're using fstreams for input and output, we don't have to explicitly close the files because the destructor will do so automatically as well as flushing the output buffer.

Results

On my 64-bit Linux machine, copying a 5.3GiB file took 1:29 with the original program, 1:25 with this rewritten version and 1:21 with cp.  Changing the rewritten version to use an 8K buffer allowed it to complete in 0:59, so that's clearly an improvement.


Error handling techniques for nested methods that can throw exceptions

If shortly, using exceptions is not a code-smell.

In my opinion using bool return values is appropriate for methods that are purposed for checking some conditions. Examples:

bool CanFunc2BeCalled() {  ... }
bool TryParse(string s, out ... value) { ... }

Such methods specifically designed to return bool. It is the main job they do.

If a method should perform some actions and during its execution an exception can be occured I would not return bool to indicate a failure. An exception is the right choice for these cases.

Exceptions is a native conception of .NET so don't be afraid of them :) Also with good XML comment on methods you always know what exceptions the method can throw:

///<summary>
///...
///</summary>
///<exception cref="InvalidOperationException">Description of failure.</exception>
void Func2() { ... }

So if you are able to check that call of a method can cause an exception before its execution, create the method for checking some conditions and call it before:

private bool CanFunc2BeCalled() {  ... }

public void Func1()
{
    if (!CanFunc2BeCalled())
        return;

    Func2();
}

But if you can't check if the Func2 can be safely called before its execution then dealing with exceptions is a good way and I would stick with it.


Multi-threaded in-place Mergesort on Java

Quick-Glance nitpicks

elements can (and should) be final. This reinforces the point that you're not changing that reference.
Always place braces around blocks. That's especially true for single-line if-blocks like the element size guard.
Somewhat interestingly inside merge you placed the braces in all if-blocks except the last.
You're inconsistent in the spacing for conditionals. In merge the inner if-statement's conditionals are surrounded by spaces, everywhere else, they are not. I personally prefer putting a space before the opening parenthesis of any condition, if only to distinguish it from a method invocation.

Density of semantics

The swap calls in merge are rather heavy in what they do. There's a lot going on at once, relying on a conscious and full understanding of unary operators and how the method works.

If I were you, I'd consider extracting the incrementing of the indices to separate statements. That can also make the reasoning somewhat easier to understand, seeing that leftIndex++ is in every branch of the tree:

    while (leftIndex < left.size()) {
        if (rightIndex == 0) {
            if (left.get(leftIndex).compareTo(right.get(rightIndex)) > 0) {
                swap(left, leftIndex, right, rightIndex);
                rightIndex++;
            }
        } else if (right.get(0).compareTo(right.get(rightIndex)) > 0) {
            swap(left, leftIndex, right, 0);
        } else {
            swap(left, leftIndex, right, rightIndex);
            rightIndex++;
        }
        leftIndex++;
    }

At this point it should also be clear that the first if-statements can be collapsed into a single statement.
  JS1 mentions that the in-place merge you are doing does not work for all cases.
  Unfortunately I can't tell you quite exactly why, but making the code easier to grasp should help troubleshooting and fixing this :)

Optional List features

You're making use of the set operation on Lists.
It's important to be aware that set is an optional operation.
Not all implementations of List provide an implementation and may throw UnsupportedOperationExcpetion instead.
Then again all the other features you could use to replace this are also optional (what with modification of Lists being optional)...


Very nice work! My only suggestions are to split your large-ish function into several smaller, simpler pieces, and to give each of those pieces its own docstring:

(require '[clojure.string :as str])

(def month-names
  "A vector of abbreviations for the twelve months, in order."
  ["Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"])

(defn month-name
  "Returns the abbreviation for a month in the range [1..12]."
  [month]
  (get month-names (dec month)))

(defn parse-iso-date
  "Returns a vector of the year, month, and day from an ISO 8601 date string."
  [date]
  (mapv #(js/parseInt %) (str/split date #"-0?")))

(defn format-date
  "Converts an ISO 8601 date string to one of the format \"(D)D Mon YYYY\"."
  [date]
  (let [[year month day] (parse-iso-date date)]
    (str day " " (month-name month) " " year)))

This is considerably longer, but most of that additional length is from the fact that now more things are named and documented. The advantage of this approach is that if you find later that you want to use only one or two of these individual parts, or use them in a different way (e.g. when writing another function for a different date format), you can do so without having to duplicate the functionality in your format-date function.

However, I was a bit confused by your comment about libraries:

  As I don't need anything else, I don't want to pull in libs like cljs-time.

One of the greatest features of ClojureScript is that it emits code that is compatible with the advanced mode of the Google Closure optimizing compiler. The impact of this is explained more in the ClojureScript unveiling video (slides are available here). Basically, in ClojureScript, your app can depend on as many libraries as you want, and when you compile it, its final size will only depend on the size of the specific parts of those libraries that you actually end up using.


Summation Over Lines in a File (Advent of Code 2018 Day 1)

That's how you use Iterator::sum:

use std::fs::File;
use std::io::{self, prelude::*, BufReader};

fn main() -> io::Result<()> {
    let file = File::open("day01.txt")?;
    let reader = BufReader::new(file);
    let sum: i32 = reader
        .lines()
        .map(|line| line.unwrap().parse::<i32>().unwrap())
        .sum();

    println!("{}", sum);

    Ok(())
}

You must first say to what type the line must be parsed: parse::<i32>() and then, you must give the sum a type because the output of the Add trait is not the same as self and other.


Sudoku solver using backtracking, in Ruby

It seems fine to me, I don't know if there is a way to solve this problem that performs better. Some minor things:

The Ruby std-lib has a matrix class which might help. It also might help to extract the board into its own class with methods like dup, get_row, get_column, get_block, is_blank?, is_complete?
You don't need to set proposed[i][j] = BLANK on each iteration since you are working on a duplicate of the board.
In get_options You don't need to call uniq, it should be impossible to get into a state with multiple entries in a row, column or block. Similarly you shouldn't need to remove BLANK as there is no way to get a blank entry in the options array.


Return office details from multiple tables

First of all, kudos for using a Parameter and not concatenating the value into your T-SQL string.

You're not disposing all IDisposable objects. SqlDataReader should be disposed as well. Now this makes it quite a bunch of nested using scopes, which you could rework like this:

    using (var connection = new SqlConnection(Settings.ConnectionString))
    using (var command = new SqlCommand(sql, connection))
    {
        command.CommandType = CommandType.Text;
        command.Parameters.AddWithValue("@syncID", syncId);
        connection.Open();

        using (var reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                this.OfficeName = reader.GetString(1);
            }
        }
    }

Note:

Usage of var for implicit typing makes the code easier to read (IMO), if you're using C# 3.0+
Disemvoweling is bad. There's no reason to call a variable rdr over reader. Use meaningful names, always.
Hungarian notation is evil. There's no reason to prefix a string with str.
Stick to camelCasing for locals - that includes parameters, so syncID becomes syncId.

The code assumes the query only returns 1 row, but the query isn't written to explicitly select a single row. This could lead to unexpected results.

Given some IList<string> results = new List<string>();:

        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                results.Add(reader.GetString(1));
            }
        }

You could then do this.OfficeName = results.Single(); (which would blow up if no rows were returned). One thing that strikes me, is that you're selecting 2 fields, but only using 1, which makes this reader.GetString(1) statement look surprising. If you don't need to select the SyncID field, remove it from your query and do reader.GetString(0) instead.

Finally, the T-SQL itself:

Select so.SyncID, so.title
From Offices o
Left Outer Join SyncOffices so On so.id = o.SyncID
Where o.SyncID = @syncID

Could look like this:

SELECT so.Title
FROM Offices o
LEFT JOIN SyncOffices so ON so.id = o.SyncID
WHERE o.SyncID = @syncID

Or, in a string:

var sql = "SELECT so.Title FROM Offices o LEFT JOIN SyncOffices so ON so.Id = o.SyncId WHERE o.SyncId = @syncId";

The line breaks make it look weird, and since it's not too long of a query, I think it would make the code better to have it on a single line.


JavaScript infinite scroll with intersection observer

I think that container and images are being repeated unecessarly.

When you call imgGenerator in appendImages, you already know that you want an array of images.
You can use Array.from:

the first argument will be an array-like object, that is, an object that is accessed by index and with a length propertie(which is identified as images on our javascript)
the second argument will be the mapFunction(which will
be imgGenerator), a function that will be called for every
item of the array

Doing this, on imgGenerator you avoid to make an instance of an array(imgs), a push into it and a for loop every time you want this array, although, you will not need to pass images as parameter again

the container is always imgsContainer, so, in the appendImages you already know where to append

function imgGenerator() {
  const img = document.createElement("img");
  img.src = `http://api.adorable.io/avatars/${randomInteger()}`;
  img.classList.add('infinite-scroll-img');
  return img;
}

function appendImages(images) {
  imgsContainer.append(
    ...Array.from({ length: images }, imgGenerator)
  );
}

function handleIntersect(entries) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      appendImages(5);
    }
  });
}

appendImages(5);


Optimising and error handling Linq query

Not having any error handling in your TopCodeForToday() method, means if anything goes wrong, you're putting the burden of catching any exceptions onto the caller.

And this isn't necessarily a bad thing. It depends on what the client code is expecting.

We don't know what class this method is a member of. The problem is that the naming of the method doesn't convey any information about what's going on, and whether the calling code should wrap it with a try/catch block. If the class is clearly an object that accesses a database and only does SELECT operations, then it's probably fine. Otherwise the method's name should say what it's doing - SelectTopCodeForToday() would be a better name regardless of all of the above, be it only because it starts with a verb.

I don't think returning a string that says "Fail" is a good idea. Replace FirstOrDefault() with First() and let it throw an exception, and then your client code will know that something is wrong with the data.

The problem with returning a "Fail" string, is that it's a valid string. And then the client code needs to verify whether the function returned "Fail" or not. By throwing, you only handle the "happy" path, making your code more focused; and you handle exceptional situations with ...exceptions.


The main problem with using snoc (or append, which your snoc effectively does) is that each call is O(n). This makes your function O(n²), which is (pun intended) deeply problematic.

Here's my O(n) implementation, which is tail-recursive along the cdrs:

(define (deep-reverse l)
  (let loop ((x l)
             (r '()))
    (cond ((null? x) r)
          ((pair? x) (loop (cdr x) (cons (deep-reverse (car x)) r)))
          (else x))))

Here's an even shorter version, using fold (also tail-recursive along the cdrs):

(define (deep-reverse l)
  (define (iter x y)
    (cons (if (pair? x) (deep-reverse x) x) y))
  (fold iter '() l))

For even more fun, an unfold-right version (also tail-recursive along the cdrs); requires compose as well:

(define (deep-reverse l)
  (define (iter x)
    (if (pair? x) (deep-reverse x) x))
  (unfold-right null? (compose iter car) cdr l))


Simplifying a series of type checks and casts in a generic method

You should create a Dictionary<Type,Type> that would associate your object's type with their DTO equivalent, so you wouldn't need any if. Then you can use the dictionary to find the types to map. ex :

//This should be instanciated wherever you want, but try to do it only once.
//The dictionary should be static
dictionary = new Dictionary<Type,Type>();
dictionary.Add(typeof(File),typeof(FileDTO));
//etc..

public T GetContentByNodeIdSync<T>(Guid nodeId)
{
    var data = m_CMSCatalog.GetContentByNodeId(nodeId);
    Type dtoType;
    bool mapExists = dictionary.TryGetValue(typeof(T), out dtoType); //To make sure you have an existing map in your dictionary.

    if(mapExists)
        return (T)Mapper.Map(data, dtoType, typeof(T));

    return default(T);
}


The trick here is to create an inner class.
Something I've started doing recently is to create a method that returns the interface you want!
private View.OnClickListener createClickListener(final int value) {
    return new View.OnClickListener()  {
        buttonValue = value;
        // the rest of your code goes here
    };
}

Thanks to marking the int value as final in the method declaration, it is accessible also from the inner class.
You can now use this like:
one.setOnClickListener(createClickListener(1));

Your actual code
While reducing the code duplication for the individual buttons is important, let's take a look at the code that is actually performed for each button!
Step 1. Adjust spacing to adhere to the Java coding standards and remove unnecessary parenthesis.
Step 2. gridLayout is used in both if and else, so put it outside.
Step 3. In the else part, you're doing the same thing no matter if nextChild.getId() and tb.getId() is the same or not, so reduce code duplication by simplifying that logic.
Step 4. Remove empty if statement
After these steps, the code is:
ToggleButton tb = (ToggleButton) view;
RadioGroup gridLayout = (RadioGroup) tb.getParent();
if (tb.isChecked()) {
    for (int i = 0; i < gridLayout.getChildCount(); ++i) {
        View nextChild = (gridLayout).getChildAt(i);
        if (nextChild instanceof ToggleButton && nextChild.getId() != tb.getId()) {
            ToggleButton tb2 = (ToggleButton) nextChild;
            tb2.setChecked(false);
        }
    }
} else {
    for (int i = 0; i < gridLayout.getChildCount(); ++i) {
        View nextChild = gridLayout.getChildAt(i);
        if (nextChild instanceof ToggleButton) {
            ToggleButton tb2 = (ToggleButton) nextChild;
            tb2.setChecked(false);
        }
    }
}

Next steps:

Put the for loop outside the if-statement
continue early if it is not an instance of ToggleButton
Adjust the if condition to take into consideration the tb.isChecked() from outside, and use an || (OR) operation for the logic.
Rename tb to clickedButton which more describes what the button is used for.

I believe this code will have the exact same effect as your original:
ToggleButton clickedButton = (ToggleButton) view;
RadioGroup gridLayout = (RadioGroup) clickedButton.getParent();
for (int i = 0; i < gridLayout.getChildCount(); ++i) {
    View nextChild = gridLayout.getChildAt(i);
    if (!(nextChild instanceof ToggleButton)) {
        continue;
    }
    if (nextChild.getId() != clickedButton.getId() || !clickedButton.isChecked()) {
        ToggleButton tb2 = (ToggleButton) nextChild;
        tb2.setChecked(false);
    }
}


Creating and referencing markup....cloning, etc. efficient system for this plugin

From a once over:

data should be declared with var, so should a number of other variables. Please paste your code into the JSHint.com site and have a look
It is considered better form to have 1 comma separated var statement:

var feedVideosInPages = this.return_feedVideosInPages(options.thumbCount, options.thumbsPerPage, feed.videos),
    pagesMenu = this.return_PagesMenu(options, listNum, feedVideosInPages),
    thumbnails = this.return_thumbsMarkup(options, optList, listNum, feedVideosInPages);

return_feedVideosInPages is a terrible name, I assume you chose it because feedVideosInPages was already taken ;) I would for something shorter:

var feedVideos = this.getFeedVideosInPages(options.thumbCount, options.thumbsPerPage, feed.videos),

which is still horizontally challenged, since you call that function only once, and since thumbCount and thumbsPerPage are in the same convenient options object you could improve even further to:

var feedVideos = this.getFeedVideos(options, feed.videos),

Finally, if you think about it, since you get the videos from the feed, let getFeedVidoes decide/worry about which property of feed contains the videos:

var feedVideos = this.getFeedVideos(options, feed),

Bad (TMI):

if (toAdd.indexOf(name) !== -1) { clonedElems[name] = elem.cloneNode(true); }//the build will contain another copy, so clone it

Better ( Comment on top ):

//The build will contain another copy, so clone it
if (toAdd.indexOf(name) !== -1) { clonedElems[name] = elem.cloneNode(true); }

Even better ( never drop the newline, but you can drop the curlies! )

//The build will contain another copy, so clone it
if (toAdd.indexOf(name) !== -1)
  clonedElems[name] = elem.cloneNode(true);

The ~ operator ( Bitwise NOT ) is great for comparing to -1:

if (!~toAdd.indexOf(name))
  clonedElems[name] = elem.cloneNode(true);


Is this usage of the dynamic keyword an indicator of a design fault?

I believe your question is more aimed at a what, where, and when to use the dynamic keyword more than a design philosophy. It just so happens that a good explanation exists here: https://cloudncode.blog/2016/07/12/c-dynamic-keyword-what-why-when/
The short and easy from the link:

There is no compile-time type checking, this means that unless you have 100% confidence in your unit tests (cough) you are running a risk.
The dynamic keyword uses more CPU cycles than your old fashioned statically typed code due to the additional runtime overhead, if performance is important to your project (it normally is) don’t use dynamic.
Common mistakes include returning anonymous types wrapped in the dynamic keyword in public methods. Anonymous types are specific to an assembly, returning them across assembly (via the public methods) will throw an error, even though simple testing will catch this, you now have a public method which you can use only from specific places and that’s just bad design.
It’s a slippery slope, inexperienced developers itching to write something new and trying their best to avoid more classes (this is not necessarily limited to the inexperienced) will start using dynamic more and more if they see it in code, usually I would do a code analysis check for dynamic / add it in code review.

In my personal opinion - These functions are accepting rather simple data types (bool, int). It's more cumbersome on the CPU/Hardware to have a dynamic used than to just use function overloading to accomplish the same task without the needed stress. It is true that this may eliminate the need of type checking but you run a very large risk if these functions are used in uncontrolled events.
Also, your confidence in the data being entered for MakeChoice() or any of the other dynamic parameter functions or functions using dynamic has to be as accurate as the sun coming up tomorrow. Otherwise, you may get runtime errors.
Let me know if this helps - thanks.


Your code is too imperative while groovy favours Functional Programming:

def largest_product =
  (0 .. number.size() - digits)
    .map {number[i..<(i + digits)].inject(1) {acc, it -> acc * (it as long)}}
    .max

println largest_product

As you can see, the code is now without all those confusing variables, and the algorithm is more clearly expressed.


First the obvious: if a line is too long, your program will seriously fail (unknown memory gets overwritten, or the program crashes). Without dynamic memory allocation, I see no way to fix it. However, you could improve the situation significantly.

Since you're reading the input character by character, and you need to remove only trailing blanks and tabs, you can printout any character that is not one of these, and put only blanks and tabs in the string. Once you encounter another non-(blank or tab), you printout that string, and reset it back to a blank string. If \n is encountered, you write it out without the content of the string, as these are the trailing blanks and tabs.

You'll also need to keep track of printout and, in case nothing was printed in the line (i.e., there were no non-(blanks or tabs)), you also skip printing of \n, to delete the entirely blank lines.

If you had to remove only the trailing blanks (or only the trailing tabs), you wouldn't need a string at all -- just a counter of how many of those you've encountered. Unfortunately, your task is a bit more complex, and so is a solution.

My modification does not solve the "line is too long" problem, but it does reduce it to "a line has more than 1000 blanks+tabs in a row" problem.

Now, I give you some comments on your actual code.

First, I have one simple remark:

    int i = -1, j; /* two counters */
    ...
    while ((c=getchar()) != EOF) {
        line[++i] = c;
        if (c == '\n') {
            j = i + 1;
            ...
            i = -1;

I think this would be more natural if i was the next character to be written to (instead of the last), i.e.,

    int i = 0, j; /* two counters */
    ...
    while ((c=getchar()) != EOF) {
        line[i++] = c;
        if (c == '\n') {
            j = i;
            ...
            i = 0;

I think that this is also more customary approach when working on strings, since after the loop you often get to do something like s[i] = '\0' instead of s[i+1] = '\0'. This also makes it possible to use the unsigned variable, although I don't see much practical use for that.

Second, this is unnecessary:

            while (line[--j] == ' ' || line[j] == '\n' || line[j] == '\t')
                line[j] = '\0';

You simply need to remember the value of i when you encounter blank or tab the first time after you encountered a character that is not one of these. You can do so easily by keeping the old value of c in a  variable, let's call it oc:

    oc = 'x'; /* anything non-(blank or tab), so it works properly for the empty lines */
    while ((c=getchar()) != EOF) {
        line[i++] = c;
        if ((c == ' ' || c == '\t') && (oc != ' ' && oc != '\t'))
            start_of_trailing_blanks_and_tabs = i;
        ...
        c = 'x';
    }

You could event replace oc by a properly set Boolean flag (in C, this is, of course, of type int).

And, as my last remark, this is also unnecessary:

            for (j = 0; j <= i; j++)
                line[j] = '\0';

You set the end of string elsewhere in the code, and it's only the first \0 that counts.

I also have one suggestion on the style: I'd make a function to identify these characters, or just use isspace() from the ctype library. The later is not exactly what you need, as it also identifies the feed and the carriage return, but I think it is in the spirit of what is asked in the exercise.


Since you have decided to go the way of the specialized object for your board, there are two obvious improvements. One is to use Python magic methods to have a more pythonic notation. The other is to offload the bounds checking to this specialized class. For instance:

class Board(object):
    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.board = [[0] * cols for row in range(rows)]

    def __getitem__(self, index):
        row, col = index
        if 0 <= row < self.rows and 0 <= col < self.cols:
            return self.board[row][col]
        return 0

    def __setitem__(self, index, value):
        row, col = index
        if 0 <= row < self.rows and 0 <= col < self.cols:
            self.board[row][col] = value

This simple class lets you use typical Python indexing with square brackets to access the board, and silently handles out of bounds access.

You may also want to be a little terser about generating your moves. This is one of many options:

def kingknight_moves(start):
    row, col = start
    dest = []
    for dr in range(-2, 3):
        cols = (1, -1) if abs(dr) != 1 else range(-2, 3)
        for dc in cols:
            dest.append((row + dr, col + dc))
    return dest

I'm also going to write a function to advance the board one move:

def advance_board(board):
    new_board = Board(board.rows, board.cols)
    for row in range(board.rows):
        for col in range(board.cols):
            count = board[row, col]
            if count:
                for dest in kingknight_moves((row, col)):
                    new_board[dest] += count
    return new_board

This is pretty much the same you are doing, modulo a nicer syntax.

Now to the meat of the problem... A naive approach like the one you have implemented works:

def chess_metric_naive(size, src, dst, moves):
    board = Board(size, size)
    board[src] = 1

    for move in range(moves):
        board = advance_board(board)

    return board[dst]

But is indeed kind of slow for the largest of the problems posed:

%timeit chess_metric_naive(100, (0, 0), (0, 99), 50)
1 loops, best of 3: 3.7 s per loop

If you were to time each of your iterations advancing the board one move, you would notice that they get progressively slower, as more and more cells are non-zero and contribute to their neighbors. One way of mitigating this effect is to, rather than completing all moves from the source towards the destination, do half of them like this, and the rest from destination to source. If there are \$m\$ ways of getting from the source to a certain cell in half the moves, and \$n\$ ways of getting from the destination to the same cell in the remaining moves, then there are \$mn\$ ways of getting from source to destination. You could implement this like:

def chess_metric(size, src, dst, moves):
    src_board = Board(size, size)
    src_board[src] = 1
    dst_board = Board(size, size)
    dst_board[dst] = 1

    for move in range(moves // 2):
        src_board = advance_board(src_board)
        dst_board = advance_board(dst_board)

    if moves % 2:
        src_board = advance_board(src_board)

    total = 0
    for row in range(size):
        for col in range(size):
            total += src_board[row, col] * dst_board[row, col]

    return total

And it turns out to be substantially (3x) faster:

%timeit chess_metric(100, (0, 0), (0, 99), 50)
1 loops, best of 3: 1.2 s per loop

We can do even better though: an alternative approach is to use something akin to a branch and bound approach. We know that the maximum distance that our made up chess piece can move is \$\sqrt 5\$, so we need not consider cells that are further from the destination more than that value times the number of moves left. A possible approach is to create a board holding minimum number of moves to get to the destination from any other cell:

def moves_lower_bound(rows, cols, dst):
    from math import sqrt, ceil
    dst_row, dst_col = dst
    board = Board(rows, cols)
    for row in range(rows):
        row2 = row - dst_row
        row2 *= row2
        for col in range(cols):
            col2 = col - dst_col
            col2 *= col2
            dist2 = row2 + col2
            # rounded up int division dist2 // 5
            board[row, col] = int(ceil(sqrt(dist2) / sqrt(5)))
    return board

With the aid of this auxiliary board, we can prune the cells that cannot add to the final result whenever we advance the board:

def advance_and_prune_board(board, bounds, moves_left):
    new_board = Board(board.rows, board.cols)
    for row in range(board.rows):
        for col in range(board.cols):
            count = board[row, col]
            if count and bounds[row, col] <= moves_left:
                for dest in kingknight_moves((row, col)):
                    new_board[dest] += count
    return new_board

Putting all this together:

def chess_metric_bb(size, src, dst, moves):
    board = Board(size, size)
    board[src] = 1
    bounds = moves_lower_bound(size, size, dst)

    for move in range(moves):
        board = advance_and_prune_board(board, bounds, moves - move)

    return board[dst]

We get close to a 9x improvement over the simpler approach:

%timeit chess_metric_bb(100, (0, 0), (0, 99), 50)
1 loops, best of 3: 424 ms per loop


Don't make your code more compact, it's a futile exercise. Use a minifier or even a compiler/optimizer. Your source code should be as readable as possible
document.write is evil, don't use it.

Here's how I would write it:

var tpp = {
    number: "1Z123489754897",
    key: "1234567890123457890123",
    width: 850,
    height: 200,
    "m width": 260,
    "m height": 200
};

function init(settings) {
    var div, script;
    div = document.createElement("div");
    div.id = "ttp";
    document.body.appendChild(div);
    script = document.createElement("script");
    script.src = "//example.com/embed.js";
    script.type = "text/javascript";
    document.body.appendChild(script);
}

window.attachEvent("load", function() {
    init(tpp);
});
/* or */
window.addEventListener("load", function() {
    init(tpp);
});

Adding the event listener on window.load avoids having to do the setTimeout later on.
Also, when doing a setTimeout, don't use the eval variant, use an anonymous function:

setTimeout(function () {
    document.getElementById('ttp').appendChild(s);
}, 1);


1. Introduction

If you really mean what you say in the post about making access "thread safe", then creating lockfiles is overkill: it would be better to use threading.Lock objects. I am going to assume, in the rest of this review, that you mean "multiprocess safe" rather than "thread safe"

2. Review

There's no documentation. What does exclusive_file do? What guarantees does it provide? What operating systems does it run on?
If code raises an exception while the lock is held, then the lock is not released.
The choice of lock_retry_wait = 0.05 could end up rate-limiting operations involving a file so that they can happen at most 20 times a second. It would be better to make this into a keyword argument to the exclusive_file function, so that a user with different requirements can specify a different value.
It seems perverse that lock_retry_wait is in seconds but lock_wait_timeout is in milliseconds. This seems likely to lead to confusion. It is better for all time values to have the same units.
The current_milli_time function is written with lambda rather than def. There does not seem to be a good reason for this. It's better to use def because you can provide a docstring.
Using Python's built-in datetime.datetime objects, you could avoid the need for the current_milli_time function.
When programming a timeout, it is more efficient to compute a deadline once, in advance, than to repeatedly compute an elapsed time.
When you have a timeout argument to a function, it's often convenient to have a special value (for example None) meaning "keep retrying indefinitely".
Instead of catching all OSError and then re-raising the ones that aren't errno.EEXIST, catch FileExistsError instead.
The built-in function open takes more arguments than mode — there's also buffering, encoding, errors, newline, closefd, opener, and maybe others in forthcoming releases. It would be better for exclusive_file to take *args and **kwargs and forward these to open.
Because exclusive_file is a wrapper around the built-in open, it would be better for it to be named exclusive_open.
The code in the post only works if the process has write access to the directory containing the file. But sometimes you want to exclusively open a file in a directory to which you do not have write access.

3. Revised code

from contextlib import contextmanager
from datetime import datetime, timedelta
import os
from time import sleep

@contextmanager
def exclusive_open(filename, *args, timeout=3, retry_time=0.05, **kwargs):
    """Open a file with exclusive access across multiple processes.
    Requires write access to the directory containing the file.

    Arguments are the same as the built-in open, except for two
    additional keyword arguments:

    timeout -- Seconds to wait before giving up (or None to retry indefinitely).
    retry_time -- Seconds to wait before retrying the lock.

    Returns a context manager that closes the file and releases the lock.

    """
    lockfile = filename + ".lock"
    if timeout is not None:
        deadline = datetime.now() + timedelta(seconds=timeout)
    while True:
        try:
            fd = os.open(lockfile, os.O_CREAT|os.O_EXCL)
            break
        except FileExistsError:
            if timeout is not None and datetime.now() >= deadline:
                raise
            sleep(retry_time)
    try:
        with open(filename, *args, **kwargs) as f:
            yield f
    finally:
        try:
            os.close(fd)
        finally:
            os.unlink(lockfile)

Notes:

I chose to document the issue in 2.12 rather than fixing it.
Possibly the second try: finally: is overkill (close rarely fails), but I think it's wise to make every effort to release a lock. Deadlock is rarely fun to debug.


Over the years I have seen other students here and they are quite proud of the performance of their code.  In some of those past instances I have discovered that they had simply run their code and thought it was fast.  They did not compare it to other methods.

You don't mention any testing or provide any numbers.  If you were to do this, just be sure that (1) your code is a Release build and not a Debug, and (2) that you do have disabled "Prefer 32-bit" for Build.

The biggest thing that strikes me about your implementation versus others I have seen is that you make 2 lists (smaller and bigger) per invocation whereas other implementations perform an in-place sort on the list or array.

Does this matter?

YES.  Performance is significantly faster when performing in-place sorting using the one list.

I wrote a sample for you.  I have decide not to post my code here because you are a CS student and your namespace is Assignment which tells me this is classwork.  It would be unethical of me to write this code for you.  What I will do instead you point you to the resources I used, and show my performance timings.

My reference was Wikipedia Quicksort.  In particular I used the Hoare partition scheme.  I translated the psuedocode to C#.

I will share key method signatures.  Yes, plural.

public static void Sort2(List<int> list) => Sort2(list, 0, list.Count - 1);

private static void Sort2(List<int> list, int lowIndex, int highIndex)
{
    // Good luck on your assignment!
}

I also had a Partition and Swap method.  I leave it to you to decide whether these should be public or private and what they do.

PERFORMANCE

Size of list: 10_000
Number of trials: 10_000
Original QuickSort ElapsedTicks: 117_816_477
In-place QuickSort ElapsedTicks:  50_171_790

Which means your original is 2.3 times slower than my in-place sorting.


As far as performance goes there are two general approaches to address this
Parallel processing
Running the com object is dragging in itself. Processing 10's of 1000's of files with one Excel instance will be draining. PowerShell does support multiple avenues of mitigating this

https://stackoverflow.com/questions/4016451/can-powershell-run-commands-in-parallel

https://stackoverflow.com/questions/8781666/run-n-parallel-jobs-in-powershell

about_foreach_parallel

I am going to show an approach using Jobs. What this will do is group up identified files. Each group will be past to its own Excel job for processing. Some comments in the code below explain it more.
# Root directory containing your files.
$path = "E:\temp\csv"

# Get Current EXCEL Process ID's so they are not affected but the scripts cleanup
# SilentlyContinue in case there are no active Excels
$currentExcelProcessIDs = (Get-Process excel -ErrorAction SilentlyContinue).Id

# Collect the files
$files = Get-ChildItem -Path $path -Filter "*.txt" -File

# Split the files up into processing groups. For Each group and excel process will be started.
$numberOfGroups = 5
$maxGroupMemberSize = [math]::Ceiling($files.Count / $numberOfGroups)

# Create as many file groups
$fileGroups = 0..($numberOfGroups - 1) | Foreach-object{
    $groupIndexStart = $maxGroupMemberSize * $_
    # Use the unary comma operator to be sure an array is returned and not unrolled
    ,$files[$groupIndexStart..($groupIndexStart + $maxGroupMemberSize - 1)]
}

# Create a job for each file group.
for($jobCount = 0; $jobCount -lt $fileGroups.Count; $jobCount++){
    # Start a unique Excel instance for this group of files.
    Start-Job -Name "Excel$jobCount" -ScriptBlock {
        param($files)
        $excelFileFormat = 56 #xlExcel8 format

        # Create a new Excel Instance
        $excel = New-Object -ComObject Excel.Application
        $excel.Visible = $false
        $excel.DisplayAlerts = $false

        ForEach ($file in $files){
            $workbook = $Excel.Workbooks.Open($file.Fullname)
            $newFilepath = $file.Fullname -replace "\..*$",".xls"
            $workbook.SaveAs($newFilepath, $excelFileFormat)
        }

        # Quit this instance and return its memory
        $excel.Quit()
        while([System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)){}
        while([System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)){}
        Remove-Variable "workbook","excel"

    } -ArgumentList (,($fileGroups[$jobCount])) | Out-Null
}

# Wait for the jobs to be completed and remove them from inventory since they won't have output we need
Get-Job -Name "Excel*" | Wait-Job | Receive-Job

# Remove any stale Excel processes created by this scripts execution
Get-Process excel -ErrorAction SilentlyContinue | Where-Object{$currentExcelProcessIDs -notcontains $_.id} | Stop-Process

Excel automation is full of pitfalls but the general approach seems to be working. For one com objects can prevent from being closed. Best thing to do is just kill any remaining processes. There is logic that can help to be sure any Excel opened before the script was run are not affected. Jobs are done in the way as well to not affect processing of other scripts.
This all would be better as a script using proper parameters but showing the logic of jobs is the point here.
Automate without Excel
There are a number of libraries out there that can create Excel documents without the need for COM objects or Excel itself. These would perform faster as well. EPPlus comes to mind and even [ImportExcel module] (which uses EPPlus) would be solid choices as well. I don't know what your text files look like so you will need to experiment.
Get-Content E:\temp\csv\data.txt | Export-Excel -Path "e:\temp\csv\file.xlsx"

Export-Excel works better with objects so, depending on your data structure, you would do this instead.
Import-Csv E:\temp\csv\data.txt | Export-Excel -Path "e:\temp\csv\file.xlsx"

Import-CSV is generally a slow process so you would want to try using streamreader and Convert-FromCSV if performance suffers.
Magic Numbers
Your 56 would be an example of that. You have to look it up to know what it represents. So 56 is for Excel Version 8. At a minimum that should be its own variable. My code above uses
$excelFileFormat = 56 #xlExcel8 format

If you wanted to go a little crazier you could actually import the assembly to access the enum
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.InterOp.Excel") | Out-Null
[Microsoft.Office.Interop.Excel.XlFileFormat]::xlExcel8

BaseName

 $NewFilepath = $file.Fullname -replace ".{4}$"
 $NewFilepath =  $NewFilepath + ".xls"

This is what you are doing to replace the extension of the file. File objects have a basename property that is the file name without the extension. I know that you are dealing with txt files, so you already know how many characters on the end to remove, but using .basename would remove that complexity in other areas as well.
$NewFilepath = "$($file.BaseName).xls"


Correct, the lifetime of objectSettings is only for the MyObject function, so you don't need the assignment to null at the end.

Passing in an object to the constructor is a common pattern to set its properties, and if you don't want to add specific assignment statements for each property, you can do something like this:

Utils = {
  // Taken from the ExtJS library
  apply: function(o, c, defaults) {
    if(defaults) {
      Utils.apply(o, defaults);
    }
    if(o && c && typeof c == 'object') {
      for(var p in c) {
        o[p] = c[p];
      }
    }
    return o;
  }
};

function MyObject(cfg) {
  Utils.apply(this, cfg, {
    id: 0,
    legs: 2,
    ...
  });

  // You now have access to this.id, etc.
}


Using prototypes creating a Hangman game

Encapsulation

  I would like to know how I should encapsulate the logic.

  Can I have logic outside the methods (as I'm doing, like
  hangman.letters.push(e.key); in document.onkeydown or should I only
  call the methods here and they should strictly run the game?

Ideally no internals should be exposed.
Using the hangman object should go more like this:

document.onkeydown = function(e) {
  if (hangman.guessLetter(e.keyCode)) {
    if (hangman.won()) {
      // congrats!
      // -> display complete word
      // -> clean up UI
    } else {
      // good guess!
    }
  } else {
    if (hangman.lost()) {
      // ouch, you lost
      // -> clean up UI
    } else {
      // ouch, you missed, try again
    }
  }
  // -> display word status, for example _we_e_ when "w" and "e" were already found in "sweden"
};

No properties of hangman should be accessed, only methods called.

Usability

The game looks incomplete:
the UI shows a large image and a button,
but expects input from the keyboard and writes messages to console.
It's hard to use like this.

Performance

The implementation of _checkWinner is inefficient.
It splits the secret word and the guess to their letters and joins them to compare to each other.
This operation is unnecessary for the secret word,
because once it's generated at the beginning of the game,
it never changes.
So it would be better to generate the word with sorted letters up front.


Is this the best way to collapse a column width?

IMHO it's completely fine to set the width like this. Table cell widths have always be defined to be a "minimum width".

As long the table doesn't have table-layout: fixed or the cells don't have overflow set to anything else than visible, I don't believe any browser (old or new) would have any problems width this.

The only nitpick I would have, it that the size of 1px feels wrong to me, mostly because this forces the column to wrap as much as possible and depending on the content this may not look very good. I would suggest 1em (purely because it "feels" better :-) and maybe a larger minimal width such as 10em would be suitable for some columns.


Batch Gradient Descent running too slowly

dot() gets called three million times.

I changed it from:

def dot(v,w):
    return sum(v_i * w_i for v_i, w_i in zip(v,w))

to:

def dot(v,w):
    return (v[0] * w[0]) + (v[1] * w[1])

And the runtime dropped from 7.09 seconds to 2.89 seconds, with the same results.


I think the catch and then parts are unnecessary. A then accepts a resolve and reject handler, which you can treat a boolean.

var Promise = require("bluebird")
var fs = Promise.promisifyAll(require("fs"))

module.exports = fs.lstatAsync

Usage would simply be

var stat = require('yourFsStatModule');

stat('path/to/file').then(function(){
  // it exists
}, function(){
  // it doesn't exist
});


Your approach seems fine. But some minor improvements are possible:

It's unnatural to write !(x == y), the more natural way is x != y
I'm wondering if option is needed outside the loop are all. If not, then you should declare and initialize it inside the loop.
in every iteration, you check cboFruits.getSelectedItem()== null twice: once after the use clicked OK, and then again in the loop condition. It would be better to rearrange this code in a way that the condition is checked once per iteration.
It's recommended to use braces always, even with single line if statements


Number of occurence of two letters separted by a finit gap

I assume you are trying to find the number of pairs of a letter i and a letter j (i and j are arbitrary letters) that are at most L indices away from each other.

Use a sliding window algorithm. The sliding window will contain all indexes of an element i that are within the range of a certain index with the letter j.

Step 1. Store all indexes of the letter i in a sorted fashion (scan the input in order) O(N)

Step 2. Store all indexes of the letter j in a sorted fashion (similar to Step 1) O(N)

Example:

string s;  <- Assume input is already in this string
vector<int> letter1, letter2; <- Store indices
for (int i = 0; i < N; i++){
    if (s[i] == 'a'){         <- Our letter 'i'
        letter1.push_back(i);
    }
    if (s[i] == 'c'){         <- Our letter 'j'
        letter2.push_back(i);
    }
}

Step 3 (more complicated):

int track = 0, sum = 0;    <- Track the front-most index and the running sum of pairs
queue<int> window;  <- Our sliding window
for (int i = 0; i < letter2.size(); i++){   <- For every letter 'j'
    while (!window.empty() && window.front() < (letter2[i] - L)){
        window.pop_front();
    }
    while (letter1[track] <= (letter2[i] + L) && (letter1[track] >= (letter2[i] - L)){
        window.push(letter1[track]);
        track++;
    }
    sum = sum + window.size();
}

Let me explain some of the lines.

while (!window.empty() && window.front() < (letter2[i] - L)){
    window.pop_front();
}

The condition !window.empty() is to prevent a run-time error when calling window.front() later on. window.front() < (letter2[i] - L) implies that the smallest index in the queue is less than the minimum allowed value in the range, thus we should exclude it. We do not have to consider it ever again as the smallest possible value in the allowed range only increases as we iterate over letter2. We continue removing the elements till all of the elements are within the range or there are no elements left.

while (track < letter1.size() && letter1[track] <= (letter2[i] + L)  ){
    if ((letter1[track] >= (letter2[i] - L)) window.push(letter1[track]);
    track++;
}

The first condition track < letter1.size() is also to prevent a run-time error. The next condition is to check if the element is less than or equal the maximum allowed value in the range. If the element is also more than or equal to the smallest allowed value in the range, then we add it to the queue. We still increment track even if no value is pushed into the queue as at the end of each iteration of the loop, letter1[track] is always the smallest element larger than the allowed range during that iteration or is out of bounds.

All you have to do after this to output sum.

Although there are 2 nested loops, this algorithm runs in O(N) where N is the number of letters. Why? Because each index of the letter i is pushed and popped from the queue at most once each throughout the entire loop. This is at most 2*N operations, which is linear time.

All of the code is in C++ as that is my main language, though the concept can be applied to any language. You might want to look up other examples of the sliding window algorithm like this question from the Australian Informatics Olympiad.


Well, your code is neat, and you use the Try-with-resources structures well. There is one potential bug, which is that there may be lines whihc have a 'successful' part[0], but no part[3] which would cause an IndexOutOfBoundsException.

As for the performance, the key here is Amdahl's Law.... essentially parallelization.

You have five CPU intensive parts to your problem:

decompression
Stream->Reader
Split & Filter
Writer->Stream
Compression

Assuming the transformations that you do in each of these are similarly expensive to do computationally, then you can probably make your system go 5 times faster by doing them each in parallel. Five threads:

one of them reads the data from the file, and decompresses that in to chunks of bytes which it feeds in to a queue.
the second takes chunks from the queue, and decodes it in to characters (UTF-8?), which it puts in to a char chunk queue
the third takes char chunks, identifies and splits the lines, and filters what's junk.
the fourth encodes the chars back to a byte stream, in chunks which it places on a queue
the fifth compresses the byte chunks back to disk

This is going to net you a potential 5X improvement.

That's pretty complicated though.

What would be much simpler is to use a different axis to process the parallelism. Your comments indicate that you have multiple files to process.... you should do them each in multiple threads...

Consider the following structure:

private static final boolean processFile(final File fileIn) throws IOException {
    //For each file in a folder:
    try (BufferedReader br = new BufferedReader(new InputStreamReader(
            new BZip2CompressorInputStream(new FileInputStream(fileIn))));
         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            new GZIPOutputStream(new FileOutputStream(fileOut))))) {

        String line;
        while ((line = br.readLine()) != null) {
            String[] parts = line.split(',');
            if(isLineToSkip(parts[0])) {
                continue;
            }
            String outLine = parts[0] + "," + parts[3];

            writer.append(outLine);
            writer.newLine();
        }
    }
    return true;
}

.......

ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
List<Future<Boolean>> queued = new LinkedList<>();
for (final File toprocess : ....... ) {
    queued.add(service.submit(new Callable () {
        public Boolean call() throws IOException {
            return processFile(toprocess);
        }
    }));
}

for (Future<Boolean> future : queueud) {
    future.get();
}

With the above code, you will do one file in each thread, and the system CPU will run at 100% ... no matter how many CPU's you have. Essentially you are using your system fully.


Determining whether a provided credit card number is valid according to Luhn’s algorithm

First thing I think of is that you have a pretty long main. You should split the code in more functions. Your code could look like this:

long long readCardnumber();
bool validateChecksum(long long cardnumber);
typedef enum { invalid, amex, mastercard, visa } company;
company getCompany(long long cardnumber);

int main()
{
    long long cardnumber = readCardnumber();
    bool valid = validateCardnumber(cardnumber);
    if(!valid) {
        printf("INVALID\n");
        exit(0);
    }
    company comp = getCompany(long long cardnumber);
    switch(comp) {
        case visa: printf("VISA\n"); break;
        case mastercard: printf("MASTERCARD\n"); break;
        case amex: printf("AMEX\n"); break;
        default: printf("INVALID\n");
    }
}

Another thing is that you are writing if (valid == false). Just write if (!valid) instead. At least I think it looks way better, since it feels natural to read it as "if not valid". Also, write if (valid) instead of if (valid == true).

One general advice on boolean expressions. Consider writing if(3 == var) instead of if(var == 3). The reason is if you accidentally write = instead of == you will get compiling code with an annoying bug if you write the constant on the right. If you have it on the left, you will instead get a compilation error, which is much nicer to handle. (I don't do this myself though, and the only reason is that I don't like how it looks.)

There are some other stuff that I would consider bad design, like when you are resetting the value of cardNumber several times. However, this is a direct consequence of not having separate functions.


Don't declare to throw if you don't throw

The constructCharSequence declares throws IOException but it will never throw that.

Pay attention to the specs

It's extremely important to pay attention to the spec,
so you implement what is required,
and you don't miss your target,
or even, shoot for the wrong target.

In this example:

  [...] return a string that contains all unique two-character strings whose first character comes from the first string and second character comes from the second string

For the input strings "ABCD", "EFG" your method returns
"EA EB EC ED FA FB FC FD GA GB GC GD",
which fails the specs.
A passing string would be for example: "AE AF AG BE BF BG CE CF CG DE DF DG"

Watch out for logical errors

Read this:

    if (firstString.length() <= secondString.length()) {
        biggerString = firstString;
        smallerString = secondString;

The code paraphrased:
if the first string is shorter, then the bigger string is the first string.
Shouldn't that be the other way around?
This way would have made more sense:

    if (firstString.length() < secondString.length()) {
        biggerString = secondString;
        smallerString = firstString;

Duplicated code

In these lines,
the code for combining the two characters is duplicated:

if (!returnedString.contains("" + firstString.charAt(i) + secondString.charAt(j) + "")) {
    returnedString = returnedString + firstString.charAt(i) + secondString.charAt(j) + " ";

It would be better to put firstString.charAt(i) + secondString.charAt(j) into a local variable and use that in the two expressions.

Half-baked constructCharSequence

The constructCharSequence method is poorly named.
Since it's defined to return a String,
we already know that it constructs some sort of character sequence,
so the name says nothing new.
createUniqueCharPairs would be better.

And it doesn't finish the job.
It returns a string with an extra space at the end.
Callers of this method need extra knowledge of this,
and trim if necessary.
It would have been better to trim the string before returning.

Inefficient implementation

!returnedString.contains is inefficient.
For example,
when both strings contain unique characters,
the (growing) returnedString will be traversed from start to end in every iteration.
You could use a Set or a boolean[] to track the characters that were already used.

Suggested implementation

With the above suggestions applied:

public String createUniqueCharPairs(String firstString, String secondString) {
    Set<Character> seenFirst = new HashSet<>();
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < firstString.length(); ++i) {
        char first = firstString.charAt(i);
        if (seenFirst.contains(first)) {
            continue;
        }
        seenFirst.add(first);

        Set<Character> seenSecond = new HashSet<>();

        for (int j = 0; j < secondString.length(); ++j) {
            char second = secondString.charAt(j);
            if (seenSecond.contains(second)) {
                continue;
            }
            seenSecond.add(second);

            builder.append(" ").append(first).append(second);
        }
    }
    return builder.substring(1);
}

Although the assignment explicitly said to use string concatenation,
the use of a StringBuilder instead is trivially easy to understand,
and it's good to adopt good practices like this one early.

I also changed the trimming logic,
opting to append space + char1 + char2,
and at the end return the result without the first space char.
This is slightly more efficient than trimming.

And here are some JUnit tests to verify it actually works as expected:

@Test
public void test_ABCD_EFGH() {
    assertEquals("AE AF AG AH BE BF BG BH CE CF CG CH DE DF DG DH", createUniqueCharPairs("ABCD", "EFGH"));
}

@Test
public void test_ABCD_EFG() {
    assertEquals("AE AF AG BE BF BG CE CF CG DE DF DG", createUniqueCharPairs("ABCD", "EFG"));
}

@Test
public void test_ABAB_EFG() {
    assertEquals("AE AF AG BE BF BG", createUniqueCharPairs("ABAB", "EFG"));
}

@Test
public void test_ABAB_EFEF() {
    assertEquals("AE AF BE BF", createUniqueCharPairs("ABAB", "EFEF"));
}


The names 'txtX' and 'txtY' don't say anything about the domain as 'line', or 'length' do. Someone would need to see how are you using that variable to figure out what it is.

If you want to make the code more readable, make explanatory variables and helper descriptive methods for example

bool fitsInCurrentLine = col+dx<=maxCol;
if( fitsInCurrentLine ) col += dx;
else moveToNextLine();

instead of

if(col+dx<=maxCol)col += dx;
else{
    col = 2;
    line += 1;
}

When I read the last one, I had to figure out "how" you were doing the thing to know "what" you were doing.

Note that I did not write the moveToNextLine method but you get the Idea of what is happening. Considering col = 2; line += 1;. Is it necessary to know that the initial col is 2? or Should I only know that you are moving to the next line if the line wraps?

It reads more like "well written prose" (as Uncle Bob in his book 'CleanCode' says)

You can do similar with the else block.

In the method setPosition, I think the correct name for the parameters is x and y instead of dx or dy given that they are not changes but just absolute values.

This if statement in the update method could be its own method

void Cursor::blink(){
    bool isTimeToChangeState = (clock.getElapsedTime().asMilliseconds()-lastTime)>blinkPeriod;
    if( isTimeToChangeState ){
        visible = !visible;
        lastTime = clock.getElapsedTime().asMilliseconds();
    }
}

void Cursor::update(){
    cursorLine.setFillColor(color);
    cursorLine.setSize(sf::Vector2f(thickness, length));
    blink();
    cursorLine.setPosition((col-1)*(length*0.6)+txtX, (line-1)*(length*1.2)+txtY);
}

Finally, by reading

cursorLine.setPosition((col-1)*(length*0.6)+txtX, (line-1)*(length*1.2)+txtY);

you can sort of guess what is txtX. Is it the position of the text area? why just don't just put textAreaX and textAreaY, not perfect (I mean, for sure there should be a better name) but at least it improves a little the readability. In the book "clean code" you can find "A name that makes you go into the code to see that it tries to identify, is a bad name"

That's all I would recommend based on the book and experiences I've got as a developer. Happy coding!


Parent implementation different to child implementation

I'm not sure what your question is about recursiveLevel, but printing only when recursiveLevel == 0 seems like pretty weird behaviour to me.  If you only care about the outermost level of your data structure, then why even bother recursing?

I'm also puzzled by what you are trying to accomplish by introducing the enterChild...() methods.  What does "child" mean — that the method should only be called when recursiveLevel > 0?

Or perhaps you mean to have ReadOnlyFilter::enterClass() chain to the superclass implementation?

struct ReadOnlyFilter: public BaseFilter {
    virtual enterClass(ClassData& classData, int recursiveLevel) {
        if (classData->isReadOnly()) {  // isReadondOnly() in original code
            BaseFilter::enterClass(classData, recursiveLevel);
        }
    }
    // etc.
}


Your usage of Data.Map is sound. I see nothing that could be improved as long as you stay with Data.Map.

If you give all of the functions explicit type declarations, so that the Monomorphism Restriction doesn't apply, you can use generic integral types:

mapTotal :: Integral i => Map a i -> i

Some quick style-related things you could change:

First:

(\x -> case x of
  Nothing -> Just 1
  Just n -> Just (n+1))

... is the same as

Just . maybe 1 (+1)

Second:

You don't need parens around many of your function calls; if you have something like a +.- (foo bar baz) ¤:* b, it means the same thing as a +.- foo bar baz ¤:* b because every operator has lower precedence than function application.

Third:

You use very long indentations. A tip is to insert newlines after = and before control structures like case to make the code more compact. I find this style to be quite good.