texts:
Problem Statement

  Akash and Akhil are playing a game. They have N balls numbered from 0
  to N−1.         Akhil asks Akash to reverse the position of the balls,
  i.e., to change the order from say, 0,1,2,3 to 3,2,1,0.   He further
  asks Akash to reverse the position of the balls N times, each time
  starting from one position further to the right, till he reaches the
  last ball.    So, Akash has to reverse the positions of the ball
  starting from 0th position, then from 1st position, then from 2nd
  position and so on.

  At the end of the game, Akhil will ask Akash the final position of any
  ball numbered K. Akash will win the game, if he can answer. Help
  Akash.

  Input

  The first line contains an integer \$T\$, i.e., the number of the test
  cases.

  The next \$T\$ lines will contain two integers \$N\$ and \$K\$.

  Output

  Print the final index in array.

  Constraints

  \$1 ≤ T ≤ 50\$
  \$1 ≤ N ≤ 10^5\$
  \$0≤K<N\$

  Sample Input

2
3 1
5 2

  Sample Output

2
4

  Explanation

    For first test case, The rotation will be like this:    0 1 2 -> 2 1 0 -> 2 0 1 -> 2 0 1    So, Index of 1 will be 2.

Solution

test = gets.chomp.to_i
test.times do
   num, numbered = gets.split.map(&:to_i)
   a = []
   elem = 0
   a << elem

  (num-1).times do
   elem += 1
   a << elem
  end

  len = a.length
  final = []
  w = []

 len.times do
  if w.length == 0
   q = a.reverse
  else
   q = w.reverse
  end
  elem = q.shift
  final << elem
  w = q - [elem]
 end

 puts final.index(numbered)
end

My Problem

I could only pass 4 test cases out of 11 since it always timed out for the rest. This is happening because my solution isn't efficient enough.  How can we do it efficiently so that it passes all 11 test cases?


texts:
This is router I created for use, however, I wish to refactor this code and make this more robust. I would really appreciate anyone who can:

Point out how to make this code more robust, clean and flexible in terms of reusability where the user of this module can easily alter the configuration, etc to his/her needs without possibly altering the source code.
Point out where code can be refactored and possibly how.
Point out how the code could be made more efficient.

Point out places where I have breached any principles of OOP.

Implementation:

$router = new Router\Router();
/**
 * The arguments for the method createRoute:
 * First Argument - URI
 * Second Argument - Namespace or Classname of which the method will be executed.
 * Third Argument - The method to be run in the specified namespace/class in the second argument.
 */
$router->createRoute('/', 'PageController', 'showHome');
$result = $router->runRouter();

Source Code:

<?php
namespace Router;

class Router
{
    private $routes = array();
    private $patternForURIs = '/\{[a-zA-Z0-9]*\}/';

    public function createRoute($uri, $class, $method)
    {
        $result = $this->checkWhetherParametersAreRequired($uri);

        if($result != false) {
            $this->routes[] = [$uri, $class, $method, $result];
            return true;
        }

        $this->routes[] = [$uri, $class, $method];
        return true;
    }

    public function checkWhetherParametersAreRequired($uri)
    {
        if(preg_match_all($this->patternForURIs, $uri, $matches)) {
            return $matches[0];
        }
        return false;
    }

    public function runRouter()
    {
        $routesWhichExpectParameters = array();

        foreach($this->routes as $route) {
            if(isset($route[3])) {
                $routesWhichExpectParameters[] = $route;
            }
            if($route[0] === $_SERVER["REQUEST_URI"]) {
                return $route;
            }
        }

        foreach($routesWhichExpectParameters as $route) {
            $route[0] = ltrim($route[0], '/');
            $route[0] = explode('/', $route[0]);
            $partsToConfirm = count($route[0]);

            $requestURI = ltrim($_SERVER["REQUEST_URI"], '/');
            $requestURI = explode('/', $requestURI);
            $partsAvailable = count($requestURI);

            if($partsToConfirm != $partsAvailable) {
                continue;
            }

            $confirmedParts = 0;

            $numberOfParametersToDetect = count($route[3]);
            $numberOfParametersDetected = 0;
            $detectedParameters = array();

            for($iterator = 0; $iterator < $partsToConfirm; $iterator++) {
                if($route[0][$iterator] == $requestURI[$iterator]) {
                    $confirmedParts++;
                    continue;
                } else if(preg_match($this->patternForURIs, $route[0][$iterator])) {
                    $confirmedParts++;
                    $detectedParameters[] = array(
                        $route[3][$numberOfParametersDetected] => $requestURI[$iterator]
                    );

                    $numberOfParametersDetected++;
                    continue;
                }
            }

            if(($numberOfParametersDetected == $numberOfParametersToDetect) && ($partsToConfirm == $confirmedParts)) {
                $route[4] = $detectedParameters;
                return $route;
                break;
            }
        }
        return false;
    }
}


texts:
Given a String. we have to print out the letter repetition

Sample input "aaaabbaac"

Sample output "4a2b2a1c"

public void continousWords(String input) {
String sample= input +" ";
String[] sampleList  =   sample.split("");
String temp = sampleList[0];
String result="";
int placeHolder=0;
for(int i=0;i<sampleList.length;i++){

    if(temp.equalsIgnoreCase(sampleList[i])) {
        placeHolder++;

    }
    else {
      result = result+placeHolder+temp;
      placeHolder =1;
      temp = sampleList[i];
    }

}
System.out.println(result);

}

Is there a better way to approach the problem


texts: Function to generate pyspark diff and return differences in line

texts:
I have written a function that takes two pyspark dataframes and creates a diff in line. I am struggling to get it to scale with 100s of columns. I get around the for loop calling .join() hundreds of times. I am stuck, or maybe tired and looking for some suggestions!

from pyspark.sql import functions as sf

def diff_generate(df_one, df_two, pk):
# create df to join compared columns with
    diff_df = df_one.select(pk)
# ensure the PK is not in the schema to iterate needed cols
    if pk in df_one.schema.names:
        df_one.schema.names.remove(pk)
    for col in df_one.schema.names:
# ensure that col exists in df2
        if col in df_two.schema.names:
            df_two_ = df_two.select(pk, col)\
            .withColumnRenamed(col, "{}_compare".format(col))
            df = df_one.select(pk, col)\
            .subtract(df_two_)\
            .join(
                df_two_,
                pk,
                "left_outer"
                )
# concat df columns to display comparison
            concat_df = df\
            .withColumn("{}_diff".format(col),
                sf.concat(
                    sf.col(col),
                    sf.lit("_compare:_"),
                    sf.col("{}_compare".format(col))))\
            .select(pk, "{}_diff".format(col))
# join column 'diff' with initialized df
            diff_df = diff_df.join(concat_df, pk, "left_outer")
    return diff_df

Sample result:

98723498,match,N_compare:_null,match,match,match,2018-05-15 18:37_compare:_2018-05-15 18:37:12,match,match


texts: internal links b/w sheets of merged workbooks, using VBA (EXCEL MACROS)

texts:
My aim is to merge all workbooks having multiple sheets from any specified folder to one workbook of multiple sheets. The problem is I don’t want external links to be maintained, If I use "breaklink" it will break all links(external links) b/w sheets of all workbooks. what I exactly I need is, After merging all sheets of workbooks in one workbook, I need links b/w these merged sheets.
CODE FOR MERGE ALL WORKBOOKS INTO ONE WORKBOOK :
Sub merge()

Dim FolderPath As String

Dim Filename As String

Dim Sheet As Worksheet

Application.ScreenUpdating = False

FolderPath = "C:\Users\Samiya jabbar\Desktop\test"

Filename = Dir(FolderPath)

Do While Filename <> ""

Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True

For Each Sheet In ActiveWorkbook.Sheets

Sheet.Copy After:=ThisWorkbook.Sheets(1)

Next Sheet

Workbooks(Filename).Close

Filename = Dir()

Loop

Application.ScreenUpdating = True

End Sub
```


texts:
I've made the following Java-class just for getting some practice with the creation and reading of files.

package modul;

import static java.lang.System.*;
import java.io.*;

public class Sandbox {
    public static void main (String[] args) {

        // I found out that the project directory is the
        //  working directory by default.
        //  Is there a way to change the working directory in Java?
        //  So that all instructions become relative to that directory.
        String currentDir = System.getProperty("user.dir") + "/src/modul/";
        String fileName = "lorem.txt";

        try {
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(currentDir + fileName)));

            // Write a few lines of dummy-text ...
            writer.println("The very first line of text.");
            writer.println("----------------------------");
            writer.println("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.");
            writer.println("Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.");
            writer.println("In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.");

            // Is it enough just closing the PrintWriter?
            //  What's about the BufferedReader and the FileReader?
            //  Are they closed automatically?
            writer.close();

            // Now open the created file. Read and print it's
            //  content to stdout.
            BufferedReader reader = new BufferedReader(new FileReader(currentDir + fileName));
            String line;
            int lineNumber = 0;

            while ((line = reader.readLine()) != null) {
                out.println(++lineNumber + ": " + line);
            }

            // Is it fair enough just closing the Reader?
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Although it won't serve a real use-case it's important for me to know if everything is done in a good way. Or does I have to improve the code?

Moreover: Are there ways to accomplish writing-, reading-operations more efficient? Respectively in a simpler way?

A few more questions I've still got about Java IO-operations I've added as comments within the code.

All comments, hints and recommendations of more experienced Java-devs much appreciated.


texts: Find intersections of overlapping intervals

texts:
This code finds the intersections of all overlapping intervals.

Example: if [0-20], [15-40], and [25-50] are the 3 intervals then the output should be [15-20] and [25-40].

I could not find an answer with complexity less than \$O(n^2)\$. Please suggest a better solution if one exists. Additionally, assume the input intervals are sorted by their start times.

public static Set<OverlapCoord> getOverlap(List<Interval> intervalList) {
    if (intervalList == null) {
        throw new NullPointerException("Input list cannot be null.");
    }

    final HashSet<OverlapCoord> hashSet = new HashSet<OverlapCoord>();

    for (int i = 0; i < intervalList.size() - 1; i++) {
        final Interval intervali =  intervalList.get(i);

        for (int j = 0; j < intervalList.size(); j++) {
            final Interval intervalj = intervalList.get(j);

            if (intervalj.getStart() < intervali.getEnd() && intervalj.getEnd() > intervali.getStart() && i != j) {
                hashSet.add(new OverlapCoord(Math.max(intervali.getStart(),intervalj.getStart()),
                                             Math.min(intervali.getEnd(), intervalj.getEnd())));
            }
        }
    }

    return hashSet;
}


texts:
I'm fairly good at programming python but of course i want to write cleaner code.

This is a simple script that scrapes leads off yellowbook.

I want to utilize list comprehensions but im comfortable with using for loops, however i can see how it can be repetitive.

Any ways i can make this cleaner ?

service_name = input("Input Industry: ")
city = input("Input The City: ")

class Item(scrapy.Item):
    business_name = scrapy.Field()
    phone_number = scrapy.Field()
    website = scrapy.Field()

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    start_urls = [
        "http://www.yellowbook.com/s/" + service_name + "/" + city
    ]
    def __init__(self):
        self.seen_business_names = []
        self.seen_websites = []

    def parse(self, response):
        for business in response.css('div.listing-info'):
            item = Item()
            item['business_name'] = business.css('div.info.l h2 a::text').extract()
            item['website'] = business.css('a.s_website::attr(href)').extract()
            for x in item['business_name'] and item['website']:
                #new code here, call to self.seen_business_names
                if (x not in self.seen_business_names and x not in self.seen_websites):
                    if item['business_name']:
                        if item['website']:
                            item['phone_number'] = business.css('div.phone-number::text').extract_first()
                            yield item
                            self.seen_business_names.append(x)

        # next_page = response.css('div.pagination a::attr(href)').extract()
        for href in response.css('ul.page-nav.r li a::attr(href)'):
            yield response.follow(href, self.parse)


texts: Reverse dictionary where values are lists

texts:
I'm working on the following problem: I've got a dictionary like this one:

dic={0:[0,1,2],1:[3,4,5]}

And I want to reverse it so it looks like this:

dic2={0:0,1:0,2:0,3:1,4:1,5:1}

I managed to make it, but doing this:

dic2={}
for i in dic:
    for j in dic[i]:
        dic2[j]=i

I know about list and dict comprehensions and this code reeks of it, but I'm not good at them when there are nested for and dicts. How would you make it more efficiently?


texts: Python lazy dict with iterator in constructor

texts:
This question began as an off-topic answer to this question, but the code here serves a different goal.

I wrote the following class for the purpose of populating a dict on demand from an iterator. The intent of the iterator passed to the constructor is that it could alternatively be passed to dict, which would consume the entire iterator in its constructor; an instance of this class consumes the iterator just far enough to locate a requested item. Such an iterator would be similar in spirit to a return value from dict.items.

class LazyDict(dict):
    """ A dict built on demand from an iterator """

    def __init__(self, iterator):
        super().__init__()
        self.iterator = iterator

    def __getitem__(self, item):
        while not self.get(item):
            try:
                (key, value) = next(self.iterator)
                self[key] = value
            except StopIteration:
                raise AttributeError
        return super().__getitem__(item)

    def __contains__(self, item):
        try:
            self[item] # pylint: disable=pointless-statement
            return True
        except AttributeError:
            return False

Here is my calling code (with other details of the Directory code omitted; if more of that is needed in this context I can provide it):

class Directory(object):
    @Lazy
    def hash(self):
        """ Lazy dict mapping entry names to entries """
        return LazyDict((self.name(entry), entry) for entry in self.readdir())

    def __contains__(self, name):
        return name in self.hash # pylint: disable=unsupported-membership-test

    def __getitem__(self, name):
        return self.hash[name] # pylint: disable=unsubscriptable-object

The code for Lazy is equivalent to lazy_property in this answer.

As I write this, it occurs to me that perhaps Directory should itself be a subclass of LazyDict rather than containing a LazyDict (that might be a better way to stifle those pylint warnings). Whether that seems right might be one specific question to fall out of this. Upon further investigation, here is an alternate version of the calling code:

class Directory(LazyDict):
    def __init__(self, mem, size):
        super().__init__((self.name(entry), entry) for entry in self.readdir())
        self.mem = mem
        self.size = size

As before, some details of Directory are omitted (the implementations of name and readdir are not included for either version), but this version of the code inherits __getitem__ and __contains__ from LazyDict rather than overriding them. The most visible difference between the two versions of the calling code is due to Directory inheriting __repr__ from dict rather than object.

Another specific question might be the role of keys and values and items in LazyDict. The methods inherited from dict reveal how much of the iterator has been consumed; convincing them to reveal all items is one AttributeError away (I can attempt to fetch self[None] within Directory to fully populate the cache). My inclination is to limit on-demand operations to __getitem__ and __contains__, but opinions on that point are welcome.

Suggestions for other ways to approach this are also welcome.


texts: Three very similar functions operating on XML files

texts:
I have 3 functions which are annoyingly similar, but I can't figure out a way to refactor them without making the code unreadable.

The three functions deal with xml files (.resx), the first function reads all files in a directory and "collects" all strings inside a data.value tag, adds them to a set and returns that set, for example:

<data name="AccessibilityTitleResource1.Text" xml:space="preserve">
<value>Pages Accessibility</value>

The second function reads these same files, and swaps the values read previously with a translation which is inside a dict called definicoes (definicoes[english] = translation), with the previous example, then saves the file. So from our previous example definicoes["Pages Accessibility"] = "Acessibilidade de Páginas". The xml file would become:

<data name="AccessibilityTitleResource1.Text" xml:space="preserve">
<value>Acessibilidade de Páginas</value>

The third function simply checks if the xml file is fully translatable, so it checks all the values <value> tags inside the <data> ones against the ones in the dict, if there is any value not present on the dict it returns False.

Here are the three functions:

def ler_todos(caminho) -> set:
    definicoes = set()
    for file in os.listdir(caminho):
        if file.endswith(".ascx.resx") or file.endswith(".aspx.resx"):
            tree = ET.parse(caminho + file)
            root = tree.getroot()
            for child in root.iter('data'):
                if child.attrib.get('namespace') == 'preserve':
                    node = child[0]
                    if node.tag == "value" and node.text != None and not node.text in definicoes:
                        definicoes.add(node.text)
    return definicoes

def escrever_arquivo(definicoes, caminho):
    if caminho.endswith(".pt.resx"):
        tree = ET.parse(caminho)
        root = tree.getroot()
        for child in root.iter('data'):
            if child.attrib.get('namespace') == 'preserve':
                node = child[0]
                if node.tag == "value" and node.text != None and node.text in definicoes:
                    node.text = definicoes[node.text]
        tree.write(caminho, encoding="UTF-8")
        anexar_cabecalho(caminho)

def existe_traducao(definicoes, caminho):
    if caminho.endswith(".resx"):
        tree = ET.parse(caminho)
        root = tree.getroot()
        for child in root.iter('data'):
            if child.attrib.get('namespace') == 'preserve':
                node = child[0]
                if node.tag == "value" and node.text != None and len(node.text) > 0 and node.text not in definicoes:
                    return False
        return True


texts:
Code shows duplicate values of integers in an array with indexes and the number of occurrences. Can you please critique my code and provide your thoughts on where I should improve my code?

import java.util.Set;
import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;

public class DuplicatesInAnArray {

    private static class ShowIndexDuplicateData<T> {
        private static final String NEW_LINE = System
                .getProperty("line.separator");
        private Set<T> indices;
        private int count;

        public ShowIndexDuplicateData(Set<T> indices, int count) {
            this.indices = indices;
            this.count = count;
        }

        public Set<T> getIndices() {
            return indices;
        }

        public int getCount() {
            return count;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("Count: ").append(getCount()).append(" Indices: ")
                    .append(getIndices()).append(NEW_LINE);

            return sb.toString();
        }
    }

    public static void duplicatesInAnArray(Integer[] array) {
        if (array == null || array.length <= 1) {
            System.out.println("");
        }

        Map<Integer, ShowIndexDuplicateData<Integer>> map = new HashMap<>();

        for (int i = 0; i < array.length - 1; i++) {

            if (map.containsKey(array[i])) {
                ShowIndexDuplicateData<Integer> showIndexDuplicateData = map
                        .get(array[i]);
                showIndexDuplicateData.count++;
                showIndexDuplicateData.indices.add(i);
            } else {
                int count = 1;
                Set<Integer> indices = new HashSet<>();
                indices.add(i);
                ShowIndexDuplicateData<Integer> showIndexDuplicateData = new ShowIndexDuplicateData<>(
                        indices, count);
                map.put(array[i], showIndexDuplicateData);
            }
        }
        System.out.println(map);
    }

    public static void main(String[] args) {
        Integer[] array = { 5, 6, 1, 2, 3, 3, 6, 1 };
        DuplicatesInAnArray.duplicatesInAnArray(array);
    }
}


texts:
This question I asked previously mentions a function named BuildControlCollection, which I didn't go into the details of since it wasn't relevant. However, because the implementation contains some funky code I'm not 100% on (it completely works, I'm just unsure if it's the best way to do it), I decided to put this up for review too.

Public Sub BuildControlCollection(ByRef ipForm As Form,
                                  ByRef mpCollection As Collection,
                                  ByVal ipControlType As ControlTypes)

The function takes the form that we're building a control collection from, an unset collection object (which will be created and filled), and an enum value to indicate the type(s) of controls to fill the collection with.

Enum ControlTypes
    eTextBox = &H1
    eComboBox = &H2
    eLabel = &H4
    eButton = &H8
    eFrame = &H10
    eRadioButton = &H20
    eListBox = &H40
    eLine = &H80
    eRectangle = &H100
    eCheckbox = &H200
    eChart = &H400
    eAll = &H800
End Enum

Public Sub BuildControlCollection(ByRef ipForm As Form, _
                                  ByRef mpCollection As Collection, _
                                  ByVal ipControlType As ControlTypes)

    If Not mpCollection Is Nothing Then
        Err.Raise 5000, "Collection has previously been set. This operation would delete the collection."
    End If

    Set mpCollection = New Collection

    Dim lControl As Control
    For Each lControl In ipForm.Controls

        If ipControlType And eAll Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eButton) And TypeName(lControl) = "CommandButton" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eChart) And TypeName(lControl) = "ObjectFrame" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eCheckbox) And TypeName(lControl) = "CheckBox" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eComboBox) And TypeName(lControl) = "ComboBox" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eFrame) And TypeName(lControl) = "Frame" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eLabel) And TypeName(lControl) = "Label" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eLine) And TypeName(lControl) = "Line" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eListBox) And TypeName(lControl) = "ListBox" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eRadioButton) And TypeName(lControl) = "RadioButton" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eRectangle) And TypeName(lControl) = "Rectangle" Then
            mpCollection.Add lControl

        ElseIf (ipControlType And ControlTypes.eTextBox) And TypeName(lControl) = "TextBox" Then
            mpCollection.Add lControl

        End If

    Next lControl

End Sub

The thinking behind the last argument of BuildControlCollection is to allow multiple options to be passed (eg eTextBox Or eButton) - I've seen this used in the built-in functions such as MsgBox - the second argument (somewhat inaccurately named Buttons) of which allows you to specify for eg vbOKOnly Or vbExclamation to get a messagebox with both an OK button and a warning triangle. I don't know what this is called, so I haven't been able to Google a real implementation, so I've had to make my best guess at it.

I understand that it works by comparing bits - for eg, vbOKOnly may be 0000 0001, whilst vbExclamation may be 0001 0000, so passing vbOkOnly Or vbExclamation (0001 0001) matches on both bits.

Whilst my implementation above definitely works, that enormous If/ElseIf smells funny. If anyone can tell me what the bit flagging thing used in MsgBox is called, that would be really useful too.


texts: Heap Sort implementation time complexity

texts:
I have implemented Heap sort, but i think the time complexity is more than (nlogn).
Could anyone explain me; what is wrong in my code which makes more time complexity.

I will be glad if the answer is in terms of algorithm time complexity based.

import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] array = { 5, 6, 10, 3, 9, 2, 12, 1, 8, 7 };
        maxHeapSort(array, array.length);
        System.out.println(Arrays.toString(array));
        System.out.println("\n\n");
    }

    private static void maxHeapSort(int[] array, int length) {
        for(int i = 1; i < length; i++ ) {
            maxHeapify(array, 1, length-i);
            swap(array, 0, length-i);
        }
        //Working on last three indexes [which is 0,1,2]
        correctNode(array, 1, 3);
        swap(array, 0, 2);
        correctNode(array, 1, 2);
        swap(array, 0, 1);
    }

    private static void maxHeapify(int[] array, int nodeIndex, int length) {
        if(nodeIndex < length) {
            correctNode(array, nodeIndex, length);
            maxHeapify(array, 2 * nodeIndex, length);
            maxHeapify(array, (2 * nodeIndex)+1, length);
            correctNode(array, nodeIndex, length);
        }
    }

    private static void correctNode(int[] array, int index, int length) {
        int rootIndex = index - 1;
        int leftIndex = (2 * index) - 1;
        int rightIndex = ((2 * index) + 1) - 1;
        if(leftIndex < length && array[rootIndex] < array[leftIndex]) {
            swap(array, rootIndex, leftIndex);
        }

        if(rightIndex < length && array[rootIndex] < array[rightIndex]) {
            swap(array, rootIndex, rightIndex);
        }
    }

    private static void swap(int[] array, int m, int n){
        int temp = array[m];
        array[m] = array[n];
        array[n] = temp;
    }
}


texts:
I am very new to matrix math. I have the following that sets the rotation in a 4x4 matrix. It is pretty ugly, so can anyone suggest how I could clean this up?

I would like to not have to call MultiplyTwoMatrixes twice. A better way of copying the 3x3 matrix into the end 4x4 matrix would be nice as well.

void MultiplyTwoMatrixes(float aMatrix[9], float bMatrix[9], float product[9])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            product[j + i * 3] = 0;
            for (int k = 0; k < 3; k++)
            {
                product[j + i * 3] += aMatrix[k + i * 3] * bMatrix[j + k * 3];
            }
        }
    }
}

void setrotation(float x, float y, float z)
{
    const float* oldMatrix = node->GetTransform();

    float xRot[9] = { 1, 0, 0, 0, cos(x), sin(x), 0, -sin(x), cos(x) };
    float yRot[9] = { cos(y), 0 ,-sin(y), 0, 1, 0, sin(y), 0, cos(y) };
    float zRot[9] = { cos(z), sin(z), 0, -sin(z), cos(z), 0, 0, 0, 1 };

    float xyResult[9];
    float xyzResult[9];
    float newMatrix[16];
    MultiplyTwoMatrixes(xRot, yRot, xyResult);
    MultiplyTwoMatrixes(xyResult, zRot, xyzResult);

    newMatrix[0] = xyzResult[0]; newMatrix[1] = xyzResult[1]; newMatrix[2] = xyzResult[2];
    newMatrix[4] = xyzResult[3]; newMatrix[5] = xyzResult[4]; newMatrix[6] = xyzResult[5];
    newMatrix[8] = xyzResult[6]; newMatrix[9] = xyzResult[7]; newMatrix[10] = xyzResult[8];
    newMatrix[12] = oldMatrix[12]; newMatrix[13] = oldMatrix[13]; newMatrix[14] = oldMatrix[14];

    node->SetTransform(newMatrix);
}


texts: Counting occurrences of a character in a string

texts:
Scenario "The Semantic Mind-Reader!" browser known as jhool is known
  as mind-reader for a reason. Here's why:

  You don't need to type 'www.' to open a website anymore. Though, you
  still need to type '.com' to open a website. The browser predicts ALL
  THE VOWELS in the name of the website. (Not '.com', though. Again!)
  Obviously, this means you can type the name of a website faster and
  save some time.

  Input format: The first line contains tc, the number of test cases. The second line contains the name of websites, as a string.

  Output format: You have to print the ratio of characters you would have typed in Jhool's browser, to your normal browser.

Constraints:
1 <= tc <= 100
1 <= Length of the website <= 200

  NOTE: You do NOT need to print the output in its lowest format. You
  should print in its original fraction format. The names of all the
  websites will be in small case only.

  Every string will start from www. and end with .com, so well!

  Sample Input

 2
www.google.com
www.hackerearth.com

  Sample Output

7/14
11/19

  Explanation
  Consider the first case: In Jhool's browser, you'll only have to type: ggl.com (7 characters) while in a normal browser, you'll have to
  type www.google.com, which is 14 characters.

Here is my solution:

import java.util.Scanner;
class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner keyboard=new Scanner(System.in);
        int t=keyboard.nextInt();
        keyboard.nextLine();
        while(t!=0){

            String s= keyboard.nextLine();

            int len=s.length();
            int count=0;
            for(int i=4;i<len-4;i++){
                if(s.substring(i,i+1).matches("[aeiouAEIOU]"))
                    count++;
            }
            System.out.println(len-count-4+"/"+len);
            t--;
        }
    }
}

But the above took around 2.4583 sec in total for against the 7 set of input.

input 1 input 2 input 3 input 4 input 5 input 6 input 7

Which I was able to further reduce to 1.9038 sec with this solution:

import java.util.ArrayList;
import java.util.Scanner;
class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner keyboard=new Scanner(System.in);
        int t=keyboard.nextInt();
        keyboard.nextLine();
        ArrayList<String> vowelList= new ArrayList<>();
        vowelList.add("a");
        vowelList.add("e");
        vowelList.add("i");
        vowelList.add("o");
        vowelList.add("u");
        while(t!=0){
            String s= keyboard.nextLine();
            int len=s.length();
            String sub=s.substring(4,len-4);
            String[] splitted=sub.split("\\B");
            ArrayList<String> splt= new ArrayList<>();
            for(String x:splitted){
                splt.add(x);
            }
            splt.removeAll(vowelList);

            int size=splt.size();
            System.out.println(size+4+"/"+len);
            t--;
        }
    }
}

Now if I'm using List<String> vowelList= new ArrayList<>(); and List<String> splt= new ArrayList<>(); instead of the above two ArrayList declaration above, I'm further able to reduce it to 1.8892 sec.

What are more possible ways of optimizing the above code which can reduce the running time? And why is their time difference using Implemented ArrayList call and through interface call of List? Or has it just happened without any reasons?


texts: Secure PHP login with SQL injection prevention

texts:
I am working on a project where users have to log in then if it is correct it creates a cookie to process requests. I would like to find a way to auto-renew sessions every day without affecting the user or requiring the user to log in again.

I would like to also know if I overlooked any security flaws such as SQL injection or session-hijacking and all those, are there any other one that I could prevent or improve?

The login page is

<?php
//Login.php
if(isset($_POST['username']) && isset($_POST['password'])){
    $username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_ENCODED, FILTER_FLAG_STRIP_HIGH); //Changes to unicode characters to prevent injection
    $password = $_POST['password']; //Get password

    $result = LoginManager::Login($username, $password); //Run login method

    if($result == "invalid_username"){
        echo 'Invalid Username!';
    }

    if($result == "invalid_login"){
        echo 'Invalid Login!';
    }

    $expires = gmdate('Y-m-d', strtotime($Date. ' + 1 days')); //sessions expire in 1 day
    DataBase::query("INSERT INTO sessions VALUES(:session, :userid, :expires)", array(':session' => $result, ':userid' => $userid, ':expires' => $expires)); //insert into database

    setcookie("session", $result); //set as cookie
    return;
}

echo '<form action="Login.php" method="post">

Username: <input type="text" name="username" placeholder="Username"/>

Password: <input type="password" name="password" placeholder="Password"/>

<input type="submit" name="login" value="Login"/>

    </form>';
?>

The LoginManager class

<?php
//LoginManager.php
public static function Login($username, $password){
    if(strlen($username) > 16 || strlen($password) > 50 || strlen($password) < 5){ //usernames less than 16, password from 5-50 char
        return 'invalid_bounds';
    }

    $sql = "SELECT * from accounts WHERE username = :username";
    $users = Database::query($sql, array(':username' => $username)); //get account

    if(sizeof($users) == 0){ //no accounts found
        return 'invalid_username';
    }

    $userdata = $users[0];

    $salt = '-45dfeHK/__yu349@-/klF21-1_\/4JkUP/4'; //salt for password
    if(password_verify($password . $salt, $userdata['password'])){ //check if password is correct
        $session = com_create_guid(); //create unique session
        return $session;
    }else{
        return 'invalid_login';
    }
}

?>

And the main page / feed

<?php
//Main.php
$session = $_COOKIE['session']; //get cookie session

$sessions = DataBase::query('SELECT * FROM sessions WHERE id=:id', array(':id' => $session));

if(sizeof($sessions) == 0){
    //Redirect to login page
    return;
}

//get first session
$session = $sessions[0];

$date = new DateTime($session['expires']);
$now = new DateTime();

if($date < $now) {
    //Expired session : Redirect to login
    return;
}

//Display feed

?>


texts:
I'm very much a beginner and have put together some JavaScript to control a pair of radio buttons which essentially behave as links.

I'm doing this as sort of a self-initiated project, or bit of fun. I know I don't have to use radio buttons, but it's something I just wanted to do.

It simply checks the radio button when you hover over it, and at the same time highlights the accompanying text. Or, highlights the text when hovered over, and also checks the accompanying radio button.

When the cursor moves out, no longer hovering over, the elements go back to their normal states.

I feel like there has to be a much cleaner way of implementing this.

Here is my mark up of the two radio buttons:

<form name=links>

        <input type="radio" name="fb" onMouseOut="out_event_01()" onMouseOver="over_event_01()" />

Button1

        <input type="radio" name="tw" onMouseOut="out_event_02()" onMouseOver="over_event_02()" />

Button2

</form>

As you can see I have a lot of onMouseOut and onMouseOver events.

This is the JavaScript I'm using:

function over_event_01()
{
var links = document.links.fb;
links.checked = true;
document.getElementById('fb_link').style.color = 'black';
}
function out_event_01()
{
var links = document.links.fb;
links.checked = false;
document.getElementById('fb_link').style.color = 'rgb(153,153,153)';
}
function over_event_02()
{
var links = document.links.tw;
links.checked = true;
document.getElementById('tw_link').style.color = 'black';
}
function out_event_02()
{
var links = document.links.tw;
links.checked = false;
document.getElementById('tw_link').style.color = 'rgb(153,153,153)';
}
function over_event_03()
{
var links = document.links.fb;
links.checked = true;
document.getElementById('fb_link').style.color = 'black';
}
function out_event_03()
{
var links = document.links.fb;
links.checked = false;
document.getElementById('fb_link').style.color = 'rgb(153,153,153)';
}
function over_event_04()
{
var links = document.links.tw;
links.checked = true;
document.getElementById('tw_link').style.color = 'black';
}
function out_event_04()
{
var links = document.links.tw;
links.checked = false;
document.getElementById('tw_link').style.color = 'rgb(153,153,153)';
}


texts: Thread-safety and delegates with generated numbers

texts:
In the main class, loops generate numbers (0~100), and when its generated number is > 20, its value is passed to the thread where it simulates some work with this number. Meanwhile, while this number is being processed, other generated numbers > 20 must be skipped.

Is this code OK? I am not sure if I'm doing something bad or not. In fact it seems to be working fine, but I don't know if it can be written by that way or even "better.".

class Program
{
    delegate void SetNumberDelegate(int number);
    delegate bool IsBusyDelegate();

    static void Main(string[] args)
    {
        Random rnd = new Random();
        ProcessingClass processClass = new ProcessingClass();
        SetNumberDelegate setNum = new SetNumberDelegate(processClass.setNumber);
        IsBusyDelegate isBusy = new IsBusyDelegate(processClass.isBusy);
        Thread processThread = new Thread(new ThreadStart(processClass.processNumbers));
        processThread.Start();
        int num;
        int count = 0;
        while (count++ < 100)
        {
            num = rnd.Next(0, 100);
            Console.WriteLine("Generated number {0}", num);
            if (num > 20)
            {
                if (!isBusy())
                {
                    setNum(num);
                }
                else
                {
                    Console.WriteLine("Thread BUSY! Skipping number:{0}", num);
                }
            }
            Thread.Sleep(1);
        }
        processThread.Abort();
        processThread.Join();
        Console.ReadKey();
    }
}
class ProcessingClass
{
    private volatile bool busy;
    private volatile int number;

    public ProcessingClass()
    {
        busy = false;
        number = -1;
    }

    public bool isBusy()
    {
        return busy;
    }

    public void setNumber(int num)
    {
        number = num;
    }

    public void processNumbers()
    {
        while (true)
        {
            if (number > -1 && !busy)
            {
                busy = true;
                Console.WriteLine("Processing number:{0}", number);
                // simulate some work with number e.g. computing and storing to db
                Thread.Sleep(500);
                Console.WriteLine("Done");
                number = -1;
                busy = false;
            }
        }
    }
}


texts: Change the JTextField font and text with radio buttons

texts:
So I learned from YouTube videos and online tutorials and they gave me a task to do a simple program. I need to pick 1 button from 4 buttons (radio buttons) and each time I pick a button he's changing a text in a text box.

The program is working great ! I'm just asking you guys to check if I did something that is considered wrong in programming or if there's a better way to do this task.

So that's my main program.

import javax.swing.JFrame;

public class Main {

    public static void main(String args[])
    {
        gui go = new gui();
        go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        go.setSize(317,220);
        go.setVisible(true);
    }

}

and that's the class i'm using (gui class)

package learning;

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class gui extends JFrame implements ActionListener  {

    private JTextField tf = new JTextField( 25);
    private JRadioButton regularRadio = new JRadioButton("Regular",true);
    private JRadioButton boldRadio = new JRadioButton("Bold",false);
    private JRadioButton italicRadio = new JRadioButton("Italic",false);
    private JRadioButton boldNitalicRadio = new JRadioButton("Bold And Italic",false);;
    private ButtonGroup group = new ButtonGroup();

    public  gui(){

        super("Changing text program");
        setLayout (new FlowLayout());

        add(tf);
        add (regularRadio);
        add (boldRadio );
        add (italicRadio);
        add (boldNitalicRadio);

        group.add(boldRadio);
        group.add(boldNitalicRadio);
        group.add(italicRadio);
        group.add(regularRadio);

        regularRadio.addActionListener(this);
        boldRadio.addActionListener(this);
        italicRadio.addActionListener(this);
        boldNitalicRadio.addActionListener(this);

    }

    public void actionPerformed(ActionEvent e){

        if (e.getActionCommand() == "Regular"){
       tf.setText("You picked regular radio button");
       tf.setFont(new Font ("David" , Font.PLAIN , 14));
        }
        else if (e.getActionCommand() == "Bold") {
            tf.setText("You picked bold radio button");
               tf.setFont(new Font ("David" , Font.BOLD , 14));
        }
        else if (e.getActionCommand() == "Italic") {
            tf.setText("You picked italic radio button");
               tf.setFont(new Font ("David" , Font.ITALIC , 14));
        }
        else{
            tf.setText("You picked Bold and Italic radio button");
               tf.setFont(new Font ("David" , Font.ITALIC + Font.BOLD , 14));
        }

    }
}


texts: Angular 2 window service that listens for 'click away'

texts:
This is the angular service I wrote window.service.ts.

import { Injectable } from '@angular/core';

import { Subject } from 'rxjs/subject';
import { Observable } from 'rxjs/observable';

declare let $: any;

@Injectable()
export class WindowService {

  private _subscriptions: Array<Subscription> = [];

  constructor() {
    $(window).bind('click', this._onWindowClick.bind(this));
  }

  ngOnDestroy() {
    $(window).unbind('click');
  }

  // Handle any click event on the document
  private _onWindowClick(event): void {
    let $target = $(event.target);
    // Check every subscription you to see if the $target element
    // that was clicked is contained inside the selector they subscribed with
    this._subscriptions.forEach((sub: Subscription) => {
      // IF you do find that selector continue - the click was inside this subscribers
      // element ELSE fire off the subject to let the subscriber know a click away from them occurred
      if ($target.closest(sub.selector).length == 0)
        sub.subject.next(event);
    });
  }

  // Sign up for clickAway event - called by components
  public clickAway(selector: string): Observable<Event> {
    let subject = new Subject();
    this._subscriptions.push(new Subscription(selector, subject));
    return subject.asObservable();
  }

}

class Subscription {
  constructor(
    public selector: string,
    public subject: Subject<Event>
  ) { }
}

The problem I was trying to solve with it was that I have custom components that open and close. Because of the strict component scope that Angular enforces I had no way to know if someone had clicked away from an open component.

Think of a native HTML select element. You click it to open it, then you click away from it and expect it to close. I needed that functionality.

So I created this service that takes a selector that should represent the most parent element of the component. When a click on the window occurs the service checks to see if the click occurred inside the element passed during subscription. If it was not on that element, it executes next() so the component can know that a click occurred away from itself and likely close itself.

Example use in a component:

ngOnInit() {
  this._windowService.clickAway('#customSelect')
    .subscribe(() => {
      console.log('clicked away');
      this.state = ViewState.Closed;
    });
}

I'm looking for a review on the code in specific to good Angular and javascript practices. I know using $ is considered a bad practice but I already have it in the project and it makes the check to see if the event occurred an easily understandable inside another element a one liner. Also, best practices on how Angular Services, Component, and Directives should interact and communicate is confusing to me so if there is changes that could make this better, looking for those.

Also of course if anyone sees any red flags, please point out.

To answer your first question: yes it works.


texts: Best approach for converting list of nested dictionaries to a single dictionary with aggregate functions

texts:
I've looked through a lot of solutions on this topic, but I have been unable to adapt my case to a performant one. Suppose I have a list of dictionaries stored as:

db_data = [
  {
    "start_time": "2020-04-20T17:55:54.000-00:00",
    "results": {
      "key_1": ["a","b","c","d"],
      "key_2": ["a","b","c","d"],
      "key_3": ["a","b","c","d"]
    }
  },
  {
    "start_time": "2020-04-20T18:32:27.000-00:00",
    "results": {
      "key_1": ["a","b","c","d"],
      "key_2": ["a","b","e","f"],
      "key_3": ["a","e","f","g"]
    }
  },
  {
    "start_time": "2020-04-21T17:55:54.000-00:00",
    "results": {
      "key_1": ["a","b","c"],
      "key_2": ["a"],
      "key_3": ["a","b","c","d"]
    }
  },
  {
    "start_time": "2020-04-21T18:32:27.000-00:00",
    "results": {
      "key_1": ["a","b","c"],
      "key_2": ["b"],
      "key_3": ["a"]
    }
  }
]

I am trying to get a data aggregation from the list output as a dictionary, with the key values of the results object as the keys of the output, and the size of the set of unique values for each date for each key.

I am attempting to aggregate the data by date value, and outputting the count of unique values for each key for each day.

Expected output is something like:

{
  "key_1": {
    "2020-04-20": 4,
    "2020-04-21": 3
  },
  "key_2": {
    "2020-04-20": 6,
    "2020-04-21": 2
  },
  "key_3": {
    "2020-04-20": 7,
    "2020-04-21": 4
  }
}

What I have tried so far is using defaultdict and loops to aggregate the data. This takes a very long time unfortunately:

from datetime import datetime
from collections import defaultdict

grouped_data = defaultdict(dict)

for item in db_data:
  group = item['start_time'].strftime('%-b %-d, %Y')
  for k, v in item['results'].items():
    if group not in grouped_data[k].keys():
      grouped_data[k][group] = []
    grouped_data[k][group] = v + grouped_data[k][group]
for k, v in grouped_data.items():
  grouped_data[k] = {x:len(set(y)) for x, y in v.items()}

print(grouped_data)

Any help or guidance is appreciated. I have read that pandas might help here, but I am not quite sure how to adapt this use case.


texts:
Below is the problem taken from here.

  Question 10: GCD*

  The greatest common divisor of two positive integers a and b is the largest integer which evenly divides both numbers (with no remainder). Euclid, a Greek mathematician in 300 B.C., realized that the greatest common divisor of a and b is one of the following:

  the smaller value if it evenly divides the larger value, OR
  the greatest common divisor of the smaller value and the remainder of the larger value divided by the smaller value
  In other words, if a is greater than b and a is not divisible by b, then

  gcd(a, b) == gcd(b, a % b)

  Write the gcd function recursively using Euclid's algorithm.

def gcd(a, b):
    """Returns the greatest common divisor of a and b.
    Should be implemented using recursion.

    >>> gcd(34, 19)
    1
    >>> gcd(39, 91)
    13
    >>> gcd(20, 30)
    10
    >>> gcd(40, 40)
    40
    """
    "*** YOUR CODE HERE ***"

Solution:

def gcd(a, b):
    """Returns the greatest common divisor of a and b.
    Should be implemented using recursion.

    >>> gcd(34, 19)
    1
    >>> gcd(39, 91)
    13
    >>> gcd(20, 30)
    10
    >>> gcd(40, 40)
    40
    """
    if b > a:
        if b % a == 0:
            return a
        else:
            return gcd(b % a, a)
    else:
        if a % b == 0:
            return b
        else:
            return gcd(b, a % b)

How can I improve this nested if block?


texts: Hash table in Java with arrays and linear probing

texts:
I did some manual tests by instantiating the class and it seems to be working okay. I wanted some feedback on the following:

Is the code well structured? I notice I have a lot of redundancy. The search and delete methods are almost the same.
I use a string to flag deleted keys until they are replaced, is there a better way to do this. Another boolean array maybe?

public class HashTable {
    //known limitation: This will break if the key value is set to none because I use none as the identifier string for deleted keys.
        private int capacity;
        String values[];
        String keys[];
        public HashTable(int capacity){
            this.capacity = capacity;
            values = new String[this.capacity];
            keys = new String[this.capacity];
        }

        public int hash(String key){
            int sum = 0;
            for (int i=0; i<key.length();i++){
                sum+=key.charAt(i);
            }
            return sum%capacity;
        }

        public void add(String key, String value){
            int keyhash;
            int i = 0;
            while(i!=capacity-1){
                keyhash = (hash(key)+i)%capacity;
                System.out.println("Try "+ i);
                if(values[keyhash]==null || values[keyhash].equals("none")) { //add delete flag to this condition after implementing delete.
                    values[keyhash] = value;
                    keys[keyhash] = key;
                    break;
                }

                if(values[keyhash]!=null && keys[keyhash].equals(key)){
                    values[keyhash]=value;
                    break;
                }
                i++;
            }
        if(i==capacity-1)
            System.out.println("Table appears to be full,unable to insert value");
        else
            System.out.println("Value inserted successfully.");
        }

        public String get(String key){
            int i = 0;
            int keyhash = (hash(key)+i)%capacity;
            while(values[keyhash]!=null && i<capacity){
                //System.out.println("Try " +i + " of finding the key.");
                if(keys[keyhash].equals(key))
                    return values[keyhash];
                i++;
                keyhash = (hash(key)+i)%capacity;
            }
        return null;
        }

        public void remove(String key){
            int i = 0;
            int keyhash = (hash(key)+i)%capacity;
            while(keys[keyhash]!=null && i<capacity) {
                if (keys[keyhash].equals(key)) {
                    keys[keyhash] = "none";
                    values[keyhash] = "none";
                    return;
                }
                i++;
                keyhash = (hash(key)+i)%capacity;
            }
            System.out.println("Key does not exist in table");
        }

        public void getHashedValues(){
            System.out.println();
            for(int i = 0; i<values.length;i++){
                System.out.print(" "+ values[i]);
            }
            System.out.println();
        }

    }


texts: Creating Quantile Cutoffs using SQL Hive

texts:
I have a table in Hadoop that looks like this (with up to hundreds of columns and millions of rows):

+--------+-----------+--------+-----+
| field0 |  field1   | field2 | ... |
+--------+-----------+--------+-----+
| 0.66   | 0.4364153 | 0.31   |     |
| 0.28   | 0.281724  | -1     |     |
| 0.48   | 0.4210872 | 0.58   |     |
| 0.44   | 0.4381265 | 0.59   |     |
| 0.5    | 0.3220857 | 0.65   |     |
| 0.42   | 0.287387  | -1     |     |
| 0.49   | 0.2775216 | -1     |     |
| 0.63   | 0.4347056 | 0.54   |     |
| 0.43   | 0.4501439 | 0.54   |     |
| 0.39   | 0.4312909 | 0.66   |     |
| 0.41   | 0.4432687 | 0.56   |     |
| 0.71   | 0.2678676 | -1     |     |
| 0.43   | 0.270604  | -1     |     |
| 0.51   | 0.2888133 | -1     |     |
| 0.6    | 0.270604  | -1     |     |
| 0.68   | 0.4177005 | 0.67   |     |
| ...    | ...       | ...    | ... |
+--------+-----------+--------+-----+

The values inside the fields are always between 0 and 1 (inclusive), -1, or blank (empty string). I want to find the minimum and maximum cutoff points when quantiling the data (with each column quantiled independently). (You can read up on quantiling here https://en.wikipedia.org/wiki/Quantile)

I have a script which generates Hive SQL code like the following (using n=9 as an example). Is there any way to optimize this SQL code so that it does not require so many joins? Each join requires a separate Hadoop MapReduce job (and due to environmental issues, we cannot enable the parallelizable feature which enables multiple SQL jobs to run at once).

select
outer0.nonile_field0 as nonile,
outer0.min_field0,
outer0.max_field0,

outer1.min_field1,
outer1.max_field1,

outer2.min_field2,
outer2.max_field2,

...

from
(
    select middle0.nonile_field0,
    min(middle0.field0) as min_field0,
    max(middle0.field0) as max_field0
    from
    (
        select inner0.field0,
        ntile(9) over (order by inner0.field0) as nonile_field0
        from
        (
            select repo.field0
            from my_table as repo
            where repo.field0 >= 0 and repo.field != ""
        ) as inner0
    ) as middle0
    group by middle0.nonile_field0
) as outer0

inner join
(
    select middle1.nonile_field1,
    min(middle1.field1) as min_field1,
    max(middle1.field1) as max_field1
    from
    (
        select inner1.field1,
        ntile(9) over (order by inner1.field1) as nonile_field1
        from
        (
            select repo.field1
            from my_table as repo
            where repo.field1 >= 0 and repo.field1 != ""
        ) as inner1
    ) as middle1
    group by middle1.nonile_field1
) as outer1
on outer0.nonile_field0 = outer1.nonile_field1

...

order by nonile

The output of the query will look like this (for example):

+--------+--------------+--------------+--------------+--------------+
| nonile | min_field0   | max_field0   | min_field1   | max_field1   |
+--------+--------------+--------------+--------------+--------------+
|      1 | 0            | 0.27         | 0.09892169   | 0.2505006    |
|      2 | 0.27         | 0.33         | 0.2505006    | 0.2900893    |
|      3 | 0.33         | 0.37         | 0.2900893    | 0.3300329    |
|      4 | 0.37         | 0.41         | 0.3300329    | 0.3687165    |
|      5 | 0.41         | 0.46         | 0.3687165    | 0.4048001    |
|      6 | 0.46         | 0.5          | 0.4048001    | 0.4399964    |
|      7 | 0.5          | 0.55         | 0.4399964    | 0.4828034    |
|      8 | 0.55         | 0.62         | 0.4828034    | 0.5445772    |
|      9 | 0.62         | 0.98         | 0.5445772    | 0.7808363    |
+--------+--------------+--------------+--------------+--------------+

Note that I've manually edited the field and table names so that they are generic for this post, but the code should still be correct.


texts: Slow Converting from JsonArray to ArrayList

texts:
I have to convert a JsonArray to an ArrayList but unfortunately the code below is used very often during the execution of the program! How can I speed it up?

Java:

public static ArrayList CastJsonObject(JSONArray object) {
        ArrayList<Cantiere> tm = new ArrayList<Cantiere>();
        Cantiere cant;
        Cliente c;
        try {
            for (int i = 0; i < object.length(); i++) {
                JSONObject value = object.getJSONObject(i);
                int IdCantiere = Integer.parseInt(value.getString("IdCantiere").toString());
                int IdCliente = Integer.parseInt(value.getString("IdCliente").toString());
                String Filiale = value.getString("Filiale").toString();
                String RagioneSociale = value.getString("RagioneSociale").toString();
                String NomeCantiere = value.getString("NomeCantiere").toString();
                String DataCreazioneCantiere = value.getString("DataCreazioneCantiere").toString();
                String Tipologia = value.getString("Tipologia").toString();
                String StatoCantiere = value.getString("StatoCantiere").toString();
                int StatoFatturazione = Integer.parseInt(value.getString("StatoFatturazione").toString());
                c = new Cliente(IdCliente, RagioneSociale, Filiale);
                cant = new Cantiere(c, IdCantiere, NomeCantiere, DataCreazioneCantiere, Tipologia, StatoCantiere, StatoFatturazione);
                tm.add(cant);
            }
        } catch (Exception ex) {
            System.out.println("\n Error: " + ex);
        }

        return tm;
    }


texts:
I need to map from one enum type to another.  Here is the enum I am
given:

enum CfgFruitType { CFGNoFruit, CFGApple, CFGApricot, CFGBanana,
   CFGMango, CFGKiwi, CFGFig, CFGGrape, CFGMelon, CFGLemon,
   CFGNectarine, CFGPineapple, CFGWatermelon, CFGCherry, CFGPear,
   CFGStrawberry };

and I need to map this to a second enum:

enum FAddressType { AddressTypeUnknown, AddressTypeCherry,
  AddressTypeApple, AddressTypePear, AddressTypePlum,
  AddressTypeStrawberry };

Here is my implementation:

FAddressType maptype(CfgFruitType cfgtype) {
   int mapper[16][2] =
   {
      { CFGNoFruit,          AddressTypeUnknown },
      { CFGApple,            AddressTypeApple },
      { CFGApricot,          AddressTypeUnknown },
      { CFGBanana,           AddressTypeUnknown },
      { CFGMango,            AddressTypeUnknown },
      { CFGKiwi,             AddressTypeUnknown },
      { CFGFig,              AddressTypeUnknown },
      { CFGGrape,            AddressTypeUnknown },
      { CFGMelon,            AddressTypeUnknown },
      { CFGLemon,            AddressTypeUnknown },
      { CFGNectarine,        AddressTypeUnknown },
      { CFGPineapple,        AddressTypeUnknown },
      { CFGWatermelon,       AddressTypeUnknown },
      { CFGCherry,           AddressTypeCherry },
      { CFGPear,             AddressTypePear },
      { CFGStrawberry,       AddressTypeStrawberry }
     };

   return cfgtype < 16 ? (FAddressType)mapper[cfgtype][1] : AddressTypeUnknown;
}

Is this the best approach?  How can it be improved?


texts: jQuery plugin to toggle a fullscreen menu open/closed

texts:
I wrote my very first jQuery plugin: open/close a fullscreen menu, using a toggle. I know a very little about object in JavaScript; I'm a PHP OOprogrammer.

How to transform this plugin using OO programming? I mean, is a good idea to inject dependecies (body and the toggle itself) into a JavaScript object?

(function($, document) {
  var $body = $(document.body),
    originalBodyOverflow = $body.css('overflow'),
    $toggles = [];

  $.fn.menuToggle = function(options) {
    var settings = $.extend({}, $.fn.menuToggle.defaults, options);

    return this.each(function() {
      var $this = $(this),
        $menu = $($this.attr('data-target'));

      $toggles.push($this);
      $this.on('click', function(e) {
        if (e) {
          e.preventDefault();
        }

        $.each($toggles, function (i, $toggle) {
          $toggle.toggleClass(settings.toggleActiveClass);
        });

        $body.toggleClass(settings.bodyActiveClass);
        $body.css('overflow', $body.hasClass(settings.bodyActiveClass)
          ? 'hidden'
          : originalBodyOverflow
        );

        if ($menu.length) {
          $menu.toggleClass(settings.menuActiveClass);
        }
      });
    });
  };

  $.fn.menuToggle.defaults = {
    bodyActiveClass: 'menu-open',
    menuActiveClass: 'open',
    toggleActiveClass: 'is-active'
  };
}(window.jQuery, document));


texts: What's the best way to make props reusable across many components in Vue.js 3?

texts:
In option API (Vue 2 syntax which is still available in version 3) we could extract some repeated pieces inside many components and define them as mixin that could be reusable like :
const colorable = {

    props: {
        bgColor: {
            type: String,
            default: "",
        },
        color: {
            type: String,
            default: "",
        },
    },
 computed:{
      colorClasses(){
       return `text--${this.color} bg--${this.bgColor}`
    }
  }
}

then we use that mixin in any component like :
mixins:[colorable]

In vue 3 they introduced the new composition api that enforces the code reusability and organization, so if we want to convert the code above to be compatible with this API we could do something like :
const colorable = {

    props: {
      // the same props as above
    },
}

and composable function :
const useColor=(props)=>{

   return {
     classes: computed(()=>`text--${props.color} bg--${props.bgColor}`)
 }
}

then in some component :
mixins:[colorable],
setup(props){

   const {classes}=useColor(props);

   return {classes}
}
}

This works fine I look for a better solution to get rid of the mixins option.


texts: JavaScript function that toggles element visibility according checked radio input

texts:
This function has a set of radio inputs, for each radio there is a hidden text input. When a radio input is checked it shows its chained text input.

I've done it with a function constructor, and I could have done this with closures or with simpler invocation patterns. My idea is to have some robust function which I could extend.

I haven't tested browser compatibility, which is somehow important for my market (IE8 lovers).

jsFiddle

<form>
<input type="radio" name="color" value="yellow" checked />Yellow
<input type="radio" name="color" value="brown" />Brown
<input type="radio" name="color" value="orange" />Orange
<input type="radio" name="color" value="purple" />Purple

<input type="text" id="value-yellow" class="radio-condition" placeholder="Which yellow?" />
<input type="text" id="value-brown" class="radio-condition" placeholder="Which brown?" />
<input type="text" id="value-orange" class="radio-condition" placeholder="Which Orange?" />
<input type="text" id="value-purple" class="radio-condition" placeholder="Which Purple?" />

</form>

// INSTRUCTIONS
// There is a hidden text input for each radio input.
// Checked radio will show its chained text input.
// They're chained by the radio value and the text id
// the radio value makes a string that is used as the id of the text

// Constructor Function
var JavaScript_form = function() {
  this.radios = document.querySelectorAll('input[type="radio"]');
}

// Public method of instance
JavaScript_form.prototype.radio_hide_element = function() {

  // inputs that will be hidden
  var els_hidden = document.getElementsByClassName('radio-condition'),
      els_hidden_length = els_hidden.length;

  // loop each radio input
  [].forEach.call(this.radios, function (el) {
      var i = 0;
      for (; i < els_hidden_length; i++) {
        els_hidden[i].style.display = 'none';
      }
      els_hidden[0].style.display = 'block';

      // click radio will toggle visibility of text input
      el.addEventListener('click', function() {
        var i = 0;
        for (; i < els_hidden_length; i++) {
          els_hidden[i].style.display = 'none';
          els_hidden[i].value = '';
        }
        document.getElementById('value-' + this.value).style.display = 'block';
      });
  });
}

// Make instance
var JS_radios = new JavaScript_form();
JS_radios.radio_hide_element();


texts:
I've written a heapsort implementation. It's generic: generic comparators and sequences with elements of a generic type.

The implementation (follows closely chapter 6 from Introduction to Algorithms 3rd Edition and) consists of

heapify: establishes the heap property for an element:

template<typename BiDirIterator, typename Cmp>
void heapify(BiDirIterator begin, BiDirIterator end,
typename std::iterator_traits<BiDirIterator>::difference_type i, Cmp cmp)
{
    const auto dist = std::distance(begin, end);

    while (true) {
        auto left = 2 * i + 1;
        auto right = left + 1;
        typename std::iterator_traits<BiDirIterator>::value_type largest;

        if (left < dist && cmp(begin[left], begin[i]))
            largest = left;
        else
            largest = i;
        if (right < dist && cmp(begin[right], begin[largest]))
            largest = right;

        if (largest == i)
            break;

        std::swap(begin[i], begin[largest]);
        i = largest;
    }
}

buildHeap: creates a heap from a permutation:

template<typename BiDirIterator, typename Cmp>
void buildHeap(BiDirIterator begin, BiDirIterator end, Cmp cmp)
{
    for (auto i = std::distance(begin, end) / 2 - 1; i >= 1; --i)
        heapify(begin, end, i, cmp);
    heapify(begin, end, 0, cmp);
}

sort: applies Heapsort to retrieve an ordered sequence from the permutation:

template<typename BiDirIterator, typename Cmp>
void sort(BiDirIterator begin, BiDirIterator end, Cmp cmp)
{
    buildHeap(begin, end, cmp);
    for (auto i = std::distance(begin, end) - 1; i > 0; --i) {
        std::swap(*begin, begin[i]);
        heapify(begin, std::next(begin, i - 1), 0, cmp);
    }
}

Necessary includes are:

#include <algorithm>
#include <iterator>
#include <functional>

In action:

#include <iostream>
#include <array>

int main()
{
    std::array<int, 10> perm { 5, 6, 9, 3, 6, 4, 8, 4, 87, 4 };

    heap::sort(perm.begin(), perm.end(), heap::max<int>{});
}

where the heap utilities are put into a separate heap namespace and heap::max is simply

template<typename T> using max = std::greater<T>;

Some questions:

Is it OK to use Cmp as a template parameter? That makes it more generic, but the error messages are way more complicated and point to stuff deep down in the implementation. (Granted, you can't say my implementation is anywhere close to "deep," but this is more of a general question.) Passing a Cmp, where Cmp is some alias for a type, would also be possible but not as generic. std::sort also uses the template parameter, though, so I do so as well.
Is my use of iterators alright? I tried to keep the interface clean with iterators for interaction with standard containers, but the implementation also uses numerical indices when it's more convenient.
heapify is ugly: there's an infinite loop with a break condition and it basically finds the largest element out of three while checking that they are within range (i.e., < dist). I have a feeling this can be beautified both syntactically and semantically. Some hint on that would be appreciated.
The implementation is supposed to work with bidirectional iterators. std::list doesn't work because subscripting is not supported, it's not efficient for std::list, etc. Should I replace subscripting with std::next to make it work on std::list at the cost of performance guarantees? std::list would work, but it might be frickin' slow asymptotically.


texts: Filtering out neighboring ascending digits in quaternary numeral system

texts:
Take in a natural number n ∈ N, then process and output a(n), with a(n) being the number of quaternary strings (with 0, 1, 2, 3) of length n, where (from left to right) there never follows a character (i + 1) directly after the character i.

  For example, n=3 results in a(3) = 42: 000, 002, 003, 020, 021, 022, 030, 031, 032,
  033, 100, 102, 103, 110, 111, 113, 130, 131, 132, 133, 200, 202, 203,
  210, 211, 213, 220, 221, 222, 300, 302, 303, 310, 311, 313, 320, 321,
  322, 330, 331, 332, 333.

How can performance be improved? n = 13 already takes 4 seconds.

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;

public class Quaternary {

    public static void start(){
        Scanner reader = new Scanner(System.in).useLocale(Locale.US);
        System.out.print("Enter number n: ");
        int n = Integer.parseInt(reader.nextLine());
        List<String> stringList = new ArrayList<String>();

        long startTime = System.nanoTime();

        for (int k=0; k < 4; k++){
        findString(n, k, "", stringList);
        }

        System.out.println(“Number of strings with n = " + n +  " : "+ stringList.size());

        long estimatedTime = System.nanoTime() - startTime;
        double time = (double)estimatedTime / 1000000000.0;
        System.out.println(time);
    }

    public static void findString(int n, Integer lastNumber, String string, List<String> stringList)
    {
        string += lastNumber.toString();

        if (string.length() == n)
        {
            stringList.add(string);
        }
        else {
            for (int i = 0; i < 4; i++)
            {
                if (i != lastNumber+1)
                {
                    findString(n, i, string, stringList);
                }
            }
        }
    }

    public static void main(String[] args) {
        start();
    }
}


texts:
I'm learning to program with PHP, so I ask your help to check if my class user.php is ok.

include('password.php');
class User extends Password{

    private $_db;

    function __construct($db){
        parent::__construct();

        $this->_db = $db;
    }

  private function get_user_hash($username){
    try {
      $stmt = $this->_db->prepare('SELECT password FROM members WHERE username = :username AND active="Yes" ');
      $stmt->execute(array('username' => $username));
      $row = $stmt->fetch();
      return $row['password'];
      } catch(PDOException $e) {
      echo '
'.$e->getMessage().'
';
    }
  }

  public function login($username, $password){
    $hashed = $this->get_user_hash($username);
    if($this->password_verify($password,$hashed) == 1){
       $_SESSION['loggedin'] = true;
      return true;
      }
    }

  public function logout(){
    session_destroy();
    }

  public function is_logged_in(){
    if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
      return true;
      }
    }

  public function is_logged_admin(){
    if(isset($_SESSION['level']) && $_SESSION['level'] == 2 ) {
      return true;
      }
    return false;
    }

  public function get_user_info($username){
    try {
      $stmt = $this->_db->prepare('SELECT * FROM members WHERE username = ?');
      $stmt->execute(array($username));
      return $stmt->fetch();
    } catch(PDOException $e) {
      echo '
'.$e->getMessage().'
';
      }
  }

  public function members_count(){
    try {
      $stmt = $this->_db->prepare('SELECT * FROM members ORDER BY memberID');
      $stmt->execute();
      $count = $stmt->rowCount();
      print("$count");
      } catch(PDOException $e) {
      echo '
'.$e->getMessage().'
';
      }
    }

  public function delete_user($id){
    try {
      $stmt = $this->_db->prepare('DELETE FROM members WHERE memberID = :id');
      $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
      $stmt->execute();
      } catch(PDOException $e) {
      echo '
'.$e->getMessage().'
';
      }
    }

  public function update_account($username){
    try {
      $stmt = $this->_db->prepare('UPDATE members SET location = ?, bio = ?, relationship = ?, interested = ?, work = ? WHERE username = ?');
      $stmt->execute([$_POST['location'], $_POST['bio'], $_POST['relationship'], $_POST['interested'], $_POST['work'], $username]);
    } catch(PDOException $e) {
      echo '
'.$e->getMessage().'
';
      }
  }

//close
}


texts: Pull out max from each column in a DataFrame in turns

texts:
I have a DataFrame like this:

n=5
df_test = pd.DataFrame(index=range(n),data={'A': np.random.randn(n),
                                            'B': np.random.randn(n),
                                            'C': np.random.randn(n)})
cols = ['A','B','C']

It will looks something like this:

            A          B            C
0   -1.218522    0.458914   -1.299367
1    1.872055    0.202141   -0.441987
2    1.104548    1.513785   -2.106882
3   -0.511132   -0.888288   -0.740854
4    1.628356    0.191733    0.394444

I want to cycle through the columns and each time extract the maximum value until there are no rows left.

I have written the following code which works fine:

vals = np.zeros(n)
cols = []
idx = []
for row_idx in range(n):
    col_idx = row_idx%3
    selected_col = cols[col_idx]
    selected_idx = df_test.drop(idx)[selected_col].idxmax()
    idx.append(selected_idx)
    cols.append(selected_agent)
    vals[row_idx] = df_test.loc[selected_idx, selected_col]

print(idx)
print(cols)
print(vals)

Correctly returning:

[1, 2, 4, 3, 0]
['A', 'B', 'C', 'A', 'B']
[ 1.87205485  1.51378518  0.39444431 -0.5111323   0.45891356]

I can't help thinking that there is a neater way to do this. Especially growing those lists in the loop.


texts:
I am taking an online training course on Python, and am at the following question:

  Write a function called median that takes a list as an input and
  returns the median value of the list.
  For example: median([1,1,2]) should return 1.
  The list can be of any size and the numbers are not guaranteed to be
  in any particular order. If the list contains an even number of
  elements, your function should return the average of the middle two.

My code seems correct and passes the tests:

def median(thelist):
    median = 0
    sortedlist = sorted(thelist)
    lengthofthelist = len(sortedlist)
    centerofthelist = lengthofthelist / 2
    if len(sortedlist) == 1:
        for value in sortedlist:
            median += value
        return median

    elif len(sortedlist) % 2 == 0:
        temp = 0.0
        medianparties = []
        medianparties = sortedlist[centerofthelist -1 : centerofthelist +1 ]
        for value in medianparties:
            temp += value
            median = temp / 2
        return median

    else:
        medianpart = []
        medianpart = [sortedlist[centerofthelist]]
        for value in medianpart:
            median = value
        return median

I am (pretty) sure that, despite passing the tests, the code is neither nice, efficient, nor Pythonic. I am wondering if the community may highlight what I did wrong and how I can improve it.


texts:
This is the cipher used in this puzzling post, if you would like to crack it before looking at the programs use to make it.

Several weeks ago, I created a custom cipher for a friend of mine to crack, and I also posted it on Puzzling. Here are the programs I used to create it - I threw them together one morning, and I didn't comment them. I decided to leave them as is - they are self-explanatory to some degree, and I would also like to have my rush-job instinct in variable naming and what not critiqued. I know it's not good per say, but since it was a personal project I didn't care. How the cipher works is explained the in answer to the puzzling question, if my code doesn't show you well enough.

I have an encoder and a decoder. They currently assume that plaintext.txt, code.txt, and decoded.txt are in the current directory. The decoder assumes that the code is formatted as the encoder would format it.

encoder.py

import random
import string

text = open("plaintext.txt").read()

#chars = "abcdefghijklmnopqrstuvwxyz*.,?!()- \n"
chars = "(stephn)a*dowjzr.b\nm,uvklc ?qig!fyx-"

def base_10_to_base_6(n):
    s = ""
    while n:
        s = str(n % 6) + s
        n //= 6

    if len(s) == 1:
        s = "0" + s

    if not s:
        return "00"

    return s

def base_10_to_base_26(n):
    s = ""
    while n:
        s = string.ascii_lowercase[n % 26] + s
        n //= 26

    if len(s) == 1:
        s = "a" + s

    if not s:
        return "aa"

    return s

print(text)

result = ""

for letter in text:
    letter = letter.lower()

    if letter not in chars:
        letter = "*"

    coded_char = base_10_to_base_6(chars.index(letter.lower()))

    print(letter + ": " + coded_char + " : " + chars[int(coded_char, 6)])

    result += coded_char

len_diff = len(result) % 3

if len_diff != 0:
    result += (3 - len_diff) * str(random.randint(0, 5))

print(str(len(result)) + " " + result)

sets_of_3 = []

index = 3

while index <= len(result):
    sets_of_3.append(result[index - 3:index])
    index += 3

print(sets_of_3)

sets_of_letters = []

for set_of_3 in sets_of_3:
    sets_of_letters.append(base_10_to_base_26(int(set_of_3)))

print(sets_of_letters)

with open("code.txt", "w") as text_file:
    print(" ".join(sets_of_letters), file=text_file, end="")

decoder.py

import random
import string

text = open("code.txt").read()

#chars = "abcdefghijklmnopqrstuvwxyz*.,?!()- \n"
chars = "(stephn)a*dowjzr.b\nm,uvklc ?qig!fyx-"

def base_10_to_base_6(n):
    s = ""
    while n:
        s = str(n % 6) + s
        n //= 6

    if len(s) == 1:
        s = "0" + s

    if not s:
        return "00"

    return s

def base_10_to_base_26(n):
    s = ""
    while n:
        s = string.ascii_lowercase[n % 26] + s
        n //= 26

    if len(s) == 1:
        s = "a" + s

    if not s:
        return "aa"

    return s

def base_26_to_base_10(n):
    result = string.ascii_lowercase.index(n[0]) * 26 + string.ascii_lowercase.index(n[1])

    result = str(result)

    if len(result) == 2:
        result = "0" + result
    elif len(result) == 1:
        result = "00" + result
    elif not result:
        result = "000"

    return result

def base_6_to_base_10(n):
    return int(n[0]) * 6 + int(n[1])

sets_of_chars = text.split(" ")

print(sets_of_chars)

triplets = []

for each in sets_of_chars:
    triplets.append(base_26_to_base_10(each))

code = "".join(triplets)

print(code)

index = 2

output = ""

while index <= len(code):
    output += chars[base_6_to_base_10(code[index - 2:index])]
    index += 2

with open("decoded.txt", "w") as text_file:
    print(output, file=text_file, end="")


texts:
I use the code below for filtering a treeview. Can this be improved?

private IEnumerable<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)
 {

    foreach (TreeNode node in nodes)
    {
        if (node.Value.IndexOf(searchstring,
              StringComparison.CurrentCultureIgnoreCase) >= 0)
            yield return node;
        else
        {
            foreach (var subNode in FindNodeByValue(node.ChildNodes, searchstring))
                yield return subNode;
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{

    var query= FindNodeByValue(TreeView1.Nodes, fieldFilterTxtBx.Text);
    if (query != null)
    {
        //TreeView1.Nodes[0].Expand();
        //TreeView1.Nodes.Clear();
        foreach (TreeNode node in query.ToList())
        {
            TreeView1.Nodes.Add(node);

        }

        //  TreeNode newnode = new TreeNode("Detail Engineering");
        // TreeView1.Nodes.Add(newnode);

        TreeView1.ExpandAll();
    }

    else
    {

        Label1.Text = "No file found";

    }
}


texts: java Thread-safe LRUCache implementation

texts:
What is best way to implement thread-safe LRUCache in java?
Please review this one.
Is there any better approach which can be taken here?

package cache;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class  LRUCache<K,V> {

    private  ConcurrentLinkedQueue<K> concurrentLinkedQueue = new ConcurrentLinkedQueue<K>();

    private  ConcurrentHashMap<K,V> concurrentHashMap = new ConcurrentHashMap<K, V>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private Lock readLock = readWriteLock.readLock();

    private Lock writeLock = readWriteLock.writeLock();

    int maxSize=0;

    public LRUCache(final int MAX_SIZE){
        this.maxSize=MAX_SIZE;
    }

    public V getElement(K key){

        readLock.lock();
        try {
        V v=null;
          if(concurrentHashMap.contains(key)){
              concurrentLinkedQueue.remove(key);
              v= concurrentHashMap.get(key);
                concurrentLinkedQueue.add(key);
          }

        return v;
        }finally{
            readLock.unlock();
        }
    }

    public V removeElement(K key){
         writeLock.lock();
         try {
        V v=null;
        if(concurrentHashMap.contains(key)){
        v=concurrentHashMap.remove(key);
            concurrentLinkedQueue.remove(key);
        }

        return v;
         } finally {
             writeLock.unlock();
         }
    }

    public V addElement(K key,V value){
        writeLock.lock();
        try {
        if(concurrentHashMap.contains(key)){
             concurrentLinkedQueue.remove(key);
        }
        while(concurrentLinkedQueue.size() >=maxSize){
             K queueKey=concurrentLinkedQueue.poll();
             concurrentHashMap.remove(queueKey);
        }
        concurrentLinkedQueue.add(key);
        concurrentHashMap.put(key, value);

        return value;
        } finally{
            writeLock.unlock();
        }
    }
}


texts: A shell script to mount a disk image file

texts:
I'm trying to create a bash shell script which mounts a disk image file. Not only that but checks to see if the disk image already exists. Is there anyway I could improve my script? Currently my script looks like this:

#!/bin/bash

MOUNTPOINT="/myfilesystem"

if [ ! -d "${MOUNTPOINT}" ]; then
    if [ -e "${MOUNTPOINT}" ]; then
        echo "Mountpoint exists, but isn't a directory..."
        exit 1
    else
        sudo mkdir -p "${MOUNTPOINT}"
    fi
fi

if [ "$(echo ${MOUNTPOINT}/*)" != "${MOUNTPOINT}/*" ]; then
    echo "Mountpoint is not empty!"
    exit 1
fi

if mountpoint -q "${MOUNTPOINT}"; then
    echo "Already mounted..."
    exit 0
fi


texts: How to append values into existed Vec with iterator

texts:
I have a Vec with value default [0], and then I want to append into the vec with an iterator which is read from stdin, now my code is not performant since I use an insert to shift all the values behind index 0, how to improve this code with rusty style?
#[allow(unused_imports)]
use std::cmp::{max, min};
use std::io::{stdin, stdout, BufWriter, Write};

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>,
}
impl Scanner {
    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let mut scan = Scanner::default();

    let n: usize = scan.next();
    // How to improve these lines?
    let mut arr = (0..n).map(|i| scan.next()).collect();
    arr.insert(0, 0);
}

Playground link


texts:
I'm fairly new to C, and this is my first time using pthread. I am pretty sure I implemented it correctly, however I'd like to verify it is indeed executing the tasks parallel instead of sequentially. Here is my main.c code:

main.c

#include "frequency.h"

/**
 * The main function. Runs {@code getMedianWord()} in parallel threads for each file,
 * then outputs the sorted elements in FileArray file_array.
 */
int main(int argc, char **argv) {
    int actual_args = argc - 1;
    pthread_t tid[argc];

    for (int i = 0; i < actual_args; ++i)
        pthread_create(&tid[i], NULL, getMedianWord, (void *) &argv[i + 1]);

    for (int j = 0; j < actual_args; ++j)
        pthread_join(tid[j], NULL);

    qsort(file_array,
          (size_t) actual_args,
          sizeof(FileArray),
          (int (*)(const void *, const void *)) file_cmp
    );

    for (int k = 0; k < actual_args; ++k)
        printf("\n%s %d %s",
               file_array[k].filename,
               file_array[k].num,
               file_array[k].median_word
        );

    pthread_exit(NULL);
}

frequency.c

...
void *getMedianWord(void *vargp) {
    char *filename = *(char **) vargp;
    WordArray word_array[MAX_WORDS];

    FILE *fp = fopen(filename, "r");
    char word[101];

    int n = 0;
    while (!feof(fp)) {
        fscanf(fp, "%s", word);
        insert_word(word_array, &n, word);
    }

    insert_arr(file_array, filename, n, word_array);

    pthread_exit(NULL);
}

The intended code to be executed in parallel is the function getMedianWord, which adds a result to a global array of structs (file_array), and terminates via pthread_exit(NULL).

Please let me know if this is actually using threads properly, thanks!

PS. If you're interested in seeing the rest of my code, here it is.


texts:
As a sequel from my previous question, I decided to solve the next problem statement from the GCJ dash board.  Any thorough critique, this time, with much attention to skill and technicalities would be much appreciated.

I have few questions:

According to the problem statement, the number of test cases was to be read from the first line in the file but I didn't need to use it.  Will this have any consequence that I do not yet know?
You will see from the code that, I read a line without using it (only for formatting purposes). Is there a better way to handle such a situation?
The for-loop in the rvrs_ln function throws segmentation fault if I do not reduce the number of elements by 1.

Here is the link to problem statement.

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <fstream>

std::string rvrs_ln(const std::string& line);

int main(){
   std::ifstream infile("B-small-practice.in");
   std::ofstream oufile("B-small-practice-result.out");
   if(!infile)
    std::cout<<"Could not open input file"<<std::endl;
   if(!oufile)
    std::cout<<"Could ont open output file"<<std::endl;

   int x = 1;       //index for formatting output file
   std::string line;
   int test_cases;
   infile>>test_cases;      //this is never used
   getline(infile,line);    //discards first line

   for(; std::getline(infile,line); x++){
       std::string all = rvrs_ln(line);
       oufile<<"Case #"<<x<<": "<<all<<std::endl;
   }
   infile.close();
   oufile.close();
}

std::string rvrs_ln(const std::string& line){
    std::istringstream buffer(line);
    std::string wrd,rvrs;
    std::vector<std::string> hold;
    int count_wrd = 0;

    while(buffer>>wrd){
        hold.push_back(wrd);
        count_wrd++;
    }
    for(int i=count_wrd-1; i>=0; --i){
        rvrs += hold[i];
        rvrs += " ";
    }
    return rvrs;
}


texts: Is this C++ naive primality test done right?

texts:
Here's my C++ code:

bool isPrime(double value) {
    if (value == 2)                    // ensure 2 returns true
        return true;
    else if (value <= 1)               // eliminate 1 and all negative numbers
       return false;
    else if (fmod(value, 2) == 0)      // eliminate all even numbers
       return false;

    for (int i = 3; i < sqrt(value); i++) {
        if (fmod(value, i) == 0) {
            return false;
        }
    }

    return true;
}

This function should return true if a number given by value is a prime, and false if a number given by value is a composite. First off, I just want to make sure it works correctly, is fairly efficient (it doesn't have to be the best, but I would like it to be decent for a naive approach), and that the code looks nice.

Thanks!


texts: BitArray (compacting 32 bool values into one integer)

texts:
I'm trying to refamiliarize myself with Java and working with it, so I've implemented my own version of a BitArray. Basically, it's an array of integers that maps 32 boolean values to each integer. This means an array of 32 boolean values only takes 4 bytes of space.

I was attempting to implement a Sieve of Eratosthenes and I figured I should implement a BitArray at the same time.

So, the BitArray class is as follows:

public class BitArray {
    private int[] elements;
    private int length;

    public boolean get(int index) {
        return (elements[(int)Math.floor(index / 32f)] >> (index % 32) & 0x01) == 1;
    }

    public void set(int index, boolean value) {
        int actualIndex = (int)Math.floor(index / 32f);
        int elementValue = elements[actualIndex] & ~(0x01 << (index % 32));

        if (value) {
            elementValue = elementValue | (0x01 << (index % 32));
        }

        elements[actualIndex] = elementValue;
    }

    public int getLength() {
        return length;
    }

    public BitArray(int maxSize) {
        length = maxSize;
        elements = new int[(int)Math.ceil(maxSize / 32f)];
    }
}

And to test this BitArray out, I implemented the following code:

public class Main {
    public static void main(String[] args) {
        int maxValue = 10000;

        // All the values will be initialized as false. If we mark them true, it means they are a composite number.
        BitArray bitArrayValues = new BitArray(maxValue);

        for (int i = 2; i < Math.sqrt(bitArrayValues.getLength()); i++) {
            if (!bitArrayValues.get(i)) {
                for (int j = i * i; j < bitArrayValues.getLength(); j += i) {
                    bitArrayValues.set(j, true);
                }
            }
        }

        // All the values will be initialized as false. If we mark them true, it means they are a composite number.
        boolean[] boolArrayValues = new boolean[maxValue];

        for (int i = 2; i < Math.sqrt(boolArrayValues.length); i++) {
            if (!boolArrayValues[i]) {
                for (int j = i * i; j < boolArrayValues.length; j += i) {
                    boolArrayValues[j] = true;
                }
            }
        }

        // Print all the numbers which are still false, which indicates the number is a prime.
        for (int i = 1; i < bitArrayValues.getLength(); i++) {
            if (!bitArrayValues.get(i)) {
                System.out.println(i + " is prime");
            }
        }

        boolean pass = true;

        for (int i = 0; i < maxValue; i++) {
            if (boolArrayValues[i] != bitArrayValues.get(i)) {
                pass = false;
            }
        }

        System.out.println("Arrays are equal? " + pass);
        System.out.println("Done.");
    }
}

I had some trouble getting back into the Java mindset for this, after having done C# and VB.NET for so long. Overall I think it was a successful adventure.

Any comments on either code block are welcome.


texts: jQuery plugin which will print to a printer an element or a jQueryUI Dialog

texts:
I have a need to print the content of a jQueryUI Dialog to a printer, and I couldn't find anything to my liking.  I developed the following simple jQuery plugin which prints one or more provided HTML elements, and am using it to print the jQueryUI Dialog DIV element.  The code is below, and a live example is located here.

It works on FF 26.0.  However, after printing a couple of times, FF asks the user if popups should be disabled, which I wish not to happen.  Also, it doesn't work with older IE, and likely other browsers.  Don't worry because, when printing, you still need to click the operating system print dialog, so you won't waste any paper!

Please provide any recommendations on how this plugin could be improved.

Actual Plugin:

/*
* jQuery printIt
* Print's the selected elements to the printer
* Copyright Michael Reed, 2014
* Dual licensed under the MIT and GPL licenses.
*/
(function($){
    var defaults = {
        elems           :null, //Element to print HTML
        copy_css        :false,//Copy CSS from original element
        external_css    :null  //New external css file to apply
    };

    var methods = {
        init : function (options) {
            var settings = $.extend({}, defaults, options)
            elems=$(settings.elems);
            return this.each(function () {
                $(this).click(function(e) {
                    var iframe   = document.createElement('iframe');
                    document.body.appendChild(iframe);
                    $(iframe).load(function(){
                        elems.each(function(){
                            iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
                        });
                        if(settings.copy_css) {
                            var arrStyleSheets = document.getElementsByTagName("link");
                            for (var i = 0; i < arrStyleSheets.length; i++){
                                iframe.contentWindow.document.head.appendChild(arrStyleSheets[i].cloneNode(true));
                            }
                            var arrStyle = document.getElementsByTagName("style");
                            for (var i = 0; i < arrStyle.length; i++){
                                iframe.contentWindow.document.head.appendChild(arrStyle[i].cloneNode(true));
                            }
                        }
                        if(settings.external_css) {
                            var style  = document.createElement("link")
                            style.rel  = 'stylesheet';
                            style.type = 'text/css';
                            style.href = settings.external_css;
                            iframe.contentWindow.document.head.appendChild(style);
                        }
                        var script   = document.createElement('script');
                        script.type  = 'text/javascript';
                        script.text  = 'window.print();';
                        iframe.contentWindow.document.head.appendChild(script);
                        $(iframe).hide();
                    });
                });
            });
        },
        destroy : function () {
            //Anything else I should do here?
            delete settings;
            return this.each(function () {});
        }
    };

    $.fn.printIt = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.printIt');
        }
    };
    }(jQuery)
);

To configure:

$(function () {
    $("#openDialog").click(function () {
        $("#myDialog").dialog('open')
    });
    $("#myDialog").dialog({
        modal: true,
        autoOpen: false
    });
    $('#printIt').printIt({
        elems: $("#myDialog"),
        copy_css: true,
        external_css: 'test2.css'
    });
});


texts: Retrieving HKLM nodes of Windows10 Registry

texts:
I have used below code, code is working fine, also retrieved the data, but there are performance issues. Retrieving the HKLM registry nodes is taking around 6 mins time. Please suggest any solution.

Private Function f_AddNodes(ByVal WindowsRegistryKey As RegistryKey, ByVal TreeNode As TreeNodeCollection, ByVal RegParent As Integer) As Integer
        Dim root As TreeNode
        If count = 1 Then
            root = TreeNode(RegParent)
        Else
            Dim KeyName = WindowsRegistryKey.Name
            Dim nLastIndex = KeyName.LastIndexOf("\")
            KeyName = KeyName.Substring(nLastIndex + 1, (KeyName.Length - 1) - nLastIndex)
            root = TreeNode.Add(KeyName) 'Node adding
        End If

        For Each subkeyName As String In WindowsRegistryKey.GetSubKeyNames
            Try
                Form_LoadingBar.Value(WindowsRegistryKey.Name)
                count = count + 1
                Dim vSubKey As RegistryKey = WindowsRegistryKey.OpenSubKey(subkeyName)
                f_AddNodes(vSubKey, root.Nodes, -1)
            Catch ex As SecurityException
                sExceptionHandling.Append(WindowsRegistryKey.Name + "\" + subkeyName + "," + ex.Message + vbNewLine)
            Catch ex As Exception
                MsgBox(ex.ToString)
                Return -1
            End Try
        Next`enter code here`
        Return 0
    End Function