Programs & Examples On #Wordpress

This tag is for programming-specific questions related to the content management system WordPress. Questions about theme development, WordPress administration, management best practices, and server configuration are off-topic here and best asked on Stack Exchange WordPress Development.

PHP - Merging two arrays into one array (also Remove Duplicates)

try to use the array_unique()

this elminates duplicated data inside the list of your arrays..

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Just to follow up, problem solved! I mentioned mod_sec settings for my server as being the possible culprit as suggested and they were able to fix this issue. Here's what the tech agent said to tell them when you go to support:

Just let them know you need the rule 340163 whitelisted for domain.com as its hitting a mod_sec rule.

Apparently you will need to do this for each domain that is having the issue, but it works. Thanks for all the suggestions everyone!

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

If you are simply testing a local dev version of WordPress as I was an hitting timeouts when WordPress tries to update itself you can always disable updates for your local version like so: https://www.wpbeginner.com/wp-tutorials/how-to-disable-automatic-updates-in-wordpress/

Don't do this for a production site!

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

How can I call a WordPress shortcode within a template?

Make sure to enable the use of shortcodes in text widgets.

// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );

// and then you can use it in any PHP file:  
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>

Check the documentation for more.

TypeError: $ is not a function WordPress

Just add this:

<script>
var $ = jQuery.noConflict();
</script>

to the head tag in header.php . Or in case you want to use the dollar sign in admin area (or somewhere, where header.php is not used), right before the place you want to use the it.

(There might be some conflicts that I'm not aware of, test it and if there are, use the other solutions offered here or at the link bellow.)

Source: http://www.wpdevsolutions.com/use-the-dollar-sign-in-wordpress-instead-of-jquery/

wp-admin shows blank page, how to fix it?

I found following solution working as I was using older version of wordpress.

  1. Open file blog/wp-admin/includes/screen.php in your favorite text editor.
  2. on line 706 find the following PHP statement: <?php echo self::$this->_help_sidebar; ?>
  3. Replace it with the statement: <?php echo $this->_help_sidebar; ?>
  4. Save your changes.

Getting the WordPress Post ID of current post

In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

Wordpress - Images not showing up in the Media Library

Ubuntu stores uploads in /var/lib/wordpress/wp-content/uploads . So what you need is to have this directory within your wordpress installation. Something like:

sudo ln -s /var/lib/wordpress/wp-content/uploads /var/www/www.mysite.com/wp-uploads

(replace mysite.com with your domain, the file should exist) should do the trick.

(Note that I've not tested this with multiple wordpress installations on one server.)

Further note that to make upload work at all (but this wasn't the question), you need to change Settings / Media / Store uploads in this folder to

 wp-content/uploads

(no leading slash).

Woocommerce get products

Do not use WP_Query() or get_posts(). From the WooCommerce doc:

wc_get_products and WC_Product_Query provide a standard way of retrieving products that is safe to use and will not break due to database changes in future WooCommerce versions. Building custom WP_Queries or database queries is likely to break your code in future versions of WooCommerce as data moves towards custom tables for better performance.

You can retrieve the products you want like this:

$args = array(
    'category' => array( 'hoodies' ),
    'orderby'  => 'name',
);
$products = wc_get_products( $args );

WooCommerce documentation

Note: the category argument takes an array of slugs, not IDs.

How can I get the image url in a Wordpress theme?

src="<?php bloginfo('template_url'); ?>/image_dir/img.ext"
worked for me for wordpress 3.6 i used it to get header logo using as

<img src="<?php bloginfo('template_url'); ?>/images/logo.jpg">

How do I find out what version of WordPress is running?

Unless he edited some code to delete this, you should be able to view source on the site and look for this meta tag:

<meta name="generator" content="WordPress 2.7.1" /> 

That will give you the version.

Bootstrap carousel resizing image

i had this issue years back..but I got this. All you need to do is set the width and the height of the image to whatever you want..what i mean is your image in your carousel inner ...don't add the style attribut like "style:"(no not this) but something like this and make sure your codes ar correct its gonna work...Good luck

Get cart item name, quantity all details woocommerce

Note on product price

The price of the product in the cart may be different from that of the product.

This can happen when you use some plugins that change the price of the product when it is added to the cart or if you have added a custom function in the functions.php of your active theme.

If you want to be sure you get the price of the product added to the cart you will have to get it like this:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

}

Instead of:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the product object
    $product            = $cart_item['data'];
    // gets the product prices
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
}

Other data you can get:

foreach ( WC()->cart->get_cart() as $cart_item ) {

    // get the data of the cart item
    $product_id         = $cart_item['product_id'];
    $variation_id       = $cart_item['variation_id'];

    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

    // gets the product object
    $product            = $cart_item['data'];
    // get the data of the product
    $sku                = $product->get_sku();
    $name               = $product->get_name();
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
    $stock_qty          = $product->get_stock_quantity();
    // attributes
    $attributes         = $product->get_attributes();
    $attribute          = $product->get_attribute( 'pa_attribute-name' ); // // specific attribute eg. "pa_color"
    // custom meta
    $custom_meta        = $product->get_meta( '_custom_meta_key', true );
    // product categories
    $categories         = wc_get_product_category_list(  $product->get_id() ); // returns a string with all product categories separated by a comma
}

Create WordPress Page that redirects to another URL

I'm not familiar with Wordpress templates, but I'm assuming that headers are sent to the browser by WP before your template is even loaded. Because of that, the common redirection method of:

header("Location: new_url");

won't work. Unless there's a way to force sending headers through a template before WP does anything, you'll need to use some Javascript like so:

<script language="javascript" type="text/javascript">
document.location = "new_url";
</script>

Put that in the section and it'll be run when the page loads. This method won't be instant, and it also won't work for people with Javascript disabled.

How to fix the "508 Resource Limit is reached" error in WordPress?

I've already encountered this error and this is the best solution I've found:

In your root folder (probably called public_html)please add this code to your .htaccess file...

REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999

#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>
<Files xmlrpc.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

In your wp-admin folder please add this code to your .htaccess file...

#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

From: https://www.quora.com/I-am-using-shared-hosting-and-my-I-O-usage-is-full-after-every-minute-What-is-this-I-O-usage-in-cPanel-How-can-I-reduce-it

Correct file permissions for WordPress

I think the below rules are recommended for a default wordpress site:

  • For folders inside wp-content, set 0755 permissions:

    chmod -R 0755 plugins

    chmod -R 0755 uploads

    chmod -R 0755 upgrade

  • Let apache user be the owner for the above directories of wp-content:

    chown apache uploads

    chown apache upgrade

    chown apache plugins

How to add "active" class to wp_nav_menu() current menu item (simple way)

If you want the 'active' in the html:

header with html and php:

        <?php
        $menu_items = wp_get_nav_menu_items( 'main_nav' ); // id or name of menu
        foreach ( (array) $menu_items as $key => $menu_item ) {
            if ( ! $menu_item->menu_item_parent ) {
                echo "<li class=" . vince_check_active_menu($menu_item) . "><a href='$menu_item->url'>";
                echo $menu_item->title;
                echo "</a></li>";
            }
        }
        ?>

functions.php:

function vince_check_active_menu( $menu_item ) {
    $actual_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    if ( $actual_link == $menu_item->url ) {
        return 'active';
    }
    return '';
}

TypeError: 'undefined' is not a function (evaluating '$(document)')

Use jQuery's noConflict. It did wonders for me

var example=jQuery.noConflict();
example(function(){
example('div#rift_connect').click(function(){
    example('span#resultado').text("Hello, dude!");
    });
});

That is, assuming you included jQuery on your HTML

<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

Use .htaccess to redirect HTTP to HTTPs

The above final .htaccess and Test A,B,C,D,E did not work for me. I just used below 2 lines code and it works in my WordPress website:

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.thehotskills.com/$1 [R=301,L]

I'm not sure where I was making the mistake but this page helped me out.

How to increase Maximum Upload size in cPanel?

New Cpanel Settings on a Godaddy
From Cpanel go to:

  • Software
  • Select PHP version
  • Click "Switch To PHP Options" located on upper right hand corner

Increase post max size and upload max file size, save and your done.

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

Nginx serves .php files as downloads, instead of executing them

If any of the proposed answers is not working, try this:

1.fix www.conf in etc/php5/fpm/pool.d:

listen = 127.0.0.1:9000;(delete all line contain listen= )

2.fix nginx.conf in usr/local/nginx/conf:

remove server block server{} (if exist) in block html{} because we use server{} in default (config file in etc/nginx/site-available) which was included in nginx.conf.

3. fix default file in etc/nginx/site-available

location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; }

4.restart nginx service

sudo service nginx restart

5.restart php service

service php5-fpm restart

6.enjoy

Create any php file in /usr/share/nginx/html and run in "server_name/file_name.php" (server_name depend on your config,normaly is localhost, file_name.php is name of file which created in /usr/share/nginx/html ).

I am using Ubuntu 14.04

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

Wordpress plugin install: Could not create directory

If you have installed wordpress using apt, the config files are split in multiple directories. In that case you need to run:

sudo chown -R -h www-data:www-data /var/lib/wordpress/wp-content/
sudo chown -R -h www-data:www-data /usr/share/wordpress/wp-content/

The -h switch changes the permissions for symlinks as well, otherwise they are not removable by user www-data

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

How can I get customer details from an order in WooCommerce?

This is happening because the WC_Customer abstract doesn't hold hold address data (among other data) apart from within a session. This data is stored via the cart/checkout pages, but again—only in the session (as far as the WC_Customer class goes).

If you take a look at how the checkout page gets the customer data, you'll follow it to the WC_Checkout class method get_value, which pulls it directly out of user meta. You'd do well to follow the same pattern :-)

How to display Wordpress search results?

WordPress include tags, categories and taxonomies in search results

This code is taken from http://atiblog.com/custom-search-results/

Some functions here are taken from twentynineteen theme.Because it is made on this theme.

This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.

You need to modify your search.php of your theme to do so.

<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) ); 
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );

$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();

foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}

foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}

foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}

$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));

$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {

}

?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {

}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {

}
?>

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

Table is marked as crashed and should be repaired

When I got this error:

#145 - Table '.\engine\phpbb3_posts' is marked as crashed and should be repaired

I ran this command in PhpMyAdmin to fix it:

REPAIR TABLE phpbb3_posts;

How to get post slug from post in WordPress?

Here is most advanced and updated version what cover many cases:

if(!function_exists('the_slug')):
    function the_slug($post_id=false, $echo=true) {
        global $product, $page;

        if(is_numeric($post_id) && $post_id == intval($post_id)) {} else {
            if(!is_object($post_id)){}else if(property_exists($post_id, 'ID')){
                $post_id = $post_id->ID;
            }
            if(empty($post_id) && property_exists($product, 'ID')) $post_id = $product->ID;
            if(empty($post_id)) $post_id =  get_the_ID();

            if(empty($post_id) && property_exists($page, 'ID')) $post_id =  $page->ID;
        }

        if(!empty($post_id))
            $slug = basename(get_permalink($post_id));
        else
            $slug = basename(get_permalink());
        do_action('before_slug', $slug);
        $slug = apply_filters('slug_filter', $slug);
        if( $echo ) echo $slug;
        do_action('after_slug', $slug);
        return $slug;
      }
endif;

This is collections from the best answers and few my updates.

WordPress query single post by slug

a less expensive and reusable method

function get_post_id_by_name( $post_name, $post_type = 'post' )
{
    $post_ids = get_posts(array
    (
        'post_name'   => $post_name,
        'post_type'   => $post_type,
        'numberposts' => 1,
        'fields' => 'ids'
    ));

    return array_shift( $post_ids );
}

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

You will have to change the value of

post-max-size
upload-max-filesize

both of which you will find in php.ini

Restarting your server will help it start working. On a local test server running XAMIP, i had to stop the Apache server and restart it. It worked fine after that.

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

How to get the category title in a post in Wordpress?

Use get_the_category() like this:

<?php
foreach((get_the_category()) as $category) { 
    echo $category->cat_name . ' '; 
} 
?>

It returns a list because a post can have more than one category.

The documentation also explains how to do this from outside the loop.

wp_nav_menu change sub-menu class name?

I had to change:

function start_lvl(&$output, $depth)

to:

function start_lvl( &$output, $depth = 0, $args = array() )

Because I was getting an incompatibility error:

Strict Standards: Declaration of My_Walker_Nav_Menu::start_lvl() should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array)

How to set character limit on the_content() and the_excerpt() in wordpress

wp_trim_words() This function trims text to a certain number of words and returns the trimmed text.

$excerpt = wp_trim_words( get_the_content(), 40, '<a href="'.get_the_permalink().'">More Link</a>');

Get truncated string with specified width using mb_strimwidth() php function.

$excerpt = mb_strimwidth( strip_tags(get_the_content()), 0, 100, '...' );

Using add_filter() method of WordPress on the_content filter hook.

add_filter( "the_content", "limit_content_chr" );
function limit_content_chr( $content ){
    if ( 'post' == get_post_type() ) {
        return mb_strimwidth( strip_tags($content), 0, 100, '...' );
    } else {
        return $content;
    }
}

Using custom php function to limit content characters.

function limit_content_chr( $content, $limit=100 ) {
    return mb_strimwidth( strip_tags($content), 0, $limit, '...' );
}

// using above function in template tags
echo limit_content_chr( get_the_content(), 50 );

Adding <script> to WordPress in <head> element

In your theme's functions.php:

function my_custom_js() {
    echo '<script type="text/javascript" src="myscript.js"></script>';
}
// Add hook for admin <head></head>
add_action( 'admin_head', 'my_custom_js' );
// Add hook for front-end <head></head>
add_action( 'wp_head', 'my_custom_js' );

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

Wordpress 4.2 introduced support for "utf8mb4" character encoding for security reasons, but only MySQL 5.5.3 and greater support it. The way the installer (and updater) handles this is that it checks your MySQL version and your database will be upgraded to utfmb4 only if it's supported.

This sounds great in theory but the problem (as you've discovered) is when you are migrating databases from a MySQL server that supports utf8mb4 to one that doesn't. While the other way around should work, it's basically a one-way operation.

As pointed out by Evster you might have success using PHPMYAdmin's "Export" feature. Use "Export Method: Custom" and for the "Database system or older MySQL server to maximize output compatibility with:" dropdown select "MYSQL 40".

For a command line export using mysqldump. Have a look at the flag:

$ mysqldump --compatible=mysql4

Note: If there are any 4-byte characters in the database they will be corrupted.

Lastly, for anyone using the popular WP Migrate DB PRO plugin, a user in this Wordpress.org thread reports that the migration is always handled properly but I wasn't able to find anything official.

The WP Migrate DB plugin translates the database from one collation to the other when it moves 4.2 sites between hosts with pre- or post-5.5.3 MySQL

At this time, there doesn't appear to be a way to opt out of the database update. So if you are using a workflow where you are migrating a site from a server or localhost with MySQL > 5.5.3 to one that uses an older MySQL version you might be out of luck.

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

The requested URL /about was not found on this server

I am working on MacOS, following operation solved my problem:

I copied from : https://akrabat.com/setting-up-php-mysql-on-os-x-10-7-lion/

cd /etc/apache2

Give write permission the config file to root: sudo chmod u+w httpd.conf sudo vim httpd.conf

Find #LoadModule php5_module libexec/apache2/libphp5.so

and remove the leading #

Find #LoadModule rewrite_module libexec/apache2/mod_rewrite.so

and remove the leading #

Find AllowOverride None within the section and change to AllowOverride All so that .htaccess files will work.

Change permissions back: sudo chmod u-w httpd.conf

Restart Apache by running following in terminal:

sudo apachectl restart

Column count doesn't match value count at row 1

The error means that you are providing not as much data as the table wp_posts does contain columns. And now the DB engine does not know in which columns to put your data.

To overcome this you must provide the names of the columns you want to fill. Example:

insert into wp_posts (column_name1, column_name2)
values (1, 3)

Look up the table definition and see which columns you want to fill.

And insert means you are inserting a new record. You are not modifying an existing one. Use update for that.

Proper way to get page content

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages 
the_ID();
the_title();

//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}

endwhile;

//if you want specific page of content then write in loop

  if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
    {
    echo get_the_ID();
    the_title();
    the_content();
    }

How To Include CSS and jQuery in my WordPress plugin?

Accepted answer is incomplete. You should use the right hook: wp_enqueue_scripts

Example:

    function add_my_css_and_my_js_files(){
        wp_enqueue_script('your-script-name', $this->urlpath  . '/your-script-filename.js', array('jquery'), '1.2.3', true);
        wp_enqueue_style( 'your-stylesheet-name', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
    }
    add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files");

How to pass extra variables in URL with WordPress

To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:

  • add_query_arg() - to create the URL with your new query variable ('c' in your example)
  • the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
  • get_query_var() - to retrieve the value of your custom query variable passed in your URL.

Note: there's no need to even touch the superglobals ($_GET) if you do it this way.

Example

On the page where you need to create the link / set the query variable:

if it's a link back to this page, just adding the query variable

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">

if it's a link to some other page

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) ) )?>">

In your functions.php, or some plugin file or custom class (front-end only):

function add_custom_query_var( $vars ){
  $vars[] = "c";
  return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );

On the page / function where you wish to retrieve and work with the query var set in your URL:

$my_c = get_query_var( 'c' );

On the Back End (wp-admin)

On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.

In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:

$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );

though in a pinch you could do the tried and true

$my_c = isset( $_GET['c'] ? $_GET['c'] : "";

or some variant thereof.

Retrieve WordPress root directory path?

Note: This answer is really old and things may have changed in WordPress land since.

I am guessing that you need to detect the WordPress root from your plugin or theme. I use the following code in FireStats to detect the root WordPress directory where FireStats is installed a a WordPress plugin.

function fs_get_wp_config_path()
{
    $base = dirname(__FILE__);
    $path = false;

    if (@file_exists(dirname(dirname($base))."/wp-config.php"))
    {
        $path = dirname(dirname($base))."/wp-config.php";
    }
    else
    if (@file_exists(dirname(dirname(dirname($base)))."/wp-config.php"))
    {
        $path = dirname(dirname(dirname($base)))."/wp-config.php";
    }
    else
        $path = false;

    if ($path != false)
    {
        $path = str_replace("\\", "/", $path);
    }
    return $path;
}

How can I get the order ID in WooCommerce?

As of woocommerce 3.0

$order->id;

will not work, it will generate notice, use getter function:

$order->get_id();

The same applies for other woocommerce objects like procut.

How to add Class in <li> using wp_nav_menu() in Wordpress?

No need to create custom walker. Just use additional argument and set filter for nav_menu_css_class.

For example:

$args = array(
    'container'     => '',
    'theme_location'=> 'your-theme-loc',
    'depth'         => 1,
    'fallback_cb'   => false,
    'add_li_class'  => 'your-class-name1 your-class-name-2'
    );
wp_nav_menu($args);

Notice the new 'add_li_class' argument.

And set the filter on functions.php

function add_additional_class_on_li($classes, $item, $args) {
    if(isset($args->add_li_class)) {
        $classes[] = $args->add_li_class;
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

Get Category name from Post ID

echo '<p>'. get_the_category( $id )[0]->name .'</p>';

is what you maybe looking for.

How to get WooCommerce order details

ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x

For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE

Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…

Using print_r() function (or var_dump() function too) allow to output the raw data of an object or an array.

So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.

IMPORTANT: With $order object you can use most of WC_order or WC_Abstract_Order methods (using the object syntax)…


Here is the code:

function get_order_details($order_id){

    // 1) Get the Order object
    $order = wc_get_order( $order_id );

    // OUTPUT
    echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
    print_r($order);
    echo '<br><br>';
    echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
    echo '$order->order_type: ' . $order->order_type . '<br>';
    echo '$order->id: ' . $order->id . '<br>';
    echo '<h4>THE POST OBJECT:</h4>';
    echo '$order->post->ID: ' . $order->post->ID . '<br>';
    echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
    echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
    echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
    echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
    echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
    echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
    echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
    echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
    echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
    echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
    echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
    echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
    echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
    echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
    echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
    echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
    echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
    echo '$order->post->guid: ' . $order->post->guid . '<br>';
    echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
    echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
    echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
    echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
    echo '$order->post->filter: ' . $order->post->filter . '<br>';
    echo '<h4>THE ORDER OBJECT (again):</h4>';
    echo '$order->order_date: ' . $order->order_date . '<br>';
    echo '$order->modified_date: ' . $order->modified_date . '<br>';
    echo '$order->customer_message: ' . $order->customer_message . '<br>';
    echo '$order->customer_note: ' . $order->customer_note . '<br>';
    echo '$order->post_status: ' . $order->post_status . '<br>';
    echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
    echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
    echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
    echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
    echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
    echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 2) Get the Order meta data
    $order_meta = get_post_meta($order_id);

    echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
    print_r($order_meta);
    echo '<br><br>';
    echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
    echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
    echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
    echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
    echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
    echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
    echo 'And so on ……… <br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 3) Get the order items
    $items = $order->get_items();

    echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';

    foreach ( $items as $item_id => $item_data ) {

        echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
        print_r($item_data);
        echo '<br><br>';
        echo 'Item ID: ' . $item_id. '<br>';
        echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
        echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';

        // Using get_item_meta() method
        echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
        echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
        echo 'And so on ……… <br><br>';
        echo '- - - - - - - - - - - - - <br><br>';
    }
    echo '- - - - - - E N D - - - - - <br><br>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Usage (if your order ID is 159 for example):

get_order_details(159);

This code is tested and works.

Updated code on November 21, 2016

Extracting a parameter from a URL in WordPress

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

Insert PHP code In WordPress Page and Post

Description:

there are 3 steps to run PHP code inside post or page.

  1. In functions.php file (in your theme) add new function

  2. In functions.php file (in your theme) register new shortcode which call your function:

add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
  1. use your new shortcode

Example #1: just display text.

In functions:

function simple_function_1() {
    return "Hello World!";
}

add_shortcode( 'own_shortcode1', 'simple_function_1' );

In post/page:

[own_shortcode1]

Effect:

Hello World!

Example #2: use for loop.

In functions:

function simple_function_2() {
    $output = "";
    
    for ($number = 1; $number < 10; $number++) {    
        // Append numbers to the string
        $output .= "$number<br>";
    } 
    
    return "$output";
}

add_shortcode( 'own_shortcode2', 'simple_function_2' );

In post/page:

[own_shortcode2]

Effect:

1
2
3
4
5
6
7
8
9

Example #3: use shortcode with arguments

In functions:

function simple_function_3($name) {
    return "Hello $name";
}

add_shortcode( 'own_shortcode3', 'simple_function_3' );

In post/page:

[own_shortcode3 name="John"]

Effect:

Hello John

Example #3 - without passing arguments

In post/page:

[own_shortcode3]

Effect:

Hello 

WP -- Get posts by category?

'category_name'=>'this cat' also works but isn't printed in the WP docs

How can I get the current page name in WordPress?

This is what I ended up using, as of 2018:

<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">

Wordpress keeps redirecting to install-php after migration

This happens due to the following issues:

  1. Missing Files
  2. Database Connection Details Problem
  3. Site URL Issue
  4. .htaccess File Issue
  5. Webserver Failure
  6. Resources Blocked by Plugin
  7. Query Limit Exceeded
  8. Insufficient Database Privileges
  9. PHP Extensions

Reference: https://www.scratchcode.io/wordpress-keeps-redirecting-to-wp-admin-install-php/

How to display Woocommerce Category image?

get_woocommerce_term_meta is depricated since Woo 3.6.0.

so change

$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );

into: ($value->term_id should be woo category id)

get_term_meta($value->term_id, 'thumbnail_id', true)

see docs for details: https://docs.woocommerce.com/wc-apidocs/function-get_woocommerce_term_meta.html

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

TypeError: $ is not a function when calling jQuery function

This should fix it:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

Put simply, WordPress runs their own scripting before you can and they release the $ var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.

From their documentation:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available...

How to Load Ajax in Wordpress

As per your request I have put this in an answer for you.

As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.

<script type="text/javascript">
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:

  • wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
  • wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.

Everything else is described in the documentation linked above. Happy coding!

P.S. Here is an example that should work. (I have not tested)

Front end:

<script type="text/javascript">
    jQuery.ajax({
        url: ajaxurl,
        data: {
            action: 'my_action_name'
        },
        type: 'GET'
    });
</script>

Back end:

<?php
    function my_ajax_callback_function() {
        // Implement ajax function here
    }
    add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end
?>

UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.

WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:

var translation = {
    success: "Success!",
    failure: "Failure!",
    error: "Error!",
    ...
};

So this simply loads an object into the HTML head tag. This can be utilized in the following way:

Backend:

wp_localize_script( 'FrontEndAjax', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' )
) );

The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.

On the front end, the URL is now accessible via ajax.url, rather than simply ajaxurl in the previous examples.

Keep values selected after form submission

<select name="name">
   <option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
   <option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>

Get custom product attributes in Woocommerce

Most updated:

$product->get_attribute( 'your_attr' );

You will need to define $product if it's not on the page.

How to display Woocommerce product price by ID number on a custom page?

If you have the product's ID you can use that to create a product object:

$_product = wc_get_product( $product_id );

Then from the object you can run any of WooCommerce's product methods.

$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();

Update
Please review the Codex article on how to write your own shortcode.

Integrating the WooCommerce product data might look something like this:

function so_30165014_price_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = "price = " . $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

Your shortcode would then look like [woocommerce_price id="99"]

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

WordPress asking for my FTP credentials to install plugins

We had the same problem as part of a bigger problem. The suggested solution of

define('FS_METHOD', 'direct');

hides that window but then we still had problems with loading themes and upgrades etc. It is related to permissions however in our case we fixed the problem by moving from php OS vendor mod_php to the more secure php OS vendor FastCGI application.

How can I find my php.ini on wordpress?

Wordpress dont have a php.ini file. It just a cms, look into your server. for example if you use XAMPP in windows xampp\php\php.ini is the location.

How do I display a wordpress page content?

@Marc B Thanks for the comment. Helped me discover this:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
the_content();
endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>

wordpress contactform7 textarea cols and rows change in smaller screens

In the documentaion http://contactform7.com/text-fields/#textarea

[textarea* message id:contact-message 10x2 placeholder "Your Message"]

The above will generate a textarea with cols="10" and rows="2"

<textarea name="message" cols="10" rows="2" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="contact-message" aria-required="true" aria-invalid="false" placeholder="Your Message"></textarea>

How do I correct this Illegal String Offset?

if ($inputs['type'] == 'attach') {

The code is valid, but it expects the function parameter $inputs to be an array. The "Illegal string offset" warning when using $inputs['type'] means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type' is not suitable.)

So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.

However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type' to 0, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)

You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs); in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:

if (is_array($inputs) && $inputs['type'] == 'attach') {

Can I install/update WordPress plugins without providing FTP access?

Two steps

  1. Add below code in wp-config file

    define('FS_METHOD', 'direct');
    
  2. We need to give full permission to the folder like if server connected with SSH then paste below code in terminal and make sure you are inside on website folder and then run below code

    sudo chmod -R 775 wp-content/plugins 
    

    or give full permission to website folder

    sudo chown -R www-data:www-data website_folder
    

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

Late to the party, but in case this happens with a WORDPRESS installation :

#1273 - Unknown collation: 'utf8mb4_unicode_520_ci

In phpmyadmin, under export method > Format-specific options( custom export )

Set to : MYSQL40

If you will try to import now, you now might get another error message :

1064 - You have an error in your SQL syntax; .....

That is because The older TYPE option that was synonymous with ENGINE was removed in MySQL 5.5.

Open your .sql file , search and replace all instances

from TYPE= to ENGINE=

Now the import should go smoothly.

Remove category & tag base from WordPress url - without a plugin

If you use Yoast SEO plugin just go to:

Search Appearance > Taxonomies > Category URLs.

And select remove from Strip the category base (usually /category/) from the category URL.

Regarding the tag removal I did not found any solution yet.

WordPress path url in js script file

If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}

Redirect after Login on WordPress

// add the code to your theme function.php
//for logout redirection
add_action('wp_logout','auto_redirect_after_logout');
function auto_redirect_after_logout(){
wp_redirect( home_url() );
exit();
}
//for login redirection
add_action('wp_login','auto_redirect_after_login');
function auto_redirect_after_login(){
wp_redirect( home_url() );
exit();
`enter code here`}

How to filter WooCommerce products by custom attribute

You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:

Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.

If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:

http://yoursite.com/shop/?filtering=1&filter_min-kvadratura=181&filter_max-kvadratura=108&filter_obem-ohlajdane=111

... and the digits are actually the id-s of the different attribute values, that you want to set.

WooCommerce return product object by id

Use this method:

$_product = wc_get_product( $id );

Official API-docs: wc_get_product

WordPress Get the Page ID outside the loop

If you by any means searched this topic because of the post page (index page alternative when using static front page), then the right answer is this:

if (get_option('show_on_front') == 'page') {
    $page_id = get_option('page_for_posts');
    echo get_the_title($page_id);
}

(taken from Forrst | Echo WordPress "Posts Page" title - Some code from tammyhart)

Woocommerce, get current product id

2017 Update - since WooCommerce 3:

global $product;
$id = $product->get_id();

Woocommerce doesn't like you accessing those variables directly. This will get rid of any warnings from woocommerce if your wp_debug is true.

How do I add a simple jQuery script to WordPress?

You can add custom javascript or jquery using this plugin.
https://wordpress.org/plugins/custom-javascript-editor/

When you use jQuery don't forget use jquery noconflict mode

How to determine the current language of a wordpress page when using polylang?

pll_current_language

Returns the current language

Usage:

pll_current_language( $value ); 
  • $value => (optional) either name or locale or slug, defaults to slug

returns either the full name, or the WordPress locale (just as the WordPress core function ‘get_locale’ or the slug ( 2-letters code) of the current language.

Display all post meta keys and meta values of the same post ID in wordpress

Default Usage

Get the meta for all keys:

<?php $meta = get_post_meta($post_id); ?>

Get the meta for a single key:

<?php $key_1_values = get_post_meta( 76, 'key_1' ); ?>

for example:

$myvals = get_post_meta($post_id);

foreach($myvals as $key=>$val)
{
    echo $key . ' : ' . $val[0] . '<br/>';
}

Note: some unwanted meta keys starting with "underscore(_)" will also come, so you will need to filter them out.

For reference: See Codex

WooCommerce - get category for product page

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

How to modify WooCommerce cart, checkout pages (main theme portion)

You can use the is_cart() conditional tag:

if (! is_cart() ) {
  // Do something.
}

Forbidden You don't have permission to access /wp-login.php on this server

I had this same problem, and after temporarily deleting all my .htaccess files, then trying to modify them as suggested, and making sure all my files and folder permissions were set to 777, I still couldn't get it to work. I don't know why I couldn't access the file, but I was able to create a new file and access it no problem. So what I did was create a new file in /wp-admin/ called temp.php and pasted all the code from install.php into it. This allowed me to access the file. The only other thing I had to do was edit the code so that the form submitted to temp.php instead of install.php. After that, I could finish the install and everything worked.

<form id="setup" method="post" action="temp.php?step=2">

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

WooCommerce: Finding the products in database

I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta table. You can find the corresponding products within wp_posts table.

How can I add a PHP page to WordPress?

Just create a page-mytitle.php file to the folder of the current theme, and from the Dashboard a page "mytitle".

Then when you invoke the page by the URL you are going to see the page-mytitle.php. You must add HTML, CSS, JavaScript, wp-loop, etc. to this PHP file (page-mytitle.php).

How to insert data using wpdb

The recommended way (as noted in codex):

$wpdb->insert( $table_name, array('column_name_1'=>'hello', 'other'=> 123), array( '%s', '%d' ) );

So, you'd better to sanitize values - ALWAYS CONSIDER THE SECURITY.

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

You're getting into looping most likely due to these rules:

RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

Just comment it out and try again in a new browser.

PHP fopen() Error: failed to open stream: Permission denied

[function.fopen]: failed to open stream

If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :

allow_url_fopen = off
should bee this 
allow_url_fopen = On

And add this line below it:
allow_url_include = off
should bee this 
allow_url_include = on

Relative URLs in WordPress

I think this is the kind of question only a core developer could/should answer. I've researched and found the core ticket #17048: URLs delivered to the browser should be root-relative. Where we can find the reasons explained by Andrew Nacin, lead core developer. He also links to this [wp-hackers] thread. On both those links, these are the key quotes on why WP doesn't use relative URLs:

Core ticket:

  • Root-relative URLs aren't really proper. /path/ might not be WordPress, it might be outside of the install. So really it's not much different than an absolute URL.

  • Any relative URLs also make it significantly more difficult to perform transformations when the install is moved. The find-replace is going to be necessary in most situations, and having an absolute URL is ironically more portable for those reasons.

  • absolute URLs are needed in numerous other places. Needing to add these in conditionally will add to processing, as well as introduce potential bugs (and incompatibilities with plugins).

[wp-hackers] thread

  • Relative to what, I'm not sure, as WordPress is often in a subdirectory, which means we'll always need to process the content to then add in the rest of the path. This introduces overhead.

  • Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible to properly implement.

  • WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to relocate, it is a global find-replace in the database.


And, on a personal note, more than once I've found theme and plugins bad coded that simply break when WP_CONTENT_URL is defined.
They don't know this can be set and assume that this is true: WP.URL/wp-content/WhatEver, and it's not always the case. And something will break along the way.


The plugin Relative URLs (linked in edse's Answer), applies the function wp_make_link_relative in a series of filters in the action hook template_redirect. It's quite a simple code and seems a nice option.

get all the images from a folder in php

when you want to get all image from folder then use glob() built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image

  $all_files = glob("mytheme/images/myimages/*.*");
  for ($i=0; $i<count($all_files); $i++)
    {
      $image_name = $all_files[$i];
      $supported_format = array('gif','jpg','jpeg','png');
      $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
      if (in_array($ext, $supported_format))
          {
            echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
          } else {
              continue;
          }
    }

for more information

PHP Manual

How organize uploaded media in WP?

Check this plugin WP Media Folder at Joomunited, you can:

  • Create visual folders and move file inside
  • Restrict file visualisation
  • Create galleries from folders
  • ...

Since the last months they add a lot of must use features.

This is a paid plugin but it worth the money, I install it now by default on all my customers websites.

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Turn off deprecated errors in PHP 5.3

this error occur when you change your php version: it's very simple to suppress this error message

To suppress the DEPRECATED Error message, just add below code into your index.php file:

init_set('display_errors',False);

upstream sent too big header while reading response header from upstream

upstream sent too big header while reading response header from upstream is nginx's generic way of saying "I don't like what I'm seeing"

  1. Your upstream server thread crashed
  2. The upstream server sent an invalid header back
  3. The Notice/Warnings sent back from STDERR overflowed their buffer and both it and STDOUT were closed

3: Look at the error logs above the message, is it streaming with logged lines preceding the message? PHP message: PHP Notice: Undefined index: Example snippet from a loop my log file:

2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
... // 20 lines of same
PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undef
2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "ta_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Firstname

you can see in the 3rd line from the bottom that the buffer limit was hit, broke, and the next thread wrote in over it. Nginx then closed the connection and returned 502 to the client.

2: log all the headers sent per request, review them and make sure they conform to standards (nginx does not permit anything older than 24 hours to delete/expire a cookie, sending invalid content length because error messages were buffered before the content counted...). getallheaders function call can usually help out in abstracted code situations php get all headers

examples include:

<?php
//expire cookie
setcookie ( 'bookmark', '', strtotime('2012-01-01 00:00:00') );
// nginx will refuse this header response, too far past to accept
....
?>

and this:

<?php
header('Content-type: image/jpg');
?>

<?php   //a space was injected into the output above this line
header('Content-length: ' . filesize('image.jpg') );
echo file_get_contents('image.jpg');
// error! the response is now 1-byte longer than header!!
?>

1: verify, or make a script log, to ensure your thread is reaching the correct end point and not exiting before completion.

WordPress - Check if user is logged in

Use the is_user_logged_in function:

if ( is_user_logged_in() ) {
   // your code for logged in user 
} else {
   // your code for logged out user 
}

How to get WordPress post featured image URL

Simply inside the loop write <?php the_post_thumbnail_url(); ?> as shown below:-

$args=array('post_type' => 'your_custom_post_type_slug','order' => 'DESC','posts_per_page'=> -1) ;
$the_qyery= new WP_Query($args);

if ($the_qyery->have_posts()) :
    while ( $the_qyery->have_posts() ) : $the_qyery->the_post();?>

<div class="col col_4_of_12">
    <div class="article_standard_view">
        <article class="item">
            <div class="item_header">
                <a href="<?php the_permalink(); ?>"><img src="<?php the_post_thumbnail_url(); ?>" alt="Post"></a>
            </div>

        </article>
    </div>
</div>            
<?php endwhile; endif; ?>

Maximum packet size for a TCP connection

According to http://en.wikipedia.org/wiki/Maximum_segment_size, the default largest size for a IPV4 packet on a network is 536 octets (bytes of size 8 bits). See RFC 879

Remove all items from a FormArray in Angular

As of Angular 8+ you can use clear() to remove all controls in the FormArray:

const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);
console.log(arr.length);  // 2

arr.clear();
console.log(arr.length);  // 0

For previous versions the recommended way is:

while (arr.length) {
   arr.removeAt(0);
}

https://angular.io/api/forms/FormArray#clear

How to disable Google asking permission to regularly check installed apps on my phone?

On Android prior to 4.2, go to Google Settings, tap Verify apps and uncheck the option Verify apps.

On Android 4.2+, uncheck the option Settings > Security > Verify apps and/or Settings > Developer options > Verify apps over USB.

How to make g++ search for header files in a specific directory?

gcc -I/path -L/path
  • -I /path path to include, gcc will find .h files in this path

  • -L /path contains library files, .a, .so

How to symbolicate crash log Xcode?

For me the .crash file was enough. Without .dSYM file and .app file.

I ran these two commands on the mac where I build the archive and it worked:

export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer" 

/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash  /yourPath/crash1.crash > /yourPath/crash1_symbolicated.crash

What does the keyword Set actually do in VBA?

Set is used for setting object references, as opposed to assigning a value.

Abort a Git Merge

as long as you did not commit you can type

git merge --abort

just as the command line suggested.

How to solve maven 2.6 resource plugin dependency?

Seems your settings.xml file is missing your .m2 (local maven repo) folder.

When using eclipse navigate to Window -> Preferences -> Maven -> User Settings -> Browse to your settings.xml and click apply.

Then do maven Update Project.

enter image description here

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I know this is an old question. The way I solved it - after failing by increasing the length or even changing to data type text - was creating an XLSX file and importing. It accurately detected the data type instead of setting all columns as varchar(50). Turns out nvarchar(255) for that column would have done it too.

Refresh certain row of UITableView based on Int in Swift

let indexPathRow:Int = 0
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)

Show week number with Javascript?

Martin Schillinger's version seems to be the strictly correct one.

Since I knew I only needed it to work correctly on business week days, I went with this simpler form, based on something I found online, don't remember where:

ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );

It fails in early January on days that belong to the previous year's last week (it produces CW = 0 in those cases) but is correct for everything else.

MemoryStream - Cannot access a closed Stream

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

However, the StreamWriter you're using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter, which is then trying to close the stream).

The best way to fix this is: don't use using and don't dispose of the StreamReader and StreamWriter. See this question.

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    var sr = new StreamReader(ms);

    sw.WriteLine("data");
    sw.WriteLine("data 2");
    ms.Position = 0;

    Console.WriteLine(sr.ReadToEnd());                        
}

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

StreamWriter sw = null;
StreamReader sr = null;

try
{
    using (var ms = new MemoryStream())
    {
        sw = new StreamWriter(ms);
        sr = new StreamReader(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;

        Console.WriteLine(sr.ReadToEnd());                        
    }
}
finally
{
    if (sw != null) sw.Dispose();
    if (sr != null) sr.Dispose();
}

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

MySQL: ALTER TABLE if column not exists

Use PREPARE/EXECUTE and querying the schema. The host doesn't need to have permission to create or run procedures :

SET @dbname = DATABASE();
SET @tablename = "tableName";
SET @columnname = "colName";
SET @preparedStatement = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (table_name = @tablename)
      AND (table_schema = @dbname)
      AND (column_name = @columnname)
  ) > 0,
  "SELECT 1",
  CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

How do I escape ampersands in XML so they are rendered as entities in HTML?

<xsl:text disable-output-escaping="yes">&amp;&nbsp;</xsl:text> will do the trick.

How do you perform address validation?

I will refer you to my blog post - A lesson in address storage, I go into some of the techniques and algorithms used in the process of address validation. My key thought is "Don't be lazy with address storage, it will cause you nothing but headaches in the future!"

Also, there is another StackOverflow question that asks this question. Entitled How should international geographic addresses be stored in a relational database.

What's the difference between a POST and a PUT HTTP REQUEST?

In simple words you can say:

1.HTTP Get:It is used to get one or more items

2.HTTP Post:It is used to create an item

3.HTTP Put:It is used to update an item

4.HTTP Patch:It is used to partially update an item

5.HTTP Delete:It is used to delete an item

What is the difference between a web API and a web service?

Well, TMK may be right in the Microsoft world, but in world of all software including Java/Python/etc, I believe that there is no difference. They're the same thing.

Increase permgen space

You can use :

-XX:MaxPermSize=128m

to increase the space. But this usually only postpones the inevitable.

You can also enable the PermGen to be garbage collected

-XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled

Usually this occurs when doing lots of redeploys. I am surprised you have it using something like indexing. Use virtualvm or jconsole to monitor the Perm gen space and check it levels off after warming up the indexing.

Maybe you should consider changing to another JVM like the IBM JVM. It does not have a Permanent Generation and is immune to this issue.

Add Legend to Seaborn point plot

I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')

In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

plt.legend(handles=[red_patch, black_patch])

And the legend ought to appear in the pointplot.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

How to convert JSON to a Ruby hash

You can use the nice_hash gem: https://github.com/MarioRuiz/nice_hash

require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'

# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json

# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)

# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]

How to convert JTextField to String and String to JTextField?

// to string
String text = textField.getText();

// to JTextField
textField.setText(text);

You can also create a new text field: new JTextField(text)

Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.

Reference: javadocs of JTextField

Chrome refuses to execute an AJAX script due to wrong MIME type

In my case, I use

$.getJSON(url, function(json) { ... });

to make the request (to Flickr's API), and I got the same MIME error. Like the answer above suggested, adding the following code:

$.ajaxSetup({ dataType: "jsonp" });

Fixed the issue and I no longer see the MIME type error in Chrome's console.

Does a foreign key automatically create an index?

Foreign keys do not create indexes. Only alternate key constraints(UNIQUE) and primary key constraints create indexes. This is true in Oracle and SQL Server.

How to programmatically take a screenshot on Android?

As a reference, one way to capture the screen (and not just your app activity) is to capture the framebuffer (device /dev/graphics/fb0). To do this you must either have root privileges or your app must be an app with signature permissions ("A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission") - which is very unlikely unless you compiled your own ROM.

Each framebuffer capture, from a couple of devices I have tested, contained exactly one screenshot. People have reported it to contain more, I guess it depends on the frame/display size.

I tried to read the framebuffer continuously but it seems to return for a fixed amount of bytes read. In my case that is (3 410 432) bytes, which is enough to store a display frame of 854*480 RGBA (3 279 360 bytes). Yes, the frame, in binary, outputted from fb0 is RGBA in my device. This will most likely depend from device to device. This will be important for you to decode it =)

In my device /dev/graphics/fb0 permissions are so that only root and users from group graphics can read the fb0.

graphics is a restricted group so you will probably only access fb0 with a rooted phone using su command.

Android apps have the user id (uid) = app_## and group id (guid) = app_## .

adb shell has uid = shell and guid = shell, which has much more permissions than an app. You can actually check those permissions at /system/permissions/platform.xml

This means you will be able to read fb0 in the adb shell without root but you will not read it within the app without root.

Also, giving READ_FRAME_BUFFER and/or ACCESS_SURFACE_FLINGER permissions on AndroidManifest.xml will do nothing for a regular app because these will only work for 'signature' apps.

Also check this closed thread for more details.

How to decrypt an encrypted Apple iTunes iPhone backup?

Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.

You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.

Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.

I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.

Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.

I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.

In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.

Good luck!

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

In addition to the locations listed above, the OS X version of Perl also has two more ways:

  1. The /Library/Perl/x.xx/AppendToPath file. Paths listed in this file are appended to @INC at runtime.

  2. The /Library/Perl/x.xx/PrependToPath file. Paths listed in this file are prepended to @INC at runtime.

How can I set a proxy server for gem?

You need to write this in the command prompt:

set HTTP_PROXY=http://your_proxy:your_port

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

Difference between setUp() and setUpBeforeClass()

Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.

Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).

"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.

Why am I getting the error "connection refused" in Python? (Sockets)

This error means that for whatever reason the client cannot connect to the port on the computer running server script. This can be caused by few things, like lack of routing to the destination, but since you can ping the server, it should not be the case. The other reason might be that you have a firewall somewhere between your client and the server - it could be on server itself or on the client. Given your network addressing, I assume both server and client are on the same LAN, so there shouldn't be any router/firewall involved that could block the traffic. In this case, I'd try the following:

  • check if you really have that port listening on the server (this should tell you if your code does what you think it should): based on your OS, but on linux you could do something like netstat -ntulp
  • check from the server, if you're accepting the connections to the server: again based on your OS, but telnet LISTENING_IP LISTENING_PORT should do the job
  • check if you can access the port of the server from the client, but not using the code: just us the telnet (or appropriate command for your OS) from the client

and then let us know the findings.

Extending the User model with custom fields in Django

Simple and effective approach is models.py

from django.contrib.auth.models import User
class CustomUser(User):
     profile_pic = models.ImageField(upload_to='...')
     other_field = models.CharField()

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

For anyone who stumbles across this in the future, this is how you do it:

xl.Range("A1:A1").Style := "Bad"
xl.Range("A1:A1").Style := "Good"
xl.Range("A1:A1").Style := "Neutral"

An easy way to check on things like this is to open excel and record a macro. In this case I recorded a macro where I just formatted the cell to "Bad". Once you've recorded the macro, just go in and edit it and it will essentially give you the code. It will require a little translation on your part, but here is what the macro looks like when I edit it:

 Selection.Style = "Bad"

As you can see, it's pretty easy to make the jump to AHK from what excel provides.

Call a python function from jinja2

from jinja2 import Template

def custom_function(a):
    return a.replace('o', 'ay')

template = Template('Hey, my name is {{ custom_function(first_name) }} {{ func2(last_name) }}')
template.globals['custom_function'] = custom_function

You can also give the function in the fields as per Matroskin's answer

fields = {'first_name': 'Jo', 'last_name': 'Ko', 'func2': custom_function}
print template.render(**fields)

Will output:

Hey, my name is Jay Kay

Works with Jinja2 version 2.7.3

And if you want a decorator to ease defining functions on template.globals check out Bruno Bronosky's answer

How to remove jar file from local maven repository which was added with install:install-file?

Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/ directory if you are using a linux OS.

How to unpublish an app in Google Play Developer Console

  1. Go to your "play.google.com" dashboard
  2. Select your app
  3. In left menu item select "Store presence"
  4. Then, select "Pricing & distribution"
  5. Click "Unpublish" in "App Availability" section

Copying text outside of Vim with set mouse=a enabled

You can use :set mouse& in the vim command line to enable copy/paste of text selected using the mouse. You can then simply use the middle mouse button or shiftinsert to paste it.

C# Copy a file to another location with a different name

System.IO.File.Copy(oldPathAndName, newPathAndName);

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Where does the iPhone Simulator store its data?

iOS 8 ~/Library/Developer/CoreSimulator/Devices/[Device ID]/data/Applications/[appGUID]/Documents/

What is the most compatible way to install python modules on a Mac?

For MacPython installations, I found an effective solution to fixing the problem with setuptools (easy_install) in this blog post:

http://droidism.com/getting-running-with-django-and-macpython-26-on-leopard

One handy tip includes finding out which version of python is active in the terminal:

which python

Simple insecure two-way data "obfuscation"?

Using the builtin .Net Cryptography library, this example shows how to use the Advanced Encryption Standard (AES).

using System;
using System.IO;
using System.Security.Cryptography;

namespace Aes_Example
{
    class AesExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the Aes
                // class.  This generates a new key and initialization 
                // vector (IV).
                using (Aes myAes = Aes.Create())
                {

                    // Encrypt the string to an array of bytes.
                    byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);

                    // Decrypt the bytes to a string.
                    string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key,byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("Key");
            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream.
            return encrypted;

        }

        static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("Key");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }
    }
}

Easiest way to open a download window without navigating away from the page

Using HTML5 Blob Object-URL File API:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
 * @param fileName String
 * @param fileContents String JSON String
 * @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
    if(typeof(Blob)!='undefined') { // using Blob
        var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        if (window.webkitURL != null) {
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
        else {
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = document.body.removeChild(event.target);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    } else {
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.onclick = document.body.removeChild(event.target);
        pp.click();
    }
}//saveBlobAsFile

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file_x000D_
 * @param fileName String_x000D_
 * @param fileContents String JSON String_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
var saveBlobAsFile = function(fileName, fileContents) {_x000D_
  if (typeof(Blob) != 'undefined') { // using Blob_x000D_
    var textFileAsBlob = new Blob([fileContents], {_x000D_
      type: 'text/plain'_x000D_
    });_x000D_
    var downloadLink = document.createElement("a");_x000D_
    downloadLink.download = fileName;_x000D_
    if (window.webkitURL != null) {_x000D_
      downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
    } else {_x000D_
      downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
      downloadLink.onclick = document.body.removeChild(event.target);_x000D_
      downloadLink.style.display = "none";_x000D_
      document.body.appendChild(downloadLink);_x000D_
    }_x000D_
    downloadLink.click();_x000D_
  } else {_x000D_
    var pp = document.createElement('a');_x000D_
    pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));_x000D_
    pp.setAttribute('download', fileName);_x000D_
    pp.onclick = document.body.removeChild(event.target);_x000D_
    pp.click();_x000D_
  }_x000D_
} //saveBlobAsFile_x000D_
_x000D_
var jsonObject = {_x000D_
  "name": "John",_x000D_
  "age": 31,_x000D_
  "city": "New York"_x000D_
};_x000D_
var fileContents = JSON.stringify(jsonObject, null, 2);_x000D_
var fileName = "data.json";_x000D_
_x000D_
saveBlobAsFile(fileName, fileContents)
_x000D_
_x000D_
_x000D_

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

What is a plain English explanation of "Big O" notation?

EDIT: Quick note, this is almost certainly confusing Big O notation (which is an upper bound) with Theta notation (which is both an upper and lower bound). In my experience this is actually typical of discussions in non-academic settings. Apologies for any confusion caused.

In one sentence: As the size of your job goes up, how much longer does it take to complete it?

Obviously that's only using "size" as the input and "time taken" as the output — the same idea applies if you want to talk about memory usage etc.

Here's an example where we have N T-shirts which we want to dry. We'll assume it's incredibly quick to get them in the drying position (i.e. the human interaction is negligible). That's not the case in real life, of course...

  • Using a washing line outside: assuming you have an infinitely large back yard, washing dries in O(1) time. However much you have of it, it'll get the same sun and fresh air, so the size doesn't affect the drying time.

  • Using a tumble dryer: you put 10 shirts in each load, and then they're done an hour later. (Ignore the actual numbers here — they're irrelevant.) So drying 50 shirts takes about 5 times as long as drying 10 shirts.

  • Putting everything in an airing cupboard: If we put everything in one big pile and just let general warmth do it, it will take a long time for the middle shirts to get dry. I wouldn't like to guess at the detail, but I suspect this is at least O(N^2) — as you increase the wash load, the drying time increases faster.

One important aspect of "big O" notation is that it doesn't say which algorithm will be faster for a given size. Take a hashtable (string key, integer value) vs an array of pairs (string, integer). Is it faster to find a key in the hashtable or an element in the array, based on a string? (i.e. for the array, "find the first element where the string part matches the given key.") Hashtables are generally amortised (~= "on average") O(1) — once they're set up, it should take about the same time to find an entry in a 100 entry table as in a 1,000,000 entry table. Finding an element in an array (based on content rather than index) is linear, i.e. O(N) — on average, you're going to have to look at half the entries.

Does this make a hashtable faster than an array for lookups? Not necessarily. If you've got a very small collection of entries, an array may well be faster — you may be able to check all the strings in the time that it takes to just calculate the hashcode of the one you're looking at. As the data set grows larger, however, the hashtable will eventually beat the array.

How do you compare structs for equality in C?

@Greg is correct that one must write explicit comparison functions in the general case.

It is possible to use memcmp if:

  • the structs contain no floating-point fields that are possibly NaN.
  • the structs contain no padding (use -Wpadded with clang to check this) OR the structs are explicitly initialized with memset at initialization.
  • there are no member types (such as Windows BOOL) that have distinct but equivalent values.

Unless you are programming for embedded systems (or writing a library that might be used on them), I would not worry about some of the corner cases in the C standard. The near vs. far pointer distinction does not exist on any 32- or 64- bit device. No non-embedded system that I know of has multiple NULL pointers.

Another option is to auto-generate the equality functions. If you lay your struct definitions out in a simple way, it is possible to use simple text processing to handle simple struct definitions. You can use libclang for the general case – since it uses the same frontend as Clang, it handles all corner cases correctly (barring bugs).

I have not seen such a code generation library. However, it appears relatively simple.

However, it is also the case that such generated equality functions would often do the wrong thing at application level. For example, should two UNICODE_STRING structs in Windows be compared shallowly or deeply?

SQL Server : Columns to Rows

You can use the UNPIVOT function to convert the columns into rows:

select id, entityId,
  indicatorname,
  indicatorvalue
from yourtable
unpivot
(
  indicatorvalue
  for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;

Note, the datatypes of the columns you are unpivoting must be the same so you might have to convert the datatypes prior to applying the unpivot.

You could also use CROSS APPLY with UNION ALL to convert the columns:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  select 'Indicator1', Indicator1 union all
  select 'Indicator2', Indicator2 union all
  select 'Indicator3', Indicator3 union all
  select 'Indicator4', Indicator4 
) c (indicatorname, indicatorvalue);

Depending on your version of SQL Server you could even use CROSS APPLY with the VALUES clause:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  values
  ('Indicator1', Indicator1),
  ('Indicator2', Indicator2),
  ('Indicator3', Indicator3),
  ('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);

Finally, if you have 150 columns to unpivot and you don't want to hard-code the entire query, then you could generate the sql statement using dynamic SQL:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot 
  = stuff((select ','+quotename(C.column_name)
           from information_schema.columns as C
           where C.table_name = 'yourtable' and
                 C.column_name like 'Indicator%'
           for xml path('')), 1, 1, '')

set @query 
  = 'select id, entityId,
        indicatorname,
        indicatorvalue
     from yourtable
     unpivot
     (
        indicatorvalue
        for indicatorname in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

How to explain callbacks in plain english? How are they different from calling one function from another function?

Always better to start with an example :).

Let's assume you have two modules A and B.

You want module A to be notified when some event/condition occurs in module B. However, module B has no idea about your module A. All it knows is an address to a particular function (of module A) through a function pointer that is provided to it by module A.

So all B has to do now, is "callback" into module A when a particular event/condition occurs by using the function pointer. A can do further processing inside the callback function.

*) A clear advantage here is that you are abstracting out everything about module A from module B. Module B does not have to care who/what module A is.

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

Using lambda expressions for event handlers

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
button.Click -= handler;

Running Bash commands in Python

subprocess.Popen() is prefered over os.system() as it offers more control and visibility. However, If you find subprocess.Popen() too verbose or complex, peasyshell is a small wrapper I wrote above it, which makes it easy to interact with bash from Python.

https://github.com/davidohana/peasyshell

Does java have a int.tryparse that doesn't throw an exception for bad data?

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

One difference is that:

  • :map does nvo == normal + (visual + select) + operator pending
  • :map! does ic == insert + command-line mode

as stated on help map-modes tables.

So: map does not map to all modes.

To map to all modes you need both :map and :map!.

Remove non-numeric characters (except periods and commas) from a string

I'm surprised there's been no mention of filter_var here for this being such an old question...

PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND flags. Like so:

$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"

It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).

How to round the double value to 2 decimal points?

I guess that you need a formatted output.

System.out.printf("%.2f",d);

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

How to replace a hash key with another key

Previous answers are good enough, but they might update original data. In case if you don't want the original data to be affected, you can try my code.

 newhash=hash.reject{|k| k=='_id'}.merge({id:hash['_id']})

First it will ignore the key '_id' then merge with the updated one.

No tests found with test runner 'JUnit 4'

Very late but what solved the problem for me was that my test method names all started with captial letters: "public void Test". Making the t lower case worked.

Microsoft SQL Server 2005 service fails to start

I agree with Greg that the log is the best place to start. We've experienced something similar and the fix was to ensure that admins have full permissions to the registry location HKLM\System\CurrentControlSet\Control\WMI\Security prior to starting the installation. HTH.

Checking for a null int value from a Java ResultSet

Another solution:

public class DaoTools {
    static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {
        int nValue = rs.getInt(strColName);
        return rs.wasNull() ? null : nValue;
    }
}

VBA: How to delete filtered rows in Excel?

As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.

ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)

As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().

SQL Inner Join On Null Values

Basically you want to join two tables together where their QID columns are both not null, correct? However, you aren't enforcing any other conditions, such as that the two QID values (which seems strange to me, but ok). Something as simple as the following (tested in MySQL) seems to do what you want:

SELECT * FROM `Y` INNER JOIN `X` ON (`Y`.`QID` IS NOT NULL AND `X`.`QID` IS NOT NULL);

This gives you every non-null row in Y joined to every non-null row in X.

Update: Rico says he also wants the rows with NULL values, why not just:

SELECT * FROM `Y` INNER JOIN `X`;

how can get index & count in vuejs

In case, your data is in the following structure, you get string as an index

items = {
   am:"Amharic",
   ar:"Arabic",
   az:"Azerbaijani",
   ba:"Bashkir",
   be:"Belarusian"
}

In this case, you can use extra variable to get the index in number:

<ul>
  <li v-for="(item, key, index) in items">
    {{ item }} - {{ key }} - {{ index }}
  </li>
</ul>

Source: https://alligator.io/vuejs/iterating-v-for/

Tar error: Unexpected EOF in archive

May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.

$ gunzip myarchive.tar.gz

And then untar the resulting tar file using

$ tar xvf myarchive.tar

Hope this helps.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How do I activate C++ 11 in CMake?

This is another way of enabling C++11 support,

ADD_DEFINITIONS(
    -std=c++11 # Or -std=c++0x
    # Other flags
)

I have encountered instances where only this method works and other methods fail. Maybe it has something to do with the latest version of CMake.

How can I check whether a radio button is selected with JavaScript?

You can use this simple script. You may have multiple radio buttons with same names and different values.

var checked_gender = document.querySelector('input[name = "gender"]:checked');

if(checked_gender != null){  //Test if something was checked
alert(checked_gender.value); //Alert the value of the checked.
} else {
alert('Nothing checked'); //Alert, nothing was checked.
}

Unable to allocate array with shape and data type

I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.

With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.

You can check which version you have by entering the interpreter. I, with a 64-bit version, now have: Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)], where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".

Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.

Sources :

Django - taking values from POST request

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))

Ways to iterate over a list in Java

In Java 8 we have multiple ways to iterate over collection classes.

Using Iterable forEach

The collections that implement Iterable (for example all lists) now have forEach method. We can use method-reference introduced in Java 8.

Arrays.asList(1,2,3,4).forEach(System.out::println);

Using Streams forEach and forEachOrdered

We can also iterate over a list using Stream as:

Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
Arrays.asList(1,2,3,4).stream().forEachOrdered(System.out::println);

We should prefer forEachOrdered over forEach because the behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept.

The advantage with streams is that we can also make use of parallel streams wherever appropriate. If the objective is only to print the items irrespective of the order then we can use parallel stream as:

Arrays.asList(1,2,3,4).parallelStream().forEach(System.out::println);

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

How to get the text node of an element?

var text = $(".title").contents().filter(function() {
  return this.nodeType == Node.TEXT_NODE;
}).text();

This gets the contents of the selected element, and applies a filter function to it. The filter function returns only text nodes (i.e. those nodes with nodeType == Node.TEXT_NODE).

pandas groupby sort within groups

Try this Instead

simple way to do 'groupby' and sorting in descending order

df.groupby(['companyName'])['overallRating'].sum().sort_values(ascending=False).head(20)

PHP foreach loop key value

foreach($shipmentarr as $index=>$val){    
    $additionalService = array();

    foreach($additionalService[$index] as $key => $value) {

        array_push($additionalService,$value);

    }
}

MySQL - SELECT all columns WHERE one column is DISTINCT

If what your asking is to only show rows that have 1 link for them then you can use the following:

SELECT * FROM posted WHERE link NOT IN 
(SELECT link FROM posted GROUP BY link HAVING COUNT(LINK) > 1)

Again this is assuming that you want to cut out anything that has a duplicate link.

SSL cert "err_cert_authority_invalid" on mobile chrome only

I had this same problem while hosting a web site via Parse and using a Comodo SSL cert resold by NameCheap.

You will receive two cert files inside of a zip folder: www_yourdomain_com.ca-bundle www_yourdomain_com.crt

You can only upload one file to Parse: Parse SSL Cert Input Box

In terminal combine the two files using:

cat www_yourdomain_com.crt www_yourdomain_com.ca-bundle > www_yourdomain_com_combine.crt

Then upload to Parse. This should fix the issue with Android Chrome and Firefox browsers. You can verify that it worked by testing it at https://www.sslchecker.com/sslchecker

Parsing JSON with Unix tools

If pip is avaiable on the system then:

$ pip install json-query

Examples of usage:

$ curl -s http://0/file.json | json-query
{
    "key":"value"    
}

$ curl -s http://0/file.json | json-query my.key
value

$ curl -s http://0/file.json | json-query my.keys.
key_1
key_2
key_3

$ curl -s http://0/file.json | json-query my.keys.2
value_2

Detecting Enter keypress on VB.NET

Use this code it will work OK. You shall click on TextBox1 and then go to event and select Keyup and double click on it. You wil then get the lines for the SUB.

Private Sub TextBox1_KeyUp(ByVal sender As System.Object, ByVal e As      
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
    If e.KeyCode = Keys.Enter Then
        MsgBox("Fel lösenord")

    End If
End Sub

Why do access tokens expire?

It is essentially a security measure. If your app is compromised, the attacker will only have access to the short-lived access token and no way to generate a new one.

Refresh tokens also expire but they are supposed to live much longer than the access token.

OSError [Errno 22] invalid argument when use open() in Python

Add 'r' in starting of path:

path = r"D:\Folder\file.txt"

That works for me.

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

Get the device width in javascript

check it

const mq = window.matchMedia( "(min-width: 500px)" );

if (mq.matches) {
  // window width is at least 500px
} else {
  // window width is less than 500px
}

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

How to change target build on Android project?

Right click the project and click "Properties". Then select "Android" from the tree on the left. You can then select the target version on the right.

(Note as per the popular comment below, make sure your properties, classpath and project files are writable otherwise it won't work)

Setting Camera Parameters in OpenCV/Python

I wasn't able to fix the problem OpenCV either, but a video4linux (V4L2) workaround does work with OpenCV when using Linux. At least, it does on my Raspberry Pi with Rasbian and my cheap webcam. This is not as solid, light and portable as you'd like it to be, but for some situations it might be very useful nevertheless.

Make sure you have the v4l2-ctl application installed, e.g. from the Debian v4l-utils package. Than run (before running the python application, or from within) the command:

v4l2-ctl -d /dev/video1 -c exposure_auto=1 -c exposure_auto_priority=0 -c exposure_absolute=10

It overwrites your camera shutter time to manual settings and changes the shutter time (in ms?) with the last parameter to (in this example) 10. The lower this value, the darker the image.

Find and replace words/lines in a file

public static void replaceFileString(String old, String new) throws IOException {
    String fileName = Settings.getValue("fileDirectory");
    FileInputStream fis = new FileInputStream(fileName);
    String content = IOUtils.toString(fis, Charset.defaultCharset());
    content = content.replaceAll(old, new);
    FileOutputStream fos = new FileOutputStream(fileName);
    IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
    fis.close();
    fos.close();
}

above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

WPF button click in C# code

You should place below line

btn.Click = btn.Click + btn1_Click;

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Your local port is using by another app. I faced the same problem! You can try the following step:

  1. Go to command line and run it as administrator!

  2. Type:

    netstat -ano | find ":5000"
    => TCP    0.0.0.0:5000           0.0.0.0:0              LISTENING       4032
       TCP    [::]:5000              [::]:0                 LISTENING       4032
    
  3. Type:

    TASKKILL /F /PID 4032
    

=> SUCCESS: The process with PID 4032 has been terminated.

Note: My 5000 local port was listing by PID 4032. You should give yours!

Check if inputs form are empty jQuery

var empty = true;
$('input[type="text"]').each(function() {
   if ($(this).val() != "") {
      empty = false;
      return false;
   }
});

This should look all the input and set the empty var to false, if at least one is not empty.

EDIT:

To match the OP edit request, this can be used to filter input based on name substring.

$('input[name*="denominationcomune_"]').each(...

How to execute mongo commands through shell scripts?

As suggested by theTuxRacer, you can use the eval command, for those who are missing it like I was, you can also add in your db name if you are not trying to preform operation on the default db.

mongo <dbname> --eval "printjson(db.something.find())"

One time page refresh after first page load

Use rel="external" like below is the example

<li><a href="index.html" rel="external" data-theme="c">Home</a></li>

Can I target all <H> tags with a single selector?

You can also use PostCSS and the custom selectors plugin

@custom-selector :--headings h1, h2, h3, h4, h5, h6;

article :--headings {
  margin-top: 0;
}

Output:

article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
  margin-top: 0;
}

How to find text in a column and saving the row number where it is first found - Excel VBA

I'm not really familiar with all those parameters of the Find method; but upon shortening it, the following is working for me:

With WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With

And if you solely need the row number, you can use this after:

Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row

onActivityResult is not being called in Fragment

If there is trouble with the method onActivityResult that is inside the fragment class, and you want to update something that's is also inside the fragment class, use:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(resultCode == Activity.RESULT_OK)
    {
        // If the user had agreed to enabling Bluetooth,
        // populate the ListView with all the paired devices.
        this.arrayDevice = new ArrayAdapter<String>(this.getContext(), R.layout.device_item);
        for(BluetoothDevice bd : this.btService.btAdapater.getBondedDevices())
        {
            this.arrayDevice.add(bd.getAddress());
            this.btDeviceList.setAdapter(this.arrayDevice);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

Just add the this.variable as shown in the code above. Otherwise the method will be called within the parent activity and the variable will not updated of the current instance.

I tested it also by putting this block of code into the MainActivity, replacing this with the HomeFragment class and having the variables static. I got results as I expected.

So if you want to have the fragment class having its own implementation of onActivityResult, the code example above is the answer.

Maven Install on Mac OS X

You can install maven using homebrew. The command is $ brew install maven

How to resize html canvas element?

Note that if your canvas is statically declared you should use the width and height attributes, not the style, eg. this will work:

<canvas id="c" height="100" width="100" style="border:1px"></canvas>
<script>
    document.getElementById('c').width = 200;
</script>

But this will not work:

<canvas id="c" style="width: 100px; height: 100px; border:1px"></canvas>
<script>
    document.getElementById('c').width = 200;
</script>

How to check if an integer is within a range?

Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:

Check if $n is between $a and $b even if:
    $a < $b  
    $a > $b
    $a = $b

All numbers can be real, not only integer.

There is an easy way to test.
I base the test it in the fact that ($n-$a) and ($n-$b) have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

Taking multiple inputs from user in python

Try this:

print ("Enter the Five Numbers with Comma")

k=[x for x in input("Enter Number:").split(',')]

for l in k:
    print (l)

C# switch on type

I have used this form of switch-case on rare occasion. Even then I have found another way to do what I wanted. If you find that this is the only way to accomplish what you need, I would recommend @Mark H's solution.

If this is intended to be a sort of factory creation decision process, there are better ways to do it. Otherwise, I really can't see why you want to use the switch on a type.

Here is a little example expanding on Mark's solution. I think it is a great way to work with types:

Dictionary<Type, Action> typeTests;

public ClassCtor()
{
    typeTests = new Dictionary<Type, Action> ();

    typeTests[typeof(int)] = () => DoIntegerStuff();
    typeTests[typeof(string)] = () => DoStringStuff();
    typeTests[typeof(bool)] = () => DoBooleanStuff();
}

private void DoBooleanStuff()
{
   //do stuff
}

private void DoStringStuff()
{
    //do stuff
}

private void DoIntegerStuff()
{
    //do stuff
}

public Action CheckTypeAction(Type TypeToTest)
{
    if (typeTests.Keys.Contains(TypeToTest))
        return typeTests[TypeToTest];

    return null; // or some other Action delegate
}

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

For those using Telerik as mentioned by Ovar, make sure you wrap your javascript in

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Since Telerik doesn't recognize <%# %> when looking for an element and <%= %> will give you an error if your javascript code isn't wrapped.

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

How can I do a line break (line continuation) in Python?

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)

What exactly is std::atomic?

I understand that std::atomic<> makes an object atomic.

That's a matter of perspective... you can't apply it to arbitrary objects and have their operations become atomic, but the provided specialisations for (most) integral types and pointers can be used.

a = a + 12;

std::atomic<> does not (use template expressions to) simplify this to a single atomic operation, instead the operator T() const volatile noexcept member does an atomic load() of a, then twelve is added, and operator=(T t) noexcept does a store(t).

powershell - extract file name and extension

Check the BaseName and Extension properties of the FileInfo object.

SQL Server Management Studio – tips for improving the TSQL coding process

Use a SELECT INTO query to quickly/easily make backup tables to work and experiment with.

Can I change the name of `nohup.out`?

nohup some_command &> nohup2.out &

and voila.


Older syntax for Bash version < 4:

nohup some_command > nohup2.out 2>&1 &

Multiple argument IF statement - T-SQL

Your code is valid (with one exception). It is required to have code between BEGIN and END.

Replace

--do some work

with

print ''

I think maybe you saw "END and not "AND"

Use images instead of radio buttons

$spinTime: 3;
html, body { height: 100%; }
* { user-select: none; }
body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-family: 'Raleway', sans-serif;
    font-size: 72px;
    input {
        display: none;
        + div > span {
            display: inline-block;
            position: relative;
            white-space: nowrap;
            color: rgba(#fff, 0);
            transition: all 0.5s ease-in-out;
            span {
                display: inline-block;
                position: absolute;
                left: 50%;
                text-align: center;
                color: rgba(#000, 1);
                transform: translateX(-50%);
                transform-origin: left;
                transition: all 0.5s ease-in-out;
                &:first-of-type {
                    transform: rotateY(0deg) translateX(-50%);
                }
                &:last-of-type {
                    transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
                }
            }
        }
        &#fat:checked ~ div > span span {
            &:first-of-type {
                transform: rotateY(0deg) translateX(-50%);
            }
            &:last-of-type {
                transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
            }
        }
        &#fit:checked ~ div > span {
            margin: 0 -10px;
            span {
                &:first-of-type {
                    transform: rotateY(90deg) translateX(-50%);
                }
                &:last-of-type {
                    transform: rotateY(0deg) translateX(-50%) scaleX(1) skew(0deg,0deg);
                }
            }
        }
        + div + div {
            width: 280px;
            margin-top: 10px;
            label {
                display: block;
                padding: 20px 10px;
                text-align: center;
                transition: all 0.15s ease-in-out;
                background: #fff;
                border-radius: 10px;
                box-sizing: border-box;
                width: 48%;
                font-size: 64px;
                cursor: pointer;
                &:first-child {
                    float: left;
                    box-shadow:
                        inset 0 0 0 4px #1597ff,
                        0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
                }
                &:last-child { float: right; }
            }
        }
        &#fat:checked ~ div + div label {
            &:first-child {
                box-shadow:
                    inset 0 0 0 4px #1597ff,
                    0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
            }
            &:last-child {
                box-shadow:
                    inset 0 0 0 0px #1597ff,
                    0 10px 15px -20px rgba(#1597ff, 0);
            }
        }
        &#fit:checked ~ div + div label {
            &:first-child {
                box-shadow:
                    inset 0 0 0 0px #1597ff,
                    0 10px 15px -20px rgba(#1597ff, 0);
            }
            &:last-child {
                box-shadow:
                    inset 0 0 0 4px #1597ff,
                    0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
            }
        }
    }
}


<input type="radio" id="fat" name="fatfit">
<input type="radio" id="fit" name="fatfit">
<div>
    GET F<span>A<span>A</span><span>I</span></span>T
</div>
<div>
    <label for="fat"></label>
    <label for="fit"></label>
</div>

get DATEDIFF excluding weekends using sql server

declare @d1 datetime, @d2 datetime
select @d1 = '4/19/2017',  @d2 = '5/7/2017'

DECLARE @Counter int = datediff(DAY,@d1 ,@d2 )

DECLARE @C int = 0
DECLARE @SUM int = 0





 WHILE  @Counter > 0
  begin
 SET @SUM = @SUM + IIF(DATENAME(dw, 

 DATEADD(day,@c,@d1))IN('Sunday','Monday','Tuesday','Wednesday','Thursday')
 ,1,0)



SET @Counter = @Counter - 1
set @c = @c +1
end

select @Sum

What is the difference between a HashMap and a TreeMap?

Use HashMap most of the times but use TreeMap when you need the key to be sorted (when you need to iterate the keys).

Using ChildActionOnly in MVC

FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here

Spring boot Security Disable security

What also seems to work fine is creating a file application-dev.properties that contains:

security.basic.enabled=false
management.security.enabled=false

If you then start your Spring Boot app with the dev profile, you don't need to log on.

Selecting only numeric columns from a data frame

This an alternate code to other answers:

x[, sapply(x, class) == "numeric"]

with a data.table

x[, lapply(x, is.numeric) == TRUE, with = FALSE]

Programmatically navigate using React router

EDIT: React Router v6

I haven't touched React in a while, but want to thank and highlight the comment below by @Shimrit Snapir

on React-Router 6.0 <Redirect /> changed to <Navigate />

React Router V4

tl:dr;

if (navigate) {
  return <Redirect to="/" push={true} />
}

The simple and declarative answer is that you need to use <Redirect to={URL} push={boolean} /> in combination with setState()

push: boolean - when true, redirecting will push a new entry onto the history instead of replacing the current one.


import { Redirect } from 'react-router'

class FooBar extends React.Component {
  state = {
    navigate: false
  }

  render() {
    const { navigate } = this.state
    
    // here is the important part
    if (navigate) {
      return <Redirect to="/" push={true} />
    }
   // ^^^^^^^^^^^^^^^^^^^^^^^
    
    return (
      <div>
        <button onClick={() => this.setState({ navigate: true })}>
          Home
        </button>
      </div>
    )
  }
}

Full example here. Read more here.

PS. The example uses ES7+ Property Initializers to initialise state. Look here as well, if you're interested.

Error "can't load package: package my_prog: found packages my_prog and main"

Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.

How to display JavaScript variables in a HTML page without document.write

hi here is a simple example: <div id="test">content</div> and

var test = 5;
document.getElementById('test').innerHTML = test;

and you can test it here : http://jsfiddle.net/SLbKX/

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

I was struggling, but the below worked for me finally!

Dim WB As Workbook

Set WB = Workbooks.Open("\\users\path\Desktop\test.xlsx")

WB.SaveAs fileName:="\\users\path\Desktop\test.xls", _
        FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
        ReadOnlyRecommended:=False, CreateBackup:=False

In C, how should I read a text file and print all strings

Instead just directly print the characters onto the console because the text file maybe very large and you may require a lot of memory.

#include <stdio.h>
#include <stdlib.h>

int main() {

    FILE *f;
    char c;
    f=fopen("test.txt","rt");

    while((c=fgetc(f))!=EOF){
        printf("%c",c);
    }

    fclose(f);
    return 0;
}

How to Empty Caches and Clean All Targets Xcode 4 and later

I had some problems with Xcode 5.1 crashing on me, when I opened the doc window.

I am not sure of the cause of it, because I was also updating docsets, while I opened the window.

Well, in Xcode 5 the modules directory now resides within the derived data folder, which I for obvious reasons didn't delete. I deleted the contents of ~/Library/Developer/Xcode/DerivedData/ModuleCache and the ~/Library/Preferences/com.apple.Xcode.plist and everything then seems to work, after I restarted Xcode.

How to get RegistrationID using GCM in android

Use this code to get Registration ID using GCM

String regId = "", msg = "";

public void getRegisterationID() {

    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {

            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(Login.this);
                }
                regId = gcm.register(YOUR_SENDER_ID);
                Log.d("in async task", regId);

                // try
                msg = "Device registered, registration ID=" + regId;

            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }
    }.execute(null, null, null);
 }

and don't forget to write permissions in manifest...
I hope it helps!

How to make child divs always fit inside parent div?

There are two techniques commonly used for this:

  1. Absolute Positioning
  2. Table Styles

Given the HTML you provided here is the solution using Absolute positioning:

_x000D_
_x000D_
body #one {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  width: auto;_x000D_
  height: auto;_x000D_
}_x000D_
body #two {_x000D_
  width: auto;  _x000D_
}_x000D_
body #three {_x000D_
  position: absolute;_x000D_
  top: 60px;_x000D_
  bottom: 0;_x000D_
  height: auto;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
html, body {width:100%;height:100%;margin:0;padding:0;}_x000D_
.border {border:1px solid black;}_x000D_
.margin { margin:5px;}_x000D_
#one {width:100%;height:100%;}_x000D_
#two {width:100%;height:50px;}_x000D_
#three {width:100px;height:100%;}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
 <div id="one" class="border">_x000D_
  <div id="two" class="border margin"></div>_x000D_
  <div id="three" class="border margin"></div>_x000D_
 </div>_x000D_
</body
_x000D_
_x000D_
_x000D_

You can always just use the table, tr, and td elements directly despite common criticisms as it will get the job done. If you prefer to use CSS there is no equivalent for colspan so you will likely end up with nested tables. Here is an example:

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
#one {_x000D_
  box-sizing: border-box;_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#two {_x000D_
    box-sizing: border-box;_x000D_
    display: table;_x000D_
    height: 50px;_x000D_
    padding: 5px;_x000D_
    width: 100%;_x000D_
}_x000D_
#three {_x000D_
  box-sizing: border-box;_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  padding-bottom: 60px;_x000D_
  padding-left: 5px;_x000D_
  _x000D_
}_x000D_
#four {_x000D_
  display: table-cell;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#five {_x000D_
  display: table-cell;_x000D_
  width: 100px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#six {_x000D_
  display: table-cell;  _x000D_
}
_x000D_
<html>_x000D_
 <div id="one">_x000D_
     <div id="two">_x000D_
            <div id="four"></div>_x000D_
        </div>_x000D_
        <div id="three">_x000D_
            <div id="five"></div>_x000D_
            <div id="six"></div>_x000D_
        </div>_x000D_
 </div>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How do I group Windows Form radio buttons?

If you cannot put them into one container, then you have to write code to change checked state of each RadioButton:

private void rbDataSourceFile_CheckedChanged(object sender, EventArgs e)
{
    rbDataSourceNet.Checked = !rbDataSourceFile.Checked;
}

private void rbDataSourceNet_CheckedChanged(object sender, EventArgs e)
{
  rbDataSourceFile.Checked = !rbDataSourceNet.Checked;
}

jQuery.each - Getting li elements inside an ul

First I think you need to fix your lists, as the first node of a <ul> must be a <li> (stackoverflow ref). Once that is setup you can do this:

// note this array has outer scope
var phrases = [];

$('.phrase').each(function(){
        // this is inner scope, in reference to the .phrase element
        var phrase = '';
        $(this).find('li').each(function(){
            // cache jquery var
            var current = $(this);
            // check if our current li has children (sub elements)
            // if it does, skip it
            // ps, you can work with this by seeing if the first child
            // is a UL with blank inside and odd your custom BLANK text
            if(current.children().size() > 0) {return true;}
            // add current text to our current phrase
            phrase += current.text();
        });
        // now that our current phrase is completely build we add it to our outer array
        phrases.push(phrase);
    });
    // note the comma in the alert shows separate phrases
    alert(phrases);

Working jsfiddle.

One thing is if you get the .text() of an upper level li you will get all sub level text with it.

Keeping an array will allow for many multiple phrases to be extracted.


EDIT:

This should work better with an empty UL with no LI:

// outer scope
var phrases = [];

$('.phrase').each(function(){
    // inner scope
    var phrase = '';
    $(this).find('li').each(function(){
        // cache jquery object
        var current = $(this);
        // check for sub levels
        if(current.children().size() > 0) {
            // check is sublevel is just empty UL
            var emptyULtest = current.children().eq(0); 
            if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
                phrase += ' -BLANK- '; //custom blank text
                return true;   
            } else {
             // else it is an actual sublevel with li's
             return true;   
            }
        }
        // if it gets to here it is actual li
        phrase += current.text();
    });
    phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);

How can I run a PHP script inside a HTML file?

You need to make the extension as .php to run a php code BUT if you can't change the extension you could use Ajax to run the php externally and get the result

For eg:

<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $.ajax({
        url:'php_File_with_php_code.php',
        type:'GET', 
        data:"parameter=some_parameter",
       success:function(data)
       {
              $("#thisdiv").html(data);
           }
    });
});
</script>
</head>
<body>
<div id="thisdiv"></div>
</body>
</html>

Here, the JQuery is loaded and as soon as the pages load, the ajax call a php file from where the data is taken, the data is then put in the div

Hope This Helps

Split string into array

...and also for those who like literature in CS.

array = Array.from(entry);

Correct way to populate an Array with a Range in Ruby

Check this:

a = [*(1..10), :top, *10.downto( 1 )]

How to display and hide a div with CSS?

To hide an element, use:

display: none;
visibility: hidden;

To show an element, use:

display: block;
visibility: visible;

The difference is:

Visibility handles the visibility of the tag, the display handles space it occupies on the page.

If you set the visibility and do not change the display, even if the tags are not seen, it still occupies space.

javac not working in windows command prompt

Give it as "C:\Program Files\Java\jdk1.6.0_16\bin". Remove the backslash it will work

How to update Android Studio automatically?

There's not always an updater between versions, depending on the version you're starting from and what you're updating to. If that happens, download the full installer and reinstall Android Studio.

Split files using tar, gz, zip, or bzip2

Tested code, initially creates a single archive file, then splits it:

 gzip -c file.orig > file.gz
 CHUNKSIZE=1073741824
 PARTCNT=$[$(stat -c%s file.gz) / $CHUNKSIZE]

 # the remainder is taken care of, for example for
 # 1 GiB + 1 bytes PARTCNT is 1 and seq 0 $PARTCNT covers
 # all of file
 for n in `seq 0 $PARTCNT`
 do
       dd if=file.gz of=part.$n bs=$CHUNKSIZE skip=$n count=1
 done

This variant omits creating a single archive file and goes straight to creating parts:

gzip -c file.orig |
    ( CHUNKSIZE=1073741824;
        i=0;
        while true; do
            i=$[i+1];
            head -c "$CHUNKSIZE" > "part.$i";
            [ "$CHUNKSIZE" -eq $(stat -c%s "part.$i") ] || break;
        done; )

In this variant, if the archive's file size is divisible by $CHUNKSIZE, then the last partial file will have file size 0 bytes.

Command failed due to signal: Segmentation fault: 11

I got segmentation fault on my Mac Mini using Xcode Bots. The seg fault did only occur during build step of testing and not during building or running locally. Only in Xcode bots during build step of testing.

I am using macOS Sierra and Xcode 8, with the code converted to Swift 2.3.

I finally found the line causing the seg fault, it was caused by:

public let isIpad = UIDevice.currentDevice().userInterfaceIdiom == .Pad

Which was declared outside a class as a constant. Changing it to check the userInterfaceIdiom at runtime fixed the issue.

Hopes this helps someone else!

This is the error log for my seg fault:

0  swift                    0x000000010f93d76b llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 43
1  swift                    0x000000010f93ca56 llvm::sys::RunSignalHandlers() + 70
2  swift                    0x000000010f93ddbf SignalHandler(int) + 287
3  libsystem_platform.dylib 0x00007fffb24aabba _sigtramp + 26
4  libsystem_platform.dylib 0x00007fbbfff49ae0 _sigtramp + 1302982464
5  swift                    0x000000010db79996 (anonymous namespace)::Traversal::visit(swift::Expr*) + 118
6  swift                    0x000000010db7b880 (anonymous namespace)::Traversal::visitApplyExpr(swift::ApplyExpr*) + 128
7  swift                    0x000000010db799eb (anonymous namespace)::Traversal::visit(swift::Expr*) + 203
8  swift                    0x000000010db78f45 swift::Expr::walk(swift::ASTWalker&) + 53
9  swift                    0x000000010d6d2c87 walkForProfiling(swift::AbstractFunctionDecl*, swift::ASTWalker&) + 231
10 swift                    0x000000010d6d2719 swift::Lowering::SILGenProfiling::assignRegionCounters(swift::AbstractFunctionDecl*) + 553
11 swift                    0x000000010d6de348 (anonymous namespace)::SILGenType::emitType() + 952
12 swift                    0x000000010d6ddf1e swift::Lowering::SILGenModule::visitNominalTypeDecl(swift::NominalTypeDecl*) + 30
13 swift                    0x000000010d6625eb swift::Lowering::SILGenModule::emitSourceFile(swift::SourceFile*, unsigned int) + 731
14 swift                    0x000000010d663139 swift::SILModule::constructSIL(swift::ModuleDecl*, swift::SILOptions&, swift::FileUnit*, llvm::Optional<unsigned int>, bool, bool) + 793
15 swift                    0x000000010d6635a3 swift::performSILGeneration(swift::FileUnit&, swift::SILOptions&, llvm::Optional<unsigned int>, bool) + 115
16 swift                    0x000000010d491c18 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&) + 12536
17 swift                    0x000000010d48dc79 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 2777
18 swift                    0x000000010d489765 main + 1957
19 libdyld.dylib            0x00007fffb229e255 start + 1

Benefits of using the conditional ?: (ternary) operator

I find it particularly helpful when doing web development if I want to set a variable to a value sent in the request if it is defined or to some default value if it is not.

Set attribute without value

Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:

document.querySelector('#selector').toggleAttribute('data-something');

This will add the attribute in all lowercase without a value or remove it if it already exists on the element.

https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute

Get selected text from a drop-down list (select box) using jQuery

Use this

const select = document.getElementById("yourSelectId");

const selectedIndex = select.selectedIndex;
const selectedValue = select.value;
const selectedText = select.options[selectedIndex].text;   

Then you get your selected value and text inside selectedValue and selectedText.

How to embed images in html email

I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.

Regarding displaying embedded (inline) images, here's what's on their documentation:

Inline Attachments

There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with <img src="cid:my-photo" alt="my-photo" />.

In detail, here is the function to add an inline attachment:

$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

To give you a more complete example of how it would work:

<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on     errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->Port       = 25;                    // set the SMTP port
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->Subject = 'PHPMailer Test';

  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';

  $mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
  $mail->Send();
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

Edit:

Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.

One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.

For example:

You can replace the line that send the email:

$mail->Send();

With this:

$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want

Hope that helps. Let me know if you run into trouble using it.

Finding all cycles in a directed graph

The simplest choice I found to solve this problem was using the python lib called networkx.

It implements the Johnson's algorithm mentioned in the best answer of this question but it makes quite simple to execute.

In short you need the following:

import networkx as nx
import matplotlib.pyplot as plt

# Create Directed Graph
G=nx.DiGraph()

# Add a list of nodes:
G.add_nodes_from(["a","b","c","d","e"])

# Add a list of edges:
G.add_edges_from([("a","b"),("b","c"), ("c","a"), ("b","d"), ("d","e"), ("e","a")])

#Return a list of cycles described as a list o nodes
list(nx.simple_cycles(G))

Answer: [['a', 'b', 'd', 'e'], ['a', 'b', 'c']]

enter image description here

What's the difference between an Angular component and module

enter image description here

Simplest Explanation:

Module is like a big container containing one or many small containers called Component, Service, Pipe

A Component contains :

  • HTML template or HTML code

  • Code(TypeScript)

  • Service: It is a reusable code that is shared by the Components so that rewriting of code is not required

  • Pipe: It takes in data as input and transforms it to the desired output

Reference: https://scrimba.com/

Insert HTML from CSS

No. The only you can do is to add content (and not an element) using :before or :after pseudo-element.

More information: http://www.w3.org/TR/CSS2/generate.html#before-after-content

jQuery UI Dialog with ASP.NET button postback

I just added the following line after you created the dialog:

$(".ui-dialog").prependTo("form");

jQuery set checkbox checked

Dude try below code :

$("div.row-form input[type='checkbox']").attr('checked','checked')

OR

$("div.row-form #estado_cat").attr("checked","checked");

OR

$("div.row-form #estado_cat").attr("checked",true);

Get all files and directories in specific path fast

This method is much faster. You can only tel when placing a lot of files in a directory. My A:\ external hard drive contains almost 1 terabit so it makes a big difference when dealing with a lot of files.

static void Main(string[] args)
{
    DirectoryInfo di = new DirectoryInfo("A:\\");
    FullDirList(di, "*");
    Console.WriteLine("Done");
    Console.Read();
}

static List<FileInfo> files = new List<FileInfo>();  // List that will hold the files and subfiles in path
static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
static void FullDirList(DirectoryInfo dir, string searchPattern)
{
    // Console.WriteLine("Directory {0}", dir.FullName);
    // list the files
    try
    {
        foreach (FileInfo f in dir.GetFiles(searchPattern))
        {
            //Console.WriteLine("File {0}", f.FullName);
            files.Add(f);                    
        }
    }
    catch
    {
        Console.WriteLine("Directory {0}  \n could not be accessed!!!!", dir.FullName);                
        return;  // We alredy got an error trying to access dir so dont try to access it again
    }

    // process each directory
    // If I have been able to see the files in the directory I should also be able 
    // to look at its directories so I dont think I should place this in a try catch block
    foreach (DirectoryInfo d in dir.GetDirectories())
    {
        folders.Add(d);
        FullDirList(d, searchPattern);                    
    }

}

By the way I got this thanks to your comment Jim Mischel

read word by word from file in C++

As others have said, you are likely reading past the end of the file as you're only checking for x != ' '. Instead you also have to check for EOF in the inner loop (but in this case don't use a char, but a sufficiently large type):

while ( ! file.eof() )
{
    std::ifstream::int_type x = file.get();

    while ( x != ' ' && x != std::ifstream::traits_type::eof() )
    {
        word += static_cast<char>(x);
        x = file.get();
    }
    std::cout << word << '\n';
    word.clear();
}

But then again, you can just employ the stream's streaming operators, which already separate at whitespace (and better account for multiple spaces and other kinds of whitepsace):

void readFile(  )
{
    std::ifstream file("program.txt");
    for(std::string word; file >> word; )
        std::cout << word << '\n';
}

And even further, you can employ a standard algorithm to get rid of the manual loop altogether:

#include <algorithm>
#include <iterator>

void readFile(  )
{
    std::ifstream file("program.txt");
    std::copy(std::istream_iterator<std::string>(file), 
              std::istream_itetator<std::string>(), 
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

Can Python test the membership of multiple values in a list?

Another way to do it:

>>> set(['a','b']).issubset( ['b','a','foo','bar'] )
True

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

List of Timezone IDs for use with FindTimeZoneById() in C#?

This is the code fully tested and working for me. You can use it just copy and paste in your aspx page and cs page.

This is my blog you can download full code here. thanks.

http://www.c-sharpcorner.com/blogs/display-all-the-timezone-information-in-dropdown-list-of-a-local-system-using-c-sharp-with-asp-net

_x000D_
_x000D_
<form id="form1" runat="server">_x000D_
    <div style="font-size: 30px; padding: 25px; text-align: center;">_x000D_
        Get Current Date And Time Of All TimeZones_x000D_
    </div>_x000D_
    <hr />_x000D_
    <div style="font-size: 18px; padding: 25px; text-align: center;">_x000D_
        <div class="clsLeft">_x000D_
            Select TimeZone :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:DropDownList ID="ddlTimeZone" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlTimeZone_SelectedIndexChanged"_x000D_
                Font-Size="18px">_x000D_
            </asp:DropDownList>_x000D_
        </div>_x000D_
        <div class="clearspace">_x000D_
        </div>_x000D_
        <div class="clsLeft">_x000D_
            Selected TimeZone :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:Label ID="lblTimeZone" runat="server" Text="" />_x000D_
        </div>_x000D_
        <div class="clearspace">_x000D_
        </div>_x000D_
        <div class="clsLeft">_x000D_
            Current Date And Time :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:Label ID="lblCurrentDateTime" runat="server" Text="" />_x000D_
        </div>_x000D_
    </div>_x000D_
    <p>_x000D_
        &nbsp;</p>_x000D_
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTimeZone();
            GetSelectedTimeZone();
        }
    }

    protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetSelectedTimeZone();
    }

    /// <summary>
    /// Get all timezone from local system and bind it in dropdownlist
    /// </summary>
    private void BindTimeZone()
    {
        foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
        {
            ddlTimeZone.Items.Add(new ListItem(z.DisplayName, z.Id));
        }
    }

    /// <summary>
    /// Get selected timezone and current date & time
    /// </summary>
    private void GetSelectedTimeZone()
    {
        DateTimeOffset newTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
        //DateTimeOffset newTime2 = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
        lblTimeZone.Text = ddlTimeZone.SelectedItem.Text;
        lblCurrentDateTime.Text = newTime.ToString();
        string str;
        str = lblCurrentDateTime.Text;
        string s=str.Substring(0, 10);
        DateTime dt = new DateTime();
        dt = Convert.ToDateTime(s);
       // Response.Write(dt.ToString());
        Response.Write(ddlTimeZone.SelectedValue);

    }

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

Run Following command to show catalina logs on the terminal---

sh start-camunda.sh; tail -f server/apache-tomcat-8.0.24/logs/catalina.out

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

How can I let a table's body scroll but keep its head fixed in place?

I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.

Basically:

  1. In HTML, create container divs to position the table header row and the table body, also create a "mask" div to hide the table body as it scrolls past the header

  2. In CSS, convert the table parts to blocks

  3. In Javascript, get the table width and match the mask's width... get the height of the page content... measure scroll position... manipulate CSS to set the table header row position and the mask height

Here's the javascript and a jsFiddle DEMO.

// get table width and match the mask width

function setMaskWidth() { 
  if (document.getElementById('mask') !==null) {
    var tableWidth = document.getElementById('theTable').offsetWidth;

    // match elements to the table width
    document.getElementById('mask').style.width = tableWidth + "px";
   }
}

function fixTop() {

  // get height of page content 
  function getScrollY() {
      var y = 0;
      if( typeof ( window.pageYOffset ) == 'number' ) {
        y = window.pageYOffset;
      } else if ( document.body && ( document.body.scrollTop) ) {
        y = document.body.scrollTop;
      } else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
        y = document.documentElement.scrollTop;
      }
      return [y];
  }  

  var y = getScrollY();
  var y = y[0];

  if (document.getElementById('mask') !==null) {
      document.getElementById('mask').style.height = y + "px" ;

      if (document.all && document.querySelector && !document.addEventListener) {
        document.styleSheets[1].rules[0].style.top = y + "px" ;
      } else {
        document.styleSheets[1].cssRules[0].style.top = y + "px" ;
      }
  }

}

window.onscroll = function() {
  setMaskWidth();
  fixTop();
}

Ruby Hash to array of values

hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]] 

Enumerable#collect takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.

The Enumerable module is pretty awesome. Knowing it well can save you lots of time and lots of code.

Retrieve column names from java.sql.ResultSet

If you want to use spring jdbctemplate and don't want to deal with connection staff, you can use following:

jdbcTemplate.query("select * from books", new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            ResultSetMetaData rsmd = resultSet.getMetaData();
            for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
                String name = rsmd.getColumnName(i);
                // Do stuff with name
            }
        }
    });

How to go to a URL using jQuery?

window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it

$("<a href='your url'></a>").click(); 

How to convert int to date in SQL Server 2008

You have to first convert it into datetime, then to date.

Try this, it might be helpful:

Select Convert(DATETIME, LEFT(20130101, 8))

then convert to date.

How to pass a view's onClick event to its parent on Android?

Put

android:duplicateParentState="true"

in child then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. you can set onclick for parent and it call on child clicked

How to fix homebrew permissions?

If you would like a slightly more targeted approach than the blanket chown -R, you may find this fix-homebrew script useful:

#!/bin/sh

[ -e `which brew` ] || {
    echo Homebrew doesn\'t appear to be installed.
    exit -1
}

BREW_ROOT="`dirname $(dirname $(which brew))`"
BREW_GROUP=admin
BREW_DIRS=".git bin sbin Library Cellar share etc lib opt CONTRIBUTING.md README.md SUPPORTERS.md"

echo "This script will recursively update the group on the following paths"
echo "to the '${BREW_GROUP}' group and make them group writable:"
echo ""

for dir in $BREW_DIRS ; do {
    [ -e "$BREW_ROOT/$dir" ] && echo "    $BREW_ROOT/$dir "
} ; done

echo ""
echo "It will also stash (and clean) any changes that are currently in the homebrew repo, so that you have a fresh blank-slate."
echo ""

read -p 'Press any key to continue or CTRL-C to abort.'

echo "You may be asked below for your login password."
echo ""

# Non-recursively update the root brew path.
echo Updating "$BREW_ROOT" . . .
sudo chgrp "$BREW_GROUP" "$BREW_ROOT"
sudo chmod g+w "$BREW_ROOT"

# Recursively update the other paths.
for dir in $BREW_DIRS ; do {
    [ -e "$BREW_ROOT/$dir" ] && (
        echo Recursively updating "$BREW_ROOT/$dir" . . .
        sudo chmod -R g+w "$BREW_ROOT/$dir"
        sudo chgrp -R "$BREW_GROUP" "$BREW_ROOT/$dir"
    )
} ; done

# Non-distructively move any git crud out of the way
echo Stashing changes in "$BREW_ROOT" . . .
cd $BREW_ROOT
git add .
git stash
git clean -d -f Library

echo Finished.

Instead of doing a chmod to your user, it gives the admin group (to which you presumably belong) write access to the specific directories in /usr/local that homebrew uses. It also tells you exactly what it intends to do before doing it.

Get the last three chars from any string - Java

I would consider right method from StringUtils class from Apache Commons Lang: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)

It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.

Example usage:

StringUtils.right("abcdef", 3)

You can find more examples under the above link.

horizontal scrollbar on top and bottom of table

If you are using iscroll.js on webkit browser or mobile browser, you could try:

$('#pageWrapper>div:last-child').css('top', "0px");

LINQ query to find if items in a list are contained in another list

I think this would be easiest one:

test1.ForEach(str => test2.RemoveAll(x=>x.Contains(str)));

How to convert a Drawable to a Bitmap?

Android provides a non straight foward solution: BitmapDrawable. To get the Bitmap , we'll have to provide the resource id R.drawable.flower_pic to the a BitmapDrawable and then cast it to a Bitmap.

Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

My five cents:

Both direction array of integers function.

When range(0, 5) become [0, 1, 2, 3, 4, 5].

And range(5, 0) become [5, 4, 3, 2, 1, 0].

Based on this answer.

function range(start, end) {
  const isReverse = (start > end);
  const targetLength = isReverse ? (start - end) + 1 : (end - start ) + 1;
  const arr = new Array(targetLength);
  const b = Array.apply(null, arr);
  const result = b.map((discard, n) => {
    return (isReverse) ? n + end : n + start;
  });

  return (isReverse) ? result.reverse() : result;
}

P.S. For use in real life you should also check args for isFinite() and isNaN().

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

Learning to write a compiler

If you're looking to use powerful, higher level tools rather than building everything yourself, going through the projects and readings for this course is a pretty good option. It's a languages course by the author of the Java parser engine ANTLR. You can get the book for the course as a PDF from the Pragmatic Programmers.

The course goes over the standard compiler compiler stuff that you'd see elsewhere: parsing, types and type checking, polymorphism, symbol tables, and code generation. Pretty much the only thing that isn't covered is optimizations. The final project is a program that compiles a subset of C. Because you use tools like ANTLR and LLVM, it's feasible to write the entire compiler in a single day (I have an existence proof of this, though I do mean ~24 hours). It's heavy on practical engineering using modern tools, a bit lighter on theory.

LLVM, by the way, is simply fantastic. Many situations where you might normally compile down to assembly, you'd be much better off compiling to LLVM's Intermediate Representation instead. It's higher level, cross platform, and LLVM is quite good at generating optimized assembly from it.

How to push both value and key into PHP array

Exactly what Pekka said...

Alternatively, you can probably use array_merge like this if you wanted:

array_merge($_GET, array($rule[0] => $rule[1]));

But I'd prefer Pekka's method probably as it is much simpler.

How to return dictionary keys as a list in Python?

list(newdict) works in both Python 2 and Python 3, providing a simple list of the keys in newdict. keys() isn't necessary. (:

Difference between database and schema

Schema in SQL Server is an object that conceptually holds definitions for other database objects such as tables,views,stored procedures etc.

How to disable margin-collapsing?

Actually, there is one that works flawlessly:

display: flex; flex-direction: column;

as long as you can live with supporting only IE10 and up

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
    background: #ddd;_x000D_
    width: 15em;_x000D_
}_x000D_
_x000D_
.square {_x000D_
    margin: 15px;_x000D_
    height: 3em;_x000D_
    background: yellow;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="square"></div>_x000D_
    <div class="square"></div>_x000D_
    <div class="square"></div>_x000D_
</div>_x000D_
<div class="container">_x000D_
    <div class="square"></div>_x000D_
    <div class="square"></div>_x000D_
    <div class="square"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check empty object in angular 2 template using *ngIf

This should do what you want:

<div class="comeBack_up" *ngIf="(previous_info | json) != ({} | json)">

or shorter

<div class="comeBack_up" *ngIf="(previous_info | json) != '{}'">

Each {} creates a new instance and ==== comparison of different objects instances always results in false. When they are convert to strings === results to true

Plunker example

How to create a sub array from another array in Java?

I you are using java prior to version 1.6 use System.arraycopy() instead. Or upgrade your environment.

How do I find all files containing specific text on Linux?

Try this

find . -type f -name some_file_name.xml -exec grep -H PUT_YOUR_STRING_HERE {} \;

Adding custom radio buttons in android

Setting android:background and android:button of the RadioButton like the accepted answer didn't work for me. The drawable image was being displayed as a background(eventhough android:button was being set to transparent ) to the radio button text as enter image description here

android:background="@drawable/radiobuttonstyle"
    android:button="@android:color/transparent"

so gave radiobutton as the custom drawable radiobuttonstyle.xml

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Maintenance"
    android:id="@+id/radioButton1"
    android:button="@drawable/radiobuttonstyle"
      />

and radiobuttonstyle.xml is as follows

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_checked="true" android:drawable="@drawable/ic_radio_checked"></item>
  <item android:state_checked="false" android:drawable="@drawable/ic_radio_unchecked"></item>
</selector>

and after this radiobutton with custom button style worked.

enter image description here

How to access Winform textbox control from another class?

You can change the access modifier for the generated field in Form1.Designer.cs from private to public. Change this

private System.Windows.Forms.TextBox textBox1;

by this

public System.Windows.Forms.TextBox textBox1;

You can now handle it using a reference of the form Form1.textBox1.

Visual Studio will not overwrite this if you make any changes to the control properties, unless you delete it and recreate it.

You can also chane it from the UI if you are not confortable with editing code directly. Look for the Modifiers property:

Modifiers

MySQL match() against() - order by relevance and column?

I was just playing around with this, too. One way you can add extra weight is in the ORDER BY area of the code.

For example, if you were matching 3 different columns and wanted to more heavily weight certain columns:

SELECT search.*,
MATCH (name) AGAINST ('black' IN BOOLEAN MODE) AS name_match,
MATCH (keywords) AGAINST ('black' IN BOOLEAN MODE) AS keyword_match,
MATCH (description) AGAINST ('black' IN BOOLEAN MODE) AS description_match
FROM search
WHERE MATCH (name, keywords, description) AGAINST ('black' IN BOOLEAN MODE)
ORDER BY (name_match * 3  + keyword_match * 2  + description_match) DESC LIMIT 0,100;

Using a .php file to generate a MySQL dump

MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.

$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";

$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";

$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");

passthru("cat {$dir}{$filename}");

I hope it helps someone else!

Show Curl POST Request Headers? Is there a way to do this?

I had exactly the same problem lately, and I installed Wireshark (it is a network monitoring tool). You can see everything with this, except encrypted traffic (HTTPS).

android asynctask sending callbacks to ui

IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.

  Main.FragmentCallback FC= new  Main.FragmentCallback(){
            @Override
            public void onTaskDone(String results) {

                localText.setText(results); //example TextView
            }
        };

new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);

Remind: I used interface on the main activity thats where "Main" comes, like this:

public interface FragmentCallback {
    public void onTaskDone(String results);


}

My API post execute looks like this:

  @Override
    protected void onPostExecute(String results) {

        Log.i("TASK Result", results);
        mFragmentCallback.onTaskDone(results);

    }

The API constructor looks like this:

 class  API_CALL extends AsyncTask<String,Void,String>  {

    private Main.FragmentCallback mFragmentCallback;
    private Context act;
    private String method;


    public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
        act=ctx;
        method=api_method;
        mFragmentCallback = fragmentCallback;


    }

select certain columns of a data table

DataView dv = new DataView(Your DataTable);

DataTable dt = dv.ToTable(true, "Your Specific Column Name");

The dt contains only selected column values.

How do I install Composer on a shared hosting?

I have successfully installed Composer (and Laravel) on my shared hosting with only FTP access:

  1. Download and install PHPShell on a shared hosting

  2. In PHPShell's config.php add a user and an alias:

    php = "php -d suhosin.executor.include.whitelist=phar"

  3. Log in to PHPShell and type: curl -sS https://getcomposer.org/installer | php

  4. When successfully installed, run Composer: php composer.phar

How do I calculate r-squared using Python and Numpy?

From the numpy.polyfit documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function

E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + ... + p_1 * x + p_0

So you just need to calculate the R-squared for that fit. The wikipedia page on linear regression gives full details. You are interested in R^2 which you can calculate in a couple of ways, the easisest probably being

SST = Sum(i=1..n) (y_i - y_bar)^2
SSReg = Sum(i=1..n) (y_ihat - y_bar)^2
Rsquared = SSReg/SST

Where I use 'y_bar' for the mean of the y's, and 'y_ihat' to be the fit value for each point.

I'm not terribly familiar with numpy (I usually work in R), so there is probably a tidier way to calculate your R-squared, but the following should be correct

import numpy

# Polynomial Regression
def polyfit(x, y, degree):
    results = {}

    coeffs = numpy.polyfit(x, y, degree)

     # Polynomial Coefficients
    results['polynomial'] = coeffs.tolist()

    # r-squared
    p = numpy.poly1d(coeffs)
    # fit values, and mean
    yhat = p(x)                         # or [p(z) for z in x]
    ybar = numpy.sum(y)/len(y)          # or sum(y)/len(y)
    ssreg = numpy.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
    sstot = numpy.sum((y - ybar)**2)    # or sum([ (yi - ybar)**2 for yi in y])
    results['determination'] = ssreg / sstot

    return results

How to initialize/instantiate a custom UIView class with a XIB file in Swift

As of Swift 2.0, you can add a protocol extension. In my opinion, this is a better approach because the return type is Self rather than UIView, so the caller doesn't need to cast to the view class.

import UIKit

protocol UIViewLoading {}
extension UIView : UIViewLoading {}

extension UIViewLoading where Self : UIView {

  // note that this method returns an instance of type `Self`, rather than UIView
  static func loadFromNib() -> Self {
    let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
    let nib = UINib(nibName: nibName, bundle: nil)
    return nib.instantiateWithOwner(self, options: nil).first as! Self
  }

}

dll missing in JDBC

Friends I had the same problem because of the different bit version Make sure following point * Your jdk bit 64 or 32 * Your Path for sqljdbc_4.0\enu\auth\x64 or x86 this directory depend on your jdk bit * sqljdbc_auth.dll select this file based on your bit x64 or x86 and put this in system32 folder and it will works for me

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

How to bind Events on Ajax loaded Content?

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

scp (secure copy) to ec2 instance without password

lets assume that your pem file and somefile.txt you want to send is in Downloads folder

scp -i ~/Downloads/mykey.pem ~/Downloads/somefile.txt [email protected]:~/

let me know if it doesn't work

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

one line only

<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>

Hibernate: get entity by id

use get instead of load

// ...
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            user =  (User) session.get(User.class, user_id);
        } catch (Exception e) {
 // ...

How to display data from database into textbox, and update it

The answer is .IsPostBack as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load

private void PopulateFields()
{
  using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
  {
    DataTable dt = new DataTable();
    con1.Open();
    SqlDataReader myReader = null;  
    SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);

    myReader = myCommand.ExecuteReader();

    while (myReader.Read())
    {
        TextBoxPassword.Text = (myReader["password"].ToString());
        TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
        DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
        DropDownListMonth.Text = (myReader["birth"].ToString());
        DropDownListYear.Text = (myReader["birth"].ToString());
        TextBoxAddress.Text = (myReader["address"].ToString());
        TextBoxCity.Text = (myReader["city"].ToString());
        DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
        TextBoxPostcode.Text = (myReader["postcode"].ToString());
        TextBoxEmail.Text = (myReader["email"].ToString());
        TextBoxCarno.Text = (myReader["carno"].ToString());
    }
    con1.Close();
  }//end using
}

Then call it in your Page_Load

protected void Page_Load(object sender, EventArgs e)
{

    if(!Page.IsPostBack)
    {
       PopulateFields();
    }
}

MSVCP120d.dll missing

I downloaded msvcr120d.dll and msvcp120d.dll for 32-bit version and then, I put them into Debug folder of my project. It worked well. (My computer is 64-bit version)

Get local IP address in Node.js

Based on a comment, here's what's working for the current version of Node.js:

var os = require('os');
var _ = require('lodash');

var ip = _.chain(os.networkInterfaces())
  .values()
  .flatten()
  .filter(function(val) {
    return (val.family == 'IPv4' && val.internal == false)
  })
  .pluck('address')
  .first()
  .value();

The comment on one of the answers above was missing the call to values(). It looks like os.networkInterfaces() now returns an object instead of an array.

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

How do I find the duplicates in a list and create another list with them?

There are a lot of answers up here, but I think this is relatively a very readable and easy to understand approach:

def get_duplicates(sorted_list):
    duplicates = []
    last = sorted_list[0]
    for x in sorted_list[1:]:
        if x == last:
            duplicates.append(x)
        last = x
    return set(duplicates)

Notes:

  • If you wish to preserve duplication count, get rid of the cast to 'set' at the bottom to get the full list
  • If you prefer to use generators, replace duplicates.append(x) with yield x and the return statement at the bottom (you can cast to set later)

Setting the default active profile in Spring-boot

If you are using AWS Lambda with SprintBoot, then you must declare the following under environment variables:

key: JAVA_TOOL_OPTIONS & value: -Dspring.profiles.active=dev

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

How to construct a std::string from a std::vector<char>?

vector<char> vec;
//fill the vector;
std::string s(vec.begin(), vec.end());