texts: Selecting a div with a blue border and changing its text

texts:
I have a function that I created in Codepen. It does what I want, where the div that you select gets a blue border and changes its text. But I would like to know if there is any way to make the JavaScript that actually makes this work more compact/efficient.
Codepen
JavaScript
function toggle(el) {
  const contentReference = document.querySelectorAll('.content');
  for (div of contentReference) { div.className = 'content'; }
  el.className = 'content selected';
  const selectedContentReference = document.querySelectorAll('.selectedContent');
  for (div of selectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'selectedContent contentThatShouldBeHidden';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'selectedContent';
    }
  }
  const notselectedContentReference = document.querySelectorAll('.notselectedContent');
  for (div of notselectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'notselectedContent';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'notselectedContent contentThatShouldBeHidden';
    }
  }
}

const selectedContentReference = document.querySelectorAll('.selectedContent');
  for (div of selectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'selectedContent contentThatShouldBeHidden';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'selectedContent';
    }
  }
  const notselectedContentReference = document.querySelectorAll('.notselectedContent');
  for (div of notselectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'notselectedContent';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'notselectedContent contentThatShouldBeHidden';
    }
  }
```


texts: Function that generates steps time series from user given values

texts:
I created simple function, that generate values of series representing repeating sequence of steps in time. User can define:

step values
width of the steps
how many times the step sequence should repeat
or the size of returned series

If the size is not defined, the size of returned data should be determined by number of repeats.

So the call

steps(2, [1, 2, 3], repeat=2)

should return

[1 1 2 2 3 3 1 1 2 2 3 3]

The function follows

def steps(step_width, values, repeat=1, size=None):
    """
    This function generates steps from given values.

    **Args:**

    * `step_width` - desired width of every step (int)

    * `values` - values for steps (1d array)

    **Kwargs:**

    * `repeat` - number of step sequence repetions (int), this value is used,
      if the `size` is not defined

    * `size` - size of output data in samples (int), if the `size` is used,
      the `repeat` is ignored.

    **Returns:**

    * array of values representing desired steps (1d array)
    """
    try:
        step_width = int(step_width)
    except:
        raise ValueError('Step width must be an int.')
    try:
        repeat = int(repeat)
    except:
        raise ValueError('Repeat arg must be an int.')
    try:
        values = np.array(values)
    except:
        raise ValueError('Values must be a numpy array or similar.')
    # generate steps
    x = np.repeat(values, step_width)
    if size is None:
        # repeat according to the desired repetions
        x_full = np.tile(x, repeat)
    else:
        try:
            repeat = int(repeat)
        except:
            raise ValueError('Repeat arg must be an int.')
        # repeat till size is reached and crop the data to match size
        repeat = int(np.ceil(size / float(len(x))))
        x_full = np.tile(x, repeat)[:size]
    return x_full

I would appreciate any feedback. Especially I am not sure about effectivity of the error raising as it is implemented right now.


texts:
I have code that checks the range of a value and sets a variable accordingly.

if ( 169 <= angle && angle < 191 ) {currentOrientation = "1";}
if ( 191 <= angle && angle < 214 ) {currentOrientation = "2";}
if ( 214 <= angle && angle < 236 ) {currentOrientation = "3";}
if ( 236 <= angle && angle < 259 ) {currentOrientation = "4";}
if ( 259 <= angle && angle < 281 ) {currentOrientation = "5";}
if ( 281 <= angle && angle < 304 ) {currentOrientation = "6";}
if ( 304 <= angle && angle < 326 ) {currentOrientation = "7";}
if ( 326 <= angle && angle < 349 ) {currentOrientation = "8";}
if ( 349 <= angle) {currentOrientation = "9";}
if ( angle < 11 ) {currentOrientation = "9";}
if ( 11 <= angle && angle < 34 ) {currentOrientation = "10";}
if ( 34 <= angle && angle < 56 ) {currentOrientation = "11";}
if ( 56 <= angle && angle < 79 ) {currentOrientation = "12";}
if ( 79 <= angle && angle < 101 ) {currentOrientation = "13";}
if ( 101 <= angle && angle < 124 ) {currentOrientation = "14";}
if ( 124 <= angle && angle < 146 ) {currentOrientation = "15";}
if ( 146 <= angle && angle < 169 ) {currentOrientation = "16";}

Each range is 1/16 of 360°. There is a shift so that cardinal values (90,180..) are in the center of the range.

I am curious about how this code can be optimized. Maybe a jQuery function? So far a loop isn't interesting enough if I can't get the values automatically.


texts: Verifying if a string can be created with the letters of another string

texts:
This is basically based on the following question on stackoverflow which was based on a codewars assignment that can be found here
Problem statement

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

Notes:

Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered

My solution
function scramble(str1, str2) {
  if (str1.length < str2.length) {
    return false;
  }
  const set = new Set([...str2]);
  return Array.from( set ).every( letter => str2.split(letter).length <= str1.split(letter).length );
}

As with the original question on SO, my question would be if there are more efficient ways of completing the assignment. I am mainly worried about the string.split, but I didn't know of any other method that might be faster (I know I should substract 1 to get the actual letter count, but it doesn't matter for this usecase)


texts:
I'm including all of my code, however, my major issue here is about returning the vector/array/pointer (I don't really know what to choose) in this function:

std::vector<TNREstimationResult>TemporalNoiseReduction::PrepareResults(std::vector<std::pair<double,int>>  sortI, int newRows, cv::Mat timeStdv,                                                                                int nControlPoints, double** ctrl_sigma, std::vector<double> ctrl_y)

My problem is regarding returning allocated memory (long lists of doubles). I used std::vector but I basically copy using TNREstimation's copy constructor into a new std::vector here:

std::vector<TNREstimationResult> resultsArray;
resultsArray.push_back(TNREstimationResult(timeMeanY, timeStdVChannelY, ctrl_y, ctrlSigmaRow0));
resultsArray.push_back(TNREstimationResult(timeMeanY, timeStdVChannelCb, ctrl_y, ctrlSigmaRow1));
resultsArray.push_back(TNREstimationResult(timeMeanY, timeStdVChannelCr, ctrl_y, ctrlSigmaRow2));

Is there a better/easier way of doing it?

TNREstimationResult::TNREstimationResult(const TNREstimationResult& other)
{
    for (int i = 0; i < other._timeMeanY.size(); i++)
    {
        _timeMeanY.push_back(other._timeMeanY[i]);
    }

    for (int i = 0; i < other._timeStdVChannel.size(); i++)
    {
        _timeStdVChannel.push_back(other._timeStdVChannel[i]);
    }

    for (int i = 0; i < other._ctrlY.size(); i++)
    {
        _ctrlY.push_back(other._ctrlY[i]);
    }
    for (int i = 0; i < other._ctrlSigmaRow.size(); i++)
    {
        _ctrlSigmaRow.push_back(other._ctrlSigmaRow[i]);
    }

}

The function to review:

std::vector<TNREstimationResult>TemporalNoiseReduction::PrepareResults(std::vector<std::pair<double,int>>  sortI, int newRows, cv::Mat timeStdv,
                                                                       int nControlPoints, double** ctrl_sigma, std::vector<double> ctrl_y)
{
    std::vector<double> timeMeanY;
    for (int i = 0; i < sortI.size(); i++)
    {
        timeMeanY.push_back(sortI[i].first);
    }

    std::vector<double>timeStdVChannelY;
    std::vector<double>timeStdVChannelCb;
    std::vector<double>timeStdVChannelCr;
    for (int i = 0; i < newRows; i++)
    {
        timeStdVChannelY.push_back(timeStdv.at<double>(i,0));
        timeStdVChannelCb.push_back(timeStdv.at<double>(i,1));
        timeStdVChannelCr.push_back(timeStdv.at<double>(i,2));
    }

    std::vector<double> ctrlSigmaRow0;
    std::vector<double> ctrlSigmaRow1;
    std::vector<double> ctrlSigmaRow2;
    for (int i = 0; i <  nControlPoints + 2; i++)
    {
        ctrlSigmaRow0.push_back(ctrl_sigma[i][0]);
        ctrlSigmaRow1.push_back(ctrl_sigma[i][1]);
        ctrlSigmaRow2.push_back(ctrl_sigma[i][2]);
    }

    std::vector<TNREstimationResult> resultsArray;
    resultsArray.push_back(TNREstimationResult(timeMeanY, timeStdVChannelY, ctrl_y, ctrlSigmaRow0));
    resultsArray.push_back(TNREstimationResult(timeMeanY, timeStdVChannelCb, ctrl_y, ctrlSigmaRow1));
    resultsArray.push_back(TNREstimationResult(timeMeanY, timeStdVChannelCr, ctrl_y, ctrlSigmaRow2));
    return resultsArray;
}


texts: Static helper function to set a property on another object

texts:
A situation has come up in which we have a block of code that will be repeated in multiple files, and this block of code has to:

Create some object based on the values of other controls/properties.
Set a property on another object to be the object from #1.

Here is an example of what this looks like:

Repeated code before refactoring (TypeScript)

public class PageViewModel {
  private _name: TextBox;
  private _type: TextBox;
  private _timestampFormat: RadioButton;

  ..

  // This should generate a data model out of the current state of its controls.
  public generateDataModel(): IDataModel {
    // Here will be some logic to generate a property value based on
    // the radio button value and some other conditions.
    let timestampProperty;
    if (this._radioControl.value() === 1) {
      timestampProperty = { format: "foo" };
    } else if(this._radioControl.value() === 2) {
      timestampProperty = { format: "bar" };
    }

    var dataModelObject = <IDataModel>{
      name: this._name.value(),
      type: this._type.value(),
      timestamp: timestampProperty
    };
    return dataModelObject;
  }

}

Problem

The generateDataModel function will be present on more than one view model, all of which will generate the timestamp field from the radio control with that logic, so code will be repeated.

How it was solved

A helper method was extracted to do both #1 and #2 from above. This method is being called with references to both the control and the IDataModel object being created.

Helpers.ts:

public static setTimestampRadioButton(radioControl: RadioButton, dataModelObject: IDataModel): void {
    let timestampProperty;
    if (radioControl.value() === 1) {
      timestampProperty = { format: "foo" };
    } else if(radioControl.value() === 2) {
      timestampProperty = { format: "bar" };
    }

    dataModelObject.timestamp = timestampProperty;
}

PageViewModel.ts:

public generateDataModel(): IDataModel {
  var dataModelObject = <IDataModel>{
    name: this._name.value(),
    type: this._type.value()
  };

  Helpers.setTimestampRadioButton(this._radioControl, dataModelObject);

  return dataModelObject;
}

I have some concerns with this approach from the point of view of readability, and also because I think Helpers.ts knows too much about IDataModel and how it is used.

My questions:

Is this a good way to solve the problem of repetition here? Why / why not?

If not, is there a better way you'd suggest?

What do you think of the pattern static setSomethingOnSomethingElse(thing1, thing2)?


texts:
Please review performance
https://leetcode.com/problems/transpose-matrix/

Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over it's main
diagonal, switching the row and column indices of the matrix.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]
Note:
1 <= A.length <= 1000 1 <= A[0].length <= 1000

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

namespace ArrayQuestions
{
    [TestClass]
    public class TransposeMatrix
    {

        /// <summary>
        /// 1 2 3       1 4 7
        /// 4 5 6       2 5 8
        /// 7 8 9       3 6 9
        /// </summary>
        [TestMethod]
        public void Transpose3X3()
        {
            int[][] matrix = { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9 } };
            int[][] expected = { new[] { 1, 4, 7 }, new[] { 2, 5, 8 }, new[] { 3, 6, 9 } };
            int[][] output = Transpose(matrix);
            for (int i = 0; i < output.GetLength(0); i++)
            {
                CollectionAssert.AreEqual(expected[i], output[i]);
            }
        }

        [TestMethod]
        public void Transpose2X3()
        {
            int[][] matrix = { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } };
            int[][] expected = { new[] { 1, 4 }, new[] { 2, 5 }, new[] { 3, 6} };
            int[][] output = Transpose(matrix);
            for (int i = 0; i < output.GetLength(0); i++)
            {
                CollectionAssert.AreEqual(expected[i], output[i]);
            }
        }
        public int[][] Transpose(int[][] A)
        {
            int h = A.GetLength(0);
            int w = A[0].GetLength(0);

            //we need to allocate the matrix as transposed already
            //for example 2x3 should allocate 3x2
            int[][] res = new int[w][];
            for (int i = 0; i < w; i++)
            {
                res[i] = new int[h];
            }

            for (int r = 0; r < h; r++)
            {
                for (int c = 0; c < w; c++)
                {
                    res[c][r] = A[r][c];
                }
            }
            return res;
        }
    }
}


texts:
Intending to reuse the installation process of a GNOME extension, I wrote the following script:

#!/bin/bash
# It installs a target gnome shell extension defined via url

STORE_URL="https://extensions.gnome.org/extension-data"
EXTENSIONS_PATH="$HOME/.local/share/gnome-shell/extensions/"
ZIP="gnome-extension.zip"

cd ~/Downloads
wget $STORE_URL/$1 -O ./$ZIP
UUID=$(unzip -c $ZIP metadata.json | grep uuid | cut -d \" -f4)

if [[ ! -d $EXTENSIONS_PATH/$UUID ]]; then
    mkdir $EXTENSIONS_PATH/$UUID
    unzip -q ./$ZIP -d $EXTENSIONS_PATH/$UUID
    gnome-shell-extension-tool -e $UUID
fi

rm $ZIP
gnome-shell --replace &

  It expects to receive as argument the target extension zip name, one available from official GNOME extensions index. The zip file, after downloaded, will be unzipped in its UUID directory inside GNOME extensions' location and then enable.

Is there something else could be done to improve this installation process?
Any of the executed commands could be improved or code get better readability?


texts:
Hi I'm implementing a few leetcode examples in Rust. https://leetcode.com/problems/flood-fill/
(looks to be same question as LeetCode: FloodFill C#)
The input is one matrix, a position and its new colour. The output is the modified matrix
// Input:
// image = [[1,1,1],[1,1,0],[1,0,1]]
// sr = 1, sc = 1, newColor = 2
// Output: [[2,2,2],[2,2,0],[2,0,1]]
// Explanation:
// From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
// by a path of the same color as the starting pixel are colored with the new color.
// Note the bottom corner is not colored 2, because it is not 4-directionally connected
// to the starting pixel.

I use q.pop_front() to fill the neighbouring cells first. Is VecDeque the best data structure for this que?
I do a lot of casting from between i32 and usize as I want to be able to check if index is out of bounds by subtracting 1. Is there a better way?
Is if (0..image.len()).contains(x1) better than if x1>=0 && x1<image.len() for the range check?
use std::collections::VecDeque;

  fn flood_fill(mut image: Vec<Vec<i32>>, sr: i32, sc: i32, new_color: i32) -> Vec<Vec<i32>> {

      let mut q:VecDeque<(i32,i32)> = VecDeque::new();
      q.push_back((sr,sc));

      let c0 = image[sr as usize][sc as usize];
      if c0 != new_color {
          while ! q.is_empty() {
              if let Some((sr,sc))=q.pop_front() {
                  if image[sr as usize][sc as usize] == c0 {
                      image[sr as usize][sc as usize] = new_color;
                      for delta in vec![(-1,0),(1,0),(0,-1),(0,1)] {
                          let new_r:i32 = sr+delta.0;
                          let new_c:i32 = sc+delta.1;
                          if (0..image.len() as i32).contains( &new_r ) && (0..image[0].len() as i32).contains( &new_c){
                              q.push_back((new_r,new_c));
                          }
                      }
                  }
              }
          }
      }
      image
  }

#[cfg(test)]
mod test{
#[test]
    fn test_lc_default(){
        assert_eq!(super::flood_fill(vec![vec![1 as i32 ,1,1],vec![1,1 as i32,0],vec![1,0,1]],1, 1, 2),vec![vec![2,2,2],vec![2,2,0],vec![2,0,1]]) ;
    }
}

It looks like I could use some memory optimization too.


texts: DataService that fetches data not loaded already or loads cached values

texts:
I load an array from an API that is available throughout the user's whole session. This data is unlikely to change, so it can be cached safely. I have a DataService that works like this:

get data from the class property (scenario: going to a new route)
if nothing is there, get data from local storage (scenario: reload)
if nothing is there, fetch data from API (scenario: new session)

This is what I've come up with:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})

export class DataService {
  protected data: Array<any> = null;

  constructor(private http: HttpClient) { }

  public getData(): Observable<Array<any>> {
    if (this.data === null) {
      this.data = JSON.parse(localStorage.getItem('data'));
  }

  if (this.datas !== null) {
    return of(this.data);
  }

  return this.http.get<Object>(this.url + this.route).pipe(
    retry(3),
    map(response => {
      this.data = response as Array<any>;
      localStorage.setItem('data', JSON.stringify(this.data));
      return this.data;
    }),
    catchError(error => {
      this.handleError(error);
      return [];
    })
  );
}

The service is registered in the app.component.ts and used like this in other components:

import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/service/data.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.less'],
  providers: []
})

export class ExampleComponent implements OnInit {
  protected subscribers: Subscription[] = [];

  public data: Array<any> = [];

  constructor(public data: DataService) { }

  ngOnInit() {
    this.subscribers.push(
      this.data.getData().subscribe((data) => { this.data = data })
    );
  }

  ngOnDestroy() {
    for (let subscriber of this.subscribers) {
      subscriber.unsubscribe();
    }
  }
}

Is it a good approach? Is this "the Angular way"? Can it be improved? Is it readable? Does this indeed increase performance? At least it uses fewer HTTP requests.

This class is shortened a bit for the review, so don't worry that there's no handleError method.


texts:
No specific question here. I am beginning with Java and here is an exercise. The rules of game:

  You roll two dice. Each die has six faces, which contain one, two,
  three, four, five and six spots, respectively. After the dice have
  come to rest, the sum of the spots on the two upward faces is
  calculated. If the sum is 7 or 11 on the first throw, you win. If the
  sum is 2, 3 or 12 on the first throw (called “craps”), you lose (i.e.,
  the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first
  throw, that sum becomes your “point.” To win, you must continue
  rolling the dice until you “make your point” (i.e., roll that same
  point value). You lose by rolling a 7 before making your point.

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class helloworld {
    private static int point;
    private static enum possibleResults {UNDEFINED, WIN, LOSE};
    private static possibleResults gameResult = possibleResults.UNDEFINED;
    private static String causeOfLose;
    private static String causeOfWin;

    public static int rollDice(int n) {
        int sum = 0;
        Random randomNumbers = new Random();
        for(int i=0; i<n; i++) {
            sum += (1 + randomNumbers.nextInt(6));
        }
        System.out.printf("Rolling dice... You got %d\n", sum);
        return sum;
    }

    public static void firstRoll() throws IOException {
        waitUser();
        int tmp = rollDice(2);
        if(tmp == 7 || tmp == 11) {
            gameResult = possibleResults.WIN;
            causeOfWin = String.format("you have got a lucky number in the first round: %d.", tmp);
        } else if(tmp == 2 || tmp == 3 || tmp == 12) {
            gameResult = possibleResults.LOSE;
            causeOfLose = String.format("you have got an unlucky number in the first round: %d.", tmp);
        } else {
            point = tmp;
            System.out.printf("Your point is %d, you need to make your point to win.%n", point);
        }
        declareResult();
    }

    public static void declareResult() {
        if(gameResult == possibleResults.LOSE) {
            System.out.printf("You have lost, because %s%n", causeOfLose);
        } else if(gameResult == possibleResults.WIN) {
            System.out.printf("You have won, because %s%n", causeOfWin);
        } else {
            System.out.println("Game continues...");
        }
    }

    public static void moreRolls() {
        Scanner inputScan = new Scanner(System.in);
        while(gameResult == possibleResults.UNDEFINED) {
            waitUser();
            int tmp = rollDice(2);
            if(tmp == point) {
                gameResult = possibleResults.WIN;
                causeOfWin = "you have made your point!";
            } else if(tmp == 7) {
                gameResult = possibleResults.LOSE;
                causeOfLose = "you have hit 7 before making your point.";
            } else {
                ;
            }
            declareResult();
        }
    }

    private static void waitUser() {
        Scanner inputScan = new Scanner(System.in);
        System.out.print("Press enter to start rolling: ");
        String input = inputScan.nextLine();
    }

    public static void main(String[] args) throws IOException {
        firstRoll();
        moreRolls();
    }

}

Any corrections and/or suggestions are welcome.


texts: Finding the longest unique sub-string in a string

texts:
I recently interviewed with a company for software engineering position. I was asked the question of finding the longest unique sub-string in a string.

My algorithms was as follows:

Start from the left-most character, and keep storing the character in a hash table with the key as the character and the value as the index_where_it_last_occurred. Add the character to the answer string as long as its not present in the hash table. If we encounter a stored character again, I stop and note down the length. I empty the hash table and then start again from the right index of the repeated character. The right index is retrieved from the (index_where_it_last_occurred) flag. If I ever reach the end of the string, I stop and return the longest length.

For example, say the string was abcdecfg.

I start with a, store in hash table. I store b and so on till e. Their indexes are stored as well. When I encounter c again, I stop since it's already hashed and note down the length which is 5. I empty the hash table, and start again from the right index of the repeated character. The repeated character being c, I start again from the position 3 ie., the character d. I keep doing this while I don't reach the end of string.

I know there could be better algorithms than this. But I am interested in knowing what the time complexity of this algorithm will be.  I believe it'll be \$O(n^2)\$.

import java.util.*;
public class longest
{
    static int longest_length = -1;
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        calc(str,0);
        System.out.println(longest_length);
    }

    public static void calc(String str,int index)
    {
        if(index >= str.length()) return;
        int temp_length = 0;
        LinkedHashMap<Character,Integer> map = new LinkedHashMap<Character,Integer>();
        for (int i = index; i<str.length();i++)
        {
            if(!map.containsKey(str.charAt(i)))
            {
                map.put(str.charAt(i),i);
                ++temp_length;
            }
            else if(map.containsKey(str.charAt(i)))
            {
                if(longest_length < temp_length)
                {
                    longest_length = temp_length;
                }
                int last_index = map.get(str.charAt(i));
//              System.out.println(last_index);
                calc(str,last_index+1);
                break;
            }
        }
        if(longest_length < temp_length)
            longest_length = temp_length;
    }
}


texts:
I have written an EmailSession class to connect and get (unread) mail messages. It is all working, but I would like to see your opinions on any enhancements or improvements, as I understood there are lots of bad examples on the Internet and I copy-pasted most of it together.

One issue I already noticed:

If there is no internet connection it throws a java.net.UnknownHostException instead of handling the issue gracefully.

import java.util.*;
import java.util.logging.*;
import javax.mail.*;

public class EmailSession {

    private Session session;
    private Store store;
    private Folder inbox;
    private int messageCount;
    private int unreadMessageCount;
    private List<Message> unreadMessages;

    public EmailSession() {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", MyProps.getProperty("mail.store.protocol"));
        try {
            session = Session.getInstance(props, null);
            store = session.getStore();
            store.connect(MyProps.getProperty("mail.host"), MyProps.getProperty("mail.user"), MyProps.getProperty("mail.password"));
            inbox = store.getFolder(MyProps.getProperty("mail.foldername"));
            inbox.open(Folder.READ_ONLY);
            messageCount = inbox.getMessageCount();
            List<Message> messages;
            if (messageCount > 100) {
                Logger.getLogger(EmailSession.class.getName()).log(Level.WARNING,
                        "More than 100 messages");
                messages = Arrays.asList(inbox.getMessages(1, 100));
            } else {
                messages = Arrays.asList(inbox.getMessages());
            }
            unreadMessages = new ArrayList<>();
            unreadMessageCount = 0;
            for (Message message : messages) {
                boolean isUnreadMessage = true;
                for (Flags.Flag flag : message.getFlags().getSystemFlags()) {
                    if (flag == Flags.Flag.SEEN) {
                        isUnreadMessage = false;
                        break;
                    }
                }
                if (isUnreadMessage) {
                    unreadMessages.add(message);
                    unreadMessageCount++;
                }
            }
            inbox.close(true);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(EmailSession.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(EmailSession.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Folder getInbox() {
        return inbox;
    }

    public int getMessageCount() {
        return messageCount;
    }

    public int getUnreadMessageCount() {
        return unreadMessageCount;
    }

    public List<Message> getUnreadMessages() {
        return unreadMessages;
    }

    public boolean close() {
        try {
            store.close();
            return true;
        } catch (MessagingException ex) {
            Logger.getLogger(EmailSession.class.getName()).log(Level.SEVERE, null, ex);

            return false;
        }
    }

}


texts:
Here's a trick for preallocating some memory for some type T. Do there exist similar tricks? Improvements?

#include <cassert>

#include <cstdlib>

#include <atomic>

#include <limits>

#include <new>

#include <thread>

#include <utility>

namespace
{
  template <typename T, typename A = unsigned>
  struct static_store
  {
    static constexpr auto const max_instances =
      ::std::numeric_limits<unsigned char>::digits * sizeof(A);

    static void cleanup() { delete [] store_; }

#ifdef __GNUC__
    template <typename U>
    static int ffz(U const v)
    {
      return __builtin_ctzll(~v);
    }
#elif _MSC_VER && !__INTEL_COMPILER
    template <typename U>
    static int ffz(U const v)
    {
      return ::std::numeric_limits<unsigned char>::digits * sizeof(v) -
        __lzcnt64(v & -v);
    }
#elif __INTEL_COMPILER
    template <typename U>
    static int ffz(U const v)
    {
      return _bit_scan_forward(~v);
    }
#else
    template <typename U>
    static int ffz(U v)
    {
      decltype(ffz()) b{};

      for (; (v & 1); ++b)
      {
        v >>= 1;
      }

      return b;
    }
#endif

    static ::std::atomic_flag lock_;

    static A memory_map_;

    static typename ::std::aligned_storage<sizeof(T),
      alignof(T)>::type* store_;
  };

  template <typename T, typename A>
  ::std::atomic_flag static_store<T, A>::lock_;

  template <typename T, typename A>
  A static_store<T, A>::memory_map_;

  template <typename T, typename A>
  typename ::std::aligned_storage<sizeof(T), alignof(T)>::type*
    static_store<T, A>::store_{(::std::atexit(static_store<T, A>::cleanup),
      new typename ::std::aligned_storage<sizeof(T),
        alignof(T)>::type[static_store<T, A>::max_instances])};

  template <typename T, typename ...A>
  inline T* static_new(A&& ...args)
  {
    using static_store = static_store<T>;

    while (static_store::lock_.test_and_set(::std::memory_order_acquire))
    {
      ::std::this_thread::yield();
    }

    auto const i(static_store::ffz(static_store::memory_map_));

    auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));

    static_store::memory_map_ |= 1ull << i;

    static_store::lock_.clear(::std::memory_order_release);

    return p;
  }

  template <typename T>
  inline void static_delete(T* const p)
  {
    using static_store = static_store<T>;

    auto const i(p - static_cast<T*>(static_cast<void*>(
      static_store::store_)));
    //assert(!as_const(static_store::memory_map_)[i]);

    while (static_store::lock_.test_and_set(::std::memory_order_acquire))
    {
      ::std::this_thread::yield();
    }

    static_store::memory_map_ &= ~(1ull << i);

    static_cast<T*>(static_cast<void*>(&static_store::store_[i]))->~T();

    static_store::lock_.clear(::std::memory_order_release);
  }
}

Usage:

auto const p(static_new<int>());
*p = 10;
static_delete(p);

The code uses an integral type (A), as a bit mask, where each cleared bit means, that a corresponding slot in the store_ is not occupied, and a set bit means it is occupied. This is done to minimize the storage requirements for the allocation mechanism. To find a free slot, the ffz function (find first zero) is used: it is compiled into a single instruction on many platforms. The same thing could have been done with an array of bools, but with greatly increased storage requirements.


texts:
I need the byte representation of a given type, especially double, float, int8, etc.

typealias Byte = UInt8

enum ByteOrder {
    case BigEndian
    case LittleEndian
}

func pack<T>(var value: T, byteOrder: ByteOrder) -> [Byte] {
    let valueByteArray = withUnsafePointer(&value) {
        Array(UnsafeBufferPointer(start: UnsafePointer<Byte>($0), count: sizeof(T)))
    }
    return (byteOrder == .LittleEndian) ? valueByteArray : valueByteArray.reverse()
}

func unpack<T>(valueByteArray: [Byte], toType type: T.Type, byteOrder: ByteOrder) -> T {
    let bytes = (byteOrder == .LittleEndian) ? valueByteArray : valueByteArray.reverse()
    return UnsafePointer<T>(bytes).memory
}

What do you think?

Especially I am interested in your opinion on

CFByteOrder does offer already a byte order, but I decided to go with a different definition.
We can use the type inference and get rid of forType type: T.Type, which works fine for

let result: double = unpack(someArray, .LittleEndian)

but fails for

let result = unpack(someArray, .LittleEndian)

Is the following nicer? I don't think so, but what about you. :-)

func unpack<T>(valueByteArray: [Byte], byteOrder: ByteOrder) -> T {
    let bytes = (byteOrder == .LittleEndian) ? valueByteArray : valueByteArray.reverse()
    return bytes.withUnsafeBufferPointer {
        return UnsafePointer<T>($0.baseAddress).memory
    }
}

What do you think about encapsulating the two function in a class, e.g. ByteBackPacker and convert them to class functions?
What about giving byteOrder: ByteOrder a default value, e.g. .LittleEndian, because this is the native byte order in iOS and Mac OS X, the primary platforms for Swift, I assume?

Update:
I created a ByteBackpacker project on github. Let me know what you think about it.


texts: How to increase download speed using the following method?

texts:
I have written an Android application which downloads pdf files through web service. I am using kSoap2 android library to parse the response of web service which basically contains file name & file data.

I have written following code. Please review & tell how to increase the speed I think there is some small defect in code which reduces the speed. I am using version 2.5.1 of kSoap2.

public void downloadPdfFiles(File fileDocsDir, int noOfFiles)
            throws NullPointerException, SoapFault, XmlPullParserException,
            FileNotFoundException, IOException, Exception {

        System.gc();

        // Download files from web service and save them in the folder.
        soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
        soapObject.addProperty("startingFile", noOfFiles);
        soapObject.addProperty("deviceId", deviceId);
        soapObject.addProperty("loginId", loginId);
        soapObject.addProperty("byoinId", "1");

        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        envelope.setOutputSoapObject(soapObject);

        // Calling the web service
        System.gc();
        androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.call(SOAP_ACTION, envelope);

        // Getting Response through xml mainly generated as soap:reponse.
        responseBean = (SoapObject) envelope.getResponse();

        // Array of PDFInfoBean.
        list = (SoapObject) responseBean.getProperty(0);

        FileOutputStream outputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        // Get Individual PDF Details from Array.
        SoapObject pdfDetails = null;

        mIncrement = noOfFiles;
        // Log.i("Increment Values", String.valueOf(mIncrement));

        File pdfFile = null;
        for (int i = 0; i < list.getPropertyCount(); i++) {
            pdfDetails = (SoapObject) list.getProperty(i);

            // Get PDF File Name.
            pdfDocName = pdfDetails.getProperty(1).toString();
            Log.i(TAG, "File Name: " + pdfDocName);

            // Check for last file.
            if (pdfDocName.equalsIgnoreCase("EOF")) {
                mFlag = false;
                break;
            }

            // Creating PDF File.
            pdfFile = new File(fileDocsDir, pdfDocName);

            // Writing PDF file received through web service.
            if (pdfFile.exists()) {
                Log.i(TAG, pdfFile.getName() + " File Already Exists");
            } else {
                outputStream = new FileOutputStream(pdfFile);
                bufferedOutputStream = new BufferedOutputStream(outputStream);

                bufferedOutputStream.write(Base64Coder.decode(pdfDetails
                        .getProperty(0).toString()));

                mIncrement = mIncrement + 1;

                bufferedOutputStream.close();
                outputStream.close();

                bufferedOutputStream = null;
                outputStream = null;
            }
            pdfDetails = null;
            pdfDocName = null;
            pdfFile = null;
            System.gc();
        }
        soapObject = null;
        envelope = null;
        responseBean = null;
        list = null;
        androidHttpTransport = null;

        System.gc();
    }


texts: Is there a better or more compact way of adding items in treeview using LINQ?

texts:
I am using the following code to add nodes in a treeview. Is there a better or more compact way of doing this by using LINQ?

foreach (Plan plan in this.IncomingPlan.Plans)
{
    foreach (Document doc in plan.Documents.Where(d => d.Name.Equals(this.DocumentName, StringComparison.OrdinalIgnoreCase)))
    {
        foreach (Author author in doc.Authors)
        {
            TreeNode treeNode = new TreeNode()
            {
                Text = author.Name,
                Type = NodeType.ParentNode,
                Tag = author
            };

            foreach (Book book in author.Books)
            {
                treeNode.Nodes.Add(new TreeNode()
                {
                    Text = book.Name,
                    Type = NodeType.ChildNode,
                    Tag = book
                });
            }

            this.treeView.Nodes.Add(treeNode);
        }
    }
}


texts: Read and reformat a list of global variables output by a compiler

texts:
I'm currently going through a large Python program, with an eye to making it more readable and maintainable. Currently using Pylint and other code review tools throws a lot of unused variable warnings because of the way I've been using .format(). Since this program manipulates a lot of text, I use .format() quite a lot, which results in many spurious warnings. I could turn these warnings off, but I'd rather not because so far they've been useful in finding genuinely unused variables in my code.

Here's an example of the existing code style. (The program is very large so this is just the tip of the iceberg, selected to show the difference in style that I'm considering. Its purpose is to read and process compiler output, which will then be fed to another set of tools. This particular function is from a module which reads and reformats a list of global variables output by a compiler. The names of some other internal functions have been modified a bit to make it easier to read out of context.)

def parse_global_variable(line, length):
    last_element = length-1
    template = ''
    if length == 0:
        template = ' Record   GLB  {logical_address} {physical_address} {module:34}{var_name}' \
                   '\n                0    {width:7}{var_type}'
    else:
        template = ' Record   GLB  {logical_address} {physical_address} {module:34}{var_name}' \
                   '(0..{last_element})\n                0    {width:7}{var_type}'
    module = line.partition('.')[0].rpartition('\t')[2]
    logical_address = line.partition('#')[2].partition('#')[0]
    physical_address = get_physical_address(logical_address)
    var_name = get_var_name(line))
    width = line.rpartition('\t')[2]
    if length != 0:
        width = str(int(width)/length)
    return template.format(**locals())

This is a different style I'm considering, which inlines most of the variables, shortens variable names in the template string, and uses explicit arguments to .format() instead of using **locals():

def parse_global_variable(line, length):
    template = ''
    if length == 0:
        template = ' Record   GLB  {la} {pa} {m:34}{vn}' \
                   '\n                0    {w:7}{vt}'
    else:
        template = ' Record   GLB  {la} {pa} {m:34}{vn}(0..{le})' \
                   '\n                0    {w:7}{vt}'
    logical_address = line.partition('#')[2].partition('#')[0]
    width = line.rpartition('\t')[2]
    if length != 0:
        width = str(int(width)/length)
    return template.format(la=logical_address, pa=get_physical_address(logical_address),
        m=line.partition('.')[0].rpartition('\t')[2], vn=get_var_name(line), le=length-1, w=width)

Is it stylistically preferable, more readable, more Pythonic, etc. to use **locals() or explicit arguments? Is using abbreviated names such as vn or pa in the format string frowned upon when there are explicit arguments? And should variables which are only used in the format string be inlined?

Edit: Here is a sample input line:

Record      imsd_ini.ini            16#3200#        0       1424

The output that this module produces corresponding to that line is:

Record   GLB  3200 133200 imsd_ini                          ini
              0    1424   ini_type


texts: Efficient element-wise function computation in Python

texts:
I have the following optimization problem:

  Given two np.arrays X,Y and a function K I would like to compute as fast as possible the matrix incidence gram_matrix where the (i,j)-th element is computed as K(X[i],Y[j]).

Here is an implementation using nested for-loops, which are acknowledged to be the slowest to solve these kind of problems.

def proxy_kernel(X,Y,K):
    gram_matrix = np.zeros((X.shape[0], Y.shape[0]))
    for i, x in enumerate(X):
        for j, y in enumerate(Y):
            gram_matrix[i, j] = K(x, y)
    return gram_matrix


texts:
I would like any ideas or suggestions on how to enhance the code for rolling hash algorithm and make if faster. Even if it is a change in one line. I tried to add a list, because I thought it would be more efficient, but it didn't work properly. So any ideas on how to enhance it. I would appreciate the assist.

import time

class RollingHash:
def __init__(self, text, sizeWord):
    self.text = text
    self.hash = 0
    self.sizeWord = sizeWord

    for i in range(0, sizeWord):
        # ord maps the character to a number
        # subtract out the ASCII value of "a" to start the indexing at zero
        self.hash += (ord(self.text[i]) - ord("a") + 1) * (26 ** (sizeWord - i - 1))  # change the first / with *

    # start index of current window
    self.window_start = 0
    # end of index window
    self.window_end = sizeWord

def move_window(self):
    if self.window_end <= len(self.text) - 1:
        # remove left letter from hash value
        self.hash -= (ord(self.text[self.window_start]) - ord("a") + 1) * 26 ** (self.sizeWord - 1)
        self.hash *= 26
        self.hash += ord(self.text[self.window_end]) - ord("a") + 1
        self.window_start += 1
        self.window_end += 1

def window_text(self):
    return self.text[self.window_start:self.window_end]

def rabin_karp(word, text):
if word == "" or text == "":
    return None
if len(word) > len(text):
    return None

rolling_hash = RollingHash(text, len(word))
word_hash = RollingHash(word, len(word))
# word_hash.move_window()

for i in range(len(text) - len(word) + 1):
    if rolling_hash.hash == word_hash.hash:
        if rolling_hash.window_text() == word:
            print(i)
    rolling_hash.move_window()
return  'Pattern length: ' , len(word)

text = input("Text: ")
word = input("Pattern: ")
t1 = time.clock()
results = rabin_karp(word, text)
print(results)
t2 = time.clock()
print('Run Time:  %0.5f ms' % ((t2 - t1) * 1000.0))


texts: Modification of javascript inheritance framework

texts:
I've modified John Resig simple javascript inheritance framework, by adding set function with setter functionality. It seems that it works. Is it written correctly? Can you see some undesired behavior?
Framework:

(function(){
   var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
   this.Class = function(){};
   Class.extend = function(prop) {
     var _super = this.prototype;
    initializing = true;
    var prototype = new this();
    initializing = false;
    for (var name in prop) {
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
            this._super = _super[name];
            var ret = fn.apply(this, arguments);
            // CHANGED HERE FROM this._super = tmp;
            // don't like some not used properties
            if(tmp)this._super = tmp;
            // END OF CHANGE
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
    function Class() {
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    Class.prototype = prototype;
    Class.prototype.constructor = Class;
    Class.extend = arguments.callee;

    // CHANGED HERE
    // Set method
    Class.prototype.set = function(attrs) {
      for (var attr in attrs) {
        //if exist setter function this.on_change{key of wrap: function(key of wrap, new value)
        if(this.on_change[attr])this.on_change[attr].call(this,attr,attrs[attr]);
        else this[attr] = attrs[attr];
      }
      return this;
    };
    if(!Class.prototype.on_change)Class.prototype.on_change={};
    // END OF CHANGE

    return Class;
  };
})();

Test code:

var Person = Class.extend({
  a: 15,
  b: 30,
  init: function(){
      //...
  },
  on_change:{
      b: function(oldKey, set){this[oldKey] = set*2}
  }
});
var p = new Person();
p.set({a:25,b:40});


texts:
I am new to Python and here is my first attempt at trying to achieve anything by myself!

Essentially, I am making JSON objects with any user defined ticker through the Alpha Vantage API.  It is basically a small part of a Python wrapper for the API (I guess).  Actually, someone already made a wrapper for the API but I want to do one for myself.  Anyways, I feel like it is a bit more messy than it has to be, and I do not know how to get to the point where someone can type something like object.lastday and get the last day's trading data with the object they just made.

NOTE: not the real API key

Any advice appreciated, I am trying to get better.

import json
import urllib.request
import datetime

#mainURL that will be appended to return our requests
mainURL = "https://www.alphavantage.co/query?"
#API key that will be needed to authenticate
myKey = "F3DH8T01FS5445IB"

#For daily activity
'''
REQUEST NEEDS:
function: will ALWAYS be equal to 'TIME_SERIES_DAILY' for daily
symbol: user defined stock ticker
outputsize: default is 'compact' which only returns 100 data points,
otherwise
we can define it as 'full' to get up to 20 years worth
datatype: default is 'json', but we can also request 'csv'
'''

#loads a json object of based on what you input in dailyData(SYMBOL)
requestTypeURL = "function=TIME_SERIES_DAILY"
def dailyData(symbol, requestType=requestTypeURL, apiKey=myKey):
    symbolURL = "symbol=" + str(symbol)
    apiURL = "apikey=" + myKey
    completeURL = mainURL + requestType + '&' + symbolURL + '&' + apiURL
    with urllib.request.urlopen(completeURL) as req:
        data = json.load(req)
        return data

#making a json object for Apple and example of getting a date's activity
(test)
'''
apple = dailyData('AAPL')
print(apple["Time Series (Daily)"]["2018-03-02"])
'''


texts: Model classes for an expense tracking app in Django

texts:
I want to build a simple expense tracking app in Django. Each user can create categories, and each category can have multiple expenses:

Additionally, I wanted to have a value field that shows the total value of the category per month. For this I am using the def save() function in the Expenses class and a def calc_category_value() function called from the signals. I was wondering if this approach is correct:

def calc_category_value(instance):
    today = date.today()
    days = calendar.monthrange(today.year,today.month)[1]
    range_start = "%s-%s-%s" % (today.year,today.month,1)
    range_end = "%s-%s-%s" % (today.year,today.month,days)
    category = Category.objects.get(id=instance.category.id)
    expenses = Expense.objects.filter(date__range=[range_start,range_end],category=category)
    total = 0
    for e in expenses:
        total += e.amount
    category.value = total
    category.save()

class Profile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    create_date = models.DateTimeField('date added', auto_now_add=True)
    modify_date = models.DateTimeField('date modified', default=timezone.now)

class Category(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, unique=True)
    value = models.DecimalField(max_digits=11,decimal_places=2, default=0)
    create_date = models.DateTimeField('date added', auto_now_add=True)
    modify_date = models.DateTimeField('date modified', default=timezone.now)

    class Meta:
        verbose_name_plural = "Categories"

    def __unicode__(self):
        return self.name +' (' + str(self.value) + ')'

class Expense(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200, blank=True)
    amount = models.DecimalField(max_digits=11, decimal_places=2,default=0)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    date = models.DateField(default=timezone.now)
    create_date = models.DateTimeField('date added', auto_now_add=True)
    modify_date = models.DateTimeField('date modified', default=timezone.now)

    def save(self, *args, **kwargs):
        super(Expense, self).save(*args, **kwargs)
        today = date.today()
        days = calendar.monthrange(today.year,today.month)[1]
        range_start = "%s-%s-%s" % (today.year,today.month,1)
        range_end = "%s-%s-%s" % (today.year,today.month,days)
        expenses = Expense.objects.filter(date__range=[range_start,range_end],category=self.category)
        total = 0
        for e in expenses:
            total += e.amount
        self.category.value = total
        self.category.save()

    class Meta:
        verbose_name_plural = "Expenses"
        order_with_respect_to = 'category'

    def __unicode__(self):
        return self.title +', ' + str(self.amount) +' (' + self.category.name + ')'

Signals.py:

@receiver(post_delete, sender=Expense)
def post_delete(sender, instance, **kwargs):
    calc_category_value(instance)


texts:
This question follows on from :Previous Question

Here is what my reworked code looks like. I neatened it up as much as I could. Changed some of the semantics of it. I also tried to add some faster exit points and checks to prevent errors.

Any further critiques?

 /**
 * @author              :KyleMHB
 * Project Number       :0002
 * Project Name         :Anagramatic
 * IDE                  :NETBEANS
 * Goal of Project      -
 * Capture user input, compare to a dictionary file for anagrams,
 * output number of matches and the matches.
 */

package anagramatic;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;

-

public class Anagramatic {
public static void main(String[] args) throws FileNotFoundException{
    String anagram=getInput("Enter the word you would like to process");
    List<String> words=readAnagramsFromFile(anagram, new File("words.txt"));
    String output= formatOutput(anagram,words);
    displayOutput(output);
}//pvsm

-

private static String getInput(String prompt) {
    String input = JOptionPane.showInputDialog(null,prompt);
    return input;
}//getInput

-

  private static List readAnagramsFromFile(String word, File f)
        throws FileNotFoundException{
    ArrayList<String> anagrams = new ArrayList<>();
    try(Scanner s = new Scanner(f)){
        while(s.hasNext()){
            String candidate=s.next();
            if ( (candidate.length()==word.length()) &&
                    (checkMatch(word,candidate)==true)){
                anagrams.add(candidate);
            }
        }
}
    return anagrams;
}//readFile

-

private static boolean checkMatch(String word, String candidate) {
    char[] wordArray = word.toCharArray();
    char[] candidateArray = candidate.toCharArray();
    if (Arrays.equals(wordArray, candidateArray)){
        return false;
    }
    Arrays.sort(wordArray);
    Arrays.sort(candidateArray);
    if(Arrays.equals(wordArray, candidateArray)){
        return true;
    }
    /**I did not use an else function for the the below return
    *because if (Arrays.equals(wordArray, candidateArray))==true
    *it will break on the return*/
    return false;

}//match

-

private static String formatOutput(String original, List<String> words) {
    StringBuilder output=new StringBuilder("[ ");
    int counter=0;
    Iterator<String> wordIt =words.iterator();
    while(wordIt.hasNext()){
       output.append(wordIt.next());
       if(wordIt.hasNext()){
           output.append((++counter % 8 == 0)? ",\n" : ", ");
       }
    }
    output.append(" ]");
    return ("The Anagram "+original+" has "+words.size()+" matches.\n\nThey are:\n"+output.toString());
}//formatOutput

-

private static void displayOutput(String output){
    JOptionPane.showMessageDialog(null,output);
}//displayOutput
}


texts:
Problem:
The task is to reverse the strings contained in each pair of matching parentheses, starting from the innermost pair. The results string should not contain any parentheses.

Example:

>>> s = "a(bc)de"
>>> reverseParentheses(s)
"acbde"
>>> s = "The ((quick (brown) (fox) jumps over the lazy) dog)"
>>> reverseParentheses(s)
"The god quick nworb xof jumps over the lazy"

To achieve this task I have written the following piece of code:

def reverseParentheses(s):
 i = 0
 brackarray = []
 recursivearray = []
 a = []
 numberofbrack = -1
 alteredstring = s

 chars = "()"
 for char in chars:
  alteredstring = alteredstring.replace(char, "")

 while i < len(s):

  if s[i] == '(':
   j = i
   numberofbrack = numberofbrack + 1
   j = j - numberofbrack
   brackarray.append(j)

  if s[i] == ')':
   m = i
   numberofbrack = numberofbrack + 1
   m = m- numberofbrack
   n = brackarray.pop()
   recursivearray.append((n,m))

  i = i+1

 for item in recursivearray:
  lenas = len(alteredstring)
  z = recursive(item[0], item[1], alteredstring)
  alteredstring1 =  alteredstring[0:item[0]]
  alteredstring2 = alteredstring[item[1]:lenas]
  alteredstring =  alteredstring1+z+alteredstring2

 return alteredstring

def recursive(start, end, string):
  y = string[start:end]
  string = y[::-1]
  return string

Could somebody please review above code and provide suggestions and improvements?


texts: Batch file for looking through text files

texts:
I was creating a program and I was trying to explain it to some of my coding friends. They commented that it was too tedious typing out all the "if" commands. How do I streamline this code?
Note: this is a ".bat" program.
Waiter.bat
@echo off
set /p Food="What would you like to eat? "
if /i %Food%==pizza findstr "Pizza" Menu.txt
if /i %Food%==bread findstr "Bread" Menu.txt
if /i %Food%==macaroni findstr "Macaroni" Menu.txt
pause

Using the user input, the batch file looks inside Menu.txt and then it echos that description for that one food item.
Menu.txt
Pizza | Flattened dough, layered with tomato sauce, cheese, and choice of toppings.
Bread | Dough that has been baked.
Macaroni | Macaroni pasta with cheese.


texts:
I'm working on a simple game in which I need to track the cardinal direction of an object. I experimented with using the enum's ordinal value, as well as using switches for the rotation, but both seemed wrong. This is what I ended up with. Is the following an adequate solution?

// Defines cardinal direction
public enum Direction {
    NORTH(0) {
        @Override
        public String getMessage() {
            return getDegrees() + " degrees due north";
        }
    },
    EAST(90) {
        @Override
        public String getMessage() {
            return getDegrees() + " degrees due east";
        }
    },
    SOUTH(180) {
        @Override
        public String getMessage() {
            return getDegrees() + " degrees due south";
        }
    },
    WEST(270) {
        @Override
        public String getMessage() {
            return getDegrees() + " degrees due west";
        }
    };

    private final int degrees;

    public abstract String getMessage();

    private Direction(final int degrees) {
        this.degrees = degrees;
    }

    public int getDegrees() {
        return degrees;
    }

    private static final Map<Integer, Direction> lookup = new HashMap<Integer, Direction>();

    static {
        for (Direction d : EnumSet.allOf(Direction.class))
            lookup.put(d.getDegrees(), d);
    }

    public static Direction get(int degrees) {
        return lookup.get(degrees);
    }

    public Direction rotateRight() {
        return Direction.get((degrees + 90) % 360);
    }

    public Direction rotateLeft() {
        return Direction.get((degrees + 270) % 360);
    }

}


texts:
I have written this code for the question:

  Finding k largest (or smallest) elements in an array

My approach uses a temporary array. Please suggest any improvements for readability or better performance.

public static void kLargest(int[] array, int k){

    if(k < 0 || k > array.length){
        return;
    }
    int[] temp = new int[k];

    for(int i = 0; i < k; i++){
        temp[i] = array[i];
    }
    for(int i = k; i < array.length; i++){
        int min = Integer.MAX_VALUE;
        int minIndex = 0;
        for(int j = 0; j < temp.length; j++){
            if(temp[j] < min){
                min = temp[j];
                minIndex = j;
            }
        }
        if(array[i] > min){
            temp[minIndex] = array[i];
        }
    }
    for(int i : temp){
        System.out.print(i + " ");
    }
}


texts:
what do you think about this code? It's upgraded version of:
Classes representing items in an RPG game

using System;
using System.Collections.Generic;

public class Item
{
    public string Name { get; protected set; }
    public int Cost { get; protected set; }

    public override string ToString()
    {
        return "Name: " + Name + "\nCost: " + Cost;
    }

    public Item(string name, int cost)
    {
        Name = name;
        Cost = cost;
    }
}

public abstract class SpecialItem : Item
{
    public virtual int GetSpecialProperty { get; }
    public override string ToString() { return base.ToString() + "\nDamages/ArmorPts/HungryRestorePts: " + GetSpecialProperty; }
    public SpecialItem(string name, int cost) : base(name, cost) { }
}

public abstract class ElementalsItem : SpecialItem
{
    public int Fire  { get; protected set; }
    public int Water { get; protected set; }
    public int Earth { get; protected set; }
    public int Wind  { get; protected set; }
    public override string ToString()
    {
        return base.ToString()
            + "\nFire Damages/Resistance: " + Fire
            + "\nWater Damages/Resistance: " + Water
            + "\nEarth Damages/Resistance: " + Earth
            + "\nWind Damages/Resistance: " + Wind;
    }
    protected ElementalsItem(string name,
                             int cost,
                             int fire,
                             int water,
                             int earth,
                             int wind)
                             : base(name, cost)
    {
        Fire  = fire;
        Water = water;
        Earth = earth;
        Wind  = wind;
    }
}

public class Weapon : ElementalsItem
{
    public int Damages { get; private set; }
    public override int GetSpecialProperty { get { return Damages; }}
    public override string ToString() { return base.ToString(); }

    public Weapon(string name,
                  int cost,
                  int damages,
                  int fireDamages  = 0,
                  int waterDamages = 0,
                  int earthDamages = 0,
                  int windDamages  = 0)
                  : base(name, cost, fireDamages, waterDamages, earthDamages, windDamages)

    {
        Damages = damages;
    }
}

public class Armor : ElementalsItem
{
    public int ArmorPts { get; private set; }

    public override int GetSpecialProperty { get { return ArmorPts; }}
    public override string ToString() { return base.ToString(); }

    public Armor(string name,
                 int cost,
                 int armorPts,
                 int fireResistance  = 0,
                 int waterResistance = 0,
                 int earthResistance = 0,
                 int windResistance  = 0)
                 : base(name, cost, fireResistance, waterResistance, earthResistance, windResistance)
    {
        ArmorPts = armorPts;
    }
}

public class Food : SpecialItem
{
    public int HungryRestorePts { get; private set; }
    public override int GetSpecialProperty { get { return HungryRestorePts; }}
    public override string ToString() { return base.ToString(); }

    public Food(string name, int cost, int hungryRestorePts) : base(name, cost)
    {
        HungryRestorePts = hungryRestorePts;
    }
}

class Equipment
{
    public static void Test()
    {
        List<Item> items = new List<Item>();
        items.AddRange(new Item[] { new Item("Stone", 1),
                                    new Armor("Steel Helmet", 80, 10),
                                    new Weapon("Great Sword", 120, 80),
                                    new Armor("Storm Cuirass", 1000, 120, 0, 0, 0, 60),
                                    new Weapon("Fire Spear", 1400, 60, 0, 80, 0, 0),
                                    new Food("Apple", 5, 10) });
        foreach(Item i in items)
        {
            Console.WriteLine(i.ToString());
            Console.WriteLine();
        }
    }
}


texts: Using a final class for string constants

texts:
I want to use something like Setting.RES_WIDTH in my code without the need for a getter function (i.e.: custom getter, enum's .name(), .toString() or .valueOf()).

Someone suggested using a final class, so I wrote this:

public final class Setting {

    public final static String RES_WIDTH        = "resolution_width";
    public final static String RES_HEIGHT       = "resolution_height";
    public final static String FULLSCREEN       = "fullscreen_enabled";
    public final static String VSYNC            = "vsync_enabled";

    //Prevent someone from creating an instance of this class
    private Setting() {}
}

This code works, but I am wondering if there are any kind of issues (performance, GC, etc) that might arise from using this.


texts:
Does my code contain anything invalid?

<form name="myForm" id="myForm">

                User ID:
                <input type="text" id="id" />

                Password:
                <input type="password" id="pass" name="pass" />

                <button type="button" class="submit">Submit</button>

<input type="reset" />

</form>


texts: Obtaining a list of files to be re-encoded (ideally determining the encoding just once)

texts:
to_convert_files = [FileEnc(filename, getEncoding(filename)) for
                    filename in filenames if getEncoding(filename) != None]

The problem here is that getEncoding gets called twice for each accepted file name: once in the if clause and once in the expression preceding for. I know I can avoid this by splitting this into a generator expression that does the mapping and a list comprehension that does the filtering, but I was wondering if there is a way keeping it condensed in a one-liner.


texts: Implementing equals(), hashCode(), toString() in the hierarchy like the Optional from Guava

texts:
I have simple hierarchy which looks [a little bit] like the Optional<?> from Guava:

public abstract class Result<T> {

    public static <ResultType> Result<ResultType> get(ResultType result) {
        return new PresentResult(result);
    }

    public static Result<?> absent(Throwable exception) {
        return new AbsentResult(exception);
    }

    Result() {
        // clients of the package can't extend this class
    }

    public abstract boolean isPresent();
    public abstract T get();
    public abstract Throwable getException();
}

class PresentResult<T> extends Result<T> {

    private final T result;

    public PresentResult(T result) {
        this.result = result;
    }

    @Override
    public boolean isPresent() {
        return true;
    }

    @Override
    public T get() {
        return result;
    }

    @Override
    public Throwable getException() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof PresentResult)) {
            return false;
        }
        PresentResult<?> other = (PresentResult<?>) obj;
        return Objects.equal(get(), other.get());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(get());
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("result", get())
                .toString();
    }
}

class AbsentResult extends Result {

    private final Throwable exception;

    public AbsentResult(Throwable exception) {
        this.exception = exception;
    }

    @Override
    public boolean isPresent() {
        return false;
    }

    @Override
    public Object get() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Throwable getException() {
        return exception;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof AbsentResult)) {
            return false;
        }
        AbsentResult other = (AbsentResult) obj;
        return Objects.equal(getException(), other.getException());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getException());
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("exception", getException())
                .toString();
    }
}

But I'm not sure whether I implemented the methods equals(), hashCode(), toString() correctly.

What do you think about them?


texts: C++ shared pointer wrapper for lazy initialization

texts:
I have written a very simple wrapper around std::shared_ptr that supports lazy initialization. Do you see any problems?
#include <functional>
#include <tuple>
#include <utility>

template <class T, typename ... Args>
class LazySharedPtr {
public:
    LazySharedPtr(Args ... args) :
        ptr(nullptr) {
        this->init = [args = std::make_tuple(std::forward<Args>(args) ...)]() mutable {
            return std::apply([](auto&& ... args) {
                return std::make_shared<T>(std::forward<Args>(args) ...);
                }, std::move(args));
        };
    }

    virtual ~LazySharedPtr() = default;

    bool IsInited() const noexcept {
        return ptr != nullptr;
    }

    void Init() {
        this->InitAndGet();
    }

    std::shared_ptr<T> Get() {
        return (ptr) ? ptr : InitAndGet();
    }

    const std::shared_ptr<T> Get() const {
        return (ptr) ? ptr : InitAndGet();
    }

    T* operator ->() {
        return this->Get().get();
    }

    const T* operator ->() const {
        return this->Get().get();
    }

    explicit operator bool() const noexcept {
        return this->IsInited();
    }

protected:
    std::function<std::shared_ptr<T>()> init;
    mutable std::shared_ptr<T> ptr;

    std::shared_ptr<T> InitAndGet() const {
        ptr = this->init();
        return ptr;
    }
};

Note: Visual Studio report warning for this->Get().get():

Warning   C26815  The pointer is dangling because it points at a
temporary instance which was destroyed.

However, I dont see why, because shared_ptr is owned by the class so there should alway be at least one instance "alive". Imho, This warning is not reported by compiler, only by Intellisense.


texts: WaitForSingleObject with windows messages processing

texts:
Is this reliable, or have I missed something?

I want a drop-in replacement for WaitForSingleObject (sans the return type, I like HRESULT much better than any other error codes).

This code works in a plugin DLL for third party closed-source software. I don’t have source code of that app, i.e. if you ask “what else might happen on the same thread while it waits?” the answer is “anything at all”.

constexpr HRESULT E_TIMEOUT = HRESULT_FROM_WIN32( ERROR_TIMEOUT );
constexpr int MSGF_SLEEPMSG = 0x5300;
inline HRESULT getLastHr() { return HRESULT_FROM_WIN32( GetLastError() ); }

// Same as WaitForSingleObject but processes windows messages while it waits.
HRESULT msgWaitForSingleObject( HANDLE h, DWORD ms )
{
    // https://blogs.msdn.microsoft.com/oldnewthing/20060126-00/?p=32513/
    while( true )
    {
        const DWORD started = GetTickCount();
        const DWORD res = MsgWaitForMultipleObjectsEx( 1, &h, ms, QS_ALLINPUT, MWMO_INPUTAVAILABLE );
        if( WAIT_OBJECT_0 == res )
            return S_OK;
        if( WAIT_OBJECT_0 + 1 == res )
        {
            MSG msg;
            while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
            {
                if( msg.message == WM_QUIT )
                {
                    PostQuitMessage( (int)msg.wParam );
                    return S_FALSE; // Abandoned due to WM_QUIT
                }
                if( !CallMsgFilter( &msg, MSGF_SLEEPMSG ) )
                {
                    TranslateMessage( &msg );
                    DispatchMessage( &msg );
                }
            }
            const DWORD elapsed = GetTickCount() - started; //< This works OK even when DWORD overflows: https://codereview.stackexchange.com/a/129670/46194
            if( elapsed > ms )
                return E_TIMEOUT;
            ms -= elapsed;
            continue;
        }
        if( WAIT_TIMEOUT == res )
            return E_TIMEOUT;
        HRESULT hr = getLastHr();
        if( FAILED( hr ) )
            return hr;
        return E_UNEXPECTED;    // Unasked IO_COMPLETION or ABANDONED?
    }
}


texts: JavaScript / jQuery selector value function

texts:
I have the following function which opens a modal and puts some value into a div. It works but the function looks ugly, I hope for improvements (maybe more dynamic).

submitDelete: function() {

    // projects
    $('button[name="removeProj"]').on('click', function(e){
        var $form      = $(this).closest('form'); // closest parent form
        var $id        = $(this).data('id');
        var $title     = $(this).data('title');
        var $createdAt = $(this).data('created-at');
        var $updatedAt = $(this).data('updated-at');
        e.preventDefault();
        if($id != '') {
            $("#prodId").empty().append($id);
        } else {
            $("#prodId").empty().append('-');
        }
        if($title != '') {
            $("#prodTitle").empty().append($title);
        } else {
            $("#prodTitle").empty().append('-');
        }
        if($createdAt != '') {
            $("#prodCreatedAt").empty().append($createdAt);
        } else {
            $("#prodCreatedAt").empty().append('-');
        }
        if($updatedAt != '') {
            $("#prodUpdatedAt").empty().append($updatedAt);
        } else {
            $("#prodUpdatedAt").empty().append('-');
        }
        $('#confirm').modal({ backdrop: 'static', keyboard: false })
        $('#delete').click(function() {
            $form.trigger('submit'); // submit the form
        });
    });


texts:
As regarding the following question I have completed the code as below.

But I am curious about other effective solutions. I am also curious about if there is any solution that could be applicable by using java stream API.

It is not mandatory to keep records at int[][] matrix. Any data structure can be used.

My solution has O(n) time complexity. If you have a better to solve the question please share your solution.

For a given retailer "100" function only needs to return 4 because product 1 exists in other retailers.

Thanks.

public class InterviewQuestion {

 public static void main(String[] args) {
    int[][] itemSeller =       { {1, 100},
                                 {2, 200},
                                 {3, 300},
                                 {4, 100},
                                 {1, 200},
                                 {2, 300} };

    int target = 100;

    getUniqueProduct(itemSeller,target);

}

private static void getUniqueProduct(int[][] itemSeller, int target) {

    int count[] = new int[itemSeller.length];

    for (int i = 0; i < itemSeller.length; i++) {
        count[itemSeller[i][0]]++;
    }

    for (int i = 0; i < itemSeller.length; i++) {
        if (target == itemSeller[i][1]) {

            int item = itemSeller[i][0];
            if (count[item] > 1) {
                continue;
            } else
                System.out.println(item);
        }
    }
}
}


texts: Two click functions doing the same thing with difference the selector

texts:
I have the following jQuery click functions:

$childCheckbox.click(function(){
    if(!$(this).hasClass('checked') && !$parentCheckbox.hasClass('checked')){
        $(this).attr('checked', 'checked').addClass('checked');
        $parentCheckbox.prop('indeterminate',true);
    }
    else if($(this).hasClass('checked')){
        $(this).removeAttr('checked', 'checked').removeClass('checked');
        $parentCheckbox.prop('indeterminate',false);
    }
});

$subparentCheckbox.click(function(){
    if(!$(this).hasClass('checked') && !$parentCheckbox.hasClass('checked')){
        $(this).attr('checked', 'checked').addClass('checked');
        $parentCheckbox.prop('indeterminate',true);
    }
    else if($(this).hasClass('checked')){
        $(this).removeAttr('checked', 'checked').removeClass('checked');
        $parentCheckbox.prop('indeterminate',false);
    }
});

As you can see both are exactly the same with the exception of the "selector". Is there a good way to combine these to minimize code?


texts: What is the fastest way to record the names of each file in a directory?

texts:
I want to fill an array of strings with the name of each directory item. The issue is allocating memory. I either need to count the items before, allocate memory, then go over them again, or I will have to reallocate each iteration of the while loop. Both of these options seem slow. Surely there's a better way.
Which is faster:
char **Names;
DIR *Dir = opendir("Some dir path");
struct dirent *Entry;
unsigned int Count = 0;
while ((Entry = readdir(Dir))) {
    Count++;
}
Names = malloc(Count*sizeof(char*));
closedir(Dir);
Dir = opendir("Some dir path"); //Also, is there a better way to reset it, other than closing it and reopening?
for (int i = 0; (Entry = readdir(Dir); i++) {
    unsigned short NamLen = strlen(Entry->d_name)+1;
    Names[i] = malloc(NameLen);
    memcpy(Names[i], entry->d_name, NameLen);
}

Or
char **Names;
DIR *Dir = opendir("Some dir path");
Dir = opendir("Some dir path");
struct dirent *Entry;
for (int i = 0; (Entry = readdir(Dir); i++) {
    Names = realloc(Names, i*sizeof(char*));
    unsigned short NamLen = strlen(Entry->d_name)+1;
    Names[i] = malloc(NameLen);
    memcpy(Names[i], entry->d_name, NameLen);
}
closedir(Dir);

Please help, I'm stuck. Both of these seem less efficient than optimal, so surely there's a better way. What's the fastest way to record all the names of items in a directory to a string array? Is there a faster option aside these two?


texts: Largest product in a grid - Project Euler 11


texts: setjmp and longjmp implementation in mmix

texts:
I've written an implementation of setjmp and longjmp in MMIX (assuming no name mangling).
I also hand-assembled it.
Are there any mistakes anyone can spot?
    // Memory stack pointer is stored in $254.
    // jmp_buf is rO, next address after setjmp call, memory stack pointer,
    // frame pointer, then possibly other data (for sigsetjmp/siglongjmp).
    // rG is preserved over a longjmp call
    // (not that it should change over one, anyway)
setjmp IS @
    GET    $1,rO            // FE01000A
    STOU   $1,$0,0          // AF010000
    GET    $1,rJ            // FE010004
    STOU   $1,$0,8          // AF010008
    STOU   $254,$0,16       // AFFE0010
    STOU   $253,$0,24       // AFFE0018
    POP    0,0              // F8000000
longjmp IS @
    LDOU   $254,$0,0        // 8FFE0000
    SAVE   $255,0           // FAFF0000
    GET    $1,rG            // FE000013
    // why 15? We save 13 special registers, two local registers,
    // and the number 2, as well as any global registers.
    // That's 256-rG + 16, and we add only 15 because $255 is the address
    // of the saved rGA.
    SETL   $0,271           // E300010F
    SUBU   $1,$1,$0         // 26010100
    SLU    $1,$1,3          // 39000003
    // now $255 is topmost saved register, $255+$1 is bottommost such,
    // $254 is rO after.
    SUBU   $0,$254,$1       // 2600FE01
    LDOU   $2,$255,$1       // 8E02FF01
    STOU   $2,$0,$1         // AE020001
    INCL   $1,8             // E7010008
    PBNZ   $1,@-12          // 5B01FFFD
    SET    $255,$0          // C1FF0000
    UNSAVE 0,$255           // FB0000FF
    // now we have restored rO, but not other stuff
    LDOU   $253,$0,24       // 8FFD0018
    LDOU   $254,$0,16       // 8FFE0010
    LDOU   $0,$0,8          // 8F000008
    PUT    rJ,$0            // F6040000
    POP    2,0              // F8020000

The register stack was the hard part here. Everything between the SAVE and the UNSAVE inclusive is essentially just “set register stack pointer properly”; after that it takes no time at all to fix up the other registers and return.
If you have any other questions, I'm happy to explain my reasons for each tetra of that code.


texts:
In order to learn Rust I'm going through The Rust Book and did the implemented a program for the following exercise:

Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song.

I have decided to use lookup tables for the repeating lines of the song and ordinals because I believe those to be good for performance.
I'd appreciate any comments on my code, especially any suggestions on how to avoid the recurring magic number 12.
type Day = u8;

const LYRICS: [&str; 12] = [
    "a partridge in a pear tree",
    "two turtle doves",
    "three French hens",
    "four calling birds",
    "five gold rings",
    "six geese a laying",
    "seven swans a swimming",
    "eight maids a milking",
    "nine ladies dancing",
    "ten lords a leaping",
    "eleven pipers piping",
    "twelve drummers drumming",
];

const ORDINALS: [&str; 12] = [
        "first",
        "second",
        "third",
        "fourth",
        "fifth",
        "sixth",
        "seventh",
        "eigth",
        "ninth",
        "tenth",
        "eleventh",
        "twelfth",
];

fn main() {
    for day in 0..12 {
        if day != 0 {
            println!();
        }

        print_first_line(day);
        print_lyrics(day);
    }
}

fn print_first_line(day: Day) {
    println!(
        "On the {} day of Christmas my true love gave to me",
        ORDINALS[day as usize],
    )
}

fn print_lyrics(day: Day) {
    for line in (0..=day).rev() {
        if line == 0 && day != 0 {
            println!("And {}", LYRICS[line as usize]);
        } else {
            println!("{}", capitalize(LYRICS[line as usize]));
        }
    }
}

fn capitalize(text: &str) -> String {
    let mut chars = text.chars();

    let mut new_text = String::with_capacity(text.len());

    if let Some(c) = chars.next() {
        new_text.extend(c.to_uppercase());
        new_text.extend(chars);
    }

    new_text
}


texts: Login to bank site and get balance and other details

texts:
I use this piece of JS code to login to my bank and get the balance. This code snippet works, but I wanted to know if I could make this code smaller, faster or if I could anything differently to improve it.

casper.start(url, function() {

    console.log("Checking login status @ " + url);

    this.waitForSelector("form[name='SignonForm']", function() {
        this.fill('form#login', {
            'SignonAccountNumber': username,
            'SignonPassword':  password,
        }, true);
    });
});

casper.then(function() {

    if (/YES/.test(this.getCurrentUrl())) {
        this.thenOpen(this.getCurrentUrl(), function() {
            this.echo("Your balance: " + this.getHTML('#ctl00_wpm_ac_ac_rba_ctl00_dsv'));
        });
    } else {
        this.echo("Looks like the login failed.");
        this.exit()
    }

});


texts:
This is how I implemented the guessing game - chapter 2 of the Rust book: https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html
use std::io;
use std::io::Error;
use std::cmp::Ordering;
use std::num::ParseIntError;

use rand::Rng;

enum MyReadLineError {
    FailReadLine(Error)
}

#[derive(Debug)]
enum MyReadU32Line {
    FailReadLine(Error),
    FailParse(ParseIntError)
}

fn my_read_line() -> Result<String, MyReadLineError> {
    let mut input = String::new();
    let result = io::stdin().read_line(&mut input);
    match result {
        Ok(_) => Ok(input),
        Err(error ) => Err(MyReadLineError::FailReadLine(error)),
    }
}

fn my_read_u32_line() -> Result<u32, MyReadU32Line> {
    match my_read_line() {
        Result::Ok(line) =>
            match line.trim().parse::<u32>() {
                Ok(value) => Ok(value),
                Err(error) => Err(MyReadU32Line::FailParse(error)),
            }

        Result::Err(MyReadLineError::FailReadLine(error)) => Err(MyReadU32Line::FailReadLine(error)),
    }
}

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");
        let guess = my_read_u32_line();
        match guess {
            Ok (value) => match value.cmp(&secret_number) {
                Ordering::Less => println!("Too small!"),
                Ordering::Greater => println!("Too big!"),
                Ordering::Equal => {
                    println!("You win!");
                    break;
                },
            }
            Err (_) => println!("Sorry I couldn't read a u32 from your input! Please try again."),
        }
    }
}

This works as expected but I would like to flatten the matches so that doesn't look at verbose, is that possible. Also is there any other way to make that code look better, more readable?


texts: Simple app to take username and password from the user

texts:
I'm beginner at programming (I guess it's quite obvious)  and this is my small "app" I tried to make, that takes username and password from the user. Could you give me some advice on how can I improve it?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Login
{
    class Program
    {

        static void Main(string[] args)
        {
            Initialization();
        }

        public static void Initialization()
        {
            int x = 0;
            int choice = 0;

            while (x < 2)
            {
                Console.Clear();

                Console.Write("Username: ");
                string username = Console.ReadLine();

                Console.Write("\nPassword: ");
                string password = Console.ReadLine();

                Console.WriteLine();

                string option1 = "Login";
                string option2 = "Exit";

                Console.WriteLine(option1 + "\n" + option2);

                while (x < 2)
                {
                    ConsoleKeyInfo info = Console.ReadKey();
                    if (info.Key == ConsoleKey.UpArrow)
                    {
                        Console.Clear();
                        Console.ResetColor();

                        Console.WriteLine("Username: {0}", username);
                        Console.WriteLine("\nPassword: {0}\n", password);

                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(option1);

                        Console.ResetColor();
                        Console.WriteLine(option2);

                        choice = 1;
                    }
                    else if (info.Key == ConsoleKey.DownArrow)
                    {
                        Console.Clear();
                        Console.ResetColor();

                        Console.WriteLine("Username: {0}", username);
                        Console.WriteLine("\nPassword: {0}\n", password);

                        Console.ResetColor();
                        Console.WriteLine(option1);

                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(option2);
                        choice = 2;

                    }

                    if (info.Key == ConsoleKey.Enter && choice == 1)
                    {
                        if (Login(username, password) == true)
                        {
                            Console.WriteLine("Welcome");
                            x = 2;
                        }
                        else
                        {
                            Console.WriteLine("Wrong password!");
                            Console.ReadLine();
                            break;
                        }

                    }
                    else if (info.Key == ConsoleKey.Enter && choice == 2)
                    {
                        Shutdown();
                    }
                }
            }

        }
        public static void Shutdown()
        {
            Console.ResetColor();
            System.Environment.Exit(0);
        }
        public static bool Login(string username, string password)
        {
            if(username == "asd" && password == "asd")
            {
                Console.WriteLine("Welcome");
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


texts: Animation for android ImageViews acting as game pieces

texts:
My question is about how to achieve a well-performing animation for a set of ImageViews, so that the foreground fades away and the background stays the same.

Currently, I'm writing a clone of "Color Lines" for Android using a GridLayout as a board and ImageViews as game pieces. Every ImageView uses the same (circular) ShapeDrawable:

ImageView ivChild.setImageResource(R.drawable.circle_shape);

where circle_shape.xml looks like this:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">

<gradient
    android:angle="0"
    android:centerColor="#eeeeee"
    android:centerX="0.0"
    android:centerY="0.0"
    android:endColor="#bbbbbb"
    android:startColor="#dddddd"
    android:type="sweep" />
</shape>

and another drawable resource as a background to get a board with tiles separated by thin lines (I'm using a rectangle shape with a color gradient and set a margin to the ImageViews).

To show the differently colored items as well as the empty fields, I simply use setColorFilter() with different color resources (#00000000 for empty fields)

Every time the user completes a line of five or more items with the same color, I want to show an animation (color fading away) instead of just setting the color to transparent. I could simply use a ViewAnimation (alpha) if the whole View was to fade away but as I said I need to keep the background unchanged and just animate the foreground.

The following method is part of the Fragment which is hosting the board:

void clearPositions(int[] completedLinesPositions, color)
{
    ImageView[] fields = new ImageView[completedLinesPositions.length];
    for (int i = 0; i < completedLinesPositions.length; i++)
    {
        // board is the GridLayout
        fields[i] = (ImageView) board.getChildAt(positions[i]);
    }

    ValueAnimator animation = ValueAnimator.ofObject(new FloatEvaluator(), 1.0f, 0f);

    ValueAnimator.AnimatorUpdateListener myUpdateListener = new MyAlphaUpdateListener(fields, color);

    animation.addUpdateListener(myUpdateListener);
    animation.setDuration(200);
    animation.start();

    int empty = Color.argb(0, 0, 0, 0);
    for (ImageView iv: fields )
    {
        iv.clearColorFilter();
        iv.setColorFilter(empty, PorterDuff.Mode.MULTIPLY);
    }
}

The MyAlphaUpdateListener:

public class MyAlphaUpdateListener implements     ValueAnimator.AnimatorUpdateListener {

    private ImageView[] imageViews;
    private int red, blue, green;

    MyAlphaUpdateListener(ImageView[] ivs, int color) {
        imageViews = ivs;
        red = Color.red(color);
        green = Color.green(color);
        blue = Color.blue(color);
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        Object o = animation.getAnimatedValue();
        int newalpha = (int) (255 * (float) o);
        int newColor = Color.argb(newalpha, red, green, blue);

        for (ImageView imageView : imageViews) {
            imageView.clearColorFilter();
            imageView.setColorFilter(newColor, PorterDuff.Mode.MULTIPLY);
        }

    }
}

As you can imagine, this will run quite often so I'd like to achieve a good performance. There seem to be no skipped frames but I also want to be as easy on the battery as possible. Is there anything I can do to reduce CPU time?


texts:
I'm new to programming and want to check if I'm using best coding practices in my program.

package scott.TicTacToe.main;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class TicTacToe implements ActionListener{
    private JFrame window = new JFrame("Tic-Tac-Toe");
    private JButton[] buttons = new JButton[9];
    private String letter = "";
    private int count = 0;
    private boolean win = false;

    public TicTacToe(){
        window.setSize(300, 300);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new GridLayout(3, 3));

        for(int i = 0; i < 9; i++){
            buttons[i] = new JButton();
            window.add(buttons[i]);
            buttons[i].addActionListener(this);
        }

        window.setVisible(true);

    }

    public void actionPerformed(ActionEvent event) {

        count++;
        if(count % 2 != 0){
            letter = "X";
        } else {
            letter = "O";
        }

        for(int i = 0; i < 9; i++){
            if (event.getSource() == buttons[i]){
                buttons[i].setText(letter);
                buttons[i].setEnabled(false);
            }

            //Horizontal Wins
            if(buttons[0].getText().equals(buttons[1].getText()) && buttons[1].getText().equals(buttons[2].getText()) && !buttons[0].getText().equals("")){
                win = true;
            } else if (buttons[3].getText().equals(buttons[4].getText()) && buttons[4].getText().equals(buttons[5].getText()) && !buttons[3].getText().equals("")){
                win = true;
            } else if (buttons[6].getText().equals(buttons[7].getText()) && buttons[7].getText().equals(buttons[8].getText()) && !buttons[6].getText().equals("")){
                win = true;
            }

            //Vertical Wins
            else if(buttons[0].getText().equals(buttons[3].getText()) && buttons[3].getText().equals(buttons[6].getText()) && !buttons[0].getText().equals("")){
                win = true;
            } else if(buttons[1].getText().equals(buttons[4].getText()) && buttons[4].getText().equals(buttons[7].getText()) && !buttons[1].getText().equals("")){
                win = true;
            } else if(buttons[2].getText().equals(buttons[5].getText()) && buttons[5].getText().equals(buttons[8].getText()) && !buttons[2].getText().equals("")){
                win = true;
            }

            //Diagonal Wins
            else if(buttons[0].getText().equals(buttons[4].getText()) && buttons[4].getText().equals(buttons[8].getText()) && !buttons[0].getText().equals("")){
                win = true;
            } else if(buttons[6].getText().equals(buttons[4].getText()) && buttons[4].getText().equals(buttons[2].getText()) && !buttons[6].getText().equals("")){
                win = true;
            } else {
                win = false;
            }

            if(win == true){
                JOptionPane.showMessageDialog(null, letter + " wins!");
            } else if(count == 9){
                JOptionPane.showMessageDialog(null, "It's a draw!");
                count = 0;
            }
        }

    }

    public static void main(String[] args) {

        new TicTacToe();

    }

}


texts:
I'm new to Rust and am working through the exercises found on the bottom of this page. The function below converts a string into pig latin. The requirements are as follows.

  Convert strings to Pig Latin, where the first consonant of each word
  is moved to the end of the word with an added “ay”, so “first” becomes
  “irst-fay”. Words that start with a vowel get “hay” added to the end
  instead (“apple” becomes “apple-hay”).

I would like to ensure that my code is as idiomatic as possible, specifically in the string manipulation area. Behold.

fn pigify(text: &str) -> String {
    let map_func = |word: &str| -> String {
        let mut chars = word.chars();
        let first_char = chars.next().unwrap();
        match first_char {
            'a' | 'e' | 'i' | 'o' | 'u' => String::from(word) + "-hay",
            _ => {
                let mut xform = String::new();
                for ch in chars {
                    xform.push(ch);
                }
                xform.push('-');
                xform.push(first_char);
                xform.push_str("ay");
                xform
            }
        }
    };

    let folder = |current: String, next: String| -> String {
        let mut this_str = String::new();
        this_str.push_str(&current);
        if !current.is_empty() {
            this_str.push(' ');
        }
        this_str.push_str(&next);
        this_str
    };

    text.split_whitespace()
        .map(map_func)
        .fold(String::new(), folder)
}


texts:
I want to design API which could handle XPATH input from a user. I currently model the XPATH input in the following way:

public interface ICondition {
    String getConditionString();
}

public class XPathCondition implements ICondition {

    private Class<? extends XPATHFunction> clazz = null;

    private Operator operator = null;

    private String compValue = null;

    private String param = null;

    public void setXPathFunction(Class<? extends XPATHFunction> clazz) {
        this.clazz = clazz;
    }

    public void setComparisionType(Operator operator) {
        this.operator = operator;
    }

    public void setComparisionValue(String value) {
        this.compValue = value;
    }

    public void setParam(String param) {
        this.param = param;
    }

    public String getConditionString() {
        XPATHFunction function = null;
        try {
            function = (XPATHFunction) clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return function.call(param) + operator.getOprValue() + compValue;
    }

    public static void main(String[] args) {
        XPathCondition xpathCond = new XPathCondition();
        xpathCond.setXPathFunction(CountFunction.class);
        xpathCond.setParam("/CPRRegistrationInfo/*");
        xpathCond.setComparisionType(Operator.GT);
        xpathCond.setComparisionValue("0");
        System.out.println(xpathCond.getConditionString());
    }
}

public interface XPATHFunction {

    public String call(String param);

}

public class CountFunction implements XPATHFunction {

    public String call(String param) {
        return "count(" + param + ") ";
    }

}

There could be other XPATH functions which have to implement and interface XPATHFunction and implement it in its way. The API just has to create XPATHCondition and set appropriate functions and call the getConditionString() method to get the final xpath.

Is there any better way in which I can model XPATH input?


texts:
I attempted to define Penultimate, i.e. a type class for shapeless.HList's that have a second to last element.

import shapeless.{HList, HNil, ::}

object Penultimate {
  type Aux[L <: HList, O] = Penultimate[L] { type Out = O }

  def apply[H <: HList](implicit ev: Penultimate[H]) = ev

  implicit def secondToLast[H, G]: Aux[H :: G :: HNil, H] =
    new Penultimate[H :: G :: HNil] {
      override type Out = H
      override def apply(in: H :: G :: HNil): Out = in.head
    }

  implicit def inductive[H, T <: HList, OutT](
     implicit penult: Aux[T, OutT]
  ): Penultimate[H :: T] = new Penultimate[::[H, T]] {

    override type Out = OutT

    override def apply(in: H :: T): Out = penult.apply(in.tail)
  }
}

trait Penultimate[H <: HList] {
  type Out
  def apply(in: H): Out
}

It appears to work:

scala> Penultimate[Int :: Int :: HNil]
res1: net.Penultimate[shapeless.::[Int,shapeless.::[Int,shapeless.HNil]]] = net.Penultimate$$anon$1@3c37902d

scala> Penultimate[Int :: HNil]
<console>:16: error: could not find implicit value for parameter ev: net.Penultimate[shapeless.::[Int,shapeless.HNil]]
       Penultimate[Int :: HNil]
                  ^

scala> Penultimate[HNil]
<console>:16: error: could not find implicit value for parameter ev: net.Penultimate[shapeless.HNil]
       Penultimate[HNil]
                  ^

But, is it a valid implementation of Penultimate? If not, what flaws does it have?