texts: Hide and show menu if button clicked and change the icon

texts:
I wrote simple jQuery code and I want suggestions as to how I can do it better and shorter.

Basically the following code is used to change the menu icon on each click event and also hide and display menu accordingly. If I did it correctly, then fine, but is there any way to make the code shorter and faster?

if ( $('.site-topbar').length ) {
    // prepend menu icon
    $('.nav-topbar').prepend('');

    // hide navigation menu
    $('.nav-topbar').find('#menu-topbar-menu').hide();

    if ( $('.responsive-menu').length ) {

        // prepare click event
        $('.responsive-menu').click(function() {

            $(this).find('.ion-android-menu').attr('class', function(){

                // find class='ion-android-menu' exists
                // then add class='ion-ios-close-empty' if button clicked
                if ( $(this).attr('class') == 'ion-android-menu' ) {
                    $(this).addClass('ion-ios-close-empty');

                    // display menu
                    $('.nav-topbar').find('#menu-topbar-menu').show(800);

                } else {

                    // remove class="ion-ios-close-empty" if condition return false
                    $(this).removeClass('ion-ios-close-empty');

                    // hide menu
                    $('.nav-topbar').find('#menu-topbar-menu').hide(800);
                }
            });
        });
    }
}


texts: Many CRUD operations for a list of technicians' shifts

texts:
The following code snippet is causing me a performance problem in my application. The first 5 db queries are not high time consuming, the real problem lays on the foreach loop. I considered to use Dictionary structures instead of List to improve the lookups, but improving the loop will make the real difference.

public void ProcessShifts(IList<NavTechAbsenceDto> navShifts)
{

    var branches = _iagiBranchModelFactory.GetAll().ToList();

    var technicians = _iagiTechnicianModelFactory.GetAll().Where(it => it.IsActive).ToList();

    var activeTechCodes = technicians.Select(t => t.ERPId).ToList();

    var absencesForActiveTech = navShifts.Where(a => activeTechCodes.Contains(a.TechCode)).ToList();

    var absences = _iagiTechnicianModelFactory.GetAllWithAbsences().SelectMany(it => it.Absences);

    IEnumerable<Absence> mwmAbsenceList = absences == null ? null : absences.Where(a => a.Start >= DateTime.Today);

    foreach (NavTechAbsenceDto absence in absencesForActiveTech)
    {
        var mwmAbsence = mwmAbsenceList == null ? null : mwmAbsenceList.FirstOrDefault(it => it.AGIErpId == absence.AGIErpId);

        AGIBranchModel branch = branches.FirstOrDefault(b => b.ERPId == absence.BranchCode);
        AGITechnicianModel tech = technicians.FirstOrDefault(t => t.ERPId == absence.TechCode);

        if (branch == null || tech == null)
        {
            Logger.Trace("NOT AVAILABLE: Shift Branch: {0}, Shift Technician: {1}", absence.BranchCode, absence.TechCode);
            continue;
        }

        if (mwmAbsence == null)
        {
            if (absence.AGILogicallyDeleted == 1)
            {

                Logger.Trace(string.Format("DELETED absence:{0} from Navision, but it does not exist in Scheduler", absence.AGIErpId));
            }
            else
            {
                Logger.Trace(string.Format("ADD absence:{0}", absence.AGIErpId));

                tech.AddAbsence(absence, branch);
            }
        }
        else
        {

            if (absence.AGILogicallyDeleted == 1)
            {
                Logger.Trace(string.Format("DELETE absence:{0}", absence.AGIErpId));
                tech.DeleteAbsence(mwmAbsence);
            }
            else
            {
                Logger.Trace(string.Format("UPDATE absence:{0}", absence.AGIErpId));

                mwmAbsence.Start = absence.Start;
                mwmAbsence.End = absence.End;
                mwmAbsence.AGIBranchId = branch.Id;
                mwmAbsence.TechnicianId = tech.Id;
                mwmAbsence.Technician = tech;
                mwmAbsence.AGIType = absence.AGIType;
                mwmAbsence.AGIMobile = absence.AGIMobile;
                mwmAbsence.AGIErpId = absence.AGIErpId;

                tech.UpdateAbsence(mwmAbsence);
            }
        }
    }
}


texts:
One of the badges available on Stack Exchange is the Archaeologist badge. This is awarded for making 100 edits on posts that had been inactive (at the time of the edit) for 6 months.

There is no indication on your profile, or elsewhere, how close you are to this badge. Here's an SEDE query that can give you a good idea of how close you are to being awarded Archaeologist:

-- Title or text edits on someone else's post
-- that had been idle for 6 or more months prior

with CandidateEdits as (

    -- Edits the user has made to titles/body of some other user's posts.

    select min(ph.Id) as EditId,
           ph.PostId EditPost,
           IsNull(p.ParentId, p.Id) as EditQuestion,
           ph.RevisionGUID as EditGUID,
           ph.CreationDate as EditDate
    from PostHistory as ph
        inner join Posts as p on ph.PostId = p.Id and OwnerUserId != UserId
    where UserId = ##UserId:int##
      and PostHistoryTypeId in (4,5) --Title/Body edits.
      and PostTypeId in (1, 2) -- question/answer
    group by ph.PostId, p.Id, p.ParentId, ph.RevisionGUID, ph.CreationDate

), RelatedPosts as (

    -- Posts that cannot be modified in the 6-month window

    select EditId,
           EditDate,
           EditGUID,
           EditQuestion as RelatedPost
    from CandidateEdits

    UNION

    select EditId,
           EditDate,
           EditGUID,
           Id as RelatedPost
    from CandidateEdits
    inner join Posts on EditQuestion = ParentId
         and PostTypeId = 2

), Inactives as (

    -- Edits that have no activity related posts in the 6 month window.
    -- Use Left join, and have a count of 0

    select EditId,
           count(distinct RevisionGUID) as Invalidations
    from RelatedPosts Left Outer Join PostHistory on
             RelatedPost = PostId
         and CreationDate between DateAdd(mm, -6, EditDate) and EditDate
         and Id < EditId
         and RevisionGUID <> EditGUID
    group by EditId
    having count(distinct RevisionGUID) = 0

), FirstEdit as (

    -- Only one of multiple edits on the same post count toward the badge.

    select ce.EditPost,
           min(i.EditId) as EditId
    from CandidateEdits as ce
      inner join Inactives as i on ce.EditId = i.EditId
    group by ce.EditPost

), Revisions as (

    -- Identify which revision in the system relates to the edit you made.
    -- convert to NVarchar to make concatenation simpler in result.

    select EditID,
           Convert(NVarchar(10), EditPost) as RevPost,
           Convert(NVarchar(10), count(distinct RevisionGUID)) as Revision
    from CandidateEdits inner join PostHistory
      on  PostId = EditPost
      and Id <= EditId
      and PostHistoryTypeId < 10
    group by EditId, EditPost
)

select Rank() over (order by EditDate) as Dig,
       ce.EditPost as [Post Link],
       EditDate,
       'site://revisions/' + RevPost + '/' + Revision
             + '|Revision ' + Revision as Revision
from  CandidateEdits as ce
inner join FirstEdit as i on ce.EditId = i.EditId
inner join Revisions as r on ce.EditId = r.EditId
order by EditDate

The logic for the inactive posts is complicated: A new, or edited answer, or an edit to the question itself, resets the 'inactive' counter. The most recent change to any of the answers, or the question itself, is what is used regardless of whether you are editing the question, or one of its answers.

Edits to the tags do not count, only to the title, or body of the post.

Because you may make multiple edits to the post, we only want to display the one edit that counts, and the revision it belongs to.

All suggestions welcome


texts:
I'm developing a legend toggling d3.js pie chart application using this jsFiddle as my latest version.

I am aiming to get a streamlined working example where the legend can toggle the slices, trying to deactivate all slices - resorts in a reset which reactivates all the slices. Splitting up presentation and application layer logic.

Tweening needs improvement too - as the slices pop into existence then re-tween smoothly.

How do I improve/fix the various bugs in this code base?

onLegendClick: function(dt, i){
                    //_toggle rectangle in legend

var completeData = jQuery.extend(true, [], methods.currentDataSet);

                    newDataSet = completeData;
                    if(methods.manipulatedData){
                        newDataSet = methods.manipulatedData;
                    }

                    d3.selectAll('rect')
                    .data([dt], function(d) {
                        return d.data.label;
                    })
                    .style("fill-opacity", function(d, j) {
                        var isActive = Math.abs(1-d3.select(this).style("fill-opacity"));
                        if(isActive){
                            newDataSet[j].total = completeData[j].total;
                        }else{
                            newDataSet[j].total = 0;
                        }

                        return isActive;
                    });

                    //animate slices
                    methods.animateSlices(newDataSet);

                    //stash manipulated data
                    methods.manipulatedData = newDataSet;

                }


texts: "Quick" save in electron with a conformation dialog

texts:
I have implemented a "quick" save for my electron app. There has to be a better way to achieve what I am doing.

The MessageBox will always be triggered on a save as command. If the user selects save (Ctrl+S), I'm basically keeping a variable to hold if a file has been loaded from the file system or not. If a file has been loaded I take the array from fs and convert into a string and use that as the filename for the quick save.

If no file has been uploaded, this means my gantt area is clear and the SaveDialog box will be triggered since this isn't a loaded file. A little code to further explain. Before the quicksave function the filename is either undefined or a string from the fs array and stored in quickSaveFilename.

// dirty quicksave
const quickSave = () => {
  let saveData = gantt.serialize();
  saveData = JSON.stringify(saveData, null, '\t');
  if (quickSaveFileName === undefined) {
    dialog.showSaveDialog(
      {
        defaultPath: `C:\\Users\\${process.env.USERNAME}\\Documents\\`,
        filters: [
          {
            name: 'json',
            extensions: ['json'],
          },
        ],
      },
      (filename) => {
        if (filename === undefined) {
          return;
        }
        fs.writeFile(filename, content, (error) => {
          if (error) {
            dialog.showErrorBox(
              'Save Failed',
              `An error occured saving the file ${error.message}`,
            );
            return;
          }
          dialog.showMessageBox({
            type: 'none',
            title: 'Ganttron',
            message: 'The chart was successfully saved',
            buttons: ['OK'],
          });
        });
      });
  } else {
    fs.writeFile(quickSaveFileName, saveData, (error) => {
      if (error) {
        dialog.showErrorBox(
          'Save Failed',
          `An error occured saving the file ${error.message}`,
        );
      }
      dialog.showMessageBox({
        type: 'none',
        title: 'Ganttron',
        message: 'The chart was successfully saved',
        buttons: ['OK'],
      });
    });
  }
};

Is there a more efficient way of doing this in electron?


texts:
I have created a binary to decimal calculator that needs to follow this spec:

Arrays may not be used contain the binary digits entered by the user
Determining the decimal equivalent of a particular binary digit in the sequence must be calculated using a single mathematical function, for example the natural logarithm. It's up to you to figure out which function to use.
User can enter up to 8 binary digits in one input field
User must be notified if anything other than a 0 or 1 was entered
User views the results in a single output field containing the decimal (base 10) equivalent of the binary number that was entered
User can enter a variable number of binary digits

My code is:

binaryForm = document.getElementById('formComplete');
numberInput = document.getElementById('numberInput');
numberInputButton = document.getElementById('updateNumberBtn');
binaryInput = document.getElementById('binaryInput');
decimalValue = document.getElementById('decimalOutput');

numberInputButton.addEventListener('click', function () {
    var numberInputValue = numberInput.value;
    binaryInput.setAttribute('maxLength', numberInputValue);
});

binaryInput.addEventListener('keydown', function (e) {

    if (e.keyCode !== 48 && e.keyCode !== 49 && e.keyCode !== 13 && e.keyCode !== 8) {
        e.preventDefault();
        alert('Only 0 and 1 is allowed');
    }

});

binaryForm.addEventListener('submit', function (e) {
    e.preventDefault();

    if (binaryInput.value == 0) {
        alert('Empty');
    } else {
        var userInput = binaryInput.value;
        var total = 0;
        for (var i = 0; i < userInput.length; i++) {
            var binaryDigit = parseInt(userInput[i]);
            var calcInput = (total * 2) + binaryDigit;
            total = calcInput;
        }
        decimalValue.innerHTML = total;
    }
});
body {
    background: #2e2e2e;
    color: #fff;
    font-family: Heebo, sans-serif;
}

h1,
h2,
h3,
h4 {
    font-weight: 900;
}

input {
    display: block;
    margin: 0 auto;
    width: 100%;
    max-width: 300px;
    height: 60px;
}

.form-body {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
}

#numberInput,
#binaryInput {
    margin-bottom: 1rem;
    border: 0.125rem solid rgba(255,255,255,0.25);
    background: rgba(255,255,255,0.05);
    color: #fff;
    font-size: 2rem;
    text-align: center;
    font-family: Heebo, sans-serif;
    font-weight: 300;
}

#updateNumberBtn,
#convertBtn {
    margin-bottom: 1rem;
    border: 0.125rem solid rgba(0,128,0,0.75);
    color: #fff;
    background: rgba(0,128,0,0.75);
    text-transform: uppercase;
}

#updateNumberBtn:hover,
#convertBtn:hover {
    background: rgba(0,128,0,0.25);
    cursor: pointer;
}

Binary to Decimal Calculator

  Set max number of bits (Max 12 - Default 8)
  <input id="numberInput" type="number" value="8" min="1" max="12">
  <input id="updateNumberBtn" type="button" value="Set Number of Bits">
  <form action="" id="formComplete">
      Enter a binary value
      <input id="binaryInput" type="text" size="12" maxlength="8">
      <input id="convertBtn" type="submit" value="Convert to Decimal">
  </form>

Decimal Value:

Are there areas that I could improve performance-wise or by making the app easier to operate, such as the part where I am targeting the keys that the user can input.


texts: Check if one string is a permutation of another using Python

texts:
The code below is an attempt at a solution to an exercise from the book "Cracking the Coding Interview."

I believe that the worst case time complexity of the code below is \$O(n)\$, where n is the length of each string (they should be the same length since I am checking if there lengths are equal) and the space complexity is \$O(n)\$.

Is this correct?  In particular does checking the length of each string take \$O(1)\$ time?

def is_permutation(first_string, other_string):
    if len(first_string) != len(other_string):
        return False

    count_first = {}
    count_other = {}

    for char in first_string:
        if char in count_first.keys():
            count_first[char] += 1
        else:
            count_first[char] = 1

    for char in other_string:
        if char in count_other.keys():
            count_other[char] += 1
        else:
            count_other[char] = 1

    for char in count_first.keys():
        if char not in count_other.keys():
            return False
        elif count_first[char] != count_other[char]:
            return False

    return True


texts:
I would prefer if more experienced users could give pointers on how I can optimize and think better when writing code.

Using Homework Questions as reference, as this is a homework related question. This should fall into the second category. I know the code is working and that no memory is leaking. The implementation nor the queue.h can not be changed.

queue.h:

#define MAX_PRIO 100
typedef const char Datatyp;

#ifndef QUEUE_H
#define QUEUE_H

struct Qelement {                           // type of a queue
    struct Qelement *next;                  // pointer to next element
    int prio;                               // order in queue
    Datatyp *dataptr;                       // pointer to data
};

typedef struct Qelement *Queue;

queue.c: (This is were feedback is wanted)

// creating an empty queue
Queue new_queue ()
{
    Queue q = (Queue)malloc(sizeof(struct Qelement));
    q->next = NULL;
    q->prio = MAX_PRIO;
    q->dataptr = NULL;
    return q;
}

// adding a new element to queue based on priority
// higher priority means earlier in queue
void add (Queue q, int priority, Datatyp *d)
{
    // initiation
    Queue previous = q;
    Queue element = (Queue)malloc (sizeof(struct Qelement));
    Queue tmp = NULL;

    while (priority <= previous->prio)
    {
        if (previous->next != NULL)
        {
            tmp = previous;
            previous = previous->next;
        }
        else if (tmp != NULL)
        {
            tmp = previous;
            previous = previous->next;
            break;
        }
        else
        {
            break;
        }
    }

    element->prio = priority;
    element->dataptr = d;

    if (tmp == NULL)
    {
        element->next = NULL;
        previous->next = element;
    }
    else
    {
        element->next = previous;
        tmp->next = element;
    }
}

The code is then used along these lines. (This part can not be changed)

int main () {
    const char *daniel = "Daniel";
    const char *lisa = "Lisa";
    const char *a[] = {"Kalle", "Olle", "Eva", lisa, "Stina",
                      "Peter", "Anna", daniel, "Johan", "Maria"};

    Queue q = new_queue();
    int i;

    for (i=0; i<10; i++) {
        add(q, i%4, a[i]);
    }
}


texts: Building a list - why is this code inefficient?

texts:
I'm attempting this code challenge.

Here's my code modified to handle one simple example test case:

string = "bcdefghij"
l = string.size

result = []

permutations = string.split('').permutation.to_a

l.times do
  permutations.each {|p| result << p.sort.join}
  permutations.map! {|p| p[1..-1]}
end

puts result.uniq.sort

It produces the correct result but it's way too slow. I've played around with benchmarking and it looks like the slowest part of the code is this line:

permutations.each {|p| result << p.sort.join}

Can I speed this code up somehow? Or am I thinking about the original problem all wrong?

RESULT

Thanks to Nat's answer below I came up with this:

string = "bcdefghij".split('')
l = string.length

result = []
(1..l).each {|i| result += string.combination(i).to_a}
puts result.map{|r| r.join}.sort

Benchmarks

Before: 6.480000   0.310000   6.790000 (  6.794669)

After: 0.000000   0.000000   0.000000 (  0.003087)


texts: Using a WCF service client and handling its exceptions

texts:
I am new to WCF and need to work with another programmer's code. I am unsure of the way the WCF service client is used here:

private void barButtonDocuments_ItemClick(object sender, ItemClickEventArgs e)
{
    try
    {
        MyServiceClient myServiceClient = new MyServiceClient();

        try
        {
            documents = myServiceClient.GetDocuments();
            // More code that isn't useful including here ...
        }
        finally
        {
            try
            {
                myServiceClient.Close();
            }
            catch
            {
            }
        }
    }
    catch (FaultException<ServiceErrorDetails> error)
    {
        MessageBox.Show(error.Detail.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Is it good practice to close the proxy in a finally block, and doing so in an additional try/catch block? I personally don't like the empty catch block because it's like hiding potentially useful exceptions when trying to close the service client.

Are there any better way of handling a WCF service client?


texts: Leap year functionality in Ruby and JavaScript

texts:
I did a line-by-line translation and am wondering if the JavaScript code looks idiomatic.

Original Ruby code:

class Year
  def initialize(number)
    @number = number
  end

  def leap?
    divisible_by?(400) || ( divisible_by?(4) && !divisible_by?(100))
  end

  private
  def divisible_by?(a_number)
    @number % a_number == 0
  end
end

JavaScript Implementation looks like this:

var Year = function( number ) {
  this.number = number;
  function isLeap() {
    return isDivisibleBy(400) || ( isDivisibleBy(4) && !isDivisibleBy(100));
  }
  function isDivisibleBy(a_number) {
    return this.number % a_number == 0
  }
  return isLeap();
}


texts:
I'm starting to code in the OOP way, but I have doubts with the following example.
I have a Product entity and I want to import & create instances of this entity from a CSV file.
I load the CSV file into an array in another part of the code, then I pass the array with the data to CSVImport class.

class Product
{
    private $id;

    private $name;

    private $price;

    private $stock;

    private $imageUrl;

    public function __construct() {}

    /** Getters & setters */
}

class CSVImport extends ProductImport
{
    private $websiteUrl;

    public function __construct($websiteUrl)
    {
        $this->websiteUrl = $websiteUrl;
    }

    public function import($csvData)
    {
        $productCollection = new ProductCollection();

        foreach ($csvData as $rowData) {
            $product = $this->parseProductData($rowData);
            $productCollection->addProduct($product);
        }

        return $productCollection;
    }

    private function parseProductData($productData)
    {
        $product = new Product();

        list(
            $id,
            $name,
            $price,
            $stock,
            $imagePath
        ) = $productData;

        $product
            ->setId($id)
            ->setName($name)
            ->setPrice($price)
            ->setStock($stock)
            ->setImageUrl($this->websiteUrl.$imagePath);

        return $product;
    }
}

My questions are:

Is it correct to pass an array of data to CSVImport class? Or should it take the responsability to read & load the CSV file?
Who should take care of data validation, Product setters, CSVImport class or a new class? And how can I manage validation errors?
In case I need to transform the source data, as I've done with imageUrl, is the correct place to do it?


texts: Why does caching of string objects perform faster?

texts:
I'm trying to implement String-Pool. I'm maintaining a HashMap<String,String> to store the keys.

public class TestStringCaching {
    static Map < String, String > cache = new HashMap < String, String > ();
    public static void main(String[] args) {
        int iter = 8000000;
        String[] temp = new String[iter];
        long st1 = System.currentTimeMillis();
        for (int i = 0; i < iter; i++) {
            temp[i] = generateString();
        }
        System.out.println(System.currentTimeMillis() - st1);
        st1 = System.currentTimeMillis();
        for (int i = 0; i < iter; i++) {
            temp[i] = generateString1();
        }
        System.out.println(System.currentTimeMillis() - st1);
        System.gc();
    }

    private static String generateString() {
        return new String("abc");
    }

    private static String generateString1() {
        String str = new String("abc");
        if (cache.containsKey(str))
            return cache.get(str);
        else {
            cache.put(str, str);
            return cache.get(str);
        }

    }

}

In both of the cases getString() and getString1() same number of string objects are created. But fetching from the map/cache is blistering fast compared to normal creation of String.

Why is that happening ?


texts:
I wrote a simple Zoopla real estate scraper for just practicing what I learned so far in Python, Requests, BeautifulSoup and overall web scraping fundamentals. By looking at my code I feel like there would be a better and more elegant way to write it but unfortunately as a beginner I don't know yet. So, I believe I should let experienced guys here at Stack Exchange to review my code for enhancement.
import requests
import json
import csv
import time
from bs4 import BeautifulSoup as bs

class ZooplaScraper:

    results = []

def fetch(self, url):
    print(f'HTTP GET request to URL: {url}', end='')
    res = requests.get(url)
    print(f' | Status code: {res.status_code}')

    return res

def parse(self, html):
    content = bs(html, 'html.parser')
    content_array = content.select('script[id="__NEXT_DATA__"]')
    content_dict = json.loads(content_array[0].string)
    content_details = content_dict['props']['initialProps']['pageProps']['regularListingsFormatted']

    for listing in content_details:
        self.results.append ({
            'listing_id': listing['listingId'],
            'name_title': listing['title'],
            'names': listing['branch']['name'],
            'addresses': listing['address'],
            'agent': 'https://zoopla.co.uk' + listing['branch']['branchDetailsUri'],
            'phone_no': listing['branch']['phone'],
            'picture': listing['image']['src'],
            'prices': listing['price'],
            'Listed_on': listing['publishedOn'],
            'listing_detail_link': 'https://zoopla.co.uk' + listing['listingUris']['detail']

        })

def to_csv(self):

    with open('zoopla.csv', 'w') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=self.results[0].keys())
        writer.writeheader()

        for row in self.results:
            writer.writerow(row)

        print('Stored results to "zoopla.csv"')

def run(self):

    for page in range(1, 5):
        url = 'https://www.zoopla.co.uk/for-sale/property/london/?page_size=25&q=London&radius=0&results_sort=newest_listings&pn='
        url += str(page)
        res = self.fetch(url)
        self.parse(res.text)
        time.sleep(2)
    self.to_csv()

  if __name__ == '__main__':
     scraper = ZooplaScraper()
     scraper.run()

Basically in this scraper I mostly did is JSON parsing. Problem was all the data on the website was coming from JavaScript under the script tag so I have to select that tag and then pass it to json.loads() and parse the JSON dict to find the right key-value pair.


texts:
I have implemented a producer consumer problem,
following the resources below:

Oracle doc
CSEE

I have used mutex_t and sem_t.  The reason for using mutex_t instead of binary semaphore because of my understanding- mentioned here.

And hence I have avoided using sem_t as binary.

Also the Oracle doc link I have provided uses two mutexes, sem_t & cmut, whereas I have used only one mutex_t object as suggested in the CSEE link provided.

Is it OK?  Please review my code and provide your valuable comments.

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

#define MAX 10

typedef struct{
    char buff[MAX];
    int in;
    int out;
    int count;
    pthread_mutex_t mutex;
    sem_t empty;
    sem_t full;
}BUFFER;

BUFFER queue;
char substring[5];

void initializeBuffer(BUFFER* b)
{
    b->count = 0;
    b->in    = 0;
    b->out   = 0;

    pthread_mutex_init(&(b->mutex),NULL);
    sem_init(&(b->full),0,0);
    sem_init(&(b->empty),0,MAX);
}

void destroyBuffer(BUFFER* b)
{
    b->count = 0;
    b->in    = 0;
    b->out   = 0;

    pthread_mutex_destroy(&(b->mutex));
    sem_destroy(&(b->full));
    sem_destroy(&(b->empty));
}

void producer(BUFFER* b,char c)
{
    sem_wait(&(b->empty));
    pthread_mutex_lock(&(b->mutex));

    b->buff[b->in]=c;
    (b->in)++;
    (b->in) %= MAX;
    (b->count)++;

    pthread_mutex_unlock(&(b->mutex));
    sem_post(&(b->full));
}

char consumer(BUFFER* b)
{
    sem_wait(&(b->full));
    pthread_mutex_lock(&(b->mutex));

    char val=(b->buff[b->out]);
    (b->out)++;
    (b->out) %= MAX;
    (b->count)--;

    pthread_mutex_lock(&(b->mutex));
    sem_post(&(b->empty));
    return val;
}

void* THREAD_PRODUCER(void* arg)
{
    char array[]="HelloWorld";
    int i=0;
    printf("Producer Thread Created\n");
    while(array[i] != '\0')
    {
        producer(&queue,array[i]);
        i++;
    }
    pthread_exit((void*) 1);
}

void* THREAD_CONSUMER(void* arg)
{
    int i=0;
    printf("Consumer Thread Created\n");
    for(i=0;i<5;i++)
    {
        substring[i]=consumer(&queue);
    }
    pthread_exit((void*) 1);
}

int main()
{
    pthread_t T1,T2;
    initializeBuffer(&queue);
    pthread_create(&T1,NULL,THREAD_PRODUCER,NULL);
    pthread_create(&T2,NULL,THREAD_CONSUMER,NULL);
    pthread_join(T1,NULL);
    pthread_join(T2,NULL);
    printf("Inside queue: %c\n",queue.buff[queue.out]);
    printf("substring: %s\n",substring);
    destroyBuffer(&queue);
    return 0;
}

The output is:

$ ./ProducerConsumer.exe
Producer Thread Created
Consumer Thread Created
Inside queue: W
substring: Hello


texts:
Is there a better way than this to copy the values from source to destination when the blocks of memory you want to copy to and from are different sizes? Also considering you have no control over making sure the sizes match to begin with.

while (count--) {
   memcpy(dst, src, dst_stride);
   src += src_stride;
   dst += dst_stride;
}


texts:
I have the following code, to store a web service name value pair response into DB. I am saving it in xml column of DB. Kindly highlight the issues with this approach. Please note that the name value pair (i.e response.details) array is dynamic and i cannot directly map it to individual db columns.

XElement ex = new XElement("ServiceResponse","");
        for (int i = 0; i < response.details.Length; i++)
        {
            string Name = Regex.Replace(response.details[i].name.Trim(),@"[^A-Za-z0-9.]+","");
            ex.Add(new XElement("Details",new XElement(Name, response.details[i].value)));
        }
using (DBDataContext con = new DBDataContext())
        {
            con.Requests.InsertOnSubmit(new Nettium.FraudManagementBase.DataContext.Request
            {
                response = ex
            }
                );
            con.SubmitChanges();
        }

Thanks


texts: Preventing duplicate submission in Rails

texts:
I have a Rails app where doctors score patients on diagnosis - their score is the model Baseline. Each Baseline has a user id and a patient id and there should only be one baseline for each patient by a user. Very occasionally I have noticed that a user may create a new baseline (at which point he is then redirected to another page) but then presses the back button, be brought to the "new" action again and if he submits again, a duplicate baseline is created. Therefore I am writing some code to try to ensure this never happens.

First, I check that a baseline doesn't already exist with the current user id and the patient id at the controller "new" action.

     before_action :check_there_is_not_an_existing_baseline, only: [:new ]

and

 def check_there_is_not_an_existing_baseline
   patient =  Patient.find(params[:patient])
   @baseline = Baseline.where(user_id: current_user.id, patient_id: patient.id).first
    if @baseline
     flash[:notice] = "There was a problem with this action. Refresh the page and try again!"
     redirect_to list_patients_path(:page =>  @current_page)
    end
 end

I also check at the create action in the model

 validate :duplicate_baselines, :on => :create

  def duplicate_baselines
     check_baseline = Baseline.where(user_id: self.user_id, patient_id: self.patient_id)
     if !check_baseline.blank?
        errors.add(:base, "There was an error. Go to 'patient list' and start again") unless check_baseline.first.new_record?
     end
  end

I am trying to learn more and my suspicion is that there is good Rails way to do this. Could an expert have a look and see if there is a neater solution?


texts:
I have a MvvM application that is working very fine. However I am not sure if I'm writing a clean code, especially the part handling child windows with their controller.

So to begin, i have this structure that helps me delegate methods to the controllers to open child windows when needed :

public struct ShowActions
{
    public readonly Action Show;
    public readonly Action ShowDialog;

    public ShowActions(Action show, Action showDialog)
    {
        this.Show = show;
        this.ShowDialog = showDialog;
    }
}

In the MainController class, I have a WindowServiceProvider property that is just a dictionary linking a type of Controller to a ShowActions structure :

public Dictionary<Type, ShowActions> WindowServiceProvider { get; set; }

The main window intializes the child windows like this :

public MainWindow()
    {
        InitializeComponent();
        var mainController = new MainController();
        this.DataContext = mainController;

        var authenticationController = new AuthenticationController(mainController);
        var modelController = new ModelController(mainController);

        AuthenticationWindow authenticationWindow = null;
        NewModelWindow modelWindow = null;

        mainController.WindowServiceProvider.Add(typeof(AuthenticationController), new ShowActions(null, () =>
        {
            authenticationWindow = new AuthenticationWindow(authenticationController)
            {
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this
            };
            authenticationController.Password = () => authenticationWindow.PasswordBox.Password;
            authenticationWindow.ShowDialog();
        }));

        mainController.WindowServiceProvider.Add(typeof(ModelController), new ShowActions(null, () =>
        {
            modelWindow = new NewModelWindow(modelController)
            {
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this
            };
            modelWindow.ShowDialog();
        }));
    }

Is this a good way to code ? I fill like it may be a bit heavy for what it's doing.
And also, is it bad to have many controllers when one can handle everything ?


texts: Project Euler # 44 Pentagon numbers in Python

texts:
Pentagonal numbers are generated by the formula, \$P_n=\frac{n(3n−1)}{2}\$. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145
It can be seen that \$P_4 + P_7 = 22 + 70 = 92 = P_8\$. However, their difference, \$70 − 22 = 48\$, is not pentagonal.
Find the pair of pentagonal numbers, \$P_j\$ and \$P_k\$, for which their sum and difference are pentagonal and \$D = |P_k − P_j|\$ is minimised; what is the value of D?

Awaiting feedback.
from time import time

def generate_pentagons(n):
    """generates next n pentagons"""
    pentagons = (num * (3 * num - 1) // 2 for num in range(1, n))
    for i in range(n - 1):
        yield next(pentagons)

def get_pentagons(n):
    """Assumes n is a range > 0.
    generates pentagons that obey to the + - rules."""
    pentagons = set(generate_pentagons(n))
    for pentagon1 in pentagons:
        for pentagon2 in pentagons:
            if pentagon1 + pentagon2 in pentagons and abs(pentagon1 - pentagon2) in pentagons:
                return pentagon1, pentagon2

if __name__ == '__main__':
    start_time = time()
    pent1, pent2 = get_pentagons(10000)
    print(abs(pent1 - pent2))
    print(f'Time: {time() - start_time} seconds.')


texts:
Learn You a Haskell demonstrates the break function:

  breaks it when the predicate is first true.

Example:

-- ghci> break (==4) [1,2,3,4,5,6,7]
-- ([1,2,3],[4,5,6,7])

Here's my code:

break' :: (a -> Bool) -> [a] -> ([a], [a])
break' _ [] = ([], [])
break' f ys = break'' f ys []
               where break'' _ [] acc = (reverse acc, [])
                     break'' g xxs@(x:xs) acc
                        | g x       = (reverse acc, xxs)
                        | otherwise = break'' g xs (x:acc)

I used the reverse rather than use the ++ function due to @Anonymous's helpful advice on my implementation of lines.

Please review it.


texts: Computing max t such that tanh(pi*sinh(t)/2) <1

texts:
I'm looking for a way to quickly determine that maximum value of t such that tanh(pi/2 sinh(t)) is strictly less than 1, for a given precision.

I have reproduced the code I am currently using to do this below:

#include <cmath>
#include <iostream>
#include <random>
#include <boost/math/special_functions/next.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/float128.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>
#include <benchmark/benchmark.h>

using std::tanh;
using std::sinh;
using std::asinh;
using std::atanh;
using std::isnormal;
using boost::math::float_prior;
using boost::math::constants::half_pi;
using boost::math::constants::two_div_pi;
using boost::multiprecision::float128;
using boost::multiprecision::cpp_bin_float_50;
using boost::multiprecision::cpp_bin_float_100;

template<class Real>
Real g(Real t)
{
    Real tmp = half_pi<Real>()*sinh(t);
    return tanh(tmp);
}

template<class Real>
Real g_inv(Real x)
{
    return asinh(two_div_pi<Real>()*atanh(x));
}

template<class Real>
Real find_max_t()
{
    Real x = float_prior((Real) 1);
    Real t_max = g_inv(x);
    while(!isnormal(t_max))
    {
        x = float_prior(x);
        t_max = g_inv(x);
    }
    // This occurs once on 100 digit arithmetic:
    while(!(g(t_max) < (Real) 1))
    {
        x = float_prior(x);
        t_max = g_inv(x);
    }
    return t_max;
}

template<class Real>
static void BM_max_t(benchmark::State& state)
{
    Real t_max;
    while(state.KeepRunning())
    {
        benchmark::DoNotOptimize(t_max = find_max_t<Real>());
    }
    std::cout << "t_max = " << t_max << std::endl;
}

BENCHMARK_TEMPLATE(BM_max_t, float);
BENCHMARK_TEMPLATE(BM_max_t, double);
BENCHMARK_TEMPLATE(BM_max_t, long double);
BENCHMARK_TEMPLATE(BM_max_t, float128);
BENCHMARK_TEMPLATE(BM_max_t, cpp_bin_float_50);
BENCHMARK_TEMPLATE(BM_max_t, cpp_bin_float_100);

BENCHMARK_MAIN();

The build sequence is:

INC = -I/path/to/boost
all: perf.x

perf.x: perf.o
    g++ -o $@ $< -lbenchmark -pthread -lquadmath

perf.o: perf.cpp
    g++ --std=c++14 -fext-numeric-literals -Wfatal-errors -g -O3 $(INC) -c $< -o $@

This computes the correct value of t_max in 153 ns (float), 214 ns (double), 246 ns (long double),  5280 ns (float128), 53us (cpp_bin_float_50), and 455 us (cpp_bin_float_100).

How can this code be made faster? For reference, at double precision, I have found 30% of the time is spent calling __expm1, 24% calling __ieee754_log_avx, and 15% calling __asinh.


texts:
I've created a simple little class called JSONSelector to be able to select relevant data from a JSON object (a dict in Python). Here's what I have so far - it's based off of a few SQL statements, NumPy methods, and JavaScript iterating methods:

class JSONSelector:
    def __init__(self, json):
        self.json = json

    def __str__(self):
        return "{}({})".format(type(self).__name__, str(self.json))
    __repr__ = __str__

    def select(self, selectors):
        if selectors == "*":
            return type(self)(self.json)
        else:
            temp = {}
            for sel in selectors:
                temp[sel] = self.json.get(sel, None)
            return type(self)(temp)

    def where(self, cond):
        temp = {}
        for key, value in self.json.items():
            if cond(key, value):
                temp[key] = value
        return type(self)(temp)

    def astype(self, type_):
        temp = {}
        for key, value in self.json.items():
            temp[key] = type_(value)
        return JSONSelector(temp)

    def sort(self, **kwargs):
        return type(self)(dict(sorted(self.json.items(), **kwargs)))

    def foreach(self, func):
        for key, value in self.json.items():
            if func(key, value) == False: break

    def print(self, func=None):
        if not func:
            print(self)
            return
        else:
            print(func(self))
            return

Here's a test case with an explanation:

a = JSONSelector({
    "stuff": 5,
    "seeded": 6,
    "number": "7",
    "more_stuff": 8
})

a.select("*") \  # Select all entries from the dict
    .where(lambda key,value: type(value) is int) \ # Where the value is an integer
    .sort(key=lambda x: x[1]) \ # Sort by the value
    .astype(str) \ # Convert the values to type str
    .foreach(lambda key, value: print(key + ": " + value)) # Loop over all entries

I'd like to know if any of my code is redundant, where I can shorten things up, and if anything is incorrect. Thank you in advance!


texts: Retrieving the nth term of an infinite stream

texts:
I recently learned how generators can be infinite in Python. For example, the infinite sequence can be the triangular numbers:
$$1, 3, 6, 10,...$$

def triangle_stream():
    """ Infinite stream of triangle numbers. """
    x = step = 1
    yield x
    while True:
        step += 1
        x += step
        yield x

I wrote a function that returns the nth term in an infinite sequence.

def nth_term(generator, n):
    """ Returns the nth term of an infinite generator. """
    for i, x in enumerate(generator()):
        if i == n - 1:
            return x

As an example:

>>> nth_term(triangle_stream, 10)
55

But this nth_term function also works:

def nth_term(generator, n):
    """ Returns the nth term of an infinite generator. """
    x = generator()
    for i in range(n - 1):
        next(x)
    return next(x)

Which of these two nth_term functions is more efficient?


texts:
The core problem is simple enough, but I've developed a type system that I'm not sure about.  The intention is, if the result is a number, calling num $ fizzBuzz 16, for example, lets me retrieve 16 as an Int.  However, it seems awfully repetitive, to have to mention "Fizz" so many times in the code.  Can it be done better?

data NoiseNum = Fizz | Buzz | FizzBuzz | Num Int
  deriving (Eq)

instance Show NoiseNum where
  show FizzBuzz = "FizzBuzz"
  show Fizz     = "Fizz"
  show Buzz     = "Buzz"
  show (Num n)  = show n

num :: NoiseNum -> Int
num (Num n) = n

fizzBuzz :: Int -> NoiseNum
fizzBuzz n
  | n `mod` 15 == 0 = FizzBuzz
  | n `mod`  3 == 0 = Fizz
  | n `mod`  5 == 0 = Buzz
  | otherwise       = Num n

main = do
  mapM_ putStrLn $ map (show . fizzBuzz) [1..100]


texts:
While answering this question, I wanted to use a generic sum of Collection function.  Java doesn't have a native method, so I wrote one.  There are a couple things I don't like about it though, so I wrote a more specific method for my answer.

public static <T extends Number, U extends Collection<T>> BigInteger sum(U numbers) {
    BigInteger sum = BigInteger.ZERO;

    for ( T number : numbers ) {
        sum = sum.add(new BigInteger(number.toString()));
    }

    return sum;
}

The first problem of course is that this wouldn't work for all Number types.  In particular, Float, Double, and BigDecimal are not guaranteed to fit in an integer type.  That's easy enough to fix:

public static <T extends Number, U extends Collection<T>> BigDecimal sum(U numbers) {
    BigDecimal sum = BigDecimal.ZERO;

    for ( T number : numbers ) {
        sum = sum.add(new BigDecimal(number.toString()));
    }

    return sum;
}

Now the problem is that it switches from an integer type to a decimal type.  So we have to convert it back if we really preferred an integer type.

I'm also not happy with converting to and from a String to convert it to a BigDecimal.  They're all numeric types.  Why add this intermediate step?  Unfortunately, String is the only interoperable type.  All the Number types have a toString method, and BigDecimal has a constructor from a String.

Overall, this may be more hacky than useful.  Does anyone have an alternative version that works better?  Or should I stick with writing a custom method each time the issue arises?  Or am I being too hard on this version?


texts: Getting employee details according to the role

texts:
Here is my issue.I have two classes:

public class Role
{
  public string RoleTitle { get; set; }
  public string Office { get; set; }
  public string Department { get; set; }
}

And

public class Employe
{
  public string Name { get; set; }
  public List<Role> Roles { get; set; }
}

As you can see, class Employee contains ListRoles as a property.I have one method that process some share point list and returns one Employee object with all of his roles, something like this:

John Johnson

Regular Office1 Department2
Regular Office2 Department1
Manager Office1 Department3
OfficeDirector Office1 Departmnet4 etc.

As you can see one employee can have lot of different roles and lot of same roles but for different office/department (OK, I know that this is not real life situation, I'm just using this as an example). Now I'm using this Role information to process another SP List to get more information that I need to display.Roles are very important, because queries are based on them, what employee can see or not.Also, office and department are crucial information because rules for roles are also based on them.

My current code looks like this, I'm going through foreach loop and for each role, which I determine on RoleTitle, I create query, which will be added to final query (using OR).

public void GetEmployeeInformation(Employee emp)
{
    query = string.Empty;
    List<string> queries = new List<string>();
    foreach (Role role in emp.Roles)
    {
        switch (role.RoleTitle)
        {
            case ("Regular"):
                {
                    query = CamlQuery(role.Office, role.Department, "Office", "Department", "Choice");
                    break;
                    }

                case ("Manager"):
                    {
                        query = CamlQuery("Department", role.Department);
                        break;
                    }
                case ("OfficeDirector"):
                    {
                        query = CamlQuery("Office", role.Offices);
                        break;
                    }
                case ("Admin"):
                    {
                        query = CamlQuery("some implementation")
                        break;
                    }
            }
            queries.Add(query);
        }
//further implementation of method

    }

Everything is working fine, I got right results, but I'm wondering is there any chance that I can optimize code, because, for example, if I have 5 regular roles for each one it will go through the loop.

Another idea I got is to make changes in Role class, and create ListOffices, and ListDepartments so when I query in first method, I will get, for each different role, something like this

Manager:

Office1 Department1
Office2 Department2
Office3 Department3

Now, I will have only one Role object for every role with all office/department information inside, and I can go through foreach and inside Camlquery use one recursive method that will process all offices/departments for that role and create final query.The recursive method I've created is based on indexes of elements inside the lists, because when I create query I know that for first Manager role office/department pair is on [0] position in the list.But I've been told that using indexes in situation like this are very bad practice, so I've been stucked with this idea.

Do you have any idea how can I optimize this code by avoiding going through foreach loop for every single role and not using this approach with Lists and indexes?


texts: C# Convert BLOB to jpg, resize, then back to BLOB

texts:
I am trying to convert a BLOB that is stored in a database to a JPG and then I need to display it on an html form in a C# application.
A little backstory first - this is an older web app that was designed to take a JPG (photo) that was stored as a path in the database, resize it, then show as a BLOB. This functionality needs to stay in place, but now one of the systems is changing and the photo is going to be stored in the database as a BLOB instead of a path to a photo (\servername\images\xyz.jpg).
One system still needs the image to be resized then sent back as a BLOB to display. The other systems that call this web-app will need the BLOB converted to a JPG to display.
The code below works, but I think it might have put an unnecessary load on the server, because this morning the system was laggy and some features were impossible to use. I have a feeling that the .Save is the troublemaker here since I am calling it twice. I know the image doesn't need to be saved anywhere physically, as long as the web-app can call and have it display to the site. Is there anything I can change here to skip saving an image on the server and just display it so it doesn't use up a ton of resources?
protected void Page_Load(object sender, EventArgs e)
{
   byte[] byteImage = null;
    string ID = Request.QueryString["id"];
    string imageFile = "\\\\server\\c$\\inetpub\\wwwroot\\web-app\\images\\" + ID+ ".jpg";
    string server = Request.ServerVariables["server_name"];
    var serverNameList = db.Servers.Select(x => x.ServerName).ToList();

    connection.Open();
    SqlCommand sqlCommand = new SqlCommand("sp", connection);
    sqlCommand.Parameters.Add("@ID", SqlDbType.VarChar);
    sqlCommand.Parameters["@ID"].Value = ID;
    sqlCommand.CommandType = CommandType.StoredProcedure;
    SqlDataReader dr = sqlCommand.ExecuteReader();

    while (dr.Read())
    {
        byteImage = (byte[])dr["BLOB"];
    }

    if (byteImage != null)
    {
        using (MemoryStream ms = new MemoryStream(byteImage))
        {
            //saving to jpg image
            Image img = new Bitmap(ms);
            img.Save(imageFile, ImageFormat.Jpeg);

            Response.Clear();
            Response.CacheControl = "public";
            Response.Cache.SetExpires(DateTime.Now.AddDays(1.0));
            Response.ContentType = "Image/jpeg";

            if (serverNameList.Contains(server)) // if user is coming from a specific server, resize the image then send back
            {
                byte[] resizedImage = GetResizedImage(imageFile, 300, 400);
                Response.OutputStream.Write(resizedImage, 0, resizedImage.Length);
            }
            else // skip resize and show image as jpg
            {
                Response.BinaryWrite(byteImage);
            }
        }
    }
    else // image is null
    {
        imageFile = HttpRuntime.AppDomainAppPath + "PERSON.GIF";
    }
}

private byte[] GetResizedImage(string path, int width, int height)
{
    Bitmap bitmap1 = new Bitmap(path);
    double height1 = bitmap1.Height;
    double width1 = bitmap1.Width;
    double num = 1.0;
    if (width > 0)
        num = width / width1;
    else if (height > 0)
    num = height / height1;
    MemoryStream memoryStream = new MemoryStream();
    Bitmap bitmap2 = new Bitmap((int)(width1 * num), (int)(height1 * num));
    bitmap2.SetResolution(150f, 150f);
    Graphics graphics = Graphics.FromImage(bitmap2);
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.Clear(Color.White);
    graphics.DrawImage(bitmap1, new Rectangle(0, 0, (int)(num * width1), (int)(num * height1)), new Rectangle(0, 0, (int)width1, (int)height1), GraphicsUnit.Pixel);
    bitmap2.Save(memoryStream, ImageFormat.Jpeg);
    return memoryStream.ToArray();
}


texts:
Context

My aim is to write an RSS parser that can handle extensions in a generic and type-safe way. I already have a working RSS parser, the missing part is the extensions handling, which is the focus of this review.

By extension, I mean extra XML elements that aren't part of the RSS specification, usually in a dedicated namespace like the Dublin Core Metadata Set.

I'm interested in a type-safe implementation that doesn't sacrifice usability/readability too much. Performance isn't a concern for now, correctness prevails.

Current implementation

{-# LANGUAGE DataKinds           #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE FlexibleInstances   #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE TypeOperators       #-}
import           Control.Exception.Safe        -- from 'safe-exceptions' library
import           Data.Conduit                  -- from 'conduit' library
import           Data.Singletons.Prelude.List  -- from 'singletons' library
import           Data.Extensible.Class         -- from 'extensible' library
import           Data.Extensible.Product       -- from 'extensible' library
import           Data.XML.Types                -- from 'xml-types' library

-- Structure for RSS item
--
-- In place of 'e', I will be using a list of proxy types,
-- in other words: 'e :: [*]'
data RssItem e = RssItem
  { someField1 :: Text
  , someField2 :: Text
  -- (...)
  , itemExtensions :: RssItemExtension e
  }

-- Open type family to associate proxy types to data types, for extensions
data family RssItemExtension :: * -> *
data instance RssItemExtension () = NoRssItemExtension
data instance RssItemExtension (Sing (a :: [*])) = SomeRssItemExtension { rssItemExtension :: RssItemExtension :* a }

-- Typeclass to associate a parsing function to an extension proxy type
class ParseRssExtension a where
  parseRssItemExtension :: MonadCatch m => ConduitM Event o m (RssItemExtension a)

instance ParseRssExtension () where
  parseRssItemExtension = pure NoRssItemExtension

instance ParseRssExtension (Sing ('[] :: [*])) where
  parseRssItemExtension = pure (SomeRssItemExtension nil)

instance (ParseRssExtension a, ParseRssExtension (Sing b)) => ParseRssExtension (Sing (a ': b)) where
  parseRssItemExtension = fmap SomeRssItemExtension $ getZipConduit $ (<:)
    <$> ZipConduit parseRssItemExtension
    <*> ZipConduit (rssItemExtension <$> parseRssItemExtension)

Example usage

Below is an example implementation of Dublin Core Metadata Set extension:

-- Proxy type to represent the extension
data DublinCore :: *

-- Associate proxy type to data type
data instance RssItemExtension DublinCore = DublinCoreItem { {- (...) -} }

-- Associate parser to proxy type
instance ParseRssExtension DublinCore where
  parseRssItemExtension    = _ -- Some function to parse a DublinCoreItem


texts: Return the indexs of two numbers that total a given number

texts:
I attempted an online Python test the other day. The function I wrote works fine however takes too long to complete.
Question:

From a list of numbers find the indexes of two numbers that total n and return as a tuple.

I tried using itertools but I don't know if there is a function that would out perform my original. I thought itertools.combinations may be able to.
Any suggestions as the best way to tackle this problem?
import numpy as np
from itertools import combinations

numbers = np.random.randint(1, 100, 1000000)

# used to time function run time
def timer_func(orig):
    import time
    def wrapper_func(*args):
        t1 = time.time()
        result = orig(*args)
        t2 = time.time() - t1
        print(f"{orig.__name__} ran in {t2}")
        return result

    return wrapper_func

# new combination test
@timer_func
def find_two_sum(numbers, target_sum):
    """
    :param numbers: (list of ints) The list of numbers.
    :param target_sum: (int) The required target sum.
    :returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum
    """
    for perm in combinations(numbers, 2):
        if sum(perm) == target_sum:
            first = np.where(numbers == perm[0])
            second = np.where(numbers == perm[1])
            return (first[0][0], second[0][0])

# original function
@timer_func
def find_two_sum_original(numbers, target_sum):
    """
    :param numbers: (list of ints) The list of numbers.
    :param target_sum: (int) The required target sum.
    :returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum
    """
    for i, x in enumerate(numbers):
        for ii, y in enumerate(numbers):
            if i != ii and x + y == target_sum:
                return (i, ii)

if __name__ == "__main__":
    print(find_two_sum(numbers, 25))
    print(find_two_sum_original(numbers, 25))

find_two_sum ran in 1.341470718383789
(2, 307)
find_two_sum_original ran in 1.0022737979888916
(2, 307)


texts:
I just started trying out SVG the other day. Eventually I hope to be able to know how to do what SE does with their reputation graphs.

For now, I've just been trying to set up an easier way to make lines. I think my below code is decent, but please let me know what I can improve on or what I'm doing poorly.

Would like your thoughts before I start adding like animations, creativity, data to it.

Demo  http://jsfiddle.net/ECKNh/

var Line = {};

Line.LINES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

var SVGline = function (l) {
    this.l = l;
}

for (var i = Line.LINES.length; i > -1; i -= 1) {
    Line[Line.LINES[i]] = new SVGline(Line.LINES[i]);
}

SVGline.prototype.createline = function (x1, y1, x2, y2, color, w) {
    var aLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    aLine.setAttribute('x1', x1);
    aLine.setAttribute('y1', y1);
    aLine.setAttribute('x2', x2);
    aLine.setAttribute('y2', y2);
    aLine.setAttribute('stroke', color);
    aLine.setAttribute('stroke-width', w);
    return aLine;
}

function start() {
    var aSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    aSvg.setAttribute('width', 1000);
    aSvg.setAttribute('height', 400);
    var w = document.getElementById('container');

    for (var i = 1; i < 11; i += 1) {
        var x1 = Math.floor(Math.random() * 500 / 2);
        var xx = Line[i].createline(x1, 0, 200, 300, 'rgb(0,0,' + x1 + ')', i);
        aSvg.appendChild(xx);
    }
    w.appendChild(aSvg);
}

start();


texts: Http Request response time within C# application

texts:
I have this method :

private string GetCheckResultFor(string url)
        {
            Stopwatch reveil = new Stopwatch();
            reveil.Start();
            HttpWebResponse response = null;
            url = Regex.Replace(url, @"\s+", "");
            if (!url.StartsWith("http") && !url.StartsWith("https")) url = "http://" + url;
            string res = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "GET";
                response = (HttpWebResponse)request.GetResponse();
                if (response.ResponseUri.ToString() == url) res = "No Action";
                else res = "Redirect to " + response.ResponseUri.ToString();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    response = (HttpWebResponse)e.Response;
                    res = "Errorcode: " + (int)response.StatusCode;
                }
                else
                {
                    res = "Error: " + e.Status;
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }

            }
            reveil.Stop();
            Debug.WriteLine("For this url : " + url + " = " + reveil.ElapsedMilliseconds + " ms");
            return res;
        }

It takes between 200 and 700 ms. I know it depends on internet connection speed but I need to improve it because I only need the reponse url. I have Three possiblities :

Reponse Url = request Url ==> No action
Redirect to another url
Request Error

So How can I edit this snippet to reduce method response time ?


texts:
I'm working on an iOS app which handles API request based on authentication. Authentication is done through OAuth and every API request is sent along with access_token. In certain cases, the access_token might be expired causing the API request to fail. I would need to call the refresh_token method to refresh the access_token followed by the API request. I have used NotificationCenter to handle callbacks. Are there better ways to handle this using closures or something else?

class DeviceInfo {

    func generateRefreshToken(callbackNotifier : String) -> Void {

        Alamofire.request(DeviceAPIRequest.GEN_REFRESH_TOKEN(refreshToken)).responseJSON {

            (request, response, results, error) -> Void in
            if (error == nil) {

                let jsonResponse = JSON(results!)
                self.accessToken = jsonResponse["access_token"].stringValue
                self.refreshToken = jsonResponse["refresh_token"].stringValue
                let refreshStatus = NSDictionary(object: "success", forKey: "status")

                NSNotificationCenter.defaultCenter().postNotificationName(callbackNotifier, object: self, userInfo: refreshStatus)

            } else {
                let refreshStatus = NSDictionary(object: "failed", forKey: "status")
                NSNotificationCenter.defaultCenter().postNotificationName(callbackNotifier, object: self, userInfo: refreshStatus)
            }
        }
    }

}

and

class UserAPI {

    func getUsers() -> Void {

        let tokenType:String = deviceInfo.tokenType
        let accessToken:String = deviceInfo.accessToken

        Alamofire.request(UserAPIRequest.GET_USER_PARTITION(tokenType, accessToken)).responseJSON() {

            (request, response, results, error) in

            if (error == nil) {

                // sucessfull in getting users...

            } else {

                // possible chances are access_token is expired.
                if response?.statusCode == 403 {
                    self.deviceInfo.generateRefreshToken("getUsers")
                } else {
                    DDLogError("Error while processing getUsers() : \(error)")
                }
            }
        }
    }
}


texts:
I Needed a method to randomly sample an IEnumerable collection without replacement. I'm using this for writing behavioral acceptance tests.

For example, in the test code, I write:
GetElements("#SearchResults > li").Sample(3);

Here's the how I implemented it:

I welcome any feedback or optimizations!

    /// <summary>
    ///  returns a random sample of the elements in an IEnumerable
    /// </summary>
    public static IEnumerable<T> Sample<T>(this IEnumerable<T> population, int sampleSize)
    {
        List<T> localPopulation = population.ToList();
        if (localPopulation.Count() < sample.size) return localPopulation;

        List<T> sample = new List<T>(sampleSize);

        Random random = new Random();
        while(sample.Count < sampleSize)
        {
            int i = random.Next(0, localPopulation.Count);
            sample.Add(localPopulation[i]);
            localPopulation.RemoveAt(i);
        }

        return sample;
    }


texts: Compare two Excel sheets by Cell Content

texts:
This code is a result of a lot of help from this community.
What does it do?
It compares two excel sheets cell by cell and copies the differences into another excel file.

I’m trying to modify the Code so it does the following:

It goes to “Name” and then searches for that name is the other file. If it doesn’t find the file it just copies that entire row including all the columns to the report file (file that is created)
In case it does find the name, then it compares all the columns of that row and if something different it shows the difference in report with color red.

The pictures below show what I'm trying to achieve with this code

Sheet1

Sheet2

Report

Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet)
  Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer
  Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String
  Dim Report As Workbook, difference As Long
  Dim row As Long, col As Integer
  Dim Arr1 As Variant, Arr2 As Variant, Arr3 As Variant, Rng As Range
  Dim tm As Double
  tm = Timer

  'Application.ScreenUpdating = False
  'Application.Calculation = xlCalculationManual
  'Application.EnableEvents = False

  With ws1.UsedRange
    ws1row = .Rows.Count
    ws1col = .Columns.Count
  End With

  With ws2.UsedRange
    ws2row = .Rows.Count
    ws2col = .Columns.Count
  End With

  maxrow = ws1row
  maxcol = ws1col
  If maxrow < ws2row Then maxrow = ws2row
  If maxcol < ws2col Then maxcol = ws2col

  Debug.Print maxrow, maxcol
  Arr1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(maxrow, maxcol)).Formula
  Arr2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(maxrow, maxcol)).Formula
  ReDim Arr3(1 To UBound(Arr1, 1), 1 To UBound(Arr1, 2))

  difference = 0

  For col = 1 To maxcol
    For row = 1 To maxrow
      If Arr1(row, col) <> Arr2(row, col) Then
      difference = difference + 1
      Arr3(row, col) = Arr1(row, col) & "<> " & Arr2(row, col)
      Else
      Arr3(row, col) = ""
      End If
    Next row
  Next col

  Debug.Print " Calc secs " & Timer - tm
  If difference > 0 Then
  Set Report = Workbooks.Add

  With Report.ActiveSheet
  .Range("A1").Resize(UBound(Arr3, 1), UBound(Arr3, 2)).Value = Arr3
  .Columns("A:B").ColumnWidth = 25
  Set Rng = .Range(Report.ActiveSheet.Cells(1, 1), Report.ActiveSheet.Cells(UBound(Arr3, 1), UBound(Arr3, 2)))
  End With

  With Rng
  .FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=""""" '""""""""
  .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
   With .FormatConditions(1)
        .Interior.Color = 255
        .Font.Bold = True
        .Font.ColorIndex = 2
    End With
   End With

  Debug.Print "Report Generated secs " & Timer - tm
  End If
 'Set Report = Nothing
  'Application.ScreenUpdating = True
  'Application.Calculation = xlCalculationAutomatic
  'Application.EnableEvents = True

  MsgBox difference & " cells contain different data! ", vbInformation, "Comparing Two       Worksheets"
End Sub

How do I run this code?

I add the code into a module and then create a button and do the following.

The first picture shows how I call the sub to compare the two sheets

The second pictures shows how I open up another file and compare two Excel files.


texts: Does PDO::quote helps me to protect me against sql injection?

texts:
I have to process raw sql user input with Laravel. I've backed them up as follows:
$query = DB::table('table_name');

function escapeString($str) {
    return DB::connection()->getPdo()->quote($str);
}

$column = escapeString($rule['query']['operand']);
$value = escapeString($rule['query']['value']);
if(in_array($rule['query']['operator'], $query->operators)) {
    return $column . ' ' . $rule['query']['operator'] . ' ' . $value;
}

Is that enough, or can I still be attacked over it?
I read:

https://stackoverflow.com/questions/18951057/escape-raw-sql-queries-in-laravel-4 - recommend it
https://www.php.net/manual/de/pdo.quote.php - they do not recommend it, but it seems possible

(This question was postet originaly at https://stackoverflow.com/questions/63091979/is-my-code-protected-against-sql-injection, but STA suggest to post this question here again)
Update:
I figured out, how to use value in variable binding. Also I changed escapeString to
$column = preg_replace('/[^a-zA-Z_]/', '', $rule['query']['operand']);

Thats fine for alle columns names and I am pretty sure that this is safe. This filtering approch ist also used in https://stackoverflow.com/questions/10080850/using-a-whitelist-on-user-input


texts: Finding occurrence of a given character in a String?

texts:
I came up with this simple solution:

public class Main {

  /**
   * How to count occurrence of a given character in a String?
   */

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    if (!in.hasNextLine()) {
      System.out.println("You must enter a string!");
    }

    String givenString = in.nextLine();

    char givenChar = in.next().charAt(0);

    int occurance = occuranceOfChar(givenString, givenChar);

    System.out.println(givenChar + " occured " + occurance + " times!");
  }

  private static int occuranceOfChar(String givenString, char givenChar) {

    int sum = 0;

    for (int i = 0; i < givenString.length(); i++) {

      char charAtI = givenString.charAt(i);

      if (charAtI == givenChar) sum++;
    }

    return sum;
  }
}

Are there any bad practices here?


texts:
I began programming recently. I am trying to implement a simple trial-division algorithm for finding all primes up to some number (it is much more "primitive" algorithm than the Sieve of Eratosthenes). Can you please find what's wrong with my code?

#range function:

range = function (a,b,c){
    var range1=[]
    for (i=a; i<b; i=i+c){
        range1.push(i);
    }
    return range1;
}

#The algorithm:

n=prompt("n");
var numbers=range(2,n,1);
var primes=[];
for (number in numbers){
 var sublist=range(2,number,1);
 console.log(sublist);
 for (x in sublist){
  if (number%x ===0){
   break;
  }
 primes.push(number);
 }
}

Thanks in advance!


texts:
The problem is the following:

We have a number of months to buy a number of supplies. The sooner we finish buying them, the better, but we don't know how much we can buy per month and would like to calculate all possible scenarios.

Suppose months = 5 and supplies = 9, and (72000) means 7 in the first month, 2 in the second and 0 in the following months.

VALID:   (90000)
VALID:   (81000)
VALID:   (72000)
VALID:   (71100)
INVALID: (61200)
INVALID: (80100)

This is basically a problem of combinations following a rule: in a MONTHS sized array, the n-th element cannot be larger than the (n-1)-th element, and the sum of all elements must be SUPPLIES.

My solution to do this was slicing the array into smaller parts and carrying digits over:

var months = 5;
var supplies = 9;

function calc(sum, nslots, maxdigit){
    if (sum === 0) return [];
    if (nslots === 0) return [];

    maxdigit = maxdigit || sum;

    var results = [];

    var firstDigit = Math.min(maxdigit,sum);
    if (maxdigit >= sum){
        var digits = [];
        for(var i=0;i<nslots;i++) digits.push(0);

        digits[0] = firstDigit;

        results = [digits];
    }

    for(;firstDigit>0;firstDigit--){
        var pointsLeft = sum - firstDigit;
        if (pointsLeft === 0) continue;

        var subArrays = calc(pointsLeft, nslots-1, firstDigit);

        if (subArrays.length === 0) continue;

        var subResults = subArrays.map(function(i){return [firstDigit].concat(i);});
        results = results.concat(subResults);
    }

    return results;
}

var results = calc(supplies,months);
console.log(results);

It's not in any way clear what this does though, and I myself would probably have a hard time understanding this code a year from now.

The clearest way I can imagine is just generating all numbers from 90000 down to 0 (in the 9 supplies and 5 months example) and checking if each number follows the rule, but it's ridiculous for bigger values of MONTHS and SUPPLIES.

I'd prefer a solution in ALGOL-descending languages. I imagine Python, Haskell or Erlang probably have some awesome way to solve this in just a few lines, but I couldn't use them here.


texts:
I created my first gem for Rails today. https://github.com/Fivell/activeresource-response.
This gem adds possibility to access http response object from result of activeresource call.

I don't know how to create test for this gem.
Also I want to ask if there is more simply and elegant way to do this?
Is it really thread-safe?
Other ways to write this functionllity except alias_method?

Here is source of library.

require "activeresource-response/version"
module ActiveresourceResponse
   module Connection
     def self.included(base)
       base.class_eval  <<-EOS
           alias_method :origin_handle_response, :handle_response
           attr_reader :http_response
           def handle_response(response)
             @http_response= response
             origin_handle_response(response)
           end
        EOS
     end
   end
   module AddResponseMethod
     def self.included(base)
        base.extend ClassMethods
      end
      module ClassMethods
         def add_response_method(method_name = 'http_response')
             class_eval  <<-EOS
               class << self
                 alias_method :origin_find, :find
                 def find(*arguments)
                     result = origin_find(*arguments)
                     result.class_eval("attr_reader :#{method_name}")
                     result.instance_variable_set(:"@#{method_name}", connection.http_response)
                     result
                 end
                end
             EOS
         end
      end
   end
end
ActiveResource::Connection.send :include, ActiveresourceResponse::Connection
ActiveResource::Base.send :include, ActiveresourceResponse::AddResponseMethod

UPDATE

I made some refactoring, please look at github sources.


texts: Is this a good algorithm for 2D collision, or will it allocate too much memory?

texts:
I have a Rectangle class, of which I have 5-6 vectors for each instance. The main vectors are the center and color of the object, while the secondary vectors represent more or less the north, south, east, and west directions of the rectangle itself. These vectors are used to detect collision by "pointing" outside of the sides of the rectangle to detect collision. I may end up creating more fields of the NW, SW, NE, SE, equivalents as well, but I'd like to know if this is actually a good implementation before I do this. The only Vec2f I have allocated as a pointer is the mWidthHeight vector, which of course is just a representation of the width and the height (x = width, y = height) of the rectangle.

Will this allocate too much memory if there are thousands of these on the screen, or is this an OK (at least) implementation?

Rect.h

Note - I'm debating with the idea of making the N, S, E, W vectors pointers to memory. Is that a good idea, or no?

#pragma once

#include <QGLWidget>
#include <GL/glext.h>
#include <cmath>
#include <QDebug>
#include "Shape.h"
#include "Vec3f.h"
#include "rand.h"

const int DEFAULT_SQUARE_WIDTH = 5;
const int DEFAULT_SQUARE_HEIGHT = 5;

typedef enum {

  V2D_NORTH,
  V2D_SOUTH,
  V2D_EAST,
  V2D_WEST

} V2D_DIRECTION;

class Rectangle : public Shape
{
public:

    Rectangle(
        Vec2f center = Vec2f(),
        Vec2f widthheight = Vec2f(DEFAULT_SQUARE_WIDTH, DEFAULT_SQUARE_HEIGHT),
        float radius = 0,
        Vec3f color = Vec3f()
    );

    ~Rectangle();

    inline Vec2f* getWidthHeight() const {
        return mWidthHeight;
    }

    inline Vec2f getDirection(V2D_DIRECTION dir) const {
        switch(dir) {
        case V2D_NORTH:
            return mNorth;

        case V2D_SOUTH:
            return mSouth;

        case V2D_EAST:
            return mEast;

        case V2D_WEST:
            return mWest;

        }
    }
    virtual void Collide( Shape &s );

    virtual void Collide( Rectangle &r );

    virtual void Collide ( Circle &c );

    virtual bool Intersects( const Shape& s ) const;

    virtual bool Intersects( const Rectangle& s ) const;

    virtual bool IsAlive( void ) const;

    virtual float Mass( void ) const;

protected:

   virtual void Draw( void ) const;
   Vec2f* mWidthHeight;
   Vec3f mColor;

private:
   Vec2f mNorth;
   Vec2f mSouth;
   Vec2f mEast;
   Vec2f mWest;
   void InitDirections();

};


texts:
I have a method which checks all of its surrounding squares and returns the number of bombs around it. It uses a long list of if statements, which is pretty ugly and probably inefficient.

       public int countArround(){
    int bombNum = 0;
    //x=0 y=1 works
    if(((SmartSquare)board.getSquareAt(xLocation, yLocation+1)!=null)&&
        (((SmartSquare)board.getSquareAt(xLocation, yLocation+1)).getBomb())){
        bombNum++;
    }
    //x=1 y=1
    if(((SmartSquare)board.getSquareAt(xLocation+1, yLocation+1)!=null)&&
        ((SmartSquare)board.getSquareAt(xLocation +1, yLocation+1)).getBomb()){
        bombNum++;
    }
    //x=1 y=0 works
    if(((SmartSquare)board.getSquareAt(xLocation+1, yLocation)!=null)&&
        ((SmartSquare)board.getSquareAt(xLocation+1, yLocation)).getBomb()){
        bombNum++;
    }
    //x=1, y=-1 works
    if(((SmartSquare)board.getSquareAt(xLocation+1, yLocation-1)!=null)&&
        ((SmartSquare)board.getSquareAt(xLocation+1, yLocation-1)).getBomb()){
        bombNum++;
    }
    //x=0 y=-1
    if(((SmartSquare)board.getSquareAt(xLocation, yLocation-1)!=null)&&
        ((SmartSquare)board.getSquareAt(xLocation, yLocation-1)).getBomb()){
        bombNum++;
    }
    //x=-1, y=-1 works
    if(((SmartSquare)board.getSquareAt(xLocation-1, yLocation-1)!=null)&&
        ((SmartSquare)board.getSquareAt(xLocation-1, yLocation-1)).getBomb()){
        bombNum++;
    }
    //x=-1, y=0 works
    if(((SmartSquare)board.getSquareAt(xLocation-1, yLocation)!=null)&&
        ((SmartSquare)board.getSquareAt(xLocation-1, yLocation)).getBomb()){
        bombNum++;
    }
    //x=-1 y=1 works
    if(((SmartSquare)board.getSquareAt(xLocation-1, yLocation+1)!=null)&&
        ((SmartSquare)board.getSquareAt(xLocation-1, yLocation+1)).getBomb()){
        bombNum++;
    }
    return bombNum;

I was wondering how this can be cleaned up. I cannot seem to get it into an if/while/for statement.


texts: Changing window buffer and size in C with WinAPI

texts:
I wrote a code to change window buffer and size in a console app with C.

Background:
I had trouble with changing window buffer and size in C with WinAPI. Simply calling system("mode con cols=XX lines=YY"); worked but I didn't want to do that like that.

First I've tried to change window buffer and size in C with WinAPI. I had a problem with the code:

SetConsoleScreenBufferSize(GetStdHandle( STD_OUTPUT_HANDLE ), newbuffersize);
SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &newwindowsize);

This worked in some cases, but failed other times. Than I changed order:

SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &newwindowsize);
SetConsoleScreenBufferSize(GetStdHandle( STD_OUTPUT_HANDLE ), newbuffersize);

This worked in some cases, but failed other times. When first order worked, second second one failed. When second one worked, first one failed. Interesting case isn't it?
Here I've posted it: https://stackoverflow.com/questions/47270329/fail-to-change-windows-size-and-buffer-under-c-with-winapi

Than I figured out the problem:
Buffer cannot be smaller than window size. If you change buffer first, you cant go smaller than old window size. If you change window first, you cant go larger than old buffer size.

This is my solution, please review and share your ideas and comments:

void newbufwinxy(int x, int y)
{
SMALL_RECT console_size2;
console_size2.Right = x;
console_size2.Bottom = y;
console_size2.Left = 1;
console_size2.Top = 1;
COORD console_size;
console_size.X = x;
console_size.Y = y;
CONSOLE_SCREEN_BUFFER_INFO screencsbi;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &screencsbi);
//if new buffer is larger than old buffer size or at least window, go ahead
if (console_size.X >= screencsbi.dwSize.X && (console_size.Y >= screencsbi.dwSize.Y||console_size.Y >= screencsbi.srWindow.Bottom-1))
{
    SetConsoleScreenBufferSize(hStdout, console_size);
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}
//if new window is larger in widght but smaller in height, do a temporary shrink
else if (console_size2.Right >= screencsbi.srWindow.Right-1 && console_size2.Bottom <= screencsbi.srWindow.Bottom-1)
{
    console_size2.Right = 20; //temporarily shrink window width...
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
    SetConsoleScreenBufferSize(hStdout, console_size);
    console_size2.Right = x;
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}
//if new buffer is smaller than old window, change window first
else if (console_size.X <= screencsbi.dwSize.X && !(console_size2.Bottom >= screencsbi.dwSize.Y))
{
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
    SetConsoleScreenBufferSize(hStdout, console_size);
}
else
{
    printf("\nold _values_ >> new _values_ \n");
    printf("dwSize.X = %i >> ",screencsbi.dwSize.X);
    printf("dwSize.X = %i\n",console_size.X);
    printf("dwSize.Y = %i >> ",screencsbi.dwSize.Y);
    printf("dwSize.Y = %i\n",console_size.Y);
    printf("srWindow.Bottom = %i >> ", screencsbi.srWindow.Bottom);
    printf("srWindow.Bottom = %i\n", console_size2.Bottom);
    printf("srWindow.Right = %i >> ", screencsbi.srWindow.Right);
    printf("srWindow.Right = %i\n", console_size2.Right);
    printf("SetConsoleWindowInfo, SetConsoleScreenBufferSize\n");
    printf("Error. Cannot recognise console windows or buffer size!\n");
    printf("\nProgram encountered errors and shall exit now.");
    printf("\nPress any key to continue...");
    getch();
    ExitProcess(1);
}
}


texts: Why below recursive DP solution is so slow? (Leetcode Q# 123 - Best Time to Buy and Sell Stock III)

texts:
This is regarding leetcode Question# 123. I have solved the question (code below) but the solution is showing "Your runtime beats 5.89 % of cpp submissions."? Is there any additional optimization I can do to make it run faster?
class Solution {
    int maxProfitUtility(vector<int>& prices, int i, int buyOrSell, int k, vector<vector<vector<int>>>& dp){
        if(i == prices.size() || k == 0){
            return 0;
        }
        if(dp[i][buyOrSell][k] != INT_MIN){
            return dp[i][buyOrSell][k];
        }
        int x, y;
        if(buyOrSell == 0){
            x = maxProfitUtility(prices, i + 1, 1, k - 1, dp) - prices[i];
            y = maxProfitUtility(prices, i + 1, 0, k, dp);
        }else{
            x = maxProfitUtility(prices, i + 1, 0, k - 1, dp) + prices[i];
            y = maxProfitUtility(prices, i + 1, 1, k, dp);
        }
        dp[i][buyOrSell][k] = max(x,y);
        return max(x,y);
    }
public:
    int maxProfit(vector<int>& prices) {
        int k = 4;
        vector<vector<vector<int>>> dp(prices.size(), vector<vector<int>>(2, vector<int>(k + 1, INT_MIN)));
        return maxProfitUtility(prices, 0, 0, k, dp);
    }
};


texts:
I am trying to implement AES on GPU using CUDA programming. I use 4 TBoxes in my implementation that requires 4kB of GPU Memory. I have used a 1KB array for 1KB plaintext. first all of plaintext would be copied to GPU memory, then encryption would be started using

cudaMemcpyToSymbolAsync(DEV_message, H_Message, 1024, 0, cudaMemcpyHostToDevice);

Then, the global kernel will run:

AESROUND<<< 8, 16, 16 >>>(1024);

AESROUND() performs one round of AES algorithm on a 1024-bit state, then 32 bytes of the array will XOR with 32 bits of the state.

__global__ void AESROUND_AD(const int SIZE)
{
    __shared__ unsigned char dev_rkey[16];
    __shared__ unsigned char dev_sh_state[16];

    int tid = blockIdx.x * 16 + threadIdx.x;
    if (tid < 128)
    {
        for (long long i = 0; i <SIZE/32; i++)
        {
            dev_sh_state[threadIdx.x] = dev_state[(tid + 112) % 128];
            dev_rkey[threadIdx.x] = dev_state[tid];
            __syncthreads();

            if (threadIdx.x < 4)
            {
                U32 v1 = ((U32*)dev_TE0)[*(dev_sh_state + threadIdx.x * 4)];
                U32 v2 = ((U32*)dev_TE1)[*(dev_sh_state + ((threadIdx.x * 4 + 5) % 16))];
                U32 v3 = ((U32*)dev_TE2)[*(dev_sh_state + ((threadIdx.x * 4 + 10) % 16))];
                U32 v4 = ((U32*)dev_TE3)[*(dev_sh_state + ((threadIdx.x * 4 + 15) % 16))];

                ((U32*)dev_sh_state)[threadIdx.x] = v1 ^ v2 ^ v3 ^ v4 ^ ((U32*)dev_rkey)[threadIdx.x];
            }
            __syncthreads();

            dev_state[tid] = dev_sh_state[threadIdx.x];
            __syncthreads();

        }
    }
}

There is no problem in code or in my program, but the big problem is its speed: just 1 megabyte per second. I don't know why this program is so slow.

I use Microsoft Visual C++ in Windows 8.1 with CUDA Toolkit 7.
My GPU is a GeForce GT 720M

Compute capability: 2.1
Number of SMs: 2
Graphic clock (MHz): 625
Processor clock (MHz): 1250
Memory clock (MHz): 800

My processor is Intel Core(TM) i5-3337U CPU @ 1.80GHz (4 CPUs) microprocessor.

Source code of the algorithm can be found here.


texts: Should I split code into smaller functions? Advice on layout

texts:
I have the following code.  I was wondering if anyone can give me any pointers on how to make this more concise and neater?  Should I be splitting this down into smaller functions?

    private void ReturnValue()
    {

        //create our WebService object
        var sample = new TestProjectService.Service1();
        //create our string to hold the Command information returned
        //select which web service to use
        var Command = new SimpleWebServiceApp.TestProjectService.CommandMessages();

        switch (WebServiceRadio.SelectedIndex)
        {
            case 0:
                Command = sample.GetData();
                break;
            case 1:
                Command = sample.GetDataLINQ();
                break;
        }

        //Check if a value is returned
        if (Command != null)
        {
            //Display result on screen
            LatestCommandLabel.Text = String.Format("Last Command Called (Using {0}) : {1}",WebServiceRadio.SelectedItem.ToString(),Command.Command);

            //Get the current logged in username
            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            //Write command to the database
            TestProjectLinqSQLDataContext dc = new TestProjectLinqSQLDataContext();
            TestProjectCommandMessage msg = new TestProjectCommandMessage();
            msg.Command_Type = Command.CommandType;
            msg.Command = Command.Command;
            msg.DateTimeSent = Command.DateTimeSent;
            msg.DateTimeCreated = Command.DateTimeCreated;
            msg.Created_User = userName;
            msg.Created_Dttm = DateTime.Now;
            dc.TestProjectCommandMessages.InsertOnSubmit(msg);
            dc.SubmitChanges();
        }
        else
        {
            LatestCommandLabel.Text = "No Commands Available";
        }
    }

    protected void GetCommandButton_Click(object sender, EventArgs e)
    {
        ReturnValue();
    }


texts: Using Dynamic to create and then flatten an arbitrarily-nested array

texts:
I have some code that I posted as a possible answer on StackOverflow (and the code I post here is almost an exact duplicate of that, but I'd rather include complete information in this post as well so people don't have to jump back and forth between posts to understand the question). I truthfully haven't quite decided whether it's terrible, really clever, or something in between (which is why I'm asking for reviews here).

I'm perfectly aware that the use of dynamic in C# is somewhat controversial. That aside, though, I'll freely admit that I rarely use it and am curious as to whether this is what would normally be considered a "valid" use of it.

Basically, the problem is to create and then "flatten" an arbitrarily-nested array. At any given index, the array could contain either an integer or another array of integers, so you could have something like this:

[ 1 2 3 4 5
  [6 7
      [8 9
         [10 11 12]
       13 14 15]
  16 17]
18 19 20]

The resulting "flattened" array would be 1, 2, 3, 4, 5, 6, 7...20.

I use the following code to create the array:

Random random = new Random();
        dynamic array = new dynamic[random.Next(3, 10)];
        for (int i = 0; i < array.Length; i++)
        {
            if (random.NextBool())
            {
                array[i] = new dynamic[random.Next(3, 10)];

                for (int j = 0; j < array[i].Length; j++)
                {
                    if (random.NextBool())
                    {
                        array[i][j] = random.Next(1, 100);
                    }
                    else
                    {
                        array[i][j] = new int[random.Next(3, 10)];

                        for (int k = 0; k < array[i][j].Length; k++)
                        {
                            array[i][j][k] = random.Next(1000);
                        }
                    }
                }
            }
            else
            {
                array[i] = random.Next(1, 100);
            }
        }

where NextBool is an extension method on the Random class:

public static bool NextBool(this Random random)
    {
        return random.Next(0, 1) == 0;
    }

Once I've created this, I can use recursion to "flatten" the list. Essentially, at any point I determine if this is a "base" case (it's just an integer) or if it's a (potentially arbitrarily-nested) array. If it's an array, I just loop over it, add the integers to the final result, and do a recursive call on any arrays I find.

private void Flatten(dynamic item, List<int> flattened)
{
    // This is the base case - the item's just an integer
    if (item.GetType() == typeof(int))
    {
        flattened.Add((int)item);
    }
    else
    {
        foreach (dynamic itm in item)
        {
            // Handle the case where the current item's an int
            if (itm.GetType() == typeof(int))
            {
                flattened.Add(itm);
            }
            // If it's not an int, it must be an array - recursively process it
            else
            {
                Flatten(itm, flattened);
            }
        }
    }
}

I could probably simply this a little by simply making everything arrays - i.e. instead of "plain" integers I have an array of length 1 - but I'm not sure that this is a dramatic improvement.

Anyone have opinions on whether this is a good solution or not? (I honestly won't be offended if people think it's a terrible idea, I'd rather have the honest feedback). Are there ways I could improve this or solve it in a better way?

Edit: I'm using arrays here (rather than some kind of a Tree structure, which I think would be preferable for data structured like this) because of constraints in the post I was responding to on SO.


texts:
I have a method in a class, and its sole purpose is to prepare another class for use:

private function createHttpPost($endPoint) {
    $httpPost = new HttpPost($this->baseUri . '/' . $endPoint);
    $httpPost->setContentType('application/json');
    $httpPost->setAccept('application/json');

    if($this->auth) {
        $this->authenticate();
        $httpPost->addCookies(array($this->sessionName => $this->sessionId));
        $httpPost->addHeaders(array('X-CSRF-Token' => $this->token));
    }

    return $httpPost;
}

I am familiar with the factory design pattern, but I'm not sure it is a good idea to apply that kind of thinking to a class method. Should I take this code out and put it in a new class called JsonHttpPostFactory, or something like that?

Is this a bad idea?  If so, why?


texts: Optimise compare and match method using scripting.dictionary in VBA

texts:
In my previous post I was looking for a better solution to write a single column of a 2D array into a worksheet besides looping between code and worksheet and finally managed to achieve that.

On deploying my code, I found that the double loop to compare two arrays was inefficient when it came to comparing arrays of 5,000 or more and so I turned to the scripting.dictionary, for which I found the easiest instructions to follow here.

Here is an example that I have tested with arrays of 80,000 rows, returning results in seconds, but I am wondering if there might be some code I could cut or write better:

Option Explicit
Option Base 1

Public Sub arrayMatch()

    Dim firstArray As Variant
    With ThisWorkbook.Worksheets(1)
        firstArray = .Range("A1").CurrentRegion
    End With

    Dim secondArray As Variant
    With ThisWorkbook.Worksheets(2)
        secondArray = .Range("A1").CurrentRegion
    End With

    Dim i As Long
    Dim dictKeyForLookup As String
    Dim dictValueToReturn As String

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare

    For i = LBound(firstArray, 1) To UBound(firstArray, 1)
        dictKeyForLookup = firstArray(i, 4)
        dictValueToReturn = firstArray(i, 3)
        If Not dict.Exists(dictKeyForLookup) Then
            dict.Add Key:=dictKeyForLookup, Item:=dictValueToReturn
        End If
    Next i

    Dim arrayToPaste As Variant
    ReDim arrayToPaste(UBound(secondArray, 1), 1)
    For i = LBound(secondArray, 1) To UBound(secondArray, 1)
        If dict.Exists(secondArray(i, 1)) Then
            arrayToPaste(i, 1) = dict.Item(secondArray(i, 1))
        End If
    Next i

    With ThisWorkbook.Worksheets(1)
        .Range(.Cells(1, 4), .Cells(UBound(secondArray, 1), 4)).Value = arrayToPaste
    End With

End Sub


texts: SQLite and Python: commit once every 10 seconds maximum, and not after every client request

texts:
In a Python Bottle server using SQLite, I noticed that doing a DB commit after each INSERT is not efficient: it can use 100ms after each client request. Thus I wanted to improve this in How to commit DB changes in a Flask or Bottle app efficiently?
.

I finally came to this solution, which is more or less a "debounce"-like method: if multiple SQL INSERT happen during a 10-second timeframe, group all of them in a single DB commit.

What do you think of the following code? Is it safe to do like this?

(Note: I know that the use of a global variable should be avoided, and replaced by a class / object with attributes, etc. I'll do this, but this part is not really on topic here).

import bottle, sqlite3, random, threading, time

@bottle.route('/')
def index():
    global committhread
    c = db.cursor()
    c.execute('INSERT INTO test VALUES (?)', (random.randint(0, 10000),))
    c.close()
    if not committhread:
        print('Calling commit()...')
        committhread = threading.Thread(target=commit)
        committhread.start()
    else:
        print('A commit is already planned.')
    return 'hello'

def commit():
    global committhread
    print("We'll commit in 10 seconds.")
    time.sleep(10)  # I hope this doesn't block/waste CPU here?
    db.commit()
    print('Committed.')
    committhread = None

db = sqlite3.connect('test.db', check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS test (a int)")
committhread = None
bottle.run(port=80)

If you run this code, opening http://localhost/ once will plan a commit 10 seconds later. If you reopen http://localhost/ multiple times, less than 10 seconds later, you will see that it will be grouped in the same commit, as desired.

Note: this method is not "Do it every 10 seconds" (this would be a classic timer), but rather: "Do it 10 seconds later; if another INSERT comes in the meantime, do all of them together". If there is no INSERT during 60 minutes, with my method it won't do anything at all. With a timer it would still periodically call a function (and notice there's nothing to do).

Worth reading too: How to improve SQLite insert performance in Python 3.6?


texts: Composing commands to control virtual machines

texts:
I created a function which takes some inputs and builds a specific set of strings. The function is working as intended, however I can't help thinking how ridiculous it looks every time I see it. I originally had a more simple way of building the strings using multiple different functions, however I couldn't stand how much repetition there was between them.

This is what I currently have.

def format_command_string(vmrunDir, command, vmxfile="", username="", password="", script="", parameters=[]):
    escapedVmxfile = "\"{}\"".format(vmxfile)
    escapedVmrunDir = "\"{}\"".format(vmrunDir)
    parameters = " ".join(parameters) if parameters else " "
    subStringTuple = (
        escapedVmrunDir,  # 0
        "-T ws",  # 1
        "-gu {}".format(username),  # 2
        "-gp {}".format(password),  # 3
        command,  # 4
        escapedVmxfile,  # 5
        "cmd.exe \"/c Z:\\vm_controller_share\scripts\{}\"".format(script),  # 6
        parameters)   # 7

    formatDictionary = {
        "list": "{0} {4}",
        "runProgramInGuest": "{0} {1} {2} {3} {4} {5} {6} {7}",
        "addSharedFolder": "{0} {1} {2} {3} {4} {5} {7}",
        "removeSharedFolder": "{0} {1} {2} {3} {4} {5} {7}",
        "start": "{0} {1} {4} {5}",
        "stop": "{0} {1} {4} {5} {7}",
        "reset": "{0} {1} {4} {5} {7}"}

    formattedCommandString = formatDictionary[command].format(*subStringTuple).strip()

    return formattedCommandString

It does the job I want it to do fine, but it just seems perhaps a bit... overly complicated? There is some obvious cons to it around readability and maintainability. However I can't bring myself to go back to what I had originally, which was something like:

def format_list_command_string(vmrunDir):
    return "{} list".format(vmrunDir)

def format_run_command_string(vmrunDir, username, password, vmxfile, script, parameters):
    return "{} -T ws -gu {} -gp {} runProgramInGuest {} cmd.exe \"/c Z:\\vm_controller_share\scripts\{} {}\"".format(vmrunDir, username, password, vmxfile, script, parameters)

def format_add_shared_folder_command_string(vmrunDir, username, password, vmxfile, guestSharedFolder, hostShareFolder):
    return "{} -T ws -gu {} -gp {} addSharedFolder {} {} {}".format(vmrunDir, username, password, vmxfile, guestSharedFolder, hostShareFolder)

def format_remove_shared_folder_command_string(vmrunDir, username, password, vmxfile, guestSharedFolder):
    return "{} -T ws -gu {} -gp {} removeSharedFolder {} {}".format(vmrunDir, username, password, vmxfile, guestSharedFolder)

def format_start_command_string(vmrunDir, vmxfile):
    return "{} -T ws start {}".format(vmrunDir, vmxfile)

def format_stop_command_string(vmrunDir, vmxfile, force):
    return "{} -T ws stop {} {}".format(vmrunDir, vmxfile, force)

def format_resetcommand_string(vmrunDir, vmxfile, force):
    return "{} -T ws reset {} {}".format(vmrunDir, vmxfile, force)

I've only really worked alone, and I've not got a lot of exposure to some simple stuff as building strings so I'm not sure what I expect from this review, but all advice is appreciated.

EDIT:
Example of how the returned strings would be used at request of @200_success

def try_vmrun_command(commandString):
    try:
        output = subprocess.check_output(commandString)
    except subprocess.CalledProcessError as error:
        print error.output
    else:
        return output