texts:
I have this code that is working fine but it's taking pretty much 100% of my cpu to run and it takes around 25min. I'd really like to optimize it but don't know what parts I could improve.

The main problem I guess is that I'm using coordinates of a file to be compared with a 3,5GB file.
So I tried putting the information of this 3,5GB file in a hash to make it faster but it's not what I thought it would be.
I want to compare exon coordinates to the whole human genome (hg38), see which two letters are before the exon position and which two are in the end, so that would count as an intron. Then, for each intron I want to see if those two letters are compatible with GUAG or not.

#!/usr/bin/perl
use warnings;
use strict;

print "Enter file path (refGene)\n";
my $ref_gene = <>;
chomp ($ref_gene);
my $local1 = "./$ref_gene";

print "Enter file path (hg38)\n";
my $filename = <>;
chomp ($filename);
my $local2 = "./$filename";

open (HG, $local2) or die "error opening $filename\n";

my %chromosome;
my $key;
while (my $line = <HG>) {
    chomp ($line);
    if ($line =~ /^\>/) {
        $key = $line;
        $key =~ s/\>//;          # / stop editor red coloring
        $chromosome{$key} = "";
    }
    else {
        $chromosome{$key} .= uc $line;
    }}

close (HG);

open (REFGENE, $local1) or die "error opening $ref_gene\n";

my $total_introns = 0;
my $GUAG_introns = 0;
while (my $line = <REFGENE>) {
    my @column = split ("\t", $line);
    my $chr = $column[2];
    my $sense = $column[3];
    my $number_exons = $column[8];
    my $beginning_of_exon = $column[9];
    my $end_of_exon = $column[10];

    my @beginning_exons = split (",", $beginning_of_exon);
    my @end_exons = split (",", $end_of_exon);
    foreach my $element (@end_exons) { #subtract 1 from end of exon because its 1-based index
        $element -= 1;
    }

    my $introns = ($number_exons - 1); #amount of introns = exons - 1
    $total_introns += $introns;

    my $current_seq = $chromosome{$chr};

    for (my $i=0; $i<@beginning_exons-1; $i++) {
        my $end = substr ($current_seq, $end_exons[$i]+1, 2); #get two letters after end of exon
        my $beginning = substr ($current_seq, $beginning_exons[$i+1]-2, 2); #get two letters before beggining of exon

        if ($sense eq "+") {
            if ( ($end eq "GT") && ($beginning eq "AG") ) {
            $GUAG_introns += 1;
            }}

        elsif ($sense eq "-") {

            if ( ($end eq "CT") && ($beginning eq "AC") ) {
                $GUAG_introns += 1;
            }}}
}

close (REFGENE);

my $GUAG = (($GUAG_introns/$total_introns)*100); #percentage of GUAG introns
print "number of GUAG introns = $GUAG_introns \n total introns = $total_introns \n";
print " $GUAG% of GT-AG introns.\n\n";

exit;

input

717     NM_000525       chr11   -       17385248        17388659        17386918        17388091        1       17385248,       17388659,
987     NM_000242       chr10   -       52765379        52771700        52768136        52771635        4      52765379,52769246,52770669,52771448,    52768510,52769315,52770786,52771700,

The two letters before the exon position would be AG or the last two letters of an intron

column 9 has the coordinates to the start of an exon and column 10 to the end, I'm trying to get the things in the middle and see if they start with GT and end with AG. Column 3 is the sense of the sequence, so if it's negative (-) instead of looking for GUAG (U cause it's RNA in the end but the reference(hg38) is T) I'll be looking for the reverse complement (AC instead of GT, and CT instead of AG). Column 2 is the chromosome, so for chromosome 6 I'd look the reference in hg38 for chromosome 6 and count the introns. The other file is 15MB

I know it's a lot of code and that nobody will download 3,5GB of human genome to run this but I'd like to know which kind of improvements I can do to optimize the code and not use 100% of cpu.

I put a small part of the input file and the hg38.


texts:
I tend to include something like the following in small and medium-sized Python projects, either at the top of the executable or as logger.py:

import logging
import sys

logger = logging.getLogger(__name__)
stoh = logging.StreamHandler(sys.stderr)
fmth = logging.Formatter("[%(levelname)s] %(asctime)s %(message)s")
stoh.setFormatter(fmth)
logger.addHandler(stoh)
logger.setLevel(logging.DEBUG)

Then import logger from logger (as needed), and proceed to make calls throughout the project like logger.level('message').

Are there any obvious (or non-obvious) red flags or anti-patterns with this approach?


texts:
I recently wrote this JavaScript algorithm for removing duplicates from an array as part of a job interview process, but was turned down for the position after submitting the code. I didn't receive any detailed feedback from the company, so I was wondering if a more experienced developer might be able to explain what I've done wrong here.

dedup = function(set){
    //loop over function, removing second instance of matching values
    for (var i = 0; i < set.length; i++){
        for (var j = i+1; j < set.length; j++){
            if (set[i] == set[j]){
                set.splice(j,1);
                i--;
            }
            //special case for objects
            if (typeof set[j] == 'object' && typeof set[i] == 'object')
                {
                //super special case for arrays
                if (Array.isArray(set[j]) && (Array.isArray(set[i])))
                {
                    if ( set[j].toString() == set[i].toString() )
                        { set.splice(j,1);
                        i-- }
                }
                //loop over key-value pairs in sets of objects
                else {
                    var firstObj = set[i];
                    var secondObj = set[j];
                    for (var key in firstObj){
                        //break loop if differences found
                        if (firstObj.hasOwnProperty(key) == false) {
                            break
                        }
                        else if (firstObj[key] != secondObj[key]){
                            break
                            }
                        else {
                            set.splice(j,1);
                            i--
                            break
                        }
                    }
                }
            }
        }
    }
    return set
}

console.log(dedup([1, 2, 2, 5, 2, 7, 3, 9, 1, 9]))
// -> [1, 2, 5, 7, 3, 9]

console.log(dedup([1, '1', 2, 0, false, true]))
// -> [1, '1', 2, 0, false, true]

console.log(dedup([8, 3, [1, 2], [1, 2, 3], [1, 2], [2, 1], true]))
// -> [8, 3, [1, 2], [1, 2, 3], [2, 1], true]

console.log(dedup([1, {a: 'b', c: 'd'}, {c: 'd', a: 'b'}, {e: 'f'}, 'b']))
// -> [1, {a: 'b', c: 'd'}, {e: 'f'}, 'b']

I've found the following possible problems:

Running time is \$\mathcal{O}(n^2)\$ - there may be a recursive algorithm which removes duplicates more effectively than nested for loops.
Code should be refactored rather than all in on big function.

I would greatly appreciate any thoughts on the problems that I've identified, or other issues with my code.


texts: Check Digit Calculator & GTIN-8 Validator

texts:
This program calculates the 7th digit of a GTIN-8 barcode and calculates the validity of an 8 digit GTIN-8 barcode. Could I simplify my code any further?

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

def doMaths(number):
     count = 0
     total = 0
     for n in number:
          n = int(n)
          if count %2 == 0:
               total += n * 3
          else:
               total += n
          count += 1
     if len(number) == 8:
          if total %10 == 0:
               print("Valid")
          else:
               print("Invalid")
     else:
          print(number + str(roundup(total)  - total))

while True:
     try:
          number = input("Enter a 7 or 8 digit number for testing: ")
          i = int(number)
          if len(number) == 7 or len(number) == 8:
               doMaths(number)
               break
          else:
               print("Length of number must be 7 or 8")
               continue
     except ValueError:
          print("Only enter numbers.")
          continue


texts:
[Bindable]
public class ProductsCache
{
    private static var _products:ArrayCollection;

    public function get products():ArrayCollection{
        return _products;
    }
    public function set products(value:ArrayCollection):void{
        _products = value;
    }
}

By the name of the class you see my intentions with this bit of code. I intend to set a "cache" of registries that I intend to use across modules and update accordingly. The get method is used for dropdown lists, the set method after a successful insert statement.

This works good for my needs. But I still need your feedback.

EDIT: I don't know what voting means here. Is this good code for its purpose? or do I really need to learn factories and dependency injections?

I was previously using a singleton for this, but I wasn't comfortable with that, I want to keep the singleton excusively for credential and config data. And use this for the rest of the app functionality.


texts:
Recently, I've been doing more and more Batch "programming".

I always find myself in the need to extract a file and do something with the files.
This is not my first version, and a few non-general-purpose were written.

However, I've re-written it all to be general-purpose.

:extractfile
REM extracts the file with whichever program is available
REM %1 = file to extract, %2 = optional target for extraction, %3 = log file path
REM exit: 0 = extracted, 1 = not found, 2 = failed, 3 = no program
set "extractfile="
setlocal EnableDelayedExpansion
set "folder=%~dp1"
set "file=%~nx1"
set "filename=%~n1"

IF NOT EXIST "!folder!!file!" (
    exit /b 1
)

set "target=%~dp2"
IF "!target!" EQU "" (
    SET "target=!folder!!filename!\"
)

REM set "LOG=%~dpnx3"
REM https://codereview.stackexchange.com/questions/208756/function-to-extract-a-file-in-batch#comment405176_208756
IF "%~3" EQU "" (
    set "LOG=nul"
) else (
    set "LOG="%~dpnx3""
)

set "CMD="

echo === COMPRESSED FILE EXTRACTION === >> !LOG!

REM yeah, not pretty, but the %ProgramFiles(x86)% causes syntax errors
FOR %%d IN ("%ProgramFiles%" "%ProgramFiles(x86)%") DO IF "!CMD!" EQU "" (
    set "DIR=%%d"
    IF "!DIR!" NEQ "" (
        set "DIR=!DIR:"=!"
        IF EXIST "!DIR!\7-Zip\7z.exe" (
            REM https://stackoverflow.com/q/14122732
            set "CMD="!DIR!\7-Zip\7z.exe" x "!folder!!file!" -bd -y -o"!target!\""
        ) ELSE IF EXIST "!DIR!\WinRAR\winrar.exe" (
            REM https://stackoverflow.com/a/19337595
            set "CMD="!DIR!\WinRAR\winrar.exe" x -ibck "!folder!!file!" *.* "!target!\""
        ) ELSE IF EXIST "!DIR!\winzip\wzzip.exe" (
            REM http://kb.winzip.com/kb/entry/125/ - WZCLINE.CHM
            set "CMD="!DIR!\winzip\wzzip.exe" -d "!folder!!file!" "!target!\""
        )
    )
)

IF "!CMD!" EQU "" (
    echo Error 3: Extraction failed, no program found >> !LOG!
    echo === COMPRESSED FILE EXTRACTION FINISHED === >> !LOG!

    exit /b 3
)

echo Extracting using command: >> !LOG!
echo !CMD! >> !LOG!
call !CMD! >> !LOG! 2>&1

IF ERRORLEVEL 1 (
    echo Error 2: Extraction failed with error %ERRORLEVEL% >> !LOG!
    echo === COMPRESSED FILE EXTRACTION FINISHED === >> !LOG!

    exit /b 2
)

echo === COMPRESSED FILE EXTRACTION FINISHED === >> !LOG!

endlocal & set "extractfile=!target!\"
goto :eof

This function uses the available program to extract the file and "returns" the path to the folder.

Assuming the following basic example:

call :extractfile a.zip abc
echo %extractfile%

This should output something like c:\[...]\abc on success.
Also responds with the following error codes:

0: extraction succeeded
1: file not found
2: extraction failed
3: couldnt find a suitable program to extract

If the 2nd argument isn't passed, it is supposed to create a sub-folder with everything inside.

(You can see this in action in https://github.com/ismael-miguel/bnsbuddy_mod_installer/blob/master/mod_installer.bat)

I've tried to keep it as DRY as possible, and as short as I could.

Is there anything I've missed or that I should improve?


texts: Converting Decimals to Fractions with JavaScript - Simplify & Improve

texts:
I wrote a simple script that converts a decimal to a mixed number, proper, or improper fraction depending on the inputed decimal.

It works but I think it could be improved as it hangs when large decimals are used. Please review and let me know how I could improve and simplify it. Thanks.

My script on JS Bin: http://jsbin.com/axulob/1/edit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>


texts: Storing values from checkboxes in database

texts:
I'm getting values from 2 checkboxes and save those values to a database.

I don't like these if statements. How is it possible to simplify the code?

def edit_user(request, user_id):

user = User.objects.get(id=user_id)

if request.POST:

    if request.POST.get('is_staff'):
        user.is_staff = True
    else:
        user.is_staff = False

    if request.POST.get('is_active'):
        user.is_active = True
    else:
        user.is_active = False

    user.save()

    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))


texts:
Taking the payload below, I need to output the average of each reading.

For example the readings for key 2 are 1, 4, 7.  The average is (1+4+7)/3 = 4.

The data is formatted in multi-dimensional arrays, such that each sub-array contains pairs with a key and a reading value. For example:

[
  [
    [2, 1],
    [4, 2],
    [6, 3]
  ],
  [
    [2, 4],
    [4, 5],
    [6, 6]
  ],
  [
    [2, 7],
    [4, 8],
    [6, 9]
  ]
]

The final result should be:

[
[2, 4],
[4, 5],
[6, 6]
]

My effort so far seems to work.

const payload = [
  [
    [2, 1],
    [4, 2],
    [6, 3]
  ],
  [
    [2, 4],
    [4, 5],
    [6, 6]
  ],
  [
    [2, 7],
    [4, 8],
    [6, 9]
  ]
]

const result = payload.reduce((accumulator, currentValue, currentIndex, array) => {

    if(currentIndex === 0){
        return accumulator
    }
    return currentValue.reduce((a, c, i) => {
        accumulator[i][1] += c[1]
        return accumulator
    }, accumulator)

 }).map((currentValue, index, array) => {
    return [currentValue[0], currentValue[1] / array.length]
})


texts: Hex encoding and decoding of ASCII strings in VBA

texts:
I needed to convert some Ascii text to binary in Hex format 0x00FF....

I've written an EncodeHex and a DecodeHex function to do the conversion.

I've avoided using concatenation in favour of performance.

I'm assuming that assigning the results of CByte("&h80") to a byte array, and then using StrConv to convert the array to a Unicode string, is more efficient than assigning the results of Chr$("&h80") to a string array, and then using Join to concatenate the strings.

I need to use this in Excel, so I'm using CVErr(xlErrValue) to return errors, but this could maybe benefit from being more generic.

Sample usage

?HexEncode("FooBar")
0x466F6F426172
?HexDecode("0x466F6F426172")
FooBar

VBA Code

Option Explicit

Const HEX_STRING_PREFIX As String = "0x"
Const VBA_HEX_PREFIX As String = "&h"

Public Function HexEncode(AsciiText As String, Optional HexPrefix As String = HEX_STRING_PREFIX) As String

  If AsciiText = vbNullString Then

    HexEncode = AsciiText

  Else

    Dim asciiChars() As Byte
    asciiChars = StrConv(AsciiText, vbFromUnicode)

    ReDim hexChars(LBound(asciiChars) To UBound(asciiChars)) As String

    Dim char As Long
    For char = LBound(asciiChars) To UBound(asciiChars)
      hexChars(char) = Right$("00" & Hex$(asciiChars(char)), 2)
    Next char

    HexEncode = HexPrefix & Join(hexChars, "")
  End If

End Function

Public Function HexDecode(HexString As String, Optional HexPrefix As String = HEX_STRING_PREFIX)

  'Check if there's anything to decode

  If HexString = vbNullString Then
    HexDecode = vbNullString
    Exit Function
  Else

    If Not StrComp(Left$(HexString, Len(HexPrefix)), HexPrefix, vbTextCompare) = 0 Then
      'Unexpected string format
      GoTo DecodeError
    End If

    Dim hexRaw As String
    hexRaw = Mid$(HexString, 1 + Len(HexPrefix))

    'Check if the string is valid for decoding
    If Len(hexRaw) Mod 2 = 1 Then
      GoTo DecodeError
    End If

    Dim numHexChars As Long
    numHexChars = Len(hexRaw) / 2

    ReDim hexChars(0 To numHexChars - 1) As Byte
    Dim char As Long
    For char = 0 To numHexChars - 1
      Dim hexchar As String
      hexchar = VBA_HEX_PREFIX & Mid$(hexRaw, 1 + char * 2, 2)
      'Check if the hex-pair is actually hex
      If Not IsNumeric(hexchar) Then
        GoTo DecodeError
      End If
      hexChars(char) = CByte(hexchar)
    Next char
    'Return the concatenated bytes as a string
    HexDecode = StrConv(hexChars, vbUnicode)

  End If

SafeExit:
  Exit Function

DecodeError:
  HexDecode = CVErr(xlErrValue)

End Function


texts:
I build this simple function, trying to use PEP 8 Style, something that I discovered recently thanks to this previous question.
The function works, but I was wondering if there is a better way to do it.
import datetime

def quarter_values_builder():
    """A function that returns an array
    with all the actual year quarters
    """
    now = datetime.datetime.now()
    year = now.year
    year_str = str(year)
    quarter_values = ["31/03/","30/06/","30/09/","31/12/"]
    quarter_values_now = [x+year_str for x in quarter_values]

    return quarter_values_now

current_quarters_string = quarter_values_builder()
print(current_quarters_string)


texts:
Is my implementation correct (it is matching this result)? How can I improve this code?

public class Parzen
{
    public static double Variance(IEnumerable<double> source)
    {
        double avg = source.Average();

        double d = source.Aggregate(0.0, (total, next) => total += Math.Pow(next - avg, 2));

        return d / (source.Count() - 1);
    }

    private static double GausianFunction(double x1, double x, double sigma2)
    {
        double up = Math.Pow(x1 - x, 2);

        double dw = 2 * sigma2;

        double firstPart = 1 / Math.Sqrt(2 * Math.PI * sigma2);

        double ret = firstPart * Math.Exp((-1) * (up / dw));

        return ret;
    }

    public static double PrazenWindowDensity(double [][] Xn, double x, double sigma2)
    {
        double gauss = 0;

        foreach(double [] arr in Xn)
        {
            foreach (double item in arr)
            {
                double xx = GausianFunction(item, x, sigma2);
                gauss += xx;
            }
        }

        return gauss / Xn.Sum(xy => xy.Length); ;
    }
}

public class Program
{
    static void Main(string[] args)
    {
        double[][] mat =
        {
            new double[]{2, 2.5},
            new double[]{3, 1},
            new double[]{6}
        };

        //double sigma2 = Parzen.Variance(mat.Cast<double>().ToList());

        double den = Parzen.PrazenWindowDensity(mat, 3, 1);

        string str = string.Empty;
    }
}


texts:
I've written a custom Error handler for use in PHP. What it does is simply capture PHP errors, and logs them using Monolog.

It works, but I can't help that it has too much stuff inside. I could remove the error levels that are not handled by set_error_handler but that's guaranteed to lead to a developer that spends 2 hours wondering "why E_ERRORs are not getting logged"...

Could this function be improved somehow?

set_error_handler(function($errno ,$errstr,$errfile ,$errline, $errcontext) {
    // When we use the error supressing operator (@)
    // error_reporting is temporarily set to 0
    // Do not log anything for that case
    if(ini_get('error_reporting')==0){return;}

    $halt = FALSE;
    // http://php.net/manual/en/errorfunc.constants.php
    switch($errno){
        case E_USER_ERROR:
        case E_RECOVERABLE_ERROR:
            $halt = true;
            $logType = 'error';
            break;

        case E_WARNING:
        case E_USER_WARNING:
        case E_STRICT:
        case E_DEPRECATED:
            $logType = 'warning';
            break;

        case E_NOTICE:
        case E_USER_NOTICE:
            $logType = 'notice';
            break;

            // The following error types cannot be caught by set_error_handler
            // Adding them for reference only
        case E_CORE_WARNING:
        case E_COMPILE_ERROR:
        case E_COMPILE_WARNING:
        case E_CORE_ERROR:
        case E_ERROR:
        case E_PARSE:
            return FALSE;

        // We should never reach this case. But you never know
        case E_ALL:
        default:
            $logType = 'warning';
    }
    Logger::{$logType}($errstr, $errcontext);
    // Halt the execution for errors that should halt
    if($halt)
        exit($errno);
});


texts: REST Server for Users using Restify and Mongoose

texts:
I am creating a REST API to access a database of users. I am new to Node.js and developing REST APIs in general. I am also trying to use best security practices.

main.js

var fs = require('fs');
var restify = require('restify');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

mongoose.connect('localhost', 'nodejs-sample');

var User = require('./models/user')

// SSL options
var options = {
  certificate: fs.readFileSync('./ssl/cert.pem'),
  key: fs.readFileSync('./ssl/key.pem')
}

var server = restify.createServer(options);

server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());

server.get('/users', function(req, res) {
  User.find(function(err, users) {
    if (err) {
      res.send(err);
    }

    res.json(users);
  });
});

server.post('/users', function(req, res) {
  bcrypt.hash(req.body.password, 10, function(err, hash) {
    if (err) {
      res.send(err);
    }

    User.create({
      username: req.body.username,
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      hash: hash
    }, function(err) {
      if (err) {
        res.send(err)
      }

      res.json({message: 'User added'});
    });
  });
});

server.get('/users/:user_id', function(req, res) {
  User.findById(req.params.user_id, function(err, user) {
    if (err) {
      res.send(err);
    }

    res.json(user);
  });
});

server.put('/users/:user_id', function(req, res) {
  var body = req.body;
  if (body.password) {
    bcrypt.hash(body.password, 10, function(err, hash) {
      if (err) {
        res.send(err);
      }

      delete body.password;
      body.hash = hash;
      User.update({_id: req.params.user_id}, body, function() {
        res.json({message: 'User updated'});
      });
    });
  } else {
    User.update({_id: req.params.user_id}, body, function() {
      res.json({message: 'User updated'});
    });
  }
});

server.del('/users/:user_id', function(req, res) {
  User.findByIdAndRemove(req.params.user_id, function(err) {
    if (err) {
      res.send(err);
    }

    res.json({message: 'User deleted'});
  });
});

server.listen(process.env.PORT || 8080, function() {
  console.log('%s listening at %s', server.name, server.url);
});

models/user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  first_name: {
    type: String,
    required: true
  },
  last_name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  hash: {
    type: String,
    required: true
  }
});

// remove hash from JSON output
UserSchema.methods.toJSON = function() {
  var obj = this.toObject();
  delete obj.hash;
  return obj;
};

UserSchema.methods.verifyPassword = function(password, cb) {
  bcrypt.compare(password, this.hash, function(err, res) {
    if (err) {
      return cb(err);
    }

    cb(null, res);
  });
};

module.exports = mongoose.model('User', UserSchema);


texts: Changing visibility of ToolbarItem - Xamarin.Forms

texts:
I want to fill collection of ToolbarItems from XAML, but change visibility of some ToolbarItem from view model.

I implemented BasePage with some wrapper around ToolbarItems collection:

public class BasePage : ContentPage
{
    public IList<CustomToolbarItem> CustomToolbar { get; private set; }

    public BasePage()
    {
        var items = new ObservableCollection<CustomToolbarItem>();
        items.CollectionChanged += ToolbarItemsChanged;

        CustomToolbar = items;
    }

    private void ToolbarItemsChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        ToolbarItems.Clear();

        foreach (var item in CustomToolbar)
        {
            item.PropertyChanged += OnToolbarItemPropertyChanged;
            if (item.IsVisible)
            {
                ToolbarItems.Add(item);
            }
        }
    }

    private void OnToolbarItemPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == CustomToolbarItem.IsVisibleProperty.PropertyName)
        {
            UpdateToolbar();
        }
    }

    private void UpdateToolbar()
    {
        foreach (var item in CustomToolbar)
        {
            if (item.IsVisible)
            {
                ToolbarItems.Add(item);
            }
            else
            {
                ToolbarItems.Remove(item);
            }
        }
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();

        ToolbarItems.Clear();
        CustomToolbar.Clear();
        foreach (var item in CustomToolbar)
        {
            item.PropertyChanged -= OnToolbarItemPropertyChanged;
        }
    }
}

CustomToolbarItem.cs:

public class CustomToolbarItem : ToolbarItem
{
    public static readonly BindableProperty IsVisibleProperty =
            BindableProperty.Create(nameof(IsVisible),
                                    typeof(bool),
                                    typeof(CustomToolbarItem),
                                    true);
    public bool IsVisible
    {
        get { return (bool)GetValue(IsVisibleProperty); }
        set { SetValue(IsVisibleProperty, value); }
    }
}

How I use it in XAML:

<local:BasePage x:Name="Page"
            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:local="clr-namespace:ToolbarExtensionSample;assembly=ToolbarExtensionSample"
            x:Class="ToolbarExtensionSample.SubPage">

  <local:BasePage.CustomToolbar>
    <local:CustomToolbarItem Name="Alloha"
                             IsVisible="{Binding IsItemVisible, Source={x:Reference Page}}"/>
  </local:BasePage.CustomToolbar>

  <Button Text="Click!"
          Clicked="OnButtonClicked"/>
</local:BasePage>

My code is working, but I'm wondering is it okay for performance? Maybe, exists some better solution.
Thanks in advance for suggestions to improvements or better approaches.


texts: Creating API clients that are "async agnostic"

texts:
Python3's async/await syntax is great, but it does create a divide between libraries which are async-based and those which are not. For example, boto3 (AWS API library) currently doesn't work with async. There is a separate project, aiobotocore, attempts to recreate some of this functionality in an async context.

I have been thinking for a while about how to create HTTP API clients which can be run async and sync contexts. I have come up with a strategy that involves creating a separation between the logic (preparation of requests, interpretation of responses), and the sending. The logic is implemented as a generator function, which yields out an object which represents the request, and receives back an object representing the response. This generator is "run" by a runner function, which does the actual sending, and may be sync or async.

You can imagine that if, for example, boto3 had been written this way, it would be easy to re-use the bulk of the code to make an async version, rather than having to do an async rewrite.

I have included a toy example below. I would welcome comments.

from typing import Iterable, NamedTuple, Dict, Any, Optional

import requests
from aiohttp import ClientSession

URL_TEMPLATE = "https://api.icndb.com/jokes/{id}/"

class Request(NamedTuple):
    method: str
    url: str
    json: Optional[Dict[str, Any]] = None

class Response(NamedTuple):
    status: int
    json: Optional[Dict[str, Any]] = None

def get_joke(id: int) -> Iterable[Request]:

    response = yield Request("GET", URL_TEMPLATE.format(id=id))

    try:

        if response.status != 200:
            raise JokeApiError("API request failed")

        data = response.json
        if data.get("type") == 'NoSuchQuoteException':
            raise NoSuchJoke(data.get("value", ""))
        if data.get("type") != "success":
            raise JokeApiError("API request failed")

        raise Return(data["value"]["joke"])

    except (JokeApiError, Return, StopIteration):
        raise
    except Exception as e:
        raise JokeApiError() from e

def call_api_sync(it):
    try:
        for req in it:
            response = requests.request(req.method, req.url, json=req.json)
            it.send(
                Response(status=response.status_code, json=response.json())
            )
    except Return as e:
        return e.value

async def call_api_async(it):
    async with ClientSession() as session:
        try:
            for req in it:
                async with session.request(
                        method=req.method,
                        url=req.url,
                        json=req.json) as res:
                    json = await res.json()
                    response = Response(status=res.status, json=json)
                    it.send(response)
        except Return as e:
            return e.value

class JokeApiError(Exception):
    pass

class NoSuchJoke(JokeApiError):
    pass

class Return(Exception):

    def __init__(self, value):
        self.value = value


texts: What would be the optimal way to address these arrays

texts:
I think the arrays here are slowing down my code due to incorrect usage.

There is a lot of stuff going on here, it's understandable if nobody responds. Just looking for some pointers. Thanks.

for MN in xrange(RowModel,TotalModels):

    if(MN%5000==0):print 'Examining models', MN,'to', (MN+5000), '...'

    fobs=fobstemp
    fobserr=fobstemp*0.1 #10% error
    y=np.array([])
    fmod=np.array([])

I was reading that it can be memory exhaustive to run for loops and range functions over numpy arrays and it is better instead to run np.arange[]. Can anyone validate this statement? I'm not sure how to implement it here where RowModel and TotalModels are separate arrays. And assuming they are the same dimensions.

Here's the section of that code (which starts off with the above snippet). Ultimately the values at the end are used in a statistical calculation. The code works but it's insanely slow at this portion.

for MN in xrange(RowModel,TotalModels):

    if(MN%5000==0):print 'Examining models', MN,'to', (MN+5000), '...'

    fobs=fobstemp
    fobserr=fobstemp*0.1 #10% error
    y=np.array([])
    fmod=np.array([])

#Set the scale factor
#units are already embedded in scalemult [mJy]

    if(modcalibrate<=13):
     scale= (10**(convertStr(data[RowStar][calibrate])/-2.5)*10**(0.4*tau_mag[choice-1])*scalemult)/((convertStr(model[MN][modcalibrate])*1e+03*Fbol*1e+23)/(c/wavelengthmodel[modcalibrate-10]))
    else:
     scale= (convertStr(data[RowStar][calibrate])*10**(0.4*tau_mag[choice-1]))/(convertStr(model[MN][modcalibrate])*Fbol*1e+029/(c/wavelengthmodel[modcalibrate-10]))

#Convert the model data into fluxes and insert into array fmod
#
    for i in xrange(10+len(wavelength)-2):#2 repeats
     y=np.append(y,model[MN][i])
    for i in xrange(10,10+len(wavelength)-2): #2 repeats
     Alambda=Ak/wavelength[i-10]
     fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10]))
     if i== 11:
      fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10]))
     if i== 13:
      fmod=np.append(fmod,convertStr(y[i])*Fbol*scale*1e+023*1e+03/(c/wavelengthmodel[i-10]))

#Delete the components that are not shared between fobs and fmod
#
    j=0

    for i in xrange(len(wavelength)):
     if j<=len(fobs)-1:
      if -10<fobs[j]<-9:
       fobs=np.delete(fobs,j,None)
       fobserr=np.delete(fobserr,j,None)
       fmod=np.delete(fmod,j,None)
      else:
       j=j+1

#Calculate Chi^2 for the model and insert into an array
#

    scalefactor=np.append(scalefactor,scale)
    chi2_new=np.sum(((fobscaled-fmod)/(fobserr))**2)/(len(fobscaled)-1)
    chi2=np.append(chi2,chi2_new)
    if chi2_new<ChiThresh: #User input required here for Chi threshold maximum.
     BestFitsModel=np.append(BestFitsModel,MN)
     BestFitsChi=np.append(BestFitsChi,chi2_new)
     BestFitsScale=np.append(BestFitsScale,scale)
     counter=counter+1
    temp=np.sort(chi2)

wavelengthmodel is defined as an array of size 8. (8 entries, all floats).

wavelength is defined as an array of size 11 (11 entries, all floats).

modcalibrate is an index array which corresponds to a list imported elsewhere.

MN is a numerical array starting at 0 and ending at some large number. This corresponds to TopModels and RowModel which starts at 0 (RowModel value) and ends at n (TopModels value).

Anything else undefined in this script-section is an empty array until filled here, except 'ChiThresh' which is an integer of user input.


texts: Grouping sorted coordinates based on proximity to each other

texts:
I created an algotrithm that groups a sorted list of coordinates into buckets based on their proximity (30) to one another.

Steps:

Create a new key with a list value and pop the first point in the list into it
Scan the list of points for points that are close to it. Push matches to the new list and replace values with None
After scan, filter the list, removing None values
Back to one, until points is empty.

I can't modify the list by deleting elements because I use indexes.

After I'm done grouping, I take the average of each group of points.

def group_points(points):
    groups = {}
    groupnum = 0
    while len(points) > 1:
        groupnum += 1
        key = str(groupnum)
        groups[key] = []
        ref = points.pop(0)
        for i, point in enumerate(points):
            d = get_distance(ref, point)
            if d < 30:
                groups[key].append(points[i])
                points[i] = None
        points = list(filter(lambda x: x is not None, points))
    # perform average operation on each group
    return list([[int(np.mean(list([x[0] for x in groups[arr]]))), int(np.mean(list([x[1] for x in groups[arr]])))] for arr in groups])

def get_distance(ref, point):
    # print('ref: {} , point: {}'.format(ref, point))
    x1, y1 = ref[0], ref[1]
    x2, y2 = point[0], point[1]
    return math.hypot(x2 - x1, y2 - y1)

If possible, I would like to reduce the amount of variables and total loops over the points array. Do I need to use indexes? Is it possible to achieve this in one pass over points?


texts: DateTimePrecise - current DateTime with millisecond precision

texts:
Answer in this question contains DateTimePrecise class that should return current date with millisecond precision. But class is pretty bug and complicated. So I wrote my own version which seems work fine. If you see any problems with my code?

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

namespace ConsoleApplication1
{
class DateTimePrecise
{
    private long startTick;
    private Stopwatch sw;

    public DateTimePrecise()
    {
        startTick = DateTime.Now.Ticks;
        sw = Stopwatch.StartNew();
    }

    public DateTime CurDateTime()
    {
        return new DateTime(startTick + sw.ElapsedTicks);
    }

}
}

I understand that my version is not accurate, meaning that actual system time may be less or more up to several milliseconds (±16 ms likely). But my version is still precise meaning that couple of measurements will defer at exactly spent milliseconds. And that's exactly what I need. I need precise but not necessary accurate clock because I only need to compare values between each other and I don't need exact current time up to milliseconds.


texts:
i am rather new at python and this is my very first project i did myself. i am wondering if there is anyway i can improve this or give me advice on making this better. thank you
import sys
valid = ["+", "-", "*", "/"]
invalid = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def start():
    while True:
        a = input("").lower()
        for banned in a:
            if banned in invalid:
                print("error")
            else:
                sum1 = int(a)
        cal = input("")
        b = input("").lower()
        for banned in b:
            if banned in invalid:
                print("Error")
                start()
            else:
                sum2 = int(b)
        break;
    for list in cal:
        if list in valid:
            if list == "+":
                total = sum1 + sum2
                print("=" + total)
            if list == "-":
                total = sum1 - sum2
                print(total)
                start()
            if list == "*":
                total = sum1 * sum2
                print(total)
                start()
            if list == "/":
                total = sum1 / sum2
                print(total)
                start()
        else:
            print("Wrong Format")
            start()
start()


texts: "Fast strlen" in C using scalar bithacks

texts:
I've translated an implementation of strlen in x86 assembly to C and added alignment checking:

#include <strings.h>
#include <string.h>
#include <stdint.h>

#define NOT_HIGH_MASK 0x080808080
#define HIGH_MASK 0x7f7f7f7f
#define LOW_MASK 0x01010101
#define mul4(x) ((x) << 2)
#define div8(x) ((x) >> 3)

size_t strlen(const char *str)
{
    const char *cptr = str;
    uint32_t i, *s;
    size_t ctr = 0;

    /* Satisfy alignment requirements */
    while((uintptr_t)cptr & (sizeof(uint32_t)-1))
    {
        if(!*cptr)
            return cptr - str;
        cptr++;
    }

    s = (uint32_t *)cptr;

    do {
        i = s[ctr];
        /* Mask off high bit */
        i &= HIGH_MASK;
        /* subtract 0x01 from each byte,
           giving a set high bit if it
           was zero */
        i -= LOW_MASK;
        ctr++;
            /* Test for the set high bit
               and if it is found exit */
    } while(!(i &= NOT_HIGH_MASK));

    /* Find the first high bit set and
       create the corresponding byte index */
    i = div8(ffs(i));
    /* Remove the counter increment from the
       loop and multiply it by 4 to find the
       rest of the byte index */
    ctr = mul4(ctr - 1);

    /* Return the combined byte index with 1
       removed so it doesn't include the null
       terminator itself */
    return i + ctr - 1;
}

I'm looking for general critique, but I'd also like additional information in these areas:

Portability. Is this portable? Will it work on all common platforms (x86, arm, etc.) and possibly some uncommon ones?
Comments. The comments I've put here seem to already document the code well enough, but is there any additional information I could add?
Hidden Bugs. This definitely works (and has a noticeable improvement in speed), but are there any hidden bugs relating to alignment requirements or otherwise (such as extended ASCII)? For context, this is part of a standard C/POSIX library implementation.

I might note that I'm relying on my header to use the builtin version of ffs. This may be an issue on non-GNU compilers.

If a GCC-compatible compiler (gcc, clang, icc, etc.) is detected during the build process, the flags -std=gnu99 -O2 are appended to the build flags.


texts: Multiple CResourceUsers using a single CResource

texts:
I need multiple CResourceUsers to share one instance of CResource.
I want to instantiate the CResource only if at least one CResourceUser exists.
CResource is not singleton by design, there may exist other users of CResource
C++98 is used
Windows only solution
CResource methods are thread-safe

I started with simple

CResource & CResourceUser::Resource() const
{
    static CResource resource("resource");
    return resource;
}

Which is supposed to be used like this:

CResourceUser::CResourceUser()
{
    std::cout << "+++ CResourceUser" << std::endl;
    Resource().DoSomething();
}

But that seems not to be thred-safe.

So I came with a bit complicated solution:

Synchronisation.h:

#include <Windows.h>

namespace Synchronization {

class CriticalSection
{
    friend class Lock;

    public: CriticalSection ()
    {
        ::InitializeCriticalSection (&_critSect);
    }

    ~CriticalSection ()
    {
        ::DeleteCriticalSection (&_critSect);
    }

    private: CRITICAL_SECTION _critSect;
};

class Lock
{
    public: Lock (CriticalSection & critSect) : _section (critSect)
    {
        ::EnterCriticalSection (&_section._critSect);
    }

    ~Lock ()
    {
        ::LeaveCriticalSection (&_section._critSect);
    }

    private: CriticalSection & _section;
};

}

#include <iostream>
#include <Windows.h>

The rest of the code now looks a bit better:

#include <iostream>
#include "Synchronization.h"

/////////////////////////////////////////////////////////////

class CResource
{
public:
    CResource(const std::string &_name)
        :name(_name)
    {
    }

    ~CResource()
    {
    }

    void DoSomething()
    {
        std::cout << "Something!" << std::endl;
    }
private:
    const std::string name;
};

/////////////////////////////////////////////////////////////

class CResourceUser
{
public:
    CResourceUser()
    {
        Resource().DoSomething();
    }
private:
    CResource & Resource() const
    {
        Synchronization::Lock resourceInitGuard(s_csResourceInit);
        static CResource resource("resource");
        return resource;
    }
    static Synchronization::CriticalSection s_csResourceInit;
};

/////////////////////////////////////////////////////////////

Synchronization::CriticalSection CResourceUser::s_csResourceInit;

int main()
{
    CResourceUser user1;
    CResourceUser user2;
    CResourceUser user3;
    return 0;
}

So for now I'm OK with the code, it is more readable than the previous revision and it seems to work as expected.

The main question remains: Is the code correct?

Please ignore the hungarian notation.


texts:
I wrote this solution for project Euler #7, to find the 10001th prime number using sieve of eratosthenes. It's really slow though. Any suggestions to improve performance (without using more complex sieves like sieve of atkin)?

#include<iostream>
#include<bits/stdc++.h>
#include<climits>
#define max 500000
using namespace  std;

int main()
{
 int ctr = 0;
 int i=2,j,n=10001,p=2;
 int arr[max];
 memset(arr,0,sizeof(arr));
 while(1)
 {

 p=2;
 while(p*p<=i)
 {

  if(arr[p] == 0)
     for(j=p*p;j<=i;j+=p)
        arr[j] = 1;

        p++;

    }
   if(arr[i]==0)
    ctr++;
   if(ctr==n)
    break;
   i++;

  }

 cout<<i;

 }


texts: Invoking thread for each item in list simultaneously and returning value in Java

texts:
I made a wrapper for an API that I am using, basically what I'm doing is sending in a list of Series objects and for each item in the list, a thread ("worker"?) starts and fetches information for their respective series.

The API that I'm using doesn't support fetching several series using one request, which would simplify this by a large margin, therefore I run threads for each item in the list.

I'm mostly concerned about the thread part, but I'll provide all the other parts as well.

@RequestMapping(value = "/series", method = RequestMethod.POST)
public List<Response> fetchSeveralSeries(@RequestBody List<Series> list) throws InterruptedException, ExecutionException {
    List<Callable<Response>> callableList = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        callableList.add(new performRequest(list.get(i).getSeries()));
    }

    final ExecutorService service = Executors.newFixedThreadPool(list.size());
    List<Future<Response>> futureObjects = service.invokeAll(callableList);
    List<Response> series = new ArrayList<>();

    for (Future<Response> obj : futureObjects) {
        series.add(obj.get());
    }

    return series;
}

Callable class used. (temporarily in my Spring boot controller class, as my entire implementation is in the controller atm.)

private class performRequest implements Callable<Response> {
    private int seriesId;

    private performRequest(int seriesId) {
        this.seriesId = seriesId;
    }

    @Override
    public Response call() throws UnirestException {
        return request.send(new Url(seriesId).toString());
    }
}

About the request made by each thread, I have a Url class which constructs the Url for the request and a Request class which sends the request to the external API.

Request class which sends the request to external API. The Response object is a "GSON Object".

@Service
public class Request {

    private static final Logger logger = LoggerFactory.getLogger(Request.class);

    public Response send(String url) throws UnirestException {
        logger.info("sending GET");
        HttpResponse<JsonNode> json = Unirest.get(url).asJson();
        String body = json.getBody().toString();
        return new Gson().fromJson(body, Response.class);
    }

}

Url class which constructs the URL.

@Data
public class Url {
    private static final String BASE_URL = "https://api.themoviedb.org/3";
    private static final String API_KEY = System.getenv("API_KEY");

    private Integer id;
    private Integer season;
    private Integer episode;
    private String searchQuery; // should turn spaces into %20

    public Url(String searchQuery) {
        this.searchQuery = searchQuery;
    }

    public Url(Integer id) {
        this.id = id;
    }

    public Url(Integer id, Integer season) {
        this.id = id;
        this.season = season;
    }

    public Url(Integer id, Integer season, Integer episode) {
        this.id = id;
        this.season = season;
        this.episode = episode;
    }

    @Override
    public String toString() {
        return this.searchQuery != null ?
                String.format("%s/search/tv?api_key=%s&language=en-US&query=%s", BASE_URL, API_KEY, this.searchQuery) : this.episode != null ?
                String.format("%s/tv/%s/season/%s/episode/%s?api_key=%s&language=en-US", BASE_URL, this.id, this.season, this.episode, API_KEY) : this.season != null ?
                String.format("%s/tv/%s/season/%s?api_key=%s&language=en-US", BASE_URL, this.id, this.season, API_KEY) :
                String.format("%s/tv/%s?api_key=%s&language=en-US", BASE_URL, this.id, API_KEY);
    }

}

An example POST request body would be something like below:

[
    {
        "series": 37680
    },
    {
        "series": 53123
    },
    {
        "series": 12345
    },
    {
        "series": 29182
    }
]

Could my code be improved somehow? Would it be possible to decrease response time? Is it "thread-safe"?
  Any feedback is welcome.


texts:
I'm writing a python script to find restrictionplaces. I was wondering if there is a better way to write the following:

def restrictionplace(string, minLength = '', maxLength = ''):
    if minLength == '': minLength = 4
    if maxLength == '': maxLength = 12

    #rest of script

if there is no min or maxlength given, the script should use 4 or 12.


texts:
I would like to know if what I did to achieve to goal of dynamic operators within an Airflow DAG (Directed Acyclic Graph) is a good or a bad practice.

The goal I had to achieve was:

  Create a 'x' amount of operators within
  a DAG based on the result of an API call. This DAG will run for example every week.

The program that I made works, but I don't know if it is a good practice for developing DAGs for Airflow. So my question is: is it a good practice or if not what would be a better solution to this problem?

The code I used to achieve this goal:

with DAG('my_dag', default_args=default_args, schedule_interval='@weekly') as my_dag:

    start = DummyOperator(
        task_id='start'
    )

    endpoint = 'www.example.com/api/dummies'
    r = requests.get(endpoint)
    dummies = r.json()

   for _, dummy in enumerate(dummies):
        dummy_operator = DummyOperator(
                    task_id='dummy_opr_{}'.format(dummy['id']
                    )
        start >> dummy_operator


texts: Extracting certain products from a webpage using Scrapy

texts:
I've written a script in Python Scrapy to harvest various product names and price from books.toscrape. The reason I submit this tiny code to Code Review is because, in Python 3 when it comes to work with Scrapy and parse some data from a web, the csv output looks awkward (if the csv is derived from default command, as in scrapy crawl toscrapesp -o items.csv -t csv). The results found in such CSV file are with a uniform gap between two lines that means there is a line gap between each two rows. I've fixed it using the below script. I didn't use default command to get the CSV output; rather, I've written few lines of code in spider class and got the desired output.

Although It is running smoothly, I'm not sure it is the ideal way of doing such thing. I expect someone to give any suggestion as to how I can improve this script.

"items.py" includes:

import scrapy

class ToscrapeItem(scrapy.Item):
    Name = scrapy.Field()
    Price = scrapy.Field()

Spider contains:

import csv
import scrapy

outfile = open("various_pro.csv", "w", newline='')
writer = csv.writer(outfile)

class ToscrapeSpider(scrapy.Spider):

    name = "toscrapesp"
    start_urls = ["http://books.toscrape.com/"]

    def parse(self, response):
        for link in response.css('.nav-list a::attr(href)').extract():
            yield scrapy.Request(url=response.urljoin(link), callback=self.collect_data)

    def collect_data(self, response):
        global writer
        for item in response.css('.product_pod'):
            product = item.css('h3 a::text').extract_first()
            value = item.css('.price_color::text').extract_first()
            yield {'Name': product, 'Price': value}
            writer.writerow([product,value])

Please click this link to see what I was having earlier. Upon executing the script, I get CSV output with no line gap or blank rows.


texts:
I am starting to try to conform to coding standards use exception handling.

What do you think is missing here and what else should I consider further?

The function run has all the other functions being called here. The run function is the one I think need further refactoring.

"""
PLUGIN etcpasswd

Description:
  Plugin to fetch users from etc/passwd
  user,host and userfilter comes from config file,
  userfilter is configurable, set in the format username|username2

ConfigFile:
  plugins/configfile.cfg
"""

from yapsy.IPlugin import IPlugin
import ConfigParser
import os.path
import os
import sys
import logging
import subprocess

import lib.restplugin.restplugin as sshp

class EtcPasswd(IPlugin):

    def __getConfigDetails(self):
        """reading the config file details """
        try:
            logging.info("fetching,config details")
            self.user = self.config.get("plugin_etc_passwd", 'user')
            self.host = self.config.get("plugin_etc_passwd", 'host')
            self.fileloc = self.config.get("plugin_etc_passwd", 'filepath')
            self.filter = self.config.get("plugin_etc_passwd", 'filter')
            logging.info("Config Details fetched")

        except ConfigParser.NoOptionError as error:
            logging.exception(error)
            print "Error in options Name", error

        except ConfigParser.NoSectionError as error:
            logging.exception(error)
            print "Error in sections Name", error

    def run(self, configpath, outputpath, logpath):
        """ main caller method to run all the functions"""
        self.outputpath = outputpath
        self.configpath = configpath
        self.logpath = logpath
        # start logs
        self.__createLog()
        logging.info("Plugin started")
        print "Fetching from etc/passwd"
        self.config = ConfigParser.RawConfigParser()
        self.config.read(self.configpath)

        try:
            self.__getConfigDetails()

            phelper = sshp.SSHPlugin()
            runcommand, runfilter = phelper.makeCommand(
                self.user, self.host, self.fileloc, self.filter)
            self.result = phelper.executeCommand(runcommand, runfilter)

            if self.result:
                self.parsedResult = self.__parseResult(self.result)
                if self.__saveResult(self.parsedResult):
                    return True
                else:
                    logging.error("Could not save the Parsed Result !")
                    return False
            else:
                logging.error("Could not get the Result")
                return False

        except Exception as error:
            logging.exception(err)

        self.__closeLogFile()

    def __createLog(self):
        """ creates a logs"""
        self.logf = open(self.logpath, 'w')
        logging.getLogger('').handlers = []
        logging.basicConfig(
            filename=self.logpath, filemode="w", level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    def __closeLogFile(self):
        """ close the logs"""
        self.logf.close()

    def __parseResult(self, result):
        """parse the result of the output from  executeCommand functions available in sshp"""
        logging.info('Parsing..')
        self.string_result = result
        # print self.string_result
        self.userlist = []
        parsed_result = self.string_result.splitlines()

        for names in parsed_result:
            self.userlist.append(names.split(":")[0])
        logging.info("Parsing SUCCESS")
        return self.userlist

    def __saveResult(self, parsed_result):
        """saving the result username into the files"""

        logging.info("Starting to SAVE output")
        try:
            fo = open(self.outputpath, 'w')
            for users in parsed_result:
                fo.write(users+"\n")
            logging.info("SAVED")
            return True
        except Exception as err:
            logging.error("ERROR while saving  %s", err)


texts: Angular Rest API generic service and implementation service

texts:
I'm wondering if there's a better way to write the ApiService and the CategoryService so that CategoryService is basically just a call to extend ApiService with the string 'category' and the base type 'ICategory' or if this is the best that I can get from typescript and angular? There will be many more endpoint services in the final app

Any other general comments on code style etc are also very welcome (or if anyone knows how to tell Webstorm to not put the constructor closing braces on the next line!!)

ApiService

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';

const baseUrl = environment.serverBaseUrl;
const apiEndpoint = environment.apiEndpoint || '/api/v1/';
const apiUrl = `${baseUrl}${apiEndpoint}`;

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) {
  }

  private createTokenOptions() {
    return {headers: new HttpHeaders().set('Authorization', `Bearer ${localStorage.getItem('access_token')}`)};
  }

  get<T>(serviceEndpoint: string, id?: number): Observable<T> {
    let url = `${apiUrl}${serviceEndpoint}`;
    if (id) {
      url += `/${id}`;
    }
    return this.http.get<T>(url, this.createTokenOptions());
  }

  create<T>(serviceEndpoint, item: T): Observable<object> {
    const options = this.createTokenOptions();
    options.headers = options.headers.append('Content-Type', 'application/json');
    return this.http.post(`${apiUrl}${serviceEndpoint}`, JSON.stringify(item), options);
  }

  delete<T>(serviceEndpoint: string, id: number): Observable<T> {
    return this.http.delete<T>(`${apiUrl}${serviceEndpoint}/${id}`, this.createTokenOptions());
  }
}

CategoryService

import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { Observable } from 'rxjs';
import { ICategory } from '../interfaces/category.model';

@Injectable({
  providedIn: 'root'
})
export class CategoryService {

  private serviceEndpoint = 'category';

  constructor(private api: ApiService) {
  }

  getCategories() {
    return this.api.get<ICategory[]>(this.serviceEndpoint);
  }

  getCategory(id: number): Observable<ICategory> {
    return this.api.get<ICategory>(this.serviceEndpoint, id);
  }

  createCategory(category: ICategory) {
    return this.api.create<ICategory>(this.serviceEndpoint, category);
  }

  deleteCategory(id: number) {
    return this.api.delete<ICategory>(this.serviceEndpoint, id);
  }
}


texts:
The Ruby on Rails framework doesn't allow you to validate enums submitted through a form in any sane manner. Evidently, enums are meant to be used to maintain internal application state, and are not supposed to be user-facing. Well, in my case it doesn't matter too much, but I still want validations *just in case*.

Here is a widely-used enum:

class Language < ActiveRecord::Base
    self.abstract_class = true

    enum language: {
        arabic: 0,
        chinese: 1,
        english: 2,
        french: 3,
        german: 4,
        italian: 5,
        japanese: 6,
        russian: 7,
        spanish: 8,
        other: 9
    }
end

In my schema, the field using this enum is a text array: t.text     "audio_languages",    default: [], allowing multiple languages to be selected through the form.

In the form, the values are added as a list of check boxes:

In the controller, the values for that field come in as:

"audio_languages"=>["English", ""]

Notice the last array entry, "". That's just how it works I guess, nothing I've tried gets rid of that, so I have to handle it in the validation.

In the validation, a language needs to be chosen, and the chosen language has to be present in the language enum:

def validate_audio_languages

    # Remove the empty string, which is an artifact of form submission of an array
    # field, during validation
    audio_languages.reject! { |l| l.empty? }

    if !audio_languages.any?
        errors.add(:audio_languages, "need to select a language")
    end

    # If any of the audio languages is invalid, add the error and break
    audio_languages.each do |al|
        valid = false
        Language.languages.each do |l, i|
            valid = true if (al.downcase == l.downcase)
        end

        if !valid
            errors.add(:audio_languages, "not a valid language selection")
            break
        end
    end
end

I'm concerned about the length of the function more than anything. Surely there's an easier way to do this kind of simple validation, especially to validate whether or not a value is actually in the enum. Any help in dealing with this issue is much appreciated!


texts: DSSudokuSolver - A JavaScript Sudoku solving algorithm

texts:
I wrote DSSudokuSolver - a sudoku solving algorithm a while back. Is there any possibility that this algorithm can be improved?

Original Algorithm:

CleanElements = function(comp_ary, Qsudoku){
    for(i=0; i<9; i++){
        for(j=0; j<9; j++){
            /*if(Qsudoku[i][j] != ""){
              comp_ary[i][j]=[];
              }*/
            for(k=0; k<9; k++){
                i_index = comp_ary[i][k].indexOf(Qsudoku[i][j]);
                if(i_index != -1){
                    comp_ary[i][k].splice(i_index, 1);
                }
                j_index = comp_ary[k][j].indexOf(Qsudoku[i][j]);
                if(j_index != -1){
                    comp_ary[k][j].splice(j_index, 1);
                }
            }
            if(i < 3){
                i_min = 0;
                i_max = 2;
            }
            else if(i < 6){
                i_min = 3;
                i_max = 5;
            }
            else{
                i_min = 6;
                i_max = 8;
            }

            if(j < 3){
                j_min = 0;
                j_max = 2;
            }
            else if(j < 6){
                j_min = 3;
                j_max = 5;
            }
            else{
                j_min = 6;
                j_max = 8;
            }

            for(i_box=i_min; i_box<=i_max; i_box++){
                for(j_box=j_min; j_box<=j_max; j_box++){
                    index = comp_ary[i_box][j_box].indexOf(Qsudoku[i][j]);
                    if(index != -1){
                        comp_ary[i_box][j_box].splice(index, 1);
                    }
                }
            }
        }
    }
    return comp_ary;
}

FindElements = function(comp_ary, Qsudoku){
    for(i=0; i<9; i++){
        for(j=0; j<9; j++){
            if(comp_ary[i][j].length == 1){
                if (Qsudoku[i][j] == ""){
                    Qsudoku[i][j] = comp_ary[i][j][0];
                    comp_ary[i][j] = [];
                }
            }
        }
    }
    return Qsudoku;
}

IsThereNullElement = function(Qsudoku){
    for(i=0; i<9; i++){
        for(j=0; j<9; j++){
            if(Qsudoku[i][j] == ""){
                return false;
            }
        }
    }
    return true;
}

InitEmptyArray = function(){
    empty_ary = Array();
    for(i=0; i<9; i++){
        empty_ary[i] = Array();
        for(j=0; j<9; j++){
            empty_ary[i][j] = Array();
            for(k=0; k<9; k++){
                empty_ary[i][j][k] = (k+1).toString();
            }
        }
    }
    return empty_ary;
}

DSSolve = function(Qsudoku){
    comp_ary = InitEmptyArray(); //Complementary Array
    window.comp_ary_old = comp_ary;
    IterationMax = 5000;

    while(true){
        IterationMax -= 1;
        comp_ary = CleanElements(comp_ary, Qsudoku);
        console.log(comp_ary);

        if(window.comp_ary_old == comp_ary){
            //implement this.
        }
        else{
            window.comp_ary_old = comp_ary;
        }

        Qsudoku = FindElements(comp_ary, Qsudoku);
        //console.log(Qsudoku);

        if(IsThereNullElement(Qsudoku)){
            return Qsudoku;
        }

        if(IterationMax == 0){
            return null;
        }
    }
}


texts: Determine whether one vector is a prefix of the other

texts:
Exercise 5.17:

  Given two vectors of ints, write a program to determine
  whether one vector is a prefix of the other. For vectors of unequal
  length, compare the number of elements of the smaller vector. For
  example, given the vectors containing 0, 1, 1, and 2 and 0, 1, 1, 2,
  3, 5, 8, respectively your program should return true.

This executes correctly, but I just want to get this double-checked.

#include <iostream>
#include <vector>

using std::vector; using std::cout; using std::endl;

int main()
{
vector<int> v1{ 0, 1, 1, 2, 3, 5, 8 };
vector<int> v2{ 0, 1, 1, 2 };
if (v1.size() < v2.size()){
    cout << "Using v1 as the prefix to v2" << endl;
    for (int smallIndex = 0, largeIndex = 1; smallIndex != v1.size(); ++smallIndex, ++largeIndex){
        if (v1[smallIndex] == v2[largeIndex])
            cout << "v1 at position " << smallIndex << " is a prefix for v2 at postion " << largeIndex << endl;
    }
}
else if (v1.size() > v2.size()){
    cout << "Using v2 as the prefix to v1" << endl;
    for (int smallIndex = 0, largeIndex = 1; smallIndex != v2.size(); ++smallIndex, ++largeIndex){
        if (v2[smallIndex] == v1[largeIndex])
            cout << "v2 at position " << smallIndex << " is a prefix for v1 at position " << largeIndex << endl;
    }
}
else {      //  v1.size() == v2.size() only comparing the first as the prefix to the second
    cout << "Size of v1 and v2 are the same, using v1 as the prefix to v2" << endl;
    for (int smallIndex = 0, largeIndex = 1; largeIndex != v1.size(); ++smallIndex, ++largeIndex){
        if (v1[smallIndex] == v2[largeIndex])
                cout << "v1 at position " << smallIndex << " is a prefix for v2 at postion " << largeIndex << endl;
        }
    }
}


texts: Unmanaged byte array to managed structure

texts:
I have a need to turn byte arrays into various structures.

First version:

public static object ConvertBytesToStructure(object target, byte[] source, Int32 targetSize, int startIndex, int length)
    {
        if (target == null)
            return null;

        IntPtr p_objTarget = Marshal.AllocHGlobal(targetSize);
        try
        {
            Marshal.Copy(source, startIndex, p_objTarget, length);
            Marshal.PtrToStructure(p_objTarget, target);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            Marshal.FreeHGlobal(p_objTarget);
        }

        return target;
    }

I have found that when i calling to the first version a lot of times in a second - i getting poor performance.

So i trying to improve that to the version 2:

  private static T ReadUsingMarshalUnsafe<T>(byte[] data, int startIndex, int length)
        {
            byte[] fixedData = new byte[length];
            unsafe
            {
                fixed (byte* pSource = data, pTarget = fixedData)
                {
                    int index = 0;
                    for (int i = startIndex; i < data.Length; i++)
                    {
                        pTarget[index] = pSource[i];
                        index++;
                    }
                }

                fixed (byte* p = &fixedData[0])
                {
                    return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
                }
            }
        }

I have found that this version getting very good performance..

But i want to getting your code review - maybe i'll have any memory leak? maybe i can to do this with efficent another way?

Thanks!


texts: Faster generation of list with multiple sublists

texts:
I'm trying to improve the performance of some rather large code. One of the bottlenecks is the line below. It doesn't look like much but it is processed millions of times.

Is there any way to improve its performance at the code level (ie: no parallelization)? I'm perfectly fine with the final outcome being a numpy array instead of a list.

import numpy as np

def func(m1, m2):
    return -2.5 * np.log10(10 ** (-0.4 * m1) + 10 ** (-0.4 * m2))

# Generate data.
N1, N2 = 300, 200
aa = np.random.random((5, N1))
idxs = np.random.choice(N1, N2, replace=False)
bb = np.random.random((10, N2))

# I need to improve the performance of this line.
cc = [func(m[idxs], bb[i]) for (i, m) in enumerate(aa)]

Add

As Mibac suggested, the issue here might actually be the successive calls to func(), not the generation of the cc list itself.

If this is the case, then I'd need to improve the performance of the line:

-2.5 * np.log10(10 ** (-0.4 * m1) + 10 ** (-0.4 * m2))

or equivalently:

-2.5 * np.log10(c ** m1 + c ** m2)

where c=10**(-0.4).


texts: HTTP download function in Rust (async/await)

texts:
Why am I fighting the compiler? - Wrote this, which works, but I feel like I'm breaking every rule in the book:

#[macro_use]
extern crate lazy_static;

use std::ffi::OsString;
use std::path::PathBuf;
use std::str::FromStr;

use actix_rt;
use actix_web::client::Client;
use async_std::fs::File;
use async_std::prelude::*;
use http::uri::Uri;

// Result<OsString, (SendRequestError|std::core::convert::Infallible|actix_http::error::PayloadError)
#[actix_rt::main]
async fn download(uri: &'static str, target_dir: &'static str) -> Result<OsString, ()> {
    let client = Client::default();
    let uri = Uri::from_str(uri).unwrap();

    // Create request builder and send request
    let response = client
        .get(&uri)
        .header("User-Agent", "Actix-web")
        .send()
        .await; // <- Send http request

    println!("Response: {:?}", response);

    let get_host = || uri.host().unwrap().to_owned();

    let path = match &uri.path_and_query() {
        Some(path_and_query) => {
            let p = path_and_query.path().to_owned();
            if p == "/" {
                get_host()
            } else {
                p
            }
        }
        None => get_host(),
    };

    let output_pathbuf = PathBuf::from_str(target_dir).unwrap().join(path);
    let output_file = output_pathbuf.as_os_str();
    let mut file = File::create(output_file).await.unwrap();
    file.write_all(&response.unwrap().body().await.unwrap())
        .await
        .unwrap();
    // file.write_all(b"Hello, world!").await.unwrap();
    return Ok(output_file.to_owned());
}

#[cfg(test)]
mod tests {
    use std::borrow::Borrow;
    // use std::env::temp_dir;
    use std::fs::create_dir_all;
    use std::path::PathBuf;
    use std::str::FromStr;

    use crate::download;

    fn temp_dir() -> PathBuf {
        return PathBuf::from_str("/tmp").unwrap();
    }

    lazy_static! {
        pub static ref TEMP_DIR: PathBuf = temp_dir().join(module_path!());
        pub static ref TEMP_DIR_O: Option<&'static str> = TEMP_DIR.to_str();
        pub static ref TEMP_DIR_S: &'static str = TEMP_DIR_O.unwrap();
    }

    #[test]
    fn test_download() {
        if !TEMP_DIR.exists() {
            create_dir_all(TEMP_DIR.borrow() as &PathBuf).unwrap();
        }

        //let output_dir =
        download(
            "http://www.rust-lang.org",
            TEMP_DIR_S.borrow() as &'static str,
        )
        .unwrap();
        //assert_eq!(output_dir, "foo")
    }
}

Remarks:

I understand that unwrap() is frowned upon, and should be replaced by error percolation (? sugar) and handled at the topmost level (that makes sense). Replacing the unwraps, and now it can return any of SendRequestError|std::core::convert::Infallible|actix_http::error::PayloadError. Should I Box/dyn a std::Error, create a big failure enum, or something cleaner?
Not so happy with the types. I tried working with AsRef<PathBuf>, Into<Uri>, and variants thereof. Clearly that doesn't work.
How do I get the Result?
This is the first step in a multi-URL downloader, but I am worried about efficiency. Do I setup some sort of executor/reactor system atop async/await concepts?


texts: QNetworkReply network reply timeout helper

texts:
Since Qt still does not support to set timeouts on QNetworkRequest objects, I wrote this little wrapper class:

/**
Usage:
new QReplyTimeout(yourReply, msec);

When the timeout is reached the given reply is closed if still running
*/
class QReplyTimeout : public QObject {
  Q_OBJECT
public:
  QReplyTimeout(QNetworkReply* reply, const int timeout) : QObject(reply) {
    Q_ASSERT(reply);
    if (reply) {
      QTimer::singleShot(timeout, this, SLOT(timeout()));
    }
  }

private slots:
  void timeout() {
    QNetworkReply* reply = static_cast<QNetworkReply*>(parent());
    if (reply->isRunning()) {
      reply->close();
    }
  }
};

You can use it in a very simple fire-and-forget manner:

QNetworkAccessManager networkAccessManger;
QNetworkReply* reply = networkAccessManger.get(QNetworkRequest(QUrl("https://www.google.com")));
new QReplyTimeout(r, 100);

If the call to Google does not finish in 100ms, it is aborted. And since the QReplyTimeout class is parented to the QNetworkReply, it will be destroyed automatically.

Review the code for any pitfalls, memory leaks, invalid casts and if it's generally in a good style.


texts: Parse a formatted string, which may have duplicate keys, into a map

texts:
I have a String which is coming in particular format so I want to parse that string into map. I have a below method which parses String to a Map and it works fine.

  public static Map<String, String> parseStringToMap(String payload) {
    Map<String, String> map = new HashMap<>();
    try {
      for (String part : payload.split("\\|")) {
        String[] subparts = part.split("=", 2);
        map.put(subparts[0], subparts[1]);
      }
    } catch (Exception ex) {
    }
    return map;
  }

Sample example of a string:

"type=3|Id=23456|user=13456"
"type=3|Id=23456|user=13456|type=3"

It might be possible that same key can appear many times in the same string payload so I need to overwrite the value for that key in my mutable map.

Also if my string payload is not in this format then I would like to return empty map back. My string format will always be like this and if it is not in this format then I would return empty map back.

"a=b|c=d|e=f"

I am still working with Java 7. What is the best and efficient way to do this?


texts:
I have this code that I am using to delete all records from an entity. The question is can it be done better or is already the best?

    func deleteIncidents() {
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext!
    let request = NSFetchRequest(entityName: "Incidents")
    request.returnsObjectsAsFaults = false

        do {
            let incidents = try context.executeFetchRequest(request)

            if incidents.count > 0 {

                for result: AnyObject in incidents{
                    context.deleteObject(result as! NSManagedObject)
                    print("NSManagedObject has been Deleted")
                }
                try context.save() } } catch {}
    }


texts:
I am/have been building a game for a long time now. The game is a web browser based system, and data is stored using JSON stored in RavenDB.

One thing I am very constantly running into as a problem is the notion of Requirements. Anyone who has played a game, particularly an RPG, is probably familiar with this. Requirements such as Requires Level 10 to use or Requires [Race] to use.

This has been a constant struggle for me, and I have finally worked out what I feel is a solution; But I wanted to see if there were other people who have overcome this issue and could offer any advice.

The way it works is that all of the various things in the game that can have requirements have a field...

List<Conditional> Conditions { get; set; }

Conditional is defined like this;

public class Conditionals {

    public Condition<bool> Named { get; set; }
    public Condition<double> Minimum { get; set; }
    public Condition<double> Maximum { get; set; }
    public Condition<double> Exactly { get; set; }
}

And then each of those is a type of Condition<T>, which is declared like this;

public class Condition<T> {

    public string Id { get; set; }
    public string Name { get; set; }
    public string Adjective { get; set; }
    public string Label { get; set; }
    public T Value { get; set; }
}

So then the JSON would, if I am right, look like this... assume an item that requires level 10.

var Conditionals = new List<Conditionals>{
    new Conditionals {
        Minimum = new Condition<double>{
            Id = "clue/level",
            Name = "Level",
            Adjective = ">=",
            Label = "Level is greater than or equal to 10",
            Value = 10
        }
    }
};

These will be resolved when the character is retrieved from the database using Clues. Clues are simple key/value pairs, like a dictionary. A clue has an identity and a value only.

var character = new Character {
    Level = 11,
    Clues = new List<Clue> () // clues will contain key/value pairs
};
// on database save
character.Clues.Add(new Clue {
    Id = "clue/level",
    Value = character.Level
});

This means I will have to do some hard coding, but only by coding in clues that we know the game is going to expect. This allows us to be a little more specific (I feel) and still have some freedom.

foreach (var condition in Conditionals) {
    // attempt to see if the condition can be satisfied. This code would
    // execute for all four propertyes (named, minimum, maximum, equals)
    var currentClue = character.Clues.FirstOrDefault(y => y.Id == condition.Minimum.Id);

    // attempt to resolve. this is the minimum section, so we always use >=
    var outcome = currentClue.Value >= condition.Value;
}

I am basically trying to ask if anyone else who has more experience has ever encountered this kind of issue in their own projects, and if my solution compares to any that are known to work. This has frustrated me for a long time.


texts:
Problem

Take an array of ints as input and run a special sorting algorithm on it. This algorithm must first sort by int frequency, less frequent first, then sort by value.

For example [4,5,6,5,4,3] is sorted to [3,6,4,4,5,5].

I'm looking for feedback on my use of data structures to implement this sort, memory management, any redundancies, and other general optimizations I can make. No need to give feedback on how I capture input in main since that is not my priority here.

Code

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

int * customSort(int * arr, int n) {
  unordered_map<int, int> frequencyMap;
  for (int i = 0; i < n; i++) {
    auto mapIt = frequencyMap.find(arr[i]);
    if (mapIt == frequencyMap.end()) {
      frequencyMap.insert(make_pair(arr[i], 1));
    } else {
      frequencyMap[arr[i]]++;
    }
  }

  map<int, set<int>> orderedfrequencyMap;
  for (auto &p : frequencyMap) {
    auto mapIt = orderedfrequencyMap.find(p.second);
    if (mapIt == orderedfrequencyMap.end()) {
      set<int> s = {p.first};
      orderedfrequencyMap.insert(make_pair(p.second, s));
    } else {
      (*mapIt).second.insert(p.first);
    }
  }

  int arrI = 0;
  int solution[n];
  for (auto &p : orderedfrequencyMap) {
    for (auto element : p.second) {
      for (int i = 0; i < p.first; i++) {
        arr[arrI] = element;
        cout << element << endl;
        arrI++;
      }
    }
  }

  return solution;
}

int main() {
    int n;
    cin >> n;

    int arr[n];

    int element;
    for (int i = 0; i < n; i++) {
      cin >> element;
      arr[i] = element;
    }

    customSort(arr, n);

    return 0;
}


texts: Middleware for sending PartialViews via email

texts:
After all partial views are rendered and all styles are inlined my RESTful service is sending them via email. I implemented this feature with a MailerMiddleware.

This middleware dumps the response body and uses it as the body of the email. I pass the recipients and the subject via the HttpContext.Items property from the controller to the middleware. It uses the <system.net> element in the app.config for sending emails.

public class MailerMiddleware
{
    private readonly RequestDelegate _next;

    private readonly IEmailClient _emailClient;

    public MailerMiddleware(RequestDelegate next, IEmailClient emailClient)
    {
        _next = next;
        _emailClient = emailClient;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Method == "POST")
        {
            var bodyBackup = context.Response.Body;

            using (var memory = new MemoryStream())
            {
                context.Response.Body = memory;

                await _next(context);

                memory.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(memory))
                {
                    var recipients = (string)context.Items["Recipients"];
                    var subject = (string)context.Items["Subject"];
                    var body = await reader.ReadToEndAsync();

                    memory.Seek(0, SeekOrigin.Begin);

                    var restoreBody = memory.CopyToAsync(bodyBackup);
                    var sendEmail = _emailClient.SendAsync(new Email<EmailSubject, EmailBody>
                    {
                        To = recipients,
                        Subject = new PlainTextSubject(subject),
                        Body = new ParialViewEmailBody(body),
                    });

                    await Task.WhenAll(restoreBody, sendEmail);
                }
            }
        }
        else
        {
            await _next(context);
        }
    }
}

Inside the action method:

[HttpPost("TestReport")]
[ActionName("TestReport")]
public IActionResult PostTestReport([FromBody] TestReportBody body)
{
    HttpContext.Items["Recipients"] = "example@email.com"; // todo use body
    HttpContext.Items["Subject"] = "Test email"; // todo use body
    return PartialView(body);
}

This solution is working great but is there anything that could still be done better?


texts:
I need to refactor some pice od method for drag-and-drop angular material.

Here is a working method in production, I need suggestion for CLEAN way to write this method.
I can't change var name and anything...

WHAT I TRY - I try to made small functions for every if/else, but in this case, I missing this drop event.
Like this example

checkIfHasRole() {
    transferArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
    let lastAddedRole = event.container.data[event.previousIndex];
    if (lastAddedRole !== undefined) {
      this.userRoleCopy.push(lastAddedRole.valueOf());
    }

But, in this case, all event is missing

Here is the working method in production

drop(event: CdkDragDrop < string[] > ) {
  if (event.container.id === "delete") {
    transferArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
    this.userRoleCopy = this.userRole.slice();
  } else {
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      let lastRole = Object.values(
        event.previousContainer.data[event.previousIndex]
      );
      let parentRole = JSON.parse(JSON.stringify(event.container.data));

      let hasRole = parentRole.some(rola => {
        return rola.role === String(lastRole);
      });

      if (!hasRole) {
        transferArrayItem(
          event.previousContainer.data,
          event.container.data,
          event.previousIndex,
          event.currentIndex
        );
        let lastAddedRole = event.container.data[event.previousIndex];
        if (lastAddedRole !== undefined) {
          this.userRoleCopy.push(lastAddedRole.valueOf());
        }
        this.resetList();
      }
    }
  }
}


texts: Get all points within given radius for a given vector

texts:
I have a vector of ints that represents a point on a N-dimensional grid. I need to find all grid points that are within a given radius. I wrote the following, but it is rather inefficient, because it iterates through all points in a cube and checks the radius for each point:

typedef std::vector<int> VectI;

bool getNextInNSphere(VectI& x,int radius){
    int pos = 0;
    bool done = false;
    while (!done && pos < x.size()){
        x[pos]++;
        if (x[pos]>radius){ x[pos] = -radius; pos++; }
        else              { done = true; }
    }
    if (done){
        int sqsum = 0;
        for (size_t i=0;i<x.size();i++){ sqsum += x[i]*x[i]; }
        if (sqsum > radius*radius){ return getNextInNSphere(x,radius); }
    }
    return done;
}

usage:

void foo(const VectI& x,int radius){
    VectI d = VectI(x.size(),-radius);
    while (getNextInNSphere(d,radius)){
        // x+d is inside a sphere of given radius around x
    }
}

Any ideas how to get this more efficient and/or in a nicer way?


texts:
I have made this class for database connections to my applications. It eases out the task of making connections to the database with knowing the credentials in advance and provides a way to execute the queries.

Class dbConnection {

    public $CONN;
    private $dbservername, $dbusername, $dbpassword, $dbname;

    public function __construct() {

        $this->dbservername = "localhost";
        $this->dbusername = "dbroot";
        $this->dbpassword = "pass";
        $this->dbname = "test";
        $this->open(); //open the connection on instantization
    }

    public function open() {

    // Create connection
        $this->CONN = new mysqli($this->dbservername, $this->dbusername, $this->dbpassword, $this->dbname);

        // Check connection
        if ($this->CONN->connect_error) {
            die("Connection failed: " . $CONN->connect_error);

        }

    }

    public function prepare($query) {
    //prepare the data
        return $this->CONN->prepare($query);

    }

    public function close() {
    //close the connection
        $this->CONN->close();

    }

}

I am using prepared statements in the queries, of course.

I would like a review to determine if the function is feasible in all situations with performance and security on top considerations. I want to know if I should make any adjustments to it. Also, a comment on the coding style would be of great use.


texts: Find the maximum GCD of a number with respect to all the values in an array for competitive programming

texts:
Here is the Question. Find the largest GCD of the input variable with the values of an array.

Inputs are as follows:- First-line contains two integers, N and Q.

Second-line contains N integers which form the arr[].

Next, Q lines contain an integer M, the time in seconds she wishes to go back.

#include <stdio.h>

int main(){
    int n,q;
    scanf("%d %d", &n,&q);
    int a[n];
    int gcdn[n];
    for (int i = 0;i < n; i++) {
        scanf("%d",&a[i]);      }
    while (q>0){
        q--;
        int x;
        int max = 0;
        scanf("%d",&x);
        max = gcd(a[0],x);
        for(int i=0;i<n;i++) {
            int t = gcd(a[i],x);
            if(t > max)
                max = t;
        }
        printf("%d \n",max);
    }

}

int gcd (int a, int b) {
    if (b==0)
        return a;
    else
        return gcd(b, a%b);
}

How can I make this code better in terms of competitive programming? And what other languages can make this code better and more efficient?


texts: Concatenating an already existing filename to create a new file

texts:
I had answered this question from stackoverlow and the code below is code that I wrote to explain to the OP a possible way to achieve what I believe they were looking for.

The general idea that I got from them was that they were trying to open a file with a specified file name and if that file does exist that they in turn wanted to create a new file with the same filename but with extra characters appended to the filename.

This is the small program that I wrote to mimic that behavior.

#include <string>
#include <fstream>
#include <iostream>

int main() {
    std::string originalFilename("out.txt");
    std::string extension(".txt");
    std::string nextFilename;
    bool originalFileFound = false;

    // First test to see if original file exist by opening
    // if so then generate the next usable name
    std::fstream fileIn( originalFilename, std::ios::in );
    unsigned int counter = 0;

    if (fileIn.is_open()) {
        counter++;
        nextFilename = originalFilename.substr( 0, originalFilename.size() - extension.size() )
                       + "_" + std::to_string(counter) + extension;
        originalFileFound = true;
    }
    fileIn.close();

    // Generate a few files with the appended number system to
    // the end of the original filename if the original file was found.
    if ( originalFileFound ) {
        for ( int i = 1; i < 6; i++ ) {
            std::fstream nextFile;
            nextFile.open( nextFilename, std::ios::out );
            if (nextFile.is_open()) {
                nextFile << nextFilename; // Write this before updating...
                counter++;
                nextFilename = nextFilename.substr(0, nextFilename.find_first_of('_') + 1)
                               + std::to_string(counter) + extension;
            }
            nextFile.close();
        }
    }
    return 0;
}

I would like to know if there is a more elegant, more efficient and cleaner way to achieve this using modern C++. Writing this simple program in essence was basically self practice to improve my skills with string manipulation and the string's set of library functions and algorithms.


texts:
I'm using the following pattern in my mobile app. The code snippet below manages a stopwatch.

Is there a way to simplify the code for better readability and probably getting away from needing to use MyApp.stopwatch. inside it? Somehow in some cases using this instead works, and in some it doesn't.

And what about getting rid of using repeating var settings = MyApp.stopwatch.settings?

(function (MyApp, $, undefined) {

    // Using strict mode to throw exceptions for 'unsafe' actions and coding patterns
    'use strict';

    // Initializes app
    function init() {
        MyApp.stopwatch.init('startStopwatch', 'pauseStopwatch', 'resetStopwatch');
    }

    // Manages the stopwatch
    MyApp.stopwatch = {

        init: function (startButton, pauseButton, resetButton) {
            document.getElementById(startButton).addEventListener('click', MyApp.stopwatch.startTimer, false);
            document.getElementById(pauseButton).addEventListener('click', MyApp.stopwatch.pauseTimer, false);
            document.getElementById(resetButton).addEventListener('click', MyApp.stopwatch.resetTimer, false);

            MyApp.stopwatch.displayTimer();
        },

        settings: {
            timerId: -1,
            interval: 100,
            millis: 0,
            seconds: 0,
            minutes: 0
        },

        displayTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings            = MyApp.stopwatch.settings,
                millis              = Math.round(settings.millis / 100).toFixed(0),
                seconds             = settings.seconds,
                minutes             = settings.minutes;

            if (seconds < 10) {
                seconds             = '0' + seconds;
            }
            if (minutes < 10) {
                minutes             = '0' + minutes;
            }
            document.getElementById('stopwatch').innerHTML = minutes + ':' + seconds + ':' + millis;
        },

        updateTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings            = MyApp.stopwatch.settings;
            settings.millis         += settings.interval;
            if (settings.millis >= 1000) {
                settings.millis     = 0;
                settings.seconds    += 1;
            }
            if (settings.seconds >= 60) {
                settings.millis     = 0;
                settings.seconds    = 0;
                settings.minutes    += 1;
            }
            MyApp.stopwatch.displayTimer();
        },

        pauseTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings    = MyApp.stopwatch.settings;
            window.clearInterval(settings.timerId);
            settings.timerId = -1;
        },

        startTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings    = MyApp.stopwatch.settings;
            if (settings.timerId === -1) {
                settings.timerId = window.setInterval(MyApp.stopwatch.updateTimer, settings.interval);
            }
        },

        resetTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings    = MyApp.stopwatch.settings;
            MyApp.stopwatch.pauseTimer();
            settings.millis = 0;
            settings.seconds = 0;
            settings.minutes = 0;
            MyApp.stopwatch.displayTimer();
        }

    };

    // PhoneGap, jQuery & device is ready now -> initialize
    $(document).on('deviceready', init);

}(window.MyApp = window.MyApp || {}, jQuery));


texts:
I think I can refactor this:

if (clicked_id == "contain-word") {
  $("#specie_filter li.checked").removeClass("checked");
  $("#specie_filter li:first").addClass("checked")
  $("#specie_filter ul").scrollTop(0)

  $("#cell_filter li.checked").removeClass("checked")
  $("#cell_filter li:first").addClass("checked")
  $("#cell_filter ul").scrollTop(0)

  $("#factor_filter li.checked").removeClass("checked")
  $("#factor_filter li:first").addClass("checked")
  $("#factor_filter ul").scrollTop(0)
} else if (clicked_id == "specie_filter") {
  $("#cell_filter li.checked").removeClass("checked")
  $("#cell_filter li:first").addClass("checked")
  $("#cell_filter ul").scrollTop(0)

  $("#factor_filter li.checked").removeClass("checked")
  $("#factor_filter li:first").addClass("checked")
  $("#factor_filter ul").scrollTop(0)

} else if (clicked_id == 'cell_filter') {
  $("#factor_filter li.checked").removeClass("checked")
  $("#factor_filter li:first").addClass("checked")
  $("#factor_filter ul").scrollTop(0)
}

it into something like

if (clicked_id == "contain-word" | clicked_id == "specie_filter"`)

but that will make the code more complex and the duplicity still exists in the conditional statement.  Does anyone have ideas about refactoring this?


texts: Check if the user is 18 years old (upto days)

texts:
This code is returning 'true' for any date which are later than Feb 24, 1998.

//minimumAge is number of years i.e., 18
public boolean isUser18Older (DateTime userDob, int minimumAge){
    DateTime minAge = new DateTime();
    Days days = Days.daysBetween(userDob, minAge.minusYears(minimumAge));

    return days.getDays()>=0 ;
}

I am not sure about my minAge.minusYears code.


texts: UPenn CIS 194 Homework 4: Higher-order programming

texts:
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.

HW4 - Higher-order programming - Full description

import Data.List

-- Exercise 1
-- Reimplement each of the following functions in a more idiomatic Haskell style

fun1 :: [Integer] -> Integer
fun1 [] = 1
fun1 (x:xs)
  | even x = (x - 2) * fun1 xs
  | otherwise = fun1 xs

fun1' :: [Integer] -> Integer
fun1' = product . map (\x -> x - 2) . filter even

fun2 :: Integer -> Integer
fun2 1 = 0
fun2 n | even n = n + fun2 (n `div` 2)
       | otherwise = fun2 (3 * n + 1)

fun2' :: Integer -> Integer
fun2' = sum . filter even . takeWhile (\x -> x > 1) . iterate (\x -> if (even x) then div x 2 else 3 * x + 1)

-- Exercise 2
-- Generates a balanced binary tree from a list of values using foldr

data Tree a = Leaf
            | Node Integer (Tree a) a (Tree a)
  deriving (Show, Eq)

foldTree :: [a] -> Tree a
foldTree = foldr makeTree Leaf

makeTree :: a -> Tree a -> Tree a
makeTree a Leaf = Node 0 Leaf a Leaf
makeTree a (Node h l m r)
   | height l <= height r = Node (height (makeTree a l) + 1) (makeTree a l) m r
   | otherwise = Node (height (makeTree a r) + 1) l m (makeTree a r)
  where
    height Leaf = -1
    height (Node h _ _ _) = h

-- Exercise 3
-- More folds:

-- implement a function which returns True if and only if there are a odd number of True values contained in the input list
xor :: [Bool] -> Bool
xor = odd . foldr (\x s -> if (x) then 1 + s else s) 0

-- map’ should behave identically to the standard map function
map' :: (a -> b) -> [a] -> [b]
map' f = foldr (\x xs -> (f x) : xs) []

-- implement foldl using foldr
myFoldl :: (a -> b -> a) -> a -> [b] -> a
myFoldl f base xs = foldr (\x s -> f s x) base (reverse xs)

-- Exercise 4
-- Implement the Sieve of Sundaram algorithm using function composition

sieveSundaram :: Integer -> [Integer]
sieveSundaram n = map (\x -> 2 * x + 1) (genSieve n)
  where
    valid x = (i <= j) && (i + j + 2 * i * j <= n) where (i, j) = x
    genCrossed m = map (\(i, j) -> (i + j + 2 * i * j)) (filter valid (cartProd [1..m] [1..m]))
    genSieve n = (\\) [1..n] (genCrossed n)

cartProd :: [a] -> [b] -> [(a, b)]
cartProd xs ys = [(x,y) | x <- xs, y <- ys]