texts: Generic function for interpolating missing values in power query

texts:
I have written a (relatively) generic function for interpolating values in power query (also useful for power bi and m code).
I am looking for any improvements or input, but especially:

speed
handle more inputs correctly (more generic)
documentation / readability of code

(Input as table, xColumn as text, yColumn as text) =>
//Interpolates missing yColumn values based on nearest existing xColumn, yColumn pairs
let
    Buffer = Table.Buffer(Input),
    //index for joining calculations and preserving original order
    #"Added Main Index" = Table.AddIndexColumn(Buffer, "InterpolateMainIndex", 0, 1),
    #"Two Columns and Index" = Table.RemoveColumns(#"Added Main Index", List.Select(Table.ColumnNames(#"Added Main Index"), each _ <> xColumn and _ <> yColumn and _ <> "InterpolateMainIndex")),
    #"Remove Blanks" = Table.SelectRows(#"Two Columns and Index", each Record.Field(_, yColumn) <> null and Record.Field(_, yColumn) <> ""),
    //index for refering to next non-blank record
    #"Added Sub Index" = Table.AddIndexColumn(#"Remove Blanks", "InterpolateSubIndex", 0, 1),
    //m = (y2 - y1) / (x2 - x1)
    m = Table.AddColumn(#"Added Sub Index",
                        "m",
                        each    (Number.From(Record.Field(_, yColumn))-Number.From(Record.Field(#"Added Sub Index"{[InterpolateSubIndex]+1}, yColumn))) /
                                (Number.From(Record.Field(_, xColumn))-Number.From(Record.Field(#"Added Sub Index"{[InterpolateSubIndex]+1}, xColumn))),
                        type number),
    //b = y - m * x
    b = Table.AddColumn(m, "b", each Record.Field(_, yColumn) - [#"m"] * Number.From(Record.Field(_, xColumn)), type number),
    //rename  or remove columns to allow full join
    #"Renamed Columns" = Table.RenameColumns(b,{{"InterpolateMainIndex", "InterpolateMainIndexCopy"}}),
    xColumnmb = Table.RemoveColumns(#"Renamed Columns",{yColumn, xColumn, "InterpolateSubIndex"}),
    Join = Table.Join(#"Added Main Index", "InterpolateMainIndex", xColumnmb, "InterpolateMainIndexCopy", JoinKind.FullOuter),
    //enforce orignal sorting
    #"Sorted by Main Index" = Table.Sort(Join,{{"InterpolateMainIndex", Order.Ascending}}),
    #"Filled Down mb" = Table.FillDown(#"Sorted by Main Index",{"m", "b"}),
    //y = m * x + b
    Interpolate = Table.ReplaceValue(#"Filled Down mb",null,each ([m] * Number.From(Record.Field(_, xColumn)) + [b]),Replacer.ReplaceValue,{yColumn}),
    //clean up
    #"Remove Temporary Columns" = Table.RemoveColumns(Interpolate,{"m", "b", "InterpolateMainIndex", "InterpolateMainIndexCopy"}),
    #"Restore Types" = Value.ReplaceType(#"Remove Temporary Columns", Value.Type(Input))
in
    #"Restore Types"

Lastly, there were no tags for power query, power bi, or interpolating. I'm not sure what other tags I can use for this post besides excel.


texts: Performing FFTW double[2] on images of type cv::Mat

texts:
I've two different types of variables: cv::Mat and array of type double[2] so I do quite lot of copying between the two types.
I feel like my code isn't written well and could be improved, I'm trying to avoid lot of copying and get rid of all unuseful calculations.

I'm using fftw because it is known that it is very fast computing the fft. So making the algorithm run faster is also important for me as it will be performed in real time applications.

The code below is part of the algorithm where I'm using fftw library to perform FFT on images

//Copying my normalized image to data_in of type double[2]
for(auto j=0, k = 0;j<src.rows;j++)
        for(auto i=0;i<src.cols;i++)
        {
            data_in[k][0] = (double) src.at<float>(j,i)/A;
            data_in[k][1] = 0.0;
            k++;
        }

    //FFT of data_in and store it in double[2] fft variable
    fftw_execute( plan_data_in );

    //product of double[2] fft and cv::Mat kernel_fft and store it in double[2] fftPro
for(auto j=0, k = 0;j<src.rows;j++)
        for(auto i=0;i<src.cols;i++)
        {
            fftPro[k][0] = fft[k][0] * kernel_fft.at<cv::Vec2f>(j,i)[0] - fft[k][1] * kernel_fft.at<cv::Vec2f>(j,i)[1];
            fftPro[k][1] = fft[k][0] * kernel_fft.at<cv::Vec2f>(j,i)[1] + fft[k][1] * kernel_fft.at<cv::Vec2f>(j,i)[0];
            k++;
        }

///////////// FFT inverse
    // FFT inverse of double[2] fftPro ans stor in double[2] data_out
    fftw_execute( plan_data_out );

    //Normalization
    for(auto i = 0 ; i < ( kernel_fft.cols * kernel_fft.rows ) ; i++ )
        data_out[i][0] /= ( double )( kernel_fft.cols * kernel_fft.rows );

    //fft to mat
    cv::Mat ifftMat=cv::Mat::zeros(src.rows, src.cols, CV_32FC1);
    for(auto j=0, k = 0;j<kernel_fft.rows;j++)
        for(auto i=0;i<kernel_fft.cols;i++)
            ifftMat.at<float>(j,i)=data_out[k++][0];

Could you spot any part could be improved in this code?

EDIT:

I didn't share all the code, if you want it all I can share it but I wanted to be specific and not share all the code that takes time to read and understand. This is all declarations:

data_in = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * kernel_fft.cols * kernel_fft.rows );

fft     = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * kernel_fft.cols * kernel_fft.rows );

fftPro     = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * kernel_fft.cols * kernel_fft.rows );

data_out    = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * kernel_fft.cols * kernel_fft.rows );

plan_data_in = fftw_plan_dft_1d( kernel_fft.cols * kernel_fft.rows, data_in, fft,  FFTW_FORWARD,  FFTW_ESTIMATE );

plan_data_out = fftw_plan_dft_1d( kernel_fft.cols * kernel_fft.rows, fftPro, data_out, FFTW_BACKWARD, FFTW_ESTIMATE );


texts:
I have created a clock divider that works as follows:

If the division factor is 0, pass the clock through unchanged.
Otherwise, flip the output clock signal after the specified number of input clock cycles has passed.

I am relatively new to hardware design, so I would like advice on general best practices that I may have violated, as well as whether there would be any robustness issues. (I know that the output clock will be delayed since it passes through gates, but I don't think this is a problem as long as downstream logic does not attempt to use both clocks simultaneously.)

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity config_clk_div is
    Port ( clk : in STD_LOGIC;
           divfactor : in STD_LOGIC_VECTOR (15 downto 0);
           clkout : out STD_LOGIC);
end config_clk_div;

architecture Behavioral of config_clk_div is
    signal clk_counter : UNSIGNED(15 downto 0);
    signal current_clk : STD_LOGIC;
begin
    process (clk, divfactor) is
    begin
        if divfactor = x"0000" then
            clkout <= clk;
            current_clk <= clk;
        else
            if rising_edge(clk) then
                clk_counter <= clk_counter + 1;
                if clk_counter >= unsigned(divfactor) then
                    clk_counter <= to_unsigned(1,16);
                    current_clk <= not current_clk;
                    -- Not here as well to avoid lag
                    clkout <= not current_clk;
                else
                    clkout <= current_clk;
                end if;
            end if;
        end if;
    end process;

end Behavioral;


texts: Android RecyclerView holding rows of razzles

texts:
I have a RecyclerView that works and everything, and this is how I coded it:

public class RazzleRecyclerViewAdapter extends RecyclerView.Adapter<RazzleRecyclerViewAdapter.RecyclerViewHolder> {
    private List<Razzle> mRazzleList;
    private Context mContext;
    private SelectRazzleRowListener mSelectRazzleRowListener;

    public RazzleRecyclerViewAdapter(
            Context context,
            List<Razzle> razzleList,
            SelectRazzleRowListener selectRazzleRowListener) {
        mContext = context;
        mRazzleList = razzleList;
        mSelectRazzleRowListener = selectRazzleRowListener;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new RecyclerViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_razzle_row, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        holder.bindRow(mRazzleList.get(position), position);
    }

    @Override
    public int getItemCount() {
        return mRazzleList.size();
    }

    public class RecyclerViewHolder extends RecyclerView.ViewHolder {
        public int thisPosition;
        public Razzle mThisRazzle;
        public TextView razzleNameTextView;

        public RecyclerViewHolder(View itemView) {
            super(itemView);
            razzleNameTextView = (TextView) itemView.findViewById(R.id.item_razzle_row_textview_razzle_name);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelectRazzleRowListener.launchRazzleDetailsActivity(mThisRazzle, thisPosition);
                }
            });
        }

        public void bindRow(final Razzle razzle, int position) {
            mThisRazzle = razzle;
            thisPosition = position;
            razzleNameTextView.setText(razzle.getRazzleName());
        }

    }
}

How can I code this better? Can I make it clearer? Am I following good conventions? Can I restructure it so it's easier to work with? In particular, the ViewHolder stuff?


texts:
I have a section of code that I've been attempting to clean up and hopefully speed up. The section of code where I pass values in order to generate a key and update a table on a different sheet I think is my biggest problem. However I would like any suggestions/modifications to clean this section up first.

An overview is my worksheet has a header section where the user will update the monthly  sales,units or avg. cost field. Once this is done I need to recalculate all values in that month. This is anywhere from 10 to 1200 rows. As the update executes the following occurs:

Cell is updated with the impact of the header change.
A new unique key is built.
The new key is found in a table and the change value is inserted.

I was stuck manually changing the "ColumnCount" variable to maintain the offset in the proper position. Any help would be great.

'Table update afet net units header update
Dim i As Integer
'LastRow used to determine final used row on worksheet
    LastSourceRow = LastRow(destsheet, "B")
'Column Count initially set to -2 to offset target to desired cell
    ColumnCount = -2
    RowCount = 1

'Runs from row 1 to the last row on the sheet
For RowCount = 1 To LastSourceRow Step 5
    i = 5
    'After header change offset 5 rows and 2 columns back to capture cell change

    Set target = target.Offset(i, ColumnCount)

        'Running Status
        Application.StatusBar = "Target value change : " & target.Row & " of " & LastSourceRow & " " & Format(target.Row / LastSourceRow, "Percent")

            'If change cell is 0 then skip and sel column count to 0 to keep offset aligned
            If target = 0 Then

            'Do Nothing if 0 value
            ColumnCount = 0
            Else

                'Generate unique key and pass to table update module
                modTableUpdate.TableUpdate target, destsheet, sourcesheet, ColumnHeader, ColumnFormula, Celladdress, Key, cell, result

                'offset target by 1 to capture change
                ColumnCount = 1

                'Set target offset to new cell
                Set target = target.Offset(, ColumnCount)

                'Generate key and pass target offset value to table update module
                modTableUpdate.TableUpdate target, destsheet, sourcesheet, ColumnHeader, ColumnFormula, Celladdress, Key, cell, result

                'Set target offset back to original cell
                ColumnCount = -1

                Set target = target.Offset(, ColumnCount)
                'Set column count to 0 to maintain alignment when loop repeats

                ColumnCount = 0
            End If
Next RowCount


texts: Converting dataframe columns to binary columns

texts:
I basically want to convert all categorical column in an R dataframe to several binary columns:

For example, a categorical column like

Company
-------
IBM
Microsoft
Google

will be converted to 3 columns:

Company_is_IBM   Company_is_Microsoft    Company_is_Google

 1                 0                       0
 0                 1                       0
 0                 0                       1

However, my code runs very slowly on my testing data, which should generate a 900 column*367 row data frame.

I'm attaching the code in to test with my dataset, simply by extracting the source code package, set working directory (setwd) to the source code files directory like shown in the picture (in archive), and run:

gpudataf = read.table("gpudataf.txt")
gpudataf_bin = ConvertCategoricalDataFrameToBinaryKeepingOriginals(gpudataf)

and you will see how slow it is.

Source code archive

source("IsCategorical.R")

# Function CategoricalToBinary: Take a data.frame, determine which columns are categorical,
# if categorical, convert the categorical column to several binary columns with values 0 and 1

#input: a Categorical Column, name of that column. Output: a data frame of multiple     binary columns.
ConvertCategoricalColumnToBinaryColumns <- function(catecol,prefix = "")
{
  set_values = unique(catecol)
  returnvalue = data.frame("ru9uGEQu" = catecol) #temporary frame no one will hit
  returnvalue[["ru9uGEQu"]] <- NULL #I just did it for the number_rows compatible!

  for(val in set_values){
    newcolName = paste(prefix, val, sep = "_is_")
    returnvalue[[newcolName]] <- Map(function(x){return (if(x==val) 1 else 0)}, catecol)
  }

  return(returnvalue)
}

#input: a dataframe_with_categorical columns, and extra categorical column names,
# if that column is categorical
# but all of numerical denotations
#output: the categorical columns are replaces by binary columns.

ConvertCategoricalDataFrameToBinary <- function(dataframe_with_cat_column, categoricalColumns=list())
{
  colNames= colnames(dataframe_with_cat_column)
  returnvalue = data.frame("ru9uGEQu" = dataframe_with_cat_column[[colNames[1]]])
  returnvalue[["ru9uGEQu"]] <- NULL

  for(columnName in colnames(dataframe_with_cat_column)){
    # print(columnName)
    if(IsCategorical(dataframe_with_cat_column[[columnName]]) || (columnName %in% categoricalColumns)){
      binary_dataframe = ConvertCategoricalColumnToBinaryColumns(dataframe_with_cat_column[[columnName]],prefix = columnName)
      # attach/insert it to the returnvalue
      for(binColName in colnames(binary_dataframe)){
        returnvalue[[binColName]] = binary_dataframe[[binColName]]
      }
    }
    else{
      # that column is numerical, don't change it.
      returnvalue[[columnName]] = dataframe_with_cat_column[[columnName]]
    }
  }
  return(returnvalue)
}

# if you want to keep the original values in the returned dataframe.

ConvertCategoricalDataFrameToBinaryKeepingOriginals <- function(dataframe_with_cat_column, categoricalColumns=list())
{
  without = ConvertCategoricalDataFrameToBinary(dataframe_with_cat_column, categoricalColumns)
  returnvalue = dataframe_with_cat_column

  existing_colNames = colnames(returnvalue)

  for(coln in colnames(without)){
    if(!(coln %in% existing_colNames)){
      returnvalue[[coln]] = without[[coln]]
    }
  }
  return(returnvalue)
}


texts: Displaying completed and failed wuuks using one or two functions

texts:
I have upgraded my code. In the old code I had two functions: display_maker_success() and display_maker_fail():

function display_maker_success($link, $userid){
    $status="closed";
    $result="completed";

    $html = '';
    $sql = "select start, name from wuuk where tasker_id ='$userid' and status ='$status' and result ='$result' order by id desc LIMIT 6;";

    $result = mysql_query($sql, $link);
    $isempty=mysql_num_rows($result);
    If ($isempty ==0) {
        $html .= "No Record";
    } else {
        $html .= "
";
        $html .= "
Date & Time	Name	Status
";
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            $html .= "
$row[0]	$row[1]	Completed
";
        };
        $html .= "
";
    };
    echo $html;
};

function display_maker_fail ($link, $userid) {
    $status="closed";
    $result="fail";

    $sql = "select start, name from wuuk where tasker_id ='$userid' and status ='$status' and result ='$result' order by id desc LIMIT 1;";
    $result = mysql_query($sql, $link);
    $isempty=mysql_num_rows($result);
    If($isempty ==0){
        $html .= "No Record";
    } else {
        $html .= "
";
        $html .= "
Date & Time	Name	Status
";
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            $html .= "
$row[0]	$row[1]	fail
";
        };
        $html .= "
";
    };
    echo $html;
};

But I realised I can combine those two functions into one display_maker_stat() by putting more arguments into the function. I like it very much!

function display_maker_stat($link, $userid, $reuslt = 'fail', $limit)
{
    $status = "closed";
    $html = '';
    $sql = "select start, name from wuuk where tasker_id ='$userid' and status ='$status' and result ='$result' order by id desc LIMIT 1;";
    $query = mysql_query($sql, $link);
    if (mysql_num_rows($query) != 0) {
        $html .= "
";
        $html .= "
Date & Time	Name	Status
";
        while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
            $html.= "
$row[0]	$row[1]	$result
";
        }
        $html.= "
";

    }
    else {
        $html.= "No Record";
    }
    echo $html;
}

Is there a better way to do this? I want more code reuse.


texts:
This is a jQuery function that controls a
 to expand up or expand down. I am trying to simplify and optimize these lines of codes.

Scenerio

By default, it does not have any classes in
.

When I clicked on
, it adds .expand-up into this
 if there .expand-up class. When I clicked on
 it should remove .expand-up from
 and only remove if there is .expand-down.

$(document).ready(function() {
  $('.title-wrapper').click(function() {
    $(this).parent().toggleClass('active').delay('1500').promise().done(function() {
      var filterSearch = $(this).children('.title-wrapper');
      // Check if have expand-up classes
      if (filterSearch.hasClass('expand-up')) {
        filterSearch.removeClass('expand-up');
        filterSearch.addClass('expand-down');
      } else {
        // Remove expand down if the class is existed
        if (filterSearch.hasClass('expand-down')) {
          filterSearch.removeClass('expand-down');
        }
        filterSearch.addClass('expand-up');
      }
    });
  });
});
body {
  font-size: 62.5%;
  font-family: 'Roboto', sans-serif;
  color: #FFF;
}
.filter-search {
  background-color: #a78464;
}
.filter-search .wrapper {
  width: 100%;
  text-align: center;
  height: 10em;
  transition: height linear 1s;
}
.filter-search .wrapper .title-wrapper {
  display: inline-block;
}
.filter-search .wrapper .title-wrapper h2 {
  font-size: 3em;
  margin-bottom: 0;
}
.filter-search .wrapper .title-wrapper span {
  font-size: 1.4em;
  display: block;
  text-transform: uppercase;
  margin-bottom: 2em;
}
.filter-search .wrapper.active {
  height: 15em;
  transition: height linear 1s;
}
.filter-search .expand-up {
  -webkit-animation: moveUp ease-in 1;
  animation: moveUp ease-in 1;
  animation-fill-mode: forwards;
  animation-duration: .5s;
}
.filter-search .expand-down,
.filter-search .expand-up {
  -webkit-animation-fill-mode: forwards;
  -webkit-animation-duration: .5s;
}
.filter-search .expand-down {
  -webkit-animation: moveDown ease-out 1;
  animation: moveDown ease-out 1;
  animation-fill-mode: forwards;
  animation-duration: .5s;
}
@-webkit-keyframes moveUp {
  0% {
    margin-top: 0;
  }
  to {
    margin-top: -1em;
  }
  ;
}
@keyframes moveUp {
  0% {
    margin-top: 0;
  }
  to {
    margin-top: -1em;
  }
  ;
}
@-webkit-keyframes moveDown {
  0% {
    margin-top: -1em;
  }
  to {
    margin-top: 0;
  }
  ;
}
@keyframes moveDown {
  0% {
    margin-top: -1em;
  }
  to {
    margin-top: 0;
  }
  ;
}
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    search

Filter Search

      Click to expand


texts:
In a project I'm working on, the data access layer has evolved to something that somewhat resembles the Unit Of Work and Repository patterns, at least they started with those names, I'm not entirely sure with how far they've drifted, if they can still be called that.

For classes data access, an implementation IWorkUnitFactory is passed as a constructor parameter from the IoC container. This is a rather simple interface:

public interface IWorkUnitFactory
{
    IWorkUnit Begin();
}

The IWorkUnit interface it returns looks like this:

public interface IWorkUnit : IDisposable
{
    T Insert<T>(T entity) where T : class;
    T Load<T>(int id) where T : class;
    void Delete<T>(int id) where T : class;
    void Delete<T>(T entity) where T : class;
    T Update<T>(T entity) where T : class;
    T InsertOrUpdate<T>(T entity) where T : class;
    IQueryable<T> Query<T>() where T : class;
    IEnumerable<T> Execute<T>(string queryName, IDictionary<string, object> parameters);

    void Commit();
    void Rollback();
}

My IWorkUnitFactory implementation for NHibernate basically just creates an NHibernate session, and passes it to the NHibernate implementation of IWorkUnit, which is just a rather thin wrapper around the NHibernate session, which starts a transaction in its constructor, and rolls it back in the Dispose implementation unless the Commit method is called.

Then, anywhere data access happens, it follows this pattern:

using(var workUnit = WorkUnitFactory.Begin())
{
    //Boring data access code here
    workUnit.Commit();
}

Next up are the Repository classes. These don't have any common inheritance or interface implementations, they just follow a few conventions, the main one being taking an IWorkUnit in its constructor. These classes contain the interaction with the IWorkUnit for operations like GetById, Find, Insert, Update, etc, and are responsible for small bits of logic (the Update method updates the LastUpdated field on the entity, Find determines what fields to search based on its parameters, etc).

So, for example, a Repository for the User entity might look something like this:

public class UserRepository
{
    private readonly IWorkUnit workUnit;
    public UserRepository(IWorkUnit workUnit)
    {
        this.workUnit = workUnit;
    }
    public virtual User GetByEmail(string email)
    {
        return workUnit.Query<User>().FirstOrDefault(u => u.Email == email);
    }
    public virtual User Update(User user, User updater)
    {
        user.ModifiedBy = updater;
        user.Modified = DateTimeOffset.Now;
        return workUnit.Update(user);
    }
}

Then, code to update a user would look something like this:

using(var workUnit = WorkUnitFactory.Begin())
{
    var userRepo = new UserRepository(workUnit);
    var userToEdit = userRepo.GetByEmail("test@example.com");

    //Do some stuff to userToEdit here

    userRepo.Update(userToEdit, currentRequestUser); //currentRequestUser is just whoever is performing the action
    workUnit.Commit();
}

Any feedback on better naming for these things, or better methods? This has served me rather well, with the only thing I don't really like is creating the repository instances like that, But I can't think of a way to handle transactions and keep the somewhat lower level data access code away from higher level business logic.


texts:
This code simulates a distributed averaging protocol. There is a network of nodes, and at the clicks of a Poisson process:

A random node wakes up
Transmits it's current average to all the nodes it is connected to
These nodes have a coroutine which waits to accept new values and compute the average.

from numpy.random import exponential, randint, uniform
import time
from itertools import product

class Node(object):
    def __init__(self, number):
        self.friends = []
        self.count = 0
        self.val = number
        self.average = number
        self.avg = self.averager()
        self.avg.next()

    def averager(self):
        while True:
            term = yield self.average
            self.val += term
            self.count += 1
            self.average = self.val/self.count

class Network(object):
    def __init__(self, num_nodes):
        self.nodes = [0]*num_nodes
        for i in range(num_nodes):
            self.nodes[i] = Node(randint(1, 10))
        self.set_connections()

    def set_connections(self):
        for f, g in product(self.nodes, self.nodes):
            p = uniform()
            if p < 0.8:
                f.friends.append(g)
                g.friends.append(f)

    def mainloop(self):
        num_nodes = len(self.nodes)
        while True:
            next_time = exponential(0.1)
            node = self.nodes[randint(num_nodes)]
            for friend in node.friends:
                friend.avg.send(node.average)
                print friend.average
            time.sleep(next_time)

So far I've only tested it as follows:

>>> n = Network(10)
>>> n.mainloop()

and then observed that the friend.average printed out all converge to the same value.

My main concern about this code is that a lot of the logic for waking up nodes is in the Network class, whilst I'd rather it was in the node class. Also, there's no exception/error handling, or proper testing.

The main purpose of this was to try and understand coroutines, which was a bit of a mind bender.


texts: Python script using Minneapolis / St. Paul Metro Transit's API to tell you how long till next bus

texts:
I have written a program which will tell you how long it is until the next bus on “BUS ROUTE” leaving from “BUS STOP NAME” going “DIRECTION” using the api defined at http://svc.metrotransit.org/.

Example:

$ metro.py "metro blue line" "target field station platform 1" "south"
6 minutes

I am very new to Python and wondering how this code could be better — more efficient, follow best practices, etc. What would you do differently?

import requests, sys, time

# need to have each: route, stop & direction
if len(sys.argv) != 4:
    sys.exit("Please be sure to enter a route, stop, and direction.")

route = sys.argv[1]
stop = sys.argv[2]
direction = sys.argv[3]

url = "http://svc.metrotransit.org/NexTrip/"

def getData (uri, key, value, arg):
    resp = requests.get(url + uri + "?format=json")
    data = resp.json()

    # default in case of invalid input
    dataID = -1

    while True:
        try: sys.exit(uri + str(resp.status_code))

        except:
            for item in data:
                if item[key].lower().find(arg) > -1:
                    dataID = item[value]
                    break
            return dataID

routeID = getData("Routes", "Description", "Route", route)

if routeID < 0:
    sys.exit(route + " is not a valid route.")

uri = routeID
directionID =  getData("Directions/" + uri, "Text", "Value", direction)

if directionID < 0:
    sys.exit(route + " does not go " + direction + ".")

uri += "/" + directionID
stopID = getData("Stops/" + uri, "Text", "Value", stop)

if stopID < 0:
    sys.exit(stop + " is not along " + route + " going " + direction + ".")

uri += "/" + stopID
timeID = getData(uri, "RouteDirection", "DepartureTime", direction)

if timeID != -1:
    #Get 10 digit timestamp from response, - from current time, and / by 60 to get minutes as an integer
    time = int((float(timeID[6:16]) - time.time()) // 60)
    if time > 1:
        print str(time) + " minutes"
    else:
        print "1 minute or less"


texts:
I've recently been asked to make some emergency changes to a legacy application written in VB.NET.  I come from a C# background so am not overly familiar with this language, though there are enough similarities for me to get by.

The current code has no separation of concerns (e.g. DAL code is written in the codebehind of each page rather than separated out).  To make it usable without introducing too much risk I'm avoiding libraries but extracting the DAL code to separate classes.  Since my DB code's going to be used from a lot of places in the app, I wanted to check that this all makes sense, that it is reasonably efficient and that I haven't made some schoolboy error in creating this.

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Collections.Generic

Public Class DB

    Private _connectionString As String

    Public Sub New(connectionString As String)
        _connectionString = connectionString
    End Sub

    Public Sub ExecuteNonQuery(cmdTxt As String, params As Dictionary(Of String, Object))
        Using cmd As SqlCommand = BuildCommand(cmdTxt, params)
            cmd.ExecuteNonQuery()
        End Using
    End Sub

    Public Function ExecuteReader(cmdTxt As String, params As Dictionary(Of String, Object)) As SqlDataReader
        Using cmd As SqlCommand = BuildCommand(cmdTxt, params)
            Return cmd.ExecuteReader()
        End Using
    End Function

    Public Function ExecuteScalar(cmdTxt As String, params As Dictionary(Of String, Object)) As Object
        Using cmd As SqlCommand = BuildCommand(cmdTxt, params)
            Return cmd.ExecuteScalar()
        End Using
    End Function

    Private Function BuildCommand(cmdTxt As String, params As Dictionary(Of String, Object)) As SqlCommand
        Using con As New SqlConnection(_connectionString)
            Using cmd As SqlCommand = con.CreateCommand()
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = cmdTxt
                AddParameters(cmd, params)
                con.Open() 'working on the assumption this command will be run as soon as it's retuned; so this open is left as late as possible but here to avoid duplicate code
                Return cmd
            End Using
        End Using
    End Function

    Private Sub AddParameters(ByRef cmd As SqlCommand, params As Dictionary(Of String, Object))
        If Not params Is Nothing Then
            For Each kvp As KeyValuePair(Of String, Object) In params
                cmd.Parameters.AddWithValue(kvp.Key, kvp.Value)
            Next
        End If
    End Sub

End Class


texts: Detect resolution of X display and change font accordingly

texts:
This is my first attempt at anything functioning within elisp. This script is part of my configuration file that I use across multiple machines, one of which is hi-dpi and the other is not. To avoid having to reset my default font size every time I pull from my remote repository, I thought it would be nice to write a function to detect the size of the screen and adjust the font size accordingly.

(if (and (eq 3840 (x-display-pixel-width))
         (eq 2160 (x-display-pixel-height)))
  (setq-default dotspacemacs-default-font '("Source Code Pro" :size 34))
  (setq-default dotspacemacs-default-font '("Source Code Pro" :size 18)))
)

It feels a bit repetitious, but I am not comfortable enough with the language to even see how I could simplify anything. Initially I tried to set a font-size variable, but it did not seem to be able to traverse functions easily (i.e. it was set at a local scope).


texts: Sending activation email for sqlmembership

texts:
private void SendActivationEmail(MembershipUser user)
{
    var message = new MailMessage();
    message.To.Add(user.Email);
    message.Subject = "Attorney Event Notification Activation";

    string urlBase = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
    string ActivationUrl = "/ActivateUser.aspx?ID=" + GetUserID(user.Email);
    var fullPath = urlBase + ActivationUrl;

    using (StreamReader sr = new StreamReader(Request.PhysicalApplicationPath + "ActivationTemplate.txt"))
    {
        message.Body = sr.ReadToEnd();
    }

    message.Body = message.Body.Replace("<%UserName%>", user.UserName);
    message.Body = message.Body.Replace("<%ActivationURL%>", fullPath);
    message.IsBodyHtml = true;

    using (var smtpClient = new SmtpClient())
    {
        smtpClient.Send(message);
    }
}

How can I clean up this activation email sender?

And is it relatively safe?


texts: Print a word with numbers substituted for characters

texts:
I wrote the following Python program to take 1 word from the user and return certain characters replaced by numbers. Given a dictionary, the program should print all possible combinations of the same word with various characters substituted:

import sys

def main(argv):

    if len(argv) != 2:
        print(f"USAGE: {argv[0]} [word]")
        return

    replacements = {}

    # Populate the known replacements
    replacements['i'] = ['1']
    replacements['e'] = ['3']
    replacements['m'] = ['/v\\']
    replacements['a'] = ['4']
    replacements['r'] = ['2']
    replacements['o'] = ['0']

    print_possibilities(argv[1], replacements, [])

def print_possibilities(s: str, replacements: dict, dupes: list):
    ctr = 0
    tally = 0
    for c in s:
        if c.lower() in replacements:
            tally += 1
    if tally == 0:
        return

    for c in s:
        if c.lower() in replacements:
            for r in replacements[c.lower()]:
                tmp = list(s)
                tmp[ctr] = r
                as_str = ''.join(tmp)
                if as_str in dupes:
                    continue
                print(as_str)
                dupes.append(as_str)
                print_possibilities(as_str, replacements, dupes)
        ctr += 1
    return

if __name__ == '__main__':
    main(sys.argv)

I've tested with python3 replace_word.py mondoman and I get this output:

/v\ondoman
/v\0ndoman
/v\0nd0man
/v\0nd0/v\an
/v\0nd0/v\4n
/v\0nd0m4n
/v\0ndo/v\an
/v\0ndo/v\4n
/v\0ndom4n
/v\ond0man
/v\ond0/v\an
/v\ond0/v\4n
/v\ond0m4n
/v\ondo/v\an
/v\ondo/v\4n
/v\ondom4n
m0ndoman
m0nd0man
m0nd0/v\an
m0nd0/v\4n
m0nd0m4n
m0ndo/v\an
m0ndo/v\4n
m0ndom4n
mond0man
mond0/v\an
mond0/v\4n
mond0m4n
mondo/v\an
mondo/v\4n
mondom4n

I feel that this could be improved to be more performant and more idiomatic and would like a code review.


texts:
My goal was to create a function as performant as possible with results being:

True/False as to whether wild matches str.
Optional capture of certain patterns.

My purposes required:

Case sensitive match.
Pattern must match entire string to succeed.
Assumption that * and ? do not exist in str.
* matches zero or more characters.
? matches exactly one character.
Lazy * in this case meaning that going from left to right, * would match as little as possible while still ensuring a match if such were possible.

It's been a challenge as many times I almost had it but then found an edge case that didn't work.  This is basically globbing, but I need such to work for strings rather than files and I also hoped to make something much faster than using a regex which IMHO would be overkill for my needs.

I have tested the following to work on many patterns but I can't be certain yet if there isn't a permutation where it fails.  I would be very interested if anyone can point out a situation where it fails the terms set above.  I'm also interested to hear if there are any ways the code can be improved (made faster).

Hacks like (unsigned)(*wild-40)<=1 are probably unnecessary given the ability of gcc to optimize, but I put it in there anyway.

static __attribute__ ((noinline)) int globSearch(char *wild,char *str,char **c)
  {
  int N=-1,n=0,nm=0;

  while(*str)
      {
      if(*wild == '*'){ N=n; wild++; }
      else if((unsigned)(*wild-40)<=1) // faster version of if(*wild=='('||*wild==')')
          {
          c[n++]=str;
          wild++;
          }
      else if(*wild == '?'){ wild++; str++; }
      else if(*wild == *str)
          {
          if(nm){while(N < n){ c[N++]+=nm; }}
          nm=0;
          N=-1;
          wild++;
          str++;
          }
      else if(N > -1){ str++; nm++; }
      else return 0;
      }

    while((unsigned)(*wild-40) <= 2) // while( *wild == '(' || *wild == ')' || *wild == '*' )
        {
        if(*wild++ != '*')c[n++]=str;
        }
    if(nm){while(N < n){ c[N++]+=nm; }}

    return !*wild;
    }

Testing function

int main()
    {
    char tmp[100]={0};
    char *c[20]={0};
    char *m="(hello) (*)(?*?)?(?)?(*)(*)";
    char *str="hello world";

    int t=globSearch(m,str,c);

    if(t)
        {
        for(int x=0;c[x]&&c[x+1];x+=2)
            {
            int z=c[x+1]-c[x];
            memcpy(tmp,c[x],z);
            tmp[z]=0;
            printf("%s:%d\n",tmp,z);
            }
        }
    return 0;
    }

The above code returns successful match with patterns captured: (hello:5) (0) (wo:2) (l:1) (0) (0)

Other patterns and results:

*(hello*)* -> (hello:5)
hello *(d) -> (d:1)
(hello) (*)(d) -> (hello:5) (worl:4) (d:1)
(hello) *(*)r(*)? -> (hello:5) (wo:2) (l:1)
(hello) *(*)r(*)*? -> (hello:5) (wo:2) (0)

All the results are exactly what I was hoping given the parameters.  Can it be done faster?


texts: Refactor a subroutine that divides date range into quarters.

texts:
The subroutine below, GetDetailsQuarterly, accepts two dates. Then it writes out each quarter that falls within the date range. It also gives the first and last day of the quarter. I really don't like how the beginning and ending dates of each quarter are hardcoded. I don't believe this solution accounts for leap year as well. Could someone point me in the right direction to refactor this? Thanks in advance.

GetDetailQuarterly:

    Public Sub GetDetailsQuarterly(ByVal beginDate As Date, ByVal endDate As Date)

Console.WriteLine("{0}>>> date range is {1} - {2} {3}", Environment.NewLine, beginDate, endDate, Environment.NewLine)

Dim incrementingStartDate As Date = beginDate
Dim fy As New FiscalYear()

While incrementingStartDate <= endDate

    fy.qOneBegin = "1/1/" & incrementingStartDate.Year
    fy.qOneEnd = "3/31/" & incrementingStartDate.Year
    fy.qTwoBegin = "4/1/" & incrementingStartDate.Year
    fy.qTwoEnd = "6/30/" & incrementingStartDate.Year
    fy.qThreeBegin = "7/1/" & incrementingStartDate.Year
    fy.qThreeEnd = "9/30/" & incrementingStartDate.Year
    fy.qFourBegin = "10/1/" & incrementingStartDate.Year
    fy.qFourEnd = "12/31/" & incrementingStartDate.Year

    Select Case incrementingStartDate
        Case fy.qOneBegin To fy.qOneEnd
            fy.CurrentQuarter = 1
        Case fy.qTwoBegin To fy.qTwoEnd
            fy.CurrentQuarter = 2
        Case fy.qThreeBegin To fy.qThreeEnd
            fy.CurrentQuarter = 3
        Case fy.qFourBegin To fy.qFourEnd
            fy.CurrentQuarter = 4
        Case Else
            Console.WriteLine("out of range")
    End Select

    Console.WriteLine("your q{0}", fy.CurrentQuarter)
    fy.getCurrentQuarterRange()

    incrementingStartDate = incrementingStartDate.AddMonths(3)

End While
  End Sub

FiscalYear Class:

    Public Class FiscalYear

Public Property qOneBegin() As Date

Public Property qOneEnd() As Date

Public Property qTwoBegin() As Date

Public Property qTwoEnd() As Date

Public Property qThreeBegin() As Date

Public Property qThreeEnd() As Date

Public Property qFourBegin() As Date

Public Property qFourEnd() As Date

Public Property CurrentQuarter As Integer

Public Sub getCurrentQuarterRange()
    Select Case CurrentQuarter
        Case 1
            Console.WriteLine("s: {0}, e: {1}", qOneBegin, qOneEnd)
        Case 2
            Console.WriteLine("s: {0}, e: {1}", qTwoBegin, qTwoEnd)
        Case 3
            Console.WriteLine("s: {0}, e: {1}", qThreeBegin, qThreeEnd)
        Case 4
            Console.WriteLine("s: {0}, e: {1}", qFourBegin, qFourEnd)
        Case Else
            Console.WriteLine("out of range")
    End Select
End Sub
 End Class


texts: Git hook to detect existing tag case insensitive

texts:
In my company, we use git as VCS, the main server run under linux but all our code is for Windows and we all develop on Windows.

The git tag system is case sensitive on linux but is case insensitive on windows.
That is:

under linux Test/Tag and TEST/Tag are different tags
under windows Test/Tag and TEST/Tag are the same tag

We had a lot of issues from that.

So we decided to add a git hook on server side, that is, a script that will test if a pushed tag already exists on the server case insensitively.

Here is the content of the pre-receive git hook.

#!/bin/sh

process_ref() {
        target="$2"   # target hash. 0s for a delete command
        refname="$3"  # the full ref name

        #detect tags
        case "$refname" in
                refs/tags/*)

                # use grep to count matching refs in .git/refs/tags folder (case unsensitivly)
                count1=`find ./refs/tags -print | grep -ic $refname`

                # use grep to count matching refs in packed-refs if present
                if [ -e "./packed-refs" ]; then
                        count2=`grep -ic "$refname" ./packed-refs`
                else
                        count2="0"
                fi

                # abort if the ref already exist and it's not a delete ref command
                if ([ $count1 -ne 0 ] || [ $count2 -ne 0 ]) && [ $target != "0000000000000000000000000000000000000000" ]; then
                        echo "push failed"
                        echo "tag already exists: $refname"
                        echo "please contact dev team"
                        exit 1
                fi
        esac
}

# iterate thru all given refs.
while read REF; do process_ref $REF; done


texts:
I want to implement Q&A systems with attention mechanism. I have two inputs; context and query which shapes are (batch_size, context_seq_len, embd_size) and (batch_size,  query_seq_len, embd_size).

I am following the paper
Machine Comprehension Using Match-LSTM and Answer Pointer.

Then I want to obtain an attention matrix which has the shape of (batch_size, context_seq_len, query_seq_len, embd_size). In the thesis, they calculate values for each row (it means each context word, G_i, alpha_i in the paper).

My code is below and it is running, but I am not sure my way is good or not. For example, I use for loop for generating sequence data (for i in range(T):). And to obtain each row, I use in-place operator like G[:,i,:,:], embd_context[:,i,:].clone() is a good manner in pytorch? If not, where should I change the code?

And if you notice other points, let me know. I am a new in this field and pytorch. Sorry for my ambiguous question.

class MatchLSTM(nn.Module):
    def __init__(self, args):
        super(MatchLSTM, self).__init__()
        self.embd_size = args.embd_size
        d = self.embd_size
        self.answer_token_len = args.answer_token_len

        self.embd = WordEmbedding(args)
        self.ctx_rnn   = nn.GRU(d, d, dropout = 0.2)
        self.query_rnn = nn.GRU(d, d, dropout = 0.2)

        self.ptr_net = PointerNetwork(d, d, self.answer_token_len) # TBD

        self.w  = nn.Parameter(torch.rand(1, d, 1).type(torch.FloatTensor), requires_grad=True) # (1, 1, d)
        self.Wq = nn.Parameter(torch.rand(1, d, d).type(torch.FloatTensor), requires_grad=True) # (1, d, d)
        self.Wp = nn.Parameter(torch.rand(1, d, d).type(torch.FloatTensor), requires_grad=True) # (1, d, d)
        self.Wr = nn.Parameter(torch.rand(1, d, d).type(torch.FloatTensor), requires_grad=True) # (1, d, d)

        self.match_lstm_cell = nn.LSTMCell(2*d, d)

    def forward(self, context, query):
        # params
        d = self.embd_size
        bs = context.size(0) # batch size
        T = context.size(1)  # context length
        J = query.size(1)    # query length

        # LSTM Preprocessing Layer
        shape = (bs, T, J, d)
        embd_context     = self.embd(context)         # (N, T, d)
        embd_context, _h = self.ctx_rnn(embd_context) # (N, T, d)
        embd_context_ex  = embd_context.unsqueeze(2).expand(shape).contiguous() # (N, T, J, d)
        embd_query       = self.embd(query)           # (N, J, d)
        embd_query, _h   = self.query_rnn(embd_query) # (N, J, d)
        embd_query_ex  = embd_query.unsqueeze(1).expand(shape).contiguous() # (N, T, J, d)

        # Match-LSTM layer
        G = to_var(torch.zeros(bs, T, J, d)) # (N, T, J, d)

        wh_q = torch.bmm(embd_query, self.Wq.expand(bs, d, d)) # (N, J, d) = (N, J, d)(N, d, d)

        hidden     = to_var(torch.randn([bs, d])) # (N, d)
        cell_state = to_var(torch.randn([bs, d])) # (N, d)
        # TODO bidirectional
        H_r = [hidden]
        for i in range(T):
            wh_p_i = torch.bmm(embd_context[:,i,:].clone().unsqueeze(1), self.Wp.expand(bs, d, d)).squeeze() # (N, 1, d) -> (N, d)
            wh_r_i = torch.bmm(hidden.unsqueeze(1), self.Wr.expand(bs, d, d)).squeeze() # (N, 1, d) -> (N, d)
            sec_elm = (wh_p_i + wh_r_i).unsqueeze(1).expand(bs, J, d) # (N, J, d)

            G[:,i,:,:] = F.tanh( (wh_q + sec_elm).view(-1, d) ).view(bs, J, d) # (N, J, d) # TODO bias

            attn_i = torch.bmm(G[:,i,:,:].clone(), self.w.expand(bs, d, 1)).squeeze() # (N, J)
            attn_query = torch.bmm(attn_i.unsqueeze(1), embd_query).squeeze() # (N, d)
            z = torch.cat((embd_context[:,i,:], attn_query), 1) # (N, 2d)

            hidden, cell_state = self.match_lstm_cell(z, (hidden, cell_state)) # (N, d), (N, d)
            H_r.append(hidden)
        H_r = torch.stack(H_r, dim=1) # (N, T, d)

        indices = self.ptr_net(H_r) # (N, M, T) , M means (start, end)
        return indices


texts: Different ways of creating a multiplication grid in ruby

texts:
The idea is to create a function that gets a number passed in and ouputs a multiplication grid.

For example the desired output for grid(10) would be :

1,2,3,4,5,6,7,8,9,10
2,4,6,8,10,12,14,16,18,20
3,6,9,12,15,18,21,24,27,30
4,8,12,16,20,24,28,32,36,40
5,10,15,20,25,30,35,40,45,50
6,12,18,24,30,36,42,48,54,60
7,14,21,28,35,42,49,56,63,70
8,16,24,32,40,48,56,64,72,80
9,18,27,36,45,54,63,72,81,90
10,20,30,40,50,60,70,80,90,100

I've come up with two variations of the same solution:

Variation 1

def grid1(grid_size)
  output = String.new
  for y in 1..grid_size
    line = Array.new
    for x in 1..grid_size
      line << x * y
    end
    output += "#{line.join(",")}\n"
  end

  output
end

Variation 2

def grid(grid_size)
  output = (1..grid_size).to_a.map do |y|
    (1..grid_size).to_a.map{|x| x*y}.join(",")
  end

  output
end

Any other ideas on how to solve this or ways that the current solutions could be improved would be most appreciated!


texts:
This is my first attempt at a login system! I've only had roughly 2 days of experience with MySQL and PHP so far and this is what I came up with:

<?php
    session_start();

    //Start Database
        $IP = "";
        $user = "";
        $pass = "";
        $db = "";
        $con = mysqli_connect($IP, $user, $pass, $db);

        // Check connection
        if ( mysqli_connect_errno() ) {
            echo "
";
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            echo "
";
        }

    // Pretty much kicks out a user once they revisit this page and is logged in
    if( $_SESSION["name"] )
    {
        echo "You are already logged in, ".$_SESSION['name']."!
 I'm Loggin you out M.R ..";
        unset( $_SESSION );
        session_destroy();
        exit("");
    }

    $loggedIn = false;
    $userName = $_POST["name"] or "";
    $userPass = $_POST["pass"] or "";

    if ($userName && $userPass )
    {
        // User Entered fields
        $query = "SELECT name FROM Clients WHERE name = '$userName' AND password = '$userPass'";// AND password = $userPass";

        $result = mysqli_query( $con, $query);
        $row = mysqli_fetch_array($result);

        if(!$row){
            echo "
";
            echo "No existing user or wrong password.";
            echo "
";
        }
        else
            $loggedIn = true;
    }

    if ( !$loggedIn )
    {
        echo "
            <form action='logmein.php' method='post'>
                Name: <input type='text' name='name' value='$userName'>

                Password: <input type='password' name='pass' value='$userPass'>

                <input type='submit' value='log in'>
            </form>
        ";
    }
    else{
        echo "
";
        echo "You have been logged in as $userName!";
        echo "
";
        $_SESSION["name"] = $userName;
    }

?>


texts:
I am doing an exercise on finding the nearest pair of prime numbers p₁ and p₂ such that:

p₁ ≤ p₂
p₁ + p₂ = n (for 4 ≤ n ≤ 10⁷)
p₁ and p₂ are primes
p₂ - p₁ is minimal

I think it should work perfectly except that it got a TLE. Can someone point out how can I avoid it?

import math
import random

def _try_composite(a, d, n, s):
    if pow(a, d, n) == 1:
        return False
    for i in range(s):
        if pow(a, 2 ** i * d, n) == n - 1:
            return False
    return True  # n  is definitely composite

def is_prime(n, _precision_for_huge_n=16):
    if n in _known_primes:
        return True
    if n in (0, 1) or any((n % p) == 0 for p in _known_primes):
        return False
    d, s = n - 1, 0
    while not d % 2:
        d, s = d >> 1, s + 1
    # Returns exact according to http://primes.utm.edu/prove/prove2_3.html
    if n < 1373653:
        return not any(_try_composite(a, d, n, s) for a in (2, 3))
    if n < 25326001:
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5))

_known_primes = [2, 3]
_known_primes += [x for x in range(5, 1000, 2) if is_prime(x)]

def main():
    n = int(input())
    if n > 4:
        for smaller in range(n // 2, -1, -1):
            if n - smaller >= smaller:
                if is_prime(n - smaller) and is_prime(smaller):
                    print (smaller, n - smaller)
                    flag = True
                    break
    else:
        print ('2 2')

main()


texts: Start, stop and restart script for a MongoDB server

texts:
I have created an start, stop, restart script for a unix-mongodb-server.

It would be nice if you could look over my code and give me some helpful hints on what I could change. I tested the script under my Mac and it works.

This is also available under my GitHub account and available under GitHub -> Mongo_Start_Stop.

VERSION=1.1.2
SCRIPTNAME=$(basename "$0")
MONGOHOME=
MONGOBIN=$MONGOHOME/bin
MONGOD=$MONGOBIN/mongod
MONGODBPATH=
MONGODBCONFIG=

if [ $# != 1 ]
then
    echo "Usage: $SCRIPTNAME [start|stop|restart]"
    exit
fi

pid() {
    ps -ef | awk '/[m]ongodb/ {print $2}'
}

stopServer() {
    PID=$(pid)
    if [ ! -z "$PID" ];
    then
        echo "... stopping mongodb-server with pid: $PID"
    sudo kill $PID
    else
        echo "... mongodb-server is not running!"
    fi
}

startServer() {
    PID=$(pid)
    if [ ! -z "$PID" ];
    then
        echo "... mongodb-server already running with pid: $PID"
    else
        echo "... starting mongodb-server"
        sudo "$MONGOD" --dbpath "$MONGODBPATH" --config "$MONGODBCONFIG"
    fi
}

restartServer() {
    stopServer
    sleep 1s
    startServer
}

case "$1" in

    start) startServer
           ;;

    stop) stopServer
          ;;

    restart) restartServer
         ;;

    *) echo "unknown command"
       exit
       ;;
esac


texts:
I'm creating an XML from a defined schema I need to follow.

This is my code:

using (XmlWriter writer = XmlWriter.Create(desktopPath + "\fatt.xml", settings))
{
  writer.WriteStartDocument();

  #region FatturaElettronicaHeader 1

  writer.WriteStartElement("FatturaElettronicaHeader");

  #region DatiTrasmissione 1.1
  writer.WriteStartElement("DatiTrasmissione");

  var statoAnag = statiRep.GetId(anagraficoCliente.stato);

  writer.WriteStartElement("IdTrasmittente");
  writer.WriteElementString("IdPaese",statoAnag.codice_iso);
  writer.WriteElementString("IdCodice",anagraficoCliente.codice_fiscale);
  writer.WriteEndElement();

  writer.WriteElementString("ProgressivoInvio", "0");
  writer.WriteElementString("FormatoTrasmissione",FORMATO_TRASMISSIONE);

  writer.WriteElementString("CodiceDestinatario",codiceSdi);

  writer.WriteElementString("PECDestinatario","prova@pec.it");
  writer.WriteEndElement();

  #endregion DatiTrasmissione 1.1

  #region 2
  ....
  #endregion 2

  writer.WriteEndDocument();
}

Basically I just have to read data from my db and then put in a xml file.

It works fine but I think is not really readable even if I used a lot of region to tidy up code.

What can I do to improve my code ? If there's any


texts:
This is a Python program to mint a hashcash token, but my code is a lot slower than using a library.  What is slowing my program down?  It takes over 10 seconds to mint a 20-bit stamp, but using a library, it takes less than a second.

This is my program:

from os import urandom
from hashlib import sha1
import time

def mint(name, bits):
    t = time.strftime("%y%m%d")
    out = " "
    count = 0
    while out[:bits] != bits*"0":
        RandomData = urandom(8).encode("base64").replace("\n", "")
        data = "1:%d:%s:%s::%s:%s"%(bits, t, name, RandomData, format(count, 'x'))
        out = (''.join(format(ord(x), '08b') for x in sha1(data).digest()))
        count += 1
    return data

print mint("email_address", 20)

This is the library I am using for comparison.


texts:
I am writing a function for a rotating navigation with JS and jQuery. I am using a plugin called jQuery transit for animating rotation. The code works, but it is very long for such a simple function. Is there any way this can be improved?

var rotation = 0;
$('nav ul li a').bind('click', function() {
'use strict';
var item = $(this).parent();
var itemI = item.index();
var navAll = $(this).parents('ul');

var condition = rotation + '_' + itemI;

switch(condition)
{
   case '0_0':
        //do nothing
        break;
    case '0_1':
        navAll.transition({rotate: '-=90deg'});
        $('nav ul li a').transition({rotate:'90deg'});
        rotation = 270;
        break;
    case '0_2':
        navAll.transition({rotate: '-=180deg'});
        $('nav ul li a').transition({rotate:'180deg'});
        rotation = 180;
        break;
    case '0_3':
        navAll.transition({rotate: '+=90deg'});
        $('nav ul li a').transition({rotate:'-90deg'});
        rotation = 90;
        break;

    case '90_0':
        navAll.transition({rotate: '0deg'});
        $('nav ul li a').transition({rotate:'0deg'});
        rotation = 0;
        break;
    case '90_1':
        navAll.transition({rotate: '-90deg'});
        $('nav ul li a').transition({rotate:'90deg'});
        rotation = 270;
        break;
    case '90_2':
        navAll.transition({rotate: '+=90deg'});
        $('nav ul li a').transition({rotate:'-180deg'});
        rotation = 180;
        break;
    case '90_3':
        break;

    case '180_0':
        navAll.transition({rotate: '0deg'});
        $('nav ul li a').transition({rotate:'0deg'});
        rotation = 0;
        break;
    case '180_1':
        navAll.transition({rotate: '-90deg'});
        $('nav ul li a').transition({rotate:'90deg'});
        rotation = 270;
        break;
    case '180_2':
        //do nothing
        break;
    case '180_3':
        navAll.transition({rotate: '-=90deg'});
        $('nav ul li a').transition({rotate:'-90deg'});
        rotation = 90;
        break;

    case '270_0':
        navAll.transition({rotate: '0deg'});
        $('nav ul li a').transition({rotate:'0deg'});
        rotation = 0;
        break;
    case '270_1':
        //do nothing
        break;
    case '270_2':
        navAll.transition({rotate: '-=90deg'});
        $('nav ul li a').transition({rotate:'180deg'});
        rotation = 180;
        break;
    case '270_3':
        navAll.transition({rotate: '-=180deg'});
        $('nav ul li a').transition({rotate:'-90deg'});
        rotation = 90;
        break;

}

});


texts: Plugin for showing cross-sells on the single product page in WooCommerce

texts:
I made a custom plugin for showing cross-sells on the single product page in WooCommerce, however i need to know if this is secure and possibly act as an attack vector. Additionally, is there a better way than a while loop for iterating through the products?

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

function show_cross_sell_in_single_product(){
    $crosssells = get_post_meta( get_the_ID(), '_crosssell_ids',true);
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 4,
        'post__in' => $crosssells
        );
    $products = new WP_Query( $args );
    if ( $products ) : ?>

<?php esc_html_e( 'Passend dazu', 'woocommerce' ); ?>

          <?php woocommerce_product_loop_start(); ?>

          <?php while ( $products->have_posts() ) : $products->the_post();
              wc_get_template_part( 'content', 'product' );
          endwhile; // end of the loop. ?>

          <?php woocommerce_product_loop_end(); ?>

      <?php endif;

    wp_reset_postdata();

}

add_action('woocommerce_after_single_product_summary', 'show_cross_sell_in_single_product', 10, 2);
/* todo removeaction woocommerce_after_single_product_summary, show_related */
}


texts:
Here is my solution for an exercise, which requires translation of strings to key presses on a phone keypad (for example, to get 'b' the digit '2' needs to be pressed twice).

It's taken from the book Haskell from first principles, and originally appeared in 1HaskellADay. I'd love to get feedback.

module Phone where
import Data.Char
import Data.String.Utils
import Data.List

data DaPhone = DaPhone [String]
convo :: [String]
convo =
          ["Wanna play 20 questions",
           "Ya",
           "U 1st haha",
           "Lol ok. Have u ever tasted alcohol lol",
           "Lol ya",
           "Wow ur cool haha. Ur turn",
           "Ok. Do u think I am pretty Lol",
           "Lol ya",
           "Haha thanks just making sure rofl ur turn"]

-- validButtons = "1234567890*#"
type Digit = Char
-- Valid presses: 1 and up
type Presses = Int

reverseTaps :: DaPhone -> Char -> [(Digit, Presses)]
reverseTaps (DaPhone keys) c = if isUpper c then ('*', 1) : looks else looks
    where looks = look keys (toLower c)
-- assuming the default phone definition
-- 'a' -> [('2', 1)]
-- 'A' -> [('*', 1), ('2', 1)]

look :: [String] -> Char -> [(Digit, Presses)]
look keys c = look' keys c 0

look' :: [String] -> Char -> Int -> [(Digit, Presses)]
look' [] _ _ = []
look' (x:xs) c n = if ind /= (-1) then [(head $ show n, ind + 1)] else look' xs c (n + 1)
where ind = maybe (-1) id $ elemIndex c x

cellPhonesDead :: DaPhone -> String -> [(Digit, Presses)]
cellPhonesDead = (concat .) . map . reverseTaps

-- count total presses
fingerTaps :: [(Digit, Presses)] -> Presses
fingerTaps = sum . map snd

mostPopularLetter :: String -> Char
mostPopularLetter = head . longest . group . sort

coolestLtr :: [String] -> Char
coolestLtr = mostPopularLetter . filter isAlpha . concat

coolestWord :: [String] -> String
coolestWord = head . longest . group . sort . words . join " "

longest :: [[a]] -> [a]
longest = maximumBy (\x y -> compare (length x) (length y))

phone :: DaPhone
phone = DaPhone keymap

keymap :: [String]
keymap =

                [
                    " 0",
                    "1",
                    "abc2",
                    "def3",
                    "ghi4",
                    "jkl5",
                    "mno6",
                    "pqrs7",
                    "tuv8",
                    "wxyz9"
                ]


texts:
The code is no longer relevant but I want to know how I can make it faster. It uses only about 10% of my CPU. Any advice about best practices, better algorithms, or how to make the existing one faster are welcome. This is purely for the purpose of personal learning.

public class BruteForce {
public static void main(String[] args) throws Exception {

    // Password dictionary
    FileInputStream fstream = new FileInputStream("C:/list.txt");
    BufferedReader BufferedReader1 = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
    // Read File Line By Line
    String input;
    long counter = 0;
    Long start = System.currentTimeMillis();
    while ((input = BufferedReader1.readLine()) != null) {
        if(counter%1000000 == 0){
            System.out.println(counter + ": " + input);
        }
        counter++;

        // Generate ID using published class
        byte[] pub = ppg.Indors.getPublicKey(input);
        // We could use getId, but we get a weird signed/unsigned problem
        byte[] pub2 = MessageDigest.getInstance("SHA-256").digest(pub);
        // Get account ID
        BigInteger BigInteger = new BigInteger(1, new byte[]{pub2[7],pub2[6],pub2[5],pub2[4],pub2[3],pub2[2],pub2[1],pub2[0]});

        // Request balance for ID
        String url = "http://localhost:1811/ppg?request=egtBalance=" + BigInteger.toString();
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        BufferedReader BufferedReader2 = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = BufferedReader2.readLine()) != null) {
            response.append(inputLine);
        }
        BufferedReader2.close();
        // Check balance bigger than 0
        if (!response.toString().contains("balance\":0")) {
            System.out.println("Found:" + input);
        }
    }
    System.out.println("Speed (tries/sec): " + counter*1000/(System.currentTimeMillis()-start));
    BufferedReader1.close();
}
 }


texts: Streaming variable length integers from a file

texts:
I wrote this script as a proof of concept of reading a file from disk as variable-length quantities (ints encoded using 7 bits from as many bytes as required). I'm mostly making use of the file system ReadStream, for reading byte buffers from files and the varint package for decoding variable length values.

This is is my first attempt at working with nodejs. When I tested it on a 1GB file read from SSD, it took about 7 minutes during which it used about 50mb of ram and saturated one CPU core.

So my question is, is there anything I'm doing here which could be optimised for CPU load?

var fs, vi, sys, rs, ints, total, remainder;
fs = require('fs');
vi = require('varint');
sys = require('sys');

rs = fs.createReadStream('/path/to/datafile');
total = 0;

// a buffer for carrying over incomplete values between chunks
remainder = new Buffer(0);

rs.on('data', function(chunk) {
  var buffer, value, byteLen;
  buffer = Buffer.concat([remainder, chunk]);

  while(buffer.length){
    // decode the value and check how many bytes it required
    value = vi.decode(buffer);
    byteLen = vi.decode.bytesRead;

    if (byteLen <= buffer.length){
      // keep the result and update position in the buffer
      total += value;
    } else {
      // result is incomplete, store remainder to be prepended to the next chunk
      remainder = new Buffer(buffer.length);
      buffer.copy(remainder);
    }

    // shift decoded bytes off the buffer
    buffer = buffer.slice(byteLen);
  }
});

// display grand total after the whole file has been read
rs.on('end', function() {
  sys.puts((total));
});


texts: Cleanly preventing flashing an element from corrupting future flashes

texts:
For a Seesaw (Swing) app I'm writing, I need to be able to flash a component for a certain duration. Here's the basic function I came up with that accomplishes this:

; Note, this isn't what I want reviewed. See below.
(defn flash-property [component prop-key flash-value duration]
  (let [old-value (sc/config component prop-key)]
    (sc/config! component prop-key flash-value)

    (sc/timer (fn [_]
                (sc/config! component prop-key old-value))
              :initial-delay duration, :repeats? false)))

It reads the current property value into old-value, sets the new value, then in a timer reverts the old value after duration many milliseconds. If I wanted to create a button that flashes for half a second when pressed, I could write:

(let [btn (sc/button :text "Button")]
  (sc/listen btn
     :action (fn [_] (flash-property btn :background :red 500)))

  btn)

I had a problem that if you start a new flash before the old one has finished, old-value becomes the flash color from the previous flash, and the component gets stuck as the flash color.

To get around this, I had to rely on a "static variable" that keeps track of what is currently being flashed. I tried to extract as much as I could out of the decider function, but I'm still unhappy with it. The atom, while in a restricted scope, still feels like a hack to cover up a bad design. I've never used a let at the top level before, and it feels kind of dirty.

Of course, I could create some kind of a "flash handler" that gets passed back and forth and keeps track of what's being flashed, but that would be it's own flavour of mess. Then the caller would need to maintain it somehow. Considering the flash gets triggered in a button handler, I'd probably have to maintain an atom there anyways.

Can anyone see how to cleanly avoid the "static variable" flashing?-atom?

(ns pet-redo.full-ui.helpers
  (:require [seesaw.core :as sc]))

(defn flash-property
  "Alters the property at prop-key to flash-value for duration-many milliseconds,
    then reverts the property back to the original value.

  Will break if a new flash is started before a previous one ends."
  [component prop-key flash-value duration component-done-callback]
  (let [old-value (sc/config component prop-key)]
    (sc/config! component prop-key flash-value)

    (sc/timer (fn [_]
                (sc/config! component prop-key old-value)
                (component-done-callback))
              :initial-delay duration, :repeats? false)))

(let [flashing?-atom (atom #{})]
  (defn maybe-flash-background!
    "Alters the property at prop-key to flash-value for duration-many milliseconds,
      then reverts the property back to the original value.

    Does nothing if the element is already being flashed.

    Returns whether or not a flash was triggered."
    [component flash-color duration]
    (when-not (@flashing?-atom component)
      (swap! flashing?-atom conj component)

      (flash-property component :background flash-color duration
                      #(swap! flashing?-atom disj component))

      true)))


texts:
I need to prepend N spaces to a string to make it 10 characters in length. I came up with the following method, but since it is going to be called often, I want to ensure it is optimized. Could this be made more efficient?

public static string PrependSpaces(string str)
{
    StringBuilder sb = new StringBuilder();
    sb.Append(str);
    for (int i = 0; i < (10 - str.Length); i++)
    {
        sb.Insert(0, " ");
    }
    return sb.ToString();
}


texts: Generator iterator with push back function

texts:
In a compiler project for an LL(1/2) grammar, I have had a need for a generator iterator with a push back function. I have been surprised not to find any perfectly applicable solution (clean, simple, obvious, standard, etc.). On the other hand I was surprised of how easy it was to create exactly what I wanted after I decided to invest a little time.

Here is what I came up with:

class Back_pushable_iterator:
    """Class whose constructor takes an iterator as its only parameter, and
    returns an iterator that behaves in the same way, with added push back
    functionality.

    The idea is to be able to push back elements that need to be retrieved once
    more with the iterator semantics. This is particularly useful to implement
    LL(k) parsers that need k tokens of lookahead. Lookahead or push back is
    really a matter of perspective. The pushing back strategy allows a clean
    parser implementation based on recursive parser functions.

    The invoker of this class takes care of storing the elements that should be
    pushed back. A consequence of this is that any elements can be "pushed
    back", even elements that have never been retrieved from the iterator.
    The elements that are pushed back are then retrieved through the iterator
    interface in a LIFO-manner (as should logically be expected).

    This class works for any iterator but is especially meaningful for a
    generator iterator, which offers no obvious push back ability.

    In the LL(k) case mentioned above, the tokenizer can be implemented by a
    standard generator function (clean and simple), that is completed by this
    class for the needs of the actual parser.
    """
    def __init__(self, iterator):
        self.iterator = iterator
        self.pushed_back = []

    def __iter__(self):
        return self

    def __next__(self):
        if self.pushed_back:
            return self.pushed_back.pop()
        else:
            return next(self.iterator)

    def push_back(self, element):
        self.pushed_back.append(element)

def main():
    it = Back_pushable_iterator(x for x in range(10))

    x = next(it) # 0
    print(x)
    it.push_back(x)
    x = next(it) # 0
    print(x)
    x = next(it) # 1
    print(x)
    x = next(it) # 2
    y = next(it) # 3
    print(x)
    print(y)
    it.push_back(y)
    it.push_back(x)
    x = next(it) # 2
    y = next(it) # 3
    print(x)
    print(y)

    for x in it:
        print(x) # 4-9

    it.push_back(x)
    y = next(it) # 9
    print(x)

if __name__ == "__main__":
    main()

Any feedback is appreciated. A better name? ;-)

Note: I have already posted this code as a very late answer to https://stackoverflow.com/questions/2425270/how-to-look-ahead-one-element-in-a-python-generator, but got no feeback.


texts:
I'm just starting to learn Java and I have written this simple Tic Tac Toe game. Please review it and give me some feedback, advice, guidance etc.

Main method:

    import java.util.Scanner;

    public class Main {

public static void main(String[] args) {
        char player='o';
        int row,column;
        Scanner k =  new Scanner (System.in);
        Game g = new Game ();

        g.initializeGame();
        System.out.println("Game ready !\n");

while(true)
{
player=g.changePlayer(player);
System.out.print("\n"+player +" ,choose your location (row, column):");
row=k.nextInt();
column=k.nextInt();

    while (g.checkIfLegal(row,column))
    {
    System.out.println("That slot is already taken or out of bounds, please try again (row, column).");
    g.displayBoard();
    row=k.nextInt();
    column=k.nextInt();
    }
g.changeBoard(player,row,column );
g.displayBoard();

if(g.checkIfWinner())
    {
    System.out.println("\nThe winner is "+ player+" !");
    break;

    }
if(g.checkIfTie())
    {
        System.out.println("\nThe game is a tie !");
        break;
    }
}

    }

    }

Game class:

    public class Game {

char [][] table = new char[3][3];

public void initializeGame()
{
    for (int i = 0; i < 3; i++)
        for (int p=0; p < 3; p++)
            table [i][p]= ' ';
}

public boolean checkIfLegal(int row, int column)
{
     if( (row>2 || column>2) || (row<0 || column <0) )
         return true;

else if(table[row][column]=='x' || table[row][column]=='o')
        return true;

        return false;
}

public void changeBoard(char player, int row, int column)
{
    table[row][column]=player;

}

public void displayBoard()
{

    System.out.println("  0  " + table[0][0] + "|" + table[0][1] + "|" + table[0][2]);
    System.out.println("    --+-+--");
    System.out.println("  1  " + table[1][0] + "|" + table[1][1] + "|" + table[1][2]);
    System.out.println("    --+-+--");
    System.out.println("  2  " + table[2][0] + "|" + table[2][1] + "|" + table[2][2]);
    System.out.println("     0 1 2 ");
}

public char changePlayer(char player) {
    char newTurn='e';
    if (player == 'o')
        newTurn='x';
    if (player == 'x')
        newTurn='o';
    return newTurn;
}

public boolean checkIfWinner() {
         if( table [0][0]==table[1][0] && table[1][0] == table[2][0] && (table [0][0]=='x' || table [0][0]=='o'))
                return true;
    else if( table [0][1]==table[1][1] && table[1][1] == table[2][1] && (table [0][1]=='x' || table [0][1]=='o'))
                return true;
    else if( table [0][2]==table[1][2] && table[1][2] == table[2][2] && (table [0][2]=='x' || table [0][2]=='o'))
                return true;
    else if( table [0][0]==table[0][1] && table[0][1] == table[0][2] && (table [0][0]=='x' || table [0][0]=='o'))
                return true;
    else if( table [1][0]==table[1][1] && table[1][1] == table[1][2] && (table [1][0]=='x' || table [1][0]=='o'))
                return true;
    else if( table [2][0]==table[2][1] && table[2][1] == table[2][2] && (table [2][0]=='x' || table [2][0]=='o'))
                return true;
    else if( table [0][0]==table[1][1] && table[1][1] == table[2][2] && (table [0][0]=='x' || table [0][0]=='o'))
                return true;
    else if( table [2][0]==table[1][1] && table[1][1] == table[0][2] && (table [2][0]=='x' || table [2][0]=='o'))
                return true;
    else
                return false;
}

public boolean checkIfTie() {
    for (int i = 0; i < 3; i++)
        for (int p=0; p < 3; p++)
            if(table [i][p]==' ')
                return false;

    return true;
}

    }


texts:
I've created a web page based on a sample from a book. It works fine, but seems to have become too complicated.

'use strict';
function toggle (triggers, elements, per_trigger, events) {
    function toggle(index, per, elem, func) {
        for (var i = 0; i < per; i++)
            func(elem[index+i]);
    }

    if ((elements.length % triggers.length != 0 && elements.length != triggers.length * per_trigger)
        || (elements.length == 0 || triggers.length == 0)
        || (events[0].func == undefined || events[0].ev == undefined)) {
        console.error('toggle: number of elements must be divisible by' +
        'number of triggers, because one trigger can toggle more than one element\n' +
        'for example: if you want a trigger to toggle two elements, then the per_trigger' +
        ' argument will be 2 and the number of elements must be equal to the number of triggers * 2');
        return false;
    }
    for (var i = 0; i < triggers.length; i++) {
        for (var f = 0; f < events.length; ++f) {
            (function(_i, _f) {
                $(triggers[_i]).on(events[_f].ev, function() {
                    toggle(_i*per_trigger, per_trigger, elements, events[_f].func);
                })
            })(i, f);
        }
    }
    return true;
}

var hidden, trigger, PER_TRIGGER = 1, onclick;
function defineTriggers(hide) {
    hidden = document.getElementsByTagName('div');
    trigger = document.getElementsByTagName('h2');

    if (hide) {
        // hiding elements ..
        for (var r=0; r<hidden.length; ++r) {
            if (hidden[r].displayinfo == undefined)
                hidden[r].displayinfo = hidden[r].style.display;
            hidden[r].style.display = 'none';
            hidden[r].shown = false;
        }
        toggle(trigger, hidden, PER_TRIGGER, [{'ev': 'click', 'func': onclick}]); // defined externally ..
    }
}

function addDiv(date, info) {
    var d = document.createElement('div'),
        s = document.createElement('h2'),
        p = document.createElement('p');
    p.textContent = info;
    s.textContent = date;
    document.body.appendChild(s);
    document.body.appendChild(d);
    d.appendChild(p);
    d.style.display = 'none';
    d.shown = false;
    d.displayinfo = 'block';
    hidden[hidden.length] = d;
    trigger[trigger.length] = s;
    toggle([s], [d], PER_TRIGGER, [{'ev': 'click', 'func' : onclick}]);
}

    alert('running')
    onclick = function(e) {
        e.style.display = e.shown ? 'none' : e.displayinfo;
        e.shown = !e.shown;
    };
    defineTriggers(true);

    // adding btn
    var b = document.createElement('button'),
        f = document.getElementsByTagName('footer')[0];

    f.appendChild(b);
    b.textContent = 'Add a Date'

    b.onclick = function() {
        var day, info, day_regex = /[A-Z][a-z]{1,7} [1-9][0-9]?, 2[0-9]{3}/;
        do {
            day = prompt('Day');
            if (!day_regex.test(day)) alert('Day not correct .. !');
        } while(!day_regex.test(day))
        info = prompt('Info');
        addDiv(day, info);
    }

Is it possible to improve the clarity of this code, without affecting its functionality?


texts:
I'm thinking about a unified error handling interface.

I've come to conclusion that the errno global variable style isn't so bad, and decided to implement an improved version of it: every function called sets an error code to a global error variable through the get/set functions.

The difference with the errno pattern is that the code is set even if there's no actual error (ERR_OK enum value), so we get a status of an operation after each function call. This allows us to not reserve a special "error" return value. The global error variable is of thread local storage type.

What pitfalls could be met with such approach?

err.h:

#ifndef ERR_H
#define ERR_H

enum err {
    ERR_OK
    ERR_SOME,
};

void err_set(enum err e);
int err_get(void);

#define ERR (err_get() != ERR_OK)

#endif /* ERR_H */

err.c:

#include "err.h"

_Thread_local static int error;

void err_set(enum err e) {
    error = e;
}

int err_get(void) {
    return error;
}

main.c:

#include <stdio.h>
#include "err.h"

static size_t get_size(void *arg) {
    if (!arg) {
        err_set(ERR_SOME);
        return 0;
    }

    err_set(ERR_OK);
    return sizeof(*arg);
}

int main(void) {
    void *bad = NULL;

    size_t size = get_size(bad);
    if (ERR) {
        printf("Bad pointer!\n");
        return 1;
    }

    printf("size == %zu\n", size);

    return 0;
}


texts: String manipulations (reverse a string by characters, permutation)

texts:
I'm trying to solve simple Java problems in various ways. Could anyone comment about the code, like how it could be better, and what could be a problem?

// When using already-defined-method is allowed
static String reverseStringByChar1(String str) {
    return str == null ? null : new StringBuilder(str).reverse().toString();
}

// When using already-defined-method is not allowed
static String reverseStringByChar2(String str) {
    if (str == null)
        return null;

    int length = str.length();
    char[] charArray = new char[length];

    for (int i = length-1, j = 0; i >= 0; i--, j++)
        charArray[i] = str.charAt(j);

    return new String(charArray);
}

// When using extra data structure is not allowed
// (Is there any way not to use extra memory? Here like the temp.)
static String reverseCharacterArray(char[] chars) {
    if(chars.length == 0)
        return null;

    for (int i = 0, j = chars.length-1; i < chars.length / 2; i++, j--) {
        /* char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
        */
        char temp = chars[i];
        chars[i] = chars[chars.length-1-i];
        chars[chars.length-1-i] = temp;

    }
    return new String(chars);
}

// When comparing two strings to see if they are permutations of each other.
static boolean arePermutations(String str1, String str2) {
    // can be trimmed
    // need to know what to do with uppercases and lowercase

    if (str1 == null || str2 == null || str1.length() != str2.length())
        return false;

    // assuming askii code
    boolean[] str1Array = new boolean[128];

    for (char c : str1.toCharArray())
        str1Array[c] = true;

    for (char c : str2.toCharArray()) {
        if (!str1Array[c])
            return false;
    }

    return true;
}


texts:
Is there a better way to handle this ClassNotFoundException ?

private Class<?> getClass(String value)
{
    Class<?> columnClass = null;
    try
    {
        columnClass = Class.forName(StringUtils.trim(value));
    }
    catch (ClassNotFoundException ex)
    {
        if (value.contains("double") || value.contains("Double"))
        {
            columnClass = Double.class;
        }
        else if (value.contains("int") || value.contains("Int"))
        {
            columnClass = Integer.class;
        }
        else if (value.contains("bool"))
        {
            columnClass = Boolean.class;
        }
        else if (value.contains("long") || value.contains("Long"))
        {
            columnClass = Long.class;
        }
        else
        {
            log.error("FAILED. Class object is not supported: " + value, ex);
        }
    }
    return columnClass;
}


texts:
This is generic logic for handling network requests that load data based on pages. It is assumed that the view controller would implement the UISource protocol. I have a test suite as well. I'm especially interested in any ideas for doing away with the Variable. I'm also interested in ideas for refactoring this code into smaller functions.

import RxSwift

protocol UISource {
    var refreshTrigger: Observable<Void> { get } // reloads most recently loaded page
    var nextPageTrigger: Observable<Void> { get } // loads next page
    var bag: DisposeBag { get }
}

protocol NetworkSource {
    associatedtype Item
    func loadData(page: Int) -> Observable<[Item]>
}

enum Result<T> {
    case success(T)
    case failure(Error)
}

struct PaginationNetworkSink<T> {

    let loading: Observable<Bool> // true if network loading is in progress.
    let elements: Observable<[T]> // elements from all loaded pages
    let error: Observable<Error> // fires once for each error
}

func paginationNetworkLogic<T, API>(ui: UISource, api: API) -> PaginationNetworkSink<T> where API: NetworkSource, T == API.Item {
    let loadResults = Variable<[Int: [T]]>([:])

    let refreshOffset = ui.refreshTrigger
        .map { loadResults.value.keys.max() }
        .filter { $0 != nil }
        .map { $0! }

    let nextOffset = ui.nextPageTrigger.map { () -> Int in
        if let page = loadResults.value.keys.max() {
            return page + 1
        } else {
            return 0
        }
    }

    let pageToLoad = Observable.of(refreshOffset, nextOffset)
        .merge()
        .startWith(0)

    let loadResult = pageToLoad.flatMapLatest {
        api.loadData(page: $0)
            .map { Result.success($0) }
            .catchError { Observable.just(Result.failure($0)) }
    }.share()

    let successResult = loadResult.map { (result) -> [T] in
        if case .success(let array) = result {
            return array
        } else {
            return []
        }
    }

    let pageAndResult = Observable.zip(pageToLoad, successResult) { (page: $0.0, array: $0.1) }
        .filter { !$0.array.isEmpty }

    pageAndResult.subscribe(onNext: {
        loadResults.value[$0.page] = $0.array
    }).disposed(by: ui.bag)

    let startLoading = pageToLoad
        .map { _ in true }

    let loadingComplete = loadResult.map { _ in false }

    let loading = Observable.of(startLoading, loadingComplete)
        .merge()
        .startWith(true)

    let elements: Observable<[T]> = loadResults.asObservable().map { results in
        var result: [T] = []
        let keys = results.keys.sorted()
        for key in keys {
            result += results[key]!
        }
        return result
    }.startWith([])

    let error = loadResult.map { result -> Error? in
        if case .failure(let error) = result {
            return error
        } else {
            return nil
        }
    }.filter { $0 != nil }.map { $0! }

    return PaginationNetworkSink(loading: loading, elements: elements, error: error)
}


texts:
I have created the classic "guess the random number" game:

Generator Interface

 package ishan.guessingGame.randomNumberGenerators;

 public interface RandomNumber {

 public int generate();
}

Generator Implementation

package ishan.guessingGame.randomNumberGenerators;

import java.util.Random;

public class SimpleRandomNumberGenerator implements RandomNumber {

private int limit=50;

public SimpleRandomNumberGenerator(){

}
public SimpleRandomNumberGenerator(int limit){
    this.limit=limit;
}
@Override
public int generate() {

    return generateRandomNumber();
}

private int generateRandomNumber(){
    Random random=new Random();
    return random.nextInt(limit+1);
}
}

Game interface

package ishan.guessingGame.game;

public interface Game {

public void startGame();
}

A Game Impl

package ishan.guessingGame.game;

import java.util.Scanner;

import ishan.guessingGame.randomNumberGenerators.RandomNumber;
import ishan.guessingGame.randomNumberGenerators.SimpleRandomNumberGenerator;

public class SimpleGuessingGame implements Game{

private int randomNumber;
private int difficultyLevel;
private Scanner scanner;
private RandomNumber random;
private int input=999;

public SimpleGuessingGame(){
    scanner = new Scanner(System.in);
}

@Override
public void startGame() {
    init();
    play();
    endGame();
}

private void init(){

    System.out.println("Enter The Difficulty : 1 = Easy , 2 = Moderate , 3 =Difficult");

    String difficulty;
    difficulty=scanner.next();

    if(!checkInputIsNumber(difficulty, true)){
        endGame();
    }

    difficultyLevel=Integer.parseInt(difficulty);

    if(difficultyLevel == 1){
        random=new SimpleRandomNumberGenerator();
    }
    else if (difficultyLevel == 2){
        random=new SimpleRandomNumberGenerator(100);
    }
    else{
        random=new SimpleRandomNumberGenerator(200);
    }
    randomNumber=random.generate();
}

private void play(){
    System.out.println("Input any character to exit..");

    while(true){
        System.out.println(" Guess The Number");
        String tempInput=scanner.next();

        if(!checkInputIsNumber(tempInput , false)){
            endGame();
        }

        input=Integer.parseInt(tempInput);
        if(input==randomNumber){
            System.out.println("You won.Bye!!");
            endGame();
        }
        else if(input > randomNumber){
            System.out.println("Easy there. Guess a smaller Number");
        }
        else{
            System.out.println("Pick a larger one");
        }
    }
}

private boolean checkInputIsNumber(String input , boolean checkForDifficulty) {

    if(checkForDifficulty){
        if(input.matches("^[0-3]")){
            return true;
        }
    }

    else if (input.matches("^[0-9]*")){
        return true;
    }
    return false;
}

private void endGame() {
    scanner.close();
    System.exit(0);
}
}

Main class

package ishan.apps;

import ishan.guessingGame.game.Game;
import ishan.guessingGame.game.SimpleGuessingGame;

public class MainApplication {

public static void main(String a[]){
    Game game=new SimpleGuessingGame();
    game.startGame();
}
}

I have tried to code to interfaces and would like to get suggestions around that area and my code in general.


texts:
NOTE: the Javascript is all I'm concerned about, the HTML/CSS is just DEMO code. One caveat is ARIA states or attributes, if you have input on that, by all means, dive in.

I had the need for and unobtrusive extensible toggle that could be applied to a handful of items: tooltips, accordions, panels, dropdowns, etc.

With the accordions, there is a need for a sidebar that also has accordion-like functionality with sub-links that reveal once clicked, this event triggers the accordion as well, so had to make paired events that triggered the actual accordion, as those sidebar sub-links anchor/smooth scroll into the accordion panels.

We're not utilizing babeljs so wrote this in ES5 compliant JS. Any recommendations to improve or areas that you see could pose an issue in compatibility, performance, maintainability, scalability, etc. feel free to offer advice. I am not a strong JS dev, know enough to get in trouble, so any advice on improvement is welcomed.

var toggleAttribute = function (el, attr) {
  !el.hasAttribute(attr) ?
    el.setAttribute(attr, '') :
  el.removeAttribute(attr);
};

var toggleValue = function (el, attr, on, off) {
  el.setAttribute(
    attr,
    el.getAttribute(attr) === off ? on : off);
};

var eventHandler = function eventHandler(event, node, callback) {

  window.addEventListener(
    event,
    function (e) {
      if (!e.target.matches(node)) return;
      callback.call(this, e);
    },
    false
  );

};

var toggleMethod = function (target, identifier, active, attr, on, off) {

  var d = document;
  target.classList.add(active);

  toggleValue(target, attr, on, off);
  toggleAttribute(target.nextElementSibling, 'hidden')

  if (target.hasAttribute('data-controls')) {

    var pairedTarget = d.querySelector('#' + target.getAttribute('data-controls'));

    toggleValue(pairedTarget, attr, on, off);
    toggleAttribute(pairedTarget.nextElementSibling, 'hidden')

  }

  var selectorList = d.querySelectorAll(identifier);

  //for (var i = 0, len = selectorList.length; i < len; ++i)

  Array.from(selectorList)
    .forEach(function (selector) {

    if (
      selector !== target &&
      selector !== pairedTarget
    ) {

      selector.classList.remove(active);
      selector.setAttribute(attr, off);
      selector.nextElementSibling.hidden = true;

    }

  });

};

eventHandler('click', '.toggle', function (e) {

  toggleMethod(e.target, '.toggle', 'active', 'aria-expanded', 'true', 'false');

});
@charset 'utf-8';
body {
  margin: 0
}

body>div {
  width: 49%;
  display: inline-block;
}

.toggle {
  display:block;
  margin-right: 5px;
  padding: 8px 12px 8px 8px;
}

.toggle:before {
  content: '›';
  margin-right: 8px;
  display: inline-block;
}

.toggle[aria-expanded='true']:before {
  transform: rotate(90deg);
}

      paired

paired a message

      isolated

isolated a message

      <button aria-describedby="message-2" aria-expanded="false" class="toggle" data-controls="toggle-b" id="toggle-a">paired</button>

paired b message

      <button aria-describedby="message-3" aria-expanded="false" class="toggle">isolated</button>

isolated b message


texts: How to best persist context to local storage

texts:
I want to be able to persist context to local storage.
My router looks like:
import React, { useState } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { Login } from './routes/login';
import { ResetPassword } from './routes/reset-password';
import { ResetEmailSent } from './routes/reset-email-sent';
import { App } from './routes/app';
import { GlobalContext, InitialState } from './globalContext';
import { Layout } from './layout';

function Router() {
  const [global, setGlobal] = useState(InitialState);
  return (
    <GlobalContext.Provider value={{ global, setGlobal }}>
      <BrowserRouter>
        <Route
          render={() => (
            <Layout>
              <Switch>
                <Route exact path='/'>
                  <Login />
                </Route>
                <Route exact path='/reset-password'>
                  <ResetPassword />
                </Route>
                <Route exact path='/reset-email-sent'>
                  <ResetEmailSent />
                </Route>
                <Route exact path='*'>
                  <App />
                </Route>
              </Switch>
            </Layout>
          )}
        />
      </BrowserRouter>
    </GlobalContext.Provider>
  );
}

export default Router;

and globalConext looks like
import { createContext, useContext } from 'react';

interface StateContextType {
  global: any;
  setGlobal: (State: any) => void;
}

const savedState = localStorage.getItem('state');
const state = savedState ? JSON.parse(savedState) : {};
const InitialState: any = state;

const GlobalContext = createContext<StateContextType>({
  global: InitialState,
  setGlobal: () => console.warn('no state provider'),
});

const useGlobal = () => useContext(GlobalContext);

export { InitialState, GlobalContext, useGlobal };

Should I set up a useEffect in the router to save to local storage whenever global changes?


texts: PHP creating slugify (clean URL) links in simple way?

texts:
I think this is the simplest way to slugify urls. You have any contra-indication?

function url_clean($str){
        $str = iconv('utf-8', 'us-ascii//TRANSLIT', $str);
        $clean_str = preg_replace(array('/\'|\"/','/ /'),array('','-'),$str);
        return $clean_str;
}


texts: Remove contiguous elements in array in a more functional way

texts:
I try to remove elements in an array if the number of contiguous element is greater than two.

Here are the tests:

test('delete pieces if number of piece contiguous greater than two', t => {
    t.deepEqual([null, null, null], removeIdenticalPieces([1, 1, 1]));
    t.deepEqual([null, null, null, null], removeIdenticalPieces([1, 1, 1, 1]));
    t.deepEqual([null, null, null, null, 4], removeIdenticalPieces([1, 1, 1, 1, 4]));
    t.deepEqual([4, null, null, null, null], removeIdenticalPieces([4, 1, 1, 1, 1]));
    t.deepEqual([1, 1, 4, 1, 1], removeIdenticalPieces([1, 1, 4, 1, 1]));
    t.deepEqual([1, 1], removeIdenticalPieces([1, 1]));
});

Here is a working function:

function removeIdenticalPieces(line) {
    const newLine = [];
    while (line.length !== 0) {
        const firstPiece = line.shift();
        let nbContiguousPieces = 0;
        for (let i = 0; i < line.length; i++) {
            let currentPiece = line[i];
            if (firstPiece !== currentPiece) {
                break;
            }
            nbContiguousPieces += 1
        }
        if (nbContiguousPieces >= 2) {
            newLine.push(null);
            for (let j = 0; j < nbContiguousPieces; j++) {
                line.shift();
                newLine.push(null)
            }
        } else {
            newLine.push(firstPiece);
            for (let k = 0; k < nbContiguousPieces; k++) {
                newLine.push(line.shift())
            }
        }
    }
    return newLine;
}

Does a more "functional" way exist to do the same?

Edit: thank you for your solutions.

Here the jsperf https://jsperf.com/removeidenticalpieces3.

I take the solution of @lilobase because it is faster and more readable.


texts: Two implementations of website internationalization

texts:
I have attempted to create an internationalization system for my PHP framework that I'm working on.

For the purpose I decided I will be using MySQL to store languages and translations. Respectively I have the tables

languages
id  | name
----+--------
1   | English
2   | Spanish

translations
id | 1             | 2           | n ...
---+---------------+-------------+------
1  | Hello, $user  | Hola, $user |   ...
2  | Friend        | Amigo       |   ...

I was told that this is not a normalized database structure. I think that this structure is easier to use, because if I were to add a column lang_id where I'd store the id of the language the string represents, then when I'm selecting I'd have to do

SELECT string FROM translations WHERE id = ? AND lang_id = {$lang_id}

Instead of what I currently use

SELECT {$lang_id} FROM translations WHERE id = ?

It looks simpler to me, also avoids the use of complex primary keys and uses less memory too. If I'm not correct please don't hesitate to criticize!

I have created two implementations of the logic class, one using eval in its base, other one using preg_replace_callback.

First implementation: Eval

class Translator {
    private $stmt = null;
    private static $instance;

    public static function getInstance(){
        if(!self::$instance){
            self::$instance = new self;
        }
        return self::$instance;
    }

    private function __construct() {
        $this->stmt = \X\Database::connection()->prepare('SELECT '.$_SESSION['lang_id'].' FROM translations WHERE id = ?')->getStmt();
    }

    public function get($id, $variables){
        $this->stmt->execute(array($id));
        foreach($variables as $k => $v){
            $$k = $v;
        }
        unset($id); unset($variables); unset($k); unset($v);

        return eval('return "'.addslashes($this->stmt->fetch(\PDO::FETCH_NUM)[0]).'";');
    }
}

Example usage in a view, assuming $t = \X\Translator::getInstance();

With variables

<?= $t->get(1, array('user'=>'John Doe')) ?>

Without variables

<?= $t->get(2) ?>

Second implementation: Regular Expressions

class Translator {
    public static function init(){
        ob_start();

        register_shutdown_function('\X\Translator::translateDocument');
    }

    public static function translateDocument(){
        $t = \X\Database::connection()->prepare('SELECT '.$_SESSION['lang_id'].' FROM translations WHERE id = ?')->getStmt();

        echo preg_replace_callback('/\{\{\s*(\d+)\s*(?:,(.+?))?\s*}}/', function($matches) use($t){
            $t->execute(array($matches[1]));

            if(count($matches) > 2){
                $keys = array();
                $vals = array();
                preg_replace_callback('/([^\s]+):\s*([^\;]+);/', function($matchesInner) use(&$keys, &$vals){
                    $keys[] = $matchesInner[1];
                    $vals[] = $matchesInner[2];
                }, $matches[2]);
                return str_replace($keys,$vals,$t->fetch(\PDO::FETCH_NUM)[0]);
            }else{
                return $t->fetch(\PDO::FETCH_NUM)[0];
            }
        }, ob_get_clean());
    }
}

Example usage, assuming that \X\Translator::init() has been called

With variables

{{ 1, $user: John Doe; }}

Without variables

{{ 2 }}

Finally

I ran a benchmark consisting of 5 runs of 1000 translations each, showing the statistics

#Average execution time
    eval:  0.65 sec
    regex: 1.15 sec

#Memory used
    eval:  240 kb
    regex: 253 kb