texts:
This is a solution for part 1 & 2 of Advent of Code 2020 Day 9.
Given the example input sample.txt:
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576

Part 1: find the first number in the list (after the preamble) which is not the sum of two of the n numbers before it. n is the preamble.
For example, after the 5-number preamble, almost every number is the sum of two of the previous 5 numbers; the only number that does not follow this rule is 127.
Part 2: find a contiguous set of at least two numbers in your list which sum to the invalid number from part 1.
For example, in this list, adding up all of the numbers from 15 through 40 produces the invalid number from part 1, 127. Add together the smallest and largest number in this contiguous range; in this example, these are 15 and 47, producing 62.
Code:
def not_in_preamble(nums, preamble):
    diff = set()
    for i in range(preamble, len(nums)):
        current = nums[i]
        found = False
        for j in range(i - preamble, i):
            if nums[j] in diff:
                found = True
                break
            diff.add(current - nums[j])
        if not found:
            return current
        diff.clear()

def sub_array_with_sum(nums, n):
    i, j = 0, 1
    partial_sum = nums[i] + nums[j]
    while j < len(nums):
        if partial_sum == n:
            return nums[i: j + 1]
        if partial_sum < n or i == j - 1:
            j += 1
            partial_sum += nums[j]
        else:
            partial_sum -= nums[i]
            i += 1

# Part 1
preamble = 5
with open('sample.txt') as f:
    nums = [int(l) for l in f.read().splitlines()]
pt1_result = not_in_preamble(nums, preamble)
print(f'PT 1 result: {pt1_result}')

# Part 2
n = pt1_result
sub_array = sub_array_with_sum(nums, n)
print(f'PT 2 result {min(sub_array) + max(sub_array)}')

The code outputs:
PT 1 result: 127
PT 2 result 62

Which is the correct result for the sample input.
Changing the sample.txt to the puzzle input and setting preamble=25, will give the correct result for the challenge.
Can the code be made more compact and efficient? Any other feedback or alternative solutions are welcome.


texts:
class Element

  attr_accessor :datum,  :prev , :next

  def initialize(datum,next_element=nil, prev_element=nil)
    @datum = datum
    @next = next_element
    @prev = prev_element
  end

end

class Deque

  attr_reader :first, :last

  def push(datum)
    if @last.nil?
      @last = Element.new(datum)
      @first = @last
    elsif @last == @first
      @last = Element.new(datum,@first)
      @first.prev = @last
    else
      prev = @last
      @last = Element.new(datum,prev)
      prev.prev = @last
    end
  end

  def pop
    datum = @last.datum
    @last = @last.next if @last
    datum
  end

  def shift
    datum = @first.datum
    @first = @first.prev
    @first.next = nil  if @first
    datum
  end

  def unshift(datum)
    if @last.nil?
      @last = Element.new(datum)
      @first = @last
    elsif @last == @first
      @first = Element.new(datum,nil,@last)
      @last.next = @first
    else
      prev = @first
      @first = Element.new(datum,nil, prev)
    end
  end

end


texts: Handling click events on ingredients list

texts:
I'm learning programming and would appreciate any feedback on my code. I've come up with the below code. The logic works fine but the code itself seems rather confusing to me. Are there some patterns I could use to improve this code?

// This code snippet handles click events on the Ingredients list (see the image below)

$('.items a').click(function (event) {

    // Remove leading letter from the href id (e.g. id="i15" --> 15)
    ingr = parseInt((this.id).substring(1));

    // Here comes the complicated logic for handling click event
    // It works well but can it be improved/simplified?
    if (buy.indexOf(ingr) != -1) {
        if (weHave.indexOf(ingr) != -1) {
            if (weNeed.indexOf(ingr) === -1) {
                weNeed.push(ingr);
                whIndex = weHave.indexOf(ingr);
                weHave.splice(whIndex, 1);
            }
        } else {
            if (weNeed.indexOf(ingr) === -1) {
                weHave.push(ingr);
            } else {
                weHave.push(ingr);
                wnIndex = weNeed.indexOf(ingr);
                weNeed.splice(wnIndex, 1);
            }
        }
    } else {
        if (weHave.indexOf(ingr) != -1) {
            weNeed.push(ingr);
            whIndex = weHave.indexOf(ingr);
            weHave.splice(whIndex, 1);
        } else {
            if (weNeed.indexOf(ingr) != -1) {
                weHave.push(ingr);
                wnIndex = weNeed.indexOf(ingr);
                weNeed.splice(wnIndex, 1);
            } else {
                weNeed.push(ingr);
            }
        }
    }
    shoplist();
    return false; // to prevent the page from scrolling to the top
});

EDIT: Edited the code above and provided more background information below.

Here is a simplified picture of the application I'm trying to create:

Briefly how the application should work:

The idea is to create a shopping list by selecting food and/or ingredients
Clicking on a food item will highlight the food item and all necessary ingredients
Clicking on already highlighted food item will remove the highlighting from the food item and all necessary ingredients
Clicking on an ingredient will highlight the ingredient
Clicking on already highlighted ingredient will remove the highlighting from the ingredient

The above is basic logic but here is where it gets complicated. There are couple of scenarios I'm trying to handle in the code above (these are independent scenarios):

I click on Spaghetti Bolognese. Necessary ingredients, including onion, get highlighted. Then I click on onion, indicating that I already have this ingredient at home. The highlighting is removed from the onion. Then I click on Pork Stew (which requires onion) but onion shouldn't get highlighted because I have already indicated that I do have an onion at home.
I click on Spaghetti Bolognese. Necessary ingredients, including onion, get highlighted. Then I click on Pork Stew. Pork Stew requires onion too so the onion item stays highlighted. But then I decide I don't want to make Spaghetti Bolognese after all so I unclick it. The onion should stay highlighted because it's required for Pork Stew.

So to handle these kind of scenarios I came up with two arrays: weNeed and weHave.

Here is a list of inputs/outputs:

ingr: integer; clicked ingredient
buy: unique list of ingredients, concatenation of weNeed + food (food is an array of ingredients coming from the FOOD list; not in the above code)
weNeed: list of ingredients collected when user clicks on unhighlighted ingredient item
weHave: list of ingredients collected when user clicks on highlighted ingredient item

P.S. Looking back at my question this has grown into a monster. I'm not sure if the extra information I provided is helpful or even more confusing. I could post the whole code if it helps but something is telling me that dealing with these kind of complex issues on the forum is probably not the right way to do things. I'll be happy for any suggestions.


texts: Is calling file write in the dispose acceptable?

texts:
class HtmlLogger:ILogger,IDisposable
{
    private System.IO.StreamWriter  _file;
    private bool _disposed;

    public HtmlLogger()
    {
        _disposed = false;
        _file = new StreamWriter(@"somepath");
        _file.Write("");
    }

    public void Log(string message)
    {
        _file.Write("
{0}
", message);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                if (_file != null)
                {
                    _file.Write("");
                    _file.Flush();
                    _file.Dispose();
                }

            }
            _file = null;
            _disposed = true;
        }
    }
}


texts: Install a Python package based on active_gpu or version

texts:
I have the following code, is there a way to optimize it/reduce the code?

  #!/bin/bash

  if [[ "${active_gpu}" == 'true' ]]; then
    if [[ "${version}" == 'dev-gpu' ]]; then
        pip install "${version}"
    else
        pip install package-gpu=="${version}"
    fi
  else
    if [[ "${version}" == 'nightly' ]]; then
        pip install "${version}"
    else
        pip install package=="${version}"
    fi
  fi


texts:
On my website, I created like this banner that rotates quotes from an array I made.

var myarray = []
myarray[0] = "\"To a contrarian like me, constant advice not to do something almost always starts me quickly down the risky, unpopular path.\"
  Micheal Bloomberg.";
myarray[1] = "\"In investing, what is comfortable is rarely profitable.\"
 Robert Arnott";
myarray[2] = "\"Know what you own, and know why you own it.\"
 Peter Lynch";
myarray[3] = "\"Buy when everyone else is selling and hold until everyone else is buying. That’s not just a catchy slogan. It’s the very essence of successful investing.\"
 J. Paul Getty";
myarray[4] = "\"When something is important enough, you do it even if the odds are not in your favor.\"
 Elon Musk";
myarray[5] = "\"I will tell you the secret to getting rich on Wall Street. You try to be greedy when others are fearful. And you try to be fearful when others are greedy.\"
 Warren Buffet";
myarray[6] = "\"Innovation distinguishes between a leader and a follower.\"
 Steve Jobs";
myarray[7] = "\"The only thing that makes sense is to strive for greater collective enlightenment.\"
 Elon Musk"
myarray[8] = "\"The single best piece of advice: Constantly think about how you could be doing things better and questioning yourself.\"
 Elon Musk "
//Quote randomizer I made.

function quote() {
    var x = Math.floor(Math.random() * (myarray.length));
    document.getElementById("quotes").innerHTML = myarray[x];

}

var myVar = setInterval(quote, 15000);

Is there a better way to write this code? I wrote it back in February of this year. Now, I am just curious if there is any way to improve it.

For those who want to see it in action, scroll down past the "meet the team" section after you click here.


texts:
I have two table. I want count how many times a value is in other table. So the codice from table "sorgente" is different in table contatore, because I have the suffix 'BRANO-' before the code.
sorgente
| codice | nome  |
|   15   | mario |
|   16   | mary  |

contatore
| nome_evento |   data     |
| BRANO-15    | 2020-08-15 |
| BRANO-15    | 2020-08-16 |
| BRANO-16    | 2020-08-14 |

the query for select is
select
    s.codice,
    (
        select count(*)
        from contatore c
        where c.nome_evento = concat('BRANO-', s.codice)
    ) no_matches_in_contatore
from sorgente s

but the original "sorgente" table has 25000 records, the "contatore" table has at now 60000 records.
when I try to execute the query it takes 600 seconds....
can you help me?


texts: Program to convert number from any base to decimal

texts:
I have made a script to convert number from any base to decimal.

I am trying to optimize the code because I think it is bloated and can be improved but if I change anything it affects error handling negatively.
I tried removing the two while loops but then the user would need to enter their number again even if they only messed up their base that is something I want to avoid.

I think printing and handling the number can be optimized but I just cannot see how. Also if anyone can help me improve my code readability that would be helpful too.

while True: #Main loop will keep the script running until user exits
    negative_flag=False #flag to check if a value is negative or not. False by default
    while True: # Loop made so that any error can be handled if input is not number
        number=input("Enter a number : ")
        try:
            if type(int(number))==int:
                break
        except:
             print("Wrong input. Only integers are allowed.")
             continue

    while True: # Loop made so that any error can be handled if input is not number
        base_from=input("Enter the base number is in : ")
        try:
            if type(int(base_from))==int and int(base_from)>=2:
                break
            else:
                print("Base should be greater than or equal to 2")
        except:
             print("Wrong input. Only integers are allowed.")
             continue

    if int(number)<0: #Check if a number is negative if it is convert it into a postive
        (number)=int(number)*-1
        negative_flag=True
    number=str(number)
 #Not useful just for reference base_to=10

    number_size=len(number)
    number_holder=0

    for x in number: #Basic conversion of a number to decimal number system.
        number_size-=1
        base_raised=int(base_from)**number_size
        number_multiplied=base_raised*int(x)
        number_holder=number_holder+number_multiplied

    if negative_flag==True: # Prints if the value is -ve
        print( number_holder*-1 )
    else:
        print(number_holder)

    while True:  # Final loop asking users if they want to exit or not
        response=input("Do you want to continue?(y or n) - ")
        if response=='n' or response=='y':
            break
        else:
            print("Wrong input")
            continue
    if response == 'n': # Conditions for only two valid answer.
        break
    elif response == 'y':
        continue


texts: Summary page with react-redux: container or presentational component

texts:
I'm building a Summary page for merchant activity in a marketplace with react and redux.

The application has already a structure where there is a "MerchantContianer"

class MerchantContainer extends Component {
  render() {
    const merchList = [];
    for(let key in this.props.merchants) {
      for(let id in this.props.merchants[key].byId) {
        let row = this.props.merchants[key].byId[id];
        merchList.push((
          <Merchant
            type={key}
            key={id}
            date={row.date}
            name={row.name}
            amount={row.amount}
            delete={() => this.props.onDeleteRow(row.id, key)} />
      ));
    }
  };
    return (

        {merchList}

    )
  }
}

const mapStateToProps = state => {
  return {
      merchants: state.list.merchants
  };
};

const mapDispatchtoProps = dispatch => {
  return {
    onDeleteRow: (id, type) => {dispatch(actions.deleteMerchantsFromList(id, type))}
  };
};

export default connect(mapStateToProps, mapDispatchtoProps)(MerchantContainer);

and a Merchant component

const Merchant = props => {
  const classArr = [classes.Merchant, classes[props.type]].join(' ');
  return (

      {props.name}
      {props.date}
      {props.amount}
      <Button click={props.delete} btnType="Delete">Delete</Button>

  )
};

export default Merchant;

In addition there is a ReviewsContainer with the same structure of MerchantContainer but for a list of reviews (with a Review container with the same structure of Merchant).

Now I want to create a Summary component

const Summary = props => {
  return (

    <MerchantContainer />
    <ReviewsContainer />

 );
}

And use a Switch Component in App.js

<Switch>
        <Route path="/merchants" component={MerchantContainer} />
        <Route path="/reviews" component={ReviewsContainer} />
        <Route path="/summary" component={Summary} />
</Switch>

It is ok to use a "dumb" component for the Summary component? Or do I have to restructure so the Summary is the only container and MerchantContainer and ReviewsContainer must work with props from Summary?

One of the other features is a Dashboard component that will include the Summary and other components (is still not defined in the requirements for this task). So this dilemma will be repeated.


texts: Find out the number under 1 million which produces the largest Collatz Sequence

texts:
So, I have written a code which calculates the number under n( 1 million in this case) which produces the largest Collatz Sequence in that range().

The problem is given in detail below:

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

My code:

def main(n):
    list = [1,2]
    for i in range(3,n):
        count = 0
        while i > len(list):
            if i % 2 == 0:
                i = i/2
            else:
                i = 3*i+1
            count += 1
        list.append(count + list[int(i)-1])
    return list.index(max(list))+1

print(main(1000000))

So, what are the ways in which I can make my code more efficient since it takes quite a lot of time to execute?


texts: testing arbitrary backend implementations dynamically using py.test parametrized tests

texts:
trying to write a bunch of tests for a program that supports loading an arbitrary backend implementation dynamically using py.test parametrized tests, and it was a bit more complicated than I expected. What I'm intending to do (and not completely achieving) is to use the list_backends method below to parametrize some tests based on the number of backend implementations that exist at runtime.
Something similar to my current implementation is below, where I copy a bunch of config files, one for each backend, to tmpdir and then basically return a particular section of the config file named after the backend:

  @pytest.fixture(scope='function')
  def backend(request):
      """Return the backend implementation class."""
      return get_backend(request.param)

  @pytest.fixture(scope='function')
  def configdir(tmpdir, request):
      """Copy all test config files to a temporary directory."""
      testdir = py.path.local(request.module.__file__).dirname
      src = testdir.join("configs")
      dest = tmpdir.join("configs").mkdir()
      for f in src.visit():
          f.copy(dest)
      return dest

  @pytest.fixture(scope='function')
  def config(configdir, request):
      """Return the appropriate config section for this test."""
      cfgfile = configdir.join(request.param)
      cfg = read_config(cfgfile)
      return cfg[request.param]

  @pytest.mark.parametrize(
S>    'backend,config', zip(*[list_backends()]*2), indirect=['backend', 'config'])
  def test_backend_with_config(backend, config):
      """Run some tests with a particular backend and config."""
      instance = backend(config)
      # test stuff

  ...

First, am I overdoing this? Second, is there a simpler way to do this kind of parameterization with py.test?


texts: Cycling through sibling elements on button click and assigning a class to the “active” element

texts:
I am attempting to do something that seems pretty simple, but I'm not sure if it as performant as it could be. I'm looking to cycle through a set of elements and toggle a class to only show a single item at a time, looping back to the first item at the end.

$(document).ready(() => {
  const toggleButton = $('.btn-toggle');
  toggleButton.on('click', function toggleButtonClick() {
    const currentItem = $(this).parent('.itemtoggle')
      .find('li:not(.d-none)').toggleClass('d-none');
    let nextItem = currentItem.next();
    if (nextItem.length === 0) {
      nextItem = currentItem.parent('.items').find('li');
    }
    nextItem.first().toggleClass('d-none');
  })
  .parent('.itemtoggle')
  .find('li')
  .toggleClass('d-none')
  .first()
  .toggleClass('d-none');
});

Full code example on Codepen

Right now it is written using jQuery. Is there a better way to do this, in jQuery, Vanilla JS, or other?


texts: Countdown number game solution v2 using itertools

texts:
I recently posted a solution for the numbers game on the Countdown TV show using a recursive technique.  For those unfarmiliar with the rules…

A fixed set of numbers (usually 6) are chosen at random
A target value is set
The player must reach the target value using some or all of the numbers from the list of 6 random numbers using only the operators +, *, - and /. The use of brackets is also permitted

I have attached a new program that uses the itertools library and for loops. As with the last code the print statement

"Eval..." means the program has used BODMAS (e.g: 1+3*10 = 31 as 10*3 = 30 and 30+1 = 31)
whereas
"Running sum..." produces a running sum of the totals (1+3*10 = 40 as 1+3 = 4, 4*10 = 40)

import itertools
import re
def unpack(method):
    string = method
    special = ["*","+","-","/"]
    list_sum = []
    list_special = []
    numbers = (re.findall(r"[\w']+", string))
    for char in string:
        if char in special:
            list_special.append(char)

    for index in range (len(numbers)-1):
        to_eval = numbers[index] + list_special[index] + numbers[index+1]
        list_sum.append(f'{to_eval} = {eval(to_eval)}')
        numbers[index+1] = str(eval(to_eval))

    return list_sum

def plus (x,y): return x+y, "+"
def minus (x,y): return x-y, "-"
def times (x,y): return x*y, "*"
def divide (x,y): return x/y, "/"

def solve():
    for numbers in list_sols:
        total = 0
        running = ""
        list_to_call = [order_ops1,order_ops2,order_ops3,order_ops4,order_ops5,order_ops6]
        for operator in list_to_call[len(numbers)-2]:
            zipped = itertools.zip_longest(numbers, operator)
            to_calculate = (list(zipped))
            running = ""
            total = 0
            for (index,item) in enumerate(to_calculate):
                if index == 0:
                    total += item[0]
                    next_operator = item[1]
                    running = str(item[0])
                else:
                    total, symbol = next_operator(total,item[0])
                    running += symbol + str(item[0])
                    if index < len(numbers)-1: next_operator = item[1]
            if eval(running)==target:
                print(f"Eval: {running}")
                break
            if total == target:
                print (f'Running sum: {unpack(running)}')
                break

def main():
    global list_sols
    global order_ops1, order_ops2, order_ops3, order_ops4, order_ops5, order_ops6
    global target

    numbers = [100,50,75,25,3,6]
    target = 952

    list_sols = []
    for number in itertools.chain.from_iterable(itertools.permutations(numbers,i) for i in range(2,7)):
        list_sols.append(list(number))

    order_ops1,order_ops2,order_ops3,order_ops4,order_ops5,order_ops6 = [],[],[],[],[],[]
    for number in itertools.chain.from_iterable(itertools.product([plus,minus,times,divide],repeat=i) for i in range(1,6)):
        if len(number) ==1: order_ops1.append(list(number))
        if len(number) ==2: order_ops2.append(list(number))
        if len(number) ==3: order_ops3.append(list(number))
        if len(number) ==4: order_ops4.append(list(number))
        if len(number) ==5: order_ops5.append(list(number))
        if len(number) ==6: order_ops6.append(list(number))

    if target in numbers:
        print (target)
        return
    else:
        solve()
        return

if __name__=="__main__":
    main()
    exit_key = input("Press any key to exit...")

```


texts: Extending the functionality of lxml.etree

texts:
I wrote a class to slightly customize the behavior of lxml.etree.ElementTree and I use it quite extensively. It works great, but there are a few methods that I'm not sure how I wrote, and there are a few other methods that seem awfully redundant. I'll elaborate on specific questions below, but first here's the code.

import lxml.etree as old_etree
from xml_utilities import clean_xml
from datetime import datetime

VERSION = 'X.X.X.X'
TOOL = 'ExampleTool'

class etree(old_etree._ElementTree):
  @staticmethod
  def parse(path):
    old_tdx = old_etree.parse(path)
    new_tdx = etree(old_tdx)
    new_tdx._setroot(old_tdx.getroot())
    return new_tdx

  @staticmethod
  def fromstring(string):
    old_tdx = old_etree.fromstring(string)
    new_tdx = etree(old_tdx.getroottree())
    new_tdx._setroot(old_tdx)
    return new_tdx

  @staticmethod
  def getISOTime():
    iso_time = datetime.now().isoformat()
    format_time = iso_time.split('.')[0] + 'Z'
    return format_time

  @staticmethod
  def SubElement(*args, **kargs):
    return old_etree.SubElement(*args, **kargs)

  @staticmethod
  def Element(*args, **kargs):
    return old_etree.Element(*args, **kargs)

  def getMetaNode(self, name, default=''):
    metas = self.findall('meta')
    for meta in metas:
      if meta.get('name') == name:
        return meta
    return old_etree.SubElement(self.getroot(), 'meta',
                                attrib={'name': name, 'value': default})

  def setMetaNode(self, name, value):
    node = self.getMetaNode(name)
    node.set('value', value)

  def write(self, path, updateTool=True):
    self.setMetaNode('saved', etree.getISOTime())

    if updateTool:
      self.setMetaNode('version', VERSION)
      self.setMetaNode('type', TOOL)

    super(etree, self).write(path)
    clean_xml(path)

The function clean_xml is custom written and largely irrelevant: It escapes troublesome characters that ElementTree.write doesn't by default (this is an issue with the file specification we use, rather than with lxml). For questions:

Is there a better way to extend the functionality of lxml.etree than inheriting from _ElementTree? Ultimately, I want to be changing the behavior of the method ElementTree.write and to add the methods ElementTree.getMetaNode and ElementTree.setMetaNode.
Is there a better way of incorporating the methods parse, fromstring, SubElement, and Element, rather than just creating thin wrappers that reference the original methods?
Does anyone understand what my methods parse and fromstring are doing? I know that my method fromstring has different functionality from lxml.etree.fromstring because I want it to return an ElementTree rather than an Element. These methods were written largely through guess-and-check (oops).
Is there a better way to write the return old_etree.SubElement(...) line so it doesn't have to take up two lines? This isn't major, but...

Originally, I tried to just overwrite lxml.etree.ElementTree.write directly, but that throws the error AttributeError: 'lxml.etree._ElementTree' object attribute 'write' is read-only. General critiques are also welcomed. I know that I should have comments in here, but everything is pretty straight-forward except for the two methods that I don't understand.

Also, I'm not sure if anyone is going to think that using the name etree in order to overwrite lxml.etree is a bad idea. The reason for this is so that I only have to change the import line at the top of any previously written file from from lxml import etree to from my_lxml import etree.


texts:
Currently, I have this and it's working for all cases:

import math
import os
import random
import re
import sys

def caesarCipher(s, k):
    st = []
    for i in range(0,len(s)):
        if 65<=ord(s[i])<=90:
            temp = ord(s[i])+k%26
            if (temp>90):
                temp-=26
            st.append(chr(temp))
        elif 97<=ord(s[i])<=122:
            temp = ord(s[i])+k%26
            if (temp>122):
                temp-=26
            st.append(chr(temp))
        else: st.append(s[i])
    return ''.join(st)

if __name__ == '__main__':

    s = input()

    k = int(input())

    result = caesarCipher(s, k)

I'm not sure if the multiple if loops reduce readability. Is there a cleaner way to do this?

Sample I/O:

Input: s = middle-Outz , k=2
Output: s = okffng-Qwvb

Input: s = Always-Look-on-the-Bright-Side-of-Life ; k=5
Output: s = Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj


texts: Best way to handle the error in async node

texts:
To catch errors, I have written if-else blocks in every function which looks bad. Please suggest a better way to handle errors in async node.

   async.waterfall([

            function(callback){

                fnOne.GetOne(req, res,function(err,result) {

                  if(err){
                    console.error("Controller : fnOne",err);
                    callback(err,null);
                  }
                  else{

                    var fnOne = result;

                   callback(null, fnOne);
                  }
                })
            },

            function(fnOne, callback){

               fnTwo.two(fnOne,function(err,result) {
                  if(err) {
                    console.error(err);
                    callback(err,null);
                  }
                  else{

                    callback(null, context);
                  }
               })
            }
        ], function (err, result) {

           if(err){
              console.error("Controller waterfall Error" , err);
              res.send("Error in serving request.");
           }
        });


texts:
Given an input N as the size of a centrifuge, I need to find out the number of balanced configurations. The full description is here.

  Centrifuge is a piece of equipment that puts multiple test tubes in rotation at very high speeds. It consists of a cylindrical rotor with holes situated evenly along the circumference of the rotor.
  Because the device is operating at high speeds, the center of mass of all tubes must coincide with the center of the rotor. We assume all tubes have the same mass.

  For the sake of simplicity, we also assume that tubes are point masses, fixed firmly to the rotor. All at the same distance from the center. You may safely assume the (x,y) coordinates of tube k are \$R\sin a, R\cos a\$, where \$a = 2\pi\frac{k}{n}\$

  The problem is: Given a centrifuge with N holes and K tubes, is it possible to balance it?

  example 1: given N = 6 possible values for K are 2,3,4,6.

  example 2: given N = 12, it is possible to balance 5 tubes: put 3 evenly dispersed (every 4th hole), then find a pair of opposite unoccupied holes and insert remaining 2 tubes there.

  example 3: given N = 10, it is impossible to balance 7 tubes: put 5 evenly dispersed, and there's no opposite unoccupied holes left!

  Input

  Line 1: An integer N for the capacity of the centrifuge.

  Output

  Line 1: An integer M for the number of different possible values of K.

This is my code:

import numpy as np

N=int(input())
angle = 2*np.pi/N
z = complex(np.cos(angle), np.sin(angle))

import itertools
combs = []
lst = range(1,N)
for i in range(2, N-1):
    combs.append(i)
    els = [list(x) for x in itertools.combinations(lst, i)]
    combs.append(els)

count=1
lis = []
while count<=len(combs):
    for a in range(len(combs[count])):
        s=0
        for b in range(len(combs[count][a])):
            s+=z**combs[count][a][b]
        if abs(s)<1e-10:
            lis.append(combs[count][a])
    count+=2

lengths = []
for i in lis:
    if len(i) not in lengths:
        lengths.append(len(i))

print(len(lengths)+1)

The code works fine, but slows down after input size of above 20, and is practically unusable after the input grows to 50 or above, due to the for loops. How do I optimize it?


texts: Multiple independent or layered constructors for TicTacToe?

texts:
At first it was like this:

public abstract class TicTacToeViewAbstract implements TicTacToeView {
    private final List<OnCellClickListener> onCellClickListeners;
    private boolean movesBlocked;
    private boolean gameFinished;
    private TicTacToeModel model;

    protected TicTacToeViewAbstract(TicTacToeModel model) {
        onCellClickListeners = new ArrayList<OnCellClickListener>();
        gameFinished = false;
        movesBlocked = false;
        plugModel(model);
    }

    protected TicTacToeViewAbstract(TicTacToeModel model, TicTacToeViewAbstract toRestore) {
        this.onCellClickListeners = toRestore.onCellClickListeners;
        this.gameFinished = toRestore.gameFinished;
        this.movesBlocked = toRestore.movesBlocked;
        this.plugModel(model);
        toRestore.unplugModel();
    }
    // other methods ...
}

Then I tried to remove duplication in both constructors:

public abstract class TicTacToeViewAbstract implements TicTacToeView {
    private final List<OnCellClickListener> onCellClickListeners;
    private boolean gameFinished;
    private boolean movesBlocked;
    private TicTacToeModel model;

    private TicTacToeViewAbstract(List<OnCellClickListener> onCellClickListeners,
                    boolean gameFinished, boolean movesBlocked, TicTacToeModel model) {
        this.onCellClickListeners = onCellClickListeners;
        this.gameFinished = gameFinished;
        this.movesBlocked = movesBlocked;
        this.plugModel(model);
    }

    protected TicTacToeViewAbstract(TicTacToeModel model) {
        this(new ArrayList<OnCellClickListener>(),
             false, false, model);
    }

    protected TicTacToeViewAbstract(TicTacToeModel model, TicTacToeViewAbstract toRestore) {
        this(toRestore.onCellClickListeners,
             toRestore.gameFinished, toRestore.movesBlocked, model);
        toRestore.unplugModel();
    }
    // ...
}

Which one looks better, and why?


texts: Is it ok to use HttpContext inside View?

texts:
I have a pretty common issue: I need to know the name of current user and also name of the current controller so I can highlight/disable some links.

Here's some solutions I found by myself:

Get all what's needed inside PartialView.

I have a PartialView inside my page layout, that takes user name like this:

@{ var userName = Context.ToContext().GetUser<Agent>().Name; }

And here's the way I take controller name:

@{ var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString(); }

I have some problem with this code, for it is suspected to ruin MVC pattern.  I have another solution, which I consider even more stupid.

I've created new controller called like ContextController:

public class ContextController : BaseController // BaseController is just a facade
{
    public string GetUserName() {
        return Context.GetUser<Agent>().Name;
    }
}

Here's the problem: I cannot get controller name with this way, because it will always be like "Context", which is useless for me. And I also get the name on view like this:

@{ var userName = Html.Action("GetUserName", "Context"); }

The last way I figured out is to pass needed strings through ViewData. But I have about 18 controllers and some of 'em have like 3 methods, returning ViewResult. It's not bad design, it's just reality. And I don't actually want to create and pass ViewDataDictionary for every single method, that returns ViewResult. Maybe I could extend my BaseController, so ViewDataDictionary for every page will always have userName and controllerName?

But here comes another problem: I have whole lot of AJAX in my project, and it seems to me not legit enough to pass unused data every time controller action is called.

If you know of a better solution, I'd be happy to hear it.


texts: Maximum Subarray Problem - Recursive O(n log n) algorithm

texts:
I have implemented a recursive O(n log n) algorithm for solving the maximum sub-array problem. I would like a general review for it.

Here the max_subarray is the main function, and the static one is the auxillary function for it.

#include<stdio.h>

int max_subarray(int array[], int *low, int *high);

static int max_crossing_subarray(int array[], int *low, int mid, int *high);

int main()
{
    //The maximum subarray-sum is 43 for the following
    int array[16] = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
    int low = 0;
    int high = 15;

    printf("%d", max_subarray(array, &low, &high));
    printf("\n%d %d", low, high);

    return 0;
}

int max_subarray(int array[], int *low, int *high)
{
    if (*low == *high) {
        return array[*low];
    } else {
        //Don't change avoids overflow
        int mid = *low + (*high - *low)/2;

        int left_low = *low;
        int left_high = mid;
        int left_sum = max_subarray(array, &left_low, &left_high);

        int right_low = mid + 1;
        int right_high = *high;
        int right_sum = max_subarray(array, &right_low, &right_high);

        int cross_low = *low;
        int cross_high = *high;
        int cross_sum = max_crossing_subarray(array, &cross_low, mid, &cross_high);

        if (left_sum >= right_sum && left_sum >= cross_sum)
        {
            *low = left_low;
            *high = left_high;
            return left_sum;

        } else if (right_sum >= left_sum && right_sum >= cross_sum) {
            *low = right_low;
            *high = right_high;
            return right_sum;

        } else {
            *low = cross_low;
            *high = cross_high;
            return cross_sum;
        }
    }
}

static int max_crossing_subarray(int array[], int *low, int mid, int *high)
{
    int left_sum = 0;
    int max_left = mid;
    for (int i = mid, sum = 0; i >= *low; i--) {
        sum += array[i];
        if (sum > left_sum) {
            left_sum = sum;
            max_left = i;
        }
    }

    int right_sum = 0;
    int max_right = mid;
    for (int i = mid + 1, sum = 0; i <= *high; i++) {
        sum += array[i];
        if (sum > right_sum) {
            right_sum = sum;
            max_right = i;
        }
    }

    *low = max_left;
    *high = max_right;
    return left_sum + right_sum;
}


texts:
I'm working on a game in JavaScript and I'm trying to generate rooms in a map.  For this example, the map is 32 by 24 (each tile is 32 by 32 pixels).

A room is made up of a collection of tiles.  A room is always in a square or rectangle shape.  For example, 16,16,8,8 would make a room that draws from the top left corner at 16 by 16 and the bottom right corner at 24 by 24.

How the algorithm works:

pick a random x,y, width and height for the room
check if these points collide with another room
if it fails repeat points 1 and 2 (it will only repeat problems 1 and 2 1000 times before finally giving up and deciding it can't fit any more rooms in)

This is done by this code here:

    //make sure a room doesn't clash here
    while (maxTrys > 0) {
        var x = randomValue(2, tileX - MAXROOMSIZE); //starting top left corner tile's x position
        var y = randomValue(2, tileY - MAXROOMSIZE);//starting top left corner tile's y position

        var width = randomValue(MINROOMSIZE, MAXROOMSIZE); //width of room in tiles sqaures e.g 3 = 96 pixels
        var height = randomValue(MINROOMSIZE, MAXROOMSIZE);//height of room in tiles e.g 3 = 96 pixels

       if (locationIsFine(x, y, width, height) == true) { //if we've found a location we're happy with
           roomStore.push(createRoom(i, x, y, width, height));
            break;
        }
        maxTrys--;
    }

How it checks if a point collides with another room:

generate a room with the randomly created x,y,width and height cordinates
check if any point in this "temp room" collides with any point of any other room
if it does we know there is a collision

The code for this is the following:

var locationIsFine = function(x, y, width, height) {
    //turn the cordinates into a fake room
    var tempTiles = new Array();

    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            tempTiles.push(new tile(tileset,x+ j,y + i,0,null,ScreenManager));
        }
    }

    //make sure room wont hit any other rooms, we do this by checking if edges of a room collide with an exisiting room
    for (var i = 0; i < roomStore.length; i++) {
        for (var j = 0; j < tempTiles.length; j++) {
            if (roomStore[i].intersects(tempTiles[j].getX(), tempTiles[j].getY()) == true) {
                return false;
            }
        }
    }
    return true;
}

The intersects method looks like this:

this.intersects = function (x,y) {

    /* find the biggest and smallest points in the room*/
    for (var i = 0; i < tiles.length; i++) {
        if (tiles[i].getX() == x && tiles[i].getY() == y) {
            return true;
        }
    }
    return false;
}

My problem with this is that it is really really slow.  After running it a few times, it can take 5-8 seconds to generate the rooms and normally it gives up after the 5th room.  I am 100% sure the bottleneck is coming from this code as if I set maxTrys to a smaller number, the program runs quicker.


texts:
A few days ago I've faced an annoying problem.
Let's imagine we have 3 classes: Base, System, Handler.

The classes Systen and Handler both inherit from the class Base.
I want to access those classes this way: System::DoStuff();
I also need the Handler be available in the System, but do not want to instantiate it there, use any kind of reference injection.

I could simply design the System and the Handler class to be static. The problem would be:
They need to inherit form the Base class, which should be static too, because if it's not, it won't work with the System and Hanlder because they ARE static. If is set Base to static, it won't work either, because once a child changes some parameter in it's parent, the parent would change for ALL children.

After some testing, I've came up with this solution:

class Wire
{
    //List of classes I'll have to load
    private static $load = array("Foo", "Hello");

    //Template of the Bootstrap class
    private static $template = NULL;

    //Wire everything up
    public function Up()
    {
            //Get the bootstrap template
        self::GetTemplate();

            //Get each class
        foreach(self::$load as $class)
        {
                    //Load it...
            require_once "./class/" . $class . ".php";

                    //Build the static shell
            $bootstrap = str_replace("%CLASS%", $class, self::$template);
            eval($bootstrap);
        }
    }

    //Get the tempalte of the bootstrap class
    private function GetTemplate()
    {
        if(self::$template === NULL)
        {
                    //I've stored it in a separate file
            self::$template = file_get_contents("./class/Bootstrap.php");
        }
    }
}

Wire::Up();

I'me using the Wire class to load the classes I need. And use this Bootstrap file to create a static shell for each instatiated class.

//This is the Bootstrap class
//It offers a static shell for other instatiated classes
class %CLASS%
{
    public static $instance = NULL;
    public function __callStatic($method, $arguments)
    {
        if(self::$instance === NULL)
        {
            $class = get_called_class() . "Controller";
            self::$instance = new $class();
        }
        call_user_func_array(array(self::$instance, $method), $arguments);
    }
}

That's the Base class, for testing purpouses only

class Base
{
    public $value = 1;
}

Here are the classes Foo and Hello that I've used above

class FooController extends Base
{
    public function Bar($args)
    {
        print $args . " " . $this->value . "
";
    }
}

class HelloController extends Base
{
    public function World($args)
    {
        $this->value = 10;
        print $args . " " . $this->value . "
";
    }
}

Now, if you call

Hello::World("Hello World") //Hello World 10
Foo::Bar("Foo Bar") //Foo Bar 1
//If Foo and Base would be static, whitout the Bootstrap shell, you would see "Foo Bar 10"

What do you think about that solution? Am I hunting a mouse with a shotgun? Or maybe there are better solutions, for this scenario? I'd appreciate costructive critics!!


texts:
I am working on wavelet decomposition and found a formula for it and wrote it by myself for computation.

The formula is:

$$I_{LH}(i,j) = \sum_{p=1}^{N_L} \sum_{q=1}^{N_H}\ L(p)\ H(q)\ I(i+p, j+q)$$

This is LH filtered and I do it for LL, LH, HL and HH so i get 4 images.

Can someone check the for loop in it and help me improve the computation time of it?

Elapsed time is 10.040462 seconds. I want to reduce time as much as possible as I need to work on hundreds of images.

%   Wavelet Decomposition
%Decomposition wavelet 'coif1' filters
[Lo_D,Hi_D] = wfilters('coif1','d');
img = imread('tumor-1.jpg');
img=  im2double(img);
figure, imshow(img), title('original image');
[nrows ncols] = size(img);
imgg = zeros(nrows+6,ncols+6);
imgg(1:nrows,1:ncols) = img(:,:);
figure, imshow(imgg);

% wavelet decomposition.
imgD_LL = zeros(size(img));
imgD_LH = zeros(size(img));
imgD_HL = zeros(size(img));
imgD_HH = zeros(size(img));

% Deconstruction
tic
for i = 1: nrows
    for j = 1:ncols
        for p = 1:numel(Lo_D)
            for q = 1:numel(Hi_D)
                tempqD_LL(q) = Lo_D(p)*Lo_D(q)*imgg(i+p,j+q);
                tempqD_LH(q) = Lo_D(p)*Hi_D(q)*imgg(i+p,j+q);
                tempqD_HL(q) = Hi_D(p)*Lo_D(q)*imgg(i+p,j+q);
                tempqD_HH(q) = Hi_D(p)*Hi_D(q)*imgg(i+p,j+q);
            end
            if (length(tempqD_LL) == q)
                tempQD_LL(p) = sum(tempqD_LL);
                tempQD_LH(p) = sum(tempqD_LH);
                tempQD_HL(p) = sum(tempqD_HL);
                tempQD_HH(p) = sum(tempqD_HH);
            end

        end
        if (length(tempQD_LL) == p )
            imgD_LL(i,j) = sum(tempQD_LL);
            imgD_LH(i,j) = sum(tempQD_LH);
            imgD_HL(i,j) = sum(tempQD_HL);
            imgD_HH(i,j) = sum(tempQD_HH);
        end
    end
end
toc
% Plots Deconstruction..
figure,
subplot(2,2,1), imshow(imgD_LL, [min(min(imgD_LL)) max(max(imgD_LL))]), title('Img Deconstruction - LL filter');
subplot(2,2,2), imshow(imgD_LH, [min(min(imgD_LH)) max(max(imgD_LH))]); title('Img Deconstruction - LH filter');
subplot(2,2,3), imshow(imgD_HL, [min(min(imgD_HL)) max(max(imgD_HL))]); title('Img Deconstruction - HL filter');
subplot(2,2,4), imshow(imgD_HH, [min(min(imgD_HH)) max(max(imgD_HH))]); title('Img Deconstruction - HH filter');

The image i used for above is :


texts:
I'm trying to write a minor lib that would enable me to measure average time measured when using struct timespec. Since C doesn't allow operator overloading, I'm forced to build functions. I am aware that checks like end_time < start_time are not done, but I've left them out to achieve some kind of shortness in the code. The accuracy of the calculations is primary goal.
enum { NS_PER_SECOND = 1000000000L };
enum { MAX_NS = 999999999 };

// t1 --> start time
// t2 --> end time
// set t1 and t2 by:
//        clock_gettime(CLOCK_REALTIME, &t1);
struct timespec get_timespec_diff(const struct timespec t1, const struct timespec t2)
{
    struct timespec t;

    t.tv_nsec = t2.tv_nsec - t1.tv_nsec;
    t.tv_sec  = t2.tv_sec - t1.tv_sec;

    if (t.tv_sec > 0 && t.tv_nsec < 0) {
        t.tv_nsec += NS_PER_SECOND;
        t.tv_sec--;
    } else if (t.tv_sec < 0 && t.tv_nsec > 0) {
        t.tv_nsec -= NS_PER_SECOND;
        t.tv_sec++;
    }

    return t;
}

struct timespec timespec_add(const struct timespec t1, const struct timespec t2) {

    unsigned int total_ns   = t1.tv_nsec + t2.tv_nsec;
    unsigned int total_s    = t1.tv_sec  + t2.tv_sec;

    while(total_ns > MAX_NS) {
        total_ns -= (unsigned)(MAX_NS + 1);
        total_s++;
    }

    struct timespec ret;
    ret.tv_sec  = total_s;
    ret.tv_nsec = total_ns;

    return ret;
}

struct timespec timespec_avg(const struct timespec t, const unsigned n) {

    struct timespec ret;
    ret.tv_sec  = 0;
    ret.tv_nsec = 0;

    unsigned int total_ns = t.tv_nsec + (t.tv_sec * (MAX_NS+1));
    unsigned int avg_ns = total_ns/n;

    while(avg_ns > MAX_NS) {
        ret.tv_sec++;
        avg_ns /= 10;
    }
    ret.tv_nsec = avg_ns;

    return ret;
}


texts:
I've followed the steps from this video from railscasts for setting ENV variables.

This is my configuration:

config/database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: <%= ENV['DATABASE_USERNAME'] %>
  password: <%= ENV['DATABASE_PASSWORD'] %>
  socket: /var/run/mysqld/mysqld.sock

development:
  <<: *default
database: <%= ENV['DATABASE_NAME'] %>
test:
  <<: *default
database: <%= ENV['DATABASE_NAME'] %>
production:
  <<: *default
  database: <%= ENV['DATABASE_NAME'] %>
  username: <%= ENV['DATABASE_USERNAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>

config/application.rb

config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
config.merge! config.fetch(Rails.env, {})
config.each do |key, value|
    ENV[key] = value.to_s unless value.kind_of? Hash
end

config/application.yml

development:

  DATABASE_USERNAME: "username goes here"
  DATABASE_PASSWORD: "password goes here"
  DATABASE_NAME: "database name goes here"

  SECRET_KEY_BASE: "secret key goes here"

test:

  DATABASE_USERNAME: "username goes here"
  DATABASE_PASSWORD: "password goes here"
  DATABASE_NAME: "database name goes here"

  SECRET_KEY_BASE: "secret key goes here"

production:

  DATABASE_USERNAME: "username goes here"
  DATABASE_PASSWORD: "password goes here"
  DATABASE_NAME: "database name goes here"

  SECRET_KEY_BASE: "secret key goes here"

Does this configuration follow best practices, or need some changes?


texts:
The first part of code is for me very unreadable. I tried to write in another way but I'm open to your suggestion!

return ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value != null && ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)) ? "" : " ";

//Looks in a dictionary for a key called parameterName
    ModelState modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value;
    //If I could find it I look for any error associatd to that and I return it as a single string
    return modelState != null && modelState.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)) ? "" : " ";


texts: Stable-sorting all even numbers before odd numbers in a linked list

texts:
Given a Linked List of integers, write a function to modify the linked
  list such that all even numbers appear before all the odd numbers in
  the modified linked list. Also, keep the order of even and odd
  numbers same. - (from geeksforgeeks: Segregate even and odd nodes in a Linked List)

  Example:

  Input:

3
7
17 15 8 9 2 4 6
4
1 3 5 7
7
8 12 10 5 4 1 6

  Output:

8 2 4 6 17 15 9
1 3 5 7
8 12 10 4 6 5 1

My Approach: get pointer to the last node of list. And then traverse the list starting from the head node and move the odd valued nodes from their current position to end of the list.Also if all the node's data is even or odd then list remains unmodified so first I check if this is the case then I simply return(len is total number of nodes & count is total number of even data nodes).

I am getting right answer on an IDE, but on other IDE where the code needs to be submitted, it's showing time limit exceeded.

How do I optimize my code?

#include <iostream>
using namespace std;
int flag=0;
struct Node{
    int data;
    Node* next;
};
void addkey(struct Node** head_ref,int key)
{struct Node* temp=(struct Node*)malloc(sizeof(Node));
temp->next=NULL;
temp->data=key;
    if(*head_ref==NULL)
    {
      *head_ref=temp;
    }
    else
    {
        struct Node* ptr=*head_ref;
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        ptr->next=temp;
    }
}
void segregate(struct Node**head_ref)
{   int len=0,count=0;
    struct Node* ptr1=*head_ref;
    struct Node* ptr2=*head_ref;
    struct Node* prev=NULL;
    while(ptr2->next!=NULL)
    {
        if((ptr2->data)%2==0) count++;
        ptr2=ptr2->next;
        len++;
    }
    if(ptr2->data%2==0)  count++;
    if(count==len+1||count==0)  return;
    struct Node* ptr5=ptr2;
    while(ptr1!=ptr5->next)
    {
        if((ptr1->data%2)==0)
        { if(flag==0) {
        *head_ref=ptr1;
        flag=1;}
            prev=ptr1;
            ptr1=ptr1->next;
        }
        else
        {
          if(prev!=NULL)  prev->next=ptr1->next;
            ptr2->next=ptr1;
            ptr2=ptr2->next;
            ptr1=ptr1->next;
            ptr2->next=NULL;
        }
    }
}
void printlist(struct Node* head)
{
    if(head==NULL) return;
    else
    {
        while(head!=NULL)
        {
            cout<<head->data<<" ";
            head=head->next;
        }
    }
}
int main() {
    int T ;
    cin>>T;
    while(T--)
    {
        int n;
        cin>>n;
        struct Node* head=(struct Node*)malloc(sizeof(Node));
        head=NULL;
        for(int i=0;i<n;i++)
        {int key;
         cin>>key;
         addkey(&head,key);
        }
        segregate(&head);
        printlist(head);cout<<"\n";
    }
    return 0;
}


texts:
I have used reflection for divide the complex property. For example, if I bind A.B[0], CustomerName means CustomerName is returned. Can anyone help to reduce the code?

var itemproperties = view.GetItemProperties();

if (itemproperties != null)
{
    if (propName.Contains("."))
    {
        string actualproperty = propName;
        string[] propertyNameList = propName.Split('.');
        int complexPropertyCount = propertyNameList.Count(), index = 0;
        bool isArrayproperty = actualproperty.IndexOf('[') != -1;

        if (isArrayproperty)
        {
            string strindex = actualproperty.Substring(actualproperty.IndexOf('[') + 1, actualproperty.IndexOf(']') - actualproperty.IndexOf('[') - 1);
            index = Convert.ToInt32(strindex);
            string property = actualproperty.Substring(0, actualproperty.IndexOf('['));
            for (int i = 0; i < propertyNameList.Length; i++)
            {
                if (propertyNameList[i].Contains('['))
                {
                    if (property.Contains("."))
                        property = propertyNameList[i].Substring(0, propertyNameList[i].IndexOf('['));
                    propertyNameList[i] = property;
                    break;
                }
            }
        }

        for (int iterator = 0; iterator < complexPropertyCount - 1; iterator++)
        {
            var tempProperyDescriptor = itemproperties.Find(propertyNameList[iterator], true);
            if (tempProperyDescriptor != null)       // Fix for SD 8318
            {
                record = tempProperyDescriptor.GetValue(record);
                itemproperties = TypeDescriptor.GetProperties(record);
            }
        }

        actualproperty = propertyNameList[complexPropertyCount - 1];

        if (isArrayproperty)
        {
            IList arrayList = ((IEnumerable)record) as IList;

            foreach (var item in arrayList)
            {
                var propertyInfo = item.GetType().GetProperty(actualproperty);

                if (propertyInfo == null)
                    return null;
                if (arrayList.IndexOf(item) == index)
                {
                    return propertyInfo.GetValue(item, null);
                }
            }
            return null;
        }

        var propertyinfo = record.GetType().GetProperty(actualproperty);

        if (propertyinfo == null && view is CollectionViewAdv)
        {
            var sourceType = (view as CollectionViewAdv).SourceType;
            if (sourceType != null && typeof(ICustomTypeDescriptor).IsAssignableFrom(sourceType))
                return itemproperties.Find(actualproperty, true).GetValue(record);
            return null;
        }

        if (!itemaccessor.ContainsKey(propName))
        {
            PropertyAccessor accessor = new PropertyAccessor(propertyinfo);
            itemaccessor.Add(propName, accessor);
            var val = accessor.GetValue(record);
            return val;
        }
    }

    if (record == null)
        return null;
    return itemaccessor[propName].GetValue(record);
}

return null;


texts: Parsing different categories using Scrapy from a webpage

texts:
I've written a script in Python Scrapy to parse different "model", "country" and "year" of various bikes from a webpage. There are several subcategories to track to reach the target page to scrape the required info.
The below scraper first starts from the main page then track each links within class art-indexhmenu then going to one layer deep it again tracks the links within class niveau2 then again follow the links within class niveau3 then tracking the links within class art-indexbutton-wrapper it reaches the target page. Then it scrapes "model", "country" and "years" of each products.
My scraper is doing its job errorlessly. However, although it is working nice, the way I've created this scraper is very repetitive to look at. As there are always room for improvement, I suppose there should be any way to make it more robust by getting rid of banality.
This is the spider (website included):
import scrapy
from scrapy.spiders import CrawlSpider
from scrapy.http.request import Request
from scrapy.crawler import CrawlerProcess

class BikePartsSpider(scrapy.Spider):
    name = 'honda'

    def start_requests(self):
        yield Request(url = "https://www.bike-parts-honda.com/", callback = self.parse_links)

    def parse_links(self, response):
        for link in response.css('.art-indexhmenu a::attr(href)').extract():
            yield response.follow(link, callback = self.parse_inner_links) #going to one layer deep from landing page

    def parse_inner_links(self, response):
        for link in response.css('.niveau2 .art-indexbutton::attr(href)').extract():
            yield response.follow(link, callback = self.parse_cat_links) # digging deep to go another layer

    def parse_cat_links(self, response):
        for link in response.css('.niveau3 .art-indexbutton::attr(href)').extract():
            yield response.follow(link, callback = self.parse_target_links) ## go inside another layer

    def parse_target_links(self, response):
        for link in response.css('.art-indexbutton-wrapper .art-indexbutton::attr(href)').extract():
            yield response.follow(link, callback = self.parse_docs) # tracking links leading to the target page

    def parse_docs(self, response):
        items = [item for item in response.css('.titre_12_red::text').extract()]
        yield {"categories":items} #this is where the scraper parses the info

c = CrawlerProcess({               #using CrawlerProcess() method to be able to run from the IDE
    'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(BikePartsSpider)
c.start()


texts: Change UI display order of an ObservableCollection

texts:
I have an ObservableCollection that is filled with custom elements of type Video runtime. These have the properties of Name, Rating and Number of Viewers.
I want to display the Video elements in different orders based on whichever of the three criteria the user chooses during Application Runtime. I created the following Enum to store the possible choices:

public enum OrderBy
{
    [Description("Video Name")]
    Name = 0,

    [Description("Video Rating")]
    Rating = 1,

    [Description("Number of Viewers")]
    ViewerNumber = 2
}

These are fed into a ComboBox called OrderCombo allowing the user to change the order criteria (I'm displaying the Description to the user):

foreach (var item in Enum.GetValues(typeof(OrderBy)))
{
    OrderCombo.Items.Add(((OrderBy)item).GetDescription());
}

To avoid sorting, I used LINQ to get the order and I came up with the following:

IOrderedEnumerable<Video> GetOrder()
    {
        switch (OrderCombo.SelectedIndex)
        {

            case 0:
                return videos.OrderBy(x => x.Name);

            case 1:
                return videos.OrderByDescending(x => x.Rating);

            case 2:
                return videos.OrderByDescending(x => x.NumberOfViewers);

        }
        return videos.OrderBy(x => x.Name);
    }

Then, I call this function every time a new element is added or an element is delelted or the user changes the order:

VideoUIElment.ItemsSource = GetOrder();

So basically I keep re-calculating the enumerable every time, which workswpf but I'm wondering if there is a more efficient/elegant way of doing this.
Maybe store the order in one or several Func<>s? I tried them, but they can only be of a (compile-time) fixed type as in Func<Video, string> for Name and I would rather avoid using implementations like Func<Video, dynamic>.


texts:
This is a HackerEarth Challenge Problem.

  Question:
  Puchi hates to carry luggage, but unfortunately he got a job to carry
  the luggage of his N friends in office. Each day, one of his N
  friends, gives him the luggage of a particular weight to carry. You
  will be given the weight of luggage of each friend in the array
  Weight, where Weighti is the weight of luggage of ith friend carried
  by Puchi on ith day. It is given that all the luggages carried by
  Puchi are distinct in their weights. As Prateek assigned this job to
  Puchi, so for each day, he wants to know the number of days in future
  when Puchi will have to carry the luggage , having weight less than
  the weight of luggage of current day. Please help Prateek for the
  same.

  Input:
   The first line contains a single integer T, denoting the number of test cases. In each test case, the following input will be
  present: First line contains an integer N, where N represents the
  number of friends. Next N line contains N integers, where ith line
  contains ith integer, which represents Weighti.

  Output:
     Output exactly T lines. Each line contains N integer separated by a space, where ith integer represents the number of
  luggage of future, which are less than the weight of luggage of the
  current day.

  Constraints:

  Subtask 1:   1 <= T <= 30 1<= N <= 104 1<= Weighti <= 106

  Subtask 2:   1 <= T <= 10 1<= N <= 105 1<= Weighti <= 106

I have used merge sort to calculate the inversions:

public class Puchi_and_Luggage {
static long invfreq[]=new long[1000001];

    public static void main(String[] args) throws NumberFormatException, IOException {

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int T=Integer.parseInt(br.readLine().trim());
        while(T-->0)
        {
          int N=Integer.parseInt(br.readLine().trim());
          StringBuilder ans=new StringBuilder();

          int arr[]=new int[N];
          int copy[]=new int[N];
          for(int i=0;i<N;i++)
          {
              arr[i]=Integer.parseInt(br.readLine().trim());
              copy[i]=arr[i];
              invfreq[arr[i]]=0l;
          }

          mergesort(arr,0,N-1);
          for(int i=0;i<N;i++)
          {
            ans.append(invfreq[copy[i]]+" ");
          }
          System.out.println(ans);
        }

    }

    private static void mergesort(int[] arr, int i, int j) {

        int mid=0;

        if(i<j)
        {
            mid=(i+j)/2;
            mergesort(arr,i,mid);
            mergesort(arr,mid+1,j);
            merge(arr,i,mid,j);

        }

    }

    private static void merge(int[] arr, int i, int mid, int j) {

        int temp[]=new int[arr.length];
        int l=i;
        int r=j;
        int m=mid+1;
        int k=l;
        long inv=0l;
        while(l<=mid && m<=r)
        {
            if(arr[l]<=arr[m])
            {
                temp[k]=arr[l];
                invfreq[temp[k]]+=inv;
                k++;
                l++;
            }
            else
            {
                temp[k]=arr[m];
                k++;
                m++;
                inv++;

            }

        }
        while(l<=mid){
            temp[k]=arr[l];
            invfreq[temp[k]]+=inv;
            k++;
            l++;
        }
        while(m<=r){
            temp[k]=arr[m];
            k++;
            m++;
        }

        for(int i1=i;i1<=j;i1++){
            arr[i1]=temp[i1];
            //System.out.print(arr[i1]+" ");
        }

    }

}

But my code is giving Time Limit Exceeded for test cases with large input files.


texts: Loop through a list of URLs multi-threading and check return code in python

texts:
I have to loop through a list of over 4000 urls and check their http return code in python.

Url.txt: Contains a list of 4000 urls with one url per line.

The script takes a long time to run and I wanted to incorporate multi-threading to improve speed but not sure if I have done it properly.

It sure doesn't seem like it is working fast enough.

#! /usr/bin/python

# To just check a site and get the URL code
#import urllib.request
#print(urllib.request.urlopen("http://www.stackoverflow.com").getcode())
#############################################################################

import time
import requests

start = time.time()

from multiprocessing.dummy import Pool
pool = Pool(8) # Number of concurrent threads

#input file
URLS = open("url.txt","r")

#output file
file = open('output.csv', 'w')

#############################################################################

GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'

def main():
    with open('url.txt') as f:

        url = f.read().splitlines()
        print( "\nTesting URLs.", time.ctime())

        all_text = pool.map(checkUrls,url)
        print("closing p")
        pool.close()
        pool.join()
            #checkUrls()
        print("Press CTRL+C to exit")
        #I don't need this sleep any longer. Can I remove the next line?
        time.sleep(100000) #Sleep 10 seconds

def checkUrls(url):
    count = 0
    status = "N/A"
    try:
        status = checkUrl(url)
    except requests.exceptions.ConnectionError:
        status = "DOWN"
    except requests.exceptions.HTTPError:
        status = "HttpError"
    except requests.exceptions.ProxyError:
        status = "ProxyError"
    except requests.exceptions.Timeout:
        status = "TimeoutError"
    except requests.exceptions.ConnectTimeout:
        status = "connectTimeout"
    except requests.exceptions.ReadTimeout:
        status = "ReadTimeout"
    except requests.exceptions.TooManyRedirects:
        status = "TooManyRedirects"
    except requests.exceptions.MissingSchema:
        status = "MissingSchema"
    except requests.exceptions.InvalidURL:
        status = "InvalidURL"
    except requests.exceptions.InvalidHeader:
        status = "InvalidHeader"
    except requests.exceptions.URLRequired:
        status = "URLmissing"
    except requests.exceptions.InvalidProxyURL:
        status = "InvalidProxy"
    except requests.exceptions.RetryError:
        status = "RetryError"
    except requests.exceptions.InvalidSchema:
        status = "InvalidSchema"

    printStatus(url, status, count)

    count+=1
    time_elapsed = datetime.now() - start_time

def checkUrl(url):
    r = requests.get(url, timeout=5)
    #print r.status_code
    return str(r.status_code)

def printStatus(url, status, count):
    color = GREEN

    count= count+1
    if status != "200":
        color=RED

    #print(color+status+ENDC+' '+ url)
    print(str(count)+'\t' + color+status+ENDC+' '+ url)
    file.write(str(count)+'\t' + color+status+ENDC+' '+ url +'\n')

    #print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))

end = time.time()
print(end - start)

# Main app
#
if __name__ == '__main__':
    main()


texts: Searching files in a directory for a string

texts:
I have the following static class that enumerates directories in a folder, then searches each file in the folder (it seems to only work with text files even thought I don't explicitly specify that) for a given string and returns an IEnumerable that holds the results.

It takes about 15 seconds to go through 40 text files that are about 250kb in size and I think it could be faster. Could I use a better algorithm, or is there a better method of achieving this?

public static class LogFileReader
{
    public static IEnumerable<string> GetLines(string path, string searchterm)
    {

        var dirs = Directory.EnumerateDirectories(path);
        List<string> thelines = new List<string>();

        foreach (var dir in dirs)
        {

            var files = Directory.EnumerateFiles(dir);

            foreach (var file in files)
            {
                using (StreamReader sr = new StreamReader(file))
                {
                    string line = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.IndexOf(searchterm, StringComparison.CurrentCultureIgnoreCase) >= 0)
                        {
                            thelines.Add(line);
                        }
                    }

                }
            }

        }

        return thelines;
    }
}


texts:
I am writing code that has objects having integer member variables where the integer value has a specific constant meaning, which normally means "use an enum".

Suppose the values are the days of the week, Monday = 0, Tuesday = 1, and so on.  (In my real case, there are several different "types" involved, some of which have 10-20 possible values.)

The code uses data objects which are auto-generated, and these data objects can only have certain, already specified types (int, string, bool, double), otherwise they could just use enums themselves.  The question is, should I use an enum, or a struct with static readonly definitions and implicit casting.  I favor the struct version.

Here is an example of using an enum:

enum Days
{
    Monday = 0,
    Tuesday = 1,
    Wednesday = 2,
    Thursday = 3,
    Friday = 4,
    Saturday = 5,
    Sunday = 6,
}

And here is my preferred struct code:

struct Day
{
    readonly int day;

    public Day(int day)
    {
        this.day = day;
    }
    public static implicit operator int(Day value)
    {
        return value.day;
    }
    public static implicit operator Day(int value)
    {
        return new Day(value);
    }

    public static readonly Day Monday = 0;
    public static readonly Day Tuesday = 1;
    public static readonly Day Wednesday = 2;
    public static readonly Day Thursday = 3;
    public static readonly Day Friday = 4;
    public static readonly Day Saturday = 5;
    public static readonly Day Sunday = 6;
}

My code frequently involves assigning values to the members of the data object.  This means if I use the struct version, I can say for example Day myDay = dataObject.Day rather than Days myDay = (Days)dataObject.Day.  With the amount of logic code that will be affected by this, I think the struct version is a win for readability because it removes a lot of explicit casts.

I don't want to just use plain ints in my code because I like function signatures that indicate the purpose of the "int" being passed or returned.  But I don't want the messiness that comes from casting enums all over.

I'm asking for arguments against the struct version.  Would it disgust you if you found this pattern in code somewhere?

Clarification:

For the data objects to allow user types, other code which depends on the data objects would have to know about these types.  The two "areas" of code are logically separate, and do not reference each other at all.  I suppose a middle layer that separates the data objects from my code would be possible, but since all it would do is convert the enums to ints and back, it would be an awful lot of code to accomplish very little.

Another reason that these values sometimes must be represented as integers is that they are put through arithmetic operations sometimes.  This is another place where explicit casting just gets annoying.

Finally, the definition of the possible values (days of week, in this example) is far less likely to change than the logic code.  So conciseness and readability in the definition code isn't as valuable as in the logic code.


texts:
I'm still new to programming and I'm not confident about this code. I recently created this File Organizer that organizes files in folders based on their extensions. How can I make this code cleaner?

# File Organizer - organizes file in folders based on their extensions.
# 03/05/2020

import shutil, os

root_path = "C:\\YourDesiredPath"
os.chdir(root_path)
dirfiles = os.listdir(root_path)

class FileOrganizer():

    # store extensions and folder names
    mydir = {}

    def name_folder(self):
        for file in dirfiles:
            ext = os.path.splitext(file)[1]
            if ext != '': # if file has an extension
                self.mydir[ext] = (ext + " FOLDER").upper()

    def create_folder(self):
        for folder in list(self.mydir.values()):
            if not os.path.isdir(folder):
                os.mkdir(os.path.join(root_path,folder))

    def organize_files(self):
        for file in dirfiles:
            # for files iterated, check if it matches the ext and move it to ext folder
            for ext in [*self.mydir]:
                if file.endswith(ext):
                    try:
                        shutil.move(file,self.mydir[ext])
                    except :
                        print(f"{file} already exists in {self.mydir[ext]}")

file_organizer = FileOrganizer()
file_organizer.name_folder()
file_organizer.create_folder()
file_organizer.organize_files()
```


texts:
I'm a beginner in programming and made a pretty simple heads or tails type game. I would like to know if I have done this efficiently. If not, please let me know what you would have done differently.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void headsOrTails();
int randomNumber();

int main()
{
    headsOrTails();
}

int randomNumber()
{
    int number;
    srand(time(0));
    for(int i = 1; i < 2; i++)
    {
        number = 1 + (rand()%2);
    }
    return number;
}

void headsOrTails()
{
    string prediction;
    cout << "Heads or Tails? ";
    cin >> prediction;

    if((prediction == "Heads") || (prediction == "heads")){
        if(randomNumber() == 1){
            cout << "Heads, you are correct!\n" << endl;
        }
        else if(randomNumber() == 2){
            cout << "Tails, you were wrong.\n" << endl;
        }
    }
    if((prediction == "Tails") || (prediction == "tails")){
        if(randomNumber() == 1){
            cout << "Heads, you were wrong.\n" << endl;
        }
        else if(randomNumber() == 2){
            cout << "Tails, you are correct!\n" << endl;
        }
    }

    char playAgain;
    cout << "Play again?(Y/N) ";
    cin >> playAgain;
    cout << "\n";

    while((playAgain == 'Y') || (playAgain == 'y')){
        headsOrTails();
    }
    while((playAgain == 'N') || (playAgain == 'n')){
        exit(EXIT_FAILURE);
    }
}


texts: Check user changed his password recently or not in specific period

texts:
I am working on Oracle SQL. What I am trying to do is:

Query a record with ID
If the record does not exists use user input value
If the record exists, compare last_login_date column and user input value (I put to_date('20160401', 'yyyymmdd') then pick recent one)
Add not_change_day to result of 3, then compare the value with sysdate
If 4 is bigger then sysdate then returns true else false

select
    case when (a.ncd + a.lld > sysdate) then 'true'
    else 'false' end as result
from
(
    select
        nvl(not_change_day, 90) as ncd,
        case
            when last_login_date is null then to_date('20160401','yyyymmdd')
            when last_login_date > to_date('20160401','yyyymmdd') then last_login_date
        END as lld
    from
        FT_PWD_CHANGE
    where
        id='some_id'
) a

RESULT

result
------
false

However, I believe there are too many case when statements and sub-queries. Would you suggest a more efficient way?


texts: Small module for getting JSON to work with in Python

texts:
I currently have a module with Class / Methods I want to use in other scripts. Recently chess.com released a read-only REST API for beta-testing. The methods in my class build a URL for the API endpoints I am interested in and get the JSON data for me to work with in other scripts.

It is worth noting that I am fairly unused to using classes in the way I am in my code below - or at all really. Here is my working code:

"""TODO: docstring"""
from requests import get

class GetGamesJson:
    """TODO: docstring"""

    def build_url_for_player(self, username):
        """Build a custom URL for the `Palyer Profile` endpoint.

        Args:
            username (`str`): Player's username as string input.

        Returns:
            string: A URL for a player that can be used as a base for
            accessing other enpoints.

        Examples:
            >>> print(build_url_for_player('foo'))
            'https://api.chess.com/pub/player/foo'

        Raises:
            ValueError: If `username` is not found.

        """
        self.username = username
        player = (
            "https://api.chess.com/pub/player/{username}".format(
                username=username
            )
        )
        try:
            if get(player).json()['code'] == 0:
                raise ValueError("User '{username}' not found.".format(
                    username=username
                ))
        except KeyError:
            return player

    def build_url_for_monthly_archives(self, year, month):
        """Build URL for the `Monthly Archives` endpoint.

        This method depends on the base URL returned by the
        build_url_for_player() method.

        Args:
            year (int): Year as integer input.
            months (int): Month as integer input.

        Returns:
            string: URL to Monthly Archives.

        Examples:
            >>> print(build_url_for_monthly_archives(2009, 5))
            'https://api.chess.com/pub/player/foo/games/2009/05'

        """
        self.year = year
        self.month = month
        username = self.username
        url_to_monthly_archive = (
            self.build_url_for_player(username) +
            "/games/{year}/{month:02d}".format(
                username=username, year=year, month=month
            )
        )
        return url_to_monthly_archive

    def get_monthly_archive_json_doc(self):
        """Returns a JSON document from Monthly Archives endpoint."""
        link_to_json_doc = self.build_url_for_monthly_archives(
            self.year, self.month
        )
        get_json_doc = get(link_to_json_doc)
        return get_json_doc.json()

I would like to know what I can do to simplify and improve in the code I have.


texts:
There are quite some questions and answers about how to make enum really type-safe and I didn't find a solution that ensures both type safety and valid values. So I took some ideas and extended it to my own generic solution, somehow resembling to enum classes used in some other languages.

My solution adds the overhead of a pointer dereference for getting the actual enum value, but I think this is a fair deal for situations where you would otherwise have to check for the valid range in a lot of places. Comparing values works naturally with the == operator because there is only one global constant instance of each enum value.

I'm posting it here for review and comments if you like -- please tell me if you spot a bug or any other weakness in my idea. Is there anything I overlooked?

The "implementation" is just a header file:

csafenum.h

#ifndef CSAFENUM_H
#define CSAFENUM_H

#ifndef __GNUC__
#define __attribute__(x)
#endif

#include <assert.h>

/* declare an enum type: CSAFENUM_DECL(TypeName); */
#define CSAFENUM_DECL(tname) struct tname##_struct; \
    typedef const struct tname##_struct * tname; \
    const char *tname##_name(tname e) __attribute__((nonnull(1))); \
    int tname##_val(tname e) __attribute__((nonnull(1)))

/* declare an enum member: CSE_DECL(TypeName, MemberName); */
#define CSE_DECL(tname, name) extern const struct tname##_struct * const name

/* define an enum type: CSAFENUM_DEF(TypeName); */
#define CSAFENUM_DEF(tname) struct tname##_struct { \
    int val; \
    const char * const name; \
}; \
const char *tname##_name(tname tname##_cannot_be_null) \
{ \
    assert(tname##_cannot_be_null); \
    return tname##_cannot_be_null->name; \
} \
int tname##_val(tname tname##_cannot_be_null) \
{ \
    assert(tname##_cannot_be_null); \
    return tname##_cannot_be_null->val; \
} \
struct tname##_struct

/* define an enum member: CSE_DEF(TypeName, MemberName, IntegerValue); */
#define CSE_DEF(tname, name, v) \
    static const struct tname##_struct name##_memb = { v, #name }; \
    const struct tname##_struct * const name = &name##_memb

#endif

Example usage:

fruit.h

#ifndef FRUIT_H
#define FRUIT_H

#include <csafenum.h>

CSAFENUM_DECL(Fruit);

CSE_DECL(Fruit, Apple);
CSE_DECL(Fruit, Banana);
CSE_DECL(Fruit, Pear);
CSE_DECL(Fruit, Strawberry);

#endif

fruit.c

#include "fruit.h"

CSAFENUM_DEF(Fruit);

CSE_DEF(Fruit, Apple, 0);
CSE_DEF(Fruit, Banana, 1);
CSE_DEF(Fruit, Pear, 2);
CSE_DEF(Fruit, Strawberry, 3);

main program

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

int main()
{
    Fruit a, b, c, d;

    a = Apple;
    b = Banana;

    printf("a = %s (%d)\n", Fruit_name(a), Fruit_val(a));
    printf("b = %s (%d)\n", Fruit_name(b), Fruit_val(b));

    c = Apple;

    if (c == a) puts("c == a");
    if (c == b) puts("c == b");

    d = 0;

    printf("d = %s (%d)\n", Fruit_name(d), Fruit_val(d));

    return 0;
}

Output

  a = Apple (0)
  b = Banana (1)
  c == a
  example: fruit.c:3: Fruit_name: Assertion `Fruit_cannot_be_null' failed.
  zsh: abort      ./example/example

As pointed out by DarkDust, this does not work in switch blocks -- pointers aren't allowed to switch on. After thinking about this issue for a while, I get the feeling better not to try solving this, because it would either weaken or overcomplicate (or both) the whole thing.

The whole code is on GitHub.


texts:
good afternoon.
I'm learning c++ and I made this app to "manage" lockers.
I would like you to review it please, you can find the source code at my github: https://github.com/VitalZero/lockermanager

The app is made up by 3 main clases:

CDocument: Takes care of file input/output
CLockers: The lockers itself, stores it's info
CLockManager: Takes care of the lockers and the document

Also, there's a "helper" class I made to show the functionality, SimpleMenu, that is not part of the main "program"

To use it as is, just create an instance, feed the file name and thats it:

#include "CLockManager.h"
#include "SimpleMenu.h"

int main()
{
  CLockManager manager("database.txt");
  SimpleMenu menu(manager);

  menu.ShowMenu();

  return 0;
}

File CDocument.h:

#ifndef CDOCUMENT_H_
#define CDOCUMENT_H_
/*
 * CDocument.h
 * It is used by CLockManager.
 * Just used to load and save data from a file using a vector of CLockers
 * CLockers overloads stream operators >> and <<
 * Just feed a vector of CLockers and it's all good!
 */
#include <fstream>
#include <string>
#include <vector>
#include "CLockers.h"

class CDocument{
public:
    CDocument() = delete;
    CDocument(const std::string& path_in)
        :
        path(path_in)
    {
    }
    ~CDocument()
    {
        if(inFile.is_open())
            inFile.close();
    }
    bool SaveData(std::vector<CLockers>& lockers);
    bool LoadData(std::vector<CLockers>& lockers);

private:
    std::fstream inFile;
    std::string path;
};

#endif /* CDOCUMENT_H_ */

File CDocument.cpp

#include "CDocument.h"

bool CDocument::SaveData(std::vector<CLockers>& lockers)
{
    inFile.open(path.c_str(), std::ios_base::out | std::ios_base::trunc);

    if(inFile.is_open())
    {
        for(unsigned int i = 0; i < lockers.size(); ++i)
        {
            inFile << lockers.at(i);
        }
        inFile.close();
        return true;
    }

    return false;
}

bool CDocument::LoadData(std::vector<CLockers>& lockers)
{
    inFile.open(path.c_str(), std::ios_base::in);

    if(inFile.is_open())
    {
        CLockers tmp;
        lockers.clear();

        while( (inFile.good()) && (inFile >> tmp) ) // here is the problem from CLockers, even though is being checked in here
        {                                           // it gives another extra loop after the fail bit is set
            lockers.push_back(tmp);
        }

        inFile.close();

        return true;
    }
    else
    {
        // Probably move this out to menu.cpp
        // interaction only should occur outside the class
        std::cout << "\tThe file "
                << path << " doesn't exist or can't be opened.\n";
        std::cout << "Do you want to create it? y/n: ";
        std::string stringAnswer;
        std::getline(std::cin, stringAnswer);

        if( (stringAnswer == "y") || (stringAnswer == "Y") )
        {
            inFile.open(path, std::ios_base::out | std::ios_base::trunc);
            inFile.close();
            return true;
        }
    }
    return false;
}

Thank you in advance! and any suggestion/correction is highly appreciated!. Greetings.


texts: Reading a file line by line - Two tokens per entry

texts:
Problem

Read a file and capture two tokens for every multi-line entry.

First token is hexcode with which the entry starts.

Second token is the remaining line(multi-line) of the entry. Trailing backslash indicates the continuation of line.

Typical entries of a file is as shown below:

0x0512ff01 R 5330 R XY.Zion, \
        "parseexp( {f 7},{S \"OWAUTO\"})", "0x0222ff02 -:-", \
        "parseexp( {g 7},{S \"TWFAB\"})", "0x0222ff02 -:-",  \
        "setfault", "0x0222ff03 -:-"
# whatever
0x0436ff02 I 5330  R XY.Yion, " \
                    ! ( strcat( {H 19.19.121.180}, {attr 0x11137f })  \
                            "default", "0x0222ff03 -:-"
0x0236ff03 G 50
0x0588ff03 H 49
0x0777ff03 R 34

There are such ~100 files to read

Solution

Input to this function is a generator that provides path, one at a time

def get_tokens(file_paths):

    for path in file_paths:
        ruleCapture = False
        with open(path) as f:

            for line in f:

                line=line.strip() # remove \n and other spaces
                if line.startswith('#'): # comments
                    continue
                elif (not line.endswith('\\')) and (ruleCapture == False):
                    event_rule_match =  re.search(r'(?<!\\\n)^(0[xX][0-9a-fA-F]+)([^\n]*)',line)
                    if event_rule_match:
                        yield event_rule_match.group(1), event_rule_match.group(2)
                elif line.endswith('\\') and ruleCapture == False:
                    buffer = line[0:-2]
                    ruleCapture = True
                elif line.endswith('\\') and ruleCapture == True:
                    buffer = ' '.join([buffer, line[0:-2]])
                elif (not line.endswith('\\')) and ruleCapture == True:
                    buffer = ' '.join([buffer, line])
                    ruleCapture = False
                    event_rule_match =  re.search(r'(?<!\\\n)^(0[xX][0-9a-fA-F]+)([^\n]*)',buffer)
                    yield event_rule_match.group(1), event_rule_match.group(2)
                    buffer=''

1) Can this code avoid regex?

2) Can elif structure still be optimized?

3) Can this code avoid reading the file line by line? Instead use f.read() and compile regex once....


texts: Copying List Elements To Another List And Changing Them

texts:
I'm a beginner python programmer..I recently started reading a python book called: "Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming"...And I found an interesting challenge...The  challenge is to copy the elements of the list to another list and change the elements to make them become lowercase...I solved the challenge by myself and wrote two versions for it...

Here is my first attempt:

#Method1: Using the slice method
currentUsers = ['MrSplash', 'MrRobot', 'Peter1234', 'Steve', 'James']
newUsers = ['Davidpeterson', 'Elliot345', 'STEVE', 'mrRobOt', 'NickB3ns0N']

currentUsersLower = currentUsers[:]
for i in range(0, 5):
    currentUsersLower[i] = currentUsersLower[i].lower()

And here is my second attempt:

#Method2: Using a normal for loop
currentUsers = ['MrSplash', 'MrRobot', 'Peter1234', 'Steve', 'James']
newUsers = ['Davidpeterson', 'Elliot345', 'STEVE', 'mrRobOt', 'NickB3ns0N']

currentUsersLower = []
for user in currentUsers:
    currentUsersLower.append(user.lower())

My first question is this: Imagine we are working with around a million elements here. Which of these methods is efficient?

I define efficient as:

Easy to maintain and read
Performance-wise(Because let's face it, a million elements requires a lot of performance here)

My second question is this: Are there better ways to do this task than the ones I presented here?
If so please share them as an answer here

Note: The code works on both Python 3 and 2.


texts:
I posted this code in an answer earlier today, but thought it was worth seeing if somebody could suggest further improvements:

#include <numeric>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

template <class InIt, class OutIt>
OutIt adjacent_sum(InIt begin, InIt end, OutIt result) {
    ++begin;
    while (begin != end) {
        *result = *begin + *(begin-1);
        ++result;
        ++begin;
    }
    return result;
}

int main() {
    std::vector<int> inputs { 1, 2, 3, 4, 5, 10, 9, 8, 7, 6};

    adjacent_sum(inputs.begin(), inputs.end(),
        std::ostream_iterator<int>(std::cout, "\t"));

    std::cout << "\n";

    std::transform(inputs.begin(), inputs.begin()+inputs.size()/2,
        inputs.rbegin(),
        std::ostream_iterator<int>(std::cout, "\t"),
        std::plus<int>());
}

Here I've placed fixed input into the vector inputs. The intent is to first produce the sums of adjacent items in the input, and second produce the sum of the first item added to the last item, second item added to the second to last, and so on.


texts:
EDIT: I turned down the brightness on my monitor using the graphics options for the video card. This solved the issue. How this setting changed is a mystery...
I am leaving this up because googling it leads down some difficult and unhelpful paths.
ORIGINAL:
Google maps has become washed out. I cannot see roads. I have made a hack work around that dims the page to make the roads contrast with the map
See https://www.youtube.com/watch?v=MAPfjlwMyB4 for example of issue I am having.
Now, I made a snippet inside the developer console in chrome to "fix" this, but I am certain there are better ways to do it.
Here is the snippet:
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.mapsTactileClientSettingsMain__widget-settings-offscreen .widget-settings-shim { width: 100%; height: 100%; opacity: 0.3; pointer-events: none; }';
document.getElementsByTagName('head')[0].appendChild(style);

This only works AFTER I have accessed the hamburger menu at least once. If I run the script before then, it has no effect.
The script simply uses the same overlay that google uses to dim the map while the menu is open. But it changes it to be "on" even when you aren't accessing the menu. It also disables mouse interaction with the overlay so the user can interact with the map.
I am looking for improvements or entirely different fixes that are better.
Thank you.


texts: Finding distinct number of coins for different denominations

texts:
Given infinite supply of coins of denominations 25, 10, 5 and 1, find the distinct number of ways to use the coins to sum up to the given value.

Can anyone help me in finding the time complexity of this algorithm?

import java.util.ArrayList;
import java.util.List;
public class Coins {
    private static class Node {
        int value;
        int count;

        public Node(int count, int value) {
            this.count = count;
            this.value = value;
        }
    }
    public static void getComibnation(int[] coins, int sum, int start, List<Node>currentValues) {
        if(sum == 0) {
            for(Node n: currentValues) {
                System.out.print(n + " ");
                System.out.println();
                return;
            }
        }
        int next_denom = 1;

        switch(start) {
        case 25:
            next_denom = 10;
            break;

        case 10:
            next_denom = 5;
            break;

        case 5:
            next_denom = 1;
            break;

        case 1:
            currentValues.add(new Node(1, sum));
            for(Node n: currentValues) {
                System.out.print(n);
                System.out.print(" ");
            }
            System.out.println();
            currentValues.remove(currentValues.size()-1);
            return;
        }

        for(int i=0; i*start<=sum; i++) {
            currentValues.add(new Node(start, i));
            getComibnation(coins, sum-(i*start), next_denom, currentValues);
            currentValues.remove(currentValues.size()-1);
        }
    }

    public static void main(String[] args) {
        int[] coins = { 25, 10, 5, 1};
        List<Node> currentValues = new ArrayList<Node>();
        Coins.getComibnation(coins, 100, 25, currentValues);
    }

}

Assuming all the coins are denomination, each node in the tree will have \$n\$ branches not exactly but upper bound. The max depth is the number of coins. Thus, it is \$O(n^m)\$. This is not a tight bound but a loose bound. Any suggestions?


texts: Child/Parent relationship by adding an element to list

texts:
I have to implement a class with has parent and child fields. The problem is that by adding a child it must immediately keep reference to its' parent. I implemented it and it seems to work but I am not quite sure if I did it right. Any advice will be useful!

namespace DocumentToDocument
{
  public class MyEventArgs<T>: EventArgs
  {
    public T D;
  }

  public class MyList<T> : List<T>
  {
    public event EventHandler OnAdd;

    public new void Add(T item)
    {
      if (null != OnAdd)
      {
        var m = new MyEventArgs<Document> {D = item as Document};

        OnAdd(this, m);
      }
      base.Add(item);
    }
   }

   public class Document
   {
     public Document()
     {
       Children = new MyList<Document>();
       Children.OnAdd += new EventHandler(Children_OnAdd);
     }

     public string Name;

     public Document Parent;

     public MyList<Document> Children;

     public void Children_OnAdd(object sender, EventArgs e)
     {
      ((MyEventArgs<Document>) e).D.Parent = this;
     }
   }

   class Program
   {
     private static void Main(string[] args)
     {
       var d = new Document {Name = "I am a parent"};

       var dd = new Document {Name = "I am a child"};

       d.Children.Add(dd);
     }
   }
 }


texts: Python class that implements the Newton method

texts:
Here is a python function I wrote to implement the Newton method for optimization for the case where you are trying to optimize a function that takes a vector input and gives a scalar output.  I use numdifftools to approximate the hessian and the gradient of the given function then perform the newton method iteration.

import numpy as np
import numdifftools as nd

class multivariate_newton(object):

    def __init__(self,func,start_point,step_size=0.8,num_iter=100,tol=0.000001):
        '''
        func: function to be optimized. Takes a vector argument as input and returns
              a scalar output
        step_size: step size in newton method update step
        num_iter: number of iterations for newton method to run
        tol: tolerance to determine convergence
        '''
        self.func=func
        self.start_point=np.array(start_point)
        self.num_iter=num_iter
        self.step_size=step_size
        self.tol=tol

    def newton_method(self):
        '''
        perform multivariate newton method for function with vector input
        and scalar output
        '''
        x_t=self.start_point
        #Get an approximation to hessian of function
        H=nd.Hessian(self.func)
        #Get an approximation of Gradient of function
        g=nd.Gradient(self.func)

        for i in range(self.num_iter):
            x_tplus1=x_t-self.step_size*np.dot(np.linalg.inv(H(x_t)),g(x_t))
            #check for convergence
            if abs(max(x_tplus1-x_t))<self.tol:
                break
            x_t=x_tplus1

        self.crit_point=x_tplus1
        self.max_min=self.func(x_t)

        return self

    def critical_point(self):
        '''
        print critical point found in newton_method function. newton_method function
        must be called first.
        '''
        print self.crit_point