texts:
I have created a REST auth layer in front of my GraphQL API, I would like to know if it is secure enough or if I can improve anything, I will be adding more auth providers, in the end this API will serve a web app using the demonstrated Google log in and a React Native app with email, SMS, Facebook and Apple auth
// index.ts
server
  .register(fastifyCors, {
    origin: process.env.CORS_ORIGIN,
    credentials: true,
  })
  .register(fastifyCookie)
  .register(fastifySession, {
    cookieName: "fid",
    store: new RedisStore({
      client: new Redis(process.env.REDIS_URI),
      ttl: SESSION_TTL,
    }),
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years
      httpOnly: true,
      sameSite: "lax",
      secure: true,
    },
    saveUninitialized: false,
    secret: process.env.SESSION_SECRET,
  })
  .register(fastifyPassport.initialize())
  .register(apolloServer.createHandler({ cors: false }))
  .register(authRoutes)

// setupPassport.ts
export const setupPassport = (prisma: PrismaClient) => {
  fastifyPassport.registerUserSerializer<User, User["id"]>(
    async (user) => user.id
  )

  fastifyPassport.registerUserDeserializer<User["id"], User>(async (id) => {
    const user = await prisma.user.findUnique({
      where: {
        id,
      },
    })

    if (!user) {
      throw new Error("No user")
    }

    return user
  })

  fastifyPassport.use(
    new Strategy(
      {
        clientID: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL: "http://localhost:4000/auth/google/callback",
      },
      async (_accessToken, _refreshToken, profile, done) => {
        const existingUser = await prisma.identity.findFirst({
          where: {
            provider: "GOOGLE",
            providerId: profile.id,
          },
          include: {
            user: true,
          },
        })

        if (existingUser) {
          return done(undefined, existingUser)
        }

        if (!profile.emails?.length || !profile.name) {
          throw new Error("No email or name")
        }

        const newUser = await prisma.user.create({
          data: {
            ...profile.name,
            email: profile.emails[0].value,
            identities: {
              create: [{ provider: "GOOGLE", providerId: profile.id }],
            },
          },
        })

        return done(undefined, newUser)
      }
    )
  )
}

// authRoutes.ts
export const authRoutes: FastifyPluginCallback = (fastify, _opts, done) => {
  fastify.get(
    "/auth/google",
    {
      preValidation: fastifyPassport.authenticate("google", {
        scope: ["profile", "email"],
      }),
    },
    async (request, reply) => {}
  )

  fastify.get(
    "/auth/google/callback",
    {
      preValidation: fastifyPassport.authorize("google", { session: false }),
    },
    async (request, reply) => {}
  )

  done()
}

// permissions.ts
import { shield } from "graphql-shield"

export const permissions = shield({
  Query: {},
  Mutation: {},
  ShopLocation: rules.isAuthenticatedUser,
})

// rules.ts
import { rule } from "graphql-shield"

export const rules = {
  isAuthenticatedUser: rule()(async (_parent, _args, ctx: Context) => {
    return ctx.request.isAuthenticated()
  }),
  isAdmin: rule()(async (_parent, _args, ctx: Context) => {
    return ctx.request.user.role === Role.ADMIN
  }),
  isOperator: rule()(async (_parent, _args, ctx: Context) => {
    return ctx.request.user.role === Role.OPERATOR
  }),
  isUser: rule()(async (_parent, _args, ctx: Context) => {
    return ctx.request.user.role === Role.USER
  }),
}


texts: SqlConnection Transaction Management Approach

texts:
I am currently working on a SharePoint 2013 project with custom application pages development. On one of those pages, there are multiple insert / update to database table operations. Here are the sample code I am working with:

Product.cs

class Product
{
    public int ProductId { get; set; };
    public string ProductName { get; set; };
}

Here is the helper class which handle CRUD of products:

ProductFacade.cs

class ProductFacade
{
    public static Product Save(Product productObject)
    {
        Product product;
        using(SqlConnection conn = new SqlConnection(DatabaseHelper.ConnectionString)) // The connection string is retrieved from other helper class
        {
            SqlCommand cmd = new SqlCommand("SaveProduct", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            conn.Open();

            // Parameters setting and execute query operations here..
        }
        return product;
    }
}

In the application pages, I used the method like:

ApplicationPage.aspx.cs

public void SaveProducts()
{
    try
    {
        DataTable products = (DataTable)ViewState["Products"];
        if(products != null)
        {
            Product product;
            foreach(DataRow row in products.Rows)
            {
                product = new Product();
                product.ProductName = row["ProductName"].ToString();
                ProductFacade.Save(product);
            }
        }
    }
    catch(Exception ex)
    {
        LogHelper.WriteLog(Category.Unexpected, "Product Application Page", ex.Message + ", " + ex.StackTrace);
    }
}

All of the methods in that helper class work fine. But I am curious, how if I want to add transaction management, for example, if I want to add BeginTransaction, Commit, and Rollback operation on the above SaveProducts() method? Should I create and pass the SqlConnection object as a parameter to the ProductFacade.Save() method so it will be something like:

ProductFacade.cs

class ProductFacade
{
    public static Product Save(Product productObject, SqlConnection conn = null, SqlTransaction tran = null)
    {
        Product product;
        if(conn == null)
            conn = new SqlConnection(DatabaseHelper.ConnectionString);
        using(SqlCommand cmd = new SqlCommand("SaveProduct", conn))
        {
            if(tran != null)
                cmd.Transaction = tran;
            // The rest of the same code from before
        }
    }
}

And call the method with SqlConnection object passed like:

ApplicationPage.aspx.cs

public void SaveProducts()
{
    using(SqlConnection conn = new SqlConnection(DatabaseHelper.ConnectionString))
    {
        conn.Open();
        SqlTransaction transaction = conn.BeginTransaction();
        try
        {
            DataTable products = (DataTable)ViewState["Products"];
            if(products != null)
            {
                Product product;
                foreach(DataRow row in products.Rows)
                {
                    product = new Product();
                    product.ProductName = row["ProductName"].ToString();
                    ProductFacade.Save(product, conn, transaction);
                }
            }
            transaction.Commit();
        }
        catch(Exception ex)
        {
            transaction.RollBack();
            LogHelper.WriteLog(Category.Unexpected, "Product Application Page", ex.Message + ", " + ex.StackTrace);
        }
    }
}

Really appreciate any thoughts on this.


texts:
I am trying out websockets using the python async framework aiohttp.
Basically I have created a game which will include multiple players and they will be able to chat using web sockets. There could be multiple game rooms and a player will be in a single room at a time.
I believe I have the implementation right.
Please look into it.

from aiohttp import web, WSMsgType
from bson.objectid import ObjectId

from models import Game

routes = web.RouteTableDef()
@routes.get('/ws/{game_id}/{player_id}')
async def create(request):
    game_id = request.match_info['game_id']
    player_id = request.match_info['player_id']

    ws_current = web.WebSocketResponse()
    ws_ready = ws_current.can_prepare(request)
    if not ws_ready.ok:
        msg = "Sorry, something went wrong!"
        return web.json_response({'error': msg})

    await ws_current.prepare(request)

    query = {'_id': ObjectId(game_id), 'active': True}
    game = await Game.find_game(query=query, db=request.app['mongodb'])

    if game is None:
        msg = "Game over, start a new game"
        await ws_current.send_json({'action': 'error', 'name': player_id, 'msg': game_id})
        await ws_current.close()
        return

    if not any(player_id == str(player['_id']) for player in game['players']):
        msg = "You have not joined the game"
        await ws_current.send_json({'action': 'error', 'name': player_id, 'msg': msg})
        await ws_current.close()
        return

    await ws_current.send_json({'action': 'connect', 'name': player_id})

    # notify other players that a new player has joined
    for player in game['players']:
        if str(player['_id']) in request.app['websockets']:
            player_ws = request.app['websockets'][str(player['_id'])]
            await player_ws.send_json({'action': 'join', 'name': player_id})

    request.app['websockets'][player_id] = ws_current

    while True:
        msg = await ws_current.receive()

        if msg.type == WSMsgType.text:
            if msg.data == 'close':
                await ws_current.close()
            else:
                for player in game['players']:
                    if str(player['_id']) in request.app['websockets']:
                        player_ws = request.app['websockets'][str(
                            player['_id'])]
                        if player_ws is not ws_current:
                            await player_ws.send_json(
                                {'action': 'sent', 'name': player_id, 'text': msg.data})
        elif msg.type == WSMsgType.ERROR:
            print('ws connection closed with exception %s' %
                  ws_current.exception())
        else:
            break

    if player_id in request.app['websockets']:
        del request.app['websockets'][player_id]

    # notify other players that the player has left
    for player in game['players']:
        if str(player['_id']) in request.app['websockets']:
            player_ws = request.app['websockets'][str(player['_id'])]
            await player_ws.send_json({'action': 'disconnect', 'name': player_id})

    return ws_current

But the code doesn't look very good or pythonic as they say. Could you please help me out with this and also if there are things I should change with the logic as well.


texts: List Comprehension in Pythonic answer to LPTHW ex48

texts:
I'm not really seeing any use for a generator here, unless there's some way to hook a generator into a language dictionary.

But in the following code, the longhand version of the if statement (type_check()) returns a tuple (foo, bar) but to get the tuple from (my first ever) lc (type_identify) it needs to be called from result[0], as opposed to simply result.

Is this normal or am I doing something wrong in the lc?

word_types = {'noun': ['bear', 'princess', 'door'],
            'verb': ['go', 'run', 'hide', 'stop', 'close', 'kill', 'eat'],
            'stop': ['in', 'of', 'at', 'to', 'from', 'the'],
            'direction': ['up', 'down', 'north', 'south',
                        'east', 'west', 'back', 'forward']}

def type_check(word):
    word = word.lower()
    for label, type in word_types.items():
            if word in type:
                return (label, word)

def type_identify(word):
    word = word.lower()
    return [ (label, word) for label, type in word_types.items() if word in type ]

def scan(sentence):
    sentence_list = sentence.split()
    for k, v in enumerate(sentence_list):
        if type_identify(v):
            sentence_list[k] = type_identify(v)[0] #needed to add [0]
        else:
            try:
                sentence_list[k] = ('number', int(v))
            except ValueError:
                sentence_list[k] = ('error', v)
    return sentence_list


texts: Spring MVC @ControllerAdvice exception handling

texts:
This is about handling sql - foreign key constraint failure exceptions (SQL Error: 1452, SQLState: 23000) globally using Spring's controller advices and Hibernate - ConstraintViolationException.class.

I'm working on a small scale REST API which has 28 database tables and contains 32 foreign keys.

To handle exceptions on entire project, in my approach has two @ControllerAdvice classes, one for handle Servlet exceptions and the other for handle Hibernate sql exceptions.

In my RootDataAccessExceptionsHandler class (sql exceptionsare being handled here), has following @ExceptionHandler method.

@ExceptionHandler(value = {ConstraintViolationException.class})
protected ResponseEntity<Object> handleConstraintViolationException(
        ConstraintViolationException ex,
        WebRequest request
) {
    String cause = ex.getCause().toString();
    LOGGER.error("[ APP Exception ] : {}", ex.getCause().toString());
        switch (ex.getErrorCode()) {
            // catch Cannot add or update a child row:
            // a foreign key constraint fails exceptions
            case 1452: {
                return handleExceptionInternal(
                        ex,
                        getSqlForeignKeyViolationExceptionsPreProcessor().generate1452SqlExceptionResponse(ex.getSQLException()),
                        new HttpHeaders(),
                        HttpStatus.NOT_FOUND,
                        request
                );
            }
            // catch other sql violations - to be developed
            default: {
                return handleExceptionInternal(
                        ex,
                        createDefaultExceptionErrorResponse(),
                        new HttpHeaders(),
                        HttpStatus.NOT_FOUND,
                        request
                );
            }
        }

    }

}

And generate1452SqlExceptionResp(SQLException) is responsible for generate appropriate error response as follows,

Simply this method scans for the key which is violated using getMessage() of SQLException class and then generate error response.

public ResponseEntity<?> generate1452SqlExceptionResponse(SQLException sqle) {
    LOGGER.error("[ APP Exception SQL ] : {}", sqle.getErrorCode());
    LOGGER.error("[ APP Exception SQL ] : {}", sqle.getSQLState());

    if (sqle.getMessage().contains("FK_ID_001_USER_ID")
            || sqle.getMessage().contains("FK_ID_006_USER_ID")) {
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(
                        ErrorServiceMessage
                        .getBuilder()
                        .putCode("ERROR")
                        .putType("Unidentified user")
                        .putPayload("Given user cannot be found")
                        .build()
                );
    }
}

In here, FK_ID_001_USER_ID and FK_ID_006_USER_ID are two foreign keys, but like this, this method has bunch of conditional checks defined in order to process all 32 key violations.

Example

When an operation tries to do something with USER_ID - 10 (Now there's no user associated with this ID), an error will be generated and returned as JSON object asfollows,

{
    "headers": {},
    "body": {
        "code": "ERROR",
        "type": "Unidentified user",
        "payload": "Given user cannot be found"
    },
    "statusCode": "NOT_FOUND",
    "statusCodeValue": 404
}

Please review this approach and what are the drawbacks can be found on this.
Is there any other better approach ?
How can i improve this ?


texts: Android: accessing global data through replaceable instance

texts:
I have to access global data shared between activities in Android application.

I have simplified DataProvider class to contain only one field - options in order to make my question clearer, but in reality it is much complex class.

There is deviation from global singleton pattern here in sense, that global instance can be replaced at certain point with new set of data in LoadDataActivity. Activities that have older version of data can retain older version until they are restarted, in which case they will just grab new instance.

MainActivity is responsible for loading initial data into global DataProvider instance.

DataProvider.class

public class DataProvider
{
    // current global instance
    public static DataProvider instance = new DataProvider();

    // data
    private Map<String, String> options = new HashMap<String, String>();

    public Map<String, String> getOptions()
    {
        return options;
    }

    public void load(String source)
    {
        options.clear();
        options.put(source, source);
        // data loading
    }
}

MainActivity

public class MainActivity extends Activity
{
    private DataProvider data;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        data = DataProvider.instance;
        data.load("main");
        Map<String, String> options = data.getOptions();
        // read data from options and perform activity initialization
    }
}

ShowDataActivity

public class ShowDataActivity extends Activity
{
    private DataProvider data;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        data = DataProvider.instance;
        Map<String, String> options = data.getOptions();
        // read data from options and perform activity initialization
    }
}

LoadDataActivity

public class LoadDataActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load);
    }

    public void loadData(String source)
    {
        DataProvider data = new DataProvider();
        data.load(source);
        // replace global data instance with new set of data
        DataProvider.instance = data;
    }
}

Can above code be improved and how?


texts: Epilogue to a binary search to find the range of matching indexes

texts:
I am trying to find out the best practice for writing a loop which does one check and at the same time has to increment a value so that the while loop will eventually fail. Performance is important that's why I thought of using the least amount of variables.

Use case

In a decently low level method I do a binarySearch(array, key) which guarantees to find a key value in a sorted array if the key can be found. However it does not guarantees to find the first or last key first. But since I need the range of indexes in which the key excists (for other code later on) I try to find the last and first element in the array that matches. With this code I am trying to let lastSucceedingIndex hold the last index which holds the key:

while (lastSucceedingIndex < tailIndex && (array[++lastSucceedingIndex] == key)) {
}
lastSucceedingIndex--;

There is one situation in which a bug exists, namely when the lastSucceedingIndex is equal to the tailIndex: the while loop will fail and the ++lastSucceedingIndex will not happen. The lastSucceedingIndex-- is there in the end to fix the ++lastSucceedingIndex when it's not equal to the key, but since this does not happen in the last case it will decrement lastSucceedingIndex incorrectly. I wrote this loop for performance and I take this little bug for granted, it happens so rarely that it will effect less than 0.001% of all cases. This way it seems like I only need one counter and one variable, the loop could be executed as much as 17000 times before it finds its lastSucceedingIndex and the array is very large with possibly up to a million entries.

Are there any alternatives for performance and readability?

I analysed my code by the build in code analysis of my IDE and I get the remark

  while statement has empty body at line

Which seems to indicate that having a loop with no lines in them is considered a possible bug by the compiler or at least bad practice. Now my question is, is having an empty loop considered bad practice? I could move the lastSucceedingIndex to the body and make it bug-free but that would require one extra addition like so:

while (lastSucceedingIndex < tailIndex && array[lastSucceedingIndex + 1] == key) {
    lastSucceedingIndex++;
}

1 less bug for millions upon millions of extra assembly instructions seems a hard trade-off to make.


texts:
I'm trying to create a read-write-execute permissions system for items using user-group-world system.

I already have the user/group system set up, just not the permissions.

This is what I wrote:

/** @param $requestedPerm the permission being requested: read write or execute - 4, 2, or 1 respectively
* @param $level the permission level: world, group, or user
* @param $permInt the permissions checked against:
   (like 754) which is user:read-write-exec, group:read-exec, world:read
*/
function check($requestedPerm,$level,$permInt){
    $digit = ($permInt/$level)%10;
    return ($requestedPerm & $digit)===$requestedPerm;
}

$read = 4;
$write = 2;
$exec = 1;

$world = 1;
$group = 10;
$user = 100;

$bool = check($read,$group,754);

It seems to work how I want it to, but I'm new to bitwise operations, so I'm not too confident.

In my production code, it will be object oriented, but basically it'll work the same.

Is this check() function reliable, as long as I provide the correct $requestedPerm, $level, and $permInt?


texts: Populating an HTML table with JSON results

texts:
Could anyone suggest a better approach than the one I'm using now? I tried to keep it as minimal as possible, but this is the best I came up with. I did extensive research just to get to this point.

baccarat.php echos a json_encoded PDO array.

function baccarat() {
  clearTimeout($.ghist);

  $.getJSON('/baccarat.php', function(data) {
    $.col = {};
    for (var n = 0; n <= 4; n++) {
      $.col[n] = '';
      $.each(data, function(i) {
        $.col[n] = '<select onchange="patatas(this.id,this.value)" class="testbigroad ' + data[i][n] + '-type" id="' + n + '-' + i + '"><option value="P" >P</option><option value="B">B</option><option value="T">T</option><option value=""></option></select>';
        $(".col-" + n + "-" + i).html($.col[n]);
        $(".col-" + n + "-" + i + " option:contains(" + data[i][n] + ")").prop('selected', true);
      });
    }
  });

  $.ghist = setTimeout(function() {
    baccarat();
  }, 5000);
}

function patatas(test, test2) {
  alert(test);
  $.ajax({
    url: "updatebaccarat.php",
    data: $.param({
      strid: test,
      strvalue: test2
    }),
    type: 'post',
    success: function(response) {
      baccarat();
    }
  });
}


texts:
I would like to know an alternative, more elegant way to write the following method.  I am especially not enthusiastic of the nested if statement.

hasUserSavedCredentials: function () {
            var userName = Storage.get(CONFIG.app.storageUserName),
                password = Storage.get(CONFIG.app.storagePassword),
                result = false;
            if (userName !== null && password !== null) {
                if (userName.length > 0 && password.length > 0) {
                    result = true;
                    // save in state for faster retrivial
                    State.xx.isSaved = result;
                    State.xx.userName = userName;
                    State.xx.password = password;
                } else {
                    result = false;
                    State.xx.isSaved = false;
                }
            }
            return result;
        },


texts: Interpret a date from a string of digits

texts:
I developed a function that, from a given sequence of digits, extracts the date and reformat it.
This is the code:

from datetime import datetime as dt

def format_dates(field):
    n = len(field)
    match = False
    i = 0
    while match is False:
        try:
            # Take the last four digits
            year = int(field[-4 - i:n - i])
        except ValueError:
            return ''

        # Check if this year is between today's year +/- (15, 100)
        if (1919 <= year <= 2019):
            # Check if there are other 4 digits before these 4 ones
            if (len(field[-8 - i:n - i]) == 8):
                try:
                    f_date = dt.strptime(field[-8 - i:n - i],
                                         '%d%m%Y').strftime('%d/%m/%Y')
                    match = True
                    return f_date
                except ValueError:
                    pass
            else:
                return ''
        i += 1

Explanation:
This function:

Takes a sequence of digits as input.
extracts the last four digits from that sequence.
Checks if the extracted four digits are between 2019 and 1919, if not, it breaks.
If yes, it checks if there are more 4 digits before the previously extracted ones, if not it breaks.
If yes, it tries to format the whole 8 digits.
If there is a ValueError exception, it passes (ValueError, means there are 8 digits, the last four of them represent a correct year, but the fist four digits are wrong. So it passes to increment i + 1 to add a the next digits in the front and remove the last digit in the processed sequence).

Example:

input: '1303201946'

Iteration 1:

i = 0, match = False
year = 1946
test 1 (year between 2019 and 1919): passes.
test2 (there are 4 other digits before 1946, which are 0320): passes.
format the whole 8 digits: ValueError exception, so i = i+1 and pass to the next iteration.

Iteration 2:

i = 1, match = False
year = 0194
test 1 (year between 2019 and 1919): fails, so i = i + 1 and pass to the next iteration.

Iteration 3:

i = 2, match = False
year = 2019
test 1: passes
test 2: passes
format the whole 8 digits (13032019): 13/03/2019 (No ValueError exception) passes
match = True, return the formatted date, break from the while loop.

This function works fine, but the way it handles the errors seems ugly. Also I believe it is not optimized (same exceptions are repeated, a lot of returns and the code does not seem elegant).
How to reformat the code and make it more optimized?


texts: Trying to grasp OOP Rock, Paper, Scissors program

texts:
I'm trying to wrap my head around OOP but so far I feel like I'm just moving functions into classes and calling them methods. I am trying to create a "Rock Paper Scissors" game using OOP best practices.

Yesterday I asked someone to review this code and was told that my use of OOP was akin to being handed an electric drill and using it to hammer nails so I tried again:

from random import randrange

class NewGame(object):
    def __init__(self, num_rounds):
        self.num_rounds = num_rounds
        self.current_round = 0

    def round(self):
        human_choice = human_player.choose()
        comp_choice = comp_player.choose()
        decide_winner()
        game.current_round += 1

class Player(object):
    def __init__(self):
        self.score = 0
        self.choice = None

    def choose(self):
        self.choice = int(raw_input("Rock [1] Paper [2] Scissors [3]"))
        return self.choice

    def win_round(self):
        self.score += 1

    def win_game(self):
        print("YOU WON!")

class ComputerPlayer(Player):

    def choose(self):
        self.comp_choice = randrange(1, 4)
        return self.comp_choice

    def win_game(self):
        print("THE COMPUTER WON!")

def who_won(score1, score2):
    human_player_score = score1
    comp_player_score = score2
    if human_player_score > comp_player_score:
        human_player.win_game()
    if human_player_score < comp_player_score:
        comp_player.win_game()
    if human_player_score == comp_player_score:
        print ("IT WAS A TIE!")

def decide_winner():

    if human_player.choice == comp_player.comp_choice:
        print("It was a tie.")
    elif human_player.choice == 3 and comp_player.comp_choice == 2:
        print("The computer has won. Scissors cut paper.")
        comp_player.win_round()
    elif human_player.choice == 2 and comp_player.comp_choice == 3:
        print ("You won. Scissors cut paper.")
        human_player.win_round()
    elif human_player.choice == 2 and comp_player.comp_choice == 1:
        print ("You won. Paper covers rock.")
        human_player.win_round()
    elif human_player.choice == 1 and comp_player.comp_choice == 2:
        print ("You lost to the computer. Paper covers rock.")
        comp_player.win_round()
    elif human_player.choice == 1 and comp_player.comp_choice == 3:
        print ("You won. Rock smashes scissors.")
        human_player.win_round()
    elif human_player.choice == 3 and comp_player.comp_choice == 1:
        print ("You lost. Rock smashes scissors.")
        comp_player.win_round()

def game_play():
    num_rounds = raw_input("How many rounds? ")
    global game
    game = NewGame(num_rounds)
    global human_player
    global comp_player
    human_player = Player()
    comp_player = ComputerPlayer()
    while game.current_round < int(num_rounds):
        game.round()
        print "COMPUTER: ", comp_player.score, "HUMAN: ",human_player.score
    who_won(human_player.score, comp_player.score)

if __name__ == '__main__':
    game_play()

While I feel like this is a step in the right direction I'm also pretty sure that I'm still not quite "getting it" and was hoping that you could offer suggestions on how to do better.

Also, I'm pretty sure I read that global variables should be avoided but I could not figure out how to get it to work without them. I understand that I needed to use them because of encapsulation and scope but I don't know of how to get around that without using global variables.


texts:
I cleaned a big repository for my team with this Python code. My goal was for every developer in my team to check if some bad email are in the commit, and replace the information by the good one. I use git filter-branch and a for loop in bash.

Because I can't make an array in an array in bash, I created a Python script to handle all the developers in my team.

Any idea on how I can optimize this code? git filter-branch take a long time.

# coding=utf-8
import subprocess
import os

def generate_command(dev):
    emails_string = ""
    for email in dev["emails"]:
        emails_string += '"%s" ' % email
    return """git filter-branch -f --env-filter 'OLD_EMAILS=(%s)
CORRECT_NAME="%s"
CORRECT_EMAIL="%s"
for email in ${OLD_EMAILS[@]};
do
        if [ "$GIT_COMMITTER_EMAIL" = "$email" ]
        then
                export GIT_COMMITTER_NAME="$CORRECT_NAME"
                export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
        fi
        if [ "$GIT_AUTHOR_EMAIL" = "$email" ]
        then
                export GIT_AUTHOR_NAME="$CORRECT_NAME"
                export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
        fi
done' --tag-name-filter cat -- --branches --tags""" % (emails_string.strip(),
                                                       dev["author_name"],
                                                       dev["author_email"])

developers = [
    {
        "emails": ["bad_email_author1@mycompany.com", "bad_email2_author1@mycompany.com"],
        "author_name": "first dev",
        "author_email": "good_email_author1@mycompany.com"
    },
    {
        "emails": ["bad_email_author2@mycompany.com", "bad_email2_author2@mycompany.com"],
        "author_name": "second dev",
        "author_email": "good_email_author2@mycompany.com"
    }
]

if __name__ == '__main__':
    for developer in developers:
        subprocess.call(generate_command(developer), shell=True)


texts: Manage Case Statement with (Int, long, short, double.....)

texts:
I have the following case statements that has to be modified to fit these cases:
Dec, Double, Int, Long, Short, Date, and String.

Please let me know if there is an easier way to handle this rather than repeating the following (slightly modified for each case):

Case GetType(Integer)
    If String.IsNullOrEmpty(c.Text) Then
        list.Add(CInt(0))
    Else
        Try
            list.Add(CInt(c.Text))
        Catch ex As Exception
            WriteAudit(ex, True)
            Dim intValue As Integer
            If Not Integer.TryParse(c.Text, intValue) Then
                c.Text = c.Text.Substring(0, c.Text.Length - 1)
                MessageBox.Show("Please Enter Only Integer Values Here")
            End If
        End Try
    End If


texts: Recursive implementation of palindrome string checker

texts:
I've tried to refactor my program to single return statement at the end of the program, however, it ruins the end statements of the recursion because I want to return from function in specific line and not in the end of the function.

I'd like suggestions on how this code can work and be elegantly designed to comply with

Multiple return statements
Single return statement

private static boolean isPalindrome(String pal)
{
        if(pal.length() == 1 || pal.length() == 2 )
        {
            if(pal.length()==1)
            {
                return true;
            }

            else
            {
                if(pal.charAt(0) == pal.charAt(1))
                {
                    return true;
                }
                return false;
            }
        }

        else
        {
            if(pal.charAt(0) == pal.charAt(pal.length()-1))
            {
                return isPalidrome(pal.substring(1, pal.length()-1));
            }
            return false;
        }
    }
}


texts:
I have a task connected with reinforcement learning. The state of my environment is described with the class below:

from dataclasses import dataclass
from typing import Tuple

@dataclass
class LearningState:
    pre_cross_densities: Tuple[int]
    global_aggregated_densities: Tuple[int]
    phase_no: int
    phase_duration: int

I need the following behaviour (*):

state_1 =          LearningState(pre_cross_densities=(0, 4, 5), global_aggregated_densities=(2, 4, 5), phase_no=2, phase_duration=1)
different_state =  LearningState(pre_cross_densities=(0, 4, 5), global_aggregated_densities=(2, 4, 8), phase_no=2, phase_duration=1)
state_1_also =     LearningState(pre_cross_densities=(0, 4, 5), global_aggregated_densities=(2, 4, 5), phase_no=2, phase_duration=1)
myDic = {state_1: [2], different_state: [7]}
myDic[state_1_also].append(6)
print(myDic[state_1]) # prints [2, 6]

So the dictionary needs to see state_1 and state_1_also as the same key. Also objects cannot be keys without a __hashable_ method implementation. To overcome these two problems I have created the following decorator.

def hashable(*args):
    def wrapper(cls):
        setattr(cls, '__hash__', eval('__hash__'))
        setattr(cls, '__eq__', eval('__eq__'))
        return cls
    return wrapper

def __hash__(self):
    all_properties = [prop for prop in self.hash_keys if not prop.startswith('__')]
    values = tuple([getattr(self, prop) for prop in all_properties])
    return hash(values)

def __eq__(self, other):
    return self.__hash__() == other.__hash__()

Now I can write my class with the decorator and hash_keys properties as follows:

from dataclasses import dataclass
from typing import Tuple
from services.hashable_decorator import hashable

@hashable()
@dataclass
class LearningState:
    pre_cross_densities: Tuple[int]
    global_aggregated_densities: Tuple[int]
    phase_no: int
    phase_duration: int
    hash_keys = ['pre_cross_densities', 'global_aggregated_densities', 'phase_no', 'phase_duration']

Code provides a (*) behaviour, but I feel like this is a sculpture. There will be a lot of data and I am also afraid about the performance couse there is a lot of immutable data.


texts: Rearrange an array in place such that the first and last halves are interleaved

texts:
Given an array of n elements in the following format { a1, a2, a3, a4,
  ….., an/2, b1, b2, b3, b4, …., bn/2 }. The task is shuffle the array
  to {a1, b1, a2, b2, a3, b3, ……, an/2, bn/2 } without using extra
  space.

  Input:

  The first line of input contains an integer T denoting the
  number of test cases. Then T test cases follow, Each test case
  contains an integer n denoting the size of the array. The next line
  contains n space separated integers forming the array.

  Output:

  Print the shuffled array without using extra space.

  Constraints:

  1<=T<=10^5

  1<=n<=10^5

  1<=a[i]<=10^5

  Example:

  Input:

  2

  4

  1 2 9 15

  6

  1 2 3 4 5 6

  Output:

  1 9 2 15

  1 4 2 5 3 6

My approach:

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

class ShuffleArray {

    private static int [] getShuffledArray (int[] arr) {
        //List <Integer> arrList = new ArrayList<>();

        return shuffleArray(arr,1,arr.length/2);
    }

    private static int [] shuffleArray (int[] arr, int swapInd1, int swapInd2) {
        if (swapInd2 == arr.length- 1) {
            return arr;
        }
        int temp = arr[swapInd2];

        for (int i = swapInd2 ; i > swapInd1; i--) {
            arr[i] = arr[i - 1];
        }

        arr[swapInd1] = temp;
        return shuffleArray(arr, swapInd1 + 2, swapInd2 + 1);
    }

    public static void main (String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            int numTests = sc.nextInt();

            while (numTests-- > 0) {
                int size = sc.nextInt();
                int[] arr = new int[size];
                for (int i = 0; i < size; i++) {
                    arr[i] = sc.nextInt();
                }
                int[] soln = getShuffledArray(arr);
                for (int i = 0; i < soln.length; i++) {
                    System.out.print(soln[i] + " ");
                }
                System.out.println();
            }
        }
    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference


texts: Two groups of Buttons but with same class name

texts:
I have two groups of two buttons (status). If you click on "Complete" or "On Hold", it will change the background color of the button. I am using same class name for all the buttons but each group of buttons have data attribute data-section='Park One' and data-section='Park Two'

jsFiddle

I am using the $.each() function to detect the section, remove all the background and add the background-color on selected button. Is the code well coded? What can be improved?

jQuery:

$(".updateStatus").click(function () {

    var buttonValue = $(this).val();
    var section = $(this).data("section");

    var cssClass = (buttonValue === "complete") ? 'green' : 'orange';

    $('.updateStatus').each(function () {
        if ($(this).data("section") == section) {

            $(this).removeClass("green orange");

            if ($(this).val() == buttonValue) {
                $(this).addClass(cssClass);
            }
        }
    })

});

HTML

Park One

<button class="updateStatus" value="complete" data-section='Park One'>Complete</button>
<button class="updateStatus" value="on hold" data-section='Park One'>On Hold</button>

Park Two

<button class="updateStatus" value="complete" data-section='Park Two'>Complete</button>
<button class="updateStatus" value="on hold" data-section='Park Two'>On Hold</button>


texts:
This is my code for an assignment. The task is to take a user input in form of a sequence of parenthesis' followed by an E to mark its end and determine whether it is a correct sequence (as an example (()())E is correct, )(()((E is incorrect) and if incorrect determine how many parentheses at the start you need to remove and how many to add at the end for it to be correct.
The code works. But it's super long and I wondered if there were any improvements I could do on it.
public class Main {

  public static String enter(){
    String enter = "";
    char nextValue ='A';
    while (nextValue!='E'){
      nextValue = In.readChar();
      enter += nextValue;
    }
    return enter;
  }
/*User Input. I know this could be done with ArrayList or scanner, but we haven't had these yet in classes.
So I did it by converting the user inputs into a string,
then storing that string into an array in main with "char []sequence = enter.toCharArray();"*/

  public static char[] removeParenthesisPairs(char[] a){
    for(int i=0; i<a.length; i++){
      if(a[i]=='('){
        a[i]='F';
        outerloop:
        for(int j=i+1; j<a.length;j++){
          if(a[j]==')'){
            a[j]='F';
            break outerloop;
          }
          if(j==a.length-1){
            a[i]='(';
          }
        }
      }
    }
    return a;
  }
/*I remove all the correct pairs from the sequence. I look for a ( and turn it into an F [to signal it's removed]
and search the rest of the sequence for a ) and turn that into an F too. If there is no ) I turn the F back into (.
This part I really don't like, it looks super clunky. Also I have read that the "break outerloop"
thing I'm using here is bad practice, but I havent figured out any other way to accomplish the same result.*/

  public static boolean checkIfCorrect(char[] a){
    for(int i=0;i<a.length-1;i++){
      if(a[i]!='F'){
        return false;
      }
    }
    return true;
  }
/* I check if the sequence is correct. If there are only F left in the array,
that means all entries were able to form pairs of () and the original sequence was correctly parenthesised.*/

   public static int subtract(char[] a){
    int count = 0;
    for(int i=0; i<a.length;i++){
      if(a[i]==')'){
        count += 1;
      }
    }
    return  count;
  }
// Check how many ) have to be subtracted at the beginning of the sequence.

  public static int add(char[] a){
    int count = 0;
    for(int i=0; i<a.length;i++){
      if(a[i]=='('){
        count += 1;
      }
    }
    return count;
  }
/*Check how many ( are still left in the sequence and need a ) added to form a pair.
I am kinda repeating myself here in the subtract() and add() methods, they are essentially doing
the same thing. The only way I have figured out for a method to return two values is by making
a class. But it seems even more convoluted to add new classes or is it preferable to this solution?*/

  public static void main(String[] args) {
    String enter= enter();
    char []sequence = enter.toCharArray();
    removeParenthesisPairs(sequence);
    boolean correct = checkIfCorrect(sequence);
    int additional = add(sequence);
    int removed = subtract(sequence);
    Out.println(correct);
    Out.println("removed = " + removed + " und additional = " + additional);
  }
/*I'm required by the assignment to have the boolean correct, int additional and int removed like this.
So I can't just do "Out.println("removed = " + subtract(sequence)+ " und additional = " + add(sequence));"*/
}


texts: 2D lattice with fixed boundary condition

texts:
I am writing code for the following equation with fixed boundary condition on a 2 dimensional lattice of \$L\times L\$ sites:

$$\begin{align}
x_{i+1} =&\ (1-\varepsilon)r\, x_i (1-x_i) + \\
         &\ 0.25\varepsilon\left((r\,x_{i-1}(1-x_{i-1}) + r\,x_{i+1}(1-x_{i+1}) + r\,x_{i-L}(1-x_{i-L}) + r\,x_{i+L}(1-x_{i+L})\right)
\end{align}$$

Fixed boundary condition means for end sites there are no neighboring sites beyond boundary.

Is there a simpler or more sophisticated way to write following code for the above equation with fixed boundary condition ?

def CML2d(x):
    eps = 0.3
    r = 3.9
    xn = np.zeros(N+1, float)
    for i in range(1, N+1):
        if i>L and i<=(L-1)*L:
            if i%L==1:
                xl, xr = 0., x[i+1]
                xu, xd = x[i-L], x[i+L]
            elif i%L==0:
                xl, xr = x[i-1], 0.
                xu, xd = x[i-L], x[i+L]
            else:
                xl, xr = x[i-1], x[i+1]
                xu, xd = x[i-L], x[i+L]
        elif i>1 and i<L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = 0., x[i+L]
        elif i>(L-1)*L+1 and i<L*L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = x[i-L], 0.
        elif i==1:
            xl, xr = 0., x[i+1]
            xu, xd = 0., x[i+L]
        elif i==L:
            xl, xr = x[i-1], 0.
            xu, xd = 0., x[i+L]
        elif i==(L-1)*L+1:
            xl, xr = 0., x[i+1]
            xu, xd = x[i-L], 0.
        elif i==L*L:
            xl, xr = x[i-1], 0.
            xu, xd = x[i-L], 0.
        xn[i] = (1-eps)*r*x[i]*(1-x[i]) + 0.25*eps*( r*xl*(1-xl) + r*xr*(1-xr) + r*xu*(1-xu) + r*xd*(1-xd) )
    return xn

L = 10 #side of 2d lattice
N = L*L #number of sites in 2d lattice
x0 = numpy.random.uniform(0.1, 0.9, N+1) #initial values for x

xf = [] # store iterate x
x = x0
for nt in np.arange(0.005, 50.005, 0.005):
    x = CML2d(x)
    xf.append(x)


texts:
Task: Get array of random integer (less than 10) numbers and random sequence of mathematical operations (multiplication and addition) which, when applied, will give a even number

Example: genOddSeq(4) -> [[6, 6, 6, 9], ['+', '*', '*']] (6 + 6 * 6 * 9 = 330)

Code:

function genOddSeq(count) {
  let getRandomInt = (min, max) => Math.floor(Math.random() * (Math.ceil(max) - Math.ceil(min))) + Math.ceil(min)
  let result = []
  let operations = []
  let numbersComp = 0;

  for (let i = 0; i < count; i++) {
    result.push(getRandomInt(1, 10))
  }

  for (let i = 0; i < count - 1; i++) {
    operations.push(Math.random() > 0.5 ? '+' : '*')
  }

  numbersComp += operations[0] == '+' ? result[0] + result[1] : result[0] * result[1]

  for (let i = 1; i < count - 1; i++) {
    numbersComp = operations[i] == '+' ? numbersComp + result[i + 1] : numbersComp * result[i + 1]
  }

  if (numbersComp % 2 != 0) {
    result[getRandomInt(0, count)] += 1
  }

  return [result, operations]
}


texts:
I've solved the problem below just would like some feedback?

  The function LetterChanges(str) takes a str parameter

  Replace every letter in the string with the letter following it in the
  alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel
  in this new string (a, e, i, o, u) and finally return this modified
  string.

function LetterChanges(str) {
  var newString = '';
  var newCode = 0;
  var len = str.length;
  var i = 0;

  for (; i < len; i++){
  /*Using ASCII code: this if statement return true if character at
  str[i] is a - y*/
  if (str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 121) {
      //Assign ASCII code plus 1 to a variable newCode
      newCode = str.charCodeAt(i) + 1;
      /*Check to see newCode variable is a lower case vowel from ASCII
      and if so, add capital of that vowel to newString variable, else
      use newCode variable to add character to newString*/
      if (newCode == 101) {
          newString += String.fromCharCode(69);
      } else if (newCode == 105) {
          newString += String.fromCharCode(73);
      } else if (newCode == 111) {
          newString += String.fromCharCode(79);
      } else if (newCode == 117) {
          newString += String.fromCharCode(85);
      } else {
          newString += String.fromCharCode(newCode);
      }

  /*Using ASCII code: this if statement return true if character at
  str[i] is z, in that case adding capital A*/
  } else if (str.charCodeAt(i) == 122){
      newString += String.fromCharCode(65);

  /*else just add to newString i.e uppercase(question didn't specify),
  symbols, number...*/
  } else {
      newString += str[i];
  }
 }
return newString;

}


texts:
I am working on a survivor problem:

  Complete Question Text: Take a second to imagine that you are in a
  room with 100 chairs arranged in a circle. These chairs are numbered
  sequentially from One to One Hundred.

  At some point in time, the person in chair #1 will be told to leave
  the room. The person in chair #2 will be skipped, and the person in
  chair #3 will be told to leave. Next to go is person in chair #6. In
  other words, 1 person will be skipped initially, and then 2, 3, 4..
  and so on. This pattern of skipping will keep going around the circle
  until there is only one person remaining.. the survivor. Note that the
  chair is removed when the person leaves the room.

  Write a program to figure out which chair the survivor is sitting in.

Below is the code I have:

public class ChairProblem {

    public static void main(String[] args) {
        System.out.println(getSurvivors(100));
    }

    private static int getSurvivors(int numChairs) {
        if (numChairs < 1) {
            return -1;
        }

        // populate chair array list
        ArrayList<Integer> chairs = new ArrayList<Integer>();
        for (int i = 0; i < numChairs; i++) {
            chairs.add(i + 1);
        }

        // removing all but one elements
        int indexOfChair = 0;
        int count = 1;
        while (chairs.size() > 1) {
            chairs.remove(indexOfChair);
            indexOfChair += count;// skip the count number of chairs
            count++; //increase the number of chairs to skip by 1
            indexOfChair %= chairs.size();// loop to beginning if necessary
        }

        return chairs.get(0);
    }
}

How can this be improved? I was asked this question in an interview and I gave this answer, but I'm not sure whether this can be improved in terms of complexity or Java Docs as well.


texts: General solution to sum multiples of multiple numbers below a limit

texts:
sumMultiples() is a working general solution to Project Euler's first problem.  Don't read it if you want to try it yourself.

This question is about preserving this general nature while improving performance, perhaps using math tricks like sumSkip() and sumIndetity().  Unfortunately everything I find that takes advantage of these tricks sacrifices the ability to have a general solution that works with any number of multiples and any limit.  Notice how using sumSkip() and sumIdentity() require hand tuning to work.  I'd like to use the same interface sumMultiples() uses and allow any number of base numbers with any values.  Well, short of causing overflows anyway.

In main sumSkip() and sumIdentity() are being used with the inclusion–exclusion principle in a rigid hand tuned form.  I'm suspecting there is a general way to apply this principle to this problem but frankly I can't see it.  I'll accept solutions that don't use it so long as they truly improve this solutions Big O Complexity.

I believe sumMultiples() is O(below x base) complexity.  I'm looking to improve on that.

Before linking possible duplicates or solutions please ensure they deal with the general requirement.

public static void main(String[] args) {
    int below = 1000;
    int[] base = {3, 5};

    System.out.println( sumMultiples(below, base) );

    // Making names shorter to help readability
    int b0 = base[0];
    int b1 = base[1];

    // Hand tuned to number and values.  Something I'd like to avoid.
    System.out.println( sumSkip(b0, below) + sumSkip(b1, below) - sumSkip(b0*b1, below) );
    System.out.println(  b0*sumIdentity(below/b0) +
                         b1*sumIdentity(below/b1-1) -
                         b0*b1*sumIdentity( below / (b0*b1) )  );
}

// General solution - any sized base with any values - uses brute force approach
private static int sumMultiples(int below, int... base) {
    int result = 0;
    boolean isMultiple;

    // Every integer below limit
    for(int i = 1; i < below; i++) {

        // Resetting dirty bit pattern
        isMultiple = false;

        // Every base
        for (int j = 0; j < base.length; j++) {

            // Stays false until a multiple is found. Then stays true.
            isMultiple |= i % base[j] == 0;
        }

        // Sum if i is a multiple of an integer in multiples
        if (isMultiple) {
            result += i;
        }
    }

    return result;
}

// Skip non multiples - still fairly brute force - less general
public static int sumSkip(int base, int below) {
    int result = 0;
    int multiple = base;

    while (multiple < below) {
        result += multiple;
        multiple += base;
    }

    return result;
}

// Sum using math
public static int sumIdentity(int n) {
    return n*(n+1)/2;
}

Output:

233168
233168
233168


texts: Can this Google Hurdles code be made to run any faster?

texts:
Anyone can play Google Hurdles today. Here is my score: 1.1 second. Is there are way of improving this score and running faster than a second?

http://www.google.com/doodles/hurdles-2012

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RunOlim {

private volatile static boolean run=true;

public static void main(String[] args) {
    Robot robot = null;

    Thread th = new Thread(new Runnable(){

        @Override
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                run=false;
            }

        }

    });
    th.start();

    try {
        robot = new Robot();
    } catch (AWTException e) {

        e.printStackTrace();
    }
    while(run){
        robot.keyPress(KeyEvent.VK_RIGHT);
        robot.keyRelease(KeyEvent.VK_RIGHT);

        robot.keyPress(KeyEvent.VK_LEFT);
        robot.keyRelease(KeyEvent.VK_LEFT);
    }
}

}


texts:
I have a requirement in my current project that will need a Prioritised Queue that supports the IObservable interface. Please notify me of any problems with the implementation that I currently have:

ObservablePriorityQueue<T>

public sealed class ObservablePriorityQueue<T> : IQueue<T>, IObservable<T> where T : IPrioritised
{
    #region "IObservable<T> Implementation"
    // A list of the subscribers for the IObservable implementation
    List<IObserver<T>> _subscribers = new List<IObserver<T>>(10);

    Object _observableSyncLock = new Object();

    #region "Interface specific"
    public IDisposable Subscribe(IObserver<T> observer)
    {
        if (observer == null)
        {
            throw new ArgumentNullException("The observer cannot be null.");
        }

        if (!_subscribers.Contains(observer))
        {
            lock (_observableSyncLock)
            {
                _subscribers.Add(observer);
            }
        }

        return new Disposable(() =>
        {
            this.Unsubscribe(observer);
        });
    }
    #endregion

    public void Unsubscribe(IObserver<T> observer)
    {
        if (observer == null)
        {
            throw new ArgumentNullException("The observer cannot be null.");
        }

        observer.OnCompleted();

        if (_subscribers.Contains(observer))
        {
            // remove the entry, but don't dispose it just
            // in case they want to re-subscribe with the same observer later
            lock (_observableSyncLock)
            {
                _subscribers.Remove(observer);
            }
        }
    }
    #endregion

    #region "IQueue<T> Implementation"

    readonly List<T> _data = new List<T>(100);
    Object _queueSyncLock = new Object();

    public void Enqueue(T value)
    {
        if (value == null)
        {
            throw new ArgumentException("The item to be enqueued cannot be null");
        }

        lock (_queueSyncLock)
        {
            _data.Add(value);
        }

        // now that the entry has been added, notify everyone
        Task.Run(() =>
        {
            lock (_observableSyncLock)
            {
                foreach (IObserver<T> subscriber in _subscribers)
                {
                    subscriber.OnNext(value);
                }
            }
        });
    }

    public T Dequeue()
    {
        if (_data.Count > 0)
        {
            lock (_queueSyncLock)
            {
                var result = _data.OrderByDescending(element => element.Priority).ThenBy(element => element.TimeStamp).First();
                _data.Remove(result);
                return result;
            }
        }
        return default(T);
    }

    public T Peek()
    {
        if (_data.Count > 0)
        {
            return _data.OrderByDescending(element => element.Priority).ThenBy(element => element.TimeStamp).First();
        }
        return default(T);
    }

    public Int32 Count { get { return _data.Count; } }
    #endregion
}

IQueue<T>

public interface IQueue<T>
{

    void Enqueue(T value);
    T Dequeue();
    T Peek();

    Int32 Count { get; }
}

IPrioritised<T>

public interface IPrioritised
{
    QueuePriority Priority { get; }
    DateTime TimeStamp { get; }
}

QueuePriority

public enum QueuePriority
{
    None = 0,
    Lowest = 1,
    Low = 2,
    Normal = 3,
    High = 4,
    Highest = 5
}

Disposable

public sealed class Disposable : IDisposable
{
    readonly Action _action;
    public Disposable(Action action)
    {
        _action = action;
    }
    public void Dispose()
    {
        if (_action != null)
        {
            _action();
        }
    }
}


texts: Comma Code (Python) (Automate The Boring Stuff)

texts:
This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. My code also includes a loop for the user to create their list.
def add_and(alist):
    if ((alist != []) & (len(alist) > 2)):
        for item in alist[:-1]:
            print(item + ", ",end="")
        print("and", alist[-1])
    elif ((alist != []) & (len(alist) == 2)):
        print(alist[0], "and", alist[1])
    elif ((alist != []) & (len(alist) == 1)):
        print(alist[0])
    else:
        print("")

your_list = []
while True:
    print("Enter An Item or nothing")
    item = input()
    if ((item) == ""):
        print("")
        break
    else:
        your_list.append(item)
        continue

add_and(your_list)

I know that the code works, but I was wondering if there were any faux-pas that I am implementing, or if there is anything I could obviously do to make it cleaner. Thanks!


texts: Building nested dictionaries to dump it to .json later

texts:
I am looking for some way to improve my code. It works but it doesn't look good and I am almost sure that lot of Best Practices rules are violated.

The save_session() function, creates dictionary with other dictionaries nested in. At the end the dictionary is dump to .json file.

I will appreciate any suggestions and advice for improvement of this code.

For better understanding the code of save_session():

workouts_instances is the list of current WorkoutPlan instances,

WorkoutPlan stores instances of Training and Exercise,

Training stores instances of Exercise,

class WorkoutPlan:
    def __init__(self, name, trainings=list(), exercises=list()):
        self.name = name
        self.trainings = trainings
        self.exercises = exercises
    ...

class Training:
    def __init__(self, name, exercises=list()):
        self.name = name
        self.exercises = exercises
    ...

class Exercise:
    def __init__(self, name, details=dict()):
        self.name = name
        self.details = details
    ...

Here is the code of save_session():

def save_session():
    """Exports current data to .json file."""
    data_to_save = {}

    # add workout plans
    for workout in workouts_instances:
        data_to_save[workout.name] = {}

        # add trainings
        if workout.trainings:
            data_to_save[workout.name]["trainings"] = {}

            for training in workout.trainings:
                data_to_save[workout.name]["trainings"][training.name] = {}

                # add training exercises
                if training.exercises:
                    data_to_save[workout.name]["trainings"][training.name]['exercises'] = {
                        exercise.name: {} for exercise in training.exercises
                    }

                    for exercise in training.exercises:

                        if exercise.details:
                            data_to_save[workout.name]["trainings"][training.name]['exercises'][exercise.name][
                                'details'] = {detail: value for detail, value in
                                              exercise.details.items()}

        # add exercises
        if workout.exercises:
            data_to_save[workout.name]["exercises"] = {}

            exercises_to_save = data_to_save[workout.name]["exercises"]

            for exercise in workout.exercises:
                exercises_to_save[exercise.name] = {}

                if exercise.details:
                    details = exercise.details
                    exercises_to_save[exercise.name]['details'] = {detail: value for detail, value in details.items()}

    with open(WORKOUTS_FILE, 'w') as json_file:
        json.dump(data_to_save, json_file, indent=4)

and here is the example of output, data stored in .json file:

{
    "FBV - Full Body Workout": {
        "trainings": {
            "Training A": {
                "exercises": {
                    "squats": {
                        "details": {
                            "description": "squats with barbell",
                            "series": 4,
                            "repeats": 4,
                            "load": 70
                        }
                    }
                }
            }
        },
        "exercises": {
            "some exercise name": {
                "details": {
                    "description": "some description",
                    "series": 5,
                    "repeats": 5,
                    "load": 60
                }
            },
            "bench press - wide": {
                "details": {
                    "description": "bench press with wide grip",
                    "series": 5,
                    "repeats": 5,
                    "load": 60
                }
            }
        }
    }
}


texts: Representing a Java Swing containment hierarchy in Haskell

texts:
A Java desktop application exposes the class/containment hierarchy of its Swing GUI through RPC. I'm building a Haskell client that connects to the application. The objective is to be able to perform queries like "find all the buttons of width less than w, located within screen rectangle r" over a data structure on the Haskell side.

I'm not sure about how to best represent the structure, especially regarding inheritance/subtyping. I have tried two approaches. The first one:

data Component = Component
    {
        componentId::Int,
        pos::(Int,Int),
        dim::(Int,Int),
        componentType::ComponentType,
        children::[Component]
    }

data ComponentType =
     ButtonComponent Button
     -- other component types here
    |OtherComponent

data Button = Button
    {
        buttonText::Text
        -- other button attributes here
    }

I'm also considering a second solution using existential types, together with Typeable to implement "downcasting":

data Component = Component
    {
        componentId::Int,
        pos::(Int,Int),
        dim::(Int,Int),
        children::[AnyComponent]
    } deriving Typeable

data AnyComponent = forall a . ( Typeable a, HasComponent a ) => AnyComponent a

class HasComponent a where
    base :: a -> Component
    downcast :: Typeable b => a -> Maybe b

instance HasComponent Component where
    base = id
    downcast = cast      -- cast function is from Data.Typeable

instance HasComponent AnyComponent where
    base (AnyComponent a) = base a
    downcast (AnyComponent a) = cast a

data Button = Button
    {
       buttonComponent:: Component,   -- pointer to "superclass" info
       buttonText::Text
       -- other button attributes here
    } deriving Typeable

instance HasComponent Button where
    base = buttonComponent
    downcast = cast

What solution is more idiomatic Haskell? Are there better solutions?


texts:
The code is meant to find the longest substring that is in alphabetical order.
I would like to know if I can do it more efficiently than I have done here. I am in my first week of my first introductory course, so I'm not looking for more advanced solutions. I just want to know if I'm not making it more complicated than necessary based on my current knowledge. I could't figure out how to use indexing for example.

s = 'azcbobobegghakl'

c = ""
d = ""
e = ""

for i in s:
    if c <= i:
        c = i
        d += c
        if len(d) > len(e):
            e = d
    else:
        c = i
        d = c
print('Longest substring in alphabetical order is: ' + e)


texts: Lowest cost path through elements in a matrix

texts:
I've developed a program in Python that calculates the lowest possible costing path between two points in a matrix, including the values contained in the start and finish cells. The code is below. Once the matrix gets larger than 4×4, it becomes very slow. Are there any obvious problems with my code (recursive method). I'm wondering if this can be improved before looking at other non-recursive approaches.

def legal_moves(rows,cols,path, start):
    list_moves = []
    row_start = start[0]
    col_start = start[1]

    if col_start < cols:
        if col_start == 0:
            new_col_start = [col_start+1, col_start]
        else:
            new_col_start = [col_start+1, col_start-1, col_start]
    else:
        new_col_start = [col_start-1, col_start]

    if row_start < rows:
        if row_start == 0:
            new_row_start = [row_start+1,row_start]
        else:
            new_row_start = [row_start+1, row_start-1, row_start]
    else:
        new_row_start = [row_start-1, row_start]

    for row in new_row_start:
        for col in new_col_start:
            if row == row_start and col == col_start:
                next
            else:
                if [row,col] not in path:
                    list_moves.append([row,col])
    return list_moves

def min_path (rows,cols,path, start, end, path_sum=0):
    if path == None:
        path = [start]
    else:
        path = path [:] + [start]

    row_index = start[0]
    col_index = start[1]

    if start == [0,1] and path_sum == 18:
        print ("",end="")

    path_sum += matrix[row_index][col_index]

    if start == end:
        list_paths.append(path)
        list_sum.append (path_sum)
        return

    list_moves = legal_moves(rows,cols,path,start)

    for move in list_moves:
        min_path (rows,cols,path, move, end, path_sum)

matrix = [[1,4,6,7],
[3,5,7,8],
[19,2,12,11]]

cols = len(matrix[0]) - 1
rows = len(matrix) - 1
start = [2,3]
end = [0,0]

list_paths = []
list_sum = []
path = None

min_path(rows,cols,path,start,end)
print (f'From: {start} to {end} with a cost of: {min(list_sum)}')
print (f'They are: {list_paths[list_sum.index(min(list_sum))]}')


texts:
This is my own implementation of an hashtable. I would like to receive some reviews or some feedbacks.

public class HashTableEntry<K,V> {

        private K key;
        private V value;
        private HashTableEntry<K,V> next;

        public HashTableEntry(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() {
            return key;
        }

        public void setKey(K key) {
            this.key = key;
        }

        public V getValue() {
            return value;
        }

        public void setValue(V value) {
            this.value = value;
        }

        public HashTableEntry<K, V> getNext() {
            return next;
        }

        public void setNext(HashTableEntry<K, V> next) {
            this.next = next;
        }
}

public class HashTable<K, V> {

    private static int DEFAULT_CAPACITY = 31;

    private HashTableEntry<K,V>[] table;

    @SuppressWarnings("unchecked")
    public HashTable() {
        table = (HashTableEntry<K,V>[])new Object[DEFAULT_CAPACITY];
    }

    @SuppressWarnings("unchecked")
    public HashTable(int capacity) {
        table = (HashTableEntry<K,V>[])new Object[capacity];
    }

    public void put(K key, V value) {

        int index = getIndex(key);

        HashTableEntry<K,V> entry = getLastEntry(table[index]);

        entry.setNext(new HashTableEntry<K,V>(key, value));
    }

    public V get(K key) {

        int index = getIndex(key);

        return findValue(table[index], key);
    }

    private int getIndex(K key) {

        return key.hashCode() % table.length;
    }

    private HashTableEntry<K,V> getLastEntry(HashTableEntry<K,V> entry) {

        if (entry == null) return null;

        HashTableEntry<K,V> currentEntry = entry;

        while(currentEntry.getNext() != null)
            currentEntry = currentEntry.getNext();

        return currentEntry;
    }

    private V findValue(HashTableEntry<K,V> entry, K key) {

        if (entry == null) return null;

        HashTableEntry<K,V> currentEntry = entry;

        while(currentEntry.getNext() != null) {

            if (currentEntry.getKey().equals(key)) {
                return currentEntry.getValue();
            }

            currentEntry = currentEntry.getNext();
        }

        return null;
    }
}


texts: Computing the sentiment score of a sentence

texts:
I wrote a script to compute the polarity of sentences. The script is based on this:

The lexicon based approach assigns a sentiment tags to words in a text based on dictionaries of positive and negative words. A sentiment score is then calculated for each document as:
$$\frac{\text{number of positive words} - \text{number of negative words}}{\text{total number of words}}$$

Is the code below okay? Should I have to improve it to take into consideration the position of the word in the sentence?
fileDir = os.path.dirname(os.path.realpath('__file__'))

lexiconpos = open(os.path.join(fileDir, 'Ressources/positive.txt'), 'r', encoding='utf-8')
lexiconpos = set([line.rstrip() for line in lexiconpos])
lexiconneg = open(os.path.join(fileDir, 'Ressources/negative.txt'),'r', encoding='utf-8')
lexiconneg = set([line.rstrip() for line in lexiconneg])

path = os.path.join(fileDir, 'data/reference/freins.tsv')
with open(path, 'r', encoding='utf-8') as l_1:
    next(l_1)
    l_1 = [line.rstrip() for line in l_1]

tagger = treetaggerwrapper.TreeTagger(TAGLANG='fr')
def process_text(text):
    '''extract lemma and lowerize then removing stopwords.'''

    text_preprocess =[]
    text_without_stopwords= []

    text = tagger.tag_text(text)
    for word in text:
        parts = word.split('\t')
        try:
            if parts[2] == '':
                text_preprocess.append(parts[0])
            else:
                text_preprocess.append(parts[2])
        except:
            print(parts)

    text_without_stopwords= [word.lower() for word in text_preprocess if word.isalnum()] #if word not in stopWords
    #return text_without_stopwords
    return text_preprocess

def extract_info(texte, lexique1, lexique2):

    lemme_treetagger = []
    lemme_sent = []
    len_sent = []
    for elt in texte:
        texte_treetagger = process_text(elt.lower())
        lemme_treetagger.append(" ".join(texte_treetagger))
        len_sent.append(len(" ".join(texte_treetagger)))

    word_pos=[]
    word_neg=[]
    word_pos_len=[]
    word_neg_len=[]
    for elt in lemme_treetagger:
        word_pos.append([word for word in lexique1 if word in elt])
        word_neg.append([word for word in lexique2 if word in elt])

    for lst in word_pos:
        word_pos_len.append(len(lst))
    for lst in word_neg:
        word_neg_len.append(len(lst))

    print(len_sent)
    return texte, lemme_treetagger, len_sent, word_pos, word_neg, word_pos_len, word_neg_len

texte, lemme_treetagger, len_sent, word_pos, word_neg, word_pos_len, word_neg_len = extract_info(l_1, lexiconpos, lexiconneg)

def polarity_word(texte, *args):

    texte, lemme_treetagger, len_sent, word_pos, word_neg, word_pos_len, word_neg_len = extract_info(texte, lexiconpos, lexiconneg)

    for elt in lemme_treetagger:
        print(elt)
        sub_list = list(map(operator.sub, word_pos_len, word_neg_len))
        score = list(map(truediv, sub_list, len_sent))

    return score


texts:
I wrote the following code using Ruby to compute item-based collaborative filtering (using Jaccard coefficient of similarity).

I would appreciate feedback about any potential issues with the code and tips to make the code better comply with the best practices.

require 'json'
require 'set'

def compute_jaccard_coefficients(users_for_activities)
    jaccard_coefficient_hash = {}
    all_activities = Set.new
    users_for_activities.each do |key1, array1|
        users_for_activities.each do |key2, array2|
            if key1 != key2
                all_activities.add key1
                all_activities.add key2
                intersected_users = array1 & array2
                unioned_users = array1 | array2
                if unioned_users.length > 0
                    jaccard_coefficient_hash[[key1, key2]] = intersected_users.length.fdiv(unioned_users.length)
                    else
                    jaccard_coefficient_hash[[key1, key2]] = 0
                end
            end
        end
    end
    return [jaccard_coefficient_hash, all_activities]
end

data = '[
{"user": "1", "activities": ["running", "swimming", "rowing"]},
{"user": "2", "activities": ["tennis", "rowing"]},
{"user": "3", "activities": ["swimming", "running"]},
{"user": "4", "activities": ["tennis", "swimming"]}
]'

parsed_data = JSON.parse(data)

users_for_activities = Hash.new{|h,k| h[k] = []}

parsed_data.each do |child|
    child["activities"].each do |activity|
        users_for_activities[activity] << child["user"]
    end
end

all_activities = Set.new
jaccard_coefficient_hash, all_activities = compute_jaccard_coefficients(users_for_activities)

parsed_data.each do |child|
    activities_to_recommend = {}
    child["activities"].each do |user_activity|
        all_activities.each do |generic_activity|
            if user_activity != generic_activity
                if activities_to_recommend.has_key?(generic_activity)
                    if jaccard_coefficient_hash[[user_activity, generic_activity]] > activities_to_recommend[generic_activity]
                        unless child["activities"].include?(generic_activity)
                            activities_to_recommend[generic_activity] = jaccard_coefficient_hash[[user_activity, generic_activity]]
                        end
                    end
                    else
                    unless child["activities"].include?(generic_activity)
                        activities_to_recommend[generic_activity] = jaccard_coefficient_hash[[user_activity, generic_activity]]
                    end
                end
            end
        end
    end
    print "User " + child["user"] + ": "
    print activities_to_recommend.sort_by {|k,v| v}.reverse
    print "\n"
end

Output:

User 1: [["tennis", 0.3333333333333333]]
User 2: [["running", 0.3333333333333333], ["swimming", 0.25]]
User 3: [["rowing", 0.3333333333333333], ["tennis", 0.25]]
User 4: [["running", 0.6666666666666666], ["rowing", 0.3333333333333333]]


texts: Keeping attribute names simple when using getters and setters

texts:
Is the use of _pn in __init__ pythonic? It seems that most examples change the actual attribute to self._pn to indicate it's private, but I would like to be able to call self.pn but have the advantage of checks with setters.

The following code will cause a recursive loop:

class part:
'Holds various attributes of interest for a part number'
def __init__(self, pn):
    self.pn = pn

def set_pn(self, pn):
    if type(pn) != str:
        raise Exception("Part number needs to be a string")
    self.pn = _pn

pn = property(fset = set_pn)

The following won't, but I'm not sure if _pn is pythonic:

class part:
'Holds various attributes of interest for a part number'
def __init__(self, _pn):
    self.pn = _pn

def set_pn(self, pn):
    if type(pn) != str:
        raise Exception("Part number needs to be a string")
    self.pn = _pn

_pn = property(fset = set_pn)


texts:
I use the following code which works as expected. The code uses open ID connect to login user. Because I'm pretty new to node and express, it will be great if I can get some tips for the async usage- e.g. if I’m doing it and the error handling correctly.
The code is doing connect via oidc layer
https://en.wikipedia.org/wiki/OpenID_Connect
which does a user login according to client secret and client id, then the authorization server is calling to the redirect route of the application  and if everything is OK the user logged in to the system.
This is the index.js
const express = require('express');
const logon = require('./logon');

const app = express();
const port = process.env.PORT || 4000;

logon(app)
  .then(() => {
    console.log('process started');
  });
app.use(express.json());

app.listen(port,
  () => console.log(`listening on port: ${port}`));

This is the logon.js
const { Issuer, Strategy } = require('openid-client');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const azpi = require('./azpi');
const bodyParser = require('body-parser');
const passport = require('passport');

module.exports = async (app) => {

  let oSrv;
  const durl = `${process.env.srvurl}/.well-known/openid-configuration`;
  try {
    oSrv = await Issuer.discover(durl);
  } catch (err) {
    console.log('error occured', err);
    return;
  }

  app.get('/', prs(), passport.authenticate('oidc'));

  const oSrvCli = new oSrv.Client({
    client_id: process.env.ci,
    client_secret: process.env.cs,
    token_endpoint_auth_method: 'client_secret_basic',
  });

  passport.serializeUser((user, done) => {
    done(null, user);
  });
  passport.deserializeUser((obj, done) => {
    done(null, obj);
  });

  const cfg = {
    scope: 'openid',
    redirect_uri: process.env.ruri,
    response_type: 'code',
    response_mode: 'form_post',
  };

  const prs = () => (req, res, next) => {
    passport.use(
      'oidc',
      new Strategy({ oSrvCli , cfg }, (tokenset, done) => {
        const claims = tokenset.claims();
        const user = {
          name: claims.name,
          id: claims.sub,
          id_token: tokenset.id_token,
        };
        return done(null, user);
      }),
    );
    next();
  };
  app.use(
    bodyParser.urlencoded({
      extended: false,
    }),
  );
  app.use(cookieParser('csec'));
  app.use(
    cookieSession({
      name: 'zta-auth',
      secret: 'csect',
    }),
  );

  app.use(passport.initialize());
  app.use(passport.session());

  app.get('/redirect', async (req, res, next) => {
    passport.authenticate('oidc', async (err, user) => {
      if (err) {
        console.log(`Authentication failed: ${err}`);
        return next(err);
      }
      if (!user) {
        return res.send('no identity');
      }

      req.login(user, async (e) => {
        if (e) {
          console.log('not able to login', e);
          return next(e);
        }
        try {
          const url = await azpi.GetUsers(user.id_token);
          return res.redirect(url);
        } catch (er) {
          res.send(er.message);
        }
      });
    })(req, res, next);
  });
};

Is my async code usage is okay?


texts: Split a string on spaces, accounting for backslash as escape character, in Haskell

texts:
This code works, but since I'm just learning Haskell I'm wondering if it could have been done in a more idiomatic way.

The main function is called tokenize, and it uses helper functions called tokenizeOne and tokenizeSeveral.

Here is the code:

tokenizeOne "" (' ':rest) = tokenizeOne "" rest
tokenizeOne str ('\\':ch:rest) = tokenizeOne (str ++ [ch]) rest
tokenizeOne x (' ':rest) = (x, rest)
tokenizeOne x "" = (x, "")
tokenizeOne x (ch:rest) = tokenizeOne (x ++ [ch]) rest

tokenizeSeveral x "" = x
tokenizeSeveral x str = let (token, rest) = tokenizeOne "" str in
    tokenizeSeveral (x ++ [token]) rest

tokenize str = tokenizeSeveral [] str


texts:
What is the most Pythonic way to take a dict of lists and produce a new dict with the list items as keys and the previous dict's keys as list items.

Here's a visual explanation:

favorite_fruits = {"alice": {"apple", "orange"}, "bob": {"apple"}, "carol": {"orange"}}
people_by_fruit = {"orange": {"carol", "alice"}, "apple": {"bob", "alice"}}

Here's the best I have at the moment:

from collections import defaultdict
favorite_fruits = {"alice": {"apple", "orange"}, "bob": {"apple"}, "carol": {"orange"}}
people_by_fruit = defaultdict(set)
for person, fruit in favorite_fruits.items():
    for fruit in fruit:
        people_by_fruit[fruit].add(person)


texts: Max and Min in array using minimum comparisons

texts:
Is this the most robust and fastest way for finding the min and max out of an array without using STL functions? How can I improve it?

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
system("clear");
int c=9,n[10],max,min,i;
while (c>=0) {
n[c]=random()%100;
printf("%d\n",n[c]);
c--;}c=10;
max=n[0];min=n[1];
for ( i =0; i<c; i++) {
  if(max<n[i])max=n[i];
  else if(min>n[i])min=n[i];
}
printf("\n%d\n%d\n",max,min);
return 0;
}


texts:
I am writing code to write a C template file; the executable takes two arguments (main) <file name> and <no of questions> and outputs a file with a file named argv[1] and inside which there are n no of functions with n+1 switch cases in main() calling those functions; where n = argv[2].

Problem

My problem is with the allocation of memory to the char*'s, it feels so messy and roundabout.
The formatting of strings some times gives no seg faults other times it is not possible. For example, ass = fopen(("./%s",fname),"w"); works fine; but strncat(swic,("    case %d : q%d();break;\n",i,i),s/n); does not work. For it to work I have to use format() a user function defined as follows:

char* format(char* s,...){
    va_list args;
    size_t siz=strlen(s)+sizeof(size_t);
    char* res=(char*)malloc(siz);
    va_start(args,s);
    vsnprintf(res, siz, s, args);
    va_end(args);
    return(res);
}

Another problem in above function is that I am unable to get the size or no. of passed arguments which I need to correctly allocate char *res which contains the resultant formatted string.
Also, during debugging I found that during fclose(ass) in main(); vscode gives two faults received SIGTRAP, Trace/breakpoint trap. in ntdll!RtlpNtMakeTemporaryKeyreceived signal ?, Unknown signal., then exits.

Click to view the complete code

    char* tail(n)
    {
        char *main="\nint main(){\nint choi;\nprintf(\"\\n*note: enter 0 to diplay all Q\\n\\n  Display Q no. \");\nscanf(\"  %%d\",&choi);\nswitch(choi){\n";
        char *naim="    default: printf(\"! invalid choice !\");\n}\nreturn 0;\n}";

        size_t f=strlen(format("void q%d(){printf(\"\\n ---- Q %d -----\\n\");\n}\n",n,n))*n, s=strlen(format("    case %d : q%d();break;\n",n,n))*n, s0=strlen(format("q%d();",n))*n,c0=strlen("    case 0 : break;\n");
        char *func=(char*)malloc(f);
        // strcpy(func,"");
        char *swic0=(char*)malloc(s0);
        char *swic=(char*)malloc(s);
        // strcpy(swic,"");
        for(int i=1;i<=n;i++){
            if(i==1){
            strcpy(func,format("void q%d(){printf(\"\\n ---- Q %d -----\\n\");\n}\n",i,i));
            strcpy(swic,format("    case %d : q%d();break;\n",i,i));
            strcpy(swic0,format("q%d();",i));
            }
            else{
                strncat(func,format("void q%d(){printf(\"\\n ---- Q %d -----\\n\");\n}\n",i,i),f/n);
                strncat(swic,format("    case %d : q%d();break;\n",i,i),s/n);
                strncat(swic0,format("q%d();",i),s0/n);
            }
        }
        // return strcat(strcat(strcat(func,main),swic),naim);
        char *case0=(char*)malloc(c0+s0);
        sprintf(case0,"    case 0 : %sbreak;\n",swic0);
        char *res=(char*)malloc(strlen(format("%s%s",main,naim))+f+s+c0+s0);
        sprintf(res,"%s%s%s%s%s",func,main,case0,swic,naim);
        return res;

    }

Example: output file if argv[2]=="2"

    //##########  Loops assigment

    #include<stdio.h>

    int abs(int n){
        if(n<0) return n*-1;
        else return n;
    }

    // answer functions --
    void q1(){printf("\n ---- Q 1 -----\n");
    }
    void q2(){printf("\n ---- Q 2 -----\n");
    }

    int main(){
    int choi;
    printf("\n*note: enter 0 to diplay all Q\n\n  Display Q no. ");
    scanf("  %d",&choi);
    switch(choi){
        case 0 : q1();q2();break;
        case 1 : q1();break;
        case 2 : q2();break;
        default: printf("! invalid choice !");
    }
    return 0;
    }


texts:
I've got a page which contains a form: when page is requested, a session is stored:

$_SESSION['ok']=date("His");

Plus, the form contains this hidden field:

<input type="text" name="email-confirm" id="email-confirm" style="display:none;" placeholder="Do not fill this field">

When user sends the form, the following PHP code is launched to check if they're not a bot:

session_start();
if(!isset($_SESSION['ok'])){die('Error: you have to enable cookies in order to make everything work fine.');}
$fast = date("His") -4;
if($fast < $_SESSION['ok']){$_SESSION['banned']=1;
die('Woah, that was fast! Would you mind doing a little captcha verification? Refresh the page to continue.');}
if(!empty($_POST['email-confirm'])){$_SESSION['banned']=1;
die('You\'ve been temporarily banned.<br>
Refresh the page to lift the ban with a captcha verification.');
}

If session 'banned' is set and user tries to visit any page on the site, they're asked to complete a captcha challenge which relies on google recaptcha.

Is this method to block bots reliable?
I don't like very much the idea to ask every user to complete a captcha verification, because  I feel like it would be annoying to do that every time, but if it's the only method to be really safe, then I'd adopt it.


texts:
I have devised what I feel to be a simple hash/salting algo for Java, and am looking for some feedback from people more skilled than myself. Please find below my code;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

public class PassSecureSuite
{
    /**
     * Method:          RecoverPass
     * Function:        This class contains methods for authenticating the user against the database and creating
     *                  a new user with a secure password.
     */
    public static String verifyIput(String submittedPass, String salt)
    {
        MessageDigest soMd = null;
        try
        {
            soMd = MessageDigest.getInstance("SHA-256");
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }

        soMd.update(salt.getBytes());
        byte[] abytesToString = soMd.digest(submittedPass.getBytes());
        StringBuilder buildThis = new StringBuilder();

        for(int i=0; i<abytesToString.length; i++)
        {
            buildThis.append(Integer.toString((abytesToString[i] & 0xff) + 0x100, 16).substring(1));
        }
        String passToVerify = buildThis.toString();
        return passToVerify;
    }
    /**
     * Method:          getSalt
     * Function:        Generate a secure, randomly-generated string to add extra security to the user password
     */
    public static String getSalt()
    {
        SecureRandom sosRand = null;
        try
        {
            sosRand = SecureRandom.getInstance("SHA1PRNG", "SUN");
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchProviderException e)
        {
            e.printStackTrace();
        }

        byte[] baniceAndSalty = new byte[16];
        sosRand.nextBytes(baniceAndSalty);
        return baniceAndSalty.toString();
    }
    /**
     * Method:          agenerateSecurePass
     * Function:        Generates a password string based on a byte feed
     */
    public static String sgenSecurePass(String password, String salt)
    {
        String ageneratedPass = null;
        MessageDigest digest = null;
        try
        {
            digest = MessageDigest.getInstance("SHA-256");
        }
        catch (NoSuchAlgorithmException nsae)
        {
            nsae.printStackTrace();
        }

        digest.update(salt.getBytes());
        byte[] babytes = digest.digest(password.getBytes());

        StringBuilder obuildThis = new StringBuilder();

        for(int i=0; i < babytes.length; i++)
        {
            obuildThis.append(Integer.toString((babytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        ageneratedPass = obuildThis.toString();
        return ageneratedPass;
    }
}

I am looking to make this as secure as possible without using other people's APIs, as I enjoy having total control over my security within applications.

The above example appears fairly robust to me, as I have been unable to break the hash/salt on any application I have built, but I feel that I can improve this, I am just not sure how.


texts: Using my own Optional type with fold method in groovy

texts:
I have written an Optional type in groovy roughly based on java8s Optional. I implemented and use a fold method and would like to know if it can be improved. First, here comes the Optional (I will only use its fold method for my question though):

class Optional<T> {
    T value

    private Opional(T value) {
        this.value = value
    }

    final Boolean isPresent() {
        value != null
    }

    final Object map(Closure mapper) {
        mapper(value).with { Object result ->
            if (result != null)
                return new Optional(result)
            else
                return new Optional(null)
        }
    }

    final Object flatMap(Closure mapper) {
        if( ! this.isPresent)
            return Optional.empty()
        else
            return this.map(mapper)
    }

    public Object fold(Closure ifEmpty, Closure f) {
        if(isPresent())
            return ifEmpty.call()
        else
            return f.call(value)

    }

    final static Optional<T> of(T value) {
        if(value == null)
            throw new IllegalArgumentException("Argument for Optional.of() must not be null")

        new Optional<T>(value)
    }

    final static Optional<T> empty() {
        new Optional(null)
    }
}

(I ommitted some methods like orElse and others)

Next, there are maybe two result-variables. They are therefore of type Optional. I want to execute an action if at least one of the result variables is present AND successfull. I do it like that:

if( resultA.fold({false}, {it.isSuccess()}) || resultB.fold({false}, {it.isSuccess()}) ) {
    //execute action
}

Is it a good way to use fold here or should I just stay with:

 (resultA.isPresent() && resultA.isSuccess())

Also, can/could this usage of fold be improved or are there other ways to work it out?


texts: Simple BST implementation using C++ Struct

texts:
I am trying to implement DSs in C++ and this is BST insert and search functions. I tried in two different ways, please review and see if one is advantageous over other.
With pointer to pointer

#include <stdio.h>
#include <iostream>

struct BstNode{
 int data;
 BstNode* left;
 BstNode* right;
};

BstNode* NewNode(int data)
{
 BstNode* newNode = new BstNode();
 newNode->data = data;
 newNode->left = NULL;
 newNode->right = NULL;
 return newNode;
}
void Insert(BstNode** root,int data)
{
 if(*root == NULL)
 {
     *root= NewNode(data);
 }
 else if(data <= (*root)->data)
 {
     (*root)->left = NewNode(data);
 }
 else
 {
     (*root)->right = NewNode(data);
 }
}
bool SearchBST(BstNode* root, int data)
{
 if(root == NULL)
 {
     return false;
 }
 else if(root->data == data)
 {
     return true;
 }
 else if(data <= root->data)
 {
     return SearchBST(root->left, data);
 }
     else
     {
         return SearchBST(root->right, data);
     }
 }
 int main()
 {
     BstNode* ptr_root = NULL;
     Insert(&ptr_root,15);
     Insert(&ptr_root,10);
     Insert(&ptr_root,16);
     int num;
     std::cout<<"Enter the number: \n";
     std::cin>> num;
     if (SearchBST(ptr_root,num))
         std::cout<<"Found\n";
     else
         std::cout<<"Not Found\n";

     return 0;
 }

Without pointer to a pointer:

#include <stdio.h>
#include <iostream>

struct BstNode{
    int data;
    BstNode* left;
    BstNode* right;
};
BstNode* NewNode(int data)
{
    BstNode* newNode = new BstNode();
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}
BstNode* Insert(BstNode* root,int data)
{
    if(root == NULL)
    {
        root= NewNode(data);
    }
    else if(data <= root->data)
    {
        root->left = NewNode(data);
    }
    else
    {
        root->right = NewNode(data);
    }
    return root;
}
bool SearchBST(BstNode* root, int data)
{
    if(root == NULL)
    {
        return false;
    }
    else if(root->data == data)
    {
        return true;
    }
    else if(data <= root->data)
    {
        return SearchBST(root->left, data);
    }
    else
    {
        return SearchBST(root->right, data);
    }
}
int main()
{
    BstNode* ptr_root = NULL;
    ptr_root=Insert(ptr_root,15);
    ptr_root=Insert(ptr_root,10);
    ptr_root=Insert(ptr_root,16);
    int num;
    std::cout<<"Enter the number: \n";
    std::cin>> num;
    if (SearchBST(ptr_root,num))
        std::cout<<"Found\n";
    else
        std::cout<<"Not Found\n";

    return 0;
}


texts: Python factory class with dynamic imports

texts:
I'm trying to write a factory class that essentially provides a user-friendly frontend to creating objects of different kinds depending on keywords. So the user will just have to import this module, and then use module.factory.make_new with the relevant keywords.
The directory structure will be pretty flat: this file will sit in a directory along with SubclassA.py which defines the class SubclassA likewise for SubclassB etc. That is, each subclass is in its own module of the same name.
If the user wants to dig a bit deeper, they can provide their extension to the code by writing SubclassC.py which provides class SubclassC and then add the line factory.register_format("subclassc", "SubclassC") to the bottom of this file (or, eventually, this will be handled by a config file). Here's what I have so far:
import importlib

class TrackerFactory:
    def __init__(self):
        self.subclass_dict = {}

    def register_format(self, subclass_name, subclass_package):
        fmt = importlib.import_module(subclass_package)
        self.subclass_dict[subclass_name] = getattr(fmt, subclass_package)

    def make_new(self, subclass, **kwargs):
        return self.subclass_dict[subclass](subclass, **kwargs)

factory = TrackerFactory()
factory.register_format("subclassA", "SubclassA")
factory.register_format("subclassB", "SubclassB")

I'm just wondering what the possible downsides of this sort of approach are, and what kind of gotchas I might have to look out for. Is there a better way to do this? I get the feeling I can achieve what I want with class methods and a class variable dictionary, and thus avoid hardcoding an instance of the factory, but I couldn't get it to work...
Some things I'm not bothered by:

sneaky hidden imports not at the top of the file (the advantages of dynamically loading the dependencies of only the registered formats outweigh the poor style, for me). And in any case, this is only used to load a very specific type to module. The modules themselves being loaded in this way (SubclassA etc) could have lots of unusual dependencies.

Some things I've already thought of:

extend the register_format method to allow the module name and class name to differ
use some try/except logic
since, in my use case, there will actually be only one or a few objects actually instantiated, I could juggle things around so that the import is actually in make_new (and subclass_dict just holds a string rather than the function), and then registering a format you won't use that you don't have the dependencies for wouldn't choke.


texts: Python: screen colors adjuster using Turtles

texts:
I am a total beginner in Python and I am trying with the modules Turtle. I am currently trying to code for 3 sliders (R, G, B) for adjusting the colors of the turtle screen. However, I found parts of my codes filled with redundancies, could anyone please tell me how to trim the code to make it more compact and clear, especially in the draw_red, draw_green, draw_blue parts? Thanks in advance.
import turtle

turtle.setworldcoordinates(0, 0, 4, 255)
turtle.colormode(255)
turtle.tracer(False)

colors = ['red', 'green', 'blue']
painters = []
red_x, green_x, blue_x = 1, 2, 3
turtle.bgcolor(0,0,0)
def spawningPainters():
    global painter
    for i in range(len(colors)):
        painter = turtle.Turtle()
        painters.append(painter)
        painter.up()
        painter.speed(0)
        painter.setheading(90)
        painter.color(colors[i])
        painter.pencolor('black')
        painter.shape('turtle')
        painter.shapesize(5, 5, 5)
        xPos = i + 1
        painter.goto(xPos, 0)

def assign_painters():
    global redPainter, greenPainter, bluePainter
    redPainter = painters[0]
    greenPainter = painters[1]
    bluePainter = painters[2]

def draw_red(x, y):
    redPainter.ondrag(None)
    x = red_x
    redPainter.goto(x, y)
    redPainter.ondrag(draw_red)
    update_screen_color()

def draw_green(x, y):
    greenPainter.ondrag(None)
    x = green_x
    greenPainter.goto(x, y)
    greenPainter.ondrag(draw_green)
    update_screen_color()

def draw_blue(x, y):
    bluePainter.ondrag(None)
    x = blue_x
    bluePainter.goto(x, y)
    bluePainter.ondrag(draw_blue)
    update_screen_color()

def update_screen_color():
    red = max(min(redPainter.ycor(), 255) , 0)
    green = max(min(greenPainter.ycor(), 255), 0)
    blue = max(min(bluePainter.ycor(), 255), 0)

    turtle.bgcolor(int(red), int(green), int(blue))

def back_to_origin():
    for painterIndex in range(len(painters)):
        painters[painterIndex].goto(painterIndex + 1, 0)

def listening_input():
    redPainter.ondrag(draw_red)
    greenPainter.ondrag(draw_green)
    bluePainter.ondrag(draw_blue)
    turtle.onkeypress(back_to_origin, 'c')

def main():
    spawningPainters()
    assign_painters()
    listening_input()

main()
turtle.listen()
turtle.tracer(True)
turtle.mainloop()