texts: Rearranging an array such that positive and negative elements are at alternate positions

texts:
We are given an array in which we have equal number of positive and negative elements.

We have to rearrange this array such that all positive and negative elements are at alternate positions and also, respective order should be maintained. N i.e. the size of array can be: 1<=N<=\$10^6\$ .  No additional data structure can be used

INPUT:

1 2 3 -1 -2 -3

OUTPUT:

1 -1 2 -2 3 -3

My code was accepted but it exceeded the time limit for a case. How can I make my code more efficient by reducing its time complexity?

My code:

import java.util.*;
 class A{
 public static void main(String args[])
 {
     Scanner s=new Scanner(System.in);
     int n=s.nextInt();
     int a[]=new int[n];
     for(int i=0;i<n;i++)
         a[i]=s.nextInt();
     rearrange(a);
     for(int i=0;i<n;i++)
         System.out.print(a[i]+" ");
 }

public static void rotateright(int a[],int l,int r)
{
    int temp=a[r];
    for(int i=r;i>l;i--)
    {
        a[i]=a[i-1];
    }
    a[l]=temp;
}
public static void rearrange(int a[])
{
    int n=a.length;
    int i=0,j=0;
    while(i<n)
    {
        if(i%2==0)    //even index should have positive element
        {
            if(a[i]>0)     //already positive
                i++;
            else               //for negative
            {
                j=i+1;
                while(j<n)      //finding next positive
                {
                    if(a[j]>0)
                        break;
                    j++;
                }
                rotateright(a,i,j);    //making even index positive
                i++;
            }
        }
        else            //odd index should have negative element
        {
            if(a[i]<0)   //already negative
                i++;
            else           //for positive
            {
                j=i+1;
                while(j<n)          //finding next negative
                {
                    if(a[j]<0)
                        break;
                    j++;
                }
                rotateright(a,i,j);     //making odd index negative
                i++;
            }
        }
    }
}
}


texts:
I've spent the last few evenings learning PHP, CSS and HTML through Codecademy and now on Team Treehouse. My goal is to progress with PHP over the next year or two and perhaps obtain Zend cert.

Anyway, I've worked on a simple calculator to test what I've learned. I'd like to see, (given the same 'functionality')what more experienced programmers would come up with.  I think this would enhance my learning curve.

I've used a switch statement, because I'm not sure if it's possible to do something like this:

Variable = Math Operator

Var1 = User Input
Var2 = User Input

Variable3 = Var1 Variable Var2

Example, if you entered *, 2, 2, Variable 3 would = 4.

I tried a few ways but could not make it work, so had to settle with a switch which seems cumbersome.

<?php
$input1    = $_GET["num1"];
$input2    = $_GET["num2"];
$input3    = $_GET["symbol"];
$mathinput = "Not Selected";

switch ($input3) {
    case "*":
        $input3    = "*";
        $mathinput = "Multiplication";
        $result    = $input1 * $input2;
        break;
    case "/":
        $input3    = "/";
        $mathinput = "Division";
        $result    = $input1 / $input2;
        break;
    case "+":
        $input3    = "+";
        $mathinput = "Addition";
        $result    = $input1 + $input2;
        break;
    case "-":
        $input3    = "-";
        $mathinput = "Subtraction";
        $result    = $input1 - $input2;
        break;
    default:
        $input3    = "0";
        $mathinput = "Invalid Operator";
}
if ($input3=="0"){
    echo '

You have entered a bad operator

' ;
}
else{
    echo '

Result: ' . $result . '

';
}
?>


texts:
Activating jQuery tabs from URL #id is www.somedomain.com/index.php#tab3

Given this my best shot, and it does work but I feel it could be far far better.

Please tell me if this is totally shockingly bad JS.

$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
    //On Click Event
$("ul.tabs li").click(function (e) {
    e.preventDefault();
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".tab_content").hide(); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active ID content
});
if(document.location.hash!='') {
    //get the index from URL hash
    var tabName = window.location.hash;
    $(tabName).show(); //Show tab from url hash
    var tabNumber = tabName.substr(4,1); //shorten #tab2 to just last digit "2"
    $("ul.tabs li:nth-child(tabNumber)").addClass("active").show();
} else {

    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
}

});

Thank you


texts: SEDE Query to Find... Weird Question/Protect Combinations

texts:
I was interested in finding some of the weirdest question/protection combinations, basically out of curiosity.

I heuristically defined this as:

Low view counts
Not a moderator/SE employee
From users who protect multiple questions

I'm... let's just say not an expert in SQL. Though this query works, it feels super inefficient (especially the 2x left join, it seems plausible that could be a single join).

Looking basically for any feedback. I used this site to format things, so hopefully it's more readable than the mess it was before I started formatting it.

You can play with it here if your curiosity is also too strong to resist ;)

DECLARE @postViews int
SET @postViews = ##postView##
SELECT [Post Link] = ph.PostId,
       [User Link] = ph.UserId,
       Protected.ProtectCount,
       Unprotected.UnprotectedCount
FROM PostHistory ph
JOIN Posts p ON ph.PostID=p.id
LEFT JOIN
  (SELECT count(UserID) AS ProtectCount,
          PostID
   FROM PostHistory ph
   WHERE ph.PostHistoryTypeID=19
   GROUP BY PostID) AS Protected ON Protected.PostID=ph.PostID
LEFT JOIN
  (SELECT count(ph.UserID) AS UnprotectedCount,
          PostID
   FROM PostHistory ph
   WHERE ph.PostHistoryTypeID=20
   GROUP BY PostID) AS Unprotected ON Unprotected.PostID=ph.PostID
WHERE ph.UserID IN
    (SELECT top ##NumbUsers## ph.UserId
     FROM PostHistory ph
     JOIN Posts p ON ph.PostID=p.id
     WHERE ph.PostHistoryTypeId = 19
       AND p.ViewCount < @postViews
       /* exclude former moderators */
       AND ph.UserID NOT IN (419,
                             1228,
                             1288,
                             19679,
                             23354,
                             50049,
                             59303,
                             102937,
                             106224,
                             246246,
                             -1)
     GROUP BY ph.UserId
     ORDER BY COUNT (ph.UserId) DESC)
  AND ph.PostHistoryTypeId = 19
  AND p.ClosedDate IS NULL
  AND p.ViewCount < @postViews
  AND isnull(Protected.ProtectCount,0) != isnull(Unprotected.UnprotectedCount,0)
ORDER BY ph.UserId


texts: Grabbing SQL records: Nullable bool to bool

texts:
So I have a method that does a lookup in an existing List<T>, populated elsewhere by grabbing the records from a SQL table holding configuration data for each state where we do business. This method just looks up in the list by state abbreviation and then returns the value of a Boolean field in the record.

public bool StateRoundsToQuarterHour(int recordID, string stateAbbrev)
    {
        bool? result = null;

        try
        {
            // Query our existing list of StateConfig objects for a match, then return the value of RoundMinutes.
            result = (from x in listStateConfig
                           where x.State == stateAbbrev
                           select x.RoundMinutes).First();

        }
        catch (Exception e)
        {
            // if state not found, email error and continue
            string strMessage = String.Format("Error: {0} Inner Exception {1}", Convert.ToString(e.Message) + Environment.NewLine, Convert.ToString(e.InnerException));

            // log and email error
            ErrorContinue(recordID, strMessage);

        }

        // as long as we found a result, we're happy
        if(result != null)
        {
            return (bool)result;
        }
        else
        {
            string strMessage = String.Format("State {0} does not exist in table, but RecordID {1} belongs to that state.", stateAbbrev, recordID);

            // log and email error
            ErrorContinue(recordID, strMessage);

            return false;   // if the state doesn't exist, we'll default to rounding is not required
                            // We send an alert about the state not existing, so we'll be able to act on it
        }

    }

The List may not contain a result, so in that case the query will not find anything and remain null. I'm not entirely happy with the method using a nullable Boolean internally and then casting it to non-nullable to use in the return, but I don't want the return type of the method to be nullable. Is this a reasonable approach? Where can this be improved?


texts:
I am writing simple code to accept/read a input of lines from a text file, split it into my class variables, sort them and finally display the input in the ordered form. But I have been struggling for the past couple of days to split the read line in appropriate manner.

static void Main(string[] args)
{
    List<MyClass> myClassList = new List<MyClass>();

    string strpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\input.txt";
    if (File.Exists(strpath))
    {
        using (var sr = new StreamReader(strpath))
        {
            string[] strFirst, strSecond;
            while (sr.Peek() >= 0)
            {
                strFirst = Regex.Split(sr.ReadLine().Replace(" ", ""), "([0-9]+)");
                strFirst = Regex.Split(sr.ReadLine().Replace("|", ">>"), "([0-9]+)");

                myClassList.Add(new MyClass
                {
                   Number = strFirst[1], Name = strFirst[2], Separator = strFirst[1].Split(">>")}
                });

            }
        }
    }

    myList = GetResults(myClassList);

    foreach (MyClass myclass in myList)
        {
            Console.WriteLine(myclass[i].Number + myclass[i].Name + myclass[i].Separator);
            Console.WriteLine(myclass.Name);
        }

        Console.ReadLine();
    }

Sample input line from text file, which I want to process:

var input = "5 string one | 5.2 string two | 5.2.1 string three\r\n" +
                    "5 string four >> 5.6 string five >> string six\r\n" +
                    "1 string seven | 1.1 string eight | 1.1.1 string nine\r\n";

Output:

MyClass
Number[0] = 5
Name[0] = string one
Separator[0] = |

Number[1] = 5.2
Name[1] = string two
Separator[1] = |

Number[2] = 5.2.1
Name[2] = string three
Separator[2] =


texts: Is there a better or more elegant way to code this CSV cell-parser (using CSVReader)?

texts:
I'm currently doing my first internship and had to create an application that will check through the first row of a CSV for valid or invalid input. Is there a more elegant way to code or to refactor my FileValidator class? This is my first time programming in a professional environment, so I'm still trying to learn how to "clean code". If you see any bad practices, please say so.

package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;

import au.com.bytecode.opencsv.CSVReader;

public class FileValidator {
    private CSVReader reader;
    List<String[]> row;
    private File file;
    private String date;
    private String[] header;

    private final static Logger log = Logger.getLogger(FileValidator.class);
    private static final int HEADER_MAX_COLUMNS = 4;
    private static String[] BUSINESS = { "SAFC", "FLDB", "RGSP", "JKAA",
            "FAKJ", "SFDK" };

    public boolean readFile(File newFile, String date) // receive File object
                                                        // and date provided by
                                                        // user
    {
        try {
            this.file = newFile;
            reader = new CSVReader(new FileReader(file));
            row = reader.readAll();
            header = row.get(0); // assign first row of CSV to a List<String[]>
                                    // (list of Strings(cells))
            this.date = date;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public boolean validateFile() {
        boolean[] checkHeader = { checkNumColumns(), checkIfEmpty(),
                checkDate(), checkFileName(), checkBusiness() };

        for (int i = 0; i < checkHeader.length; i++) {
            if (checkHeader[i] == false)
                return false;
        }
        return true;
    }

    public boolean checkNumColumns() // check if number of header columns are
                                        // correct
    {
        if (!(row.get(0).length <= HEADER_MAX_COLUMNS)) {
            return false;
        } else
            return true;
    }

    public boolean checkIfEmpty() // check if any cells are empty
    {
        for (int i = 0; i < HEADER_MAX_COLUMNS; i++) {
            if (!header[i].trim().equals(header[i]) || header[i] == null
                    || header[i] == "" || header[i].length() == 0)
                return false;
        }
        return true;
    }

    public boolean checkDate() // check if user-given date matches header:
                                // cell[0]
    {
        if (!header[0].equals(date)) {
            return false;
        } else
            return true;
    }

    public boolean checkFileName() // check if file name equals cell[1]
    {
        if (!header[1].equals(file.getName())) {
            return false;
        } else
            return true;
    }

    public boolean checkBusiness() // check if business name (cell[2]) matches
                                    // any from static string list
    {
        for (int i = 0; i < BUSINESS.length; i++) {
            if (header[3].equals(BUSINESS[i]))
                return true;
        }
        return false;
    }
}


texts: Is this an appropriate approach and layout for conditionally continuing execution in bash?

texts:
I've seen others use && for conditionally continuing execution in bash, and found it effective but rather ugly. (I'm not sure if there's a better name for this technique.)

do_something && something_else && the_next_thing

Then I found out that you can simply wrap things in parentheses just because you feel like it. (And in my original motivation was to return to easily return to the calling folder.)

So in the following script, I tried combining those techniques. (The motivation for the script is an attempt to install RabbitVCS for development.)

Questions:

is combining && and () in this way "idiomatic" for bash?
similarly, is using () to return to the calling folder appropriate
how's my indentation? (I normally program in Python ;) )

    #! /bin/bash

    # CC0 To the extent possible under law, the person who associated CC0
    # with this work has waived all copyright and related or neighboring
    # rights to this work. https://creativecommons.org/publicdomain/zero/1.0/

    # Required folders (must exist beforehand):
    #  * Source code and script folders (see export statements below)
    #  * Nautilus 3: ~/.local/share/nautilus/python-extensions
    #  * CLI: /usr/bin (always exists)
    #  * GEdit: ~/.local/share/gedit/plugins

    # Out of scope for this script:
    #  * Setting up folders above
    #  * Keeping RabbitVCS source code up-to-date

    # Set customisable folder paths:
    # Source code, cloned from GitHub
    export SOURCE_FOLDER=~/Code/rabbitvcs
    # User scripts location for RabbitVCS CLI (must be in .bashrc or equivalent)
    export SCRIPT_FOLDER=~/Code/scripts

    if [ "$1" = "--help" ] || [ -z $1 ] || [ "$2" ];
    then

        # if "--help" is called, or too many or too few parameters given, display help
        echo "Install specified branch of RabbitVCS with Nautilus, Gedit and CLI clients."
        echo "(Assumes prerequisites are installed and target branch and folders exist.)"
        echo "Usage: install-rabbitvcs-branch "

    else
        ( # parentheses so that we return to original folder

            # install all prerequisites, even the obvious ones
            # (package names as used in Ubuntu 13.10)
            # (also triggers prompt for sudo password as soon as possible)
            sudo apt-get install gedit git hicolor-icon-theme ipython meld subversion python python-configobj python-dbus python-dulwich python-gobject python-gobject-2 python-gtk2 python-gtkspell python-nautilus python-simplejson python-support python-svn -qq && (

                # kill existing Nautilus and RabbitVCS processes (if they exist)
                pgrep -f nautilus && nautilus -q
                pgrep -f service.py && xargs kill

                # checkout requested branch
                cd $SOURCE_FOLDER && git checkout $1 && (

                    # (re)install RabbitVCS library
                    sudo python setup.py check && sudo python setup.py install && (

                        # (re)install RabbitVCS clients
                        echo "Installing RabbitVCS clients..."
                        cp clients/nautilus-3.0/RabbitVCS.py ~/.local/share/nautilus/python-extensions
                        cp clients/gedit/rabbitvcs-plugin.py ~/.local/share/gedit/plugins
                        cp clients/gedit/rabbitvcs-gedit3.plugin ~/.local/share/gedit/plugins
                        cp clients/cli/rabbitvcs $SCRIPT_FOLDER
                        echo "done."
                    )
                )
            )
        )
    fi


texts:
I am a beginner in Python, and I made a Morse translator that converts letters to Morse, and Morse to letters (where a decimal point is 'dot' and underscore is 'dash'). Is there any way I could make my code shorter and more efficient? For reference, here's the translation of Morse to letter characters.
dot = '.'
dash = '_'
letter_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
               'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
morse_list = [dot + dash, dash + dot * 3, dash + dot + dash + dot, dash + dot * 2, dot, dot * 2 + dash + dot,
              dash * 2 + dot, dot * 4, dot * 2, dot + dash * 3, dash + dot + dash, dot + dash + dot * 2,
              dash * 2, dash + dot, dash * 3, dot + dash * 2 + dot, dash * 2 + dot + dash, dot + dash + dot,
              dot * 3, dash, dot * 2 + dash, dash * 3 + dot, dot + dash * 2, dash + dot * 2 + dash,
              dash + dot + dash * 2, dash * 2 + dot * 2]
# The for loop below prints the entire translation (Eg. 'A: ._ B: _...') so the user could reference it
for n in range(len(letter_list)):
    print(letter_list[n] + ': ' + morse_list[n], sep=' ', end=' ', flush=True)
while True:
    print("\nTYPE 'EXIT' if you want to EXIT.")
    user_input = input("INPUT LETTERS OR MORSE CHARACTERS (DECIMAL AND UNDERSCORE) TO CONVERT."
                       "\nSEPERATE LETTERS WITH SPACES: ")
    # Converts user input into an iterable list
    user_list = user_input.split()
    if user_input == 'EXIT':
        print("THANK YOU FOR USING THE MORSE TRANSLATOR")
        break
    for i in range(len(user_list)):
        if user_list[i] in letter_list:
            for n in range(len(morse_list)):
                if user_list[i] == letter_list[n]:
                    print(morse_list[n], sep=' ', end='  ', flush=True)
        elif user_list[i] in morse_list:
            for n in range(len(letter_list)):
                if user_list[i] == morse_list[n]:
                    print(letter_list[n], sep=' ', end='  ', flush=True)


texts: Handling an array of Promises where we care about the outcome of each

texts:
Given some data (a job) like, which is from listening in on a RabbitMQ queue:

let data = {
  "format_oid":["35474527960032","2595837960032"],
  "name": "abc123-def456-gug010",
};

Where we want to loop over the format_oid (one or many) and get more information about them.

We have a Job handler class that will retrieve this information, by passing in the whole data object, extracting the format_oid array and handling getting/receiving the format information to be passed back.

class Handler {
  constructor() {}

  handleJob(job) {
    return this._extractJob(job);
  }

  _extractJob(job) {
    let request = job.format_oid.map( (releaseId) => {
      return this._requestReleaseFormat(releaseId);
    });
    return Promise.all(request.map(p => p.catch(e => e)));
  }

  _requestReleaseFormat(formatId) {
    return new Promise( (resolve, reject) => {
      let release = this._fakeRelease(formatId);
      let errorMessage = `No such release for ${formatId}`;
      return this._isRelease(release) ? resolve(release) : reject(errorMessage);
    });
  }

  _isRelease(release) {
    return Object.keys(release).length !== 0 && !release.constructor !== Object;
  }

  _fakeRelease(formatId) {
    // Not quite written so currently just a
    // fake function that returns either an empty
    // object or an object with random data
    // But this would call an API with the formatId to
    // receive data about the formatId if available.
  }
}

module.exports = Handler;

I'm slightly breaking the point of Promise.all with this current code as I need to know about the failure's to retrieve information as well as the successes.  Is there a better way to do this without misusing Promise.all?


texts: How to best reference a mongoose schema into another schema

texts:
Hi there I would like to know if there's a better way of specifying an array of objects on a mongoose schema.
This is what I have at the moment:
const mongoose = require('mongoose')

const photoCode = mongoose.Schema(
  {
    value: { type: String, trim: true, unique: true },
    status: {
      type: String,
      enum: ['valid', 'expired', 'attributed'],
      default: 'valid',
    },
  },
  { strict: true, timestamps: true },
)

const photoCodeSchema = new mongoose.Schema({
  code: [photoCode],
})

module.exports = mongoose.model('PhotoCode', photoCodeSchema)


texts:
In an effort to rid my code of jQuery, I wrote a custom global event management/handling system. I was expecting this to be hard as, from what I've read, most people don't create their own. It's far simpler than most libraries I've seen. Is there a flaw in this method? What are the benefits of using something like EventEmitter.js?

var EvtMgr = function() {
  var events = {};
  this.on = function(evtName, callback) {
    if (!events[evtName]) events[evtName] = [];
    events[evtName].push(callback);
  }
  this.trigger = function(evtName, evtObj) {
    events[evtName].forEach(function(callback) {
      callback(evtObj);
    });
  }
  this.remove = function(evtName) {
    delete events[evtName];
  }
}

exports.evtMgr = new EvtMgr();

Then I can register listeners with evtMgr.on('foo', function(evtObj) {…});


texts:
I'm aware that there are existing questions about JButtons, but I haven't found anything that's asking exactly what I'm trying to figure out.

I inherited a Java project that has a horrible structure; my job is essentially to go through and fix it. The project includes a GUI, which is where this question becomes relevant.

In the state that I inherited it, the GUI's buttons simply didn't work correctly. I don't have an exact way to describe it, but essentially the previous programmer neglected event-driven programming, and set up a bunch of busy-wait threads waiting for things to happen. It did not work.

In the course of trying to get the buttons to trigger the correct state change in the GUI, I completely reworked the buttons into this form:

JButton button = new JButton(new AbstractAction("A button") {
    @Override
    public void actionPerformed(ActionEvent ae) {
        doStuff();
    }
});

As far as I can tell, this works correctly; doStuff() is called, which handles the GUI's state transitions. This form is the result of struggling with different methods suggested at various places; this is the only one that I was able to get to work.

My specific question at this point is, firstly, is there a problem with using an AbstractAction in this form to listen for a button click, and secondly, is there a better way to do this? Most everyone uses button.addActionListener(), which is what I couldn't get to work correctly. If it's at all relevant, there are multiple buttons on some GUI states.

I'm using Java 7 for this. However, it wouldn't be a huge deal to switch to Java 8.


texts:
Problem

Balanced number is the number that the sum of all digits to the left of the middle digit(s) and the sum of all digits to the right of the middle digit(s) are equal. The middle digit(s) should not be considered when determining whether a number is balanced or not.

If the number has an odd number of digits then there is only one middle digit, e.g. 92645 has middle digit 6; otherwise, there are two middle digits , e.g. 1301 has middle digits 3 and 0.

Given a number, find if it is balanced or not. Number passed is always Positive. Return the result as String.

My solution

I solved it. But I am not sure, how to fold the similarly looking code for odd and even lengths.

data ListLength a = ListLength {list :: [a], len :: Int} deriving Show

digs :: Integral x => x -> ListLength x
digs 0 = ListLength [0] 1
digs x = let
      helper :: Integral x => x -> [x] -> Int -> ListLength x
      helper 0 acc len = ListLength acc len
      helper n acc len = helper (n `div` 10) ((n `mod` 10) : acc) $ len + 1
  in
      helper x [] 0

balancedNum :: Int -> String
balancedNum n | n > 0 = let digits = digs n
                            middle = (len digits) `div` 2
                        in
                          if even (len digits) then
                            let (left, right) = splitAt (middle - 1) (list digits) in
                              if (sum left) == (sum $ drop 2 right) then
                                "Balanced"
                              else
                                "Not Balanced"
                          else
                            let (left, right) = splitAt middle (list digits) in
                              if (sum left) == (sum $ tail right) then
                                "Balanced"
                              else
                                "Not Balanced"
              | otherwise = error "Number must be positive"


texts: Looping over files to create a dataframe

texts:
As part of my NLP project at work, I want to loop over all files that are either PDF of docx in the same directory. The end purpose is to create a dataframe with text content of the files in one column and filename in another column. So I wrote a loop to open them up, extract the text, add it to a list as below:
import docx
import PyPDF2

    #wordfile
    def ReadingText(filename):
        doc=docx.Document(filename)
        comp = []
        for par in doc.paragraphs:
            comp.append(par.text)
        return '\n' .join(comp)

    #PDF files
    def Readingpdf(pdfname):
        pdfRead=PyPDF2.PdfFileReader(pdfname)
        comp = ""
        for i in range(pdfRead.getNumPages()):
            comp += pdfRead.getPage(i).extractText()
        return comp

After that I will specify directory and perform the loop as below:
directory= "my directory"
all_together = []
name = []

for filename in os.listdir(directory):
    if filename.endswith(".docx"):
        f = ReadingText(filename)
        all_together.append(f)
        name.append(filename)
    elif filename.endswith(".pdf"):
            try:
                pdf = Readingpdf(filename)
                all_together.append(pdf)
                name.append(filename)
            except:
                pass

    df = pd.DataFrame({"article":name,"text":all_together})

df.head(10)

It is doing the job, but I really want to develop myself so I want to know your opinion - be as harsh as you can.


texts: A class to add and select players within a database

texts:
I have a question and want to know if my class is considered object oriented.

class Player {

    private $db

    function __construct($db) {

        $this->db = $db;

    }

    public function set_player($name, $position, $number, $team) {

        try {

            $sql = 'INSERT INTO players SET playername = :playername, position = :position, teamid = :teamid, jersey = :jersey';
            $this->db->prepare($sql);
            $s->bindValue(':playername', $name);
            $s->bindValue(':teamid', $team);
            $s->bindValue(':position', $position);
            $s->bindValue(':jersey', $number);
            $s->execute();

        } catch (PDOEXception $e) {

            echo 'Could not add player, please try again.';
            exit();

        }

    }

    public function get_player($id) {

        $result = $this->db->query('SELECT * FROM players WHERE id =' . $id);
        $row = $result->fetch(PDO::FETCH_OBJ);
        return $row;

    }

}

In another file  I will use this class in this way

include_once('./includes/global.php');

$player = new Player($pdo);

$player->set_player(Chris, Forward, 13, 1);

echo $player->get_player(1)->playername;
echo $player->get_player(1)->position;


texts: Copying files into Dropbox folder from command line

texts:
I made the following code.
Since it is a Batch, any kind of problems can appear.
Please review it and point any problems when copying files into Dropbox!
Its intent is that you will copy a file into an Dropbox folder.
Its syntax is dropbox <files-to-dropbox> <dropbox-folder-to-copy-to>.

@echo off
set dropbox=%userprofile%\dropbox
if exist %dropbox% (if not exist %dropbox%\%2 mkdir %dropbox%\%2) else (echo Get Dropbox for PC before using this!)
if exist %dropbox%\%2 copy %1 %dropbox%\%2
@echo on

It would have been cool to use the dropbox tag as well, right?


texts: Size of the largest connected component in a grid in Python

texts:
Given an R x C grid of 1s and 0s (or True and False values), I need a function that can find the size of the largest connected component of 1s. For example, for the following grid,

grid = [[0, 1, 0, 1],
        [1, 1, 1, 0],
        [0, 1, 0, 0],
        [0, 0, 0, 1]]

The answer is 5.

Here is my implementation:

def largest_connected_component(nrows, ncols, grid):
    """Find largest connected component of 1s on a grid."""

    def traverse_component(i, j):
        """Returns no. of unseen elements connected to (i,j)."""
        seen[i][j] = True
        result = 1

        # Check all four neighbours
        if i > 0 and grid[i-1][j] and not seen[i-1][j]:
            result += traverse_component(i-1, j)
        if j > 0 and grid[i][j-1] and not seen[i][j-1]:
            result += traverse_component(i, j-1)
        if i < len(grid)-1 and grid[i+1][j] and not seen[i+1][j]:
            result += traverse_component(i+1, j)
        if j < len(grid[0])-1 and grid[i][j+1] and not seen[i][j+1]:
            result += traverse_component(i, j+1)
        return result

    seen = [[False] * ncols for _ in range(nrows)]

    # Tracks size of largest connected component found
    component_size = 0

    for i in range(nrows):
        for j in range(ncols):
            if grid[i][j] and not seen[i][j]:
                temp = traverse_component(i, j)
                if temp > component_size:
                    component_size = temp

    return component_size

Feel free to use the following code to generate random grids to test the function,

from random import randint

N = 20
grid = [[randint(0,1) for _ in range(N)] for _ in range(N)]

Problem: My implementation runs too slow (by about a factor of 3). Since I wrote this as a naive approach by myself, I am guessing there are clever optimizations that can be made.

Context: This is for solving the Gridception problem from Round 2 of Google Codejam 2018. My goal is to solve the problem in Python 3. As a result, there is a hard constraint of using only the Python 3 standard library.

I have figured out that this particular portion of the full solution is my performance bottleneck and thus, my solution fails to clear the Large Input due to being too slow.

Thank you so much!

Edit: Adding some timeit benchmarks

For a randomly generated 20 x 20 grid, my implementation takes 219 +/- 41 μs (a grid of 0s takes 30 μs, and a grid of 1s takes 380 μs).


texts: JavaScript-function for to convert a dash-separated string into camel case

texts:
I have to write a function which turns a string with the words separated by dashes ( - ) into a sentence using camel case notation.

I've had the following idea for an implemenation using the reduce-method of Array:

// -------- THE ACTUAL FUNCTION -------------------------

/**
* Converts a string with dashes as word-separators
*  to a string using camel case notation.
* --------------------------------------------------
* @param {String} Sentence-string with dashes (-)
*  as word-separators.
*
* @returns {String} Sentence-string in Camel Case
*  notation.
*  Returns an empty string as an indicator of failure.
* ---------------------------------------------------
* Usage-Example:
* dashedToCamelCase('north-east-east') // Returns 'northEastEast'
*/
function dashedToCamelCase( dashed ) {
  var ret;
  var parts;

  if (typeof dashed !== 'string' || !dashed) {
    return '';
  }

  parts = dashed.split('-');
  ret = parts[0].toLowerCase();
  parts = parts.slice(1);

  ret = parts.reduce(function(previous, current) {
    return previous +
      current.slice(0, 1).toUpperCase() +
      current.slice(1).toLowerCase();
  }, ret);

  return ret;
}

// -------- THE ACTUAL FUNCTION - END -------------------

// --- TESTING ---------------------------
var test = [ 'north',
             'north-east',
             'north-east-east',
             'south-west-west-north',
             'south-wEst-EaSt',
             'North-west-EAST',
             'NORTH-EAST-SOUTH-WEST',
             248,
             '' ];
var expect = [ 'north',
               'northEast',
               'northEastEast',
               'southWestWestNorth',
               'southWestEast',
               'northWestEast',
               'northEastSouthWest',
               '',
               '' ];

test.forEach(function(item, i) {
  dashedToCamelCase(item) === expect[i]
  ? console.log('%s passed.', i)
  : console.error('%s FAILED!', i);
});

I have seen similar functions which use the replace-method of String together with a function as a parameter. Still not convinced if I should keep with my solution ...

So:
Should I use an implementation using String.replace? Or are just some improvements needed?

I would like to try it out with a large amount of automatically created data.

Does someone know a good way for measuring the performance?


texts: Powershell script to create folders on remote servers

texts:
This is pretty much the first Powershell script I've ever done and I am here looking for a quick review of it. Is there something I could have done better? Is the format okay? I don't know much about expected standards, and this was cobbled together as a result of me wanting to learn.

$Company = Read-Host 'Enter Company Name:'
$Credentials = Get-Credential

Write-Host 'Thank you! Creating client FTP folder on ServerA.' -ForegroundColor Magenta -BackgroundColor White

Invoke-Command ServerA {mkdir ("e:\ftp\users\" + $args[0] + "\INCOMING")} -ArgumentList $Company -Credential $Credentials
Invoke-Command ServerA {mkdir ("e:\ftp\users\" + $args[0] + "\OUTGOING")} -ArgumentList $Company -Credential $Credentials

Write-Host 'Done. Now creating duplicate folder on ServerB.' -ForegroundColor Magenta -BackgroundColor White

Invoke-Command ServerB {mkdir ("e:\ftp\users\" + $args[0] + "\INCOMING")} -ArgumentList $Company -Credential $Credentials
Invoke-Command ServerB {mkdir ("e:\ftp\users\" + $args[0] + "\OUTGOING")} -ArgumentList $Company -Credential $Credentials

Write-Host 'Done.' -ForegroundColor Magenta -BackgroundColor White

Whenever we first set up a user for FTP, we have to set up a folder for them. The folder needs to be named after the company, and include "Incoming" and "Outgoing" subfolders. This needs to be created on ServerA, and the exact same thing created on ServerB. This script finds out what the company name is, checks credentials, and then creates the folders in the appropriate places.

Thoughts? Things I could research to improve it?


texts:
I would like to ask for code review for my LRU Cache implementation from leetcode.

  Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

  get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
  put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should
  invalidate the least recently used item before inserting a new item.

  Follow up:
  Could you do both operations in O(1) time complexity?

I make sure that I used the LinkedListNode class to make sure the solution is optimal with O(1) time complexity.

class ListNode(object):
    def __init__(self, key, val):
        self.val = val
        self.key = key
        self.next = None
        self.prev = None

class LinkedList(object):
    def __init__(self):
        self.head = None
        self.tail = None

    def insert(self, node):
        node.next, node.prev = None, None  # avoid dirty node
        if self.head is None:
            self.head = node
        else:
            self.tail.next = node
            node.prev = self.tail
        self.tail = node

    def delete(self, node):
        if node.prev:
            node.prev.next = node.next
        else:
            self.head = node.next
        if node.next:
            node.next.prev = node.prev
        else:
            self.tail = node.prev
        node.next, node.prev = None, None  # make node clean

class LRUCache(object):

    # @param capacity, an integer
    def __init__(self, capacity):
        self.list = LinkedList()
        self.dict = {}
        self.capacity = capacity

    def _insert(self, key, val):
        node = ListNode(key, val)
        self.list.insert(node)
        self.dict[key] = node

    # @return an integer
    def get(self, key):
        if key in self.dict:
            val = self.dict[key].val
            self.list.delete(self.dict[key])
            self._insert(key, val)
            return val
        return -1

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def put(self, key, val):
        if key in self.dict:
            self.list.delete(self.dict[key])
        elif len(self.dict) == self.capacity:
            del self.dict[self.list.head.key]
            self.list.delete(self.list.head)
        self._insert(key, val)

This passes the leetcode tests.


texts:
I used this code to give -h(help) options to my bash script. It's working fine and I wanted to get the code reviewed.

while true; do
        if [ "$1" != "-l" ] && [ "$1" != "-a" ] && [ "$1" != "-h" ] && [ "$1" != "" ];
        then
                output=$(curl -k -s -u "$username:$password" -H "X-Requested-With: Curl" -d "action=list&echo_request=1" "${!url}" | grep -B 2 -w $name | grep ID | head -1 | sed 's/[^0-9]*//g')
        fi
        case "$1" in
                "")
                        echo "use -h for usage information";;
                -h)
                        echo  "-a       add"
                        echo  "-d       delete"
                        echo  "-l       name all"
                        echo  "-sv      addvlan"
                        echo  "-mv      add multiple vlan"
                        echo  "-dv      del vlan"
                        echo  "-ar      add route"
                        echo  "-mr      add multiple route"
                        echo  "-dr      delete route";;
                -a)
                        add ;;
                -d)
                        delete ;;
                -l)
                        list ;;
                -sv)
                        addvlan ;;
                -mr)
                        multipleroute ;;
                -dv)
                        delvlan "$@" ;;
                -mv)
                        addmulvlan ;;
                -dv)
                        delvlan ;;
                -ar)
                        addroute ;;
                -dr)
                        delroute "$@" ;;
        esac
        break
done;


texts: Wrapping tuples to be used as keys in a Dictionary

texts:
I'm currently working on a project where I have to map some objects to several properties.

Basically I need a Dictionary with Tuples as keys and instances of MyClass as values.

As using tuples can quickly lead to an obscure (because of item1, item2... properties) and verbose code I decided to make a class to wrap the tuples.

class Key
{
    private Tuple<string, int, int, int> _impl;

    public Key(string unitID, int address, int comPort, int id)
    {
        _impl = new Tuple<string, int, int, int>(unitID, address, comPort, id);
    }

    public override int GetHashCode()
    {
        return _impl.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        return _impl.Equals(obj);
    }

    public override string ToString()
    {
        return _impl.ToString();
    }
}

That way I should take advantage of the Tuple class and avoid its inconvenients.

So I can write:

Dictionary<Key, MyClass> mapping = new Dictionary<Key, MyClass>();

Instead of:

Dictionary<Tuple<string, int, int, int>, MyClass> mapping = new Dictionary<Tuple<string, int, int, int>, MyClass>();

And look up the dictionary like this:

Key key = new Key("abc", 1, 5, 5464);
MyClass myInstance = mapping[key];

Is this implementation correct ? Is there a more proper way to achieve this ?


texts: Drawing a hollow rectangle of rows and column provided by the console application

texts:
This question was put forward by my senior to draw a hollow rectangle in C#, and with the condition that the rows and column would be specified by the user. I was stuck at first, but tried to code and after several hours I realized how it would be done, and then I accomplished the task.

I would like to share my code, as the beginners may get help out of it, and the experts can also look and propose, if they know any other alternative solution which would be composed of less code.

class Program
{
    static void Main(string[] args)
    {
        int arg1;
        int arg2;
        arg1 =Convert.ToInt16(Console.ReadLine());
        Console.ReadLine();
        arg2 = Convert.ToInt16(Console.ReadLine());
       // Console.WriteLine(arg1 + " " + arg2);
        for (int row = 1; row <= arg1; row++)
        {

            if (row == 1 || row == arg1)
            {
                for (int col = 1; col <= arg2; col++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }

            if (row < arg1 && row < arg1-1)
            {
                Console.Write("*");
                for (int i = 0; i < arg2-2; i++)
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                    Console.WriteLine();
            }

        }
        Console.ReadKey();
       // Console.ReadKey();
    }
}


texts:
I have removed a lot of the code, but you should get an idea of what I am doing:

<?php

$upOne = realpath(__DIR__ . '/..');
require_once $upOne . '/vendor/autoload.php';

use phpseclib\Net\SFTP;

$errors = array();
$fileData = array();
$inputArray = array();
$config = new CONFIG\Config();

if (empty($_POST['emailAdd'])) {
    $errors['emailAdd'] = '- Please input your Email address';
} else {
    if (!filter_var($_POST['emailAdd'], FILTER_VALIDATE_EMAIL)) {
        $errors['emailAdd'] = '- Please input your Email address';
    } else {
        $email = filter_var($_POST['emailAdd'], FILTER_SANITIZE_EMAIL);
        array_push($inputArray, $email);
    }
}

//Additional validation
...

if (!empty($errors)) {
    echo json_encode("failed");
} else {
    try {
        $dbh = new PDO("mysql:host=".$config::DB_HOST.";dbname=".$config::DB_NAME."", $config::DB_USER, $config::DB_PASSWORD);

        $stmt = $dbh->prepare("INSERT INTO emirates_user("...");

        if($stmt->execute()) {

            $lastId = $dbh->lastInsertId();

            if (isset($_FILES)) {
                foreach($_FILES as $file) {
                    $upload = UPLOAD\Upload::factory($config::TEMP_DIR);
                    $upload->file($file);

                    if(!$upload->get_errors()) {
                        $fileData[$results['full_path']] = $results['mime'];
                    }
                    else {
                        echo json_encode("failed");
                        break;
                    }
                }

                $date = date('_dmY_H:i:s');
                $pdf = new PDF\PdfGenerator($fileData, $inputArray, $date);

                if($pdf) {
                    $command = '/usr/bin/python /srv/www/vhosts/someurl/html/php/somefile.py';
                    exec($command, $retval);

                    if(isset($retval[0])  && $retval[0] === 'success') {
                        $mail = new PHPMailer;

                        .....

                        if(!$mail->send()) {
                            echo json_encode("failed");
                        } else {
                            $lstmt = $dbh->prepare("...");
                            ...

                            if($lstmt->execute()) {
                                echo json_encode("success");
                            }
                        }
                    } else {
                        echo json_encode("failed");
                    }
                }

            } else {
                echo json_encode("failed");
            }
        } else {
            echo json_encode("failed");
        }
    }
    catch(Exception $e) {
        echo json_encode("failed");
    }
}

First of all, I validate the user input.  If this fails, I return a failed message back to my Ajax.  If all is ok, the process begins.  This script inserts into a database, generates a PDF, SFTP's the file using a Python script, sends an email etc.  All of these actions could potentially go wrong.  I have handled things via conditional statements to make sure the code is executed correctly.  If not, then I return a failed message again.  If it makes it to the very end, I return a success message.

My Ajax is like so (not the whole function, just the done and failure sections):

.done(function (response) {
    if(response == 'failed'){
        window.location.replace('failure.html');
    } else {
        window.location.replace('success.html');
    }
}).fail(function (jqXHR, textStatus) {
    console.log(textStatus);
});

So if the response is failed, I display a failed page.

Really, I am just seeking advice as to whether this type of logic is ok.  Should I maybe return more detail information about the error so I know what it relates too?  If so, how would I handle this in Ajax?


texts: Bare bones implementation of Java HashMap

texts:
I've done a minimal implementation of a HashMap. Invite comments.

public class HashMap<K, V> {

    private final int size = 16;
    private Node<K, V>[] arr;

    public HashMap(){

        arr = new Node[size];
    }

    class Node<K, V> {

        private int index;
        private K key;
        private V value;
        private Node<K, V> next;

        protected Node(K key, V value){
            this.key = key;
            this.value = value;
        }

    }

    private int getHashCodeForKey(K key){
        int result = 7;
        return 31 * result + (key != null ? key.hashCode() : 0);
    }

    public V get(K key){

        int hashcode = getHashCodeForKey(key);
        int index = hashcode & size;
        Node head = arr[index];
        while(head != null){
            if(head.key == key) return (V) head.value;
            head = head.next;
        }
        return null;

    }

    public void put(K key, V value){
        Node curr = new Node(key, value);
        int hashcode = getHashCodeForKey(key);
        int index = hashcode & size;

        if(arr[index] == null){
            arr[index] = curr;
        }else{
            Node head = arr[index];
            curr.next = head;
        }
    }

}


texts:
This is my try at the proxy pattern.

What do you Pythoneers think of my attempt?

class Image:
    def __init__( self, filename ):
        self._filename = filename
    def load_image_from_disk( self ):
        print("loading " + self._filename )
    def display_image( self ):
        print("display " + self._filename)

class Proxy:
    def __init__( self, subject ):
        self._subject = subject
        self._proxystate = None

class ProxyImage( Proxy ):
    def display_image( self ):
        if self._proxystate == None:
            self._subject.load_image_from_disk()
            self._proxystate = 1
        print("display " + self._subject._filename )

proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") )
proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") )

proxy_image1.display_image() # loading necessary
proxy_image1.display_image() # loading unnecessary
proxy_image2.display_image() # loading necessary
proxy_image2.display_image() # loading unnecessary
proxy_image1.display_image() # loading unnecessary

Output:

loading HiRes_10Mb_Photo1
display HiRes_10Mb_Photo1
display HiRes_10Mb_Photo1
loading HiRes_10Mb_Photo2
display HiRes_10Mb_Photo2
display HiRes_10Mb_Photo2
display HiRes_10Mb_Photo1


texts: Count of anagrams of a text in a given string

texts:
Problem Statement:

  Given a word and a text, return the count of the occurences of
  anagrams of the word in the text. For eg. word is “for” and the text
  is “forxxorfxdofr”, anagrams of “for” will be “ofr”, “orf”,”fro”, etc.
  So the answer would be 3 for this particular example.

The above is an interview question I saw here.

Here is the code I have written:

#include <iostream>
#include<string.h>
#include<stdio.h>
using namespace std;

int equals(char* A, char* B)
{
    int i,len = strlen(A);
    int a[26],b[26];
    for(i=0;i<26;i++)
    {
        a[i]=0;
        b[i]=0;
    }
    for(i=0;i<len;i++)
    {
        a[A[i]-'a']++;
    }
    for(i=0;i<len;i++)
    {
        b[B[i]-'a']++;
    }
    for(i=0;i<26;i++)
    {
        if(a[i]!=b[i])
            return 0;
    }
    return 1;
}
int check(char* s1, char* s2)
{
    int i,j,len1=strlen(s1), len2=strlen(s2), flag=0;
    char arr[len2];

    for(i=0;i<=len1-len2;i++)
    {
         for(j=0;j<len2;j++)
         {
             arr[j]=s1[i+j];
         }
        if(equals(arr,s2))
            flag++;
    }
    return flag;
}
int main()
{
    char text[50]="",pat[50]="";
    cout<<"Enter original string: ";
    cin>>text;
    cout<<"Enter pattern string: ";
    cin>>pat;
    cout<<"No. of anagrams in text are :"<<check(text,pat);
    return 0;
}

(I have also mentioned this code in my technical blog).

Questions:

How can I improve my code in terms of its complexity and efficiency? As of now, it uses an approach similar to the naive string matching algorithm.
Is my method to not compute all permutations and instead use an array good enough, or are there any better approaches?


texts: "The Story of a Tree" solved using depth-first search

texts:
Found this problem in hackerrank.

  One day Bob drew a tree, with \$n\$ nodes and \$n-1\$ edges on a piece of paper. He soon discovered that parent of a node depends on the root of the tree. The following images shows an example of that:

  Learning the fact, Bob invented an exciting new game and decided to play it with Alice. The rules of the game is described below:

  Bob picks a random node to be the tree's root and keeps the identity of the chosen node a secret from Alice. Each node has an equal probability of being picked as the root.
  Alice then makes a list of \$g\$ guesses, where each guess is in the form \$u, v\$ and means Alice guesses that \${\rm parent}(v) = u\$ is true. It's guaranteed that an undirected edge connecting \$u\$ and \$v\$ exists in the tree.
  For each correct guess, Alice earns one point. Alice wins the game if she earns at least \$k\$ points (i.e., at least \$k\$ of her guesses were true).

  Alice and Bob play \$q\$ games. Given the tree, Alice's guesses, and the value of \$k\$ for each game, find the probability that Alice will win the game and print it on a new line as a reduced fraction in the format p/q.

Solution: There is a tree with some edges marked with arrows. For every vertex in a tree you have to count how many arrows point towards it. For one fixed vertex this may be done via one depth-first search (DFS). Every arrow that was traversed during DFS in direction opposite to its own adds 1. If you know the answer for vertex \$v\$, you can compute the answer for vertex \$u\$ adjacent to \$v\$ in \$O(1)\$.

It's almost the same as for \$v\$, but if there are arrows \$u→v\$ or \$v→u\$, their contributions are reversed. Now you can make the vertex \$u\$ crawl over the whole graph by moving to adjacent vertices in the second DFS.

def gcd(a, b):
    if not b:
        return a
    return gcd(b, a%b)

def dfs1(m, guess, root, seen):
    '''keep 1 node as root and calculate how many arrows are pointing towards it'''
    count = 0
    stack = []
    stack.append(root)
    seen.add(root)
    while len(stack):
        root = stack.pop(len(stack)-1)
        for i in m[root]:
            if i not in seen:
                seen.add(i)
                count += (1 if root in guess and i in guess[root] else 0)
                stack.append(i)
    return count

def dfs2(m, guess, root, seen, cost, k):
    '''now make every node as root and calculate how many nodes
       are pointed towards it; If u is the root node for which
       dfs1 calculated n (number of arrows pointed towards the root)
       then for v (adjacent node of u), it would be n-1 as v is the
       made the parent now in this step (only if there is a guess, if
       there is no guess then it would be not changed)'''
    stack = []
    stack.append((root, cost))
    seen.add(root)
    t_win = 0
    while len(stack):
        (root, cost) = stack.pop(len(stack)-1)
        t_win += cost >= k
        for i in m[root]:
            if i not in seen:
                seen.add(i)
                stack.append((i, cost - (1 if root in guess and i in guess[root] else 0) + (1 if i in guess and root in guess[i] else 0)))
    return t_win

q = int(raw_input().strip())
for a0 in xrange(q):
    n = int(raw_input().strip())
    m = {}
    guess = {}
    seen = set()
    for a1 in xrange(n-1):
        u,v = raw_input().strip().split(' ')
        u,v = [int(u),int(v)]
        if u not in m:
            m[u] = []
        m[u].append(v)
        if v not in m:
            m[v] = []
        m[v].append(u)
    g,k = raw_input().strip().split(' ')
    g,k = [int(g),int(k)]
    for a1 in xrange(g):
        u,v = raw_input().strip().split(' ')
        u,v = [int(u),int(v)]
        if u not in guess:
            guess[u] = []
        guess[u].append(v)
    cost = dfs1(m, guess, 1, seen)
    seen = set()
    win = dfs2(m, guess, 1, seen, cost, k)
    g = gcd(win, n)
    print("{0}/{1}".format(win/g, n/g))


texts:
I am looking to simplify this code as it is to bulky for what it is doing. I do not need to stick to jQuery.

Simple checkbox in html relates to adding underline to some text:

$("#houseOrCar").on("change", function () {
    if ($(this).is(":checked") ) {
        $("#houseChosen").css("text-decoration", "none");
        $("#carChosen").css("text-decoration", "underline");
    }
    else  {
        $("#houseChosen").css("text-decoration", "underline");
        $("#carChosen").css("text-decoration", "none");
    };
});


texts: A get_extents helper function for Boost.MultiArray in C++

texts:
This is a follow-up question for A filled_multi_array Template Function for Boost.MultiArray in C++. Based on G. Sliepen's answer, there is another get_extents template function mentioned for handling retrieving boost::detail::multi_array::extent_gen<NumDims> type size information from a multi_array. I am trying to implement this get_extents template function here.
template<class T, std::size_t NumDims>
auto get_extents(const boost::multi_array<T, NumDims>& input) {
    boost::detail::multi_array::extent_gen<NumDims> output;
    std::vector<size_t> shape_list;
    for (size_t i = 0; i < NumDims; i++)
    {
        shape_list.push_back(input.shape()[i]);
    }
    std::copy(shape_list.begin(), shape_list.end(), output.ranges_.begin());
    return output;
}

I am trying to copy shape content into the output object. In general cases, boost::detail::multi_array::extent_gen object is always constructed by boost::extents[][][].... However, I am not sure how to use boost::extents in this context and I fill the values of shape information into output.ranges_ instead. It works with the following testing code.
auto filled_multi_array1 = filled_multi_array(boost::extents[3][4][2], 1.0);
auto filled_multi_array2 = filled_multi_array(get_extents(filled_multi_array1), 2.0);

//  Checking shape
std::cout << "filled_multi_array2.shape()[0]:" << filled_multi_array2.shape()[0] << std::endl;
std::cout << "filled_multi_array2.shape()[1]:" << filled_multi_array2.shape()[1] << std::endl;
std::cout << "filled_multi_array2.shape()[2]:" << filled_multi_array2.shape()[2] << std::endl;

for (decltype(filled_multi_array2)::index i = 0; i != filled_multi_array2.shape()[0]; ++i)
    for (decltype(filled_multi_array2)::index j = 0; j != filled_multi_array2.shape()[1]; ++j)
        for (decltype(filled_multi_array2)::index k = 0; k != filled_multi_array2.shape()[2]; ++k)
            std::cout << filled_multi_array2[i][j][k] << std::endl;

All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
A filled_multi_array Template Function for Boost.MultiArray in C++

What changes has been made in the code since last question?
The extent_gen function implementation is the main part in this question.

Why a new review is being asked for?
The shape_list which type is std::vector<size_t> in get_extents function is used just for copying shape data into output.ranges_. The reason why I create a std::vector for this operation is that there is neither .begin() function nor .end() function in input.shape(). Something like std::copy(input.shape().begin(), input.shape().end(), output.ranges_.begin()); doesn't work. If there is any possible improvement, please let me know.


texts: Generating words based on a list of letters

texts:
I wrote a program to take a list of letters and from every permutation of them and check that against the dictionary and print out valid words.  The constraints are that there is a control letter which means that letter must be in the word, and you can't repeat any letters.

Everything works, but the running time is way too long.  I'm hoping to get some feedback on how to cut down my running time in O-notation. Also, if you know the running times of the built in function, that would be great. Also, comment if my code style is not what it should be for Python.

import itertools
from multiprocessing import Process, Manager

dictionary_file = '/usr/share/dict/words'
letter_list = ['t','b','a','n','e','a','c','r','o']
control_letter = 'e'

manager = Manager()
word_list = manager.list()

def new_combination(i, dictionary):
    comb_list = itertools.permutations(letter_list,i)
    for item in comb_list:
        item = ''.join(item)
        if(item in dictionary):
            word_list.append(item)
    return

def make_dictionary():
    my_list = []
    dicts = open(dictionary_file).readlines()
    for word in dicts:
        if control_letter in word:
            if(len(word) >3 and len(word)<10):
                word = word.strip('\n')
                my_list.append(word)
    return my_list

def main():
    dictionary = make_dictionary()
    all_processes = []
    for j in range(9,10):
        new_combo = Process(target = new_combination, args = (j,dictionary,))
        new_combo.start()
        all_processes.append(new_combo)
    while(all_processes):
        for proc in all_processes:
            if not proc.is_alive():
                proc.join()
        all_processes = [proc for proc in all_processes if proc.is_alive()]
        if(len(all_processes) == 0):
            all_processes = None

    print list(set(word_list))

if __name__ == '__main__':
    main()


texts:
I have a (large) number of nodes and (triangular) cells, e.g.,

cells_nodes = [
    [0, 3, 1],
    [0, 2, 3]
    ]

This example represents the small mesh

(Please call me Picasso from here on out.)

Now, I would like to create the edges for these meshes (in red above), specifically edge–node and edge–cell relations. For the above example, the result would be

[[0], [1], [1], [0, 1], [0]]  # edge -> cells
[[1, 3], [2, 3], [0, 2], [0, 3], [0, 1]]  # edge -> nodes
[[0, 3, 4], [1, 2, 3]]  # cell -> edges

The problem I wasn't able to solve to my satisfaction is to identify the individual edges. Note that [1, 2] is the same edge as [2, 1]. Using frozensets works, but is perhaps overkill. This code

import numpy

def create_edges(cells_nodes):
    from collections import defaultdict
    d = defaultdict(list)
    # Loop over lists all pairs of nodes, i.e., all possible edges.
    cells_edges = []
    for local_edges in [[0, 1], [1, 2], [2, 0]]:
        # Put those into a list of frozensets so [21, 54] == [54, 21].
        cells_edges.append(
                map(frozenset, cells_nodes[:, local_edges])
                )
        # Store the edges in a dictionary, store the corresponding cell too.
        for k, f in enumerate(cells_edges[-1]):
            d[f].append(k)

    edges_nodes = numpy.array(map(list, d))
    edges_cells = list(d.values())

    edge_indices = dict(zip(d.keys(), range(len(d))))
    cells_edges = numpy.vstack(
        [[edge_indices[edge] for edge in c] for c in cells_edges]
        ).T

    return edges_nodes, edges_cells, cells_edges

if __name__ == '__main__':
    import meshzoo
    vertices, cells = meshzoo.rectangle.create_mesh(
            0.0, 1.0,
            0.0, 1.0,
            2, 2
            )
    edges_nodes, edges_cells, cells_edges = create_edges(cells)

    print(vertices)
    print
    print(cells)
    print
    print(edges_nodes)
    print
    print(edges_cells)
    print
    print(cells_edges)

works, but it too slow. The applications of map, and likely the explicit loops are killing the performance.

$ python -m cProfile -o program.prog e.py
$ snakeviz program.prog

Any idea of how improve this?


texts: Print all possible sequences that could have created this BST

texts:
I was working through Cracking The Coding interview, and I couldn't wrap my brain around their solution to one of the problems, so I ended up coming up with my own that, IMHO, is a lot cleaner and easier to read. Would love your feedback. Here is the actual problem:

"A binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all of the arrays that could have led to this tree."

In other words, what are all of the possible sequences of values that could have led to this tree.

For reference, here is a link to the 'official' solution.

And here is what I came up with

public class AllSequences {
public LinkedList<LinkedList<TreeNode>> allSeqs;

public AllSequences(TreeNode root) {
    allSeqs = new LinkedList<>();
    LinkedList<TreeNode> pre = new LinkedList<>();
    LinkedList<TreeNode> poss = new LinkedList<>();

    buildSeqs(pre, poss, root);
    for (LinkedList<TreeNode> ll : allSeqs) {
        for (TreeNode n : ll) {
            System.out.print(n.data + " ");
        }
        System.out.println();
    }
}

private void buildSeqs(LinkedList<TreeNode> pre, LinkedList<TreeNode> poss, TreeNode root) {
    pre.add(root);
    if (root.left != null) {
        poss.add(root.left);
    }
    if (root.right != null) {
        poss.add(root.right);
    }

    if (poss.isEmpty()) {
        allSeqs.add(pre);
    }

    for (TreeNode n: poss) {
        LinkedList<TreeNode> temp = (LinkedList<TreeNode>) pre.clone();
        LinkedList<TreeNode> ptemp = (LinkedList<TreeNode>) poss.clone();
        ptemp.remove(n);
        buildSeqs(temp, ptemp, n);
    }
}

public static void main(String[] args) {
    TreeNode root = new TreeNode(10);
    root.left = new TreeNode(5);
    root.right = new TreeNode(15);
    root.left.right = new TreeNode(7);
    root.left.left = new TreeNode(3);

    AllSequences all = new AllSequences(root);
}
}

Granted mine ends up with a set of LinkedLists of possible input sequences, not arrays, but it would be easy enough to convert that if the interviewer was a stickler about it. It seems to correctly print out for all of my hand-coded, relatively small test cases.


texts:
How can I combine these if statements to make this a little cleaner and be less repetitive?

$(document).keydown(function(e){
    if (e.keyCode == 38) {
        if($html.hasClass('client-loading') || canAnim === false) {
            return false;
        }
        var $prevProj = $('.project-current').prev('.project');
        $prevProj.click();
    }

    if (e.keyCode == 40) {
        if($html.hasClass('client-loading') || canAnim === false) {
            return false;
        }
        var $nextProj = $('.project-current').next('.project');
        $nextProj.click();
    }

    // Prevent rapid clicking
    if ( e.keyCode == 38 || e.keycode == 40 ) {
        canAnim = false;

        setTimeout(function(){
            canAnim = true;
        },2000);
    }
});


texts: Optionally running some code on a background thread

texts:
Is this a good method to optionally run some code on a background thread depending on a configuration setting? This will primarily be called from an ASP.NET front-end (although others are possible) under Framework 3.5. I'm attempting to keep this as DRY as possible.

Dim sendEmails = Sub()
                     Dim emailToSend As New SendEmailRequest()
                     TransferCommonValuesTo(emailToSend, request, sendingUser)
                     usersToSendEmailTo.ForEach(Sub(u)
                                                    TransferValuesTo(emailToSend, u, m_EmailMessageMerger.GetMergedMessage(request.Message, u))
                                                    m_EmailSender.Send(emailToSend)
                                                End Sub)
                 End Sub

If cfg.SendBulkEmailUsingBackgroundThread Then
    Dim worker As New Thread(sendEmails)
    worker.IsBackground = True
    worker.Start()
Else
    sendEmails()
End If


texts:
An API (I have no control over) gives me a bunch of Collections (Lists, to be precise,) and I need the elements that are common to all of them. In this concrete case, I'm trying to find Selenium WebElements that match several selectors. But I went off on a Yak-Shaving spree and tried to figure out how to make an intersection of a stream of Collections. This is what I came up with (and I think it works, at least my tests say so.)

/**
 * Given a stream of collections, intersect it.
 *
 * @param stream A stream of collections you want to intersect
 * @param <T> Any item that has a decent .equals()/.hashCode().
 *            Seriously, don't attempt this without a working .equals()/.hashCode().
 * @return The unique(!) elements present in *all* collections in the stream
 */
public static <T> Collection<T> intersect(Stream<Collection<T>> stream) {
  // Optimization: sorting by size so that the biggest constrainer
  // (smallest collection) comes first
  final Iterator<Collection<T>> allLists = stream.sorted(
        (l1, l2) -> l1.size() - l2.size()
  ).iterator();

  final Set<T> result = new HashSet<>(allLists.next());
  while(allLists.hasNext()) {
      result.retainAll(allLists.next());
  }
  return result;
}

I fiddled around with Collectors in the beginning, but that seemed to be too convoluted, since it'd require the unit element to be some special class.

Any better way of doing it? Is this woefully inefficient? I think its complexity is somewhere around O(n) where n should be the total number of elements in all the collections.


texts:
Before everybody yells at me about why I wrote a PDO wrapper class, it's to avoid writing try/catch, prepare(), execute(), etc. each time a query should be executed.

I have pretty big website, so instead of repeating:

$sth =  $dbh->prepare('Some query');
$dbh->BindParam('x', $x);
$dbh->BindParam('y', $y);
 //..etc
$sth->execute();

a few thousands times I can simply do:

$res = $dbh->query('Some query', $x1, $y1, //etc);
$res->fetch(\PDO::FETCH_OBJ)

And also because I want to do some operations on each query like count queries, execution time, etc.

Is this Singleton wrapper really bad or overkill?

namespace App\Database {

class Database
{

 static private $PDOObject;

 function __construct()
 {
     if(!self::$PDOObject) {

        try{

            self::$PDOObject = new \PDO('mysql:host=127.0.0.1;dbname=test', 'username', 'pentagonpassword');

        }
        catch(\PDOException $e) {
             //handle exception
             throw $e;
        }
        return self::$PDOObject;

      }
 }

 public function query($query, ...$params)
 {

   try
   {
    //start timer and other stuff (count queries etc)
    $sth = self::$PDOObject->prepare($query);
    $sth->execute($params);
    //end timer
    return $sth;
    }
    catch(\PDOException $e)
    {
       throw $e;
    }

 }

 public function lastid($name = NULL)
 {
   return self::$PDOObject->LastInsertId($name);
 }

  //Other methods that processes some complex stuff

}
}


texts: Continued fraction with relative precision in Python

texts:
I have the following recursive function to compute the continued fraction:

$$s_i = \frac{a_{i}}{b_{i} + s_{i+1}}$$

The relative error is defined as:

$$\text{Delta} = \frac{s_n - s_{n-1}}{s_{n}}$$

Here is the implementation in Python, of Lentz's method for computing continued fractions:

import numpy as np

def n_continued_fraction(a, b, err, i_min=3):
    f = lambda i : a(i)
    g = lambda i : b(i)
    d = lambda i : 1./g(0) if i == 0 else 1./(g(i) + f(i) * d(i-1))
    h = lambda i : 0 if i == -1 else f(0)/g(0) if i == 0 else (h(i-1) * g(i) + h(i-2) * d(i-1) * f(i)) * d(i)
    delta_h = lambda i : h(i) - h(i-1)

    i_final = i_min

    while np.abs(delta_h(i_final)) > err * np.abs(h(i_final)):
        i_final += 1

    return h(i_final)

and you can test it with e.g.

a = lambda i : (i+1.)
b = lambda i : (i+5.)

n_continued_fraction(a, b, 1.e-16)

Is there a better method to do it? Am I doing anything wrong?


texts:
How would you review this way of implementing a std::static_cast

template <typename ToType, typename FromType>
ToType safe_static_cast( const FromType &from )
{
    assert( from <= std::numeric_limits<ToType>::max() );
    assert( from >= std::numeric_limits<ToType>::min() );

    return static_cast<ToType>(from);
}

Is assertions on the limits a good way?


texts: Any way to optimize this already fast Python solution to Project Euler 31 (coin sums)?

texts:
This is a Python solution for all general cases. Any suggestions at all would be appreciated; in my opinion it's already quite good! Here's a link to the problem.

from timeit import default_timer as timer

def count_coins(target, operands):
    ways_to_make = [1] # list of ways to make x at index x
    for o in range(0, len(operands)):
        for t in range(target + 1):
            # initialise undefined target
            if len(ways_to_make) <= t:
                ways_to_make.append(0)
            # add ways to make number recursively
            if t >= operands[o]:
                ways_to_make[t] += ways_to_make[t - operands[o]]

    return ways_to_make[target]

start = timer()
ans = count_coins(200, [1, 2, 5, 10, 20, 50, 100, 200])
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts:
I have here some code which is working but it seems to be a lot of coding to do here. I would really appreciate if someone could make this simpler.

click

Close

                <?php get_search_form(); ?>

Your recent searches

search 1

search 1

search 1

search 1

search 1

click

Close

favourite page

favourite page

favourite page

favourite page

favourite page

and here is my js

$(".icontap").toggle(function(){
    $("#search").animate({height:40},200).css( "overflow", "hidden" );
    $(".search-w .widget-close").css("visibility","visible");
    $(".search-w .biz-widget").css("border-color", "#335ccc");
},function(){
    $("#search").animate({height: $("#search").get(0).scrollHeight}, 200 );
    $(".search-w .widget-close").css("visibility","visible");
    $(".search-w .biz-widget").css("border-color", "#335ccc");
});

$(".closeme").click(function(){
    $("#search").animate({height:0},200);
    $(".search-w .biz-widget").css("border-color", "#fff");
    $(".search-w .widget-close").css("visibility","hidden");
});

/*******/

$(".icontap2").toggle(function(){
    $("#favourite").animate({height:40},200).css( "overflow", "hidden" );
    $(".favourite-w .widget-close").css("visibility","visible");
    $(".favourite-w .biz-widget").css("border-color", "#335ccc");
},function(){
    $("#favourite").animate({height: $("#favourite").get(0).scrollHeight}, 200 );
    $(".favourite-w .widget-close").css("visibility","visible");
    $(".favourite-w .biz-widget").css("border-color", "#335ccc");
});

$(".closeme2").click(function(){
    $("#favourite").animate({height:0},200);
    $(".favourite-w .biz-widget").css("border-color", "#fff");
    $(".favourite-w .widget-close").css("visibility","hidden");
});

Or see this in fiddle.


texts: How to optimize jQuery to run on asp.net web form updatepanel?

texts:
I wrote this Jqeury to make it work with asp.net update panel. I know i do little bit of hacking to make it work just. I want to get some help in how to optimize and remove the hacks from my script.

<script type="text/javascript">

    //get all elemnt with class .resource-download
    $.each($(".resource-download"), function () {
        var fileExtension = getFileExtension(this.href);
        if (fileExtension == "" || fileExtension != "pdf") {
            $(this).addClass("hideLinke");
        }
    });

    //load script agine
    function init() {
        $.each($(".resource-download"), function () {
            var fileExtension = getFileExtension(this.href);
            if (fileExtension == "" || fileExtension != "pdf") {
                $(this).addClass("hideLinke");
            }
        });
    }

    // getFileExtension
    function getFileExtension(fileURL) {
        if (fileURL.indexOf('.') === -1) { return ""; } //check for no extension
        return fileURL.split('.').pop();
    }

    //loadGridLayout
    function loadGridLayout() {
        $('#grid-wrapper').masonry();
        $('.selectpicker').selectpicker();

        $('.btn-hamburger').click(function () {
            $('.lts-nav').toggleClass('expanded');
            $('.wrapper').toggleClass('wrapper-expanded');
        });

        /* iPhone Site Search Styling */
        var searching = false;

        $('.search-add-on').click(function () {
            if ($(window).width() < 480) {
                $('.section-1 .search-hideable').toggle();
                $('.section-1 .site-search').focus();
                searching = true;
            }
        });

        $('.site-search').blur(function () {
            if ($(window).width() < 480) {
                $('.section-1 .search-hideable').toggle();
                searching = false;
            }
        });

        $(window).resize(function () {
            if ((searching || !$('.site-search').is(':visible')) && $(window).width() > 480) {
                $('.section-1 .search-hideable').toggle(true);
                $('.section-1 .search-hideable').removeAttr('style');
                searching = false;
            }
        });
    }
    //add script to script manager
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(init);
    prm.add_endRequest(loadGridLayout);

</script>


texts: Group Anagrams Together approach in Java

texts:
Given an array of words, print the count of all anagrams together in
  sorted order (increasing order of counts). For example, if the given
  array is {“cat”, “dog”, “tac”, “god”, “act”}, then grouped anagrams
  are “(dog, god) (cat, tac, act)”. So the output will be 2 3.

  Input:

  First line consists of T test case. First line of every test case
  consists of N, denoting the number of words in array. Second line of
  every test case consists of words of array.

  Output:

  Single line output, print the counts of anagrams in increasing
  order.

  Constraints:

  1<=T<=100 1<=N<=50

  Example:

    Input:

    2

    5

    act
    cat tac god dog

    3 act cat tac

    Output:

    2 3

    3

My approach:

/*package whatever //do not write package name here */

import java.util.Scanner;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.lang.StringBuffer;

class GFG {

    private static void getAnagramCt (String[] words) {
        HashMap <String, Integer> anag = new HashMap<>();
        List<Integer> counts = new ArrayList<> ();
        Set<String> keys;
        String[] keyArr;

        anag.put(words[0],0);

        keys = anag.keySet();
        keyArr = keys.toArray(new String[keys.size()]);

        for (int i = 1; i < words.length; i++) {
            String elem = words[i];
            for (int j = 0; j < keyArr.length; j++) {
                if (isAnagram(elem,keyArr[j])) {
                        int ct = anag.get(keyArr[j]);
                        anag.put(keyArr[j],ct+1);
                }
                else {
                    if (j == keyArr.length - 1) {
                        anag.put(elem, 0);
                    }
                    else {
                        continue;
                    }
                }
            }
        keys = anag.keySet();
        keyArr = keys.toArray(new String[keys.size()]);
        }

        for (Map.Entry<String,Integer> entry : anag.entrySet()) {
            //System.out.println(entry.getKey() + " " + entry.getValue());
            counts.add(entry.getValue() + 1);
        }
        Collections.sort(counts);

        for (Integer elem : counts) {
            System.out.print(elem + " ");
        }
        System.out.println();
    }

    private static boolean isAnagram (String word2, String word1) {
        if (word1.length() != word2.length()) {
            return false;
        }

        StringBuffer word = new StringBuffer(word2);
        for (int i = 0; i < word1.length(); i++) {
            if (word.length() == 0) {
                return false;
            }
            else if (word.indexOf((String.valueOf(word1.charAt(i)))) == -1) {
                return false;
            }
            else {
                int ind = word.indexOf((String.valueOf(word1.charAt(i))));
                word.deleteCharAt(ind);
            }
        }

        return true;
    }

    public static void main (String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int numTests = sc.nextInt();

        for (int i = 0; i < numTests; i++) {
            int numWords = sc.nextInt();
            String[] words = new String[numWords];

            for (int j = 0; j < numWords; j++) {
                words[j] = sc.next();
            }
            getAnagramCt(words);
        }
    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference


texts: Program to implement Merge Sort Algorithm

texts:
So, I just learned the Merge Sort algorithm from Youtube and tried implementing it. Is this the most efficient way to do it?

public class MergeSort {

private static void merge(int[] left, int[] right, int[] arr) {
int i=0, j=0, k=0;
while(i<left.length && j<right.length) {
if(left[i]<right[j]) {
    arr[k++]=left[i++];
    }
else {
    arr[k++]=right[j++];
    }
}
while(i<left.length)
    arr[k++] = left[i++];
while(j<right.length)
    arr[k++] = right[j++];
}

public static void mergeSort(int[] arr) {
if(arr.length<2)
    return;

int mid = arr.length/2;
int[] left = new int[mid];
int[] right;

//checking wether array is even or not, based on which right array length           is defined
int rightLength;
if((arr.length&1)==0) //if even
    rightLength = mid;
else
    rightLength = mid+1;
right = new int[rightLength];

//assign values to left and right arrays from the original array
for(int i=0;i<mid;i++)
    left[i] = arr[i];

for(int j=0;j<rightLength;j++)
    right[j] = arr[j+mid];

mergeSort(left);
mergeSort(right);
merge(left,right,arr);

}

}


texts:
I got a coding problem to solve and was wondering if I got a commonly acceptable and efficient/clean solution. If there is a better way I'd gladly hear it.

  given a list with numbers return if the sum of 2 elements in the list = k

def is_sum_of_2nums_in_list_k(list, k):
    for i in list:
        if k - i in list:
            return True
    return False

They also mentioned you get bonus points if you do it in one 'pass'. What does this mean?


texts: Add effective error handling to Python Notebook in Azure Synapse Analytics

texts:
I have some Python code that runs as part of an Azure Synapse Analytics Apache Spark Notebook (or Synapse Notebook) and would like to add effective error handling.  The code simply executes a given SQL script against the database.  The code runs but I sometimes see errors like attempt to use closed connection.  I would like to do the following:

Improve code that I wrote through peer review
Can I improve the error handling?  eg pseudo-code if connection still open close connection
The code using SQL auth works.  I would like to authenticate as the Managed Identity, I've tried using the object id of the MI in the connection string with Authentication=ActiveDirectoryMsi but it didn't work

Cell1 - parameters
pAccountName = 'someStorageAccount'
pContainerName = 'someContainer'
pRelativePath = '/raw/sql/some_sql_files/'
pFileName = 'someSQLscript.sql'

Cell 2 - main
import pyodbc
from pyspark import SparkFiles

try:
    # Add the file to the cluster so we can view it
    sqlFilepath = f"""abfss://{pContainerName}""" + "@" + f"""{pAccountName}.dfs.core.windows.net{pRelativePath}{pFileName}"""
    sc.addFile(sqlFilepath, False)

    # Open the file for reading
    with open(SparkFiles.getRootDirectory() + f'/{pFileName}', 'r') as f:
        lines = f.read()    ## read all text from a file into a string

    # Open the database connection
    conn = pyodbc.connect( 'DRIVER={ODBC Driver 17 for SQL Server};'
                        'SERVER=someServer.sql.azuresynapse.net;'
                        'DATABASE=someDatabase;UID=batchOnlyUser;'
                        'PWD=youWish;', autocommit = True )

    # Split the script into batches separated by "GO"
    for batch in lines.split("GO"):
        conn.execute(batch)  # execute the SQL statement

except:
    raise

finally:
    # Tidy up
    conn.close()


texts: Objective-C class for placing UI elements based on screen size

texts:
I'm always programmatically creating and laying out UI elements in multiple ViewControllers and I've wanted an easy way to get relevant Screen information (sizes/points) globally using a helper class.

I've created a FlexibleScreen class and would like some constructive feedback.  In addition to the typical code review feedback of format, syntax, etc I would really like to know how well this solves my problem functionally and what suggestions you have about the design or what additional functionality I could add.

FlexibleScreen.h

#import <Foundation/Foundation.h>

@interface FlexibleScreen : NSObject

+(CGSize)getScreenSize;
+(CGPoint)getCenter;
+(CGPoint)getCenterWithY:(double)y;
+(CGPoint)getCenterWithX:(double)x;

@end

FlexibleScreen.m

#import "FlexibleScreen.h"

@interface FlexibleScreen()

@property (assign) CGRect bounds;
@end

@implementation FlexibleScreen

+(CGSize)getScreenSize
{
    return CGSizeMake([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
}

+(CGPoint)getCenter
{
    return CGPointMake([[UIScreen mainScreen] bounds].size.width/2, [[UIScreen mainScreen] bounds].size.height/2);
}

+(CGPoint)getCenterWithY:(double)y
{
    return CGPointMake([[UIScreen mainScreen] bounds].size.width/2, y);
}

+(CGPoint)getCenterWithX:(double)x
{
    return CGPointMake(x, [[UIScreen mainScreen] bounds].size.height/2);
}

@end

Implementing Code

#import "FlexibleScreen.h"

...

CGRect headerFrame = CGRectMake(0, 0, [FlexibleScreen getScreenSize].width, HEADER_HEIGHT);
CGRect footerFrame = CGRectMake(0, [FlexibleScreen getScreenSize].height-FOOTER_HEIGHT, [FlexibleScreen getScreenSize].width, FOOTER_HEIGHT);

...

[label setCenter:[FlexibleScreen getCenterWithY:0]];

UPDATE:
As I used this more I realized I wanted it to be a lot simpler. Here is my latest version GitHub: UIScreen+Flexible.


texts:
I came across this thread and I am working on the same problem. My best algorithm passes 6/11 cases while the algorithm in the other thread does indeed pass 8/11 cases. Running time trials with random input my algorithm is significantly quicker (8 to 12 times depending on input) then the one in the other thread. So I am pretty confused on these results.

I came across this thread and I am working on the same problem. My best algorithm passes 6/11 cases while the algorithm in the other thread does indeed pass 8/11 cases. Running time trials with random input my algorithm is significantly quicker (8 to 12 times depending on input) then the one in the other thread. So I am pretty confused on these results.

Aside from empirical testing these are the reasons I think my code should be running better than the other implementation for these reasons.

Appending to a StringBuilder and printing once should be more
efficient than multiple print statements.
Better reduction in logic for binary addition. As well doing addition
from the bit index’s least significant 0 in both BitSets, a and b,
reduces unnecessary computation.
Using BufferedReader has a lot less overhead than using Scanner.
BitSet really didn’t offer much difference in the terms of
performance than a character array but reversing the binary strings
is a waste and the StringBuilder reverse is not the best
performance.

Can anyone shed some light onto why the seemingly slower algorithm does better in the testing?

Version 2

private static String floatSum()
{
    final Scanner input = new Scanner(System.in);
    final int number_bits = input.nextInt();
    final int number_queries = input.nextInt();
    final StringBuilder builder = new StringBuilder();
    final char[] a = new StringBuilder(input.next()).reverse().toString().toCharArray();
    final char[] b = new StringBuilder(input.next()).reverse().toString().toCharArray();

    for(int queries = 0; queries < number_queries; queries++)
    {
        switch(input.next().charAt(4))
        {
            case 'a':
                a[input.nextInt()] = input.next().charAt(0);
                break;
            case 'b':
                b[input.nextInt()] = input.next().charAt(0);
                break;
            default:
                final int index = input.nextInt();

                int carry_bit = 0;

                for(int iter = index - 1; iter >= 0; iter--)
                {
                    if(a[iter] == b[iter])
                    {
                        carry_bit = a[iter] - 48;
                        break;
                    }
                }

                builder.append(index == number_bits ? carry_bit : ((a[index] - 48) + (b[index] - 48) + carry_bit) % 2);
                break;
        }

    }

    return builder.toString();
}


texts: Get element at a specific position in a string with separator

texts:
I have created the following user defined function in order to get the element at the position POSI (starting at 0) in the string EXPR. Each element is separated by a separator (SEP).

CREATE FUNCTION [dbo].[getStringElement_Expr_Pos_Sep]
(
  @EXPR nvarchar(MAX),
  @POSI int,
  @SEP nchar
)
RETURNS nvarchar(MAX)
AS
BEGIN
  IF (@POSI < 0)
  BEGIN
    RETURN N'ERROR'
  END

  -- determine the occurrence of SEP in EXPR
  DECLARE @NB_SEP int
  SET @NB_SEP = LEN(@EXPR) - LEN(REPLACE(@EXPR, @SEP, ''))

  -- if there is no SEP -> return original EXPR
  IF (@NB_SEP = 0)
  BEGIN
    RETURN @EXPR
  END

  -- if POSI is higher than number of SEP -> return ERROR
  IF (@POSI > @NB_SEP)
  BEGIN
    RETURN N'ERROR'
  END

  DECLARE @i int = 0

  WHILE (@i < (@POSI))
  BEGIN
    SET @EXPR = SUBSTRING(@EXPR, LEN(LEFT(@EXPR, CHARINDEX(@SEP, @EXPR))) + 1, LEN(@EXPR))
    SET @i = @i + 1
  END

  IF (@POSI = @NB_SEP)
  BEGIN
    RETURN @EXPR
  END

  RETURN LEFT(@EXPR, CHARINDEX(@SEP, @EXPR) - 1)
END

For example, if I want to get the 3rd element (cc) in the string aaa|zzzzz|cc|mmmmm|e, I will call the UDF as below:

SELECT dbo.getStringElement_Expr_Pos_Sep(N'aaa|zzzzz|cc|mmmmm|e', 2, N'|')

Is there a more direct way to achieve the same result ? If not, are there things I could improve in my implementation ?


texts: Largest substring which starts and ends with some substring

texts:
This code is meant to find the length of the largest substring within a string that starts and ends with a given non-empty substring. Here are some examples:

strDist("catcowcat", "cat") → 9
strDist("catcowcat", "cow") → 3
strDist("cccatcowcatxx", "cat") → 9

This is based off this question.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def strDist(string, sub):
    if len(string) < len(sub):
        return 0
    elif string[0:len(sub)] == sub and string[-len(sub):] == sub:
        return len(string)
    elif string[0:len(sub)] == sub and string[-len(sub):] != sub:
        return strDist(string[:-1], sub)
    elif string[0:len(sub)] != sub and string[-len(sub):] == sub:
        return strDist(string[1:], sub)
    elif string[0:len(sub)] != sub and string[-len(sub):] != sub:
        return strDist(string[1:-1], sub)

While the original question said that this should be done recursively, I would also be interested to see if there are any nice non-recursive ways of doing this. Also, let me know if a recursive or non-recursive approach would be preferable in an interview (assuming the question wasn't restricted to doing it recursively).

I think this algorithm is O(n) time complexity but O(n^2) space complexity. Correct me if I'm wrong. Also, any suggestions about how to improve complexities are welcome.


texts: Finding Matches in a Range / Formatting Call to Sub

texts:
The code below cycles through a number of columns/pairs of columns looking for a match and doing something with it. I have this structure in three different subs with the difference being what I have labeled ' Unique Code '. My two questions are is there an obvious way to combine the two softwareCol loops and how could I structure this better to isolate the identical code.

Sub filterFile()
    ActiveWorkbook.Worksheets("Current File").ListObjects("SoftwareTable").DataBodyRange.Rows.Hidden = True
    Dim currentFile As Worksheet: Set currentFile = ActiveWorkbook.Sheets("Current File")
    Dim cell As Object
    Dim softwareCol As Integer
    Dim targetSoftware As String
    targetSoftware = UserForm1.TextBox1.Value & " " & UserForm1.TextBox2.Value
    With currentFile
        For softwareCol = 0 To 10
            For Each cell In .Range("J2:J" & lastRow(currentFile)).Offset(0, softwareCol * 2)

                ' Unique Code '
                If targetSoftware = cell.Value & " " & cell.Offset(0, 1).Value Then
                    cell.Rows.Hidden = False
                End If

            Next
        Next softwareCol
        For softwareCol = 0 To 5
            If Not (softwareCol = 2 Or softwareCol = 4) Then
                For Each cell In .Range("AF2:AF" & lastRow(currentFile)).Offset(0, softwareCol)

                    ' Unique Code '
                    If targetSoftware = cell.Value & " " Then
                        cell.Rows.Hidden = False
                    End If

                Next
            End If
        Next softwareCol

        ' Unique Code '
        .Activate
        .Range("A1").Select

    End With
End Sub


texts:
Please comment about code complexity, and coding style, I'm preparing for a code interview, so any comment would be appreciated.

Example:

Input

1    2   3   4
5    6   7   8
9   10  11  12
13  14  15  16

Output:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Code:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JobInterviewTests
{

    //Spiral printing of 2D matrix.
    [TestClass]
    public class Spiral2Dmatrixprint
    {
        [TestMethod]
        public void TestSpiralPrint()
        {
            int[,] matrix = new int[3, 3];
            matrix[0, 0] = 1; matrix[0, 1] = 2; matrix[0, 2] = 3;
            matrix[1, 0] = 8; matrix[1, 1] = 9; matrix[1, 2] = 4;
            matrix[2, 0] = 7; matrix[2, 1] = 6; matrix[2, 2] = 5;
            SpiralPrint(matrix);

        }

        private void SpiralPrint(int[,] matrix)
        {
            int colRight = 2;
            int colLeft = 0;
            int rowTop = 0;
            int rowEnd = 2;

            PrintRight(matrix, colLeft, colRight, rowTop, rowEnd);
        }

        private void PrintRight(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                System.Diagnostics.Debug.Write(matrix[colRight,rowTop]);
                return;
            }
            for (int i = colLeft; i <= colRight; i++)
            {
                System.Diagnostics.Debug.Write(matrix[rowTop, i]);
            }
            PrintDown(matrix, colLeft, colRight, ++rowTop, rowEnd);
        }

        private void PrintDown(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                return;
            }
            for (int i = rowTop; i <= rowEnd; i++)
            {
                System.Diagnostics.Debug.Write(matrix[i, colRight]);
            }
            PrintLeft(matrix, colLeft, --colRight, rowTop, rowEnd);
        }

        private void PrintLeft(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                return;
            }
            for (int i = colRight; i >= colLeft; i--)
            {
                System.Diagnostics.Debug.Write(matrix[rowEnd, i]);
            }
            PrintUp(matrix, colLeft, colRight, rowTop, --rowEnd);
        }

        private void PrintUp(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                return;
            }
            for (int i = rowEnd; i >= rowTop; i--)
            {
                System.Diagnostics.Debug.Write(matrix[i, colLeft]);
            }
            PrintRight(matrix, ++colLeft, colRight, rowTop, rowEnd);
        }
    }
}


texts:
This function is intended to remove leading and trailing whitespace from a string. How can it be made more efficient?  For example, can the two for loops be combined into one?

string trim(string str)
{
    int i = 0;
    for (char c : str)
    {
        if (!isspace(c))
            break;
        i++;
    }

    string trimmed = str.substr(i, (str.length()-i));

    i = 0;
    for (char c : str)
    {
        if (isspace(c))
            break;
        i++;
    }

    trimmed = trimmed.substr(0, i);
    return trimmed;
}


texts:
I've written a small program that draws a vector field in R using ggplot for a given differential equation.

There is a topic on the subject here however, the proposed solutions either don't provide the same functionality as the code below or don't use ggplot.

//example differential equation: f_prime = f(x,y)

f_prime <- function(x,y){
  return(x^2/(1-x^2-y^2))
}

//set the min and max for the x and y curves
x <- 4      //change if you like
y <- 4
minX <- -x
maxX <- x
minY <- -y
maxY <- y
len <- 40   //number by which the x,y space will be subdivided by
            //larger number => more points and vice versus

//create an equally spaced grid
data <- data.frame(expand.grid(x = seq(minX, maxX, length.out=len),
                               y = seq(minY, maxY, length.out=len)))

//create a new column for the results of (x,y) applied on f_prime
data$dydx <- mapply(f_prime, data$x, data$y)

A small graphic to visualize the problem:

//The next step is important to understand:
//The goal is have arrows that have approx. the same length (c = const) and
//point to the direction of f_prime at some point (x,y) for all points
//Note: f_prime is the derivative of F(x,y) with respect to x,
//hence f_prime provides the relative change in y as a result of a change in x
//Now the problem to draw the arrows can be formulated using f_prime (= dy/dx)
//and the fact that c^2 = dy^2 + dx^2 (Pythagoras)
//Using basic algebra to solve the problem:
//Solve for dx = dy/f_prime(x,y) and insert into
//c^2 = dy^2 + dx^2 = dy^2 + (dy/f_prime(x,y))^2 and solve for dx
//dx = sqrt(c^2/(1+f(x,y)^2) and
//dy = f(x,y)*dx
//now we can draw the arrows using (x,y) as the start and (x+dx, y+dy) as the end
//translating this into code:

data$dx <- sqrt((1/len)/(1+data$dydx^2))
data$dy <- data$dx*data$dydx
ggplot(data=data, aes(x=x,y=y), environment = environment()) +
  geom_point(size = 1) +
  geom_segment(aes(xend=x+dx, yend=y+dy), arrow = arrow(length = unit(0.1, "cm"))) +
  xlim(minX,maxX) +
  ylim(minY,maxY)

Looks like:

Maybe there is a better/faster more elegant way to do it, if yes please share if not happy to help.