#StackBounty: #algorithms #sorting #strings #binary Partitioning through block moves to the end

Bounty: 50

Suppose we have a binary string $s$. We wish to partition this string in a series of $0$s followed by $1$s (alternatively: we wish to sort), using only one operation: moving three consecutive elements to the end.

E.g. if our string is $ABCDEFGH$ we can do our operation at index $1$ to get $DEFGHABC$. If we did it at index $4$ we’d get $ABCGHDEF$.

I’m interested in optimal solutions – that is with the least amount of moves. I have a working algorithm using IDA* with heuristic “# of groups of ones with length $leq 3$ before the final zero”, with the logic that each such a group requires at least one move to fix. An example optimal solution (where ^ indicates where a block was chosen to move to the end):

1101101011101011010010010011                               
                       ^                                   
1101101011101011010010011100                               
                     ^                                     
1101101011101011010011100001                               
              ^                                            
1101101011101010011100001110                               
           ^                                               
1101101011110011100001110010                               
                        ^                                  
1101101011110011100001110001                               
     ^                                                     
1101111110011100001110001010                               
  ^                                                        
1111110011100001110001010011                               
                     ^                                     
1111110011100001110000011101                               
                       ^                                   
1111110011100001110000001111                               
               ^                                           
1111110011100000000001111111                               
        ^                                                  
1111110000000000001111111111                               
   ^                                                       
1110000000000001111111111111                               
^                                                          
0000000000001111111111111111 

However, this algorithm is exponential and not feasible for larger strings. After studying quite some optimal solutions, especially tough ones like above, I can’t immediately think of an optimal algorithm. Moves can be quite non-trivial.

Is there a feasible optimal algorithm? Or is this problem hard?


Get this bounty!!!

#StackBounty: #sorting #binary Partitioning through block moves to the end

Bounty: 50

Suppose we have a binary string $s$. We wish to partition this string in a series of $0$s followed by $1$s (alternatively: we wish to sort), using only one operation: moving three consecutive elements to the end.

E.g. if our string is $ABCDEFGH$ we can do our operation at index $1$ to get $DEFGHABC$. If we did it at index $4$ we’d get $ABCGHDEF$.

I’m interested in optimal solutions – that is with the least amount of moves. I have a working algorithm using IDA* with heuristic “# of groups of ones with length $leq 3$ before the final zero”, with the logic that each such a group requires at least one move to fix. An example optimal solution (where ^ indicates where a block was chosen to move to the end):

1101101011101011010010010011                               
                       ^                                   
1101101011101011010010011100                               
                     ^                                     
1101101011101011010011100001                               
              ^                                            
1101101011101010011100001110                               
           ^                                               
1101101011110011100001110010                               
                        ^                                  
1101101011110011100001110001                               
     ^                                                     
1101111110011100001110001010                               
  ^                                                        
1111110011100001110001010011                               
                     ^                                     
1111110011100001110000011101                               
                       ^                                   
1111110011100001110000001111                               
               ^                                           
1111110011100000000001111111                               
        ^                                                  
1111110000000000001111111111                               
   ^                                                       
1110000000000001111111111111                               
^                                                          
0000000000001111111111111111 

However, this algorithm is exponential and not feasible for larger strings. After studying quite some optimal solutions, especially tough ones like above, I can’t immediately think of an optimal algorithm. Moves can be quite non-trivial.

Is there a feasible optimal algorithm? Or is this problem hard?


Get this bounty!!!

#StackBounty: #indexing #sorting #imakeidx Sorting problem with umlauts

Bounty: 50

I have a problem with a self-generated index of authors.
If I have a name with umlaut, the sorting fails. In My MWE, the two entries should be inverted. How could I fix the issue?
I’m including also the coding for the “namea” mod, in case it could be useful.

% !BIB TS-program = biber
% !BIB program = biber
% !TEX encoding = UTF-8 Unicode
% !TeX TS-program = xelatexmk

begin{filecontents}{archivio.bib}

@book{Doll,
    Address = {Moskwa},
    Author = {Pippo Donninger},
    Publisher = {Sinodal'naja tip.},
    Title = {I'm the sheep},
    Year = {1894}}

@book{Dol2,
    Address = {Moskwa},
    Author = {Philip Döllinger},
    Publisher = {Sinodal'naja tip.},
    Title = {Sistematičeskoe opisanie rukopisej moskovskoj Sinodal'noj (patriaršej) biblioteki},
    Year = {1894}}


end{filecontents}

documentclass[11pt, openany]{book}
usepackage{polyglossia}
setmainlanguage[babelshorthands=true]{italian}
setotherlanguages{latin, english, french}

usepackage[]{csquotes}
usepackage{xpatch}
usepackage[style=verbose-trad2,
            language=auto,
            ibidpage=true,
            autolang=other,
            useprefix=true,
            giveninits=true,
            indexing=true,
            dateabbrev=false,
            backend=biber,
        ]{biblatex}



addbibresource{archivio.bib}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


usepackage{imakeidx}
makeindex[name=nomi, intoc=true, title=Indice dei nomi]

renewbibmacro*{citeindex}{%
  ifciteindex
    {ifnameundef{namea}{indexnames{labelname}}{indexnames{namea}}}
    {}}

DeclareIndexNameFormat{default}{%      Formato del nome dell'autore
  usebibmacro{index:name}
    {index[nomi]}
    {namepartfamily}
    {namepartgiveni}
    {namepartprefix}
    {namepartsuffix}}


begin{document}


I should like to sort properly cite{Doll} and cite{Dol2}.



printindex[nomi]       % Indice dei nomi   
end{document}


Get this bounty!!!

#StackBounty: #magento-2.1 #sorting #php-7 How to convert Magento 2 Sort By Dropdown to Horizontal List

Bounty: 50

I was trying to Convert Magento 2 Drop down to Horizontal list.

Code Path:

/app/design/frontend/Vendor/Theme/Magento_Catalog/templates/product/list/toolbar/sorter.phtml

Actual Code:

getAvailableOrders() as $_key => $_order): ?> " isOrderCurrent($_key)): ?> selected="selected" > escapeHtml(__($_order)) ?>

What I tried :


Did some research on this and found this LINK

But Couldn’t able to find the Solution. Please help me on this.

Actual Display

Actual Display

Expected Result : On Click Products should sort according to the selection

Expected

Sorter.phtml File

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php
/**
 * Product list toolbar
 *
 * @var $block MagentoCatalogBlockProductProductListToolbar
 */
use MagentoCatalogModelProductProductListToolbar;
?>
<?php if ($block->getCurrentDirection() == 'desc'): ?> <a title="<?= /* @escapeNotVerified */ __('Set Ascending Direction') ?>" href="#" class="action sorter-action sort-desc" data-role="direction-switcher" data-value="asc"> <span><?= /* @escapeNotVerified */ __('Set Ascending Direction') ?></span> </a> <?php else: ?> <a title="<?= /* @escapeNotVerified */ __('Set Descending Direction') ?>" href="#" class="action sorter-action sort-asc" data-role="direction-switcher" data-value="desc"> <span><?= /* @escapeNotVerified */ __('Set Descending Direction') ?></span> </a> <?php endif; ?> </div>


Get this bounty!!!

#StackBounty: #php #python #c++ #algorithm #sorting Table cells / 2d array sorting algorithm

Bounty: 50

Is there an algorithm that could help sort the left table (which is an abstraction for multidimensional array of scalars or objects) down below so the result would be as in the right one, given that there maybe a limited amount of available depth in the right table (e.g. max of 30 rows)?

enter image description here

And slightly more complex version of the problem (first key in a cell is having precedence over another):

enter image description here

EDIT: And another level of complexity (merge rows/levels if it’s safe to do so to prevent redundancy):

enter image description here


Get this bounty!!!

#StackBounty: #r #sorting #shiny #dt Format date in Datatable output

Bounty: 50

library(DT)
seq_dates <- data.frame(dates = as.Date("2017-01-01") + 1:6 * 100)
datatable(seq_dates) %>% formatDate(1, "toDateString")

I get a datatable in viewer pane displaying dates in following format “Mon May 22 2017”.

Q – How can I format date column as “MM-YY”

If I do,

dplyr::mutate(seq_dates, dates = format(dates, format = "%b-%Y")) %>%
  datatable()

I get the required date format, but in this second case column sorting doesn’t work (sorting is done on alphabets rather than dates.)

P.S – I’m implementing this on shiny.


Get this bounty!!!

#StackBounty: #magento-2.1 #category #sorting Add new options into sorter

Bounty: 50

In magento 2 project, it provides 3 options by default.

  1. Position
  2. Product Name
  3. Price

I need to change these options to sort as,

  1. Most Popular
  2. Price high to low
  3. Price low to high

I can add from backend some other sorting options like color and product attributes as sorting options.
But I need to add above options.

Can anyone help me with that please?

How do I add new values in sorter? can it be done in backend or have to do by code?


Get this bounty!!!

#StackBounty: #magento2 #admin #sorting #column Magento 2 adminhtml custom column sorting ascending and descending

Bounty: 50

I made a custom column in sales_order_invoice_grid to display some additional data. This works fine but when clicking on the given column it does not react on any sorting mechanism like descending and ascending

Here is what I got

sales_order_invoice_grid

 <column name="order_state" class="FoobarInvoiceOrderStatusUiComponentListingColumnStatus">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">textRange</item>
                    <item name="label" xsi:type="string" translate="true">Order Status</item>
                </item>
            </argument>
        </column>

The corresponding class

class Status extends Column
{

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        $objectManager = MagentoFrameworkAppObjectManager::getInstance();

        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$item) {

                $orderId = $item["order_id"];
                if (empty($orderId)) {
                    $item[$this->getData('name')] = "unkown";
                    continue;
                }

                /** @var MagentoSalesModelOrderRepository $orderRepo */
                $orderRepo = $objectManager->get('MagentoSalesModelOrderRepository');
                /** @var MagentoSalesModelOrder $order */
                $order = $orderRepo->get($orderId);
                $item[$this->getData('name')] = $order->getStatus();
            }
        }

        return $dataSource;
    }


}

How can I apply descending / ascending sorting to my custom column?


Get this bounty!!!

#StackBounty: #python #multithreading #sorting #file #audio Speech Recognition Part 2: Classifying Data

Bounty: 50

Now that I have generated training data, I need to classify each example with a label to train a TensorFlow neural net (first building a suitable dataset). To streamline the process, I wrote this little Python script to help me. Any suggestions for improvement?


classify.py:

# Builtin modules
import glob
import sys
import os
import shutil
import wave
import time
import re
from threading import Thread

# 3rd party modules
import scipy.io.wavfile
import pyaudio

DATA_DIR = 'raw_data'
LABELED_DIR = 'labeled_data'
answer = None

def classify_files():
    global answer
    # instantiate PyAudio
    p = pyaudio.PyAudio()

    for filename in glob.glob('{}/*.wav'.format(DATA_DIR)):
        # define stream chunk
        chunk = 1024

        #open a wav format music
        wf = wave.open(filename, 'rb')
        #open stream
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)
        #read data
        data = wf.readframes(chunk)

        #play stream
        while answer is None:
            stream.write(data)
            data = wf.readframes(chunk)
            if data == b'': # if file is over then rewind
                wf.rewind()
                time.sleep(1)
                data = wf.readframes(chunk)

        # don't know how to classify, skip sample
        if answer == '.':
            answer = None
            continue

        # sort spectogram based on input
        spec_filename = 'spec{}.jpeg'.format(str(re.findall(r'd+', filename)[0]))
        os.makedirs('{}/{}'.format(LABELED_DIR, answer), exist_ok=True)
        shutil.copyfile('{}/{}'.format(DATA_DIR, spec_filename), '{}/{}/{}'.format(LABELED_DIR, answer, spec_filename))

        # reset answer field
        answer = None

        #stop stream
        stream.stop_stream()
        stream.close()

    #close PyAudio
    p.terminate()

if __name__ == '__main__':
    try:
        # exclude file from glob
        os.remove('{}/ALL.wav'.format(DATA_DIR))

        num_files = len(glob.glob('{}/*.wav'.format(DATA_DIR)))
        Thread(target = classify_files).start()
        for i in range(0, num_files):
            answer = input("Enter letter of sound heard: ")
    except KeyboardInterrupt:
        sys.exit()


Get this bounty!!!