texts:
I wrote a simple function for retrying the passed function in case it throws.
I did it for my app that needs to call an external API through the network, which may spuriously fail.
export async function retry(fn, retries, delayMs, onFailedAttempt = null) {
    let lastError = null;

    for (let attempt = 0; attempt <= retries; attempt++) {
        if (attempt > 0) {
            await delay(delayMs);
        }

        try {
            const res = await fn();
            return res;
        } catch (error) {
            if (onFailedAttempt) {
                onFailedAttempt(error, attempt, retries, delayMs);
            }

            if (window.verbose) {
                console.debug(`Trial ${attempt + 1}/${retries} failed. Retrying in ${delayMs}ms...`);
            }

            lastError = error;
        }
    }

    throw lastError;
}

This seems to work, do you folks think I have overlooked any corner case?


texts:
I've heard about the binary search in an intro class I took a couple months ago, remembered how it worked and read this article, so I attempted to write my first binary search in Python. It works, but when I look at other people's attempts in the article, their code looks cleaner and a bit different.

My two main questions are:

What can I do to optimize my code from here?
Am I even performing a true binary search?

def binsearch(mylist, keyval):
large = len(mylist)-1
small = 0
temp = (len(mylist)-1)/2
key = 'undefined'
flag = 0
while flag == 0:
    if mylist[small] == keyval:
        key = small
        flag = 1
    elif mylist[large] == keyval:
        key = large
        flag = 1
    elif mylist[temp] == keyval:
        key = temp
        flag = 1
    elif temp + 1 == large or temp -1 == small:
        flag = 1
    if keyval > mylist[temp]:
        small = temp
        temp = small + (large - small)/2
    elif keyval < mylist[temp]:
        large = temp
        temp = temp - (large-small)/2
return key


texts:
Examples:

char test1[] = "               ";
char test2[] = "   hello  z";
char test3[] = "hello world   ";
char test4[] = "x y z ";

Results:

"               "
"   olleh  z"
"olleh dlrow   "
"x y z "

The problem:

  Reverse every world in a string, ignore the spaces.

  The following is my code. The basic idea is to scan the string, when
  finding a word, then reverse it. The complexity of the algorithm is
  O(n), where n is the length of the string.

Could anyone help me verify it? Is there any better solution?

void reverse_word(char* s, char* e)
{
    while(s < e)
    {
        char tmp = *s;
        *s = *e;
        *e = tmp;
        ++s;
        --e;
    }
}

char* word_start_index(char* p)
{
    while((*p != '\0') && (*p == ' '))
    {
        ++p;
    }

    if(*p == '\0')
        return NULL;
    else
        return p;
}

char* word_end_index(char* p)
{
    while((*p != '\0') && (*p != ' '))
    {
        ++p;
    }

    return p-1;
}

void reverse_string(char* s)
{
    char* s_w = NULL;
    char* e_w = NULL;
    char* runner = s;

    while(*runner != '\0')
    {
        char* cur_word_s = word_start_index(runner);
        if(cur_word_s == NULL)
            break;
        char* cur_word_e = word_end_index(cur_word_s);
        reverse_word(cur_word_s, cur_word_e);
        runner = cur_word_e+1;
    }
}


texts: Jest - mocking a class function from an external node module

texts:
I am writing unit tests for a NestJS service, which imports and instantiates a class (OAuth2Client) from an external module (google-auth-library) and uses one of its functions (verifyIdToken).
I am mocking the class to override that function as follows:
// service.test.ts

jest.mock('google-auth-library', () => {
  return {
    OAuth2Client: jest.fn(),
  };
});
import { OAuth2Client } from 'google-auth-library';

describe('test', () => {
  it ('test1', () => {
    OAuth2Client.mockImplementation(() => {
      return {
        verifyIdToken: () => true
      }
    });
  });

  it('test2', () => {
    OAuth2Client.mockImplementation(() => {
      return {
        verifyIdToken: () => false
      }
    });
  });
});

This works correctly and the test passes, but I am seeing a Typescript error saying that mockImplementation does not exist on OAuth2Client and am wondering if this approach is the best way to achieve what I want or is there an alternative. I was reading around and saw that an option is to use jest.spyOn as well.


texts:
I have a piece of code that will have to fetch the token to call a different API. The token has an expiry of 10 hours; after 10 hours, it has to re-fetch the token.

I have created a singleton class to do it. Is there anything wrong with this code?

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class CredentialsHolder {

        private static CredentialsHolder instance = null;
        private String loginToken;
        private Date loginTokenExpiry;

        private static final String API_BASE_URL_V1 = "https://api.com/rest";
        private static final String API_LOGIN_TOKEN_PATH = "token";
        private static final String API_USER_NAME = "userName";
        private static final String API_PASSWORD = "password";

        private final Lock lock = new ReentrantLock();

        public static synchronized CredentialsHolder getInstance()  {
           if (instance == null)
               instance = new CredentialsHolder();
           return instance;
       }

        private CredentialsHolder()  {
            setAPICredentials();
        }

        private void refreshToken() {
            setAPICredentials();
        }

        private void setAPICredentials() {
            if (Calendar.getInstance().after(toCalendar(loginTokenExpiry))) {
                Map headers = new HashMap();
                headers.put("userName", API_USER_NAME);
                headers.put("password", API_PASSWORD);
                Map criteria = new HashMap();
                criteria.put("headers", headers);
                criteria.put("url", API_BASE_URL_V1 + API_LOGIN_TOKEN_PATH);
                Map response = new ExternalAPICaller().httpGet(criteria);
                Map responseHeaders = ((Map) response.get("headers"));
                System.out.println(responseHeaders);
                loginToken = (String) (responseHeaders.get("Token"));
                try {
                    loginTokenExpiry = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a").parse((String) (responseHeaders.get("TokenExpiry")));
                } catch (ParseException e) {
                    e.printStackTrace();
                    loginTokenExpiry = null;
                }
            }
        }

        public String getAccessToken() {
           if (Calendar.getInstance().after(toCalendar(loginTokenExpiry))) {
              if (lock.tryLock()) {
                 try {
                    refreshToken();
                 } finally {
                    lock.unlock();
                 }
              }
           }
          return loginToken;
        }

        public static Calendar toCalendar(Date date){
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.HOUR, -1);
            return cal;
        }
    }

I have used ReentrantLock to not allow the refresh happen simultaneously by multiple threads. So if a refresh is happening once, the other will continue. (I am trying to refresh the token 1 hour ahead before expiry).


texts: Finding all possible distinct palindromes of a string

texts:
There was some online test where I was asked about finding all possible distinct palindromes of a string.

Here I had to give the count of all possible distinct palindromes of a given string (continuous substring). Here, a single character word is considered a palindrome.

Below is what I did. Can you please tell me if it is good OR there is a scope of improvement?

public class Solution {
/*
* Complete the function below.
*/

static int palindrome(String str) {
    String[] strArray = str.split("");
    List<String> list = Arrays.asList(strArray);
    list = list.subList(1, list.size());
    //Set does'nt allow duplicates.
    //Sublist is required because split method gives an extra space.
    Set<String> palindromeSet = new HashSet<>(list);
    String palindromeStr = null;
    for(int i = 0;i<list.size();i++){
        palindromeStr = list.get(i);
        for(int j = i+1;j<list.size();j++){
            palindromeStr = palindromeStr+list.get(j);
            if(isPalindrome(palindromeStr)){
                palindromeSet.add(palindromeStr);
            }
        }
    }
    return palindromeSet.size();
}

static boolean isPalindrome(String str){
    char[] chars = str.toCharArray();
    for(int i =0;i<(chars.length/2);i++){
        if(chars[i] != chars[chars.length-1-i]){
            return false;
        }
    }
    return true;
}

public static void main(String[] args) throws IOException{
    System.out.println(palindrome("arewenotdrawnonwardtonewera"));
}
}


texts:
This code creates a singleton event dispatcher. It's called like this:

eventDispatcher = Event()
eventDispatcher.on("event", handler)
eventDispatcher.trigger("event", 5)

I'm wondering if this is "the python way," or if it could be improved? Especially the class, I'm not sure about creating a new object for every use of the dispatcher.

class Event():
    events = {}

    def on(self, event, func):
        if event not in self.events.keys():
            self.events[event] = []

        self.events[event].append(func)

    def trigger(self, event, *args, **namedArgs):
        if event in self.events.keys():
            for func in self.events[event]:
                func(*args, **namedArgs)


texts: Codility binary gap solution using regex

texts:
Below is the code I implemented to solve the binary gap problem:

  Find longest sequence of zeros, bounded by ones, in binary representation of an integer.

However, it seems to be different from the answers out there. Is it because this is a bad approach in terms of performance? I wanted to get some ideas.

function binaryGap(number) {
    let binary = (number >>> 0).toString(2), // convert to binary
        regex = /(?!1)(0+)(?=1)/g; // regex to match zeros between 1s

    let matches = binary.match(regex);

    return matches ? matches.reduce(function(carry, current){
        return carry.length > current.length ? carry : current;
    }).length : 0;
}


texts: Leftmost bisect search to find valid perfect square

texts:
I am working on Valid Perfect Square - LeetCode
and wrote a standard leftmost bisect search to solve the problem:

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        #base case 1
        if num == 1: return True
        lo = 1
        hi = num
        #recur case
        while lo < hi:
            mid = (lo + hi) // 2
            if num > mid ** 2:
                lo = mid + 1
            else:
                hi = mid
        return True if lo ** 2 == num else False

However, the score is annoying:

  Runtime: 48 ms, faster than 24.22% of Python3 online submissions for Valid Perfect Square.
  Memory Usage: 13.2 MB, less than 5.17% of Python3 online submissions for Valid Perfect Square.

I am not able to improve a standard template a little bit.

Could you please provide any advice?


texts: Recursively convert a list of lists into a dict of dicts

texts:
As a challenge to myself, I wrote a solution to this Stack Overflow question. For completeness, the bulk of the question is as follows:

Problem

Input:

[
  ['key1', 'value1'],
  ['key2',
     [
       ['key3', 'value3'],
       ['key4',
          [
            ...
          ]
       ],
       ['key5', 'value5']
     ]
  ],
  ['key6', 'value6'],
]

Ouput:

{
  "key1": "value1",
  "key2": {
     "key3": "value3",
     "key4": ...,
     "key5": "value5"
  },
  "key6": "value6"
}

Solution

Please note that this is my first attempt.

import pprint

def main():
    lt = [ \
            ['key1', 'value1'], \
            ['key2', \
                [ \
                    ['key3', 'value3'], \
                    ['key4',  \
                        ['key7','value7'] \
                    ], \
                    ['key5', 'value5'] \
                ] \
            ], \
            ['key6', 'value6'] \
        ]
    print('Input:')
    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(lt)
    dt = lists2dict(lt, pp)
    print('-' * 80)
    print('Output:')
    pp.pprint(dt)

def lists2dict(lt, pp):
    # form a dict from a list of lists,
    # if a key's value is a single-element list, just add the element
    dt = {l[0]: l[1:] if len(l[1:]) > 1 else l[1] for l in lt}
    # print('-' * 70)
    # pp.pprint(dt)
    for k,v in dt.items(): # step through the dict, looking for places to recurse
        # print('k=%r, v=%r' %(k,v))
        if isinstance(v, list): # a value which is a list needs to be converted to a dict
            if isinstance(v[1], list): # only recurse if a to-be-parsed value has a list
                dt[k] = lists2dict(v, pp)
            else: # just a single k/v pair to parse
                dt[k] = {v[0]: v[1]}
    return dt

if __name__ == '__main__':
    main()

If anyone has improvements, or a more efficient and/or Pythonic implementation, please share it.


texts: Project Euler problem #19: counting months that began on Sundays

texts:
You are given the following information, but you may prefer to do some
  research for yourself.

  1 Jan 1900 was a Monday.
  Thirty days has September,
  April, June and November.
  All the rest have thirty-one,
  Saving February alone,
  Which has twenty-eight, rain or shine.
  And on leap years, twenty-nine.
  A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

  How many Sundays fell on the first of the month during the twentieth
  century (1 Jan 1901 to 31 Dec 2000)?

public static void problem_19() {
        int day = 4; // Lets number the days of week from 1:7 && SaturDay is the first day;;; note : 1 jan 1901 was Tue day
        int sundays = 0;
        for(int year = 1901; year <= 2000; year++)
            for(int mon = 1; mon <= 12; mon++) {
                day += days(mon, year);
                if(day%7 == 1)
                    sundays++;
            }
        System.out.println(sundays);
    }
    public static int days(int num, int year) {
        int res = 0;
        int feb = 28;
        if(isLeapYear(year))
            feb = 29;
        switch(num) {
            case 1 : res = 31; break;
            case 2 : res = feb; break;
            case 3 : res = 31; break;
            case 4 : res = 30; break;
            case 5 : res = 31; break;
            case 6 : res = 30; break;
            case 7 : res = 31; break;
            case 8 : res = 31; break;
            case 9 : res = 30; break;
            case 10 : res = 31; break;
            case 11 : res = 30; break;
            case 12 : res = 31; break;
        }
        return res;
    }
    public static boolean isLeapYear(int year) {
        if(year%4 == 0)
            if(year%100 == 0) {
                if(year%400 == 0)
                    return true;
            } else
                return true;
        return false;
    }


texts:
The prompt is as follows: This script will use a text menu to give the
user options. The options will include the ability to add grades of different types as well
as an option to print the current grades and average. Types of grades are tests, quizzes,
and assignments. For the final average, the tests and assignments count 40% each and the
quizzes make up the remaining 20%. The lowest quiz grade should be dropped. The menu
will have numbers by each option and users enter a number to select that option.
Note: grades are the numbers obtained (i.e. 0 to 100)
I have written the following code:
 import io.StdIn._
  //global var for grades, implemented as Lists so that updating is easier and efficient
  var testList:      List[Int] = Nil
  var assignmentList:List[Int] = Nil
  var quizList:      List[Int] = Nil

  //boolean variable to run program in a loop
  var is_over: Boolean = false

  while (!is_over) {

    //display menu to let the user choose from the options
    println("Choose an option from below\n1. Add grades\n2. Get grades and average\n3. Exit program ")
    val chosenOption: Int = readInt()

    //match to call the functions according to user selection
    chosenOption match {
      case 1 => println("\nWhich type of grade do you want to enter?\n1. Test\n2. Quiz\n3. Assignment")
                returnGrades(readInt()) //pass the option for the type of grade to add
      case 2 => outputGrades()
      case 3 => is_over = true //option 3 will exit the program
      case _ => println("Invalid option")
    }
  }

  def returnGrades(option$:Int):Unit = {
    //tell the user that while building the list, they enter -1 to exit building the list
    println("\nEnter grades, \"-1\" to exit\n ")
    //match to add grades of a specific type
    option$ match {
      case 1 => testList       = buildList()
      case 2 => quizList       = buildList()
      case 3 => assignmentList = buildList()
      case _ => println("Error in value entered")
    }
    println("-"*40)
  }

  //recursive function to build a list
  def buildList():List[Int] = {
    val x: Int = readInt()
    if (x < -1 || x>100) {
      print("Invalid entry. Re-enter: ")
      buildList()
    } else if (x == -1) {
        Nil
    }
    else x::buildList()
  }

  def outputGrades():Unit= {
    //output current grades with .mkString
    println("Grades for tests are      : " + testList.mkString("\t"))
    println("Grades for quizzes are    : " + newQuizList().mkString("\t"))
    println("Grades for assignments are: " + assignmentList.mkString("\t"))

    val x:Double = 0.4 * calculateAverage(testList) + 0.4 * calculateAverage(assignmentList) +
      0.2 * calculateAverage(quizList)

    println("Average is: " + x )
    println("-"*40)
  }

  //function for quizList so that the program does not returns an error if you use .min method on an empty list.
  def newQuizList():List[Int] = {if (quizList.nonEmpty) quizList diff List(quizList.min) else Nil}

  def calculateAverage(lst:List[Int]):Double = {if (lst.isEmpty) 0 else lst.sum/lst.length}

Are there perhaps more efficient ways to achieve the same goal?


texts: Persisting objects in a ListBox ObjectCollection

texts:
I have a C# WinForms app containing a ListBox control, which I populate with objects of type BukkitServer.  When an object is added or removed from the list, I want to write them to an XML file.  I have a static method in a helper class that takes an ICollection argument and achieves this.

However, since the ListBox.ObjectCollection class is not serializable (fittingly, since it contains elements of type object), I wrote a helper method to convert it to a List<BukkitServer>.

It feels like a hack, though, and I feel (hope) there is a cleaner answer.

Any other comments and criticisms are welcome as well.

static class BukkitServerDataWriter {

    public static void SaveServers(ICollection objects) {

        using (XmlTextWriter writer = new XmlTextWriter("servers.xml", Encoding.UTF8)) {
            XmlSerializer xml = new XmlSerializer(
                typeof(List<BukkitServer>),
                new Type[] { typeof(BukkitServer) });

            List<BukkitServer> servers = MakeBukkitServerList(objects);
            xml.Serialize(writer, servers);
        }

    }

    private static List<BukkitServer> MakeBukkitServerList(ICollection collection) {

        List<BukkitServer> servers = new List<BukkitServer>();
        foreach (object obj in collection) {
            servers.Add((BukkitServer)obj);
        }

        return servers;
    }

}


texts: Reading a file representing word frequencies in Wikipedia, for clustering analysis

texts:
I am writing a system that will run Kmeans to determine the most used words in Wikipedia. I do this by building a core set with streaming data. Wikipedia is 50TB but after a year of processing I was given data of size 14 GB which I need to parse and I want it to run fast. From client I send server 10000 points which are processed.

CODE:

import gc
import time

class point:
    def __init__(self, x, y, w):
        self.x = x
        self.y = y
        self.w = w

def parse(pathToFile):
    myList = []
    with open(pathToFile) as f:
        for line in f:
            s = line.split()
            x, y, w = [int(v) for v in s]
            obj = point(x, y, w)
            gc.disable()
            myList.append(obj)
            gc.enable()
    return myList

if __name__ == "__main__":
    startTime = time.time()
    L = parse('C:/Users/user/workspace/finalSub/api/data100mb.txt')
    print("--- %s seconds ---" % (time.time() - startTime))

Parsing a 114MB file takes 130 seconds when I've been told it should take few seconds.

I tried splitting the data to multiple chunks and apply multiprocessing, but it ended up that reading from multiple files is bad and results in even longer time time to parse. Look here.

File Sample:

1 1 1
1 2 1
1 3 1
1 4 1
.
.
1 N 1
2 1 1
2 2 1
2 3 1
2 4 1
.
.
2 N 1

How should I parse the file correctly or access it in-order to make it faster?


texts: Splitting a string on delimiter outside of quotes while returning item-by-item

texts:
One of the more recent functions I've needed for personal and work purposes is to split a string on a delimiter, but while ignoring the delimiter when inside a quote. Just as well, if within a quote then two adjacent double-quotes ("") should be treated as a double-quote escape, and as such should be output directly into the resultant string.

  Input:

"\"Doe, \"\"John\"\" Johnathan\", \"Doe, James\"".QuotedSplit(",")

  Output:

"Doe, \"\"John\"\" Johnathan", "Doe, James"

This actually posed a larger challenge than I originally anticipated, but in the end it was resolved pretty swiftly.

Obviously I want comments on all facets, but especially the idea of the performance of the method, and anything related to the yield return nature of it. I want it to be as lazy as possible, after all that's what good framework developers do, but I also want it to be robust.

The code is actually surprisingly long, but I think that's my fault for not abstracting it to a class, and I really do not want to abstract this to a class.

The method is as follows:

public static IEnumerable<string> QuotedSplit(this string s, string delim)
{
    var esb = new ExtendedStringBuilder(s.Length);

    bool inQuote = false;
    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] == '\"')
        {
            if (i < s.Length - 1 && s[i + 1] == '\"')
            {
                esb += s[i++];
                esb += s[i];
            }
            else
            {
                inQuote = !inQuote;
                esb += s[i];
            }
        }
        else if (!inQuote)
        {
            if (s[i] == delim[0])
            {
                var split = true;
                for (int j = 0; j < delim.Length; j++)
                {
                    if (s.Length - 1 <= i + j)
                    {
                        split = false;
                        break;
                    }

                    if (s[i + j] != delim[j])
                    {
                        split = false;
                        break;
                    }
                }

                if (split)
                {
                    yield return esb;
                    esb.Length = 0;
                    i += delim.Length - 1;
                    split = true;
                    continue;
                }
            }

            esb += s[i];
        }
        else if (inQuote)
        {
            esb += s[i];
        }
    }

    if (esb.EndsWith(delim))
    {
        esb.Length -= delim.Length;
    }

    yield return esb;
}

The unique advantage of this method is that it can take a string as the delimiter, and will lazily evaluate it, without creating a weird method structure (like string.Split does).

I haven't noticed any bugs with it, though I guess it's possible that there are some. I've used it in the production environment it's part of for a while with no issues.


texts: Using nested if statements to select textfield for update of associated label

texts:
So I have written a very simple program using a cocoa pods library to calculate the distance between different cities. Here is what the UI looks like:

So I have a textfield on top for entry of starting location, and then four other textfields for destination city input.

I went with nested if statements which I am not fully happy with, but at least it does the job in terms of calculating distances for each. Is there a better way to do this than nesting if statements as I have done? There are only four cases for the four textfields but if there is a cleaner way to do it I would love to know about that.

Here is the code itself for the ViewController.m file:

#import "ViewController.h"
#import "DistanceGetter/DGDistanceRequest.h"

@interface ViewController ()

@property (nonatomic) DGDistanceRequest *req;

@property (weak, nonatomic) IBOutlet UITextField *startLocation;

@property (weak, nonatomic) IBOutlet UITextField *endLocationA;

@property (weak, nonatomic) IBOutlet UITextField *endLocationB;
@property (weak, nonatomic) IBOutlet UITextField *endLocationC;

@property (weak, nonatomic) IBOutlet UITextField *endLocationD;

@property (weak, nonatomic) IBOutlet UILabel *distanceA;
@property (weak, nonatomic) IBOutlet UILabel *distanceB;

@property (weak, nonatomic) IBOutlet UILabel *distanceC;
@property (weak, nonatomic) IBOutlet UILabel *distanceD;

@property (weak, nonatomic) IBOutlet UIButton *calculateButton;

@end

@implementation ViewController

- (IBAction)calculateButtonTapped:(id)sender {

    self.calculateButton.enabled = NO;

    self.req = [DGDistanceRequest alloc];
    NSString *start = self.startLocation.text;
    NSString *destA = self.endLocationA.text;
    NSString *destB = self.endLocationB.text;
    NSString *destC = self.endLocationC.text;
    NSString *destD = self.endLocationD.text;

    NSArray *dests = @[destA, destB, destC, destD];

    self.req = [self.req initWithLocationDescriptions:dests sourceDescription:start];
    __weak ViewController *weakSelf = self;

    self.req.callback = ^void(NSArray *responses){
        ViewController *strongSelf = weakSelf;
        if (!strongSelf) return;

        NSNull *badResult = [NSNull null];

          if (responses[0] != badResult) {

            double num = ([responses[0] floatValue] / 1000.0);
            NSString *ans1 = [NSString stringWithFormat:@"%.2f km", num];

            strongSelf.distanceA.text = ans1;

            if (responses[1] != badResult) {
                double num = ([responses[1] floatValue] / 1000.0);
                NSString *ans2 = [NSString stringWithFormat:@"%.2f km", num];

                strongSelf.distanceB.text = ans2;

                if (responses[2] != badResult) {
                    double num = ([responses[2] floatValue] / 1000.0);
                    NSString *ans3 = [NSString stringWithFormat:@"%.2f km", num];

                    strongSelf.distanceC.text = ans3;

                    if (responses[3] != badResult) {
                        double num = ([responses[3] floatValue] / 1000.0);
                        NSString *ans4 = [NSString stringWithFormat:@"%.2f km", num];

                        strongSelf.distanceD.text = ans4;

                    }

                }

            }

        }

        strongSelf.req = nil;
        strongSelf.calculateButton.enabled = YES;

    };

    [self.req start];

   }

@end

Please be patient with me as I am pretty much completely new to writing my own code from scratch.


texts: Insert into two tables during user registration using PHP

texts:
I'm working on creating a user registration script in PHP.  I have two tables that need to be inserted into.  One that stores some general user information, and another that stores their login credentials.  My issue is that my code to perform these insert is a mess of if/else blocks and I'm trying to figure out a good way to condense this down into a logical and clean code block.

Note that for now I have just placed some echo's that will later be replaced by a real error handling system once I truly know how many paths I'm going to need.

Can someone please review this script and let me know some improvements I can make to it?  I know it's quite ugly right now.

$mysqli = getMysqlConnection();
  if ($stmt = $mysqli->prepare("INSERT INTO users (username, email, regtime, emailverified, type) values (?,?,?,?,?);")) {
      date_default_timezone_set("America/New_York");
      $dateStr = date("m-d-Y h:i:s");
      $emailverified = 0;
      $type = 0;
      $rc = $stmt->bind_param('sssii', $username, $email, $dateStr, $emailverified, $type);
      if($rc === true){
        $rc = $stmt->execute();
        if($rc === true)
        {
          if ($stmt = $mysqli->prepare("INSERT INTO usercreds (username, hash) VALUES (?, ?);")) {
              $rc = $stmt->bind_param('ss', $username, $hash);
              if($rc === true){
                $rc = $stmt->execute();
                if($rc !== true)
                {
                  echo "so close...";
                }
              }
              else
              {
                echo "well, shit...";
              }
          }
          else {
            {
              echo "whoops...";
            }
          }
        }
        else {
          echo "noooooooooo!";
        }
      }
  }
  else {
    echo "uh oh";
  }

  echo "done";


texts: Read and display JSON results from Google Books API

texts:
I’m working with the Google Books API and I’m not so sure about the way I’m going to get the search data and return it to the user. I will describe the path here and I would like to know if you would do something different.
First, I receive a search request from the user via a form inside index.html:
<form action='/lookup' method="post">
  <input type="text" name="search" placeholder="Search by title, author, publisher, release, ISBN ...">
  <button type="submit">Buscar</button>
  {% block search %}{% endblock %}
</form>

So in an app.py I get this request like this:
@app.route("/lookup", methods=["GET", "POST"])
@login_required
def search():
    """Get book search."""
    if request.method == "POST":
        result_check = is_provided("search")
        if result_check is not None:
            return result_check
        search = request.form.get("search").upper()
        search = lookup(search)
        if search is None:
            return "Invalid Search"
        return render_template("search.html", search={
            'totalItems': search['totalItems'],
            'title': search['title'],
            'authors': search['authors']
        })
    else:
        return render_template("/")

Next, I access a lookup function in helpers.py:
def lookup(search):
    """Look up search for books."""
    # Contact API
    try:
        url = f'https://www.googleapis.com/books/v1/volumes?q={search}&key=MYAPIKEY'
        response = requests.get(url)
        response.raise_for_status()
    except requests.RequestException:
        return None

    # Parse response
    try:
        search = response.json()
        return {
            "totalItems": int(search["totalItems"]),
            "items": search["items"]
        }
    except (KeyError, TypeError, ValueError):
        return None

To return the results to the user I have a search.html that is still under construction:
{% extends "index.html" %}

{% block search %}

Total Items: {{search['totalItems']}}

Título: {{search['items'][0]['volumeInfo']['title']}}

Autor(a): {{search['items'][0]['volumeInfo']['authors']}}

Título: {{search['items'][2]['volumeInfo']['title']}}

Autor(a): {{search['items'][2]['volumeInfo']['authors']}}

{% endblock %}

Finally, my question: is this path I am following to access the API and return the data to the user the most recommended? Would you do anything other than that?


texts: Seeking a quick and dirty way to populate a list of entities for testing purposes

texts:
Here's what I have at the moment. Any ideas for improving on this?

public static Snapshot[] GetSnapshots()
{
    var arrayedSnapshot = new
    {
        Id = Enumerable.Range(1, 9),
        ScenarioTimeInSeconds = new[] { 0, 0, 0, 60, 60, 60, 120, 120, 120 },
        BearingInDegrees = new[] { 0, 120, 220, 0, 120, 220, 0, 120, 220},
        RangeInNauticalMiles = new[] { 0, 1, 1, 0, 1, 1, 0, 1, 1 },
        CourseInDegrees = new[] { 90, 90, 90, 90, 90, 180, 90, 90, 90 },
        SpeedInKnots = Enumerable.Repeat(7, 9),
        XCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
        YCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    };
    return arrayedSnapshot.Id
        .Select((td, index) =>
            new Snapshot
            {
                Id = arrayedSnapshot.Id ElementAt(index),
                ScenarioTimeInSeconds = arrayedSnapshot.ScenarioTimeInSeconds.ElementAt(index),
                BearingInDegrees = arrayedSnapshot.BearingInDegrees.ElementAt(index),
                RangeInNauticalMiles = arrayedSnapshot.RangeInNauticalMiles.ElementAt(index),
                CourseInDegrees = arrayedSnapshot.CourseInDegrees.ElementAt(index),
                SpeedInKnots = arrayedSnapshot.SpeedInKnots.ElementAt(index),
                XCoordinate = arrayedSnapshot.XCoordinate.ElementAt(index),
                YCoordinate = arrayedSnapshot.YCoordinate.ElementAt(index),
            })
        .ToArray();
}

Edit

Here is a new version based on Anton Golov's answer:

public static IEnumerable<Snapshot> GetSnapshots()
{
    for (var i = 0; i < 9; i++)
    {
        yield return new Snapshot
        {
            Id = i + 1,
            ScenarioTimeInSeconds = new[] { 0, 0, 0, 60, 60, 60, 120, 120, 120 }[i],
            BearingInDegrees = new[] { 0, 120, 220, 0, 120, 220, 0, 120, 220 }[i],
            RangeInNauticalMiles = new[] { 0, 1, 1, 0, 1, 1, 0, 1, 1 }[i],
            CourseInDegrees = new[] { 90, 90, 90, 90, 90, 180, 90, 90, 90 }[i],
            SpeedInKnots = new[] { 7, 7, 7, 7, 7, 7, 7, 7, 7 }[i],
            XCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }[i],
            YCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }[i]
        };
    }
}

This seems a lot more elegant than my original.


texts:
This is my old topic,it is about show table's records by JavaScript using a JsGrid file and can edit or delete by ajax.

This is my topic How can I load rows in JsGrid table that got from php file?,
The problem I am not sure the data is secure during inserting and loading or not?

Is it really secure?

The names of PHP files are: newsConf, controll and getnewscat

HTML file: basic.html

in controll.php:

public function newsConfig(){ $this->CONN = new Conn();//class from external page to connect DB try{
    $dfnet = $this->CONN->open_connect();
    $qnco = mysqli_query($dfnet,"select * from category");
    if(!$qnco) return "";
    else{
        while($qncoarray = mysqli_fetch_assoc($qnco)){
            //here I try copy rows into array
            $nnopCo[] = array(
                'ID' => $qncoarray['ID'],
                'Name' => $qncoarray['Name']
            );
        }
        return $nnopCo;
    }
    $this->CONN->close_connect($dfnet); } catch(Exception $er){ }

in getnewscat.php:

<?php require_once "../../bin/controll.php";
$db_controll = new Controll();
$cat_news = new ArrayObject($db_controll->newsConfig());

header('Content-type: application/json');
echo json_encode($cat_news->getArrayCopy());

?>

in basic.html: is the same file from jsgrid demo, but I change the code in JavaScript and canceled the db.js file

    <script>
            $(function() {
                {

                $("#jsGrid").jsGrid({
                    height: "70%",
                    width: "50%",//100%
                    selecting: false,
                    filtering: false,
                    editing: false,
                    sorting: false,
                    paging: true,
                    autoload: true,
                    pageSize: 15,
                    pageButtonCount: 5,
                    controller: {
                        loadData: function(filter) {
return $.ajax({url: "../bin/getnewscat.php",data:filter
                            });

                        }
    },
                    fields: [
                        { name: "ID", type: "number", width: 50 },
                        { name: "Name", type: "text", width: 50},
                        { type: "control", modeSwitchButton: false, deleteButton: false }
                    ]
               });
    $(".config-panel input[type=checkbox]").on("click", function() {
                    var $cb = $(this);
                    $("#jsGrid").jsGrid("option", $cb.attr("id"), $cb.is(":checked"));
                });

            });
        </script>

In newsConf.php: that file should call basic.html and give the result by using an iframe:

<iframe name="demo" src="jsgrid-1.2.0/demos/basic.html"></iframe>


texts: Simple ES6 Truncate method for character, word, and sentence limits

texts:
Simple truncating method for characters, words, and sentences for a personal utility library I've been working on.

Improvements & criticism welcomed! Especially around default param usage, as I've not utilized it much to date.

const truncate = ((
  value = '',
  int = 0,
  elipsis = '\u2026', /* ... */
  prune = (val, num, at) => val.split(at).splice(0, num).join(at)
) => {
  const sentences = (val = value, num = int, end = elipsis) => prune(val, '.', num) + end;
  const words = (val = value, num = int, end = elipsis) => prune(val, ' ', num) + end;
  const characters = (val = value, num = int, end = elipsis) => val.substring(0, num) + end;
  return {sentences, words, characters};
})();

console.clear();
console.log([
  truncate.sentences("This is a sentence. There are many like it but you won't see the 2nd one", 1, '.'),
  truncate.words("These are words but you won't see what's after this because it'll be hidden", 10),
  truncate.characters("This won't exceed 31 characters so we cutting off the ending", 31, '!')
]);


texts: Basic myVector class raw vs smart pointer

texts:
I'm writing a myVector class for a class I'm taking.  I don't believe I'm "strong" with smart pointers right now, so that's my question.  This is just an excerpt from a much larger class that I've completed.

Is there a way to use the shared pointer and dynamically allocate the size, so that I can use the [] notation with that pointer?  I've been looking on Stack Overflow and don't see anything referencing this particular usage.  My next question/conclusion would then be that it's best to stick with raw pointers in the case where I want to use array notation.

#include <iostream>
//#include <memory>

class myVector
{
private:
    int sz;
    int * array;

public:
    myVector(int a, int b)
    {
        sz = a;
        array = new int[sz];
        for(int i(0); i < sz; ++i)
            array[i] = b;
    }
    ~myVector(){ delete [] array; };
    int size() const
    {
        return sz;
    }
    int &operator[](const int num)
    {
        return array[num];
    }
};

int main()
{
    myVector testing(10, 6);
    for(int i(0); i < testing.size(); ++i)
    {
        testing[i] = testing[i] * i;
        std::cout << testing[i] << std::endl;
    }
    return 0;
}


texts:
We have to print the last word of the given string. How to improve and optimise this code?

#include <iostream>

std::string get_last_word(const std::string& str)
{
    if (str.length() == 0)
    {
        std::cerr << "No string\n";
        return 0;
    }

    int len = str.length();
    int i = len - 1;
    while (i >= 0 && str[i] != ' ')
    {
        i--;
    }
    std::string last_word;
    for (int j = i + 1; j < len; j++)
    {
        last_word += str[j];
    }
    return last_word;
}

int main()
{
    std::string str;
    std::cout << "Enter string :\n";
    std::getline(std::cin, str);
    std::cout << "Last word :\n";
    std::cout << get_last_word(str);
    std::cout << std::endl;
}


texts: Calculating the seconds between 2 numbers in a specific place in a string

texts:
We have a

string text =
"SOME OTHER TEXT
WHITE SPACES AND NEW LINES

[HitObjects]
109,192,7241,1,0,0:0:0:0:
256,192,7413,1,0,0:0:0:0:
475,192,75865,1,0,0:0:0:0:
329,192,86524,1,0,0:0:0:0:
182,192,256242,1,0,0:0:0:0:
256,192,306521,1,2,0:0:0:0:

WHITE SPACES AND NEW LINES
"

The third number of every row is the milliseconds.
I need to know the seconds between the first time and last time.
Right now I'm doing it like this:

text = text.Substring(text.IndexOf("Objects]") + 8).Trim();
string[] lines = text.Split('\n');
string[] firstLine = lines[0].Split(',');
string[] lastLine = lines[lines.Length - 1].Split(',');
int length = Convert.ToInt32(lastLine[2]) - Convert.ToInt32(firstLine[2]);
length = length / 1000;

I need to do this with thousands of 'text's though. Any optimalization or other methodes possible?

more information on the request of @Slothario:

the string text is the full text of 1 file
file type: .osu
average file size: 25KB
average characters: 30000
SOME OTHER TEXT - HitObjects ratio: 1 - 100
average amount of files to check: 500


texts: Searching for a value from one CSV file in another CSV file

texts:
I am writing a script that takes one CSV file searches for a value in another CSV file then writes an output depending on the result it finds.

I have been using Python's CSV Distreader and writer.  I have it working, but it is very inefficient because it is looping through the 2 sets of data until it finds a result.

There are a few bits in the code which are specific to my setup (file locations etc), but I'm sure people can see around this.

# Set all csv attributes

cache = {}
in_file = open(sript_path + '/cp_updates/' + update_file, 'r')
reader = csv.DictReader(in_file, delimiter= ',')
out_file = open(sript_path + '/cp_updates/' + update_file + '.new', 'w')
out_file.write("StockNumber,SKU,ChannelProfileID\n")
writer = csv.DictWriter(out_file, fieldnames=('StockNumber', 'SKU', 'ChannelProfileID'), delimiter=',')
check_file = open(sript_path + '/feeds/' + feed_file, 'r')
ch_file_reader = csv.DictReader(check_file, delimiter=',')

#loop through the csv's, find stock levels and update file

for row in reader:
    #print row
    check_file.seek(0)
    found = False
    for ch_row in ch_file_reader:
        #if row['SKU'] not in cache:
        if ch_row['ProductCode'] == row[' Stock']:
            Stk_Lvl = int(ch_row[stk_lvl_header])
            if Stk_Lvl > 0:
                res = 3746
            elif Stk_Lvl == 0:
                res = 3745
            else:
                res = " "
            found = True
            print ch_row
            print res

            cache[row['SKU']] = res
    if not found:
        res = " "
        #print ch_row
        #print res
        cache[row['SKU']] = res
    row['ChannelProfileID'] = cache[row['SKU']]
    writer.writerow(row)

This is a few lines from my in_file and also the outfile is the same structure.  It just updates the ChannelProfileID depending on the results found.

"StockNumber","SKU","ChannelProfileID"
"10m_s-vid#APTIIAMZ","2VV-10",3746
"10m_s-vid#CSE","2VV-10",3746
"1RR-01#CSE","1RR-01",3746
"1RR-01#PCAWS","1RR-01",3746
"1m_s-vid_ext#APTIIAMZ","2VV-101",3746

This is a few line from the check_file:

ProductCode, Description, Supplier, CostPrice, RRPPrice, Stock, Manufacturer, SupplierProductCode, ManuCode, LeadTime
2VV-03,3MTR BLACK SVHS M - M GOLD CABLE - B/Q 100,Cables Direct Ltd,0.43,,930,CDL,2VV-03,2VV-03,1
2VV-05,5MTR BLACK SVHS M - M GOLD CABLE - B/Q 100,Cables Direct Ltd,0.54,,1935,CDL,2VV-05,2VV-05,1
2VV-10,10MTR BLACK SVHS M - M GOLD CABLE - B/Q 50,Cables Direct Ltd,0.86,,1991,CDL,2VV-10,2VV-10,1

You can see it selects the first line from the in_file, looks up the SKU in the check_file then writes the out_file in the same format as the in_file changing the ChannelProfileID depending what it finds in the Stock field of the check_file, it then goes back to the first line in the check_file and performs the same on the next line on the in_file.

As I say this script is working and outputs exactly what I want, but I believe it is slow and inefficient due to having to keep loop through the check_file until it finds a result.

What I'm after is suggestions on how to improve the efficiency.  I'm guessing there's a better way to find the data than to keep looping through the check_file.


texts: Reformatting a date from YYYY-MM-DD to MM/DD/YYYY

texts:
In this small bit of JavaScript, a date is passed in as YYYY-MM-DD. It's formatted like this to be passed to the backend system. On the front end, we need to display it as MM/DD/YYYY.

I split the string, and put the each array index in the correct position. However, I feel like there could be a a better way to do this.

This is the code I have at the moment.

static formatCourseDate(date: string): string {
    const _date = date.split('-');
    const dateObj = {month: _date[1], day: _date[2], year: _date[0]};

    return dateObj.month + '/' + dateObj.day + '/' + dateObj.year;
}


texts:
I am trying to convert "Random = 1" into dictionary {"Random":1}
I tried

Key = (line.split('=')[0]).split()[0] #to get key and remove spaces
value = (line.split('=')[1]).split()[0]
CQ_Options[Key] = value

How could I do it in more mature way?


texts: C - A function that calculates the integral of a polynomial

texts:
I have written a simple function which takes an array of coefficients of a polynomial and then integrates it. My polynomial is represented like this:
$$polynomial[0] + polynomial[1]x + polynomial[2]x^2 + \dots + polynomial[n]x^n$$
And its integral will become:
$$polynomial[0]x + \frac 1 2 polynomial[1]x^2 + \frac 1 3 polynomial[2] x^3 + \dots + \frac{1}{n+1}x^{n+1}$$

#include <stdio.h>

void integrate(double *polynomial, double *buff, int number_of_terms) {
    for(int i = 0; i < number_of_terms; i++) {
        buff[i+1] = polynomial[i] / (i+1);
    }
    buff[0] = 0;
}

int main(void) {
    double polynomial[4] = {1, 2, 3, 4}; // 1 + 2x + 3x^2 + 4x^3
    double buff[5];
    integrate(polynomial, buff, 4);
    for(int i = 0; i < 5; i++) {
        printf("%f, ",  buff[i]);
    }
    //Output: 0.000000, 1.000000, 1.000000, 1.000000, 1.000000
    //0 + x + x^2 + x^3 + x^4
}

The problem with my solution is that I need  to set the value at index zero manually - I don't think this is a good practice and therefore would like to somehow wrap the 0th index into the formula in the loop. Is there an easy way to do this?


texts: How to reduce load when fading in multiple elements in jQuery

texts:
I have a dynamic order page which has to update multiple elements when a value is changed.

Here is the main function that does that. Note it only updates the values if they are different from what is already there. So for example it doesn't update with a checkmark, if there already is a check mark there.

  function reput(element, content, animate) {
        target = $(element);
        target_check = target.html().indexOf("check_mark");
         //checks if target already has a check mark
        content_check = content.indexOf("check_mark");
         //checks if new value has check mark
        th = target.html();
        if(th == content || (target_check == content_check && target_check != -1)) {
            return true;
            //if any of the values match, then don't do anything
        }
        else {
            //values didn't match so update the element
            if (animate || animate == undefined)
                target.fadeOut(100).empty().fadeIn(200).append(content);
            else
                target.empty().append(content);
        }
    }

This function is called multiple times in several places like so:

reput(("#email"),   (cp.email));
reput(("#chat"),    (cp.chat));
reput(("#voice"),   (cp.voice));
reput(("#member"),  (cp.member));
reput(("#price"),   ('$' + cp.price), false);

What would be the best way to improve the load time of this function? Having it accept an array, iterating through it and appending the values one by one? Would it save resources to just use fadeIn instead of fadeOut/fadeIn?

Bonus question: What are some ways to test how much processing power your script/function is using up?


texts: Should I include a view for each message?

texts:
For now, I have two views using Twig:

messages.html.twig
item.html.twig

The first one is the view which displays all of the users' posts in my forum. When a user post a new message, it's done via Ajax so the server returns a view with the posts information. That view is item.html.twig

So I have something like:

messages.html.twig

{% for item in posts %}

         Posted by {{ item.author }}

         {{ item.body }}

{% endfor %}

(well much more information in each posts of course)

item.html.twig

         Posted by {{ item.author }}

         {{ item.body }}

But the code is now duplicated and if I have to add a functionality or if I change my class names, I'll have to edit both of the views.

Would it be okay, in terms of performances, if I just included the item.html.twig in messages.html.twig like:

{% for item in posts %}
    {% include 'item.html.twig' with {item: item} %}
{% endfor %}

I don't know if there's a better solution so I would like to hear about ideas to improve my code.


texts:
So, here is a Hackerearth question, regarding (more or less) counting the number of primes between a given pair of numbers (up to 106).

Then there were 3 major options available to  me:

Trial division method, and its variants.
Sieve of Eratosthenes
Segmented sieve of Eratosthenes.

As learned from this answer.

The naive method  trial division, and its variants gave "Time Limit Exceeded" errors for about 70 % test cases.

Both the Sieve of Eratosthenes and its segmented version gave "Time Limit Exceeded" error for 60 % of the test cases.

Here is my code :

import java.util.* ;
import java.io.BufferedReader ;
import java.io.InputStreamReader ;
/*
Trial division : failed. 6 points
Sieve of Eratosthenes : failed 8 points.
Segmented sieve of Eratosthenes : failed.  8 points.
*/
public class MoguLovesNumbers
{
    public static void main(String args[]) throws Exception
    {
        BufferedReader bro = new BufferedReader(new InputStreamReader(System.in)) ;
        int T = Integer.parseInt(bro.readLine()) ;
        for(int t=0;t<T;t++)
        {
            String[] S = bro.readLine().split(" ") ;
            int l = Integer.parseInt(S[0]) ;
            int r = Integer.parseInt(S[1]) ;
            int temp = l<r?l:r ;
            r = l<r?r:l ;
            l = temp ;

            System.out.println(segmentedSieve(l,r)) ;
        }

    }
    static void sieveOfEratosthenes(int l,int r,List<Integer> prime)
    {
        boolean[] mark = new boolean[r+1] ;
        int counter = 0 ;
        Arrays.fill(mark,true ) ;

        for(int i=2;i<r+1;i++)
        {
            if(mark[i])
            {
                if(i>=l)
                {
                    prime.add(i) ;
                    counter++ ;
                }
                for(int j=i*2;i*i<=r && j<r+1;j+=i)
                    mark[j] = false ;
            }
        }
        // return counter ;
    }
    static int segmentedSieve(int l,int n)
    {
        int limit = (int)Math.sqrt(n)+1 ;
        List<Integer> prime = new ArrayList<Integer>() ;
        sieveOfEratosthenes(0,limit,prime) ;
        int low = limit ;
        int high = limit*2 ;
        int count = 0 ;
        while(low<n)
        {
            if(high>n)
                high = n ;
            boolean mark[] = new boolean[limit+1] ;
            Arrays.fill(mark,true ) ;
            for(int i=0;i<prime.size();i++)
            {
                int loLim = (int)(Math.ceil((float)low/prime.get(i)))*prime.get(i) ;
                for(int j=loLim;j<=high;j+=prime.get(i))
                {
                    mark[j-low] = false ;
                }
            }
            for(int i = 0;i<mark.length;i++)
                if(mark[i] && (i+low>=l)&& (i+low<=high))
                {
                    count++ ;
                }
            low+=limit ;
            high+=limit ;
        }
        if(l<=Math.sqrt(n)+1)
        {
            for(int i=0;i<prime.size();i++)
                if(prime.get(i)>=l)
                    count++ ;
        }
        return count ;

    }
}

SUBMISSIONS:

Segmented Sieve
Simple Sieve
Naive trial division

Question:

How can this code be made more efficient? The Segmented Sieve and Simple Sieve both run in O(N log(log(N))) time.


texts:
I have been learning C++ for the past few weeks, and I made my first try with policy classes. Ultimately my goal is to use policy classes to manufacture wrapper classes on an std::vector. Part of what the wrapper class does is generate a custom allocator class that depends on the policy classes.

That's the inspiration for what I have below, which is a widget maker that makes widgets with a printing function that depends on the templated inputs.

Printing policy classes:

template <class T>
struct Chatty
{
  static void logVal(T val){
    std::cout << val << std::endl;
  }
  static void logS(std::string s){
    std::cout << s << std::endl;
  }
};

template <class T>
struct Silent
{
  static void logVal(T val){}
  static void logS(std::string s){}
};

Widget:

class Widget {
public:
  int x;
  int y;
  std::function<void(std::string)> print;
  Widget()
    :x(0), y(0), print([](std::string){})
  {};
};

WidgetManager:

template < template <class Created> class CreationPolicy, template <class Created> class LoggingPolicy>
class WidgetManager : public CreationPolicy<Widget>, public LoggingPolicy<Widget>
{
public:
  WidgetManager() {};
  static Widget* doAll(){
    Widget* w = WidgetManager::Create();
    std::function<void(std::string)> f1 = WidgetManager::logS;
    w->print = WidgetManager::logS;
    return w;
  }
};

I would appreciate feedback on all aspects of the code, but I also have two specific questions:

My biggest concern: is there a better way to assign functions to the Widgets I am making? For example, perhaps I could directly assign member functions of Widgets from my WidgetManager, but then I'd have to bind the WidgetMaker's static functions to individual instances of Widgets, which seems like more overhead. What's best performance-wise?
I am sure WidgetManager::doAll() is not the way to go, but I am struggling to find another way to call functions from various policies all together. What's a better way to do this?


texts: Converting Array of `UINT8` (`unsigned char`) to Array of `Float32` (`float`) Using AVX2

texts:
Given input array of UINT8 (unsigned char) with numElements how could one efficiently convert it into array of Float32 (float)?

For instance, here is a vanilla code for it (Pay attention there is a scaling operation):

void ConvertFromUint8(float* mO, unsigned char* mI, int numElements, float scalingFctr)
{
    int ii;
    for (ii = 0; ii < numElements; ii++) {
        mO[ii] = (float)(mI[ii]) * scalingFctr;
    }
}

Where mO is the output array.

I need a code which utilizes up to AVX2 intrinsics.
The objective is to yield faster code than the vanilla example as in Compiler Explorer - ConvertFromUint8.


texts:
I implemented the Vigenere cipher in haskell as a part of exercises for  Haskell programming from first principles.

Though the code isn't all that long, I feel it could use some refactoring to simplify things (I feel the code I wrote is ugly). One caveat: string inputs should all be in uppercase.

The vigenere function should be applied like so:

vignere "ALLY" "MEET AT DAWN"

which will create the output:

"MPPRAEOYWY"

As it stands, here's the code I implemented:

import Data.Char

-- exercise chapter 11
encode :: Char -> Int
encode x = ord x - ord 'A'

decode :: Int -> Char
decode x = chr (x + ord 'A')

shift :: (Int -> Int -> Int) -> Int -> Char -> Char
shift f x ch =  decode $ f (encode ch) x `mod` 26

rightShift :: Int -> Char -> Char
rightShift = shift (+)

leftShift :: Int -> Char -> Char
leftShift = shift (-)

encodeString :: String -> [Int]
encodeString str = map encode str

type Secret = String
type PlainText = String
type CipherText = String

vignereString :: Secret -> PlainText -> String
vignereString secret plain = take len $ cycle secret
                          where len = length $ concat $ words plain

vignereCode :: Secret -> PlainText -> [Int]
vignereCode secret plain = encodeString $ vignereString secret plain

vignere :: Secret -> PlainText -> CipherText
vignere secret plain =
  zipWith rightShift code plainNoSpace
  where code = vignereCode secret plain
        plainNoSpace = concat $ words plain

unvignere :: Secret -> CipherText -> PlainText
unvignere secret cipher =
  zipWith leftShift code cipherNoSpace
  where code = vignereCode secret cipher
        cipherNoSpace = concat $ words cipher


texts: Inversion of an array that contains indices

texts:
I have an array of length n that contains numbers from 0 to n-1 in random order.
I now want to "inverse" this array to one that where index i corresponds to the location of i in the source array.

Example

Source_Array = {2,0,1}

Transform to:

Result_Array = {1,2,0}

This means I find the index 0 at position 1 in my source, 1 is at location 2 and so on.

I did this with the following function:

Dim Sourcelist As List(Of Integer) = Source.ToList
Dim Result(Source.Count - 1) As Integer
For i = 0 To Source.Count - 1
   Result(i) = Sourcelist.IndexOf(i)
Next

Casting the array to List and then slowly using IndexOf to select the indices is not really great. Is there a better method maybe using LINQ?

Both VB.NET and C# answers are very much appreciated.


texts:
I am using jQuery to implement a basic quiz functionality. How can I improve this code snippet even more? Is there any better way of doing it?

I am using jQuery 1.6.4.

/*jshint -W065 */
$(function () {
    var jQuiz = {
        answers: {
            q1: 'd',
            q2: 'd',
            q3: 'a',
            q4: 'c',
            q5: 'a'
        },
        questionLenght: 5,
        checkAnswers: function () {
            var arr = this.answers;
            var ans = this.userAnswers;
            var resultArr = [];
            for (var p in ans) {
                var x = parseInt(p) + 1;
                var key = 'q' + x;
                var flag = false;
                if (ans[p] == 'q' + x + '-' + arr[key]) {
                    flag = true;
                } else {
                    flag = false;
                }
                resultArr.push(flag);
            }
            return resultArr;
        },
        init: function () {
            $('.btnNext').click(function () {
                if ($('input[type=radio]:checked:visible').length === 0) {

                    return false;
                }
                $(this).parents('.questionContainer').fadeOut(500, function () {
                    $(this).next().fadeIn(500);
                });
                var el = $('#progress');
                el.width(el.width() + 120 + 'px');
            });
            $('.btnPrev').click(function () {
                $(this).parents('.questionContainer').fadeOut(500, function () {
                    $(this).prev().fadeIn(500);
                });
                var el = $('#progress');
                el.width(el.width() - 120 + 'px');
            });
            $('.btnShowResult').click(function () {
                var arr = $('input[type=radio]:checked');
                var ans = jQuiz.userAnswers = [];
                for (var i = 0, ii = arr.length; i < ii; i++) {
                    ans.push(arr[i].getAttribute('id'));
                }
                $('#progress').width(300);
                $('#progressKeeper').hide();
                var results = jQuiz.checkAnswers();
                var resultSet = '';
                var trueCount = 0;
                for (var i = 0, ii = results.length; i < ii; i++) {
                    if (results[i] === true) trueCount++;
                    resultSet += '
 Question ' + (i + 1) + ' is ' + results[i] + '
';
                }
                resultSet += '
Your total score is ' + trueCount * 20 + ' / 100
';
                $('#resultKeeper').html(resultSet).show();
            });

        }
    };
    jQuiz.init();
});


texts: Improving the time complexity of my back pack algorithm

texts:
Is there anyone who can help me improve the time complexity of this backpack algorithm, for which I already use sliding array to improve the space complexity.

The problem is as follows:

  Given n items with size A[i], an integer m denotes the size of a backpack. How full you can fill this backpack?

Example:
If we have 4 items with size [2, 3, 5, 7], and the backpack size is 11, we can select [2, 3, 5], so that the max size for this backpack is 10. If the backpack size is 12, we can select [2, 3, 7] and fill it completely.

The function should return the max size we can fill in the given backpack.

class Solution:
# @param m: An integer m denotes the size of a backpack
# @param A: Given n items with size A[i]
# @return: The maximum size
def backPack(self, m, A):
    # write your code here
    n = len(A)
    f = [[False for x in range(m+1)] for y in range(2)]
    for i in range(n+1):
        f[i%2][0] = True

    for i in range(1, n+1):
        for j in range(1, m+1):
            f[i%2][j] = f[(i-1)%2][j]
            if j >= A[i-1] and f[(i-1)%2][j-A[i-1]]:
                f[i%2][j] = True

    max = 0
    for i in range(m+1):
        if f[n%2][i]:
            max = i

    return max


texts: Handling response from another microservice

texts:
I have this piece of code placed in ESI class. There is switch statement nested in a try-catch block and it feels simply wrong for me (I have a suspicion that I'm close to exception driven development). I'm looking forward to read your suggestions on how could I potentially improve this code.

@PostConstruct
public void initialize() {
    this.webTarget = this.client.target("http://demo1173642.mockable.io/");
}

public Message getMockMessage() {
    Response response = null;

    try {
        response = this.webTarget.request().get();

        switch (response.getStatusInfo().getFamily()) {
            case SUCCESSFUL:
                return response.readEntity(Message.class);

            case SERVER_ERROR:
                throw new WebApplicationException(ErrorCode.EXTERNAL_SERVICE_BAD_GATEWAY.getMessage(),
                        Response.Status.BAD_GATEWAY);

            default:
                throw new InternalServerErrorException(ErrorCode.EXTERNAL_SERVICE_EXCEPTION.getMessage());
        }

    } catch (Exception ex) {
        logger.log(Level.WARNING, ErrorCode.UNEXPECTED_EXECPTION.getMessage(), ex);
        if (response != null) {
            response.close();
        }
        throw new InternalServerErrorException();
    }
}


texts:
I've been trying to implement the basic search algorithms: Sequential search for ordered and unordered arrays and the binary search algorithms, as part of a package.

So, this is the implementation:

"""
`seqsearch{T}(x::AbstractArray{T}, item::T)` ↦ found::Bool
Searches for an item using the **Sequential Search** approach.
"""
function seqsearch{T}(x::AbstractArray{T}, item::T)
  index = 1
  found = false

  while index <= length(x) && !found
    x[index] == item ? found = true : index += 1
  end

  return found
end

"""
`ordseqsearch{T}::(x::AbstractArray{T}, item::T) ↦ found::Bool`
Searches for an item in a sorted array using the **Sequential Search** approach.
"""
function ordseqsearch{T}(x::AbstractArray{T}, item::T)
  index = 1
  found = false
  stop  = false

  while index <= length(x) && !found && !stop
    x[index] == item ? found = true : x[index] > item ? stop = true : index += 1
  end

  return found
end

"""
`binarysearch{T}::(x::AbstractArray(T), item::T) ↦ found::Bool`
Searches for an item in a sorted array using the **Binary Search** algorithm
"""
function binarysearch{T}(x::AbstractArray{T}, item::T)
  first = 1
  last = length(x)
  found = false

  while first <= last && !found
    middle = fld(first+last, 2)

    if x[middle] == item
      found = true
    else
      if item > middle
        first = middle + 1
      else
        last = middle - 1
      end
    end

  end

  return found
end

I want to make the implementations as fast as possible, with as less dependencies as possible.

So, are there any ways to make it cleaner (and/or) faster?


texts: A "todo" app built to practice Object Oriented JavaScript

texts:
I built a small "todo" app with an object oriented JavaScript approach.

I have spent this morning reading on a few ways to approach this, and I've come up with the following:

document.addEventListener("DOMContentLoaded", function () {
 var todo = Object.create(null);

 todo.newTodo = function (evt) {
  evt.preventDefault();
  var newTodo = document.getElementById("todo-item").value;
  var ul = document.getElementById("todo-view");
  var li = document.createElement("li");
  li.innerHTML = newTodo + 'x';

  //using tertnary operator to add items to top of list if other items already exist
  (ul.childElementCount == 0) ? ul.appendChild(li) : ul.insertBefore(li, ul.firstChild);

  document.getElementById('todo-item'). value = "";

  var span = li.getElementsByTagName("span");

  span[0].addEventListener("click", todo.deleteTodo, false);
 }

 var todoCache = [];

 todo.deleteTodo = function () {
  todoCache.push(this.parentNode);

  this.parentNode.parentNode.removeChild(this.parentNode);

  return todoCache;
 }

 todo.undoDelete = function () {
  var ul = document.getElementById("todo-view");

  if (todoCache.length > 0 ) {
   var lastTodo = todoCache.length - 1;

   ul.appendChild(todoCache[lastTodo]);

   todoCache.pop();
  }
 }

 var todoSub = document.getElementById("submit-item");

 todoSub.addEventListener("click", todo.newTodo, false);

 var undo = document.getElementById('undo');

 undo.addEventListener("click", todo.undoDelete, false);
});
 body, html {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
 }

 body {
  background: #ccc;
  font-family: 'Open Sans Condensed', sans-serif;
  font-weight: 100;
 }

 .list-container {
  padding: 15px 10px;
  margin: 0 auto;
  max-width: 30em;
  text-align: center;
 }

 .input {
  width: 100%;
 }

 .input input {
  height: 50px;
  display: block;
  width: 100%;
  margin: 0 auto;
  box-sizing: border-box;
  transition: linear .2s;
 }

 input[type="text"] {
  padding: 10px 20px;
  margin: 10px auto;
  border: none;

 }

 input[type="submit"] {
  background: #7FFFD4;
  border: none;
  color: white;
  padding: 0;
  display: block;
  cursor: pointer;
  font-size: 15px;
  text-transform: uppercase;
 }

 input[type="submit"]:hover {
  background-color: #66ccaa;
 }

 h1 {
  text-transform: uppercase;
  font-size: 40px;
  color: #fff;
 }

 ul {
  margin: 0;
  padding: 0;
 }

 li {
  list-style-type: none;
  padding: 7px 0;
  width: 100%;
  transition: .2s linear;
  position: relative;
 }

 li:hover span {
  display: inline-block;
 }

 li span {
  position: absolute;
  right: 10px;
  color: red;
  margin-right: 5px;
  display: none;
  cursor: pointer;
  font-size: 20px;
 }

 a {
  color: white;
 }

 <meta charset="UTF-8">

<link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>

TODO List

 UNDO

  <form>
   <input id="todo-item" type="text" placeholder="Enter your tasks here...">
   <input id="submit-item" type="submit" value="add">
  </form>

What do you suggest i do to improve this? Is there anything else you recommend to help further my learning efforts?


texts:
I have declared a react hook which will contain an array of object as follows:
const [rowDataTracker, setRowDataTracker] = useState([]);

Now I need to update the hook to basically create a payload as the following:
[
  {id: 100, payload: {field1: "value", field2: "value"}},
  {id: 105, payload: {field1: "value", field3: "value"}},
  {id: 109, payload: {field4: "value"}}
]

I need to check the following condition Before updating the hook:

Need to first check if the id exists in the array or not
if the id exists, then need to update/add the filed to the payload object
if the id does not exist, add a new object to the array with id and the field

const ifItemExist = (arr, item) => {
  return arr.findIndex((e) => e.id === item);
};
function storeEdit(rowId, field, newValue) {
  let itemIndex = ifItemExist(rowDataTracker, rowId);
  let newArr = [...rowDataTracker];
  if (itemIndex > -1) {
    newArr[itemIndex]["payload"][columnId] = newValue;
  } else {
    const obj = {
      itemNbr: rowId,
      payload: {
        [field]: newValue
      }
    };
    newArr.push(obj);
  }
  setRowDataTracker(newArr);
}

I am not sure if this is the correct way to update a hook.
Any review and suggestion will be appreciated.


texts: Create a collection of functions tupled with a collection of parameters, and execute the collection in order in Scala

texts:
I am trying to create a collection of Unit functions that have any arity and type, and will execute them in order.

This is the working implementation that I have:

/** A Subroutine simply represents a unit function that takes any number of parameters. */
type Subroutine = (Any) => Unit

/** A Routine represents a collection of functions which may consume a collection of parameters and will always
  * complete an action.
  */
type Routine = List[(Subroutine, Seq[_])]

/** This function will consume a list of functions executing them in order.
  *
  * @param routine is the list of functions and their parameters to be consumed.
  */
def executeRoutine(routine: Routine): Unit = {
  routine.headOption match {
    case Some((f, x)) =>
      f(x)
      executeRoutine(routine.tail)
    case None => ()
  }
}

and when I declare a function or "subroutine", I have to declare it like this in order to extract the parameters:

def myFunction: Subroutine = {
  case (firstParam: Int) :: (secondParam: String) :: _ => ...
  case _ => throw new InvalidParameterException()
}

def myFunction2: Subroutine = {
  case (firstParam: Int) :: _ => ...
  case _ => throw new InvalidParameterException()
}

val routine: Routine = List(
  (myFunction, Seq(firstParam, secondParam)),
  (myFunction2, Seq(firstParam))
)

I realize that this is not close to idiomatic Scala code, and I've been working on implementing a different approach which will partially apply functions one parameter at a time, and then execute the function after the parameters are fully applied. I do not yet have a working version of this approach, but this is as far as I have gotten:

/** A Subroutine simply represents a unit function that takes any number of parameters. */
sealed abstract class Subroutine extends (Any => Unit)

case class Curried(partiallyApplied: Function[_, Function[_, _]], unapplied: Function[_, _]) extends Subroutine

case class Uncurried(function: Function[_, Unit]) extends Subroutine

/** A Routine represents a collection of functions which may consume a collection of parameters and will always
  * complete an action.
  * Using HList for the parameters, from Shapeless
  */
type Routine = List[(Subroutine, HList)]

/** This function will consume a list of functions executing them in order.
  *
  * @param routine is the list of functions and their parameters to be consumed.
  */
def executeRoutine(routine: Routine): Unit = {
  routine.headOption match {
    case Some((f, x)) =>
      executeSubroutine(f, x)
      executeRoutine(routine.tail)
    case None => ()
  }
}

private def executeSubroutine(subroutine: Subroutine, params: HList): Any = {
  subroutine match {
    case Curried(partiallyApplied, unapplied) =>
      partiallyApplied(params.head)(executeSubroutine(unapplied, params.tail))
    case Uncurried(function) => function(params.head)
  }
}

If anyone can help me out that would be greatly appreciated!


texts: JavaScript architecture example on an HTML page

texts:
I'd want an advise about the following idea that I have for organizing JavaScript when it comes to creating an HTML page. My group will be starting a new project and the approach that I'm trying to come up with will be large scale because every HTML page will be using it. Below I'll show a sample code and I'd like it to be reviewed and advised if you think that's a good approach. I did not find anywhere anything better it seems.

There are 4 files:

${root}/billing.html: contains an input box for the name on credit card
${root}/js/com/mycompany/common/common.js: initializes logging and error handling
${root}/js/com/mycompany/common/Url.js: class that is used to perform an AJAX call
${root}/js/com/mycompany/aproject/billing.js: initializes things on the billing page

common.js:

var com_mycompany_common_common = function() {

    function log(message) {
        console.log((new Date()) + ': ' + message);
    }

    function init() {
        window.onerror = function(message) {
            log('Unhandled error: ' + message);
        }
    }

    return {
        log: log,
        init: init
    }
} ();

$(document).ready(function() {
    try {
        com_mycompany_common_common.init();
    } catch (e) {
        console.log('Error during initialization: ' + e);
    }
});

Url.js:

function com_mycompany_common_Url(url) {
    this.url = url;
}

com_mycompany_common_Url.prototype.addParameter(name, value) {
    this.url += '?' + name + '=' + value;
}

com_mycompany_common_Url.prototype.ajax() {
    com_mycompany_common_common.log('Send ajax to: ' + this.url);
}

billing.js:

var com_mycompany_aproject_billing = function() {

    function init() {
        $('#submitButton').click(function() {
            Url url = new com_mycompany_common_Url('http://bla.com/process/billing');
            var creditCardName = $('#ccName').val();
            url.addParameter('name', creditCardName);
            url.ajax();
        }
    }

    return {init: init};
} ();

$(document).ready(function() {
      try {
           com_mycompany_aproject_billing.init();
      } catch (e) {
           com_mycompany_common_common.log('Error during initialization: ' + e);
      }
});

billing.html:

<!DOCTYPE html>

        <title>Billing</title>

        Enter name on credit card: <input type="text" id="ccName" />

        <button id="submitButton">Submit Payment</button>


texts:
I'm using the BigRational beta off the BCL CodePlex (bcl.codeplex.com), and I realized it had no parsing method, so I tried to write one. However, it's quite inefficient (5.5ms for a 254 character number). That's over 45x slower than the BigInteger implementation. I'd like to lower it to .5ms if that's even possible.

private static Regex DigitDotDigit = new Regex(@"^(\-|\+)?(\d+\.\d+)$", RegexOptions.Compiled);
private static Regex PlainDigit = new Regex(@"^(\-|\+)?\d+$", RegexOptions.Compiled);
private static Regex DigitSlashDigit = new Regex(@"^(\-|\+)?\d+/\d+$", RegexOptions.Compiled);
private static Regex DotDigit = new Regex(@"^(\-|\+)?(\.\d+)", RegexOptions.Compiled);
private static bool RegexInitiated = false;
public static bool TryParse(string parse, out BigRational result)
{
    if (DigitDotDigit.IsMatch(parse))
    {
        int zeros;
        bool isNegative = false;
        string[] parts = parse.TrimStart('+').Split('.');
        parts[1] = parts[1].TrimEnd('0');
        if (parts[0].StartsWith("-"))
        {
            isNegative = true;
            parts[0] = parts[0].Substring(1);
        }
        BigRational whole = new BigRational(BigInteger.Parse(parts[0]), BigInteger.Zero, BigInteger.One);
        BigRational decimalPart = new BigRational(BigInteger.Parse(parts[1]), BigInteger.Zero, BigInteger.One);
        zeros = parts[1].Length - parts[1].TrimStart('0').Length;
        toSubtract = toSubtract + zeros;
        if (zeros > 0)
        {
            toSubtract = toSubtract - 1;
        }
        while (toSubtract != 0)
        {
            decimalPart /= 10;
            toSubtract = toSubtract - 1;
        }
        result = whole + decimalPart;
        if (isNegative)
        {
            result = -result;
        }
        return true;
    }
    else if (DotDigit.IsMatch(parse))
    {
        return TryParse("0" + parse, out result);
    }
    else if (PlainDigit.IsMatch(parse))
    {
        parse = parse.TrimStart('+');
        if (parse.StartsWith("-"))
        {
            result = new BigRational(-BigInteger.Parse(parse), BigInteger.Zero, BigInteger.One);
            return true;
        }
        result = new BigRational(BigInteger.Parse(parse), BigInteger.Zero, BigInteger.One);
        return true;
    }
    else if (DigitSlashDigit.IsMatch(parse))
    {
        string[] parts = parse.TrimStart('+').Split('/');
        if (parts[0].StartsWith("-"))
        {
            parts[0] = parts[0].Substring(1);
            result = -(new BigRational(BigInteger.Parse(parts[0]), BigInteger.Parse(parts[1])));
            return true;
        }
        result = new BigRational(BigInteger.Parse(parts[0]), BigInteger.Parse(parts[1]));
        return true;
    }
    result = BigInteger.Zero;
    return false;
}


texts: Find the nearest point of a given set of points (part 2)

texts:
This is a continued discussion from here, and I use new a approach (bounding box/or envelop algorithm) to improve the algorithm efficiency. Any code bugs, algorithm time complexity improvement or general code advice is highly appreciated.

Major structure of my code:

assign_box is used to build the bounding box or envelop
find_min is finding min points among all candidate points for a given target point. It first uses a bounding box/envelop solution. If it cannot find an answer, it will use a brute force solution
bruce_force is a brute force solution which is used to check the correctness of find_min
distance is a utility method used to check the distance between two points

import sys
import random
from collections import defaultdict
def assign_box(box_map, points, k):
    x_min = min([p[0] for p in points])
    x_max = max([p[0] for p in points])
    y_min = min([p[1] for p in points])
    y_max = max([p[1] for p in points])
    x_distance = (x_max - x_min) / k
    y_distance = (y_max - y_min) / k
    for p in points:
        i = (p[0]-x_min)/x_distance
        j = (p[1]-y_min)/y_distance
        box_map[(i,j)].append(p)

    return (x_min, x_distance, y_min, y_distance)

def distance(p1, p2):
    return (p1[0]-p2[0]) ** 2 + (p1[1]-p2[1]) ** 2

def find_min(points, box_map, target_point, x_min, x_distance, y_min, y_distance):
    # try 9 neighbour first
    row = (target_point[0] - x_min) / x_distance
    col = (target_point[1] - y_min) / y_distance
    result = sys.maxint
    result_point = None
    for r in range(row-1, row+2):
        for c in range(col-1, col+2):
            if (r,c) in box_map:
                for p in box_map[(r,c)]:
                    d = distance(p, target_point)
                    if d < result:
                        result = d
                        result_point = p
    if result_point:
        return (result, result_point)
    else:
        # try brute force solution
        result = sys.maxint
        result_point = None
        for p in points:
            d = distance(p, target_point)
            if d < result:
                result = d
                result_point = p
        return (result, result_point)

def bruce_force(points, target_point):
    result = sys.maxint
    result_point = None
    for p in points:
        d = distance(p, target_point)
        if d < result:
            result = d
            result_point = p
    return (result, result_point)

if __name__ == "__main__":
    # key is a tuple, (box row index, box col index)
    # value is a list of points fall into it
    box_map = defaultdict(list)
    points = []
    for i in range(100):
        points.append((random.randint(0,10), random.randint(0,10)))
    x_min, x_distance, y_min, y_distance = assign_box(box_map, points, 5)
    target_point = (random.randint(0,10), random.randint(0,10))
    print 'target point, ', target_point
    print 'find min result, ', find_min(points, box_map, target_point, x_min, x_distance, y_min, y_distance)
    print 'brute force result, ',  bruce_force(points, target_point)


texts: Solving a practical problem involving square of root of a number

texts:
A student has a book containing 411 pages.
  She read a certain number of pages on the first day and created a rule to work out how many pages she had to read on each succeeding day.
  She decided that the number of pages to be read on the next day should be equal to the square of the sum of the digits of the page she ended at.
  For example, if she ended on page 36, then she should read 81 pages on the next day as this is the square of 6 + 3.
  She found that on the sixth day, the number of pages she had set herself to read took her exactly to the final page of the book.
  How many pages did she read each day?

Here's what I did:

import java.util.*;
import java.lang.*;
import java.io.*;

class ADG {
  public static void main(String[] args) throws java.lang.Exception {
    for (int firstpage = 1; firstpage <= 411; firstpage++) {
      int sum = firstpage;
      int day = 1;
      do {
        sum += squareofroot(sum);
        day++;
        if (sum == 411) {
          System.out.println(firstpage + "&" + day + "\\\\");
          break;
        }
      } while (sum <= 411);
    }
  }
  public static int squareofroot(int pnum) {
    int root = 0;
    int j = 0;
    do {
      root += pnum % 10;
      pnum = pnum / 10;
      j = j + 1;
    } while (pnum != 0);
    return (root * root);
  }

}

Any reviews?

Numbers that end up with 411 pages, not necessarily in 6 days:

$$\begin{array}{c|c}
\text{pages read $\\$on first day}&\text{days required to$\\$ read exactly 411 pages}\\\hline
13&5\\
16&4\\
29&4\\
\huge \color{red}{61}&\huge \color{red}{6}\\
65&3\\
110&5\\
114&4\\
150&3\\
186&2\\
190&3\\
241&3\\
290&2\\
\end{array}$$


texts:
I've spent a few days making the transition from WinForms to WPF, and do not have much time for tutorials as the work needs to be done quickly.  I was wondering if anyone could take a look at a sample of my code and point out any conventions that I'm missing (and that are commonplace in modern WPF usage).  I've picked a random sample of some XAML code which I've written:

<Window x:Class=""
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Width="300" Height="300">
    <Window.Resources>

    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition>
                </RowDefinition>
                <RowDefinition>
                </RowDefinition>
                <RowDefinition>
                </RowDefinition>
                <RowDefinition>
                </RowDefinition>
                <RowDefinition>
                </RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="70">
                </ColumnDefinition>
                <ColumnDefinition Width="200">
                </ColumnDefinition>
            </Grid.ColumnDefinitions>
            Server:
            <ComboBox Grid.Column="1" Grid.Row="0" Name="cmbServer" Style="{StaticResource componentsStyle}"/>
            <CheckBox Name="chkWindowsAuthentication" Grid.Column="0" Grid.Row="1" IsChecked="False"/>
            Use Windows Authentication
            Username:
            <TextBox Grid.Column="1" Grid.Row="2" Name="txtUsername" Style="{StaticResource componentsStyle}"/>
            Password:
            <PasswordBox Grid.Column="1" Grid.Row="3" Name="txtPassword" Style="{StaticResource componentsStyle}"/>
            Database:
            <ComboBox Grid.Column="1" Grid.Row="4" Name="cmbDatabase" Style="{StaticResource componentsStyle}"/>
        </Grid>
        <StackPanel Orientation="Horizontal" Margin="10,30,10,10">
            <Button Margin="0,0,10,0" Style="{StaticResource buttonsStyle}">Connect</Button>
            <Button Style="{StaticResource buttonsStyle}">Reset</Button>
        </StackPanel>
    </StackPanel>
</Window>

The code is functional and displays the proper result, however I am worried that I am not using the right techniques.  Any input at all is greatly appreciated.


texts: Checking that a 6-digit number is not repeated and not in sequence

texts:
Following is the objective C code snippet to check that the 6-digit number is not repeated and not in sequence/reverse-sequence. I have just printed the proper messages in NSLog that user should be allowed or not:

 NSError *error = nil;
 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?!(\\d)\\1+$|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\\d$)\\d{6}$" options:NSRegularExpressionCaseInsensitive error:&error];

        NSRange matchRange = [regex rangeOfFirstMatchInString:text options:NSMatchingReportCompletion range:NSMakeRange(0, text.length)];

        BOOL didValidate = NO;
        if(matchRange.location != NSNotFound){
            didValidate = YES;
        }
        if(didValidate){
            NSLog(@"Allowed");
        }else{
            NSLog(@"Not Allowed");
        }

I just want to know if this regex has an effect on performance, and if yes, then what should be optimal solution for it. It would be great if anyone can provide their inputs for the same.


texts: Program to check if heap order is correct or not

texts:
There is a Java program to check if a Heap (Min) is in the correct order. Heap Order means the parent is less than both left child and right child.

package testers;

import heap.Heap;
import java.util.List;

public class HeapTester
{
    public static void main(String[] args)
    {
        Heap<Integer> heap = new Heap <>();
        heap.add(50);
        heap.add(25);
        heap.add(26);
        heap.add(15);
        heap.add(10);
        heap.add(16);
        heap.add(3);
        heap.add(7);
        heap.add(10);
        heap.add(12);
        heap.add(2);
        System.out.println(heap);
        System.out.println(hasHeapOrder(heap.copy()));
    }

    private static <T extends Comparable<T>> boolean hasHeapOrder(List<T> list)
    {
        if(list.size() < 2) return true;

        boolean hasOrder = true;

        int parent = 0;
        int leftChild = 2 * parent + 1;
        int rightChild = 2 * parent + 2;

        while(leftChild < list.size())
        {
            if(list.get(parent).compareTo(list.get(leftChild)) > 0)
            {
                hasOrder = false;
                break;
            }
            if(rightChild < list.size())
            {
            if(list.get(parent).compareTo(list.get(rightChild)) > 0)
                {
                    hasOrder = false;
                    break;
                }
            }

            parent++;
            leftChild = 2 * parent + 1;
            rightChild = 2 * parent + 2;
        }
        return hasOrder;
    }
}


texts: Create a Promise that resolves when jQuery loads

texts:
I'm currently experimenting with async loading of JavaScript and came up with the following trick to detect when jQuery loads:

var jQueryPromise = new Promise(function(resolve) {
  Object.defineProperty(window, '$', {
    get: function() {
      return this.jQuery;
    },
    set: function(value) {
      if (typeof value === 'function') {
        resolve(value);
      }
    }
  });
  if (typeof jQuery === 'function') {
    $ = jQuery;
  }
});

jQueryPromise.then(function($) {
    // use $ normally here
});

The idea is to have a method which works regardless of how and when jQuery was loaded (via a script tag, async script tag, script created via document.createElement...)

My aim is really just to understand how to best utilise async loading in general - all comments are welcome, especially regarding possible quirks of this (hacky) approach.

In addition, I'm curious whether there are any performance advantages to loading jQuery async and then waiting for the Promise to resolve using this method over just loading it normally before the script (and in which cases would this performance boost happen)?


texts: StreamIterable - create an iterable from a Java 8 Stream

texts:
This seems like an easy thing to mess up, so I'd be grateful if you could think of any edge-cases that I've missed.

public class StreamIterable<T> implements Iterable<T> {

  private final Stream<T> stream;

  public StreamIterable(Stream<T> stream) {
    this.stream = stream;
  }

  @Override
  public Iterator<T> iterator() {
    return new StreamIterator<>(stream);
  }
}

where

public class StreamIterator<T> implements Iterator<T> {
  private final Spliterator<T> spliterator;

  private boolean nextIsKnown = false;
  private T next = null;

  public StreamIterator(Stream<T> stream) {
    this.spliterator = stream.spliterator();
  }

  @Override
  public boolean hasNext() {
    if (nextIsKnown)
        return true;
    return spliterator.tryAdvance(t -> {next = t; nextIsKnown = true;});
  }

  @Override
  public T next() {
    if (nextIsKnown) {
        return resetAndReturnNext();
    }
    if (!hasNext())
        throw new NoSuchElementException();
    return resetAndReturnNext();
  }

  private T resetAndReturnNext() {
    T result = next;
    nextIsKnown = false;
    next = null;
    return result;
  }
}

Tests

public class StreamIteratableTest {

    @Test
    public void empty() {
        assertThat(new StreamIterable<>(Stream.<String>empty()), Matchers.emptyIterable());
    }

    @Test
    public void matcher() {
        Stream<String> stream = Stream.of("1", "2", "3");
        assertThat(new StreamIterable<>(stream), Matchers.contains("1", "2", "3"));
    }

    @Test
    public void torture_empty() {
        StreamIterator<Object> empty = new StreamIterator<>(Stream.empty());

        assertFalse(empty.hasNext());
        try {
            empty.next();
            fail();
        } catch (NoSuchElementException expected) {
        }

        assertFalse(empty.hasNext());
        assertFalse(empty.hasNext());
        try {
            empty.next();
            fail();
        } catch (NoSuchElementException expected) {
        }
        try {
            empty.next();
            fail();
        } catch (NoSuchElementException expected) {
        }
    }

    @Test
    public void dont_call_hasNext() {
        StreamIterator<Object> twoItems = new StreamIterator<>(Stream.of("1", "2"));

        assertEquals("1", twoItems.next());
        assertEquals("2", twoItems.next());
        try {
            twoItems.next();
            fail();
        } catch (NoSuchElementException expected) {
        }
    }

    @Test
    public void repeat_call_hasNext() {
        StreamIterator<Object> twoItems = new StreamIterator<>(Stream.of("1", "2"));

        assertTrue(twoItems.hasNext());
        assertTrue(twoItems.hasNext());
        assertEquals("1", twoItems.next());
        assertTrue(twoItems.hasNext());
        assertEquals("2", twoItems.next());
        assertFalse(twoItems.hasNext());
        assertFalse(twoItems.hasNext());
    }
}


texts: Yet another Pascal triangle in Python written in functional programming pattern

texts:
Here is my implementation of a Pascal program, which is used to print an n-order Pascal triangle. This is actually an exercise I came up with to familiarize myself with Python's Functional Programming Modules.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import operator
from itertools import starmap, tee
from functools import lru_cache

def pairwise(iterable):
    """
    s -> (s0,s1), (s1,s2), (s2,s3), ...
    https://docs.python.org/3/library/itertools.html#itertools-recipes
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

@lru_cache()
def pascal_row(n):
    """
    Print the nth row of a Pascal triangle
    """
    if n < 2:
        return (x for x in [1])
    else:
        def dispatch():
            yield 1
            yield from starmap(operator.add, pairwise(pascal_row(n-1)))
            yield 1
        return dispatch()

def pascal(n):
    """
    Print an n-order Pascal triangle
    """
    for i in range(1, n):
        print(pascal_row(i))

print([x for x in pascal_row(500)])

Is this the right way of functional programming? Also, I want you to tell me how to make this piece of code clearer :)


texts:
I want to use Microsoft.AspNet.Identity's PasswordHasher but I don't want to pollute my Domain layer with knowledge of it. As such I created an interface in my Domain layer

public interface IPasswordService
{
    string HashPassword(string password);

    bool VerifyPassword(string hashedPassword, string testPassword);
}

So I can use DI for both IPasswordHasher and IPasswordService I created an adaptor:

public class PasswordServiceAdaptor : IPasswordService, IPasswordHasher
{
    private readonly PasswordHasher hasher;

    public PasswordServiceAdaptor()
    {
        this.hasher = new PasswordHasher();
    }

    string IPasswordHasher.HashPassword(string password)
    {
        return this.hasher.HashPassword(password);
    }

    PasswordVerificationResult IPasswordHasher.VerifyHashedPassword(
        string hashedPassword,
        string providedPassword)
    {
        return this.hasher.VerifyHashedPassword(hashedPassword, providedPassword);
    }

    string IPasswordService.HashPassword(string password)
    {
        return this.AsPasswordHasher().HashPassword(password);
    }

    bool IPasswordService.VerifyPassword(string hashedPassword, string testPassword)
    {
        var result = this.AsPasswordHasher().VerifyHashedPassword(
                         hashedPassword,
                         testPassword);

        return result == PasswordVerificationResult.Success;
    }

    private IPasswordHasher AsPasswordHasher()
    {
        return this;
    }
}

Is this a reasonable way to go about this? Are there any better patterns I can use?


texts: Multi-threaded in-place Mergesort on Java

texts:
What is an efficient way to implement the Mergesort algorithm in Java such that it meets the following criteria:

Must be multi-threaded.
Must retain the Mergesort time complexities.
Must be in-place implementation, no copying arrays.
Must use Java Collection classes, not an array.
Must work on any Java Comparable.

My solution involves using an ArrayList and fork-join to create the in-place Mergesort. I've tested this on multiple inputs and they all work.

I'm curious if anyone can find a way I can improve my code. Either a more efficient solution or perhaps an edge case I didn't address.

import java.util.*;
import java.util.concurrent.*;

public class MergeSort<N extends Comparable<N>> extends RecursiveTask<List<N>> {
    private List<N> elements;

    public MergeSort(List<N> elements) {
        this.elements = elements;
    }

    @Override
    protected List<N> compute() {
        if(this.elements.size() <= 1)
            return this.elements;
        else {
            final int pivot = this.elements.size() / 2;
            MergeSort<N> leftTask = new MergeSort<N>(this.elements.subList(0, pivot));
            MergeSort<N> rightTask = new MergeSort<N>(this.elements.subList(pivot, this.elements.size()));

            leftTask.fork();
            rightTask.fork();

            List<N> left = leftTask.join();
            List<N> right = rightTask.join();

            merge(left, right);
            return this.elements;
        }
    }

    private void merge(List<N> left, List<N> right) {
        int leftIndex = 0;
        int rightIndex = 0;
        while(leftIndex < left.size()) {
            if(rightIndex == 0) {
                if( left.get(leftIndex).compareTo(right.get(rightIndex)) > 0 ) {
                    swap(left, leftIndex++, right, rightIndex++);
                } else {
                    leftIndex++;
                }
            } else {
                if( right.get(0).compareTo(right.get(rightIndex)) < 0 ) {
                    swap(left, leftIndex++, right, 0);
                } else {
                    swap(left, leftIndex++, right, rightIndex++);
                }
            }
        }

        if(rightIndex < right.size() && rightIndex != 0)
            merge(right.subList(0, rightIndex), right.subList(rightIndex, right.size()));
    }

    private void swap(List<N> left, int leftIndex, List<N> right, int rightIndex) {
        //N leftElement = left.get(leftIndex);
        left.set(leftIndex, right.set(rightIndex, left.get(leftIndex)));
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        List<Integer> result = forkJoinPool.invoke(new MergeSort<Integer>(new ArrayList<>(Arrays.asList(1,3,5,7,2,4,6))));
        System.out.println("result: " + result);
    }
}

Update: The code will fail on the edge case where the following input integers are used:

{5,9,8,7,6,1,2,3,4}

This occurs because the recursive call to merge only works successfully when the left and right lists are of equal length or differ by only one in length. This call however will result in the comparison of two lists that breaks that expectation. I have yet to find a solution which handles all edge cases properly.