text:
Q: symmetric DS registration fails on tomcat I am trying to run symmetric DS war on tomcat. Below ar the steps I followed :

*

*I have created war using this command:
command: ../bin/symadmin create-war /root/symmetric-ds.war

*Then I deployed war on the tomcat.

*When my client node tries to register with master node it gives following
error as shown below:
[SGW-000] - DataLoaderService - Requesting current configuration {symmetricVersion=3.8.28, configVersion=null}
[SGW-000] - PullService - Could not communicate with node 'null:null:?' at http://10.97.57.75:31415/symmetric-ds/sync because of unexpected error
java.io.IOException: Server returned HTTP response code: 403 for URL: http://10.97.57.75:31415/symmetric-ds/sync/config?nodeId=000&securityToken=07a654896b216bfd6acb9746470f73&hostName=mc-ha-vm1.edcharman.com&ipAddress=10.97.57.74&symmetricVersion=3.8.28&configVersion=
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1926)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1921)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1920)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1490)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at org.jumpmind.symmetric.transport.http.HttpTransportManager.getInputStreamFrom(HttpTransportManager.java:301)
at org.jumpmind.symmetric.transport.http.HttpIncomingTransport.openStream(HttpIncomingTransport.java:118)
at org.jumpmind.symmetric.transport.http.HttpIncomingTransport.openReader(HttpIncomingTransport.java:125)
at org.jumpmind.symmetric.service.impl.DataLoaderService.loadDataFromTransport(DataLoaderService.java:554)
at org.jumpmind.symmetric.service.impl.DataLoaderService.loadDataFromConfig(DataLoaderService.java:487)
at org.jumpmind.symmetric.service.impl.PullService.pullConfigData(PullService.java:170)
at org.jumpmind.symmetric.AbstractSymmetricEngine.start(AbstractSymmetricEngine.java:623)
at org.jumpmind.symmetric.AbstractSymmetricEngine.start(AbstractSymmetricEngine.java:571)
at org.jumpmind.symmetric.ClientSymmetricEngine.start(ClientSymmetricEngine.java:244)
at org.jumpmind.symmetric.web.SymmetricEngineHolder$EngineStarter.run(SymmetricEngineHolder.java:524)
Caused by: java.io.IOException: Server returned HTTP response code: 403 for
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at org.jumpmind.symmetric.transport.http.HttpIncomingTransport.openConnectionCheckRedirects(HttpIncomingTransport.java:159)
at org.jumpmind.symmetric.transport.http.HttpIncomingTransport.openStream(HttpIncomingTransport.java:99)
... 8 more
Can anyone please help here ?

A: I think running symmetric DS with Tomcat is little bit tricky for new comers. So I sharing steps that worked for me:
sync url on master node:
sync.url=https://masterNodeIP:31415/warName/sync
register url on client node:
sync.url=https://masterNodeIP:31415/warName/sync

*

*Go to symmetric-ds-3.x.x-server/bin folder and create symmetric-ds.war:
./symadmin create-war /Path of war/symmetric-ds.war

*Copy war to /tomcat/webeapps folder.

*copy postgresql-9.4-1212.jre7.jar file from ~/symmetric-server-3.8.28/lib to
~/apache-tomcat-8.0.24/webapps/symmetric-ds/WEB-INF/lib folder

*Do following port configuration in /tomcat.x.x/conf/server.xml

*Execute below command on master node to open registration:
master node id: ABC-000
client node group: XYZ
Clinet node external id: 001
../bin/symadmin --engine ABC-000 open-registration XYZ 001


text:
Q: Why do I receive this error when I use LINQ in MVC? I have a table named Student in my linq in model folder. When I run my app and I click on student tab this error appears on IE. I don't have any idea why I see this.
Compiler Error Message:

CS0012: The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Source Error:

Line 27:
  Line 28:
  Line 29:     public class _Page_Views_Student_Index_cshtml : System.Web.Mvc.WebViewPage> {
  Line 30:
  Line 31: #line hidden

Source File:

c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\682ba75a\2833b27b\App_Web_index.cshtml.b4fd288c.t7qdtf0f.0.cs    Line: 29

A: You need to add a reference to System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 in your project. Pretty much as the error is saying.
You must add a reference to assembly 'System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
You can do this by either right clicking the project and clicking Add Reference and navigating to System.Data.Linq or you can do it manually in your Web.Config.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django ORM repeats DB columns when trying to save() I'm working with an old legacy database, and I'm having trouble with working out the correct way to perform an insert into this database. When I'm trying to save() an object i get SQL error

CUSTOMER_ID cannot be repeated in INSERT statement

This is caused (I believe) by the way I had to create foreign key connection:
customer_id = models.IntegerField(db_column='CUSTOMER_ID')
tbcustomer = models.ForeignKey(TbCustomer, db_column='CUSTOMER_ID', to_field='customer_id')

The customer_id integer field must stay! I know this structure is ugly,  but the database is really old and I'm in no position to change it.
Should I rethink this foreign key implementation, or would it be possible to overcome this error in other way (custom save() method maybe?). Any suggestions are welcome, Thanks.


text:
Q: Removing common words from a searched for string PHP OK, so I have a string of words delimited by space i.e.
$commonwords = 'a,an,and,I,it,is,do,does,for,from,go,how,the,etc';
And I receive a search query from $_POST['searchquery'];
I want to remove any common words from the search string, what I am looking for as an end result will be more concise keywords that I can then use to query the database.
So if the user searches for "How do I search for files"
The string becomes "search files" when all common words are removed.

A: This will work but you will have to add the capitalized "how" to your $commonwords

$commonwords = 'a,an,and,I,it,is,do,does,for,from,go,how,the,etc';

$commonwords = explode(",", $commonwords);

$search = "How do I search for files";

$search = explode(" ", $search);

foreach($search as $value){
    if(!in_array($value, $commonwords)){
        echo "$value<br/>";
        $query[] = $value;
    }
}

    $query = implode(" ", $query);

    echo $query;
?>

A: Here is a lib to remove stop words: Remove Stop Words. You can use it like this:
echo remove_stop_words('The quick brown fox jumps over the lazy dog');
// quick brown fox jumps   lazy dog

A: Try this (CodePad):
<?php

$commonwords = 'a,an,and,I,it,is,do,does,for,from,go,how,the,etc';
$commonwords = explode(',', $commonwords);

$_POST['searchquery'] = "How do I search for files";
$_POST['searchquery'] = explode(' ', $_POST['searchquery']);
echo implode(' ', array_udiff($_POST['searchquery'], $commonwords, 'strcasecmp'));

It first explodes both strings (your list, and the query) into workable arrays. Then it filters the differences and outputs the imploded array.
Output:
search files

A: For better result, convert common words and search words in to lower or upper case, here I used lowercase,
<?php
$commonwords = 'a,an,and,i,it,is,do,does,for,from,go,how,the,etc';

$commonwords = explode(",", $commonwords);

$search = strtolower("How do I search for files");

$search = explode(" ", $search);

foreach($search as $value){
    if(!in_array($value, $commonwords)){
       $query[] = $value;
    }
}

    $query = implode(" ", $query);

    echo $query; // this is output
?>


text:
Q: How to view 'only those commits' where were added since the repo was cloned? I cloned a git repository
git clone xyz.git

*

*I
modified a file (say 'a.txt'), added and committed it locally.

*Again,  I modified a file (say 'b.txt'), added and committed it locally.

*I did NOT push the changes to remote

The git log produces the entire list of commits.

I would like to view only the commits which were added since the repository was cloned.
Is there any way to accomplish this?

A: "Since cloned" is difficult, or even impossible, depending on what information you specifically saved right after cloning, or how long it has been since then.  But it's also not useful, so it doesn't matter how difficult it is: "since cloned" is the wrong question to ask.  (For a very flawed analogy, imagine trying to catch an escaped animal.  The interesting question is not where it was three weeks ago, but rather where it is now.)
When you have a remote—which is just a short name, like origin, for another URL where there is another Git repository that contains commits—the interesting question is not What do I have that they didn't back when I ran git clone? but rather What do I have that they don't have the last time I saw what they have?  And that is a question Git will answer, because your Git records, in your repository, its memory of what they had the last time you connected to them.
If you have a branch master that your Git made from their branch master, your Git also has its memory of "where their master was, the last time we talked to them."  That memory is stored in origin/master.  Therefore, you can run:
git log origin/master..master

which means "show me what I have on my master, that is not also on origin/master".
If you run:
git fetch origin

(which you can do at any time), that tells your Git: Connect to the other Git over at origin, and pick up whatever new items they have, and update my origin/master and other origin/ remote-tracking branch names.
Similarly, when you run:
git push origin master

that tells your Git: Connect to the other Git at origin, give them my new commits, and ask them to set their master to the same thing as my master.  If they—the other Git at origin—agree to the request to update their master, your Git records that in your origin/master, since your Git knows their Git is updated.

A: @torek brings up a good point, which is that it's tricky to tell when a repository was cloned. However, it's very easy to get a list of commits between your remote branch and your local branch.
Use
git log HEAD...origin/your_branch

HEAD is where the tip of your local branch currently sits.
origin/your_branch is where the repo has the tip of the remote branch

From the git help log page:
git log [<options>] [<revision range>] [[--] <path>...]

   <revision range>
       Show only commits in the specified revision range. When no <revision range> is specified, it
       defaults to HEAD (i.e. the whole history leading to the current commit).  origin..HEAD
       specifies all the commits reachable from the current commit (i.e.  HEAD), but not from origin.
       For a complete list of ways to spell <revision range>, see the Specifying Ranges section of
       gitrevisions(7).


text:
Q: AppServiceConnection re-constructing already running app We have a UWP app with a full-trust component in which the communication is handled through an AppServiceConnection (like this). In handling the case where the full-trust component goes down (for whatever reason, as described here), I occasionally see the already-running UWP app get reconstructed, instead of just background activated.
The docs aren't incredibly descriptive, but it seems like OnBackgroundActivated on the UWP side should be called on the running instance. This is what has been happening until recently.
I haven't been able to pin down anything surrounding the cases where the UWP app gets reconstructed vs just background activated, but it causes problems because whatever state the running instance had in the App class is gone after getting reconstructed.


text:
Q: Authentication - Only HTTPS scheme is allowed Currently working on an app that is connecting to Azure Mobile Services, and needs to require a Microsoft Account to authenticate.
I have been following this guide:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-universal-dotnet-get-started-users/ Unforunately I have run into this error: Only https scheme is allowed. and I am not entirely sure on how to fix it.
Screenshot of error: http://i.stack.imgur.com/hod9i.png
My code is as follows and comes from the guide listed above.
        private async void executiveLoginBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            await AuthenticateAsync();
        }

        // Define a member variable for storing the signed-in user.
        private MobileServiceUser user;

        // Define a method that performs the authentication process
        // using a Facebook sign-in.
        private async System.Threading.Tasks.Task AuthenticateAsync()
        {
            while (user == null)
            {
                string message;
                try
                {
                    // Change 'MobileService' to the name of your MobileServiceClient instance.
                    // Sign-in using Facebook authentication.
                    user = await App.MobileService
                        .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
                    message =
                        string.Format("You are now signed in - {0}", user.UserId);
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }

                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }
        }

The error also says "WinRT Information: URI Scheme is not https" - so how could I go about making the URI scheme https or otherwise fixing this error when authenticating to Azure Mobile Services?

A: 1) Select the local MobileService project in Solution Explorer.
2) In the Properties window, change SSL Enabled to True.
3) Take note of the SSL URL and use that address to initialize the MobileServiceClient object in your client application.

A: How I fix the error is as follows:

*

*SSL Enabled to True.

*http://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-register-microsoft-authentication/
Input to Redirect URL

*App.xaml.cs
public static MobileServiceClient MobileService = new MobileServiceClient("http://service.azure-mobile.net/", "---------------------");
Change to
public static MobileServiceClient MobileService = new MobileServiceClient("https://service.azure-mobile.net/", "---------------------");


text:
Q: How to bold a specific substring in a string of xml node using XSLT while transforming into HTML I have to render a certain substring in the string of a XML node bold and change the color in html file while transforming a XML file using XSLT. I am using Vi sual studio 12.0 and not able to use XSLT 2.0 features like tokenize(),analyze-string() etc and I am new to XSLT.
The following is the XMLNode:
<LogMsg>
   Not able to do the given task as expected because of this **{reason}**.Please verify it.
</Logmsg>

I have to show the message present in flower braces in bold and red color while rendering in HTML.
The below is the part of XSLT code used in our application:
<xsl:for-each select="./LogMsg">
   <pre>
      <xsl:value-of select="."/>
   </pre>
</xsl:for-each>

Any help in this regards is very much thankful.
Regards,
Nagasree.

A: If

*

*the value of LogMsg is always a string (no child elements), and

*there is always exactly one part of the string that must be colored reed and wrapped in braces, and

*the part that must be colored red and wrapped in braces is always preceded by **( and followed by )**,

then it's straightforward to isolate the relevant part of the string:
<xsl:template match="LogMsg">
  <xsl:variable name="s1" select="substring-before(.,'**(')"/>
  <xsl:variable name="s2"
      select="substring-before(substring-after(.,'**('),')**')"/>
  <xsl:variable name="s3" select="substring-after(.,')**')"/>
  <pre>
    <xsl:value-of select="$s1"
    /><xsl:text>**(</xsl:text
    ><b style="color: red;"
    ><xsl:value-of select="$s2"
    /><xsl:text>)**</xsl:text
    ><xsl:value-of select="$s3"/>
  </pre>
</xsl:template>

If the **( and )** are not present in the input, but the LogMsg always begins with "Not able to do the given task as expected because of this " and ends with ".Please verify it.", then it's equally simple to isolate the middle part of the message, using substring-before() and substring-after().  I'll leave the details as an exercise for the reader.
If neither of those sets of assumptions hold, then your question may need clarification.


text:
Q: Connecting untrained python predictive model to backend I already have a built predictive model written in Python, however currently it is executed by hand and functions on a single data file. I am hoping to generalize the model so that it can read in different datasets from my backend, each time effectively producing a different model since we are using different data for training as well. How would I be able to add the model onto my backend then?

A: Store the model as a pickle and read it from your backend when you need analog to your training data.
But you might want to checkout MLFlow for an integrated model handling solution. It is possible to run it on prem. With MLFlow you can easily implement a proper ML lifecycle. You can store your training stats and keep the history of your trained models.


text:
Q: Increase resolution in X-axis for an existing x-y graph in MATLAB In MATLAB, I have an existing set of values for X,Y where X = [0,1,2, ... 255], and Y is in the range of -5 to 4.
When I plot this graph MATLAB, obviously interpolates these values.
I require to increase the resolution of the X-axis to X = [0, 0.25, 0.5, 0. 75, 1 .... 254.75, 255].
I am not looking for a simple averaging kind of operation. Rather I want it to be as good as MATLAB which does it very smoothly. Please guide me.

A: A few things to know:

*

*Matlab doesn't interpolate if you haven't made it interpolate. The figure you see is scalable, so there is no interpolation, at most a line connecting between adjacent dots.

*If you want to interpolate just use interp1....
fore example,
 Xnew= 0:0.25:255;
 Ynew=interp1(X,Y,Xnew,'spline');
 plot(Xnew,Ynew);

should do.


text:
Q: Implementing current html into WordPress navigation I have a piece of code in html. I would like my menu i WordPress to be like this accordion.
This is my html

Menu 1

Submenu 1

Submenu 2

Menu 2

Javascript

jQuery

In funtions.php I have the following code where I call the navigation function.
function bh_nav()
{
    wp_nav_menu(
    array(
        'theme_location'  => 'header-menu',
        'menu'            => '',
        'container'       => false,
        'container_class' => 'menu-{menu slug}-container',
        'container_id'    => '',
        'menu_class'      => '',
        'menu_id'         => '',
        'echo'            => true,
        'fallback_cb'     => 'wp_page_menu',
        'before'          => '',
        'after'           => '',
        'link_before'     => '',
        'link_after'      => '',
        'items_wrap'      => '
%3$s
',
        'depth'           => 0,
        'walker'          => ''
        )
    );
}

I call the function with the following code
How do I make my navigation generate the html above?

A: Please check updated code:
 wp_nav_menu( array(
    'theme_location' => 'primary',
    'container' => false,
    'items_wrap' => '
%3$s
',
    'walker' => new Walker_Nav_Menu_add
));

Code for function.php
    class Walker_Nav_Menu_add extends Walker {
    /**
     * What the class handles.
     *
     * @since 3.0.0
     * @var string
     *
     * @see Walker::$tree_type
     */
    public $tree_type = array( 'post_type', 'taxonomy', 'custom' );

    /**
     * Database fields to use.
     *
     * @since 3.0.0
     * @todo Decouple this.
     * @var array
     *
     * @see Walker::$db_fields
     */
    public $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );

    /**
     * Starts the list before the elements are added.
     *
     * @since 3.0.0
     *
     * @see Walker::start_lvl()
     *
     * @param string   $output Used to append additional content (passed by reference).
     * @param int      $depth  Depth of menu item. Used for padding.
     * @param stdClass $args   An object of wp_nav_menu() arguments.
     */
    public function start_lvl( &$output, $depth = 0, $args = array() ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent = str_repeat( $t, $depth );

        // Default class.
        $classes = array( 'submenu' );

        /**
         * Filters the CSS class(es) applied to a menu list element.
         *
         * @since 4.8.0
         *
         * @param array    $classes The CSS classes that are applied to the menu `<ul>` element.
         * @param stdClass $args    An object of `wp_nav_menu()` arguments.
         * @param int      $depth   Depth of menu item. Used for padding.
         */
        $class_names = join( ' ', apply_filters( 'nav_menu_submenu_css_class', $classes, $args, $depth ) );
        $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

        $output .= "{$n}{$indent}
{$n}";
    }

    /**
     * Ends the list of after the elements are added.
     *
     * @since 3.0.0
     *
     * @see Walker::end_lvl()
     *
     * @param string   $output Used to append additional content (passed by reference).
     * @param int      $depth  Depth of menu item. Used for padding.
     * @param stdClass $args   An object of wp_nav_menu() arguments.
     */
    public function end_lvl( &$output, $depth = 0, $args = array() ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent = str_repeat( $t, $depth );
        $output .= "$indent
{$n}";
    }

    /**
     * Starts the element output.
     *
     * @since 3.0.0
     * @since 4.4.0 The {@see 'nav_menu_item_args'} filter was added.
     *
     * @see Walker::start_el()
     *
     * @param string   $output Used to append additional content (passed by reference).
     * @param WP_Post  $item   Menu item data object.
     * @param int      $depth  Depth of menu item. Used for padding.
     * @param stdClass $args   An object of wp_nav_menu() arguments.
     * @param int      $id     Current item ID.
     */
    public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent = ( $depth ) ? str_repeat( $t, $depth ) : '';

        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;

        /**
         * Filters the arguments for a single nav menu item.
         *
         * @since 4.4.0
         *
         * @param stdClass $args  An object of wp_nav_menu() arguments.
         * @param WP_Post  $item  Menu item data object.
         * @param int      $depth Depth of menu item. Used for padding.
         */
        $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );

        /**
         * Filters the CSS class(es) applied to a menu item's list item element.
         *
         * @since 3.0.0
         * @since 4.1.0 The `$depth` parameter was added.
         *
         * @param array    $classes The CSS classes that are applied to the menu item's `<li>` element.
         * @param WP_Post  $item    The current menu item.
         * @param stdClass $args    An object of wp_nav_menu() arguments.
         * @param int      $depth   Depth of menu item. Used for padding.
         */
        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
        $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

        /**
         * Filters the ID applied to a menu item's list item element.
         *
         * @since 3.0.1
         * @since 4.1.0 The `$depth` parameter was added.
         *
         * @param string   $menu_id The ID that is applied to the menu item's `<li>` element.
         * @param WP_Post  $item    The current menu item.
         * @param stdClass $args    An object of wp_nav_menu() arguments.
         * @param int      $depth   Depth of menu item. Used for padding.
         */
        $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
        $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

        $output .= $indent . '
';

        $atts = array();
        $atts['title']  = ! empty( $item->attr_title ) ? $item->attr_title : '';
        $atts['target'] = ! empty( $item->target )     ? $item->target     : '';
        $atts['rel']    = ! empty( $item->xfn )        ? $item->xfn        : '';
        $atts['href']   = ! empty( $item->url )        ? $item->url        : '';

        /**
         * Filters the HTML attributes applied to a menu item's anchor element.
         *
         * @since 3.6.0
         * @since 4.1.0 The `$depth` parameter was added.
         *
         * @param array $atts {
         *     The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
         *
         *     @type string $title  Title attribute.
         *     @type string $target Target attribute.
         *     @type string $rel    The rel attribute.
         *     @type string $href   The href attribute.
         * }
         * @param WP_Post  $item  The current menu item.
         * @param stdClass $args  An object of wp_nav_menu() arguments.
         * @param int      $depth Depth of menu item. Used for padding.
         */
        $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );

        $attributes = '';
        foreach ( $atts as $attr => $value ) {
            if ( ! empty( $value ) ) {
                $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
                $attributes .= ' ' . $attr . '="' . $value . '"';
            }
        }

        /** This filter is documented in wp-includes/post-template.php */
        $title = apply_filters( 'the_title', $item->title, $item->ID );

        /**
         * Filters a menu item's title.
         *
         * @since 4.4.0
         *
         * @param string   $title The menu item's title.
         * @param WP_Post  $item  The current menu item.
         * @param stdClass $args  An object of wp_nav_menu() arguments.
         * @param int      $depth Depth of menu item. Used for padding.
         */
        $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );

        $item_output = $args->before;

        if($depth=='0'){
        $item_output .= '
';
        $item_output .= $args->link_before . $title . $args->link_after;
        $item_output .= '
';
        }
        else if($depth=='1'){
        $item_output .= '';
        $item_output .= $args->link_before . $title . $args->link_after;
        $item_output .= '';
        }

        $item_output .= $args->after;

        /**
         * Filters a menu item's starting output.
         *
         * The menu item's starting output only includes `$args->before`, the opening `<a>`,
         * the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
         * no filter for modifying the opening and closing `<li>` for a menu item.
         *
         * @since 3.0.0
         *
         * @param string   $item_output The menu item's starting HTML output.
         * @param WP_Post  $item        Menu item data object.
         * @param int      $depth       Depth of menu item. Used for padding.
         * @param stdClass $args        An object of wp_nav_menu() arguments.
         */
        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }

    /**
     * Ends the element output, if needed.
     *
     * @since 3.0.0
     *
     * @see Walker::end_el()
     *
     * @param string   $output Used to append additional content (passed by reference).
     * @param WP_Post  $item   Page data object. Not used.
     * @param int      $depth  Depth of page. Not Used.
     * @param stdClass $args   An object of wp_nav_menu() arguments.
     */
    public function end_el( &$output, $item, $depth = 1, $args = array() ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $output .= "
{$n}";
    }

} // Walker_Nav_Menu


text:
Q: How do i change the size of a CheckBox Title or make it Wrap in a PreferenceScreen xml? I'm writing a preference screen in in xml for my Android application. My issue is that some of the titles of the preferences are too long and will not wrap the page. Consider my example:
 <CheckBoxPreference
                android:title="Language Detection (BETA)"
                android:defaultValue="false"
                android:summary="Automatically decide which language to use"
                android:key="lan_det_pref"
                android:textSize="15px"
                android:lines="4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                />

Maybe I'm missing something but I have tried using number of other properties with no positive results. I have tried android:singleLine, android:lines, etc., and none of these seem to effect the title of the preference. Also is there a way to scale down the size of a CheckBox title?
Any help would be greatly appreciated.
Thanks :)

A: You could customize you checkbox like this:
MyPreference.xml
<CheckBoxPreference android:key="testcheckbox"
    android:title="Checkbox Title"
    android:summary="Checkbox Summary..."
    android:layout="@layout/custom_checkbox_preference_layout">
</CheckBoxPreference>

and custom_checkbox_preference_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:paddingLeft="16dip"
    android:paddingRight="?android:attr/scrollbarSize">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="horizontal">
        <ImageView
            android:id="@+android:id/icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="6dip"
        android:layout_marginTop="6dip"
        android:layout_marginBottom="6dip"
        android:layout_weight="1">

        <TextView android:id="@+android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="false"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal" />

        <TextView android:id="@+android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignLeft="@android:id/title"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="?android:attr/textColorSecondary"
            android:maxLines="4" />

    </RelativeLayout>

    <!-- Preference should place its actual preference widget here. -->
    <LinearLayout android:id="@+android:id/widget_frame"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical" />

</LinearLayout>

the point is android:singleLine="false"".

A: A CheckBoxPreference is not derived from View, so the usual view attributes don't apply.
Instead, a CheckBoxPreference is bound to a view, which has a predefined layout.
You can derive a class from CheckBoxPreference and override onBindView. In your class' onBindView, find the CheckBox view and adjust its view attributes to your liking.
class MyCBPref extends CheckBoxPreference{
  public MyCBPref( Context context, AttributeSet attrs){
    super(context, attrs);
  }
  protected void onBindView( View view){
    super.onBindView(view);
    makeMultiline(view);
  }
  protected void makeMultiline( View view)
  {
    if ( view instanceof ViewGroup){

        ViewGroup grp=(ViewGroup)view;

        for ( int index = 0; index < grp.getChildCount(); index++)
        {
            makeMultiline(grp.getChildAt(index));
        }
    } else if (view instanceof TextView){
        TextView t = (TextView)view;
        t.setSingleLine(false);
        t.setEllipsize(null);
    }
  }
}

Then in your layout, reference your class instead of CheckBoxPreference:
<com.mycorp.packagename.MyCBPref android:title="..." ... />

A: You can derive a class from CheckBoxPreference and override onBindView. In your class onBindView, find the CheckBox view and adjust its view attributes to yours.


text:
Q: Need two excel windows side by side, on different monitors Excel opens all workbooks in the same instance and as a result you cannot place them on different monitors (or side by side). You can extend one window across both screens and then split windows from within excel, but that is a horrible solution. This also merges the undo functionality, and you can no longer undo per document, but you have to undo all actions from all open documents sequentially.
Honestly I don't know what they were thinking and made this the default behavior.

A: You simply just open Excel multiple times from the start menu. This will open as many Excel instances as you need!
From here, you just File -> Open to open the files (or drag files in).

A: At work I use two monitors arranged like this:

I often want to compare two excel sheets by placing them side by side on both monitors.  Just maximizing a single excel workspace with two windows in them does not work well, since I would need to drag the workspace as big as the black square.
Opening a new instance via the start menu works, but most of the times I just want to double click on an .xls(x) file and have it open in a new workspace.
One trick to do that is to write a batch file with these contents:
"C:\Program Files (x86)\Microsoft Office\Office14\excel.exe" %1

An improved trick (see comments) is:
start "" "C:\Program Files (x86)\Microsoft Office\Office12\excel.exe" %1.

(This will not spawn the console window).
Place is somewhere where it will not be deleted:

Then go to an excel file, right click on it and select [Open with].  Browse to the file you just saved and select that. From now on all your double clicked excel files will open in new workspaces which can be put side by side.

A: For word that is easy, if you go to File > Options > Advanced, scroll down to the Display section and check the box for "Show all windows in the Taskbar". For some reason in excel that doesn't seem to cut it.
You can however open new instances of excel if you go to start menu > run and type "excel /x". From the newly spawned instance you have to file > open each file, or use the resents. It is an annoyance but it is what I could find, and it works.


text:
Q: Multiline Regex Matching Issue I have the following string that I am trying to match via regex:
;IF TEST_DATE <= 200112 THEN E>=90 AND S>=90
 OR P = "25" ENDIF
IF TEST_DATE >= 200201 AND TEST_DATE < 200407 THEN E>=89
AND S>=90 OR P = "25" ENDIF

I am using the following regex in an attempt to match from the semicolon (intended to be a comment) until the first ENDIF:
;\s*IF (\d|\D)+ ENDIF

Unfortunately, this pattern matches all the way until the second ENDIF. I've tried various solutions using the Java Pattern.DOTALL, as well as the (?s) flag, with no luck.

A: You are using greedy quantifier, due to which your pattern (\d|\D) matches everything till it finds the last ENDIF.
You need to use reluctant quantifier - +? if you want your regex to stop matching at the first ENDIF : -
;\s*IF (\d|\D)+? ENDIF

A: Use the non-greedy qualifier.
;\s*IF (\d|\D)*? ENDIF


text:
Q: hover without moving the below content I want on hover to display some items without moving the below content.
My code is the following:

one

two

 three

and the css for hover:
ul#try li {display: inline-block;background: transparent;}
ul#try li:hover {background: transparent;}
ul#try li:hover ul {display: block;background: transparent;}
ul#try li ul {
  display: none;
}
ul#try li ul li {
  display: block;
  background: transparent;
}

I want to display values one and two, without moving the  three

A: Set ul#try li ul to position: absolute. Absolute positioning removes the element from the layout flow, and prevents it from changing other elements positions.

ul#try li {
  display: inline-block;
  position: relative;
  background: transparent;
}

ul#try li:hover {
  background: transparent;
}

ul#try li:hover ul {
  display: block;
  background: transparent;
}

ul#try li ul {
  display: none;
  position: absolute;
}

ul#try li ul li {
  display: block;
  background: transparent;
}

one

two

three


text:
Q: URL Rewrite when WordPress is in subdirectory I have a website with WordPress installed in a subdirectory called "articles." The rest of the site is built outside of WordPress.
I'm wondering if it's possible to rewrite the author page URLs from:

mysite.com/articles/author/persons-name

to

mysite.com/team/persons-name

Any advice is greatly appreciated.

A: You can use this code in your .htaccess file to achieve what you want.
RewriteEngine On
RewriteRule ^\.html$ /articles/author/persons-name [L]


text:
Q: How to make a system event application in c#? I am trying to make the following. I have a class that at midmight it makes a log from what happened in a SQL table and makes an excel file of it. My issue is that I was told that it is inexcusable to have this application running all day only to have it run once a day and that I should do this with a system event, but I have no idea how to do this. Help, please?

A: The easiest solution is to use Windows' built in Scheduled Task support to run your app.  Or, if you're using Microsoft Sql Server, a scheduled Sql Agent job.


text:
Q: QR Barcode image back to text I've converted hello world to QR Barcode image but my question is about getting the text back.

I mean if I sent that image to my friend, then is there any way that my friend get it back to text without using mobile reader/barcode reader machine .etc. so is there any PHP function can do this?!
If not then is there any idea I can convert text to encoded image then with PHP function whatever! I can get it back to text?!

A: I use the ZBar bar code reader on linux (there's also a Windows and an iPhone binary), which can scan them using any supported video in device or a number of file formats (e.g., directly from PDF). It's also useful if you want to script the QR code processing.
E.g.,
$ zbarimg http://i.stack.imgur.com/pQV0s.png
QR-Code:hello world

A: There are several web based QR decoders.  Your friend can just upload the image and the service will tell her what the code says.
One of the most popular is ZXing - http://zxing.org/w/decode.jspx
There are also others at
http://www.onlinebarcodereader.com/
http://www.patrick-wied.at/static/qrgen/


text:
Q: Misaligned Ordered List Items in Chrome Has anyone noticed that alpha ordered list items in certain fonts don't line up properly in Chrome?
Example:

li
{
  font-size: 20px;
  font-family: sans-serif;
  list-style: upper-alpha;
}
ol:after
{
  content: '';
  position: absolute;
  top: 0; left: 2.45em;
  height: 100%;
  width: 1px;
  background: black;
}

Testing

Testing

Testing

Testing

Testing

Testing

Testing

The periods for items C, D and G are 1 pixel further to the left than the rest of the items.
Here's what I see in Chrome on Windows in case it's somehow limited to certain OS/browser/font versions:

Everything lines up fine in Firefox and IE. I have seen the problem in Chrome on Mac, Windows and Android. It does seem to depend on the font. Most serif fonts that I checked have a problem. Both lower and upper-alpha have the problem, but different items end up shifted by 1 pixel.
Any thoughts on how to fix this, or is this a bug that I just have to wait for Google to fix? I've done some searching, but can't find anyone else mentioning this issue.

A: Revisting this unanswered question 3 years later... I just tried the example code snippet again and everything's aligned perfectly in Chrome now, so it appears this was probably just a bug that has since been fixed.


text:
Q: Querying database within a while loop I am trying to determine whether a database has been initialised by executing a query and examining the exit code. If the exit code is 0 then I know that the database query has been accepted and the database should be initialised.
I cannot use pg_isready because the postgres version is prior to 9.3 so I have developed the following code:
while (( $(su -l postgres -c "psql -d db_name -c 'select count(1) from table_name' > /dev/null 2>&1") != 0 ))
        do
            echo "waiting for database to initialise"
            sleep 10
        done

Running $(su -l postgres -c "psql -d db_name -c 'select count(1) from table_name' > /dev/null 2>&1" on its own returns an exit code of 0 however I am getting an error message when it is used within the loop:
((: != 0 : syntax error: operand expected (error token is "!= 0 ")

A: You should be able to use the return value directly.
while ! cmd
do
    ...
done


text:
Q: Existence of function satisfying some properties. Is there  continuous function $f(x)$ satisfy
$$
0\le f \le M_1 \\
\int_{\mathbb R^n} |z|^2 f(z) dz \le M_2   \\
\int_{\mathbb R^n} f(z) dz = (M_1B_n)^{2/(n+2)} M_2^{n/(n+2)}~(\frac{n+2}{n})^{n/(n+2)}
$$
where $B_n$ is the volume of the unit ball of $\mathbb R^n$.
This problem origins from the Lemma 1 of
Li, Peter; Yau, Shing-Tung, On the Schrödinger equation and the eigenvalue problem, Commun. Math. Phys. 88, 309-318 (1983). ZBL0554.35029.
I don't know whether the inequation in Lemma 1 is sharp, so I ask here.

A: For $n=1$,  let
\begin{align}
&f(x)=M_1,~~~|x|\le \left(\frac{3M_2}{2M_1}\right)^{1/3}=T  \\
&f(x)=0,~~~~~~~\text{others}
\end{align}
therefore, we have
$$
0\le f\le M_1 \\
\int_{-\infty}^{+\infty} x^2 f(x) dx =
\int_{-T }^{+T}
x^2 M_1 dx
=\frac{2M_1}{3}T^3
=M_2
$$
and
$$
\int_{-\infty}^{+\infty} f(x) dx
=
\int_{-T }^{+T} M_1 dx
=
2M_1 \left(\frac{3M_2}{2M_1}\right)^{1/3}
$$
note that, when $n=1$, we have
$$
2M_1 \left(\frac{3M_2}{2M_1}\right)^{1/3}
=
(M_1B_n)^{2/(n+2)} M_2^{n/(n+2)}~(\frac{n+2}{n})^{n/(n+2)}
$$


text:
Q: How to save phone number with braces and minuses if I use XSS filter? I use third party XSS filter to secure my application from xss attacks(com.cj.xss.XSSFilter)
But I faced following issue:
I am saving phone number in format like this:
+7 (911) 111-11-11

but on server I see that phone looks like this:
+7 (911) 111-11-11

As I understand it is encoding result.
I want to allow user to use phone number with braces, minuses and spaces.
Is it possible to achieve without security hole ?


text:
Q: What set of access permissions on content in USB HDDs will ensure portability in Windows? I have content on a portable HDD that is to be shared between 2 or more computers, but none of the computers are connected to a domain (none exists). I want to give permissions to the content in such a way that the permissions remain the same across all my computers, irrespective of which computer I connect the HDD to and irrespective of which user account was used to set the permissions.
For example, I want the built-in Administrators group (SID: S-1-5-32-544) to have Full Control of a file on the portable HDD, irrespective of the computer it is connected to (I am aware this constitutes a big security hole, but so long as the drive doesn't get stolen, I am ok with it. Anyway, once an attacker has physical access to a drive, all bets are off.).
Problem I am trying to solve is this: I connect the HDD to computer1, set all permissions, disconnect. Then I connect the HDD to computer2, and suddenly the permissions aren't right for the user on this computer since the SIDs are different (both in terms of permissions and ownership of content).

A: If you want the Administrators group to have full control, just set it that way. In Windows XP Pro or some other system that gives you a Security tab in Properties, use it. In the drive's security properties, add Administrators (if it's not already there), and in the privileges for Administrators give full control and enable all inheritance. You just have to set that on one machine and then other NT-based Windows PCs will obey the settings.
If you can't find one Pro system to use for that setting, then you'll have to learn the cacls command line. Fortunately you still just have to do it once. Oops. You'll have to do it n times where the first (n-1) times are various mistakes, but you just have to get it right once.

A: The permission scheme you choose for your HDD depends on the filesystem you've formatted the drive with.  Different filesystems specify permissions differently and have to be treated separately.

A: Why are you using permissions at all?  If someone gets the drive then they have access.  Instead, just use something like truecrypt to protect everything, and give everyone permissions to everything in the truecrypt volume.


text:
Q: How exactly do we add a animated border of a div inside the div itself? I am looking to display an image inside a div and when mouse hover over it the border should appear inside the div in some sort of animated manner. I have done it using animated svg and it works for large screen but have no idea of doing it for smaller screens. there must be a proper alternative to it!!
I have attempted to do it using svg lines.. for which i used four such lines and added animation on each line and triggered it while hover. What is the proper way please. Codesandbox link  link of what i have done till now.  I want similar effect for variable image/div sizes.


text:
Q: Trying to get property of non-object Yii I dont get this error, there is a row in database.
$tip = StringHelper::trimmer($_GET['tip']);
$sql = 'SELECT id FROM contact_reasons WHERE alias = "' . $tip . '"';
$model = ContactReasons::model()->findAllBySql( $sql );

die($model->id);

if(!is_null($model)) {
 $this->render('kontakt', array(
     'model' => $model,
 ));
} else {
 $this->renderText('Tražena stranica ne postoji.');
}

I used debug to see if there is a response, and even used query on database, and it returns a row with ID. I get this error on line with die();

A: Please note that, findAllBySql returns an array of CActiveRecords, while findBySql returns a single CActiveRecord. You may also use parameter binding for your SQL statements to prevent SQL injection.
see also http://www.yiiframework.com/doc/api/1.1/CActiveRecord


text:
Q: How to dynamiccally bind checkboxlist in gridview using backend Query For normally checkboxlist i using these binding is work, but how to bind in gridview for each row dynamically.
        List<string> availableItems = new List<string> { "Item1", "Item2", "Item3", "Item4", "Item5" };
        List<string> selectedItems = new List<string> { "Item1", "Item3", "Item4", "Item6" };

        // add available items to checkboxlist control
        foreach (string item in availableItems)
            chkItems.Items.Add(new ListItem(item));

        // check pre-selected items
        var query = from ListItem listItem in chkItems.Items
                    join item in selectedItems
                    on listItem.Value equals item
                    select listItem;

        foreach (ListItem listItem in query)
            listItem.Selected = true;

A: When in RadGrid ItemCreated using the FindControl to find the checkBoxList and bind on it.


text:
Q: jQuery chaining of getting html and replaceWith I'm using jQuery to get the content of a link and want to replace the link with just the content it has.
I got it to work, but I'm wondering if I could write it in just one statement instead of two.
Here is my code:
text = $(this).closest('.ui-btn-text').find("a[data-rel='popup']").html();
$(this).closest('.ui-btn-text').find("a[data-rel='popup']").replaceWith(text);

Thank you!

A: The .replaceWith() function accepts a function which returns the new HTML to replace that element with, so you could do:
$(this).closest('.ui-btn-text').find("a[data-rel='popup']").replaceWith(function() {
    return $(this).html();
});

It's important to note that this inside the function passed to .replaceWith() is different to this at the beginning of the line; inside the function it refers to the current matched element being replaced by the new HTML.

A: You can optimize it like
textObj = $(this).closest('.ui-btn-text').find("a[data-rel='popup']");
textObj.replaceWith(textObj.html());

A: var node = $(this).closest('.ui-btn-text').find("a[data-rel='popup']");
node.replaceWith(node.html());


text:
Q: How to restrict admin page via URL? I am building a website wherein I have an admin and user page. I have a problem wherein I can access the admin page via URL even though I am logged in as a user. I have validation checks at the login page, however if I am already logged in as a user or as an admin, I can access all the pages. I want to restrict the pages to their roles only.
This is my controller
class login extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->helper('url','html');
        $this->load->model('login_model');

    }
    public function index(){
        $this->load->view('login');
    }
    public function verify_login()
    {
        $data = $this->login_model->verify_login();
        if ($data) {
            $userdata = array('id' => $data[0]['user_id'] , 'name' => $data[0]['full_name'], 'type' => $data[0]['user_type'] );
            $this->session->set_userdata('login_info',$userdata);

            if($userdata['type'] == 0) {
                header("Location: ".base_url()."home");
            }
            else {
                header("Location: ".base_url()."reports_controller");
            }

        }

        else{
            header("Location: ".base_url()."login");
        }
    }

    public function logout(){
        $this->session->sess_destroy('login_info');
        header("Location: ".base_url()."login");
    }
}

A: First you have to check what your session value will return,then you can restrict url.Use this to check your session
$session = $this->session->userdata('login_info');
$type = $session['type'];


text:
Q: Cakephp System-wide Search Function I am looking to implement a search function into my system that allows system-wide search that can search through every single model. Is that possible?
I have tried CakeDC Search plugin but it somehow only allows me to search in the particular model that I add the search function into. Also, it seems to be limited to the search fields that I add in the view and I have to keep adding those search fields to enable search for them. What I am looking for is something with just one search box and able to retrieve information from all over the system (eg. Google's basic search with just one search field).
would be great that someone can point me in the right direction or even provide instructions on how to do so as I am fairly new with Cake.
I am using PHPMyAdmin for the database and the latest version of CakePHP. Please do let me know if you need further information as I am not sure what I need to include here.
Thank you.

A: http://cakedc.com/downloads/view/cakephp_search_plugin
The plugin allows you to attach the behavior to any model you want, and specifiy the table fields that it should take data from to create a search index. (basically when ever you save some data against the model, it runs through all the fields you specify it to look through, creates a data array to save, and saves the search data in its own table, ready to be searched on).
I would suggest giving this a go as it sounds like what you are after. The documentation provies detailed instructions on setting things up.
Hope it helps
Pete


text:
Q: Wordpress taxonomy template - Print mixed posts and sub taxonomies with pagination I have WordPress task and it seems there is nowhere an answer available on this.
What do I have:
I have a custom taxonomy called "product_taxonomies" and custom post type called "products". In the taxonomy file called "taxonomy-product_taxonomies.php" I fetch all products belonging to the current taxonomy and I print them with pagination as well. So when I click on the taxonomy called "Product Category 1" I get all its products with pagination.
What I need:
I need to modify my code that for the current taxonomy it prints both its products and sub-taxonomies all mixed together and with pagination as well. So when I click on the taxonomy called "Product Category 1" I should get all its products and subcategories "Product Sub-Category 1", "Product Sub-Category 2" etc. with pagination. Pagination should work as if products and sub-taxonomies are the same thing and they should also look like they are the same thing:
Here is the image showing how I want it to be like
What I managed to do:
I used get_categories() so as to get all sub-taxonomies of the current taxonomy and print them. The problem is that all the sub-taxonomies are not mixed with products and the pagination takes into account only the products and not the sub-taxonomies.
Here is my code:

<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
                $args1 = array(
'type'         => 'post',
'child_of'     => $current_id,
'parent'       => '',
'orderby'      => 'id',
'order'        => 'ASC',
'hide_empty'   => 0,
'hierarchical' => 1,
'exclude'      => 0,
'include'      => '',
'number'       => '',
'taxonomy'     => 'product_taxonomies',
'paged' => $paged,
'pad_counts'   => false );

$sub_terms = get_categories($args1);
foreach($sub_terms as $sub_term){
    //var_dump($sub_term);
    $sub_term_link = get_term_link($sub_term->slug, 'product_taxonomies');
    $sub_term_image = get_field('category_image', 'product_taxonomies_' . $sub_term->term_id );
?>

        <a href="<?php the_permalink(); ?>">

<img src="<?php echo $sub_term_image['sizes']['product_images']; ?>" />

<?php echo $sub_term->name; ?>

                     <?php echo $sub_term->category_description; ?>

<?php
}
            wp_reset_query();

            $args = array(
                'post_type' => 'products',
                'posts_per_page' => get_option('posts_per_page'),
                'tax_query' => array(
                            array(
                                'taxonomy' => 'product_taxonomies',
                                'field'    => 'id',
                                'terms'    => $current_id,
                            ),
                        ),
                'paged' => $paged
            );
            $query = new WP_Query($args);
         if ($query->have_posts()) {
             $i=1;
             while ( $query->have_posts() ) { $query->the_post();

                 $terms = wp_get_post_terms(get_the_ID(), 'product_taxonomies');
                 $tags = wp_get_post_terms( get_the_ID(), 'product_tag');
                 $all_terms = "";
                 foreach($terms as $single_term){
                    $all_terms .=  $single_term->slug . " ";
                 }
                foreach($tags as $single_tag){
                    $all_terms .=  $single_tag->slug . " ";
                 } ?>
                <li class="mix <?php echo trim($all_terms); ?>">
                    <a href="<?php the_permalink(); ?>">

<?php the_post_thumbnail('product_images'); ?>

<?php the_title(); ?>

                                 <?php echo get_the_excerpt(); ?>

                 <?php $i++;
             }
             wp_reset_query();
         }else{
            _e('Sorry, no available products under this category.','site');
         } ?>

    <?php
    //global $query;

    $big = 999999999; // need an unlikely integer

    echo paginate_links(array(
        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $query->max_num_pages,
        'prev_text' => __(' '),
        'next_text' => __(' '),
        'type' => 'list'
    ));
    wp_reset_query();
    ?>
    <?php wp_pagenavi(); ?>


text:
Q: Acceptance-Rejection using Functional Setup
Let $X\in L^1(\Omega,\mathcal{F},\mathbb{P})$.
As far as I've seen, Monte-Carlo methods generate $x_1,\dots,x_n$ from the distribution of $X$ and uses the Glivenko-Cantelli theorem to conclude that
$$
\frac1{n}\sum_{i=1}^N \delta_{x_i} \overset{D}{\rightarrow} Law(X).
$$
Acceptance\rejection sampling follows the same procedure, but given a function $f:\mathbb{R}\rightarrow \mathbb{R}$ and a threshold $M\in \mathbb{R}$, it extends the above method to obtain
$$
\frac1{\sum_{i=1}^N I_{f(x_i)\leq M}}\sum_{i=1}^N \delta_{x_i}I_{f(x_i)\leq M} \overset{D}{\rightarrow} Law(X|f(X)\leq M),
$$
(here I've assume that $N$ was large enought, and $f$ was nice enough so that we're not dividing by $0$).
Question
My question is, if $f$ is instead a continuous functional $f:\mathscr{P}(\Omega,\mathcal{F})\rightarrow \mathbb{R}$, then can it be used to do the acceptance/rejection?
Here, $\mathscr{P}(\Omega,\mathcal{F})$ is the set of probability measures on $(\Omega,\mathcal{F})$.


text:
Q: How to find a unique button that has no name or id? I have a webpage that has multiple containers that each have a header (fooHeading), name (fooName), and a button (fooButton).
There would be multiple containers on the same page that look as follows:

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
fooTitle fooButton
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

The html for each container looks identical to the following:

        fooTitle

    <button class="fooButton"></button>

FooTitle is the only thing that would change. How can I uniquely click fooButton based on what fooTitle is?

A: I'd recommend xpath:
WebElement button = driver.findElement(By.xpath("//span[contains(text(), 'fooTitle')]/../button"));

This will find a span that contains the text fooTitle.  The .. will go up to the div, then find the button that is the child of the div.

A: I also encountered such problem in the my project while creating scripts in selenium sometime all traditional method fails like xpath,css selector ,etc.
if same happens with you then my approach may help you
first you have to check total count of button tag from starting then find the position of count of your button e.g. its position is pos
List<WebElement> element = driver.findElements(By.tagName("button"));
Iterator<WebElement> itr = element.iterator();
int count=0;
WebElement e = null ;

while(itr.hasNext())
{
    count++;

    e = (WebElement) itr.next();

    if(count==pos)
        break;
}

//System.out.println(count);
//for checking total count without using break in while loop

e.click();


text:
Q: How do you pass 'this' as an argument to another class constructor without circular dependencies? I'm thinking specifically of the Strategy pattern (Design Patterns, GoF94), where it is suggested that the context passed to the strategy constructor can be the object which contains the strategy (as a member) itself.  But the following won't work:
//analysis.h

class StrategyBase;
class Strategy1;
class Strategy2;
class Analysis
{
   ...
      void ChooseStrategy();
   private:
      StrategyBase* _s;
      ...
};

//analysis.cpp

void Analysis::ChooseStrategy()
{
   if (...) _s = new Strategy1(this);
   else if (...) _s = new Strategy2(this);
   ...
}

//strategy.h

#include analysis.h
...

and then StrategyBase and its subclasses then access the data members of Analysis.
This won't work because you can't instantiate Strategy* classes before they've been defined.  But its definition depends on that of Analysis.  So how are you supposed to do this?  Replace ChooseStrategy with
void SetStrategy(StrategyBase* s) { _s = s; }

and do the instantiation in files which #include both analysis.h and strategy.h?  What's best practice here?

A: You will always have circular dependencies in the State/Strategy Pattern, except for very general States/Strategies. But you can limit the in-size (Lakos) use of the respective other class such that it compiles, at least:

*

*Forward-declare Analysis (analysis.h or strategies.h)

*Define StrategyBase and subclasses (don't inline methods that use Analysis) (strategies.h)

*Define Analysis (may already use inline methods that use strategies) (analysis.h)

*Implement Analysis and the strategy classes' non-inline methods (analysis.cpp)

A: analysis.cpp also needs to include strategy.h to pick up the full definitions of the strategies. Since it's a source file there's no circular dependency.

A: You don't need to instantiate classes if you're passing pointers (or references): Use a Forward Declaration.

A: One important feature of c++ that is sometimes quite difficult to figure out is that the classes need to be provided for compiler in the correct order. And dependencies between classes decides which order needs to be used. It does not make it easier that people want to put every class to separate .h file, so the order of classes need to be provided several times when deciding order of #include's. While people are learning header and class dependencies, it's recommended to put every class to the same .h file, as this will force you to decide the order just once. After learning the correct order, you can again start using the good conventions of placing all classes to separate header files.


text:
Q: Error while Sending authorization headers in RSpec's Request Spec I am getting the following error while trying to send http headers using RSpec's request spec
 Failure/Error: request.env["HTTP_AUTHORIZATION"] = ""
 NoMethodError:
   undefined method `env' for nil:NilClass

Any suggestions?

A: You can set an HTTP header while testing your controllers like this:
post :action, params, session, {"HTTP_AUTHORIZATION" = ""}


text:
Q: Why does Android draw View inside another (with width and height defined in pixels) in incorrect way? I am wondering in which way Android draws views on the screen inside layout views with defined android:layout_width and android:layout_height values in pixels.
I am using Android class view extends android.view.SurfaceView. It is just MjpegView to display MJPEG stream from the camera on the Android app. I am working with this code (with some small changes): Android ICS and MJPEG using AsyncTask
This MjpegView class is placed inside the RelativeLayout. MjpegView object is added programmatically and this RelativeLayout has attributes defined in this way:
android:layout_width="800px"
android:layout_height="600px"

This size values is necessary for this application so I can't change them. Application is working only in landscape orientation. My MjpegView need to be set 320 x 240 pixels size inside  RelativeLayout (800 x 600 px). My application enlarges this RealtiveLayout to fill the screen on the current device. And this is a problem connected also with the streaming MJPEG. I am working on Nexus 7 (2012 version), which has 1280 x 800 resolution.
To get the real size of this view inside layout I have to measured the height of the Nexus 7 screen without action and navigation bars. To get this I have used this method inside one Activity:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.parent_layout);
    if (parentLayout != null && isLandscape) {
        this.measuredActivityHeight = parentLayout.getBottom();
    }
}

I am getting 703 value as the measuredActivityHeight of the running Activity. So to get the ratio in which Android translates 320 x 240 px inside 800 x 600 px to the dp value on the screen I have written this method:
 public int calculateForCurrentScreen(float pixelValue) {
    float ratio = PageActivity.measuredActivityHeight / 600f;
    int result = (int) (pixelValue * ratio);
    return result;
}

So for the 320 x 240 px on the Nexus 7 I am getting 374 x 281. And to get MjpegView in this size I need to use this method inside the MjpegView class:
public void setResolution(int width, int height) {
    holder.setFixedSize(width, height);
}

And the size of the streaming view is in the wanted size. But this view has additional black areas. So in fact the whole view (camera stream + black areas on the its bottom and right side) has 440 x 328 size.
I have checked that Rect object in MjpegView is drawing with 374 x 281 size so it is OK. SurfaceHolder and Canvas also have this size. Bitmap object has 320 x 240 size, but this is OK because Bitmap object is from camera stream. And it is resized to the wanted size.
Problem disappear (there is no black areas and MjpegView is in correct position and size relative to other views) when I have switched RelativeLayout to the 800dp x 600dp size and invoke setResolution(320, 240) for the MjpegView object. But the whole layout is in this moment too big.
EDIT
Thanks @mathiash for your comment. I have just uploaded screenshot from Nexus 7 (2012 edition) to show you my problem.
As you can see, the green area is the RelativeLayout with defined 800 x 600 px size. To get MJPEG stream from the http://trackfield.webcam.oregonstate.edu/. I have used this URL: http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg/video.cgi?resolution=320x240.
For this screenshot I have invoked setResolution(320, 240) method. And black area has 374 x 281 and video stream 320 x 240.

For this screenshot I have invoked setResolution(374, 281) method. And black area is much bigger and video stream is 374 x 281. And in this case video stream has correct size but this black area is unnecessary.

A: As Levente Kurusa suggested, using a virtual pixel unit such as dp may solve your problem. We should avoid using px diretly.

A: dont use dp, even dp changes with different screens. Instead i learned to use my own value times density.
So use DisplayMetrics metrics = getResources().getDisplayMetrics(); and
metrics.getDensity() * 50 for example. Also try to use weights to keep them relative in different screens.

A: You can try with
whateveryourvideoname.setDisplayMode(MjpegView.SIZE_BEST_FIT)

in order to make the best fitting of your inputstream (with the resolution you set up previously) within the layout view.

But all this doesn't make sense if you have defined your Mjpegview in the layout.xml file with the same size as the resolution of your source image, so the best way is to skip the setResolution command and just use
whateveryourvideoname.setDisplayMode(MjpegView.SIZE_FULLSCREEN)

and your image will fit perfectly inside your MjpegView display.


text:
Q: Why does this test only fail when there is a rejection? This test passes; i.e. sinon says the stub is in fact, called:
const sinon = require('sinon')

async function underTest (s){
  promise1 = new Promise((yes, no)=>yes())
  promise2 = new Promise((yes, no)=>yes())

  Promise.all([promise1, promise2]).then(s.yes).catch(s.no)
}

async function test(){
  s = {yes: sinon.stub(), no:sinon.stub()}
  await underTest(s)
  sinon.assert.called(s.yes)
}

test().then(console.log('done'))

Note how I did not return a promise from Promise.all.
However, the following test will fail, and sinon will say the stub was NOT called:
const sinon = require('sinon')

async function underTest (s){
  promise1 = new Promise((yes, no)=>no())
  promise2 = new Promise((yes, no)=>no())

  Promise.all([promise1, promise2]).then(s.yes).catch(s.no)
}

async function test(){
  s = {yes: sinon.stub(), no:sinon.stub()}
  await underTest(s)
  sinon.assert.called(s.no)
}

test().then(console.log('done'))

And if I return the Promise.all, then it will pass, and sinon will say the s.no stub is called:
const sinon = require('sinon')

async function underTest (s){
  promise1 = new Promise((yes, no)=>no())
  promise2 = new Promise((yes, no)=>no())

  return Promise.all([promise1, promise2]).then(s.yes).catch(s.no)
}

async function test(){
  s = {yes: sinon.stub(), no:sinon.stub()}
  await underTest(s)
  sinon.assert.called(s.no)
}

test().then(console.log('done'))

It makes sense that the test only passes if I return the promise from Promise.all. If I return nothing the async function will resolve to undefined and the stub might or might not have been called.
My question is, I would have expected the test to fail, in case there is no return statement, even for the first case, where the promises resolve. I would have expected for sinon to tell me s.yes was not called. But why does it pass? Why is there inconsistency between resolve and reject?

A: I run your code. No. Your first code / case test is done, but the result is not passed.
You have better way of knowing it if you also implement catch when run the test something like this:
test()
.then(() => console.log('done'))
.catch((error) => console.log('Error:', error.message));

You are using async await inconsistently.
If you are using async await, you can catch the error using try and catch.
For example:
async function underTest (s){
  promise1 = new Promise((yes, no)=>yes())
  promise2 = new Promise((yes, no)=>yes())

  try {
    await Promise.all([promise1, promise2]);
    s.yes();
  } catch {
    s.no();
  }
  // This will return Promise<void>
}


text:
Q: Is there a way to call nested array in Vue? I am really new to Vue JS. I was trying to print my nested object using console.log but it throws me an undeifned error.
Array Image

View Code
<b-button variant="primary" v-on:click="dontknow();">Print</b-button>
Script
methods:{
      dontknow(){
        console.log(this.allPlayerList.booker_id);
      },
 }

It displays me undefined when I use console.log(this.allPlayerList.booker_id). Can anyone please let me know what am I doing wrong? I want to get all the booker_id from allPlayerList.

A: allPlayerList obviously is an array of objects, which doesn't have itself a booker_id property, but contains objects which have it.
To print all the booker_id you need to loop over the array, and print it for every object, there are multiple ways of doing this, some of the common ways are:
this.allPlayerList.forEach(player => {
  console.log(player.booker_id);
});

Another way would be
console.log(this.allPlayerList.map(player => return player.booker_id));

The fist way will print every booker_id separately, while the second will print and array of all the booker_id items.


text:
Q: notation for sum of matrix columns Let $A \in \mathbb{R}^{m \times n}$. Is there a name or notation for the vector $\vec{v} \in \mathbb{R}^{m}$, such that $\vec{v}$ is the sum of the $n$ columns of $A$?

A: Sometimes, $\vec{1}_n$ denotes the $n$-entry column vector with every entry equal to $1.$ In that case, what you're looking for is $$\vec v=A\vec{1}_n.$$
Sometimes, $\mathbf{1}_{j\times k}$ denotes the $j$-row, $k$-column matrix with every entry equal to $1.$ In that case, what you're looking for is $$\vec v=A\mathbf{1}_{n\times 1}.$$
Sometimes, other notation is used. It's really context-dependent. You can frankly make your own notation, as long as it doesn't conflict with notation you've previously defined, and as long as you define it explicitly.


text:
Q: Customize JButton style I'm working on a project. I want to add a toolbar to the software so I put some buttons in a panel . However the default button style doesn't meet my need. I want the button to have the following effects:

*

*When the mouse doesn't hover over the button, the button should looks like a JLabel. The icon in the button just looks like an image on the panel, i.e. all we can see is the icon in the button and other things are transparent.

*When the mouse hovers over the button, the button's border appears. It looks like a real button.

Example: Just like the buttons on the eclipse's toolbar.

A: Why not use a JToolbar instead of a JPanel?

A: I got it. The answer to my question is the setContentAreaFilled() method. When the mouse hovers over the button, call the setContentAreaFilled(true). Otherwise call the setContentAreaFilled(false). Here is a relative code: link text

A: So, you want to customize your JButton renderings ?
First, for an all-inclusive soluition, you can take a look at existing LnF like Substance (obviously, it's a far too powerful solution for your need, however it may give you some inspiration).
Then, if you want to solve that by yourself, you'll have to override the paintComponent method.
For that, the first move is to subclass JButton.
Then, in your subclass, start by redefining the paintComponent(Graphics) method.
Notice that if all that is overcomplicated to you, you can also take a look at setBorderPainted(boolean) method.

A: Extend JButton and:

*

*Just add an Icon instead of Text to
the button.

*Add MouseMotionListener    to capture
hovering to show/hide    border.


text:
Q: Check connection to IP address from local HTML via javascript quick background
I'm making a map in HTML out of SVGs of the office I work in. I have the locations of the printers in the office, and planned on using the map to 1) show new users where their printers are and 2) be able to quickly see if the printers are all online. I would like to do more(possibly check toner levels), but that's a task for another day maybe. Anyway, I'm trying to figure out if the locally running HTML file can somehow try to connect in some way to the printer's known IP address. If it can connect, then clearly it is online, and if not, well... then it isn't.
So my question is: How do I connect to a networked printer via Javascript to verify that it is online?
I've tried using an iframe to load the printers webpage, but I can't look at it to see anything about it because my page is using the file protocol, and the printers page is using http. I could go that way, but I have no idea if I can even see if the iframe loaded successfully or not.
I've also tried the Image method, where you use the ip address as the image src, but it doesn't seem to work.
Any ideas?


text:
Q: Vertical centering of multiple variable sized images in a div with CSS in IE 9 I've seen and read numerous posts on this subject but none worked in my environment or I did something wrong. I have a div that contains images and text of various unknown sizes. I want all the images and in the div to be vertically centered. I'm using Internet Explorer 9.
Here is my code, I'm removed all the various techniques I've attempted for the sake of simplicity:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title></title>

<form id="form1" runat="server">

            Centered Text Vertically

</form>

I'd like to emphasize that the text and images are of unknown sizes. I've found this certainly complicates the solution. Also, based on ActiveX requirements, I'm using Internet Explorer version 9. Any advice out there? Thanks!

A: To use vertical alignment, you are better off setting a wrapper with the display set to table-cell:
See this Fiddle Example!
THE CSS:
/* the vertical alignment class */
.centerImage {
    display: table-cell;
    vertical-align:middle;
}

THE HTML
...

Centered Text Vertically

...

Tested:
IE9, IE8, OPERA, SAFARI, FIREFOX, K-MELEON, GOOGLE CHROME
Notes:
You should specify the image width and height to a proper HTML validation and to allow a better understanding by the browser.
Read More About This:
CSS Display Property  |  CSS vertical-align property  |  CSS Tricks: What is vertical Align?

EDITED
In regards to the comment given by reisio, to have the same vertical point to the images on the left and the text on the right, we can go with a more simple solution:
See the Fiddle Here!
RELEVANT CSS
/* the trick you want */
.centerImage {
    vertical-align:middle;
}
div.headerleft {
    border: none;
    float: left;
    margin: 0;
    padding: 0;
    line-height: 75px;
}

div.headerright {
    border: none;
    float: right;
    margin: 0;
    padding: 0;
    line-height: 75px;
}
h1 {
    font-size: 44px;
    font-family: Tahoma, Geneva, Verdana, sans-serif;
    margin-bottom: 0;
    margin-top: 0;
    padding-bottom: 0;
    padding-top: 0;
}

RELEVANT HTML

Centered Text Vertically

For this solution, we use the vertical-align set to the img tag, and the line-height to create the same vertical-point and to align vertically the text.
You can read: CSS line-height Property
EDITED
If you can't set a height to the images, the only way to solve your issue is to use a bit of JavaScript to dynamically find the tallest image and apply that height to the line-height on the H1 tag.
See this working Fiddle!
JQUERY
$(document).ready(function() {

    // initialize the variable to 0
    var height = 0;

    // run by each image to find the tallest
    $('.headerleft img').each(function() {
        height = ($(this).outerHeight(true)>height) ? ($(this).outerHeight(true)) : height;
    });

    // vertical center the text
    $('.headerright h1').css({"line-height": height + "px"});
});

Note:
Removed the line-height from the div.headerleft and div.headerright since it is not longer needed!


text:
Q: Undo preventDefault() method I was wondering if there was any way of "undoing" the preventDefault() method on submit. I have this code that does the trick, but I want to know if there is a more efficient way of doing it.
var $form = $('form');
var canSubmit = false;

$form.data('working', false);

$form.submit(function(e){
    if (form.validations.form($form)) {
        if (!$form.data('working')) {
            $form.data('working', true);

            if (canSubmit) {
                // make the post here
            } else {
                e.preventDefault();
                $.get(BASE+'file.txt', function(response){
                    $form.data('canSubmit', true);
                    $form.submit();
                });
            }
        }
    } else {
        $form.data('working', false);
        e.preventDefault();
        return false;
    }
});

This is because I have to read and write a file after the validations are done and only after that make the post to the page.
The post can't be done by ajax.
Thanks

A: You can't undo the e.preventDefault() as you are dealing with a later instance of e by the time you submit.
return false does the same as e.preventDefault() and e.stopPropagation(), so you can simplify your code a little though by simply returning your flag.
var $form = $('form');
var canSubmit = false;

$form.data('working', false);
$form.submit(function(e){
    if (form.validations.form($form)) {
        if (!$form.data('working')) {
            $form.data('working', true);
            if (!canSubmit) {
                e.preventDefault();
                $.get(BASE+'file.txt', function(response){
                    canSubmit = true;
                    $form.submit();  // trigger recursive call
                });
            }
        }
    } else {
        $form.data('working', false);
    }
    return canSubmit;
});


text:
Q: TypeScript - Combine two interfaces and making some of its members mandatory I have the following two interfaces that cannot be modified:
interface User {
  username: string;
  email?: string;
  age?: number;
  country?: string;
}

interface Player {
  room: number;
  group?: string;
  device?: string;
}

I want to combine them into just one inteface: Member and at the same time making the fields: User['email'] and Player['group'] mandatory (just those 2).
I tried the following (just as an starting point (TBD)):
// please edit this code accordingly
interface Member extends User, Player  {}

Then, the expected result is to get an error on:
const member: Member = {
  username: 'bill.gates',
  // email: 'bill.gates@microsoft.com',
  age: 50,
  room: 5,
  // group: 'A',
}

since email and group are not specified.
Here you have a Playground.
Thanks!

A: You can achieve that with a combination of Pick, Required and Omit from the Utility Types.
type Member = Required<Pick<User & Player, 'email' | 'group'>> & Omit<User & Player, 'email' | 'group'>;

/*
Type '{ username: string; age: number; room: number; }' is not assignable to type 'Member'.
  Type '{ username: string; age: number; room: number; }' is missing the following properties from type 'Required<Pick<User & Player, "email" | "group">>': email, group(2322)
*/
const member: Member = {
  username: 'bill.gates',
  // email: 'bill.gates@microsoft.com',
  age: 50,
  room: 5,
  // group: 'A',
}

Here is a working playground

A: Define Member like this:
interface Member extends User, Player  {
    email: string;
    group: string;
}


text:
Q: I have a context menu which is being shared by 6 different labels, how can I tell which label is using the current instance of the context menu? Here is the xaml for the contextMenu:
    <Window.Resources>
    <ContextMenu x:Key="IBContextMenu" x:Shared="true" Name="IBContextMenu1">
        <MenuItem Header="Edit" Click="ibEdit_Click" AllowDrop="False" />
        <MenuItem Header="Clear" Click="ibClear_Click"/>
    </ContextMenu>
</Window.Resources>

Both the edit and clear items' methods need to know which label to act upon. How can I do this?

A: I think you are looking for PlacementTarget:
http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.placementtarget.aspx
If you switch over to a Command-pattern, you can actually get this via Binding and pass it along as the CommandParameter...

A: Here's an answer I came up with. I don't really like it because it's a bit hack-ish, but it works. The idea is that you make your labels listen to the MouseRightButtonUp event, which is fired when the user releases the right mouse button after clicking to open the context menu. In the event handler, you set a private Label variable to the label that the user just right-clicked. Then, in your MenuItem click handler, you can access that private Label variable. Note that all the labels you want to do this must use the same event handler for MouseRightButtonUp.
For example:
<Window.Resources>
    <ContextMenu x:Key="MyMenu">
        <MenuItem Header="Edit" Click="Edit_Click"/>
        <MenuItem Header="Clear" Click="Clear_Click"/>
    </ContextMenu>
</Window.Resources>
<StackPanel>
    Some text
    Some junk
    Some stuff
    Some 0000
</StackPanel>

Code behind:
private void Edit_Click(object sender, RoutedEventArgs e)
{
    if (clickedLabel != null)
    {
        MessageBox.Show(clickedLabel.Content.ToString());
    }
}

private void Clear_Click(object sender, RoutedEventArgs e)
{
    if (clickedLabel != null)
    {
        MessageBox.Show(clickedLabel.Content.ToString());
    }
}

private Label clickedLabel;
private void Label_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    clickedLabel = (Label)sender;
}

A: Try to set a DataContext to the Labels, for example

And in the Click event just check the ((FrameworkElement)sender).DataContext for FIRST/SECOND etc. Let us know if that works.


text:
Q: Cannot save data to .txt (Java OOP console application) So basically i'm developing simple library management system console app using Java on NetBeans IDE. I wanted to save book data to .txt but it seems like i made a some logical error here or something. I'm a newbie, please help.
So I made a class called "Book"

import java.io.*;
import java.util.Scanner;

public class Book {

        Scanner sc = new Scanner(System.in);
        public int bookId;
        public String bookTitle, author,Description, alley;

        public Book(){}
        public Book(int bookid, String booktitle, String Author, String desc, String Alley)
        {
            bookId = bookid;bookTitle=booktitle;author=Author;Description=desc;alley=Alley;
        }
        public int getbookID()
        {return bookId;}
        public String getBookTitle()
        {return bookTitle;}
        public String getAuthor()
        {return author;}
        public String getDescription()
        {return Description;}
        public String getAlley()
        {return alley;}

        public void setbookID(int bid)
        {bookId = bid;}
        public void setbookTitle(String bt)
        {bookTitle = bt;}
        public void setbookAuthor(String a)
        {author = a;}
        public void setDescription(String Desc)
        {Description = Desc;}
        public void setAlley(String alleY)
        {alley = alleY;}

        public String ToString()
        {
            return bookId + " " + bookTitle + " " + author + " " + Description + " " + alley;
        }

        public void WriteToTxt()
        {
            try
            {
                File f = new File("book.txt");
                FileWriter fw = new FileWriter(f, true); //set to True to append more
                PrintWriter pw = new PrintWriter(fw);
                pw.write(this.toString());
                pw.write("/n");
                pw.flush();
                pw.close();
            }
            catch(IOException ex)
            {
                System.out.println(ex);
            }
        }
}

and I made a class Administrator that has add book method

public void addNewBook()
    {
         int bid;
         String bookTitle, Author, Description, alley;
         Scanner scan = new Scanner(System.in);
        System.out.println("Enter Book ID: ");
        bid = sc.nextInt();
        System.out.println("Enter Book Title: ");
        bookTitle = sc.next();
        System.out.println("Enter Book Author: ");
        Author = sc.next();
        System.out.println("Enter Book Description: ");
        Description = sc.next();
        System.out.println("Enter Book Alley: ");
        alley = scan.next();

        Book b = new Book(bid, bookTitle, Author, Description, alley);
        b.WriteToTxt();

    }

It successfully created the txt file but the content isn't what expected.
lmsconsole.Book@7d4991ad/n
What did I do wrong? Thanks in advance.

A: You have a silly typo in your ToString method. The correct name is toString (methods always begin with lowercase letters in Java).
To write a new line you can use println() or simply write the "\n" char (note that escaped chars use a backslash).
Finally, always add a @Override annotation (above the method) to be extra sure you are overriding the correct method from now on.

By the way, as matter of coding style, you also might consider using this when assigning Book fields in the constructor:
this.bookId = bookId;
this.bookTitle = bookTitle;
...

which would enable safer code and better parameters names in your constructor, improving code readability.

A: Below is what I have noticed :
public String ToString()

What you want to accomplish can't be achieved through this method, it should be toString
Also you have to follow @Paulos answer as well

A: you have wrote definiton for ToString() instead of toString()
you used /n instead of \n
correcting the above mentioned mistakes should do the trick.


text:
Q: Function for getting position of values From this data I want a new column ("from") with the first value for each row of cumulative values. It should actually be the last value from column "cum" + 1. How would you do this with a function? Imagine many rows.
     a <- c(5,5,4,3)
cum <- cumsum(a)
df <- data.frame(a,cum)
df
  a cum
  5   5
  5  10
  4  14
  3  17

df$from <- c(1,6,11,15)
 df
  a cum from
  5   5    1
  5  10    6
  4  14   11
  3  17   15

A: One possible solution is using lag() and then head() to remove the last element of the created vector
df$from <- head(c(1, lag(df$cum + 1)), -1)

df
#   a cum from
# 1 5   5    1
# 2 5  10    6
# 3 4  14   11
# 4 3  17   15

A: library(tidyverse)
a <- c(5,5,4,3)
cum <- cumsum(a)
df <- data.frame(a,cum)

df %>%
  mutate(from = lag(cum, default = 0) + 1)
#>   a cum from
#> 1 5   5    1
#> 2 5  10    6
#> 3 4  14   11
#> 4 3  17   15

Created on 2021-03-01 by the reprex package (v1.0.0)

A: A base R option
transform(
  df,
  from = c(1, head(cum, -1) + 1)
)

gives
  a cum from
1 5   5    1
2 5  10    6
3 4  14   11
4 3  17   15


text:
Q: Is it possible to make external numpad or second keyboard only input to a certain window? I picked up a external Logitech numpad recently and figured it might be useful to use it for macros.
However, since it's a numpad, every time I will press the button to set off the macro, that number will show up in whatever I'm typing, thus forcing me to backspace.
Is there a way that I can make the input from this numpad be redirected so that only one window actually receives the keystroke?


text:
Q: Add html attribute if the input value meet requirements Let say I have two input.
When I key-in value in input1 for example 0.4 and meets the requirement then the input2 will remove the readonly attribute. Meanwhile if I input value in input1 is 0.3 then the input2 attribute will become readonly again.
It doesnt work. Maybe i missed out anything here

$(".input1").keydown(function() {
    var dInput = $(this).val();
    if (dInput >= 0.4 && dInput <= 0.6) {
        $(".input2").attr('readonly', true);
    } else {
        $(".input2").removeAttr("readonly");
    }
});

function isNumberKey(e) { // stub
    return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" onkeypress="return isNumberKey(event)" id="input1" name="input1" value="" />

<input type="text" class="input2" onkeypress="return isNumberKey(event)" id="input2" name="input2" value="" readonly />

A: 1: Use keyup function, as the value fills up in a field later and you are trying to capture at keydown
2: I have switched the if and else block statements as per your description. Your original code contradicts what you are saying here.

        $(".input1").keyup(function() {

            var dInput = $(this).val();
            if(dInput >= 0.4 && dInput <= 0.6)
            {
                $(".input2").removeAttr("readonly");
            }
            else
            {
                $(".input2").attr('readonly',true);
            }
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" o id="input1" name="input1" value="" />

<input type="text" class="input2"  id="input2" name="input2" value="" readonly />

A: You are setting the attribute in the wrong condition. I also prefer input event instead of keydown here:

$(".input1").on('input', function() {
    var dInput = $(this).val();
    if(dInput >= 0.4 && dInput <= 0.6){
      $(".input2").removeAttr("readonly");
    }
    else{
      $(".input2").attr('readonly', true);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1"  id="input1" name="input1" value="" />

<input type="text" class="input2" id="input2" name="input2" value="" readonly />

A: use keyup

function isNumberKey(e){
}

   $(".input1").keyup(function() {

            var dInput = $(this).val();
            dInput = parseFloat(dInput);
            console.log(dInput);
            if(dInput >= 0.4 && dInput <= 0.6)
            {
                $(".input2").attr('readonly',true);
            }
            else
            {
                $(".input2").removeAttr("readonly");
            }
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" onkeypress="return isNumberKey(event)" id="input1" name="input1" value="" />

<input type="text" class="input2" onkeypress="return isNumberKey(event)" id="input2" name="input2" value="" readonly />


text:
Q: getting SLF4J error when starting corda network i am getting SLF4J error while booting up corda netowrk,
I am using JDK8_221, corda 4.1, windows OS,
I am using gradle
Logs:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
  SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J:
  See http://www.slf4j.org/codes.html#StaticLoggerBinder for further
  detail s.

tried same with JDK8_181, JDK8_191
Env. variable and path variable are correct.

A: This issue could be due to the version of SLF4J.
Use 1.6 or 1.7 version of SLF4J.
Go through the following link for details
URL: https://www.slf4j.org/api/org/slf4j/impl/StaticLoggerBinder.html
Excerpts from the above link -

As of SLF4J version 1.8.0, the static binder mechanism (StaticLoggerBinder) is deprecated.

This class exists for backward compatibility earlier versions of slf4j-api.jar, in particular in the 1.6.x and the 1.7.x series.

Note that this class is likely to be removed in future releases of SLF4J.


text:
Q: R: How to extract everything after first occurence of a dot (.) I need to extract from a string such as outside.HLA.DR.highpass the part after the first dot, yielding HLA.DR.highpass.
Importantly, the middle part of the string, outside.xxx.highpass might or might not have additional dots, e.g. outside.CD19.highpass should yield in CD19.highpass as well.
I got similar steps where extraction of the first part I do with sub(".[^.]+$", "", "outside.HLA.DR.highpass" ) to return "outside.HLA.DR". However, I fail to adapt it so that it returns only the part of the string after the first dot?
any help is greatly appreciated!!

A: You want to use a non-greedy regex operator here to capture the start of the sentence (^), followed by the fewest possible characters (.*?) followed by a literal dot (\\.)
sub("^.*?\\.", "", "outside.HLA.DR.highpass")
# "HLA.DR.highpass"

A: Your solution for extraction of the first area is correct. Simply apply a similar rule:
sub("^[^.]+.","","outside.HLA.DR.highpass")

Should return the desired string.

A: Here's a solution with stringr that will work on a vector.
library(stringr)

s <- c("outside.HLA.DR.highpass", "outside.CD19.highpass")

str_sub(
  s,
  start = str_locate(s, fixed("."))[, 1] + 1,
  end   = str_length(s)
)
#> [1] "HLA.DR.highpass" "CD19.highpass"

Created on 2022-07-13 by the reprex package (v2.0.1)


text:
Q: React updating state with big object I need advice to work with large object in React.js.
Example:

const [myObject, setMyObject] = React.useState({
  next_step: {
    id: 1575567015473,
    block_type: 'message',
    position: 'bottom',
    message: 'lorem ipsum',
    actions: {
      id: 1575562323,
      type: 'step_action',
      title: 'Show answers',
      description: 'Resend answer to another user',
      method: 'show_answer',
      points: 30
    },
    waiting: {
    interval: '4h50m',
    id: 1,
    position: 'right,
    next_step: {
      id: 3,
      position: 'bottom',
      block_type: 'message',
      message: 'lorem ipsum 3',
      waiting: null,
      next_step: null
    }
    }
    next_step: {
      id: 2,
      position: 'bottom',
      block_type: 'message',
      message: 'lorem ipsum 2',
      waiting: null,
      next_step: {
          id: 4,
          position: 'bottom',
          block_type: 'message',
          message: 'lorem ipsum 4',
          waiting: null,
          next_step: null
        }
      }
  }

});

I use recursion to render inputs with value message
After input changed I rerender my object.

Example:

const findObject = (id, obj, fn) => {
  if (obj.id === id) {
    return fn(obj);
  }

  if (obj.waiting && obj.waiting.id) findObject(id, obj.waiting, fn);
  if (obj.next_step && obj.next_step.id) findObject(id, obj.next_step, fn);
  return obj;
};

const inputHandler = (value, id) => {
  const strFlowData = JSON.stringify(myObject);
  const newFlowData = JSON.parse(strFlowData);

  const inputUpdate = newObj => {
    const slackBlocks = newObj.body.blocks;
    const slackMassage = slackBlocks[0].text;
    slackMassage.text = value;
    return null;
  };

  findObject(id, newFlowData.next_step, newObj => inputUpdate(newObj));
  setMyObject(newFlowData);
};

Everything is working fine, but if this object becomes larger, Will I have problems  when the input changes?
Maybe there is a better solution ?

A: You should use a tree of pure components (or React.useMemo) and structure your website that only changed parts need to be checked for rerendering.
That each input is a component on it's own and the check if it should be updated can be done while checking if the properties changed.
React does a good job at diffing the virtual dom, but if you can help and expect a performance impact otherwise, you might optimize. Most times it makes development easier, too :-)


text:
Q: Eliminar Precio Woocommerce Estoy tratando de desaparecer el precio en woocommerce a través de la cadena de consulta.
Lo que necesito hacer es aquí el ejemplo:
www.example.com/product-show (muestra url normal y precio)
www.example.com/product-show?noprice (precio oculto)

Gracias por adelantado.

A: Hay muchas formas de lograr lo que quieres, depende mucho de si estás usando las plantillas por defecto de WooCommerce, si es así con poner el siguiente código en el functions.php de tu tema debería hacer lo que pides:
// Quitar del hook woocommerce_single_product_summary la funcion que imprime el precio
add_action('template_redirect', 'wc_product_single_remove_price_on_param');
function wc_product_single_remove_price_on_param() {
    // Comprueba que estamos en el detalle de un producto y que viene el parametro en la url
    if ( is_singular('product') && isset($_GET['noprice']) ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
    }
}