texts: Callback functions to select the tab to the left in Google Chrome

texts:
I'm a JavaScript rookie, but I wrote a JavaScript function as part of a Chrome extension that will activate the tab to the left of the currently active tab. The function is pretty ugly, but I couldn't figure out another way to write it.

The logic is pretty simple, but I ran into problems setting variables throughout the various scopes. How would I move the functionality of the Chrome API calls into individual functions that return values? Can callback functions return a value?

// Activates the tab to the left of the currently active tab
tabLeft = function() {
    var parent = this;
    var activeTabIndex;
    var targetTabIndex;

    // Get the index of the active tab
    chrome.tabs.query({'active':true, 'currentWindow': true}, function(tabs) {
        parent.activeTabIndex = tabs[0].index;
    });

    // Get the count of the number of tabs in the current window
    chrome.tabs.query({'currentWindow': true}, function(tabs) {
        var tabCount = tabs.length;
        parent.targetTabIndex = (parent.activeTabIndex == 0) ? (tabCount - 1) : (parent.activeTabIndex - 1);

        // Get the tabId of the of the tab we want to activate
        chrome.tabs.query({'index': parent.targetTabIndex}, function(tab) {
            var tabId = tab[0].id;

            // Activate the target tab
            chrome.tabs.update(tabId, {'active': true}, function() {});
        });
    });
};


texts:
I wrote a JavaScript app with allows the user to add events and get countdown for every event. Also the events and their dates are stored in localStorage.
I want a general review and I think that every second the browser makes a lot of operations like here:
 let interval = setInterval(() => {
      let timerValue = this.__timer.tick(values);
      if (timerValue === "Timed out") {
        alert(`${values.title} is out now !`);
        this.__adapter.removeEvent(values.title);
        clearInterval(interval);
      } else {
        this.__adapter.createEventOrUpdateIfExisted(values, timerValue);
      }
    }, 1000);

What's the best approach to follow?
Source code: https://github.com/dvmhmdsd/Events-countdown


texts:
import sys
import time
import multiprocessing

def change_char_at(s: str, ch: str, i: int, j: int=None):
    '''strings are immutable so i made this handy-little function to 'mutate' strings
    similar to =>
    s[i] = ch    # if j is not specified
    s[i:j] = ch  # if j is specified

    *note*: negative indices does not work!
    '''
    if not j:
        j = i + 1
    return s[:i] + ch + s[j:]

def loader(width: int=20, bar_width: int=3):
    '''
    A simple loading bar which shows no information or whatever
    the function should be run in a different thread and must be killed.
    '''
    s = '[' + ' ' * (width - bar_width - 1) + ']'
    while 1:
        for i in range(1, width - bar_width - 1):
            sys.stdout.write('\r' + change_char_at(s, '===', i))
            sys.stdout.flush()
            time.sleep(0.1)
        for i in range(width - bar_width - 1, 0, -1):
            sys.stdout.write('\r' + change_char_at(s, '===', i))
            sys.stdout.flush()
            time.sleep(0.1)

def loader_with_wait(wait: int=None, width: int=20, bar_width: int=3):
    '''
    A simple loading bar which shows no information or whatever.
    it will quit after `wait` seconds or will *run forever* if wait is not specified

    param: wait: for how much time should the loading bar run.
    '''
    # Start the loader
    p = multiprocessing.Process(target=loader, name='loader', args=(width, bar_width))
    p.start()

    if wait:
        # let the loader run for `wait` seconds
        time.sleep(wait)
        # terminate the loader() function
        p.terminate()
        # Cleanup
        p.join()
        # Start from newline
        sys.stdout.write('\n')

if __name__ == '__main__':
    try:
        loader_with_wait(10)
    except KeyboardInterrupt:
        pass

Hey Guys!
I made a simple progress bar in python. The animation is cool!
it can wait for a few seconds or it can run forever, the choice is upto you.
it can be used in other programs and can run in a separate thread.
Implementing the wait function was the hardest thing to do. is there any other way to do it?

Any suggestions will be helpful...  :-)

see it in action: https://asciinema.org/a/323180


texts: strTok function (thread safe, supports empty tokens, doesn't change string)

texts:
I'm new to C language and want to explode a string like we do in PHP explode() function, I searched for a built-in function with the C standard library, and I found strtok , but It doesn't support empty tokens like 1,2,3,,5 . Inspired by the answers I found in this SO question I made this function, it is supposed to be thread safe and support empty tokens and doesn't change the original string

char* strTok(char** newString, char* delimiter)
{
    char* string = *newString;
    char* delimiterFound = (char*) 0;
    int tokLenght = 0;
    char* tok = (char*) 0;

    if(!string) return (char*) 0;

    delimiterFound = strstr(string, delimiter);

    if(delimiterFound){
        tokLenght = delimiterFound-string;
    }else{
        tokLenght = strlen(string);
    }

    tok = malloc(tokLenght + 1);
    memcpy(tok, string, tokLenght);
    tok[tokLenght] = '\0';

    *newString = delimiterFound ? delimiterFound + strlen(delimiter) : (char*)0;

    return tok;
}

I designed it to be used like

char* input = "1,2,3,4,5,6,7,,,10,";
char** inputP = &input;
char* tok;
while( (tok=strTok(inputP, ",")) ){
    printf("%s\n", tok);
}


texts: Powershell script that updates Active Directory user information

texts:
I wrote this Powershell script years ago for updating AD from a CSV file.  I'd like to try to optimize to run quicker and be more efficient... but I'm not sure where to start / what could improve it.  Any suggestions are welcome.

EDIT: I've updated my original script to this:

$users = Import-Csv C:\Scripts\Employees.csv

foreach ($user in $users) {

$employeeNumber = $User.employeeNumber
$Department     = $User.department
$Title          = $User.title
$Office         = $User.office
$Address        = $User.address
$City           = $User.city
$State          = $User.state
$PostalCode     = $User.postalCode
$Company        = $User.company
$Telephone      = $User.telephone
$Mobile         = $User.mobile
$Fax            = $User.fax
$Custom1        = $User.custom1
$Custom2        = $User.custom2
$Custom3        = $User.custom3
$Custom4        = $User.custom4

Get-ADUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" `
    -SearchBase "OU=Logins,DC=domain,DC=com" |
    Set-ADUser -Replace @{ `
    employeeNumber=$EmployeeNumber;
    department=$Department;
    title=$Title;
    Office=$office;
    streetAddress=$Address;
    l=$City;
    st=$State;
    postalCode=$PostalCode;
    company=$Company;
    telephoneNumber=$telephone;
    mobile=$cell;
    facsimileTelephoneNumber=$Fax;
    ExtensionAttribute1=($user.custom1);
    ExtensionAttribute2=($user.custom2);
    ExtensionAttribute3=($user.custom3);
    ExtensionAttribute4=($user.custom4)
                    }
}


texts: Methods to get single and multiple JDBC results

texts:
I have two methods which are very similar apart from the method call inside and the return type. I wondered if there was a way to make it neater, i.e not duplicate the boiler plate connection code. I considered putting a flag in the method signature to switch, something like isMultiple but in the end I didn't like this and as the return type is different that won't work. I wondered if there was something nice I could do with Java 8.

Methods:

protected String getSingleFilePathResult(Query query) throws UwsException {
      JdbcPooledConnection conn = createConnection();
      try {
         return conn.getSingleFilePathResult(query);
      } catch (SQLException sqle) {
         throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
      } finally {
         closeConnection(conn);
      }
   }

protected List<String> getMultipleFilePathResults(Query query) throws UwsException {
      JdbcPooledConnection conn = createConnection();
      try {
         return conn.getMultipleFilePathResults(query);
      } catch (SQLException sqle) {
         throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
      } finally {
         closeConnection(conn);
      }
   }


texts:
I wrote this program that recursively prints all the files and directories starting at the current directory:

import Data.Tree (Tree (..))
import System.Directory (doesDirectoryExist, getCurrentDirectory, getDirectoryContents)

main :: IO ()
main = do
  currentDirectory <- getCurrentDirectory
  tree <- tree currentDirectory "."
  printTree 0 tree

printTree :: Int -> Tree FilePath -> IO ()
printTree indent tree = do
  putStrLn $ (replicate indent ' ' ++ rootLabel tree)
  mapM_ (printTree $ indent + 2) (subForest tree)

treeHelper :: FilePath -> IO [Tree FilePath]
treeHelper path =
  let filter' = filter (`notElem` [".", ".."]) in
  do
    contents <- getDirectoryContents path
    trees <- mapM (tree path) (filter' contents)
    return trees

tree :: FilePath -> FilePath -> IO (Tree FilePath)
tree parent path =
  let fullPath = (parent ++ "/" ++ path) in
  do
    isDirectory <- doesDirectoryExist fullPath
    case isDirectory of
      False -> return $ Node path []
      True -> treeHelper fullPath >>= (return . Node (path ++ "/"))

If you run it, it might print something like this:

./
  dist/
    build/
      autogen/
        cabal_macros.h
        Paths_Tree.hs
      tree/
        tree
        tree-tmp/
          Main.hi
          Main.o
    package.conf.inplace
    setup-config
  Setup.lhs
  tree.cabal
  Tree.hs

I think this is pretty nifty. It's a toy program, so I purposefully left out stuff like error checking and symlink handling and etc. How would you improve this program? Am I duplicating functionality available in a library? Are there places where the code could be tighter? Is my Haskell style not up to snuff?


texts:
Here's the code I am trying to refactor. The same Http client is being used in each nested try with resource. I don't understand the rationale behind nesting client.execute() calls.
The code tries to Post data to an endpoint if resource is missing and retries to Post to a backup endpoint if earlier call fails
public void makeSeveralApiCalls() throws Exception {
  try (final CloseableHttpClient client = HttpClients.createDefault()) {
    try (final CloseableHttpResponse response = client.execute(httpGetUri())){
      if (response.getStatusLine().getStatusCode() == 404) {
        // Resource not found, Post data to Microservice A
        try (final CloseableHttpResponse nestedResponse = client.execute(httpPostToMicroserviceA())) {
          if (resp.getStatusLine().getStatusCode() == 201) {
            LOGGER.info("Success");
          } else {
            // Microservice A could not consume data, log error response
            final String responseString = EntityUtils.toString(resp.getEntity());
            LOGGER.debug("Error response: " + responseString);
            // Try to Post to Microservice B
            try (final CloseableHttpResponse subResponse = client.execute(httpPostToMicroserviceB())) {
              if (resp.getStatusLine().getStatusCode() == 201) {
                LOGGER.info("Success");
              } else {
                // Is this exception propagated to the caller?
                throw new RuntimeException("Very bad unrecoverable state");
              }
          }
       }
    }
  }
}

Is this a valid way to call multiple executes on the same HTTP client in a nested fashion. Is it better to separate out each client.execute() call?


texts: JavaScript function to convert decimal number to binary

texts:
I was recently asked this in an interview for a front-end position and I came up with something like the code below, which seems to work but is clunky.  (Number.toString() was not allowed.)

function convertBinary(number) {
  var n = 0;
  var binaryArr = [];

  var difference = Math.pow(2, n);

  //find out how many digits are needed
  while (difference <= number){
    n++;
    difference = Math.pow(2, n);
    binaryArr.push(0);
  }

  n--;

  while(number > 0) {
    if (Math.pow(2, n) <= number) {
      binaryArr[n] = 1;
      number-= Math.pow(2, n);
    }
    n--;
  }

  return binaryArr.reverse().join("") * 1
}

Also I was asked what the Big(o) of this was but had a hard time figuring it out— what is the time complexity of JavaScript reverse?


texts:
I have a program that has to initialize a few big things (connect to a few databases, parse some XML) and without the initialization being successful the program would not be able to continue.
Right now I have my main method throwing just a general Exception

public static void main(String[] args) throws Exception
{
    //Throws numerous types of Exceptions
    WhateverObject we = WhateverObject.getInstance();

    we.doSomething();
}

My question is, is there a better way to handle this? Should I catch the exception and then print out that it failed an exit? Something else maybe? Note, there's no hope of program recovery at this point.


texts: Resets Rows to default values if column A is missing a value

texts:
I have this Subroutine that works, but I have recently started updating the sheet and adding new columns. I'm finding updating the current macro to be a bit of a chore.

Is there a way to use named ranges instead of declaring the cell ranges as in this code?

    Private Sub Reset_Rows_Click()
        Const USED_RANGE    As String = "A2:FI5002"
        Const BLANKS_COLS   As String = "A2:A5002,B2:B5002,F2:G5002,K2:K5002,M2:O5002,V2:Y5002,AA2:AB5002,AE2:AM5002,AU2:AW5002,AY2:AY5002,BA2:BD5002,BG2:BL5002,BN2:BU5002,CL2:CO5002,CX2:CX5002,DF2:FI5002"
        Const SELECT_COLS   As String = "H2:I5002,J2:J5002,P2:U5002,Z2:Z5002,AC2:AD5002,AN2:AT5002,AX2:AX5002,AZ2:AZ5002,BE2:BF5002"
        Const NA_COLS       As String = "E2:E5002"
        Const BLANKS_VAL    As String = vbNullString
        Const SELECTS_VAL   As String = " --Select--"
        Const NA_VAL        As String = "N/A"

        Dim ws As Worksheet, ur As Range

        Set ws = ActiveSheet
        Set ur = ws.Range(USED_RANGE)

        Application.ScreenUpdating = False
        With ur
            .AutoFilter Field:=1, Criteria1:="="
            If .SpecialCells(xlCellTypeVisible).Count > 1 Then
                .Range(BLANKS_COLS).Value2 = BLANKS_VAL
                .Range(SELECT_COLS).Value2 = SELECTS_VAL
                .Range(NA_COLS).Value2 = NA_VAL
           End If
                .AutoFilter
           End With
                'ws.Cells(5003, 1).EntireRow.Delete

'Sort
    Range("A3:FS5002").Select
ActiveWorkbook.Worksheets("Master").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Master").Sort.SortFields.Add Key:=Range( _
    "E3:E5002"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("Master").Sort.SortFields.Add Key:=Range( _
    "L3:L5002"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("Master").Sort.SortFields.Add Key:=Range( _
    "A3:A5002"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("Master").Sort
    .SetRange Range("A3:FS5002")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Application.ScreenUpdating = True
End Sub


texts: TCP client reconnection logic running on 30 machines

texts:
I am working on a service that is supposed to run on a large installation 24/7. Once the software is deployed, I will most likely not be able to make any changes anymore. This is my first time working on a network application so I want to make sure I am not making any obvious mistakes.

60 instances of this program are supposed to run on 30 machines, meaning there are 2 instances of it running on each machine. It is used to keep all the client instances (running this code) connected to the controller that gives them updates when needed.

I am wondering if there are any optimizations you guys can recommend to me or if there are any other insufficiencies that catch your eyes.

public class ControllerConnectionService {

    public ControllerConnectionService() {
        Initialize();
    }

    private Timer _pingTimer;
    private SimpleTcpClient _tcpClient;

    public event EventHandler<DataModel> ContentTypeChanged;

    private void Initialize() {
        CreateTcpClient();
        Connect();

        var messageString = GetMessageString(MessageType.SendId, MainViewModel.Id.ToString());
        SendMessage(messageString);

        _pingTimer = new Timer {Interval = 2000};
        _pingTimer.Elapsed += PingTimerOnElapsed;
        _pingTimer.Start();
    }

    private void PingTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) {
        if (!IsConnected()) Reconnect();
    }

    private bool IsConnected() {
        try {
            var pingBytes = Encoding.UTF8.GetBytes(GetMessageString(MessageType.Ping, string.Empty));
            _tcpClient.TcpClient.Client.Send(pingBytes);
            return true;
        }
        catch (Exception) {
            return false;
        }
    }

    private void CreateTcpClient() {
        _tcpClient = new SimpleTcpClient();
        _tcpClient.DataReceived += TcpClientOnDataReceived;
    }

    private void Connect() {
        try {
            _tcpClient.Connect(ControllerIp, ClientControllerPort);
        }
        catch (Exception) {
            Reconnect();
        }
    }

    private void Reconnect() {
        try {
            while (!IsConnected()) {
                Thread.Sleep(500);
                CreateTcpClient();

                _tcpClient.Connect(ControllerIp, ClientControllerPort);
            }
        }
        catch (Exception) {
            Reconnect();
        }
    }

    private void SendMessage(string message) {
        try {
            _tcpClient.TcpClient.Client.Send(Encoding.UTF8.GetBytes(message));
        }
        catch (Exception) {
            Reconnect();
        }
    }

    private void TcpClientOnDataReceived(object sender, Message message) {
        if (string.IsNullOrEmpty(message.MessageString))
            return;

        var messageParts = message.MessageString.Split(';');

        Enum.TryParse(messageParts[0], out MessageType messagetype);

        if (messagetype == MessageType.UpdateContentType) {
            Console.WriteLine($@"{DateStamp} Data received: {message.MessageString} ");
            var dataModel = JsonConvert.DeserializeObject<DataModel>(messageParts[1]);

            ContentTypeChanged?.Invoke(this, dataModel);
        }
    }
}

If you require any additional information or code, feel free to ask.


texts: Handling argument validation in JavaScript

texts:
var saveUser = function(name, profile){
  assert(typeof name === 'string')
  assert(profile instanceof Profile)
  return new bluebird.Promise(function(resolve, reject){
    // async code saving user to DB
  })
}

Or

var saveUser = function(name, profile){
  return new bluebird.Promise(function(resolve, reject){
    try {
      assert(typeof name === 'string')
      assert(profile instanceof Profile)
    } catch(err){
      return reject(err)
    }
    // async code saving user to DB
  })
}

Which way is better?
It is good idea to catch validation errors and throw custom ValidationError instead?


texts: Try to implement comments tree for Django

texts:
I've tried to create an implementation of a tree for comments. I want use it in Django to store comments. Please tell me how to implement it much simpler, without recursion, to find child nodes.

class commentTree(object):
def __init__(self, id, data, parentId = 0, childrens = None):
    "Represents one leaf Tree"
    self.id = id
    self.parentId = parentId
    self.title = data['title']
    self.body = data['body']
    self.childrens = []
    self.isLeaf = True if len(self.childrens) > 0 else False
    if childrens is not None:
        for children in childrens:
            self.childrens.append(children)

def addComment(self, parentId, data):
    root = 1 if self.isLeaf == False else 0
    comment = commentTree(parentId + root + len(self.childrens), data, self.id)
    if parentId == self.id:
        self.childrens.append(comment)
    else:
        node = self.findById(parentId)
        node.childrens.append(comment)

def getParent(self, node):
    "Gets parent node"
    if self.parent is not None:
        return self.parent

def getSize(self, node):
    "Returns size of childrens length + node"
    return len(node.childrens) + 1

def findById(self, id):
    def searchInChildren(id, childNodes):
        for children in childNodes:
            if children.id == id:
                return children
            else:
                searchInChildren(id, children)
    if id == self.id:
        return self
    else:
       result = searchInChildren(id, self.childrens)
       if result.id == id:
           return result
       else: return None

def getSiblings(self, node):
    "Get nodes that have one parent"
    nodes = []

    def getAllChildrens(self, child):
        for children in node.childrens:
            nodes.append(children)
            if children.isLeaf:
                getAllChildrens(self, children)

    getAllChildrens(self, node)
    return nodes


texts: Project Euler Problem # 8 maximum product of sequences


texts:
I wrote a bash script for reviewing scientific articles. It adds a blank page for notes and creates a new landscape file. I'm sure it can be made better code wise. Any suggestions?

#!/bin/bash

if [ $# -ne 1 ]
then
  echo "Usage example: ./bashscript src.pdf"
  exit $E_BADARGS
else
  NUM=$(pdftk $1 dump_data | grep 'NumberOfPages' | awk '{split($0,a,": "); print a[2]}')
  COMMSTR=''

  for i in $(seq 1 $NUM);
  do
    COMMSTR="$COMMSTR A$i B1 "
  done
  $(echo "" | ps2pdf -sPAPERSIZE=a4 - pageblanche.pdf)
  $(pdftk A=$1 B=pageblanche.pdf cat $COMMSTR output 'mod_'$1)
  (pdfnup 'mod_'$1 --nup 2x1 --landscape --outfile 'print_'$1)
  $(rm pageblanche.pdf && rm 'mod_'$1)

fi

#for f in *.pdf; do ./bashscript.sh $f; done 2> /dev/null


texts: Fetching items from database with "Outstanding" status

texts:
I am fetching around more than 300000 items through a query:

@items = current_company.item_masters.user_hierarchies_filter(current_user).accessible_by(current_ability).paginate(:conditions => condition.compile, :include=> includable_tables,
        :order => (sort_column + " " + sort_direction),
        :page=> new_params[:page],:per_page => new_params[:per_page_records].blank? ? 10 : new_params[:per_page_records])

And the scope used in that query is :

named_scope :user_hierarchies_filter, lambda { |user|
    {select: "DISTINCT item_masters.id", conditions: ["item_masters.company_id = ?", user.company_id]}
  }

It produces this log message:

ItemMaster Load (43445.6ms)   SELECT DISTINCT item_masters.id FROM `item_masters` WHERE (item_masters.status IN ('Outstanding')) AND (((item_masters.company_id = 1) AND (`item_masters`.company_id = 1))) ORDER BY item_number asc LIMIT 331230, 10

It takes around 44 seconds to load items. Can anyone please suggest any option to reduce the loading time of this query?


texts: Feedback on automatic form filling with reflection

texts:
Context:

I need to fill a handful of .docx templates with answers that come from form.responses, which is a dynamic object that comes from a JSON and can have different properties that vary according to the type of the form that was answered.

To do the filling, we need to instantiate a DTO called BindDto that takes the template string (eg.: ${PersonName}) and the value that will replace it (eg.: form.responses.client_name = "John Doe").

In my case, I created some [X]Constants classes that have properties that look like this...

public static readonly KeyValuePair<string, string> PERSON_NAME = new KeyValuePair<string, string>("client_name", "${PersonName}");
public static readonly KeyValuePair<string, string> PERSON_AGE = new KeyValuePair<string, string>("my_age", "${PersonAge}");
public static readonly KeyValuePair<string, string> MOTHER_NAME = new KeyValuePair<string, string>("mother", "${MotherName}");

...to map which template string each field from the JSON correponds to.

The code below was written so I could fill all the templates independent from which fields they might have by searching the [X]Constants classes and using the KeyValuePairs that I have set.

It works (o' course), but it seems I little... clumsy. And I don't have enough knowledge about C# to be sure this isn't pure madness.

What do you think about this code? Is it valid? Is is overengineering? How can I improve it?

I don't think performance will ever be a concern, but I would like to be enlightened in that sense too.

Thanks in advance to anyone willing to discuss it!

public List<BindDto> GenerateBinds(IEnumerable<Form> forms)
{
    var constants = new List<FieldInfo>();
    var binds = new List<BindDto>();

    constants.AddRange(typeof(AuthConsts).GetFields());
    constants.AddRange(typeof(ClientConsts).GetFields());
    constants.AddRange(typeof(ContactConsts).GetFields());
    constants.AddRange(typeof(AddressConsts).GetFields());
    constants.AddRange(typeof(ReferenceConsts).GetFields());

    foreach (var form in forms)
    {
        var formResponses = form.response.ToObject<Dictionary<string, string>>();

        IEnumerable<string> formFields = formResponses.Keys;

        foreach (var field in formFields)
        {
            foreach (var constant in constants)
            {
                if (constant.FieldType == typeof(KeyValuePair<string, string>))
                {
                    var templateString = (KeyValuePair<string, string>)constant.GetValue(this);

                    if (templateString.Key == field)
                        binds.Add(new BindDto(templateString.Value, formResponses[field]));
                }
            }
        }
    }

    return binds;
}


texts: Basic calculator that calculates result based on operands using a class

texts:
Question:

  Create a basic calculator using classes that given 3 inputs - number 1, number 2 and operator -  calculates the result.

class calculator():

    def __init__(self,value1 , value2, operand):
        self.value1 = int(value1)
        self.value2 = int(value2)
        self.operand = operand

    def calculate (self):
        if self.operand == '+' :
            return self.value1 + self.value2

        if self.operand == '*':
            return self.value1 * self.value2

        if self.operand == '-' :
            return self.value1 - self.value2

        if self.operand == '/' :
            if self.value2 == 0:
                raise ZeroDivisionError
            else:
                return self.value1 / self.value2

r = calculator(6,7, '+')
print r.calculate()

r = calculator(3,7, '-')
print r.calculate()

r = calculator(6,0, '*')
print r.calculate()

r = calculator(9,5, '/')
print r.calculate()

How can i make this function better? Is this a correct implementation of a class?


texts:
Relatively new here so please let me know if I'm doing something wrong.

I'm mostly wondering if there's any additional way I can make this code more efficient. Specifically the moveset and win condition part of the code feels unnecessarily long or overcomplicated. Still a beginner in python, so any feedback regarding syntax is also appreciated! Thank you!

#Contains all basic variables for ease of coding
class Player():

    symbols = ['O','X']

    def __init__(self, number):
        self.wins = 0
        self.number = number
        self.symbol = self.symbols[number]

#2D list to represent the 3x3 board
def createBoard():
    a = ['', '', '']
    b = ['', '', '']
    c = ['', '', '']
    return [a, b, c]

board = createBoard()

#Makes the board look nicer for user; numbers as placeholder for empty spaces
def printBoard():
    i = 0
    for row in board:
        print("---------------")
        for place in row:
            i += 1
            if place == '':
                print("|",i,"|", end='')
            else:
                print("|",place,"|", end='')
        print("")
    print("---------------")

#Receives numbers to return x and y position of the 2d list
def getMove():
   #Any other more efficient way for this?
    moveset = {
            '1': (0,0),
            '2': (1,0),
            '3': (2,0),
            '4': (0,1),
            '5': (1,1),
            '6': (2,1),
            '7': (0,2),
            '8': (1,2),
            '9': (2,2)
            }
    print("Please enter the number of the spot to place your move",end='')
    xpos, ypos = moveset[input("> ")]
    return xpos, ypos

#changes the board with received x and y
def placeMove(xpos, ypos, player):
    global board
    board[ypos][xpos] = player.symbol

#Checkes if the spot has been filled
def validateMove(xpos, ypos):
    if board[ypos][xpos] != '':
        print("Cannot place there!")
        return False
    return True

#Checks win conditions; any more efficient way for this as well?
def checkWin():
    for row in board:
        if row[0]==row[1]==row[2]:
            return row[0]
    for i in range(0,3):
        if board[0][i]==board[1][i]==board[2][i]:
            return board[0][i]
    if board[0][0]==board[1][1]==board[2][2]:
        return board[1][1]
    elif board[0][2]==board[1][1]==board[2][0]:
        return board[1][1]
    for row in board:
        for spot in row:
            if spot == '':
                return False
    return 2

def switchPlayer(currentPlayer):
    if currentPlayer.number == 0:
        return 1
    else:
        return 0

#game loop
def game():
    global board

    playerList = [Player(0), Player(1)]
    game = True
    currentPlayer = playerList[0]
    printBoard()

    while game:
        print("Current Player:",currentPlayer.number+1,)
        xpos, ypos = getMove()
        #repeats until valid input
        while not validateMove(xpos, ypos):
            xpos, ypos = getMove()
        placeMove(xpos, ypos, currentPlayer)
        printBoard()
        if checkWin() == currentPlayer.symbol:
            print("Player",currentPlayer.number+1, "wins!")
            game = False
        elif checkWin() == 2:
            print("The game is a draw!")
            game = False
        else:
            currentPlayer = playerList[switchPlayer(currentPlayer)]

#Should I just make the game() the main() function?
def main():
    game()

if __name__ == "__main__":
    main()


texts:
I've made a program in C# that generates Mersenne numbers starting from the current largest known Mersenne prime. It then calculates the modulo between those numbers and smaller ones starting from 3 in order to figure out if it is divisible.

I've used some math tricks to make the process pretty fast, and so I can check the divisibility of what is basically a multi-million digit number against small numbers several times per second. However, I'd like to see if I can make it faster.

Also, if my program does work, it would suggest that the current largest known Mersenne prime (\$2^{74207281} - 1\$) is actually divisible by 7. Therefore I'm hesitant to say that my program actually does work, so if anyone can confirm this for me, I'd also greatly appreciate that!

using System;
using System.IO;
using System.Numerics;

namespace Prime
{
    public class Prime
    {
        const double C = 10601040; //this is a constant that I divide the exponent by to split it into the easiest possible chunks to work with
        static int exp = 74207281;
        static BigInteger big = BigInteger.Pow(2, exp) - 1;
        static TextWriter tw = new StreamWriter(@"prime.txt"); //writes confirmed primes to a text file

        public static void Main()
        {
            for (int i = exp; true; i++) //this loop infinitely runs the prime checker, incrementing the exponent as it goes
            {
                exp++;
                primes(i);
            }
        }

        private static void primes(int exp)
        {
            double div = Math.Floor(exp/C),
                exp1 = div,
                exp2 = exp - (exp1*C), //this is where the exponent is divided into chunks
                result = 0; //anywhere this appears is just to make extra sure that the result stays zero outside the following loop, where the result really matters

            for (long i = 3; i <= (big/i); i+=2)
            {
                double result1 = (Math.Pow(2, exp1) % i)*C;
                double result2 = (Math.Pow(2, exp2) % i);
                result = (((result1 * result2) - 1) % i);
                if (result == 0)
                {
                    Console.WriteLine(exp + ", not prime.");
                    return;
                }
                Console.WriteLine(i);
                result = 0;
            }
            Console.WriteLine(exp);
            tw.WriteLine(exp);
        }
    }
}

I modulo the chunks of the tested number against odd numbers because a Mersenne number will never be even, therefore it's a waste to check for that. Also, I made the stopping point for the loop dynamic so that any extra numbers can be cut out.
It's like this: 377 isn't divisible by 12, so we know that if it is divisible by something, it will be less than \$\frac{377}{12}\$, which is about 31.4. 377's actual factors are 13 and 29 (aside from itself and 1), which are both less than 37.7.

The technique used to modulo these massive numbers is known as modular exponentiation. It works for all numbers. Here's an example.

$2^7, C = 3, I = 5$

$2^7 = 128$

$Mersenne number being tested: 2^7 – 1 = 127 (this is prime)$

$Exp1 = 2$

$Exp2 = 1$

$Result1 = (2^2 % 5) * 3 = (2^2 % 5) * (2^2 % 5) * (2^2 % 5) = 4 * 4 * 4 = 64$

$Result2 = (2^1 % 5) = 2$

$Result = (  (  (64 * 2) – 1) % 5) = (  (  128 – 1) % 5) = (127 % 5) = 2$


texts: Is this C++ program correctly implemented in SSE?

texts:
I have to implement a simple program in SSE, and I don't know if I have done it in the right way (it's my first program in SSE).

This is the C++ program:

double distance (int x1, int x2, int y1, int y2)
{
    double x = abs(x2 - x1);
    double y = abs(y2 - y1);

    double dist = sqrt(x*x + y*y);

    return dist;
}

And this is the program in SSE instructions:

__m128d vx1 _mm_load_pd(x1); // load x1 and x2
__m128d vx2 = _mm_load_pd(x2);
__m128d vdiff = _mm_sub_pd(vx2, vx1); // x2 - x1
__m128d vnegdiff = mm_sub_pd(_mm_set1_pd(0.0), vdiff); // 0.0 - diff
__m128d vabsX = _mm_max_pd(vdiff, vnegdiff);        //  abs = max(diff, - diff)

__m128d vy1 = _mm_load_pd(y1);
__m128d vy2 = _mm_load_pd(y2);
__m128d vdiff2 = _mm_sub_pd(vy2, vy1);
__m128d vnegdiff2 = mm_sub_pd(_mm_set1_pd(0.0), vdiff2);
__m128d vabsY = _mm_max_pd(vdiff2, vnegdiff2);

__m128d absX = _mm_mul_pd(vabsX,vabsX); //x*x
__m128d absY = _mm_mul_pd(vabsY,vabsY); //y*y

__m128d suma = _mm_add_pd(absX, absY); // x^2 + y^2

__m128d square = _mm_sqrt_pd(suma); // square root x^2 + y^2

return square;


texts: Sum of all multiples of 3 or 5 below 1000 (Project Euler #1 - typical)

texts:
I'm learning LISP and am starting with Project Euler. I would love some initial feedback on my LISP code for this simple task.

I know it spits out the correct answer, but what I'm not sure about is if I'm using LISP the way it is intended (and the way to strive for in the future in order to achieve success with LISP).

(defun sum (L)
  "sum a list"
  (apply '+ L)
)

(defun range (max &key (min 0) (step 1))
  "range of numbers from min to max by jumps of step"
  (loop for n from min below max by step
    collect n)
)

; take a range that steps by 3's and a list that steps by 5's and take the union of them (union removes duplicates)
(setq answer (sum (union (range 1000 :step 3) (range 1000 :step 5))))
(print answer)


texts:
I've just implemented a cache for my server, and I'd like your thoughts about performance improvements and maybe some possible bug fixes:

public class Cache<CacheKey, CacheValue>
{
    private Dictionary<CacheKey, KeyValuePair<CacheValue, DateTime>> _map;

    /// <summary>
    /// The first element is the least recently used.
    /// </summary>
    private List<CacheKey> _lru;

    private int _maxSize;

    private ReaderWriterLock _lock;

    private int _minutes;

    public Cache(int maxNumberOfRecords, int minutes)
    {
        _maxSize = Math.Max(maxNumberOfRecords, 1);
        _lru = new List<CacheKey>(_maxSize + 1);
        _map = new Dictionary<CacheKey, KeyValuePair<CacheValue, DateTime>>();
        _lock = new ReaderWriterLock();
        _minutes = minutes;
    }

    public CacheValue find(CacheKey key)
    {
        _lock.AcquireReaderLock(-1);

        CacheValue ans;

        if (_map.ContainsKey(key) && (DateTime.Now - _map[key].Value).Minutes < _minutes)
        {
            ThreadPool.QueueUserWorkItem(o =>            //don't wait for lru to update
            {
                _lock.AcquireWriterLock(-1);
                _lru.Remove(key);
                _lru.Add(key);
                _lock.ReleaseWriterLock();
            });

            ans = _map[key].Key;
        }
        else
        {
            ans = default(CacheValue);
        }

        _lock.ReleaseReaderLock();
        return ans;
    }

    public void insert(CacheKey key, CacheValue value)
    {
        _lock.AcquireWriterLock(-1);

        if (_map.ContainsKey(key))      //if exists
        {
            _map.Remove(key);
            _map.Add(key, new KeyValuePair<CacheValue, DateTime>(value, DateTime.Now));       //update value
        }
        else
        {                               //if not
            _lru.Add(key);
            _map.Add(key, new KeyValuePair<CacheValue, DateTime>(value, DateTime.Now));       //add to cache

            if (_lru.Count > _maxSize)
            {
                _map.Remove(_lru[0]);   //and delete least recently used

                _lru.RemoveAt(0);
            }
        }

        _lock.ReleaseWriterLock();
    }
}

I've used ThreadPool because the List operations are expensive, but I think that this hurts the LRU integrity.  I'm also thinking to implement a queue with \$O(1)\$ Remove to replace the List class.


texts: Directive to randomly show/hide elements

texts:
This directive works fine but I have the feeling that I'm not doing it the "angular way" with .attr('hide', 'true'). Is there a better way to show or hide elements from a directive?

app.directive('myRandomshow', function() {
  // Show a random element from child elements

  function randomIntFromInterval(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }
  return {
    link: function(scope, element) {
      // Ensure everything is initialy hidden
      element.children().attr('hide', 'true');
      scope.$on('event::event', function() {
        // Show result
        element.children().attr('hide', 'true');
        element.children().eq(randomIntFromInterval(2, element.children().length - 1)).removeAttr('hide');
      });
    }
  };
});


texts: Routes Between Node, Cracking the coding interview

texts:
I am going though Cracking the coding interview and trying to improve my coding interview skills.

The question is "Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

I think the run time is N^2 but I could be wrong.

Is there a better way to do BFS?

package TreesAndGraph;

import java.util.LinkedList;
import java.util.Queue;

public class PathSearch
{
    public static void main(String[] args)
    {
        int[][] matrix = {
                {0, 1, 0, 0, 1, 1},
                {0, 0, 0, 1, 1, 0},
                {0, 1, 0, 0, 0, 0},
                {0, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0}};

        //Following are all true.
        System.out.println("0 -> 1: " + routeBetweenNode(matrix, 0, 1));
        System.out.println("0 -> 4: " + routeBetweenNode(matrix, 0, 4));
        System.out.println("0 -> 5: " + routeBetweenNode(matrix, 0, 5));
        System.out.println("0 -> 3: " + routeBetweenNode(matrix, 0, 3));
        System.out.println("0 -> 2: " + routeBetweenNode(matrix, 0, 2));
        System.out.println("1 -> 1: " + routeBetweenNode(matrix, 1, 1));
        System.out.println("2 -> 4: " + routeBetweenNode(matrix, 2, 4));
        System.out.println("1 -> 2: " + routeBetweenNode(matrix, 1, 2));

    }

    private static boolean routeBetweenNode(int[][] matrix, int start, int end)
    {
        Queue<Integer> q = new LinkedList<>();
        if (traverseMatrix(end, q, matrix[start])) return true;

        while (!q.isEmpty())
        {
            Integer activeVisited = q.remove();
            if (traverseMatrix(end, q, matrix[activeVisited])) return true;
        }
        return false;
    }

    private static boolean traverseMatrix(int end, Queue<Integer> q, int[] currentArray)
    {
        for (int i = 0; i < currentArray.length; i++)
        {
            int value = currentArray[i];
            if (value == 1)
            {
                q.add(i);
                if (i == end)
                {
                    return true;
                }
            }
        }
        return false;
    }
}


texts: Should I call a method (i.e. size()) multiple times or store it (if I know the value will not change)

texts:
I have a function that searches the shortest vector in a vector of vectors of pointers.

Which is a better way?

std::vector<std::vector<void*>> const& ways

{
   size_t i = SIZE_MAX;
   for(auto& it : ways)
   {
      if(i > it.size())
         i = it.size();
   }
}

OR

std::vector<std::vector<void*>> const& ways

{
   size_t i = SIZE_MAX;
   for(auto& it : ways)
   {
      const auto temp = it.size();
      if(i > temp)
         i = temp;
   }
}

As far as I can see size() does not return reference so second one is a better way, is it true?

Also, is there any other approach you can suggest for this method?


texts:
I am a student doing their AS Computing course and I have created a piece of code in which a message can be typed and then scrambled by moving letters along the alphabet. I was wondering if anyone knew any way in which this could be improved.

while(True):
 message = input("What would you like the message to say? ").lower()
 newmessage = ""
 for i in range(0,26):
    for letter in message:
        decimal = (ord(letter))
        decimal = decimal + i

        if decimal > 122:
            decimal = decimal -26

        elif decimal < 97:
            decimal = decimal + 26

        newmessage += (chr(decimal))

    print (newmessage)
    newmessage = ""


texts: Searching two different elements in a same list

texts:
I have a list of conversion histories, where information about user channels is stored. For example user may have app for iOS and Android installed. Each time user logs in, I store a conversion history, so that there might be multiple rows with shared data (e.g. client is always iOS).

I need to get the latest usage of iOS and Android in this case, as you can see code is pretty much in 'serial' way, so I wonder how this part can be optimized. Any help is appreciated.

private List<UserChannel.AppUser> findLatestAppClients(
            List<Conversion> conversions
    ) {
        Optional<Conversion> iosClient =
                conversions.stream().filter(c -> IOS.clientName().equals(c.getClient())).findFirst();

        Optional<Conversion> androidClient =
                conversions.stream().filter(c -> ANDROID.clientName().equals(c.getClient())).findFirst();

        List<UserChannel.AppUser> appUsers = new ArrayList<>();

        if (iosClient.isPresent()) {
            appUsers.add(new UserChannel.AppUser(iosClient.get().getClient(), iosClient.get().getClientId()));
        }

        if (androidClient.isPresent()) {
            appUsers.add(new UserChannel.AppUser(androidClient.get().getClient(), androidClient.get().getClientId()));
        }

        return appUsers;
    }


texts:
Problem :- Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Here is my solution
Approach 1
public static int majorityElement(int[] nums) {
    if (nums.length == 0) {
        return 0;
    }

    Map<Integer, Integer> numCountMap = new HashMap<>();

    int majorityElement = 0;

    for (int i : nums) {
        if (numCountMap.getOrDefault(i, 0) >= nums.length / 2) {
            majorityElement = i;
            break;
        }

        int currentCount = numCountMap.getOrDefault(i, 0);
        numCountMap.put(i, ++currentCount);
    }

    return majorityElement;
}

And here is my approach 2
 public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }

I was thinkin the first approach is better as the complexity would be n in first case and nlogn in 2nd case.
However, the result shows 2nd approach is better.
Please help me understand why 2nd approach is better and any suggestion for code for first and second.


texts: Converting between Fahrenheit and Celsius

texts:
I'm learning Ruby and working through some exercises. I completed the following exercise without truly understanding why and how it works. I know that's an embarrassing thing to say but I feel like my subconscious mind wrote the code and conscious me (or maybe unconscious me you could say) is having trouble understanding why and how it works and if it's even written correctly.

I would appreciate if someone can run through this code and give me a breakdown of how it works and if you think it's written well.

My Code

class Temperature

  class << self
    def from_fahrenheit temp
      Temperature.new({f: temp})
    end

    def from_celsius temp
      Temperature.new({c: temp})
    end
  end

  def initialize(options={})
    @f = options[:f]
    @c = options[:c]
  end

  def in_fahrenheit
    return @f if @f
    (@c * (9.0 / 5.0)) + 32
  end

  def in_celsius
    return @c if @c
    (@f - 32) * 5.0 / 9.0
  end
end

class Celsius < Temperature
  def initialize temp
    super(c: temp)
  end
end

class Fahrenheit < Temperature
  def initialize temp
    super(f: temp)
  end
end

Rspec Test

describe Temperature do

  describe "can be constructed with an options hash" do
    describe "in degrees fahrenheit" do
      it "at 50 degrees" do
        Temperature.new(:f => 50).in_fahrenheit.should == 50
      end

      describe "and correctly convert to celsius" do
        it "at freezing" do
          Temperature.new(:f => 32).in_celsius.should == 0
        end

        it "at boiling" do
          Temperature.new(:f => 212).in_celsius.should == 100
        end

        it "at body temperature" do
          Temperature.new(:f => 98.6).in_celsius.should == 37
        end

        it "at an arbitrary temperature" do
          Temperature.new(:f => 68).in_celsius.should == 20
        end
      end
    end

    describe "in degrees celsius" do
      it "at 50 degrees" do
        Temperature.new(:c => 50).in_celsius.should == 50
      end

      describe "and correctly convert to fahrenheit" do
        it "at freezing" do
          Temperature.new(:c => 0).in_fahrenheit.should == 32
        end

        it "at boiling" do
          Temperature.new(:c => 100).in_fahrenheit.should == 212
        end

        it "at body temperature" do
          Temperature.new(:c => 37).in_fahrenheit.should be_within(0.1).of(98.6)
        end
      end
    end
  end

  describe "can be constructed via factory methods" do

    it "in degrees celsius" do
      Temperature.from_celsius(50).in_celsius.should == 50
      Temperature.from_celsius(50).in_fahrenheit.should == 122
    end

    it "in degrees fahrenheit" do
      Temperature.from_fahrenheit(50).in_fahrenheit.should == 50
      Temperature.from_fahrenheit(50).in_celsius.should == 10
    end

  end

  describe "utility class methods" do

  end

  # Here's another way to solve the problem!
  describe "Temperature subclasses" do
    describe "Celsius subclass" do
      it "is constructed in degrees celsius" do
        Celsius.new(50).in_celsius.should == 50
        Celsius.new(50).in_fahrenheit.should == 122
      end

      it "is a Temperature subclass" do
        Celsius.new(0).should be_a(Temperature)
      end
    end

    describe "Fahrenheit subclass" do
      it "is constructed in degrees fahrenheit" do
        Fahrenheit.new(50).in_fahrenheit.should == 50
        Fahrenheit.new(50).in_celsius.should == 10
      end

      it "is a Temperature subclass" do
        Fahrenheit.new(0).should be_a(Temperature)
      end
    end
  end

end


texts: Method that returns description attribute of enum value

texts:
I have the following method in .NET Core that returns the description attribute of an enum value. I think this code can be more elegant. I'd appreciate some suggestions.

public static string GetDescription(System.Enum input)
{
   Type type = input.GetType();
   MemberInfo[] memInfo = type.GetMember(input.ToString());

   if (memInfo != null && memInfo.Length > 0)
   {
      object[] attrs = (object[])memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
      if (attrs != null && attrs.Length > 0)
      {
         return ((DescriptionAttribute)attrs[0]).Description;
      }
    }

    return input.ToString();
}


texts:
I am currently working on an app and have some issues with the date handling.
Found a simple solution, and want your opinion.
First thing, that I want to achieve:

I have 2 date format inputs, one is like 2013-09-30 14:20:00 and the other is 30/09/2013 1420
Time stamp is given with no day light saving time.

So, I have to store my date/time in DB with the same format in order to compare one with each other, and also I need to adjust the time stamp +1 hour if it is in the DST period.
For this, I made the following function:

function format_date($date_string, $date_format)
{
$unix = mktime( substr($date_string, strpos($date_format, 'HH'), 2),
                (strpos($date_format, 'ii'))? substr($date_string, strpos($date_format, 'ii'), 2) : '00',
                (strpos($date_format, 'ss'))? substr($date_string, strpos($date_format, 'ss'), 2) : '00',
                substr($date_string, strpos($date_format, 'MM'), 2),
                substr($date_string, strpos($date_format, 'DD'), 2),
                substr($date_string, strpos($date_format, 'YYYY'), 4)
            ) ;
$human = date('Y-m-d H:i:s', $unix);
$dst = date('I', $unix);

return (object)array(
                'unix' => $unix,
                'human' => $human,
                'dst' => $dst
                );
}

//Usage:
$date1 = format_date('2013-09-30 14:20','YYYY-MM-DD HH:ii');
$date2 = format_date('30/09/2013 1420','DD/MM/YYYY HHii');

echo $date1->human ;
echo '
';
echo $date2->human ;
echo '
';
//  $date1->human is the same with $date1->human, also ->unix

Maybe this will help others, but if you find something not right in this function please let me know before I put it in production.

Update: (thank you Glavić)

function format_date1($date_string, $date_format)
{
$date_build = DateTime::createFromFormat ( $date_format , $date_string  );
return (object)array(
                'unix' => $date_build->format('U'),
                'human' => $date_build->format('Y-m-d H:i:s'),
                'dst' => $date_build->format('I')
                );
}
$make_date = format_date1('30/09/2013 1420', 'd/m/Y Hi');
print_r($make_date);
//returns stdClass Object ( [unix] => 1380540000 [human] => 2013-09-30 14:20:00 [dst] => 1 )
//Use: $make_date->unix | $make_date->human | $make_date->dst


texts: A script that uses placeholder attribute to show a typing effect

texts:
An easy to use type feature that uses the placeholder attribute and setTimer to give the effect of a user typing. Helpful if you need to draw attention to the search box field.

I'm looking to know if this type of implementation would be a performance impact or cause browser lag. Help in making this more condensed would also be helpful. I was thinking about using $.extend, but leaned away. Any reason why I shouldn't make this a jquery plugin?

https://jsfiddle.net/googabeast/jsepy3ed/

obj = {
    searchTxt: [
        "Welcome. What are you searching for? ",
        "Something else to type out "
        "Note the space at the end -> "
    ],
    hasFocus:false
}

if(obj.searchTxt !== null && obj.searchTxt !== "undefined"){
    var i = 0, ct = 0; obj.typeIt;

    function type(){
        obj.typeIt = obj.searchTxt[ct].slice(0, ++i);
        if(obj.typeIt === obj.searchTxt[ct]){
            i = 0;
            if(ct === obj.searchTxt.length-1){
                ct = 0;
            }else{
                ++ct;
            }
            return;
        };
        $(".searchBox").attr("placeholder", obj.typeIt);
        setTimeout(type, 80);
    };
    type();

    $(window).on({
        focus: function(){ obj.hasFocus = true; },
        blur: function(){ obj.hasFocus = false; }
    }).trigger("focus");

    setInterval(function(){
        if(obj.hasFocus){
            type();
        };
    }, 10000);
};


texts: Merge multiple pandas dataframe along with np.where to process values

texts:
I have a pandas dataframe, df1:
id  level  val
1   l1     0.2
1   l2     0.1

and another dataframe which contains type for l1 level, df2:
id  type
1   A

Similarly, df3 which contains type for l2 level as well as new ids:
id  new_id  type
1   19      A
1   19      B
1   20      A
1   20      B

Now I want type for l1 level from df2. And for l2 level from df3, while also resetting ids and level. This is what I am doing:
df2['level'] = 'l1'
df3['level'] = 'l2'
df1 = pd.merge(df1, df2, how='outer', on=['id','level'])
df1 = pd.merge(df1, df3, how='outer', on=['id','level'], suffixes=["_", ""])
df1['id'] = np.where(df1['new_id'].isnull(), df1['id'], df1['new_id'])
df1['type'] = np.where(df1['type'].isnull(), df1['type_'], df1['type'])
df1['level'] = np.where(df1['level']=='l2', 'l3', df1['level'])
df1 = df1.drop('new_id', 1)
df1 = df1.drop('type_', 1)

Which finally gives me, df1:
id  level  val  type
1   l1     0.2  A
19  l3     0.1  A
19  l3     0.1  B
20  l3     0.1  A
20  l3     0.1  B

Since df1 is a large dataframe, I want to avoid using np.where thrice, i.e., I am looking for a faster approach to get this. Thanks!


texts: Is there a better way to write insertion sort?

texts:
Background

I am doing an insertion sort and I would like it to be as efficient as the algorithm allows.

Code

After much research, this is what I made:

const isFunction = require("lodash.isfunction"); //copy pasta from lodash :D

const insertion = ( array ) => {

    if(!Array.isArray(array))
        throw new Error("array must be an Array");

    if (array.length === 0)
        return [];

    //shallow copy
    const clonedArray = array.slice();

    //Optimized iterative version: https://en.wikipedia.org/wiki/Insertion_sort
    let i = 1, j, temp;
    while( i < clonedArray.length ){
        temp = clonedArray[i];
        j = i - 1;
        while( j >= 0 && clonedArray[ j ] > temp ){
            clonedArray[ j + 1 ] = clonedArray[ j ];
            j = j - 1;
        }
        clonedArray[ j + 1 ] = temp;
        i = i + 1;
    }

    return clonedArray;
};

module.exports = insertion;

Questions

I tested the code and I know it works. But I wonder if the algorithm available in wikipedia is the best insertion sort algorithm.

Having in mind I wish this function's API to be pure ( I don't want to change the original array, I want to return a new one), I have the following questions:

Is there a better way to code insertion sort?
What improvements can be made to this code?


texts: ASP.NET HTML code generation, two approaches

texts:
I was asked to give more context. So here we go.

We want to create some HTML in code behind to add an "add" and a "refresh" button to a grid view header column. Approach #1 does this using string concatination to produce the necessary HTML, whereas approach #2 uses .NET objects to create exactly the same HTML.

This time I'm posting the complete classes:

Approach #1

class AddBtnTemplate : ITemplate {
    StatRefTimeGrid Parent;
    public AddBtnTemplate(StatRefTimeGrid parent) {
        Parent = parent;
    }
    public void InstantiateIn(Control container) {
        GridViewHeaderTemplateContainer ctr = (GridViewHeaderTemplateContainer)container;
        string html = "
";
        if (Parent.MayEdit)
            html += string.Format("", Texts.CompValue.AddRefTime[Parent.Parent.State.LangIdx]);
        if (ctr.Grid.VisibleRowCount > 1)
            html += string.Format("", Texts.CompValue.RefreshRefTimeGrid[Parent.Parent.State.LangIdx]);
        html += "
";
        ctr.Controls.Add(new LiteralControl(html));
    }
}

Approach #2

private class AddBtnTemplate : ITemplate {
    private readonly StatRefTimeGrid mParent;
    public AddBtnTemplate(StatRefTimeGrid parent) {
        mParent = parent;
    }
    public void InstantiateIn(Control container) {
        GridViewHeaderTemplateContainer templateContainer = (GridViewHeaderTemplateContainer)container;

        HtmlGenericControl div = new HtmlGenericControl("div") {
            Style = {[HtmlTextWriterStyle.Width] = "150px"},
        };
        if (mParent.MayEdit) {
            AddNewImage(div, Texts.CompValue.AddRefTime[mParent.Parent.State.LangIdx], "~/Img/add18d.png", "StatRefTimeGrid.addRow()");
        }
        if (templateContainer.Grid.VisibleRowCount > 1) {
            AddNewImage(div, Texts.CompValue.RefreshRefTimeGrid[mParent.Parent.State.LangIdx], "~/Img/refresh18d.png", "StatRefTimeGrid.refresh()");
        }

        templateContainer.Controls.Add(div);
    }
    private void AddNewImage(HtmlGenericControl div, string altText, string imageUrl, string onClick) {
        div.Controls.Add(new Image {
            AlternateText = altText,
            ToolTip = altText,
            ImageUrl = imageUrl,
            Attributes = {
                ["onclick"] = onClick,
            },
            Style = {
                [HtmlTextWriterStyle.Cursor] = "pointer",
                [HtmlTextWriterStyle.Position] = "relative",
                [HtmlTextWriterStyle.Top] = "3px",
            },
        });
    }
}

I'm looking for arguments for or against either solution. What do you think?


texts: Create individual files via Bash with MD5 hashes of all files in a directory recursively

texts:
I have an archive of photos stored in a directory tree on my Mac like:

./2016/05/17/photo-312.jpg
./2016/05/19/photo-1234.jpg
./2016/05/19/photo-5678.jpg

I want to create MD5 hashes of each file that can be used to verify the photos have not been altered or corrupted. My goals are:

One MD5 file per photo
Store the MD5 files in the same directory their corresponding photos
Use the same base name as the photo, but switch the extension to .md5
Capture only the hash value (e.g. b1046abbe7bbf2a2473e9489599f38e0) without any trailing spaces or newlines

For example, the above directory structure would look like this after the process runs:

./2016/05/17/photo-312.jpg
./2016/05/17/photo-312.md5
./2016/05/19/photo-1234.jpg
./2016/05/19/photo-1234.md5
./2016/05/19/photo-5678.jpg
./2016/05/19/photo-5678.md5

(Note: I only need to run this process one time. The process I use to move photos into the archive will create the necessary MD5 files for new photos from this point forward.)

Here's the one-liner I came up with:

find . -type f -name "*.jpg" -exec bash -c 'printf "%s" $(md5 -q "$0") > "${0%.*}.md5"' {} \;

(Note: my machine has md5 instead of md5sum which I often see referenced. So, I'm using that.)

Here's a few details on how I understand this to work:

The first section runs a basic find command on the current directory (i.e. ".") looking for .jpg files and sends them to bash with -exec bash -c

find . -type f -name "*.jpg" -exec bash -c

Bash runs printf to setup for a string that doesn't have a newline:

printf "%s"

This section generates the hash that is used to feed the string into printf:

$(md5 -q "$0")

The -q flag tells md5 to output only the hash instead of the standard MD5 output which would look something line:

MD5 (photo-312.jpg) = b1046abbe7bbf2a2473e9489599f38e0

The value of $0 is the relative path to the source .jpg file that find sent to bash.
This section creates the file path to store the value in where the original extension is replaced by .md5:

"${0%.*}.md5"

More details about what's going on there can be found in the ${parameter%word} section of the Bash Manual.
The last little bit is:

{} \;

I'm not sure why, but the {} is necessary to make this run. (My understanding is that it's a reference to the file path. I don't know how that ties in, but md5: bash: No such file or directory errors pop up if it's not there.)

Finally, the \; identifies the end of find's -exec.

While I normally use other languages for this type of work, I decided to try this with bash to get some practice with it. I've done some basic testing and everything appears to work as expected. Given my infrequent use of bash, I'd like to make sure I'm not getting myself in trouble. So, my questions are:

Are there any gotchas in this code that are waiting to bite me?
Is there a more standard or efficient way to do this?

UPDATE: I modified my code based on the answers. In case it's useful, here's what I ended up with:

find . -type f \( -name '*.cr2' -or -name '*.jpg' \) -execdir sh -c 'sha1sum "{}" > "${1%.*}".sha1' -- {} \;

Which:

Allows for multiple file extension to be processed at the same time.
Uses -execdir instead of -exec so the default output of the hashing algorithm don't contain paths. (Which is one reasons I was trying to strip them originally).
Instead of md5 uses sh1sum which provides a sha1sum -c flag for verifying files and didn't require installation via homebrew.
Uses the more appropriate ${1%.*} (with the help of the -- at the end) instead of ${0%.*} to remove the initial file extension.


texts: Python program for testing the Collatz Conjecture

texts:
This is a simple program to test if integers will follow an interesting, improvable statement that if disproven, calls for a bravo.

But, ignoring the pretentious poetry, this code allows the user to input a number, which, if it is a finite, positive integer, will be calculated according to the Collatz Conjecture as stated/commented out below. Any optimizations? Obvious mistakes? Formatting issues?

Maybe let me know how to inform the user that the function-ception went a few levels too deep?

# The Collatz conjecture states that
# when you take a finite, positive integer, and
# if it's even, divide by 2, or
# if it's odd, multiply by 3 and add 1,
# and repeat this process enough times,
# you will eventually end up with one.
# Here's a module to demonstrate it.

def collatz(x):
  if abs(int(x)) == x:
    if x == 1:
      print ("The Collatz Conjecture works with this number!")
      print ("It took %s repetitions to reach 1.") % (collatz.counter)
    elif x % 2 == 0:
      y = x / 2
      print ("%s") % (y)
      collatz.counter += 1
      collatz(y)
    elif x % 2 == 1:
      y = x * 3 + 1
      print ("%s") % (y)
      collatz.counter += 1
      collatz(y)
    else:
      print ("Oh, my god!")
      print ("This number does NOT work with the Collatz Conjecture!")
      print ("You've disproven it!")
      print ("...Or maybe this program is broken. Try viewing the source?")
  else:
    print ("That isn't a finite positive integer...")

collatz.counter = 0

#Here's our attempt:

collatz(int(raw_input("Enter a finite positive integer")))


texts:
A \$Z^m\$ number system includes integers in the interval \$[0, m)\$ when \$m > 0\$ or \$(m, 0]\$ when \$m < 0\$. The code defines a trait Mod to represent numbers in this system and the +, -, and * operator for it.

use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;
use std::ops::Rem;

struct Mod<T>
    where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone
{
    modulo: T,
    i: T,
}

trait Modulo<T>
    where T: Add<Output=T> + Rem<Output=T> + Copy + Clone
{
    fn modulo(self, n: T) -> T;
}

impl<T> Modulo<T> for T
    where T: Add<Output=T> + Rem<Output=T> + Copy + Clone
{
    fn modulo(self, n: T) -> T {
        ((self % n) + n) % n
    }
}

impl<T> Mod<T>
    where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone
{
    fn new(modulo: T, i: T) -> Mod<T> {
        let n = i.modulo(modulo);
        Mod {
            modulo: modulo,
            i: n,
        }
    }
}

impl<T> Add for Mod<T>
    where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone
{
    type Output = Mod<T>;
    fn add(self, other: Mod<T>) -> Mod<T> {
        Mod::new(self.modulo, self.i + other.i)
    }
}

impl<T> Sub for Mod<T>
    where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone
{
    type Output = Mod<T>;
    fn sub(self, other: Mod<T>) -> Mod<T> {
        Mod::new(self.modulo, self.i - other.i)
    }
}

impl<T> Mul for Mod<T>
    where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone
{
    type Output = Mod<T>;
    fn mul(self, other: Mod<T>) -> Mod<T> {
        Mod::new(self.modulo, self.i * other.i)
    }
}

fn main() {
    let x = Mod::new(-5i8, 3i8);
    let y = Mod::new(-5i8, 8i8);
    println!("{}", (x + y).i);
    let x = Mod::new(-5i8, 3i8);
    let y = Mod::new(-5i8, 8i8);
    println!("{}", (x - y).i);
    let x = Mod::new(-5i8, 3i8);
    let y = Mod::new(-5i8, 8i8);
    println!("{}", (x * y).i);
    let x = Mod::new(-5i16, 3i16);
    let y = Mod::new(-5i16, 8i16);
    println!("{}", (x + y).i);
    let x = Mod::new(-5i16, 3i16);
    let y = Mod::new(-5i16, 8i16);
    println!("{}", (x - y).i);
    let x = Mod::new(-5i16, 3i16);
    let y = Mod::new(-5i16, 8i16);
    println!("{}", (x * y).i);
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x + y).i);
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x - y).i);
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x * y).i);
    let x = Mod::new(5u8, 3u8);
    let y = Mod::new(5u8, 8u8);
    println!("{}", (x + y).i);
    let x = Mod::new(5u8, 3u8);
    let y = Mod::new(5u8, 8u8);
    println!("{}", (x - y).i);
    let x = Mod::new(5u8, 3u8);
    let y = Mod::new(5u8, 8u8);
    println!("{}", (x * y).i);
}

I tried to achieve the goals laid out in the previous version:

Changed the modulo method for better performance.
Generalized over a bunch of types other than i32.

All suggestions are still welcome. In particular, requiring T to implement Copy and Clone might be a bit too restrictive, I would like to relax that.


texts: An Edit action in ASP.NET MVC, with handling for missing id parameter

texts:
I have a standard Edit action in Asp.Net MVC 5 and I want to avoid throwing the unhandled exception when is made a get request without the id like ~/food/edit, so I did this.

public ActionResult Edit(int id = 0)
{
    if (id == 0)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    string result = _foodAppService.GetById(id);
    FoodVm food = string.IsNullOrEmpty(result)
        ? null
        : JsonConvert.DeserializeObject<FoodVm>(result);

    if (food == null)
    {
        return RedirectToAction("Index");
    }

    return View(food);
}

My question is: Is it a good practice to handled it in this way or there are more suitable strategies ?

I'm new to this asking question thing, if a should I ask in another way, just let me know, thank you for your time.


texts: Change the title attribute of summary if details is open

texts:
I have this JavaScript code that functions as intended, although as a beginner, I do not know of a shorter, more efficient way of writing it.

The code is a simple toggle that changes the title attribute of the <summary> HTML tag from hide to show when the user clicks on the <summary> to open the <details>.

I used loops since there are several of these in my page:

var i,l;

var detailsElem = document.getElementsByTagName('details'),
summaryElem = document.getElementsByTagName('summary'),
summElemLen = summaryElem.length;
detlElemLen = detailsElem.length;

function detailsToggle() {
  for (i = 0; i < summElemLen; i++) {
    if (detailsElem[i].open === true) {
      summaryElem[i].title = 'hide';
    }
    else {
      summaryElem[i].title = 'show';
    }
  }
}

for (i = 0; i < detlElemLen; i++) {
  detailsElem[i].ontoggle = function() {detailsToggle()};
}

Is there a less verbose way of achieving the same function?


texts:
I decided to build my own fade-in fade-out function, since that is all I need on my page.

Please comment on things I can make better.

<!DOCTYPE html>

<title></title>
<meta charset="utf-8" />

        Fade In |
        Fade Out

Fading Box


texts: Inserting customer care database analysis detail records

texts:
I have written this linq-to-sql query to insert a bunch of customer care database analysis detail records:

DataClasses1DataContext behzad = new DataClasses1DataContext(conn);
            var query = (from p in behzad.Customer_Care_Database_Analysis_TEMPs
                         select p).ToArray();

            for (int i = 0; i < query.Count(); i++)
            {
                Customer_Care_Database_Analysis_DETAIL custom_detail = new Customer_Care_Database_Analysis_DETAIL();
                custom_detail.code_faaliyat = query[i].code_faaliyat.Trim();
                custom_detail.code_markaz = query[i].code_markaz.Trim();
                custom_detail.code_switch = query[i].code_switch.Trim();
                custom_detail.ellate_xata = query[i].ellate_xata.Trim();
                custom_detail.name_faaliyat = query[i].name_faaliyat.Trim();
                custom_detail.name_markaz = query[i].name_markaz.Trim();
                custom_detail.name_switch = query[i].name_Switch.Trim();
                custom_detail.noe_moshtarak = query[i].haq_hoq.Trim();
                custom_detail.shomare_tel = query[i].phone_number.Trim();

                behzad.Customer_Care_Database_Analysis_DETAILs.InsertOnSubmit(custom_detail);
                behzad.SubmitChanges();

            }

The code works, but it can take a long time - more than 10 minutes for my data.

How can I speed this up?


texts: Repository pattern method implementation with entity framework and C#

texts:
I have two entities in my database: Employee and Shift. I want to implement a C# repository pattern method, that given two workshift IDs, swaps the two workshifts for two employees.
Limitation: one employee cannot work multiple shifts at a time.
Models
public class Employee
{
    public int ID { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
}

public class WorkShift
{
    public int ID { get; set; }
    public int EmployeeID { get; set; }
    public DateTime ShiftStart { get; set; }
    public DateTime ShiftEnd { get; set; }
}

Repository
public class WorkShiftRepository : RepositoryBase<WorkShift>, IWorkShiftRepository
{
    private readonly ShiftContext _databaseContext;

    public WorkShiftRepository(ShiftContext context) : base(context)
    {
        _databaseContext = context;
    }

    private async Task<bool> Overlaps(WorkShift shift, int employeeId)
    {
        return await _databaseContext.Shifts.Where(u => u.EmployeeID == employeeId).
            Where((s => shift.ShiftStart < s.ShiftEnd && s.ShiftStart < shift.ShiftEnd)).AnyAsync();
    }

    public async Task<int> SwapShifts(int shiftIdA, int shiftIdB)
    {
        var result = 0;
        // Load shifts into memory
        var shiftA = await _databaseContext.Shifts.SingleAsync(s => s.ID == shiftIdA);
        var shiftB = await _databaseContext.Shifts.SingleAsync(s => s.ID == shiftIdB);
        int shiftAid = shiftA.EmployeeID;

        // Swap Employee IDs
        shiftA.EmployeeID = shiftB.EmployeeID;
        shiftB.EmployeeID = shiftAid;

        // Check if the swapped shifts has any overlaps on db
        if (await Overlaps(shiftA, shiftA.EmployeeID) || await Overlaps(shiftB, shiftB.EmployeeID))
            throw new Exception("ShiftsOverlap");

        // update in memory
        _databaseContext.Shifts.Update(shiftA);
        _databaseContext.Shifts.Update(shiftB);

        // Write changes to DB
        result = await _databaseContext.SaveChangesAsync();

        return result;
    }
}

The code compiles and it meets the limitations. But I am looking for tips and tricks to make the code cleaner and/or more efficient.


texts:
I suspect there is a simpler way to find if a select has a certain option, but don't know what. The objective of the following is to check if the desired option exists or not, and if it does, set it as the selected option:

Markup

<input type="text" size="2" id="selectVal"/>
<button onclick="setSelect()">Set the select</button>
<select id="mySelect">
    <option value="0">Select an option</option>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</select>

JS

function setSelect() {
    var desiredOption = $("#selectVal").val();
    if (desiredOption == '') {
        $("#selectVal").focus();
        return false;
    }
    var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
    if (hasOption.length == 0) {
        alert('No such option');
    } else {
        $('#mySelect').val(desiredOption);
    }
    $("#selectVal").select();
}

To be clear, I wonder if a single method could do the job of the following two lines:

var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
if (hasOption.length == 0)

Any suggestions?

jsfiddle here.


texts: Finding the position in a triangle for the given challenge

texts:
The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space station, and as a result
the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given
numerical IDs starting from the corner, as follows:

| 7

| 4 8

| 2 5 9

| 1 3 6 10

Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y being the height from the ground.

For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners).

Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your answer as a  string representation of the number.

Here is my solution:

y = int(input())
x = int(input())
sum_in_x = 1
for i in range(x):
    sum_in_x = sum_in_x + range(x)[i]
    in_sum =i + 2
sum_in_y = sum_in_x
for j in range(y - 1):
    sum_in_y = sum_in_y + in_sum
    in_sum += 1
print(sum_in_y)

It works and generates the needed solutions, but I am trying to understand if there are better ways of doing this.


texts: Find the fastest run of each year from a list of running results

texts:
Problem Explained:

Imagine there is a list of running results of 1000m, like following:

[
    { id: 1, date: '2017-01-01 00:00:00', duration: 195 },
    { id: 2, date: '2017-01-10 00:00:00', duration: 270 },
    { id: 3, date: '2017-03-12 00:00:00', duration: 220 },
    { id: 4, date: '2018-01-10 00:00:00', duration: 218 },
    { id: 5, date: '2018-02-23 00:00:00', duration: 220 },
    { id: 6, date: '2018-05-18 00:00:00', duration: 215 }
]

I'd like to find out the fastest run of each year, which will be

[
    { id: 1, date: '2017-01-01 00:00:00', duration: 195 },
    { id: 6, date: '2018-05-18 00:00:00', duration: 215 }
]

Here's my ugly solution (TypeScript):

const items = JSON.parse('Use the JSON above.');
const results: any[] = [];
const fastestOfEachYear: object = {};
const idsOfFastestEachYear: object = {};

// Go through the list to find the fastest of each year.
// Save the IDs in an object.
items.forEach((item) => {
    const runId = item['id'];
    const date = item['date'];
    const dateParts = date.split('-');
    const year = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]).getFullYear();
    const duration = item['duration'];

    // Found a faster one, update our objects with the new item.
    if (fastestOfEachYear[year] == null || fastestOfEachYear[year] > duration) {
        fastestOfEachYear[year] = duration;
        idsOfFastestEachYear[year] = runId;
    }
});

// Retrieve the IDs of the runs that are the fastest of a year.
const idsOfFastest = Object.keys(idsOfFastestEachYear).map((key) => idsOfFastestEachYear[key]);

// Loop through the list again to find those items matching the IDs
// Save them to results.
items.forEach((item) => {
    const runId = item['id'];
    if ($.inArray(runId, idsOfFastest) !== -1) {
        results.push(item);
    }
});

Surely there are nicer and better ways of achieving this? (Reviews in TypeScript, ES6 or even just Vanilla JS are ok.)


texts: Getting keyboard input for real-time console application

texts:
I've been building an IDE using C# and only the console. To get keyboard input in real time (as opposed to a read–eval–print loop,) I have the following method to get keyboard input:
public static ConsoleKeyInfo[] GetInput()
{
    // A list of characters
    List<ConsoleKeyInfo> input = new List<ConsoleKeyInfo>();

    // Loop while keys are available or we hit 10 keys
    for (int i = 0; Console.KeyAvailable && i < 10; i++)
    {
        // Read a key (preventing it from being printed)
        // and put it in the key list (if it's not in there yet)
        ConsoleKeyInfo info = Console.ReadKey(true);
        if (!input.Contains(info))
        {
            input.Add(info);
        }
    }

    // Use up any remaining key presses
    while (Console.KeyAvailable)
    {
        // Read a single key
        Console.ReadKey(true);
    }

    // Convert the list to an array and return
    return input.ToArray();
}

GetInput called once at the start of the main loop and the result is passed into objects that handle key presses:
ConsoleKeyInfo[] keysHit = ConEx.ConEx_Input.GetInput();
Program.Interpreter.Update(Program.Interpreter.CurMode, keysHit);
Program.WindowUI.Update(Program.Interpreter.CurMode, keysHit);
Program.WindowSideBar.Update(Program.Interpreter.CurMode, keysHit);

Inside an Update method:
for (int i = 0; i < keysHit.Length; i++)
{
    switch (keysHit[i].Key)
    {
        //Cycle through the pages
        case ConsoleKey.Home:
            //Do some stuff
            break;
        case ConsoleKey.End:
            //Do other stuff
            break;
    }
}

Is this a sub optimal solution for getting keyboard input? I'm very willing to breakout P/Invoke or a threaded solution if need be. I can't support an event handler based solution due to the tight control of sequence needed.
Edit:
Nikita B's answer is marked as Accepted because it reduced the amount of ticks taken from ~60 to ~30. Thanks!


texts: Golang - Splitting a string by a separator not prefixed by an escape string

texts:
I need to split a string by a separator but don't want to split if the separator is prefixed by the escape string.
For example:
"This works\\ but it\\ isn't pretty." with " " as the separator and "\\" as the escape string should produce the following: []string{"This", "works but", "it isn't", "pretty."}
I wrote the following code for it:
func SplitWithEscaping(s string, separator string, escapeString string) []string {
    untreated := strings.Split(s, separator)
    toReturn := make([]string, 0, len(untreated))
    for i := 0; i < len(untreated); i++ {
        next, ii := t(untreated, i, separator, escapeString)
        i = ii - 1
        toReturn = append(toReturn, strings.ReplaceAll(next, escapeString+separator, separator))
    }
    return toReturn
}

func t(stringSlice []string, i int, seperator, escapeString string) (string, int) {
    if !strings.HasSuffix(stringSlice[i], escapeString) {
        return stringSlice[i], i + 1
    }
    next, ii := t(stringSlice, i+1, seperator, escapeString)
    return stringSlice[i] + seperator + next, ii
}

This is the playground link for my working code: https://play.golang.org/p/jfHFt9_vtE7
How can I make my code prettier but also more performant?


texts: Find largest palindrome from the product of two 3-digit numbers

texts:
I think this is a good solution to finding the largest numeric palindrome that can be formed from the product of two 3-digit numbers... But it seems like there are some improvements that we could make which I haven't thought of...

Given int inputs[899] which is initialized by: iota(begin(inputs), end(inputs), 100), Do you guys have any thoughts on this code:

for(auto it = crbegin(inputs); it != crend(inputs) && *it * *it > max_product; ++it) {
    const auto rhs = find_if(it, crend(inputs), [lhs = *it](const auto rhs){
        const auto input = to_string(lhs * rhs);

        return equal(cbegin(input), next(cbegin(input), size(input) / 2U), crbegin(input));
    });

    if(crend(inputs) != rhs) {
        const auto product = *it * *rhs;

        if(product > max_product) {
            max_product = product;
            max[0] = *it;
            max[1] = *rhs;
        }
    }
}

Live Example

This will correctly find 993 and 913 as the pair of 3-digit numbers that would form the largest numeric palindrome.


texts: Printing a calendar for a month based on user input

texts:
I have a long piece of code that has many repeating points. I am sure that it doesn't take this amount of code to create a simple calendar, but I do not know how to shorten this piece of code.

# Creating a calendar in proportion to the user defined starting date

n = int(input('Enter number of days: '))#days in a month
s = input('The first day of the week: ')#The date that user wants the month to start
s = s.capitalize()

lis1 = ['Sa','M','T','W','Th','F','Su']
print('{:>3}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}'.format('Sa','M','T','W','Th','F','Su'))

for i in range(1,n+1):#loop to generate the dates for a month
  if s==lis1[0] and i ==1:#this is to determine how much should the code indent to align to traditional calendar formatting
    print('{:>3}'.format(i),end =' ')
  elif s==lis1[1] and i ==1:
    print(' '*4+'{:>3}'.format(i),end =' ')
  elif s==lis1[2] and i ==1:
    print(' '*8+'{:>3}'.format(i),end =' ')
  elif s==lis1[3] and i ==1:
    print(' '*12+'{:>3}'.format(i),end =' ')
  elif s==lis1[4] and i ==1:
    print(' '*16+'{:>3}'.format(i),end =' ')
  elif s==lis1[5] and i ==1:
    print(' '*20+'{:>3}'.format(i),end =' ')
  elif s==lis1[6] and i ==1:
    print(' '*24+'{:>3}'.format(i),end =' ')
  else:
    print('{:>3}'.format(i),end =' ')#after the indent this is to print the remaining dates

  if s==lis1[0] and i%7==0:#this is to print a new line in proportion the choosen starting date so as to stay in check with the traditional calendar format
    print()
  elif s==lis1[1] and i%7==6:
    print()
  elif s==lis1[2] and i%7==5:
    print()
  elif s==lis1[3] and i%7==4:
    print()
  elif s==lis1[4] and i%7==3:
    print()
  elif s==lis1[5] and i%7==2:
    print()
  elif s==lis1[6] and i%7==1:
    print()

This is an example of the calendar I am outputting.

Please guide me on shortening code that is related to loops if possible.


texts:
In light of this months Community Challenge, I've taken a stab at building something related. Keep in mind, this isn't a submission for the challenge, just a utility to help in the later process of completing the challenge.

What we have here is your simple encryption and decryption (with a given key) tool. I'd like to know if what I have is the most efficient, the most well written, and the simplest form of these functions.

import random

alpha = "abcdefghijklmnopqrstuvwxyz"

def encrypt(original, key=None):

    if key is None:
        l = list(alpha)
        random.shuffle(l)
        key = "".join(l)

    new = []

    for letter in original:
        new.append(key[alpha.index(letter)])

    return ["".join(new), key]

def decrypt(cipher, key=None):
    if key is not None:
        new = []
        for letter in cipher:
            new.append(alpha[key.index(letter)])

        return "".join(new)
    # we'll have an else here for the actual Community Challenge!

I'm nowhere near an expert with Python, so if I'm not following coding standards, please guide me there too.

A simple test might be:

e = encrypt("helloworld", None)
print(e)
print(decrypt(e[0], e[1]))

and we'd get something along the lines of:

['wussndnkst', 'qxvtupaweroslynzhkbigcdjmf']
helloworld


texts: Comparer that compares by int than by enum type

texts:
Below is the implementation of a comparer that compares objects of type Region first by index and then by it's type. The sort order of the type is defined within the comparer.

I know, it's a trivial piece of code, however I am happy about any comments about the realization. :)

public class Region
{
    public RegionType Type { get; set; }
    public int Index { get; set; }
}

public enum RegionType
{
    DeletionBeforeNamedRegion,
    DeletionWithinNamedRegion,
    DeletionAfterNamedRegion,
    InsertionBetweenNamedRegions,
    InsertionWithinNamedRegion,
    NamedRegion,
}

public class RegionComparer : IComparer<Region>
{
    private static readonly List<RegionType> sortOrderByType = new List<RegionType>
        {
            RegionType.DeletionBeforeNamedRegion,
            RegionType.NamedRegion,
            RegionType.DeletionWithinNamedRegion,
            RegionType.InsertionWithinNamedRegion,
            RegionType.DeletionAfterNamedRegion,
            RegionType.InsertionBetweenNamedRegions,
        };

    public int Compare(Region x, Region y)
    {
        if (x == null && y == null)
            return 0;
        if (x == null) return -1;
        if (y == null) return 1;

        var result = x.Index.CompareTo(y.Index);
        if (result != 0) return result;

        var xSort = sortOrderByType.IndexOf(x.Type);
        var ySort = sortOrderByType.IndexOf(y.Type);

#if DEBUG
        if (xSort < 0 || ySort < 0)
            throw new NotImplementedException($"Sort order for region type '{(xSort < 0 ? x.Type : y.Type)}' is not defined. Please extend the '{nameof(sortOrderByType)}' list." );
#else
        if (xSort < 0) xSort = int.MaxValue;
        if (ySort < 0) ySort = int.MaxValue;
#endif
        return xSort.CompareTo(ySort);
    }
}


texts: Duplicate detection and reporting in a BST

texts:
For the purpose of this problem, the BST is defined to allow duplicates, and the duplicate values will always follow to the right-side of the parent nodes with the same value. For example, with the data:

 1, 2, 2, 2, 2

if the root node has the value 2 (as opposed to 1) then the tree will look like:

          2
         / \
        1   2
             \
              2
               \
                2

The following code scans the tree, identifies any values that are duplicated, and prints the duplicate values, as well as how many times that value is duplicated.

public class DuplicateCountInBST {

    private TreeNode root;

    private class TreeNode {
        TreeNode left;
        int item;
        TreeNode right;

        TreeNode (TreeNode left, int item, TreeNode right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    private class DuplicateInfo {
        int item;
        int count;

        public DuplicateInfo(int item, int count) {
            this.item = item;
            this.count = count;
        }
    }

    public void print () {
        if (root == null) {
            return;
        }
        // find right most node.
        TreeNode rightMostNode = root;
        while (rightMostNode.right != null) {
            rightMostNode = rightMostNode.right;
        }

        printHelper (root, root.item, new DuplicateInfo(0, 0), rightMostNode);
    }

    // inorder traversal
    // rightmostnode is a guard against skewed trees.
     private void printHelper (TreeNode node, int prevValue, DuplicateInfo duplicateInfo, TreeNode rightMostNode) {
         if (node == null) {
             return;
         }

         printHelper(node.left, node.item, duplicateInfo, rightMostNode);

         if (node.item == duplicateInfo.item) {
             duplicateInfo.item = node.item;
             duplicateInfo.count++;

         }
         if (node.item != duplicateInfo.item || node == rightMostNode) {
             if (duplicateInfo.count > 1) {
                 System.out.println(duplicateInfo.item + " : " + duplicateInfo.count);
             }
             duplicateInfo.item = node.item;
             duplicateInfo.count = 1;
         }

         printHelper(node.right, node.item, duplicateInfo, rightMostNode);
     }
 }


texts: Get argument as unicode string from argparse in Python 2 and 3

texts:
Code from my last project, that has to work on Python 2.7 and Python 3.
I want to get a path as a unicode string from argparse:

parser = argparse.ArgumentParser(
    description='Organize your movie collection using symbolic links')
parser.add_argument('media_src', metavar='FILE|DIR',
                    help='Media file or directory')
args = vars(parser.parse_args(args=argv[1:]))
try:
    args['media_src'] = unicode(args['media_src'], "utf-8",
                                errors="ignore")
except NameError:
    pass  # py3

Can that be done more elegantly without relying on duck typing?


texts:
As a Python newbie, I have coded this binary tree as best as I could to follow Python
idioms. However, I know it is still very verbose and not up to standard. I would like Python experts to tear this apart and identify its weaknesses.

class TreeNode(object):
  """ applicable to all tree nodes including root node """
  def __init__(self, value, left=None, right=None,root=False):
    self.value = value
    TreeNode.check(left)
    TreeNode.check(right)
    self.left = left
    self.right = right
    self.root = root

  def inorder(self):
    s = list()
    if not self.left:
      s.append('')
    else:
      s.append(self.left.inorder())

    s.append(str(self.value))

    if not self.right:
      s.append('')
    else:
      s.append(self.right.inorder())

    return ' '.join(s).strip()

  # returns True if success, False otherwise
  def insert( self, new_value ):
    # TODO ?? what happens if we are inserting strings
    if not new_value and new_value != 0:
      return False

    if new_value == self.value:
      return False

    # need to find the right location in terms of binary tree ordering
    if new_value < self.value:
      if not self.left:
        self.left = TreeNode(new_value)
        return True
      else:
        return self.left.insert( new_value )
    elif new_value > self.value:
      if not self.right:
        self.right = TreeNode(new_value)
        return True
      return self.right.insert( new_value )

    return False

  @staticmethod
  def check(node):
    if not node:
      return
    if not isinstance(node, TreeNode):
      raise TypeError('only instances of TreeNode are allowed')

  def __repr__(self):
    return '(' + repr(self.left) + ',' + \
      str(self.value) + ',' + repr(self.right) + ')'


texts:
Problem:

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

Solution:

#include <stdio.h>
#include <stdlib.h>

void print_answer(int limit){

    int a = 1; //1st term
    int b = 2; //2nd term
    int even_fibbonaci = 0; //start as zero,because of the loop
    int sum = 2;//sum of even up to 2nd term
    int steps_taken = 0;
    do{
        sum += even_fibbonaci;
        even_fibbonaci = 2*a + 3*b; //even fibbonaci
        a += 2*b; //fibbonaci just before even fibbonaci
        b = even_fibbonaci;
        steps_taken++;
    }while(even_fibbonaci<limit);

    printf("Sum of the even-valued fibbonaci below %d\n",limit);
    printf("Answer = %d, Steps Taken = %d\n",sum,steps_taken);

}

int main(int argc, char ** argv){

    if(argc!=2){
        printf("Invalid number of arguments\n");
        printf("Usage a.exe [limit]\n");
        return -1;
    }

    int limit = atoi(argv[1]);

    if(limit < 3){
        printf("Invalid input\n");
        printf("Enter a limit of 3 or more\n");
        return -1;
    }

    print_answer(limit);

    return 0;
}

For limit = 4000000

Execute as {executable} [limit]

  Sum of the even-valued fibbonaci below 4000000

  answer = 4613732, steps taken = 11

Compiler:


texts: Create a simple hangman game using OOP and Javascript

texts:
I had a task to create a simple hangman game using O.O.P. with Javascript. It had to render the puzzle and remaining guesses to the DOM but didn't require any C.S.S.
This is what I created.
This is my index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

This is my hangman.js which is used to create a hangman object
"strict";
const Hangman = function (word, remainingGuesses) {
  this.word = word.toLowerCase().split("");
  this.remainingGuesses = remainingGuesses;
  this.guessedWords = new Set();
  this.status = "Playing";
};

Hangman.prototype.getPuzzle = function () {
  let puzzle = [];
  this.word.forEach((char) => {
    this.guessedWords.has(char) || char === " "
      ? puzzle.push(char)
      : puzzle.push("*");
  });
  return puzzle.join("");
};

Hangman.prototype.makeGuess = function (guess) {
  guess = guess.toLowerCase();
  const isUnique = !this.guessedWords.has(guess);
  const isBadGuess = !this.word.includes(guess);

  if (isUnique) {
    this.guessedWords.add(guess);
  }

  if (isUnique && isBadGuess && this.status === "Playing") {
    this.remainingGuesses--;
  }

  this.calculateStatus();
};

Hangman.prototype.calculateStatus = function () {
  const finsished = this.word.every((letter) => this.guessedWords.has(letter));

  if (this.remainingGuesses === 0) {
    this.status = "Failed";
  } else if (finsished) {
    this.status = "Finished";
  } else {
    this.status = "Playing";
  }
};

Hangman.prototype.getStatus = function(){

  let message = "";

  if (this.status === "Playing") {
    message = `Remaining Guesses: ${this.remainingGuesses}`
  } else if(this.status === "Failed") {
    message = `Nice try! The word was ${this.word.join("")}`;
  } else {
    message = `Great Work! You guessed the word!!!`
  }

  return message;
}

and this is the app.js where I create an instance of the hangman game
"strict";
const puzzle = document.querySelector("#render-puzzle");
const guesses = document.querySelector("#guesses");

const hangman = new Hangman("Cat", 2);
generatePuzzleDom();

window.addEventListener("keypress", (e) => {
  hangman.makeGuess(e.key);
  generatePuzzleDom();
  console.log(hangman.status);
});

function generatePuzzleDom() {
  puzzle.innerHTML = hangman.getPuzzle();
  guesses.innerHTML = hangman.getStatus();
}


texts: Processing a string containing product variants

texts:
I have a variable containing a string in this format "Size-XS|Size-XL|Color-Red|Color-Green". When i process it the final result is "Variations: Size: XS, XL, Color: Green, Red. The code for this is like below.

$variations = explode("|", $search_db_row['variations']);
 foreach ($variations as $variations_arr1) {
  $variations_arr1_exp = explode("-", $variations_arr1);
  $variations_arr[$variations_arr1_exp[0]][] = $variations_arr1_exp[1];
 }
foreach ($variations_arr as $variations_arr2k => $variations_arr2v) {
 $variation.= $variations_arr2k.": ";
 foreach ($variations_arr2v as $variations_arr2_value) {
  $variation.= mb_strtolower($variations_arr2_value, "utf-8").", ";
 }
}

Is there a simpler way to achieve this? I think there are too much foreach's but I'm not sure how can I do it with less code.


texts: Database code for Python-based URL shortener

texts:
I had implemented a URL shortener with Python and a database. Please review the database part of the code. The idea is to create an MD5 hash of the URL in question and then store it in a database. The hex digits of the MD5 hash is then encoded with a large base encoding i.e base 62 encoding or base 128 encoding to do away with the long length of the hash. The rest of the code can be found on https://github.com/hirok19/URLShortener.

import pysqlite3
import hashlib
class DatabaseConnector:
    cursor=None
    conn=None
    def __init__(self,path):
        try:
            self.conn = pysqlite3.connect(path)
            self.cursor=self.conn.cursor()
        except:
            print("Unable to initialize database")

    def createTable(self):
        try:
            self.cursor.execute("""CREATE TABLE IF NOT EXISTS urlTable (id,url)""")
        except Exception as e:
            print("Unable to create table")
            print(e)

    def insertURL(self,URL):
        key=self.getKey(URL)
        #print(type(key))
        insert_stmt = ("INSERT INTO urlTable (id,url) VALUES ('{0}','{1}');")
        statement=insert_stmt.format(key,URL)
        #print(statement)
        try:
            if(self.getURLFromKey(key) is None):
                self.cursor.execute(statement)
                self.conn.commit()
                print("Data inserted!")
            else:
                print("Data already present")
        except Exception as e:
            print("Unable to insert data")
            print(e)
            return None
        return key
    def getKey(self,URL):
        hashedKey=hashlib.md5(URL.encode())
        return hashedKey.hexdigest()

    def getURLFromKey(self,key):
        insert_stmt=("SELECT url from urlTable where id='{0}';")
        statement=insert_stmt.format(key)
        #print(statement)
        try:
            self.cursor.execute(statement)
            rows = self.cursor.fetchall()
            if(len(rows)>0):
                return rows[0][0]
            else:
                return None

        except Exception as e:
            print("Unable to fetch URL")
            print(e)
            return None