How get HTML entities to display correctly in Buddypress messages

Question: In BuddyPress the messages preview window truncates the message at one line (225 characters), and then appends a horizontal ellipsis.
Unfortunately, this HTML entity displays as a string, and is not parsed to display as an ellipse.
We have tried all the HTML codes for ellipse, all display as strings.
The function that controls this in the /plugins/bp-core/bp-core-template.php file (start line 878)
Does anybody know how to fix this problem?  Many, many thanks in advance.    (Code below)
function bp_create_excerpt( $text, $length = 225, $options = array() ) {

    // Backward compatibility. The third argument used to be a boolean $filter_shortcodes.
    $filter_shortcodes_default = is_bool( $options ) ? $options : true;

    $r = bp_parse_args(
        $options,
        array(
            'ending'            => __(  ' [U+02026] '  , 'buddypress' ),
            'exact'             => false,
            'html'              => true,
            'filter_shortcodes' => $filter_shortcodes_default,
            'strip_tags'        => false,
            'remove_links'      => false,
        ),
        'create_excerpt'
    );

    // Save the original text, to be passed along to the filter.
    $original_text = $text;

    /**
     * Filters the excerpt length to trim text to.
     *
     * @since 1.5.0
     *
     * @param int $length Length of returned string, including ellipsis.
     */
    $length = apply_filters( 'bp_excerpt_length',      $length      );

    /**
     * Filters the excerpt appended text value.
     *
     * @since 1.5.0
     *
     * @param string $value Text to append to the end of the excerpt.
     */
    $ending = apply_filters( 'bp_excerpt_append_text', $r['ending'] );

    // Remove shortcodes if necessary.
    if ( ! empty( $r['filter_shortcodes'] ) ) {
        $text = strip_shortcodes( $text );
    }

    // When $html is true, the excerpt should be created without including HTML tags in the
    // excerpt length.
    if ( ! empty( $r['html'] ) ) {

        // The text is short enough. No need to truncate.
        if ( mb_strlen( preg_replace( '/<.*?>/', '', $text ) ) <= $length ) {
            return $text;
        }

        $totalLength = mb_strlen( strip_tags( $ending ) );
        $openTags    = array();
        $truncate    = '';

        // Find all the tags and HTML comments and put them in a stack for later use.
        preg_match_all( '/(<\/?([\w+!]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER );

        foreach ( $tags as $tag ) {
            // Process tags that need to be closed.
            if ( !preg_match( '/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s',  $tag[2] ) ) {
                if ( preg_match( '/<[\w]+[^>]*>/s', $tag[0] ) ) {
                    array_unshift( $openTags, $tag[2] );
                } elseif ( preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag ) ) {
                    $pos = array_search( $closeTag[1], $openTags );
                    if ( $pos !== false ) {
                        array_splice( $openTags, $pos, 1 );
                    }
                }
            }

            $truncate     .= $tag[1];
            $contentLength = mb_strlen( preg_replace( '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3] ) );

            if ( $contentLength + $totalLength > $length ) {
                $left = $length - $totalLength;
                $entitiesLength = 0;
                if ( preg_match_all( '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE ) ) {
                    foreach ( $entities[0] as $entity ) {
                        if ( $entity[1] + 1 - $entitiesLength <= $left ) {
                            $left--;
                            $entitiesLength += mb_strlen( $entity[0] );
                        } else {
                            break;
                        }
                    }
                }

                $truncate .= mb_substr( $tag[3], 0 , $left + $entitiesLength );
                break;
            } else {
                $truncate .= $tag[3];
                $totalLength += $contentLength;
            }
            if ( $totalLength >= $length ) {
                break;
            }
        }
    } else {
        // Strip HTML tags if necessary.
        if ( ! empty( $r['strip_tags'] ) ) {
            $text = strip_tags( $text );
        }

        // Remove links if necessary.
        if ( ! empty( $r['remove_links'] ) ) {
            $text = preg_replace( '#^\s*(https?://[^\s"]+)\s*$#im', '', $text );
        }

        if ( mb_strlen( $text ) <= $length ) {
            /**
             * Filters the final generated excerpt.
             *
             * @since 1.1.0
             *
             * @param string $text          Generated excerpt.
             * @param string $original_text Original text provided.
             * @param int    $length        Length of returned string, including ellipsis.
             * @param array  $options       Array of HTML attributes and options.
             */
            return apply_filters( 'bp_create_excerpt', $text, $original_text, $length, $options );
        } else {
            $truncate = mb_substr( $text, 0, $length - mb_strlen( $ending ) );
        }
    }

    // If $exact is false, we can't break on words.
    if ( empty( $r['exact'] ) ) {
        // Find the position of the last space character not part of a tag.
        preg_match_all( '/<[a-z\!\/][^>]*>/', $truncate, $_truncate_tags, PREG_OFFSET_CAPTURE );

        // Rekey tags by the string index of their last character.
        $truncate_tags = array();
        if ( ! empty( $_truncate_tags[0] ) ) {
            foreach ( $_truncate_tags[0] as $_tt ) {
                $_tt['start'] = $_tt[1];
                $_tt['end']   = $_tt[1] + strlen( $_tt[0] );
                $truncate_tags[ $_tt['end'] ] = $_tt;
            }
        }

        $truncate_length = mb_strlen( $truncate );
        $spacepos = $truncate_length + 1;
        for ( $pos = $truncate_length - 1; $pos >= 0; $pos-- ) {
            // Word boundaries are spaces and the close of HTML tags, when the tag is preceded by a space.
            $is_word_boundary = ' ' === $truncate[ $pos ];
            if ( ! $is_word_boundary && isset( $truncate_tags[ $pos - 1 ] ) ) {
                $preceding_tag    = $truncate_tags[ $pos - 1 ];
                if ( ' ' === $truncate[ $preceding_tag['start'] - 1 ] ) {
                    $is_word_boundary = true;
                    break;
                }
            }

            if ( ! $is_word_boundary ) {
                continue;
            }

            // If there are no tags in the string, the first space found is the right one.
            if ( empty( $truncate_tags ) ) {
                $spacepos = $pos;
                break;
            }

            // Look at each tag to see if the space is inside of it.
            $intag = false;
            foreach ( $truncate_tags as $tt ) {
                if ( $pos > $tt['start'] && $pos < $tt['end'] ) {
                    $intag = true;
                    break;
                }
            }

            if ( ! $intag ) {
                $spacepos = $pos;
                break;
            }
        }

        if ( $r['html'] ) {
            $bits = mb_substr( $truncate, $spacepos );
            preg_match_all( '/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER );
            if ( !empty( $droppedTags ) ) {
                foreach ( $droppedTags as $closingTag ) {
                    if ( !in_array( $closingTag[1], $openTags ) ) {
                        array_unshift( $openTags, $closingTag[1] );
                    }
                }
            }
        }

        $truncate = rtrim( mb_substr( $truncate, 0, $spacepos ) );
    }
    $truncate .= $ending;

    if ( !empty( $r['html'] ) ) {
        foreach ( $openTags as $tag ) {
            $truncate .= '</' . $tag . '>';
        }
    }

    /** This filter is documented in /bp-core/bp-core-template.php */
    return apply_filters( 'bp_create_excerpt', $truncate, $original_text, $length, $options );
}
add_filter( 'bp_create_excerpt', 'stripslashes_deep'  );
add_filter( 'bp_create_excerpt', 'force_balance_tags' );

Trying to get the messages preview window to display the HTML entities correcty, instead of actual strings.
Answer: To display a horizontal ellipsis instead of the HTML entity string in the message preview window in BuddyPress, you can use to replace the entity string with the actual Unicode character for the ellipsis likewise
and you can write like this
'ending' => __( '…' , 'buddypress' )
The ellipsis character '…' is represented by the Unicode character U+2026, which is a single character, After making the change, save the file and refresh your BuddyPress site to see the updated preview window. i hope this will help you
Comment: Hello Muhammad,  thank you, we did try using the horizontal ellipse three dots "..." but BuddyPress interprets that as …  So, every entity displays as a literal string, and the ellipse displays as an HTML entity. This seems to be a bug in BuddyPress.


About the inequality $rx^{r-1}\left(\sqrt{xy}-y\right)>x^{r}-y^{r}$ for $x>y>0$ and $r<0$

Question: In my book (Dictionnary of Inequalities ed 2 by Peter Bullen) we have p:27
If $x>y>0$ and $r<0$ then :
$$rx^{r-1}\left(x-y\right)>x^{r}-y^{r}>ry^{r-1}\left(x-y\right)$$
The above inequality is easy dividing by $x-y$ and using Hermite-Hadamard inequality .
Now I ask for a refinement of it :
If $x>y>0$ and $r<0$ then :
$$rx^{r-1}\left(\sqrt{xy}-y\right)>x^{r}-y^{r}\tag{I}$$
I have two question :
How to show $(I)$ ?
What is the limit for $x\to \infty$ (RHS-LHS in $(I)$)?
Thanks for all your reply and your effort in this sense .
Comment: How did you come up with that inequality? Why do you think that it holds? Why would that be interesting?
Comment: @MartinR I come up with this inequality solving https://math.stackexchange.com/questions/2176571/if-ab-1-then-a4b2b4a2-leq1 .
Comment: Note that you can reduce this to a single-variable inequality if you divide by $y^r$ and set $u=x/y$. In other words: Without loss of generality $x > y =1$.
Comment: @MartinR What about $r$ ?
Answer: This seems to be true
Considering the function $$f(x,y)=rx^{r-1}\left(\sqrt{xy}-y\right)-(x^{r}-y^{r})$$
Part 1
Let $y=k x$ with $0 < k <1$.
$$f(x,k x)=g(x)=\left(k^r-k r+\sqrt{k} r-1\right) x^r$$ So, to have $g(x)>0$ for any value of $k$ and $r<0$ it remains to show that
$$h(r)=k^r-k r+\sqrt{k} r-1 >0$$
$$h'(r)=k^r \log (k)-k+\sqrt{k}\qquad \text{and} \qquad h''(r)=k^r \log ^2(k) ~~> ~~0$$
$$h'(r)=0 \implies r_*=\frac{1}{\log (k)}\log \left(-\frac{\sqrt{k}-k}{\log (k)}\right) > 0$$ So, $h(r)$ is a decreasing function which is always positive and then $f(x,kx) >0$.
Part 2
If, as commented by @Martin R, we make $y=1$, we have
$$f(x,1)=g(x)=1-x^{r-1} \left(x-r \sqrt{x}+r\right)$$
$$g'(x)=\frac{1}{2} r \Big[(2 r-1) \sqrt{x}-2 x+2-2r\Big] x^{r-2}$$
$g'(x)$ cancels for two values of $x$
$$x_\pm=\frac{1}{8} \left(4 r^2-12 r+9 \pm(2 r-1) \sqrt{4 r^2-20 r+17}\right)$$ but $x_+ <1$.
But $g(x_-) >0$ as well as $g''(x_-)$.
Comment: Good Claude have you an idea for the second question ?
Comment: @ErikSatie. If what I wrote is correct, since $h(r)>0$ and $r<0$, $(g(x) \sim x^r \to 0^+$
Comment: Ok that is good thanks .


Hbase master not starting correctly

Question: I'm using Hadoop2.4.0 / Hbase 0.98.0 / Hive 0.14.0
Hadoop and HBase were running fine until I restarted my HMaster. The following error appears in hbase-hduser-master-master.log file :
 2015-02-17 05:46:15,157 INFO  [master:master:60000] master.TableNamespaceManager: Namespace table not found. Creating...
    2015-02-17 05:46:15,193 DEBUG [master:master:60000] lock.ZKInterProcessLockBase: Acquired a lock for /hbase/table-lock/hbase:namespace/write-master:600000000000004
    2015-02-17 05:46:15,212 DEBUG [master:master:60000] lock.ZKInterProcessLockBase: Released /hbase/table-lock/hbase:namespace/write-master:600000000000004
    2015-02-17 05:46:15,212 FATAL [master:master:60000] master.HMaster: Master server abort: loaded coprocessors are: []
    2015-02-17 05:46:15,213 FATAL [master:master:60000] master.HMaster: Unhandled exception. Starting shutdown.
    org.apache.hadoop.hbase.TableExistsException: hbase:namespace
        at org.apache.hadoop.hbase.master.handler.CreateTableHandler.prepare(CreateTableHandler.java:120)
        at org.apache.hadoop.hbase.master.TableNamespaceManager.createNamespaceTable(TableNamespaceManager.java:232)
        at org.apache.hadoop.hbase.master.TableNamespaceManager.start(TableNamespaceManager.java:86)
        at org.apache.hadoop.hbase.master.HMaster.initNamespace(HMaster.java:1049)
        at org.apache.hadoop.hbase.master.HMaster.finishInitialization(HMaster.java:913)
        at org.apache.hadoop.hbase.master.HMaster.run(HMaster.java:606)
        at java.lang.Thread.run(Unknown Source)
    2015-02-17 05:46:15,214 INFO  [master:master:60000] master.HMaster: Aborting
    2015-02-17 05:46:15,214 INFO  [master,60000,1424180766819-BalancerChore] balancer.BalancerChore: master,60000,1424180766819-BalancerChore exiting
    2015-02-17 05:46:15,215 INFO  [master,60000,1424180766819-ClusterStatusChore] balancer.ClusterStatusChore: master,60000,1424180766819-ClusterStatusChore exiting
    2015-02-17 05:46:15,215 INFO  [CatalogJanitor-master:60000] master.CatalogJanitor: CatalogJanitor-master:60000 exiting
    2015-02-17 05:46:15,216 DEBUG [master:master:60000] master.HMaster: Stopping service threads
    2015-02-17 05:46:15,216 INFO  [master:master:60000] ipc.RpcServer: Stopping server on 60000
    2015-02-17 05:46:15,216 INFO  [RpcServer.listener,port=60000] ipc.RpcServer: RpcServer.listener,port=60000: stopping
    2015-02-17 05:46:15,218 INFO  [RpcServer.responder] ipc.RpcServer: RpcServer.responder: stopped
    2015-02-17 05:46:15,218 INFO  [RpcServer.responder] ipc.RpcServer: RpcServer.responder: stopping
    2015-02-17 05:46:15,218 INFO  [master:master:60000.oldLogCleaner] cleaner.LogCleaner: master:master:60000.oldLogCleaner exiting
    2015-02-17 05:46:15,218 INFO  [master:master:60000.oldLogCleaner] master.ReplicationLogCleaner: Stopping replicationLogCleaner-0x14b97c83f580008, quorum=slave:2181,master:2181, baseZNode=/hbase
    2015-02-17 05:46:15,219 INFO  [master:master:60000.archivedHFileCleaner] cleaner.HFileCleaner: master:master:60000.archivedHFileCleaner exiting
    2015-02-17 05:46:15,219 INFO  [master:master:60000] master.HMaster: Stopping infoServer
    2015-02-17 05:46:15,223 INFO  [master:master:60000.oldLogCleaner] zookeeper.ZooKeeper: Session: 0x14b97c83f580008 closed
    2015-02-17 05:46:15,223 INFO  [master:master:60000-EventThread] zookeeper.ClientCnxn: EventThread shut down
    2015-02-17 05:46:15,229 INFO  [master:master:60000] mortbay.log: Stopped firstname.lastname@example.com:60010
    2015-02-17 05:46:15,236 DEBUG [master:master:60000] catalog.CatalogTracker: Stopping catalog tracker org.apache.hadoop.hbase.catalog.CatalogTracker@19f9598
    2015-02-17 05:46:15,236 INFO  [master:master:60000] client.HConnectionManager$HConnectionImplementation: Closing zookeeper sessionid=0x14b97c83f580007
    2015-02-17 05:46:15,237 INFO  [master:master:60000-EventThread] zookeeper.ClientCnxn: EventThread shut down
    2015-02-17 05:46:15,238 INFO  [master:master:60000] zookeeper.ZooKeeper: Session: 0x14b97c83f580007 closed
    2015-02-17 05:46:15,238 INFO  [master,60000,1424180766819.splitLogManagerTimeoutMonitor] master.SplitLogManager$TimeoutMonitor: master,60000,1424180766819.splitLogManagerTimeoutMonitor exiting
    2015-02-17 05:46:15,243 INFO  [main-EventThread] zookeeper.ClientCnxn: EventThread shut down
    2015-02-17 05:46:15,243 INFO  [master:master:60000] zookeeper.ZooKeeper: Session: 0x14b97c83f580006 closed
    2015-02-17 05:46:15,243 INFO  [master:master:60000] master.HMaster: HMaster main thread exiting
    2015-02-17 05:46:15,243 ERROR [main] master.HMasterCommandLine: Master exiting
    java.lang.RuntimeException: HMaster Aborted
        at org.apache.hadoop.hbase.master.HMasterCommandLine.startMaster(HMasterCommandLine.java:192)
        at org.apache.hadoop.hbase.master.HMasterCommandLine.run(HMasterCommandLine.java:134)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.hbase.util.ServerCommandLine.doMain(ServerCommandLine.java:126)
        at org.apache.hadoop.hbase.master.HMaster.main(HMaster.java:2785)

what's wrong here and what HMaster Aborted means ?
for more information this is what my hbase-site.xml looks like:
<property>
<name>hbase.rootdir</name>
<value>hdfs://master:54310/hbase</value>
</property>
<property>
<name>hbase.cluster.distributed</name>
<value>true</value>
</property>
<property>
<name>hbase.zookeeper.quorum</name>
<value>master,slave</value>
</property>
<property>
<name>hbase.zookeeper.property.clientPort</name>
<value>2181</value>
</property>
<property>
<name>hbase.zookeeper.property.dataDir</name>
<value>/usr/local/hbase/zookeeper</value>
</property>

Answer: I ran into this problem today! My solution is as follows:
Step 1:stop Hbase.
Step 2:run the follow command
hbase org.apache.hadoop.hbase.util.hbck.OfflineMetaRepair

This command is used to repair MetaData of Hbase
Step 3:delete the data in zookeeper (WARNING It will make you lost you old data)
./opt/cloudera/parcels/CDH-5.1.0-1.cdh5.1.0.p0.53/lib/zookeeper/bin/zkCli.sh

you can use ls / to scan the data in zookeeper
use rmr /hbase to delete the hbase's data in zookeeper
Step 4:Start hbase
Comment: access the zookeeper through "hbase zkcli"
Comment: what if zookeeper is managed internally by hbase? how to delete the zookeeper data then?
Answer: This is based on the other answer but to clarify for upgrade cloudera 5.4
Step 1:
service hbase-regionserver stop

service hbase-master stop

Step 2:
hbase org.apache.hadoop.hbase.util.hbck.OfflineMetaRepair

Step 3: Delete the data in zookeeper (WARNING It will make you lost your old data)
cd /usr/lib/zookeeper/bin/
./zkCli.sh

It opens up the zookeeper shell.
Then run:
ls /
rmr /hbase

Step 4:Start hbase
service hbase-master restart
service hbase-regionserver restart

Hbase master not starting correctly


Microsoft´s sqlsrv driver for PHP not returning any result when querying "SELECT SCOPE_IDENTITY() AS id"

Question: this query works fine using the php_mssql driver:
<code>INSERT INTO Table(columnName) VALUES ('text');
SELECT SCOPE_IDENTITY() AS id;
</code>
Table does have an id column, which is an identity.
I would execute that query, and get the last id in the table.
The same code doesn´t work if the query is executed using Microsoft´s php_sqlsrv driver.
I don´t get any error when executing the query (sqlsrv_query function) , but i get the following error when calling sqlsrv_fetch_array:
"The active result for the query contains no fields"
I´ve googled a lot, and didn´t find no answer, it was a big surprise for me that no one faced this problem before, it seems like nobody is using this driver, even though is the "official" one since PHP 5.3 release...
Thanks.
Answer: In the initial CTP the field indices started at 1. Later they were changed to start at 0.
Try something like this:
<code>// connection to the dbserver

$result = sqlsrv_query("INSERT INTO Table(columnName) VALUES ('text'); SELECT SCOPE_IDENTITY() AS ID");

echo "The last insert_id is".lastId($result);

function lastId($queryID) {
     sqlsrv_next_result($queryID);
     sqlsrv_fetch($queryID);
     return sqlsrv_get_field($queryID, 0);
}
</code>
Comment: This code gave me the clue to find out what´s happening. INSERT_QUERY returns 1 result, and SELECT SCOPE_IDENTITY returns another result. If you are pointing towards the 1st result you get an error if you try to fetch an array (the insert query doesn´t return anything), so you have to make the next result available (sqlsrv_next_result) and then you can call sqlsrv_fetch_array. WATCH OUT if you are migrating from php_mssql to php_sqlsrv, because this behaviour is different, and can possibly lead to errors.
Comment: I had similar issue; i used sqlsrv_next_result($result) to resolve it. At first it didn't solve the issue; then later on I found that there was a PRINT() statement in my SP which caused the problem. I had to remove PRINT() and use sqlsrv_next_result($result) also to solve it. don't we have anything that would let sqlsrv_query() discard PRINT()???
Comment: I had the same issue with the "Messages" data generated by SQL Server.  Using sqlsrv_next_result() resolved it.


Telegram-master\TMessagesProj\debug.keystore' specified for property 'signingConfig.storeFile' does not exist

Question: I read many posts about this issue in stackoverflow and Github but I couldn't solve my problem and still get this error when I run the code:
Error:A problem was found with the configuration of task ':TMessagesProj:packageDebug'

File 'D:\telegram\Telegram-master\TMessagesProj\debug.keystore' specified for property 'signingConfig.storeFile' does not exist.

I don't know what to do now. please help!
Answer: I  just solved this problem by copy and paste the debug.keystore at the selected path.
The debug.keystore of your android studio is in the

C:\User\ %USERPROFILE% .android

then you can find debug.keystore and copy it and paste in :

telegram\Telegram-master\TMessagesProj


Pandoc `lang` option makes font ugly

Question: I am trying to learn pandoc. I used latex before because I always deal with formulas, code. Here is the simple document I compile to pdf:
---
title: Test
...

# Test!

This is a test of *pandoc*.

- list one
- list two
- $E=mc^2$
- На русском

Горит костер рябины красной.

$$
A = \int\limits_{-\infty}^{\infty} e^{-x^2}dx
$$

```python
class ClassName(object):
    """docstring for ClassName (Кириллица?)"""
    def __init__(self, arg):
        super(ClassName, self).__init__() # English comment
        self.arg = arg # Кириллический комментарий

```

I've tried two different commands to produce pdf:

pandoc test1.md -o test1.pdf
pandoc -V lang=ru-RU -o test1-2.pdf test1.md

The first command failed rendering for cyrillic symbols. Moreover, I always write non-English documents, so I need documents to be generated with captions written in russian. I used lang property to do it as pandoc documentation suggests. Now, cyrillic symbols render correct but if you look at the screenshot a couple of seconds you can see that font looks much uglier than before. Espesially code.
What is going on and how to fix it?
Comment: probably it chose a different font now... you can try `pandoc -s -o output.tex` to see the LaTeX pandoc generates. Then you can fix it by e.g. setting the right `mainfont`, see http://pandoc.org/MANUAL.html#variables-for-latex
Comment: @mb21 yes you are right. The problem was `pandoc` set Latin Modern font as default font. It does not have cyrillic glyphs. I've changed pdf-engine to `xelatex` and set font to DejaVu Serif. Now it works fine for text and code but I still have issues with math, because pandoc ignores `-V mathfont="Some Math Font"`
Answer: I found it difficult to set-up fonts for Latin, Cyrillic, Math and code blocks in a consistent way with the interface offered by pandoc. The best compromise I found was:

Set lang equal to en and mark-up Russian parts explicitly.
Use XITS fonts for normal text and math
Use a fixed width font that covers Cyrillic, e.g. Liberation Mono
Process with XeLaTeX or LuaLaTeX

All combined:
---
title: Test
mainfont: XITS
monofont: Liberation Mono
mathfont: XITS Math
lang: en
---

# Test!

This is a test of *pandoc*.

- list one
- list two
- $E=mc^2$
- [На русском]{.class lang="ru-RU"}

::::: {.class lang="ru-RU"}

Горит костер рябины красной.

:::::

$$
A = \int\limits_{-\infty}^{\infty} e^{-x^2}dx
$$

```python
class ClassName(object):
    """docstring for ClassName (Кириллица?)"""
    def __init__(self, arg):
        super(ClassName, self).__init__() # English comment
        self.arg = arg # Кириллический комментарий

```

Result of pandoc cyr.md --pdf-engine=lualatex  -o cyr.pdf:
Comment: Maybe I am doing smth wrong but it seems that your solution face the same problem with math font: If you use smth like this in equation: `$k_Б = 1,381 \cdot 10^{-23}$` than underscored "Б" wont render. Moreover, compiler say this: `[WARNING] Missing character: There is no Б (U+0411) in font lmmi10!
[WARNING] Missing character: There is no Б (U+0411) in font lmmi7!`. It looks like XITS math did not set as math font.
Comment: @danielleontiev If I remove `mathfont: XITS Math` I get a visibly different result. So I am positive that for me the mathfont is set-up correctly. I would use `$k_\text{Б} = 1,381 \cdot 10^{-23}$` since the "Б" is probably meant as abbreviation of "Boltzmann" (in Cyrillic transliteration). And if it is not a mathematical variable, the surrounding text font should be used. Things get more difficult if you want to use Cyrillic letters for variables. I know no font that is set-up for that.

Pandoc `lang` option makes font ugly


adding a paragraph in list items breaking aligment in unordered list

Question: i'm trying to make an unordered list like this

but as soon as in input the content part under a list-item , the third list-item shifts up and ends up looking like this

HTML:

 |

 .01

       First

 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Expedita qui ipsa dolor.

CSS:
.wrapper{
  text-align: center;
  padding: 60px 0;
}
.wrapper ul{
  list-style: none;
  padding: 50px;
}
.wrapper ul li{
  display: inline-block;
  padding-left: 30px;
}
.wrapper ul .text{
  text-align: left;
}

Can you let me know how to fix it or is there anything i'm doing wrong?
Thanks in advance!!
Answer: Try this:

.wrapper{
  text-align: center;
  padding: 60px 0;
}
.wrapper ul{
  list-style: none;
  padding: 50px;
  display: flex;      /* add this line */
}
.wrapper ul li{
  padding-left: 30px;
}
.wrapper ul .text{
  text-align: left;
}
Comment: thanks , it works.. but how?  flex works on child elements and since no property set for the child element how is it taking that change?
Comment: `display: inline-block` ist trying to display the block elements as text. Therefore they are aligned at the bottom. That is why it moves the elements up. `display: flex` is just a different aproach in getting the items next to each other without `inline`. Maybe `float: left` would work fine aswell.
Comment: tried that , but when im trying to populate the list the list-items are stacking horizontally and not vertically, tried flex:1 nothing changes.
Comment: yeah but `flex: 1` will only work if you use `display: flex` on the parent element.
Comment: thanks a lot man ,one last thing is this the right way to go ? or should i have tried with tables instead?
Comment: You definitely should try to avoid tables as much as possible.
Now if you want to make this example responsive you could simply float the items beneath each other.

In my opinion that is definitely the right approach!
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/124965/discussion-between-aaron-mahlke-and-tankit88).


How do i publish a firebase login app on amazon app store?

Question: so i have been trying to publish my app on the amazon app store.
but as i have made my app on the firebase system i use mobile authentication or google login to let users login to my app but as amazon is not able to login to my app using those features they're unable to login to my app and is continuously rejecting my app.
can anyone please tell me what is the correct way to let them login to my app.
or do i need to create a fake login system with a fake account just for them to login.
here is my app link http://texts.ga

i did contacted them and told them to login via any of the two methods and they did login via the google login but still they are asking for login credentials again.
thanks in advance for any kind of help
Comment: Did you find the issue that triggers this, recently I uploaded my app that's based on firebase and amazon has reviewed my app functionality and made the app live when users downloaded it into their android devices they can't make a login. But when I made login from a side-load app it works perfectly. So, for that reason I took down my app from amazon app store
Answer: Firebase Authentication, along with some other Firebase products, require Google Play services installed on the device in order to work correctly.  Amazon devices don't have Google Play services, so Firebase Authentication will not work on them.
Comment: i too thought the same at first but as i said in my question they did logged in to my app using the google login method as i saw them pop up in the users list with a weird id


How can I clean tile debris from the bottom of my pool?

Question: After changing tiles, I have lots of tile/thinset debris on the bottom of the concrete pool.
Robot cleaner does not pick it up, since they are too heavy for it.
I did try to manually vacuum it by placing a hose into a skimmer. While a suction from a skimmer is ok, and it does pick up some of it, the system (pool pvc pipes) get clogged with tile debris, which tells me it is not the right way to go.
Did some diving and cleaning manually, but it just too much to clean by hand.
I can see that there are autonomous vacuum cleaners such as this, but not sure they are going to do any better than my dolphin..
What are the other things I can try, or maybe I am missing something and there are known ways to do it which I have not tried without clogging the pool system?
Answer: You have two choices:

Drain Pool and it hit with a scooper, shop vac, and broom.  If refilling it isn't a big deal this is definitely the fastest way by far.
Buy something like a pool leaf eater .  You will still have to scoop out the big stuff.  I have used a simple plastic dust pan to do this.  This process will keep you swimming but could take 10 vacuums over the course of a few weeks to get everything out.
Comment: #1 is somewhat an expensive option: it is quite problematic to drain the pool since it cannot go directly to a storm sewer to avoid chemistry in a local creek, and it is about $1000 and 4 days to refill it all back by the "house water". As to #2, how does it work? Does it have batteries or connect to ... outlet/skimmer?
Comment: It works just like a pool vacuum, except it is bigger and has a bag that houses the large debris - instead of sucking to your filter.
Comment: Looks like there are many different "pool vacuum" kinds :) So it does take the "sucking" power from a skimmer, but all the debris go to its bag instead of a skimmer?
Comment: That is it.  Only issue is if you have "heavy" objects they might not get sucked up.  I have had to clean a few pools when I lifeguarded (when punks threw crap in at night) and if it was really bad we had to drain.  If it was kind of bad we would dive with a a scoop and then hit it with a leaf eater.  If you are talking about tile scraps and plaster - a shopvac has issues with those.  You are going to have to just scoop it up little by little and hope they break down a little so vacuum can get them.
Comment: "leaf eater" stirs the water, and most of the tile pieces fall right back to the bottom rather than stay in a bag.
Comment: when you go over bigger pieces you can flip the leaf eater when they hit the bag, drag the pole up, and dump on other side of pool.  I have been through this.  It isn't easy to clean with water in the pool.


What is makeinfo, and how do I get it?

Question: I'm trying to build GNU grep, and when I run make, I get:
[snip]
/bin/bash: line 9: makeinfo: command not found

What is makeinfo, and how do I get it?
(This is Ubuntu, if it makes a difference)
Comment: For those who came here wondering how the subject matter experts below find this stuff: just do `apt-file search bin/makeinfo`
Comment: ```apt search makeinfo``` #(or ```yum search makeinfo```)
Answer: In (at least) Ubuntu when using bash, it tells you what package you need to install if you type in a command and its not found in your path. My terminal says you need to install 'texinfo' package.
sudo apt-get install texinfo

Comment: Just a note that to install the package it is sudo apt-get install **texinfo**. Note that it is teXinfo, not texTinfo which I mistakenly read at first.
Comment: If your shell doesn't give you magical hints like @Tuminoid's does, you can install apt-file and run the commands: `apt-file update && apt-file search makeinfo` Among the results you will see `texinfo: /usr/bin/makeinfo`
Comment: @egor7 The utility telling you the missing command is called `command-not-found`, which you can install with `sudo apt-get install command-not-found`.
Comment: You run the command in the terminal `$ makeinfo` and Ubuntu will tell it to you: `he program 'makeinfo' is currently not installed. You can install it by typing:
sudo apt-get install texinfo`
Comment: Just for the note - how to get notion about what package contains the utility? i.e. how to get know about texinfo if only I know the name makeinfo.
Comment: On Ubuntu 18, at least, make sure you have the `universe` source enabled if you want to install `texinfo`
Comment: macOS users: `brew install texinfo`
Comment: Or, you could use: `dpkg -S /usr/bin/makeinfo`
Comment: Not having the `sudo` on the machine, this might be the worst package to compile yourself...
Comment: Just a note that I needed to install this for a build process that was failing, and which still continued to fail after installing this package.  It turned out that `./configure` had placed a line `MAKEINFO=missing` into the makefiles for the project that was causing them to continue failing; I needed to rerun configure after installing it.
Comment: This doesn't explain what makeinfo is
Comment: I can't success. It shows: installed rsyslog package post-installation script subprocess returned error exit status 10.
Answer: For Centos , I solve it by installing these packages.
yum install texi2html texinfo

Dont worry if there is no entry for makeinfo.
Just run
make all

You can do it similarly for ubuntu using sudo.
Comment: texi2html is, strictly speaking, unnecessary. (CentOS 7).
Comment: texi2html is strictly speaking, unncecessary. (RHEL6+)
Comment: CentOS / Rocky Linux 8: `dnf config-manager --set-enabled powertools && dnf install texinfo`
Answer: Another option is to use apt-file (i.e. apt-file search makeinfo).  It may or may not be installed in your distro by default, but it is a great tool for determining what package a file belongs to.
Answer: Need to install texinfo. configure will still have the cache of its results so it will still think makeinfo is missing. Blow away your source and unpack it again from the tarball. run configure then make.
Answer: If you build packages from scratch:

Download a version from here: http://www.gnu.org/software/texinfo/

As of writing, version 5.2 is the latest.

Learn how to build here: http://www.linuxfromscratch.org/lfs/view/stable/chapter05/texinfo.html

LFS project is constantly updating, but texinfo build/install instructions rarely change.

Specifically, if you build bash from source, install docs, including man pages, will fail (silently) without makeinfo available.
Answer: A few words on "what is makeinfo" -- other answers cover "how do I get it" well.
The section "Creating an Info File" of the Texinfo manual states that

makeinfo is a program that converts a Texinfo file into an Info file,
  HTML file, or plain text.

The Texinfo home page explains that
Texinfo itself "is the official documentation format of the GNU project" and that it "uses a single source file to produce output in a number of formats, both online and printed (dvi, html, info, pdf, xml, etc.)".
To sum up: Texinfo is a documentation source file format and makeinfo is the program that turns source files in Texinfo format into the desired output.
Answer: On SuSE linux, you can use the following command to install 'texinfo':
sudo zypper install texinfo

On my system, it shows it is downloading about 1000 MiB, so make sure you have enough free space.
Answer: If it doesn't show up in your package manager (i.e. apt-cache search texinfo) and even apt-file search bin/makeinfo is no help, you may have to enable non-free/restricted packages for your package manager.
For ubuntu, sudo $EDITOR /etc/apt/sources.list and add restricted.
deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-security main
deb http://archive.ubuntu.com/ubuntu bionic-updates main

For debian, sudo $EDITOR /etc/apt/sources.list and add non-free. You can even have preferences on package level if you don't want to clutter the package db with non-free stuff.
After a sudo apt-get udpate you should find the required package.

What is makeinfo, and how do I get it?


Installing NVIDIA GeForce GTX 560 on Ubuntu 13.04

Question: I have a NVIDIA GeForce GTX 560 graphic card with Ubuntu 13.04 running kernel 3.8.0-19 (tried with 3.10.0-999, same issue) and whenever i tried to install NVIDIA driver, either by downloading the *.run file from http://www.nvidia.com and installing it as root (during installation it give some errors as it failed to set runlevel), or doing those following steps:
sudo add-apt-repository ppa:xorg-edgers/ppa
sudo apt-get update
sudo apt-get install nvidia-current nvidia-settings

Whenever I reboot the system, all my screen is messed up (with lower resoluition that should be, and with left and top bars missing), and worked hard to uninstall this driver and get my screen resolution and bars back. Are there any secure and working way to install NVIDIA driver for that graphic card?
Answer: I had the same problem, tried every answer i could found on the net and it didn't work.
if you are in this case :

on startup your bios is visible only with your nvidia card
ubuntu is visible only with the motherboard screen outpout

the reason seems to be the bad detection of device with modern bios (new motherboard, and relative old video card).
Try doing the following : first follow the indications there : http://ubuntuguide.net/how-to-install-nvidia-graphics-driver-in-ubuntu-10-10-maverick-meerkat
ie :

do the install of nvidia-current as suggested everywhere
make sure you have a xorg.conf file in /etc/X11/
once you are back on your problem with black screen etc, the idea is to have a terminal open from now. if you have it go to next step, otherwise try : connect your monitor to the motherboard outpout, reboot, go to the grub (double shift on startup after the bios), select the option advanced option for ubuntu, connect internet and go root console.
edit the xorg.conf file : sudo nano /etc/X11/xorg.conf
and once there : what did change everything is to add the line
BusID          "PCI:01:00:0"

in the section "Device", in my case that give this code :
Section "Device"
  Identifier     "Device0"
  Driver         "nvidia"
  VendorName     "NVIDIA Corporation"
  BusID          "PCI:01:00:0"
EndSection

save (ctrl+x), connect your monitor to the nvidia card and reboot, in my case, this solved the problem.
Comment: Thank you, I had the exact same problem of what you describe above. Just adding "BusID" line as you suggested did the trick.
Answer: Try the following commands in the terminal and see if this works:
sudo apt-get install linux-source
sudo apt-get install linux
sudo apt-get autoremove nvidia-current
sudo apt-get install xserver-xorg xserver-xorg-video-all
sudo apt-add-repository ppa:noobslab/nvidia-quantal
sudo apt-get update
sudo apt-get install nvidia-current
sudo reboot

Also look at this link, it may be of use to you.
Answer: You do not have to install any PPA's at all to install nvidia drivers, simply install the nvidia-current package, though you will need to remove the PPA you added before and then do a full update.
Comment: Yeah, exactly. The GTX 560 is supported for any version included in Ubuntu 13.04. I don't see why this got downvoted.
Answer: Possibly duplicate of this answer here :
How can I Install Nvidia Driver GT 520 and Cuda 5.0 in Ubuntu13.04?
It concerns CUDA-support by nvidia-driver specially written for CUDA-chipsets.


custom permalink structure for custom post type based on meta fields and custom taxonomy

Question: I have two custom post types. One with the slug artwork and another with the slug research-materials. The permalink structure for an artwork post is http://example.com/artwork/artwork-slug and this is expected, works fine and what I want. On the post.php page for any post that is of the research-materials post type I have a custom field (via ACF) that has the slug of the artwork post that the research materials post is related to and the desired slug for the research materials post. There's also a custom taxonomy set for the research-materials post type which would play a part in the construction of the permalink structure for the research-materials posts. The permalink would look like http://example.com/artwork/related-artwork-slug/research-materials/custom-taxonomy-term/research-materials-slug
Here's the code I have so far but I'm not getting the result I'd expect... instead I'm redirected to the artwork custom post type when I should be redirected tot he research-materials custom post type single page.
Any help appreciated. Thanks in advance.
class RRP{
    public static function init(){
        // set up custom post types and custom taxonomies
        add_action( 'init', 'RRP::build_custom_post_types' );
        add_action( 'init', 'RRP::build_custom_taxonomy' );

        // set up custom fields
        add_action( 'acf/init', 'RRP::register_custom_fields' );

        // validate saved value in custom fields
        add_filter( 'acf/validate_value', 'RRP::validate_saved_value_in_custom_fields', 10, 4 );

        // update related artwork slug
        add_filter( 'acf/update_value', 'RRP::update_related_artwork_slug', 10, 3 );

        // add the research material type
        add_action( 'save_post_research-materials', 'RRP::set_research_material_type' );

        // build rewrite rules
        add_action( 'init', 'RRP::rewrite_stuff', 10, 0 );
        add_filter( 'query_vars', 'RRP::build_query_vars', 10 );
        add_filter( 'pre_get_posts', 'RRP::pre_get_posts', 10 );
    }
    public static function build_custom_post_types(){

        $labels = array(
            'name'                => 'Research Materials',
            'singular_name'       => 'Research Material',
            'add_new'             => 'Add New Research Material',
            'add_new_item'        => 'Add New Research Material',
            'edit_item'           => 'Edit Research Material',
            'new_item'            => 'New Research Material',
            'view_item'           => 'View Research Material',
            'search_items'        => 'Search Research Materials',
            'not_found'           => 'No Research Materials found',
            'not_found_in_trash'  => 'No Research Materials found in Trash',
            'parent_item_colon'   => 'Parent Research Material:',
            'menu_name'           => 'Research    Materials',
        );

        $args = array(
            'labels'              => $labels,
            'hierarchical'        => false,
            'description'         => 'description',
            'taxonomies'          => array('research-material-type'),
            'public'              => true,
            'show_ui'             => true,
            'show_in_menu'        => true,
            'show_in_admin_bar'   => true,
            'menu_position'       => null,
            'menu_icon'           => null,
            'show_in_nav_menus'   => true,
            'publicly_queryable'  => true,
            'exclude_from_search' => false,
            'has_archive'         => true,
            'query_var'           => true,
            'can_export'          => true,
            'rewrite'             => true,
            'capability_type'     => 'post',
            'supports'            => array(
                'title', 'editor'
            )
        );

        register_post_type( 'research-materials', $args );

    }

    public static function build_custom_taxonomy(){

        $labels = array(
            'name'                  => 'Research Material Types',
            'singular_name'         => 'Research Material Type',
            'search_items'          => 'Search Research Material Types',
            'popular_items'         => 'Popular Research Material Types',
            'all_items'             => 'All Research Material Types',
            'parent_item'           => 'Parent Research Material Type',
            'parent_item_colon'     => 'Parent Research Material Type',
            'edit_item'             => 'Edit Research Material Type',
            'update_item'           => 'Update Research Material Type',
            'add_new_item'          => 'Add New Research Material Type',
            'new_item_name'         => 'New Research Material Type Name',
            'add_or_remove_items'   => 'Add or remove Research Material Types',
            'choose_from_most_used' => 'Choose from most used sfmomatheme',
            'menu_name'             => 'Research Material Type',
        );

        $args = array(
            'labels'            => $labels,
            'public'            => true,
            'show_in_nav_menus' => true,
            'show_admin_column' => false,
            'hierarchical'      => false,
            'show_tagcloud'     => true,
            'show_ui'           => true,
            'query_var'         => true,
            'rewrite'           => true,
            'query_var'         => true,
            'capabilities'      => array(),
        );

        register_taxonomy( 'research-material-type', array( 'research-materials' ), $args );

        $terms = get_terms('research-material-type');

        if( empty($terms) ){
            wp_insert_term( 'Document', 'research-material-type', array(
                'slug' => 'document',
            ) );
        }
    }

    public static function register_custom_fields(){
        acf_add_local_field_group(array(
            'key' => 'group_research_materials',
            'title' => 'Research Material Custom Fields',
            'fields' => array(
                array(
                    'key' => 'field_research_materials_slug',
                    'type' => 'text',
                    'name' => 'research_materials_slug',
                    'label' => 'Research Material Slug',
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork',
                    'type' => 'relationship',
                    'name' => 'research_materials_related_artwork',
                    'label' => 'Related Artwork',
                    'post_type' => array(
                        'artwork',
                    ),
                    'max' => 1,
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork_slug',
                    'type' => 'text',
                    'name' => 'research_materials_related_artwork_slug',
                    'label' => 'Related Artwork Slug',
                    'disabled' => 1,
                    'instructions' => 'Generated based on Related Artwork',
                )
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'research-materials',
                    ),
                )
            ),
        ));
    }

    public static function validate_saved_value_in_custom_fields($valid, $value, $field, $input){
        if( empty($value) && $field['name'] !== 'research_materials_related_artwork_slug' ){
            $valid = 'Field must not be empty!';
        }
        return $valid;
    }

    public static function set_research_material_type($post_id){
        // build main term by default term or by whatever's the first result set
        $terms = wp_get_object_terms( strval($post_id), 'research-material-type' );
        $default_term = get_term_by( 'slug', 'document', 'research-material-type' );
        if( empty($terms) ){
            wp_set_object_terms( strval($post_id), $default_term->term_id, 'research-material-type' );
        }
        else{
            wp_set_object_terms( strval($post_id), $terms[0]->term_id, 'research-material-type' );
        }
    }

    public static function build_query_vars($vars){
        $vars[] = 'research_materials_related_artwork_slug';
        $vars[] = 'research_materials_slug';
        $vars[] = 'research_materials_type';
        return $vars;
    }

    public static function update_related_artwork_slug($value, $post_id, $field){
        if( $field['name'] === 'research_materials_related_artwork_slug' ){
            $value = get_field('research_materials_related_artwork', $post_id)[0]->post_name;
        }
        return $value;
    }

    public static function pre_get_posts($query){
        // check if the user is requesting an admin page
        // or current query is not the main query
        if ( is_admin() || !$query->is_main_query() ){
            return;
        }

        $research_materials_related_artwork = get_query_var('research_materials_related_artwork_slug');

        $research_materials_slug = get_query_var('research_materials_slug');

        $research_materials_type = get_query_var('research_materials_type');

        if( !empty($research_materials_related_artwork) && !empty($research_material_slug) && !empty($research_materials_type) ){

            $meta_query = $query->get('meta_query');

            if( empty($meta_query) ){
                $meta_query = array(
                    'relation' => 'AND',
                    array(
                        'key' => 'research_materials_related_artwork_slug',
                        'value' => $research_materials_related_artwork,
                        'compare' => '==',
                    ),
                    array(
                        'key' => 'research_materials_slug',
                        'value' => $research_materials_slug,
                        'compare' => '==',
                    )
                );
            }
            else{
                $meta_query[] = array(
                    'relation' => 'AND',
                    array(
                        'key' => 'research_materials_related_artwork_slug',
                        'value' => $research_materials_related_artwork,
                        'compare' => '==',
                    ),
                    array(
                        'key' => 'research_materials_slug',
                        'value' => $research_materials_slug,
                        'compare' => '==',
                    )
                );
            }

            $query->set('meta_query', $meta_query);

            $tax_query = $query->get('tax_query');

            if( empty($tax_query) ){
                $tax_query = array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'research-material-type',
                        'field' => 'slug',
                        'terms' => array($research_materials_type),
                    )
                );
            }
            else{
                $tax_query[] = array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'research-material-type',
                        'field' => 'slug',
                        'terms' => array($research_materials_type),
                    )
                );
            }

            $query->set('tax_query', $tax_query);

        }

        return $query;
    }

    public static function rewrite_stuff(){
        add_rewrite_tag( '%research_materials_related_artwork_slug%', '([^&]+)' );
        add_rewrite_tag( '%research_materials_slug%', '([^&]+)' );
        add_rewrite_rule( '^artwork/([^/]*)/research-materials/([^/]*)/([^/]*)/?', 'index.php?post_type=research-materials&research_materials_related_artwork_slug=$matches[1]&research_materials_slug=$matches[2]&research_materials_type=$matches[3]', 'top' );
    }
}

RRP::init();

Answer: After much tinkering I figured it out. There were a lot of small things wrong with the above code and I also had to make use of the index_template hook. Here's the final code:
class RRP{
    public static function init(){
        // set up custom post types and custom taxonomies
        add_action( 'init', 'RRP::build_custom_post_types' );
        add_action( 'init', 'RRP::build_custom_taxonomy' );

        // set up custom fields
        add_action( 'acf/init', 'RRP::register_custom_fields' );

        // validate saved value in custom fields
        add_filter( 'acf/validate_value', 'RRP::validate_saved_value_in_custom_fields', 10, 4 );

        // update related artwork slug
        add_filter( 'acf/update_value', 'RRP::update_related_artwork_slug', 10, 3 );

        // add the research material type
        add_action( 'save_post_research-materials', 'RRP::set_research_material_type' );

        // build rewrite rules
        add_filter( 'index_template', 'RRP::point_artwork_and_artist_to_single_templates' );
        add_action( 'init', 'RRP::rewrite_stuff', 0 );
        add_filter( 'query_vars', 'RRP::build_query_vars', 10 );
        add_filter( 'pre_get_posts', 'RRP::pre_get_posts', 10 );

    }
    public static function build_custom_post_types(){

        $labels = array(
            'name'                => 'Research Materials',
            'singular_name'       => 'Research Material',
            'add_new'             => 'Add New Research Material',
            'add_new_item'        => 'Add New Research Material',
            'edit_item'           => 'Edit Research Material',
            'new_item'            => 'New Research Material',
            'view_item'           => 'View Research Material',
            'search_items'        => 'Search Research Materials',
            'not_found'           => 'No Research Materials found',
            'not_found_in_trash'  => 'No Research Materials found in Trash',
            'parent_item_colon'   => 'Parent Research Material:',
            'menu_name'           => 'Research    Materials',
        );

        $args = array(
            'labels'              => $labels,
            'hierarchical'        => false,
            'description'         => 'description',
            'taxonomies'          => array('research-material-type'),
            'public'              => true,
            'show_ui'             => true,
            'show_in_menu'        => true,
            'show_in_admin_bar'   => true,
            'menu_position'       => null,
            'menu_icon'           => null,
            'show_in_nav_menus'   => true,
            'publicly_queryable'  => true,
            'exclude_from_search' => false,
            'has_archive'         => true,
            'query_var'           => true,
            'can_export'          => true,
            'rewrite'             => array(
                'slug' => 'research-materials',
                'with_front' => false,
            ),
            'capability_type'     => 'post',
            'supports'            => array(
                'title', 'editor'
            )
        );

        register_post_type( 'research-materials', $args );

    }

    public static function build_custom_taxonomy(){

        $labels = array(
            'name'                  => 'Research Material Types',
            'singular_name'         => 'Research Material Type',
            'search_items'          => 'Search Research Material Types',
            'popular_items'         => 'Popular Research Material Types',
            'all_items'             => 'All Research Material Types',
            'parent_item'           => 'Parent Research Material Type',
            'parent_item_colon'     => 'Parent Research Material Type',
            'edit_item'             => 'Edit Research Material Type',
            'update_item'           => 'Update Research Material Type',
            'add_new_item'          => 'Add New Research Material Type',
            'new_item_name'         => 'New Research Material Type Name',
            'add_or_remove_items'   => 'Add or remove Research Material Types',
            'choose_from_most_used' => 'Choose from most used sfmomatheme',
            'menu_name'             => 'Research Material Type',
        );

        $args = array(
            'labels'            => $labels,
            'public'            => true,
            'show_in_nav_menus' => true,
            'show_admin_column' => false,
            'hierarchical'      => false,
            'show_tagcloud'     => true,
            'show_ui'           => true,
            'query_var'         => true,
            'rewrite'           => true,
            'query_var'         => true,
            'capabilities'      => array(),
        );

        register_taxonomy( 'research-material-type', array( 'research-materials' ), $args );

        $terms = get_terms('research-material-type');

        if( empty($terms) ){
            wp_insert_term( 'Document', 'research-material-type', array(
                'slug' => 'document',
            ) );
        }
    }

    public static function register_custom_fields(){
        acf_add_local_field_group(array(
            'key' => 'group_research_materials',
            'title' => 'Research Material Custom Fields',
            'fields' => array(
                array(
                    'key' => 'field_research_materials_slug',
                    'type' => 'text',
                    'name' => 'research_materials_slug',
                    'label' => 'Research Material Slug',
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork',
                    'type' => 'relationship',
                    'name' => 'research_materials_related_artwork',
                    'label' => 'Related Artwork',
                    'post_type' => array(
                        'artwork',
                    ),
                    'max' => 1,
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork_slug',
                    'type' => 'text',
                    'name' => 'research_materials_related_artwork_slug',
                    'label' => 'Related Artwork Slug',
                    'disabled' => 1,
                    'instructions' => 'Generated based on Related Artwork',
                )
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'research-materials',
                    ),
                )
            ),
        ));
    }

    public static function validate_saved_value_in_custom_fields($valid, $value, $field, $input){
        if( empty($value) && $field['name'] !== 'research_materials_related_artwork_slug' ){
            $valid = 'Field must not be empty!';
        }
        return $valid;
    }

    public static function set_research_material_type($post_id){
        // build main term by default term or by whatever's the first result set
        $terms = wp_get_object_terms( strval($post_id), 'research-material-type' );
        $default_term = get_term_by( 'slug', 'document', 'research-material-type' );
        if( empty($terms) ){
            wp_set_object_terms( strval($post_id), $default_term->term_id, 'research-material-type' );
        }
        else{
            wp_set_object_terms( strval($post_id), $terms[0]->term_id, 'research-material-type' );
        }
    }

    public static function build_query_vars($vars){
        $vars[] = 'research_materials_related_artwork_slug';
        $vars[] = 'research_materials_slug';
        $vars[] = 'research_materials_type';
        return $vars;
    }

    public static function update_related_artwork_slug($value, $post_id, $field){
        if( $field['name'] === 'research_materials_related_artwork_slug' ){
            $value = get_field('research_materials_related_artwork', $post_id)[0]->post_name;
        }
        return $value;
    }

    public static function pre_get_posts($query){
        // check if the user is requesting an admin page
        // or current query is not the main query
        if ( is_admin() || !$query->is_main_query() ){
            return;
        }

        $research_materials_related_artwork = $query->get('research_materials_related_artwork_slug');
        error_log(print_r($research_materials_related_artwork, true));
        $research_materials_slug = $query->get('research_materials_slug');
        error_log(print_r($research_materials_slug, true));
        $research_materials_type = $query->get('research_materials_type');
        error_log(print_r($research_materials_type, true));

        if( !empty($research_materials_related_artwork) && !empty($research_materials_slug) && !empty($research_materials_type) ){
            $meta_query = array(
                'relation' => 'AND',
                array(
                    'key' => 'research_materials_related_artwork_slug',
                    'value' => $research_materials_related_artwork,
                    'compare' => '=',
                ),
                array(
                    'key' => 'research_materials_slug',
                    'value' => $research_materials_slug,
                    'compare' => '=',
                )
            );

            $query->set('meta_query', $meta_query);

            $tax_query = array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'research-material-type',
                    'field' => 'slug',
                    'terms' => array($research_materials_type),
                )
            );

            $query->set('tax_query', $tax_query);
        }
        return $query;
    }
    // needed because I also have a CPT called artwork
    public static function point_artwork_and_artist_to_single_templates($templates = ''){
        global $post;
        if( $post->post_type == 'research-materials' ){
            $templates = locate_template( 'single-research-materials.php' );
        }
        return $templates;
    }
    public static function rewrite_stuff(){
        add_rewrite_tag( '%research_materials_related_artwork_slug%', '([^&]+)' );
        add_rewrite_tag( '%research_materials_slug%', '([^&]+)' );
        add_rewrite_tag( '%research_materials_type%', '([^&]+)' );
        add_rewrite_rule( 'artwork\/(.*)\/research-materials\/(.*)\/(.*)\/?$', 'index.php?post_type=research-materials&research_materials_related_artwork_slug=$matches[1]&research_materials_type=$matches[2]&research_materials_slug=$matches[3]', 'top' );
    }
}

RRP::init();


Method returns String and null at the same time.

Question: I'm learning Java on my own since a month, and want to create Hangman Game with GUI. I've spent 2 days trying to figure out whats going on, but cannot find the solution myself nor any help from google.
I think the problem is (except for the noobish approach for sure :P) that displayWord() method returns String AND null at the same time, but don't know how to fix that and why exactly it's giving me a null...
I'd be really grateful if someone would be so kind and point out the error.
import net.miginfocom.swing.MigLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Game {
    private CLabel guessRemainLabel = new CLabel("GUESSES REMAINING: ");
    private CTextField guessRemainField = new CTextField("");
    private CLabel wordLabel = new CLabel("WORD TO GUESS: ");
    private CTextField wordField = new CTextField("");
    private CButton[] buttons = new CButton[26];
    private CButton guessButton = new CButton("GUESS");
    private String qwerty = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    ButtonListener buttonListener = new ButtonListener();
    private char chosenChar;
    private String buttonText;

    private String wordDisplayed;
    private String wordPicked;
    private String wordChecked;
    private String word;
    private boolean buttonPressed = false;

    public Game() {
        // Frame settings
        JFrame frame = new JFrame("Hangman");
        frame.setSize(900, 600);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        MigLayout layout = new MigLayout("", // layout constrains
                "[] [] [] [] [] [] []", // columns constrains
                "[]40[]10[]30[] [] []"); // rows constrains
        JPanel panel = new JPanel();
        panel.setLayout(layout);

        frame.add(panel);

        // Remaining guesses
        panel.add(guessRemainLabel, "span 2");
        panel.add(guessRemainField, "span 7, alignleft, wrap");

        // Word
        panel.add(wordLabel, "span 7, center, wrap");
        wordField.setText(displayWord());
        panel.add(wordField, "span 7, center, wrap");

        // Buttons
        for (int i = 0; i < buttons.length; i++) {
            buttons[i] = new CButton("" + qwerty.charAt(i));
            buttons[i].addActionListener(buttonListener);
            if (i == 6 || i == 13 || i == 20) {
                panel.add(buttons[i], "wrap");
            } else {
                panel.add(buttons[i]);
            }
        }
        panel.add(guessButton, "span");
        guessButton.setPreferredSize(new Dimension(224, 50));
        guessButton.setBackground(new Color(243, 156, 18));

        newGame();

        frame.pack();
        frame.setVisible(true);
    }

    // Buttons' actions
    private class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (CButton button : buttons) {
                if (e.getSource().equals(button)) {
                    buttonText = button.getText();
                    chosenChar = button.getText().charAt(0);
                    buttonPressed = true;
                    checkWord();
                }
            }
        }
    }

    public void newGame() {
        pickWord();
        checkWord();
        displayWord();
    }

    public String pickWord() {
        WordReader wordReader = new WordReader();
        wordPicked = wordReader.getRandomWord();
        word = wordPicked;
        return wordPicked;
    }

    public String checkWord() {
        if (!buttonPressed) {
            // replace all letters with dashes
            // word.replaceAll(".","_");
        } else {
            if (word.toUpperCase().contains(buttonText)) {
                for (int i = 0; i < word.length(); i++) {
                    if (word.toUpperCase().charAt(i) == chosenChar) {
                        // show letters if char found
                    }
                }
            } else {
                // count lives left
            }
        }

        wordChecked = word;
        return wordChecked;
    }

    public String displayWord() {
        wordDisplayed = wordChecked;
        return wordDisplayed;
    }

    public static void main(String[] args) {
        // Anti-aliasing
        System.setProperty("awt.useSystemAAFontSettings", "on");
        System.setProperty("swing.aatext", "true");

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Game();
            }
        });
    }

}

Comment: Welcome to SO. Try to post MCVE code: http://stackoverflow.com/help/mcve. Also, not really related to your problem, but in general I'd avoid mixing graphics & game logic. Just a tip.
Comment: What exactly is your problem? Does it run? Just trying to get more idea to help
Comment: How do you know its return is null and a String? I don't think that's possible.
Comment: Frame runs correctly but displayWord() doesn't display anything. Checked with System.out.println it returns two values - word AND null
Comment: Not really related since it is about commented code, but `word.replaceAll(".","_");` should be `word = word.replaceAll(".","_");` (remember that strings are immutable so methods can't change them, all they can do is create new string based on old one).
Comment: Why are `pickWord(), checkWord(), displayWord()` all of return type `String`, shouldn't they be `void`?
Answer: Here's the easiest way to figure out your problem. You say that your displayWord() method is returning String and null at the same time (although that's not really possible). What this means is that:
public String displayWord() {
    wordDisplayed = wordChecked;
    return wordDisplayed;
}

In the method above, wordChecked must be null because then wordDisplayed would become null and thus the method would return null, creating your problem.
I would go through your code to where you set the value for the variable wordDisplayed and figure out if you access it BEFORE you set it, because accessing before setting a private instance variable is going to give you a null value.
EDIT: This is also a major problem. Most of your method return a String, but when you run them, you also setting the returned value to a variable. I would advise that you either chance the return type to void, because there's no reason to have the return type as String if you aren't going to use the returned value.
Comment: Deleted call to the wordDisplayed() from Game(), called wordField.setText() in wordDisplayed() instead, and it's working... Also changed return types to void. Thanks for tips!
Answer: From what you have, I believe your problem is within the method you described, displayWord(). In this method you don't initialize your wordChecked variable at all, that might throw an exception since you are using it to set wordDisplayed.


Red "x" by easy difficulty in Zombies

Question: Does anyone know why there is a red "x" by easy when you change the difficulty to easy on zombies?
Comment: I did notice on Die Rise, if you play on normal some guy speaks to you from a speaker system. That was absent from easy.
Comment: It's like they punish you for playing on easy by taking stuff out?....
Answer: The red 'X' indicates that the rounds will not count towards the zombies leaderboards.
These games will count towards your rank and progress however.
Comment: Can you still achieve the trophies under easy?
Comment: It depends on which DLC you are playing. AFIK you can get every Achievement/Trophy under easy except for the Easter Egg Achievements (Tower of Babble, High Maintenance, Pop Goes the Weasel)
Answer: It his is a really simple answer, on multiplayer custom games if you change one of the settings you get a yellow star ( to state that the default settings have been changed) zombies version of this is the red tick. It also means that the score gathered from that game won't be added to the online leader boards! Hoped this helped :)

Red "x" by easy difficulty in Zombies


GUI Debugging server app using Visual Studio Code

Question: I've been tasked with getting a GUI Debugger working for project being developed for Ubuntu 16.04 server in C++ 11.0 with BOOST.
I've got the app building and running on 'headless' Ubuntu 16.04 servers.  My boss is a windows user and wants me to set the build so that he can connect via his windows computer, and use Visual Studio Code on the server to debug the program.  I think he put it like this: "just setup X11 or some XWindows server so my box can code/debug the app."
I've gotten an x11 service up and running, and loaded up firefox in this environment, but it was painfully slow. Basically followed:
http://dasunhegoda.com/gui-ubuntu-server-x11-forwarding/679/.
Is this possible?  I desperately need suggestions, and no he doesn't want to use an Ubuntu 16.04 Desktop like I'm doing.
Comment: It's a bit of a game of chinese whispers here, but it sounds like what your boss has in mind is something like PuTTY + xming, or MobaXterm (a Windows SSH client with a built-in X server).
Comment: Mobaxterm did the trick.  Now I have to see if I can get it all working on a Docker container.....
Answer: thank you @steeldriver, MobaXTerm worked beautifully.  It's working now, but took a bit to get Visual Studio Code for linux up and working!  Once I got all the dependancies all worked out it ran pretty well on my iMac.  Can't say the same for my Windows computer, it was still a little glitchy in the window update department, but worked like I needed anyway.


Unable to move to second function after the result of the first

Question: Program Goal: Search a defined yamlfile (scan_dcn.yaml) and return all lines matching the search criteria as defined in the  function_search_search_key() and function_search_event_type() functions.
Input File - scan_dcn.yaml:
search_dict:
    [
        {search_key: ["Failed to Process the file"],
        event_type: "evttyp_repl_dcn_error",
        event_description: "Failure to process DCN file",
        priority: 50,
        scan_interval: 1,
        remove_dups: True,
        category: "dcn",
        context_begin: 0,
        context_end: 1,
        reportable: False,
        offset: 0
        },

Problem:
My program will return function_search_search_key() but will not proceed to function_search_event_type().
I would think that my problem is that I have no logic to proceed to the second function after the completion of the first.
Do I need to return a value in each function to proceed?
Python Source Code
yamlfile = open('scan_dcn.yaml', 'r')

def function_search_search_key():
    search_search_key = ['{search_key:']
    for line in yamlfile.readlines():
        for word in search_search_key:
            if word in line:
                print(line)

def function_search_event_type():
    search_event_type = ['event_type:']
    for line in yamlfile.readlines():
        for word in search_event_type:
            if word in line:
                print(line)

def main():
    function_search_search_key()
    function_search_event_type()

main()

Comment: `yamlfile.readlines()` reads all lines of the file in your first loop. When called again, it has no lines left to read. Try adding `lines = yamlfile.readlines()` at the top and replace `yamlfile.readlines()` with `lines`
Comment: You can read only once a file descriptor
Comment: It's not directly related to your issue, but why not use a library for the YAML parsing? You really should use a context manager to handle that file object. You don't need to use `.readlines()` here, by the way, you can simply iterate over the file object directly.
Comment: You make a completely valid point AMC. I'm new to programming and would rather build this properly from the ground up. I'm going to research a YAML parsing library and iterate over the file itself.
Answer: Your second function is being entered. It must if the call above it has finished.
You aren't seeing anything printed because you're attempting to loop though the same file more than once. Once you've read the file, it's exhausted. You can just re-read the file as a simple fix:
def function_search_search_key():
    with open('scan_dcn.yaml', 'r') as yamlfile:
        search_search_key = ['{search_key:']
        for line in yamlfile.readlines():
            for word in search_search_key:
                if word in line:
                    print(line)

def function_search_event_type():
    with open('scan_dcn.yaml', 'r') as yamlfile:  # Read the file again
        search_event_type = ['event_type:']
        for line in yamlfile.readlines():
            for word in search_event_type:
                if word in line:
                    print(line)

Answer: In your first function you read the whole file with readlines. When you use readlines again in your second function you're already at the end of the file and there is no more data to read, so the for loop is not even entered.
But there's no need to read the file again for every function. Read the file outside of the functions and put it in a list. Then add a parameter to each of those functions that takes this list. In the function you can loop over the list.
def function_search_search_key(lines):
    search_search_key = ['{search_key:']
    for line in lines:
        for word in search_search_key:
            if word in line:
                print(line)

def function_search_event_type(lines):
    search_event_type = ['event_type:']
    for line in lines:
        for word in search_event_type:
            if word in line:
                print(line)

def main():
    with open('scan_dcn.yaml', 'r') as yamlfile:
        lines = yamlfile.readlines()
    function_search_search_key(lines)
    function_search_event_type(lines)

if __name__ = '__main__':
    main()

If you ever need to change the name of the file you can do it in one place. If you open and read the file in every single function you would have to change all occurrances of the file name.
Comment: You presented a well-formatted and good explained question. Something like this has become rare. So I'm more than glad to help.
Answer: You can read a file descriptor only once (if you don't seek to start), so you may open your file in each function
def function_search_search_key():
    search_search_key = ['{search_key:']
    with open('scan_dcn.yaml') as fic:
        for line in fic:
            for word in search_search_key:
                if word in line:
                    print(line)

def function_search_event_type():
    search_event_type = ['event_type:']
    with open('scan_dcn.yaml') as fic:
        for line in fic:
            for word in search_event_type:
                if word in line:
                    print(line)


share it on Ubuntu 16.04

Question: I want to transfer files from my smartphone to the desktop so I can install wine and configure it with windows 7 and download share-it. It got installed alright using Wine but every time I double-click on the share-it shortcut it does not work. I am trying to find out a way to use share-it on Ubuntu 16.04
Comment: WINE is pretty much useless. Very few apps **actually** work with it.
Answer: You could try AirDroid. It is similar to SHAREit but they also have a native linux variant for transferring from Android to desktop.
There also seems to be Shareit for Linux, however I'm not sure how safe this is. Try at your own risk - http://shareitappforpc.com/shareit-for-linux-download.
These are alternatives and probably don't fix your problem.
Answer: Shareit can be installed on Ubuntu 16.04 using wine. Wine installation described here.
Comment: i already installed wine, configure it and also install share-it but it does not work.

share it on Ubuntu 16.04


Are blocking diodes necessary for solar panels

Question: In a residential solar array, bypass diodes are used when panels are in series to prevent a shaded panel from effectively becoming a large resistor. Blocking diodes prevent current from going back into a panel (or series of panels) in parallel with a load or other panel series. From what I understand, these were used in the dark ages (pun intended) of solar energy when people dumped the electricity from the panel straight into a battery bank and didn't want the reverse happening at night.
Do installers typically install blocking diodes for PV panels in parallel, such as with a string inverter?

The inverter obviously doesn't rectify current so the panels can't draw power from the AC-side, but I am worried about, for example, if Panel 1 is at a slightly higher voltage than Panel 2 and some current produced in Panel 1 being sunk by Panel 2 as a result.
In this case, I am working with "identical" (same manufacturer and model, and likely manufactured around the same date in the same facility) panels.
Comment: A photovoltaic solar cell _is_ a diode, and it points the wrong way. I don't know much about grid-tie inverters, but If you connect a solar panel directly to a battery without a blocking diode, then the solar panel will _drain_ the battery when sun isn't shining.
Comment: @jameslarge Yes, it is a photodiode, meaning there is a reverse leakage current, but grid-tied inverters don't allow backflow. There's no energy storage.
Answer: They are required.  If the panel becomes shaded it is considered DARK. If the panel is Dirty it is Dark. What happens is your produced voltage has a PATH to the other panel. The Diodes block that action - allowing current to flow in only one direction.

These blocking diodes, also called a series diode or isolation diode,
  ensure that the electrical current only flows in one direction "OUT"
  of the series array to the external load, controller or batteries.
The reason for this is to prevent the current generated by the other
  parallel connected PV panels in the same array flowing back through a
  weaker (shaded) network and also to prevent the fully charged
  batteries from discharging or draining back through the array at
  night. So when multiple solar panels are connected in parallel,
  blocking diodes should be used in each parallel connected branch.

 Excerpt above from here ^
Connecting Solar Panels / Cells
Comment: @HariGanti  Your picture does not show a microinverter installation but a central inverter. If you used a MicroInverter you would not need the blocking diodes, the microinverter takes care of that.
A shorted (even dead) battery will drain a good battery, much like the diode consuming power from the batteries is a Shunt. I used that analogy because it is easy enough to understand rather than discuss breakdown voltages of diodes. In your picture the shaded panel will load the other panel (you will lose performance) the blocking diode prevents that load from being 'seen' by the other panel.
Comment: To answer the question yes blocking diodes are still used in parallel panel setups. The diodes increase the overall effency a panel in direct sunlight compares to one that is shaded will produce different voltages that if blocking or isolation diodes are not used some of the power gets wasted on the shaded panel. The last system I installed used micro inverters at each panel , Over all cost was similar to 1 large inverter but now there are 15 inverters to fail the advantage was smaller wiring and high output voltage so voltage drops were not a problem. With parallel panels diodes are needed.
Comment: @HariGanti in string Inverter installations the answer is yes blocking diodes are required,the purpose of the diodes is not just for battery drainage, but also with partial or dark panel in a parallel setup. Microinverters are different the electronics are actually in that box to handle partial and dark situations as they are at each panel. As commented above by Ed he installed microinverters and they still used them. Microinverters convert to ac at the panel and combine all at the power panel, where as the other methods combine panels [DC] and then convert to ac at a single point.
Comment: From my understanding, voltage is relatively indifferent to irradiance. Current increases proportionally, but a panel with less incident light still produces the same voltage (which I've also tested experimentally). This is why I want to know what installers actually practice when installing parallel panels (which I'll update my question to reflect).
Comment: @HariGanti, Were you testing the open-circuit voltage? or were you testing the voltage under load?
Comment: @jameslarge It was Voc. I don't have a good load testing setup right now, but I did test Isc as well. Both panels I have were within 5% of each other's values.
Comment: @HariGanti think of your solar cells a bit like batteries. In Series you increase the voltage, in parallel you increase the current. A panel may have several cells in series to get the desired voltage and possibly cells in parallel to get the amperage. When Light increases Voltage remains constant & Current increases. Open Circuit or Load Testing will not change the physics of how they operate. Under load you have a small voltage drop naturally, ohms law. See my additional link in the answer above.
Comment: @Ken I understand the photoelectric effect quite well, but thinking of them like batteries is a bit inaccurate. I also understand what diodes do, but this addresses the issue of dark current through the panel, which is related to the reverse current through a diode. Panels can take electricity at night from batteries if simply connected to them, but not from a microinverter. Just because a panel produces less current does not make it a lower impedance pathway for the higher current panel. This is why I didn't mark it as the accepted answer.
Comment: I suppose the terminology here is kind of funny. The inverter *is* technically a microinverter (being a 250W, on-panel unit), but yes, I am using it as a string inverter. Good thing to clarify. It's also not the breakdown voltage that allows for reverse (or dark) current, but the nature of the photodiode itself. Breakdown is a different, typically very bad phenomenon. Regardless, the question still stands as whether or not blocking diodes are commonly used in string inverter installations.
Comment: @HariGanti just to finish up with one more point - I have seen studies that show MicroInverters are actually 3% less efficient than just running a central system.
Comment: @Ken I believe it depends quite heavily on your setup. In my case, a central inverter is much more expensive.


Invariants of a Reynolds stress tensor

Question: I am dealing with a Reynolds stress tensor, which arises in Navier-Stokes equations and is symmetric. By using an Ultrasound based instrument, I can read the velocity components of the fluid along three non orthogonal axis named 1-2-3. I can transform the measured velocities along these three axis in a Cartesian three orthogonal axis system x-y-z by writing the transformation matrix A and hence:
$\begin{Bmatrix}
u\\
v\\
w
\end{Bmatrix}=
\mathbf{A}\cdot \begin{Bmatrix}
u_1\\
u_2\\
u_3
\end{Bmatrix}                       $
where $\begin{Bmatrix}
u\\
v\\
w
\end{Bmatrix}$ is the velocity vector in a Cartesian orthogonal coordinate system, $u_1,u_2$ and $u_3$ are the three measured velocities along the three non orthogonal axes, $\mathbf{A}$ is the transformation matrix. The tensor transformation is:
$\mathbf{Q}^*=\mathbf{A}\cdot\mathbf{Q}\cdot\mathbf{A}^T$.
where $\mathbf{Q}$ is the Reynolds stress tensor as computed in the 1-2-3 instrument coordinate system:
$\mathbf{Q}=\begin{bmatrix}
 u_1^{\prime}u_1^{\prime}&u_1^{\prime}u_2^{\prime}  &u_1^{\prime}u_3^{\prime} \\
  u_2^{\prime}u_1^{\prime}&u_2^{\prime}u_2^{\prime}  &u_2^{\prime}u_3^{\prime} \\
  u_3^{\prime}u_1^{\prime}&u_3^{\prime}u_2^{\prime}  &u_3^{\prime}u_3^{\prime}
\end{bmatrix}$
and $\mathbf{Q}^*$ is the Reynolds stress tensor in the x-y-z coordinate system:
$\mathbf{Q}=\begin{bmatrix}
 u^{\prime}u^{\prime}&u^{\prime}v^{\prime}  &u^{\prime}w^{\prime} \\
  v^{\prime}u^{\prime}&v^{\prime}v^{\prime}  &v^{\prime}w^{\prime} \\
   w^{\prime}u^{\prime}&w^{\prime}v^{\prime}  &w^{\prime}w^{\prime}
\end{bmatrix}$
The prime indicates that that the variable is the fluctuating part and the overline indicates the mean value, e.g. $u=\overline{u}+u^{\prime}$.
One half of the trace of the tensor $\mathbf{Q}^*$ is the turbulent kinetic energy of the fluid (per unit mass) and should be invariant. Indeed it is invariant as long as the transformation matrix $\mathbf{A}$ is orthogonal, i.e. $\mathbf{A}^{-1}=\mathbf{A}^T$ but it is not for general transformation matrix. In fact the trace of the tensor $\mathbf{Q}$ is different from the trace of the tensor $\mathbf{Q}^*$ if $\mathbf{}$ is the non-orthogonal transformation matrix between the two coordinate system 1-2-3 and x-y-z.
I wonder if the invariants of a tensor are really invariant (i.e. assume the same value) only for specific class of transformations (e.g. for similarity transformations).
Comment: Are you sure your tensor transformation is correct? Assuming your tensor is $(1, 1)$, it should be $Q \mapsto AQA^{-1}$, and $A^T = A^{-1}$ only for orthogonal matrices :)
Comment: @Alexei: I believe the transformation is correct. If you write $\vec{v}$ to be the velocity vector, the tensor $\mathbf{Q} = \vec{v}\otimes \vec{v}$ or $\vec{v}~\vec{v}^T$. In other words, $\mathbf{Q}$ is a type (0,2) or (2,0) tensor, so the coordinate transformation law is correct. (What you wrote would be the transformation law for a linear transformation, a type (1,1) tensor.)
Comment: @Willie: Well, yeah, I agree with you. But stress tensor canonically *is* a (1,1)-tensor, it maps direction to the force acting in it (or is force a covector? I dunno). If it's (0,2) tensor, though, then you first have to raise an index with a metric, just like you wrote.
Comment: @Alexei: mmm, I don't think I completely agree. The stress-energy tensors for classical field theories is, like you say, canonically a (1,1) tensor; but the [Cauchy stress tensor](http://en.wikipedia.org/wiki/Cauchy_stress_tensor) is defined to be (0,2), and in using it one usually consider its transpose (which is a (2,0) tensor) acting on directions *through dot product*. We in the modern age have the benefit of hindsight that stress tensors *should* be (1,1). But I don't think Reynolds or Cauchy or Biot had that opportunity.
Answer: The problem is that you are not defining "trace" correctly.
The trace of a rank 2 tensor is only equivalent to the sum of the diagonal entries of its matrix representation if the tensor is type (1,1). (Type (1,1) here means that the tensor represents a linear transformation; or equivalently that the matrix representation transforms like $\mathbf{Q} \to A\mathbf{Q}A^{-1}$ under change of basis/coordinates in the vector space.)
The Reynold stress tensor as you defined it is a type (0,2) (or type (2,0), depending on your convention) tensor, so its transformation law is $\mathbf{Q} \to A\mathbf{Q}A^T$. This type of tensors cannot be "traced"...until you specify what you are tracing with respect to. To be able to trace, you need to first multiply a type (0,2) tensor against a type (2,0) tensor to form a type (1,1) tensor, and then you can perform the trace. The type (2,0) tensor in this case is the symmetric bilinear form that corresponds to the Euclidean inner product.

In other words, going back to the more physical part of the story: the kinetic energy is an invariant, but you are just computing it wrong. Think about the case where you have just a particle. The kinetic energy of a particle is $\frac12 m \vec{v}\cdot\vec{v}$. In an orthonormal coordinate system
$$ \vec{v}\cdot \vec{v} = (v_x)^2 + (v_y)^2 + (v_z)^2 $$
but in a coordinate system that is not orthonormal, the dot product is not given by just the sum of the squares of the components! (For example, consider spherical or cylindrical coordinates!)

Invariants of a Reynolds stress tensor


Xrandr gives wrong info about screen connections?

Question: After a fresh install of Ubuntu 22.04 LTS I fail to get my second screen to work. Google does not turn up much useful, nothing that has worked yet. So after spent a couple of days searching, I decided to try to both up- and downgrade the kernel, but had no effect on this at all. I then detached the cable for the second screen (USB-C/DisplayPort) and kept only the HDMI between the comp and screen. To my great surprise, when issuing the command xrandr -q it wants me to believe I am connected through DisplayPort, which I am not.
I have not seen this talked about anywhere I have looked, but have read several reports of second screens suddenly not working after fresh installs and upgrades, and that xrandr only shows one of two attached screens etc, but no fix or cause. The closest thing would be a mention it may be an issue with the current kernel somehow.
Below is what it looks like. The first command was before I disconnected the other screen - should've shown both, the second after re-installation with that detached - this should have been shown for the HDMI-1 port...
Ideas anyone?
$ xrandr --listproviders
Providers: number : 1
Provider 0: id: 0x47 cap: 0x9, Source Output, Sink Offload crtcs: 4 outputs: 5 associated providers: 0 name:modesetting

$ xrandr -q
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 16384 x 16384
DP-1 disconnected (normal left inverted right x axis y axis)
DP-2 disconnected (normal left inverted right x axis y axis)
HDMI-1 disconnected (normal left inverted right x axis y axis)
DP-3 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 621mm x 341mm
   1920x1080     60.00*+  50.00    59.94
   1920x1080i    60.00    50.00    59.94
   1680x1050     59.88
   1280x1024     75.02    60.02
   1440x900      59.90
   1280x960      60.00
   1152x864      75.00
   1280x720      60.00    50.00    59.94
   1440x576      50.00
   1024x768      75.03    70.07    60.00
   1440x480      60.00    59.94
   832x624       74.55
   800x600       72.19    75.00    60.32    56.25
   720x576       50.00
   720x480       60.00    59.94
   640x480       75.00    72.81    66.67    60.00    59.94
   720x400       70.08
DP-4 disconnected (normal left inverted right x axis y axis)

Comment: Are you using x11? 22.04 uses Wayland by default so xrandr won't work correctly.
Comment: Yes, I am using X11. I started using Wayland, and then tested along and ended up with x11 for the moment. I'm happy with either really
Answer: Found the issue - what is going on is beyond me though, if anyone knows, please enlighten me.
When re-installing Ubuntu I also upgraded the BIOS, and when at that disabled some stuff I don't use, amongst others support for ThunderBolt...
Turns out this is actually needed(?!) for my USB-C ports to function. After enabling it, USB-C now works again. However, Xrandr still thinks my HDMI is DP, but not an issue for me at this point;
$ xrandr --listmonitors
Monitors: 2
 0: +*DP-3 1920/621x1080/341+3840+0  DP-3
 1: +DP-1 3840/697x2160/392+0+0  DP-1


Sequential Asynchronous Tasks Without Blocking

Question: I have a C# WPF application using a rather noddy MVVM approach.  In one of the ViewModels I would like to run a sequence of tasks sequentially but would like to run each asynchronous to the main thread.  I want the granularity of being able to report progress between tasks but I don't want to block the GUI while any of the tasks is running.
Is there a standard way of achieving this, or a "best practice"?
I have implemented something that makes use of BackgroundWorker that I feel at once happy and mildly horrified with.  The code to kick the whole thing off feels especially non-C#ish.  I feel there must be a better or, at least, an established way of doing this.
Many thanks for your suggestions.
Dan

Here's the cobbled-together option:
protected void runAsyncTask(SequentialTask seqTask)
    {
        if (HasErrored) return;

        DoWorkEventHandler worker = (s, e) =>
        {
            setTaskStartStatusMessage(seqTask.TaskMessage);
            ShowProgress = true;
            seqTask.Task((BackgroundWorker)s);
        };

        ProgressChangedEventHandler progress = (s, e) =>
        {
            if (seqTask.TaskProgress != null)
                seqTask.TaskProgress(e.ProgressPercentage, e.UserState);
        };

        RunWorkerCompletedEventHandler done = null;
        done = (s, e) =>
        {
            ShowProgress = false;
            if (e.Error != null)
            {
                HasErrored = true;
                displayTaskExceptionMessage(e.Error, seqTask.TaskMessage);
            }
            else
            {
                setTaskCompleteStatusMessage(seqTask.TaskMessage);
                if (seqTask.TaskComplete != null)
                    seqTask.TaskComplete();
            }
            ((BackgroundWorker)s).RunWorkerCompleted -= done;
            ((BackgroundWorker)s).DoWork -= worker;
            ((BackgroundWorker)s).ProgressChanged -= progress;

            if (seqTask.NextTask != null && (seqTask.CanExecuteNext == null ? true : seqTask.CanExecuteNext()))
                runAsyncTask(seqTask.NextTask);
        };

        if (seqTask.TaskProgress != null)
            backgroundWorker.WorkerReportsProgress = true;
        backgroundWorker.DoWork += worker;
        backgroundWorker.RunWorkerCompleted += done;
        backgroundWorker.ProgressChanged += progress;
        backgroundWorker.RunWorkerAsync();
    }

SequentialTask is just a simple set of Properties:
public class SequentialTask
{
    public Action<BackgroundWorker> Task { get; set; }
    public String TaskMessage { get; set; }
    public Func<bool> CanExecuteNext { get; set; }
    public Action<int, object> TaskProgress { get; set; }
    public Action TaskComplete { get; set; }
    public SequentialTask NextTask { get; set; }
}

Which leads to the Perl-like syntax of:
runAsyncTask(new SequentialTask()
        {
            Task = (x) => loadFile(),
            TaskMessage = "Load File",
            CanExecuteNext = null,
            NextTask = new SequentialTask()
            {
                Task = (x) => validateImport(),
                TaskMessage = "Validate Input Lines",
                TaskComplete = () =>
                {
                    if (!ImportIsValid)
                        displayValidationMessages();
                },
                CanExecuteNext = () => ImportIsValid,
                NextTask = new SequentialTask()
                {

etc.
Comment: Coroutines or Reactive Framework are a good fit for this: http://csharperimage.jeremylikness.com/2010/03/sequential-asynchronous-workflows-in.html
Comment: Hi Jay, thanks for the link - had a quick look over and it's something I'll definitely spend the time getting my head around but I think Adam's TPL suggestion is where I'll spend my initial efforts.
Answer: Have you looked at the Task Parallel Library (TPL) in .NET 4.0?  This allows you to do things like this:
Task firstTask = new Task(()=>RunStepOne());
firstTask.ContinueWith(task=>()=>RunSecondStep());
firstTask.Start();

There are a ton of options for creating, continuing, and stopping tasks built on the TPL.  It will certainly be worth a look.
Comment: Not to mention that this will give you a leg up when C# 5 is released.
Comment: Thanks Adam,  that's the next chapter in C# in a Nutshell - I'll get on and have a look.  From the snippet you've shown it certainly looks a lot cleaner than chaining recursive structures.
Comment: I think that this definitely gives me what I want and in an "out-of-the-box", thanks again.
Answer: I don't see anything wrong with your approach.  And the most important thing is: it works.