text:
Q: How am I supposed to implement this custom query into index.php? The following is my index.php file
<?php get_header(); ?>
<?php
if(get_option('zens_home') == "blog") { ?>
<?php include (TEMPLATEPATH . '/lib/blog-home.php'); ?>
<?php } else { ?>

<?php
?>

<?php while (have_posts()) : the_post(); ?>
/*Start of mark*/
<li class="box" id="post-<?php the_ID(); ?>">
<?php $disc = get_post_meta($post->ID, 'fabthemes_discount', true); ?>
<?php if ( $disc ) { ?>

<?php }?>

<a href="<?php the_permalink() ?>"><img class="productshot" width="172" height="243" src="<?php get_image_url(); ?>" alt="<?php the_title(); ?>"/>

<?php if ( $disc ) { ?>
 <?php echo get_post_meta($post->ID, 'fabthemes_disc-price', true) ?>
<?php }?>

<a href="<?php the_permalink() ?>"><?php $price=get_post_meta($post->ID, 'fabthemes_price', true); echo $price; ?>

/*End of mark*/
<?php endwhile; ?>

<?php getpagenavi(); ?>

On top of the loop it is already using, I also want to place the following custom query
$args = [
    'posts_per_page' => -1,
    'post_type'      => 'products',
    'orderby'        => 'rand', // Order these posts randomly
    'tax_query'      => [
        [
            'taxonomy' => 'product-category',
            'terms'    => 27
        ]
    ]
];
$vip_posts = new WP_Query( $args );

// Run the loop
if ( $vip_posts->have_posts() ) {
    while ( $vip_posts->have_posts() ) {
        $vip_posts->the_post();

        // Display what you want in your loop like

        echo '
';

    }
    wp_reset_postdata();
}

However, I failed to do it properly without having it as either plaintext on my mainpage or finding myself in some sort of syntax error.
The problem is that I can't get the elements that I marked in the code of index.php and start after the loop in the to work with the custom query

A: A cleaner approach here would be to add your custom query via the loop_start action. The advantage of doing this is that you do not need to alter template files at all. You can simply drop your code in functions.php or a plugin if you wish (which I always prefer)
Another advantage is that the loops are apart from each other, something that you needed according to another question, so this approach would fit perfectly
The following code is untested, but should give you an idea of how to use the action
add_action( 'loop_start', function ( \WP_Query $q )
{
    // Make sure we only target the main query, if not, bail
    if ( !$q->is_main_query() )
        return;

    // Set a static counter to make sure this runs only once to avoid infinitive loops
    static $count = 0;

    // Make sure our counter is 0, if not, bail
    if ( 0 != $count )
        return;

    // Update our counter
    $count++;

    // This is the main query, lets target specific pages only
    if (    $q->is_home()
         || $q->is_post_type_archive( 'products' )
         || $q->is_tax( 'product-category' )
    ) {
        // Bail on vip pages
        if ( $q->is_tax( 'product-category', 'vip' ) ) // Make sure about vip slug
            return;

        // Bail if this is not the first page
        if ( $q->is_paged() )
            return;

        // Lets add our custom loop
        global $wp_query;

        $args = [
            'posts_per_page' => -1,
            'post_type'      => 'products',
            'orderby'        => 'rand', // Order these posts randomly
            'tax_query'      => [
                [
                    'taxonomy' => 'product-category',
                    'terms'    => 27
                ]
            ]
        ];
        $vip_posts = new WP_Query( $args );

        // Run the loop
        if ( $vip_posts->have_posts() ) {
            while ( $vip_posts->have_posts() ) {
                $vip_posts->the_post();

                // Display what you want in your loop like
                the_title();
                echo '
';

            }
            wp_reset_postdata();
        }

        // Lets make sure our main loop counter starts at -1
        $wp_query->rewind_posts();
    }
});


text:
Q: how to change text of nested html element using asp.net I'm new to web techs. I have a bunch of elements nested in each other. I want to change some of them's texts using asp.net neither jquery nor javascript. Firstly, I need to select that element by code. Then I need to assign new text value to it.
Here's my HTML.

                    Dolma Yemeği

                        For 6-8 people Prep time 2 hours

                        385

                    electricianSmurf
                    5

Here's my ASP code. I want to dynamically change foodImage's image and foodAnchor's text. I can get those elements using their IDs but there are 8 more "card" articles(they're used as flexbox). I want to reach all of them with code and change them according to the data coming from the database(ignore this database part, firstly I need to bring elements with code)
This is a coined code represents what I want to do. Please help.
 List<anchorText's type or anchor type> anchorList = new List<anchorText's type or anchor type>;
    for (int i = 0; i < anchorList.Count; i++)
    {
        Control targetElement = FindControl("card #foodImage mealInfo left a");
        if (targetElement != null)
        {
            anchorList.Add(targetElement);
        }
    }
    for (int i = 0; i < anchorList.Count; i++)
    {
        anchorList[i].Text = textComingFromDatabase;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using the pandas Rolling object to create a sliding window of lists This outstanding post illustrates quite clearly how to use the pandas cumsum() DataFrame method to build a 3D tensor containing a column with lists of lists whose dimensions make them suitable to be used as time series input to an LSTM. I would like to do something very similar but with a rolling list of lists instead of a cumulative aggregation of lists.
For example. Say you had a DataFrame with 3 time series thus:
 A   B   C
 1   2   3
 4   5   6
 7   8   9
10  11  12

The article I linked to above, shows you how to use pandas cumsum() to build a DataFrame column of nested lists that look like this:
[[1, 2, 3]]
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The key lines of python code that accomplish this are as follows:
input_cols =  list(df.columns)
df['single_list'] = df[input_cols].apply(
                       tuple, axis=1).apply(list)
df['double_encapsulated'] = df.single_list.apply(
                                      lambda x: [list(x)])

But I want a rolling window of lists, not a cumulative sum of lists. It should look like this:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[4, 5, 6], [7, 8, 9], [10, 11, 12]]
[[7, 8, 9], [10, 11, 12], [13, 14, 15]]

Can this be done with a Rolling object?

A: Here are a couple of tricks to achieve your desired results:
import pandas as pd
dd = {'A': {0: 1, 1: 4, 2: 7, 3: 10, 4: 13},
 'B': {0: 2, 1: 5, 2: 8, 3: 11, 4: 14},
 'C': {0: 3, 1: 6, 2: 9, 3: 12, 4: 15}}
df = pd.DataFrame(dd)

list_of_indexes=[]
df.index.to_series().rolling(3).apply((lambda x: list_of_indexes.append(x.tolist()) or 0), raw=False)
list_of_indexes

d1 = df.apply(tuple,axis=1).apply(list)
[[d1[ix] for ix in x] for x in list_of_indexes]

Output:
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
 [[4, 5, 6], [7, 8, 9], [10, 11, 12]],
 [[7, 8, 9], [10, 11, 12], [13, 14, 15]]]

Details:
Create an empty list.  Use rolling and apply with a trick of a function that returns None and "or" operator with zero to allow rolling apply to return 0 (a number).  However, what we are really after are the results of the function, "append" in this case.  We are using the dataframe index as the input to our rolling function, so "list_of_indexes" is a rolling list of indexes of the original dataframe, df.  Now, let's modify the dataframe to convert rows in to list which is d1, using "apply tuple" and "apply list".
Lastly, let's use d1 to replace our list_of_indexes with the appropriate list from the origingal dataframe using list comprehension.

A: Since pandas 1.1 rolling objects are iterable and you can do:
[win.values.tolist() for win in df.rolling(3, axis=1) if win.shape[0] == 3]

With the if we make sure to only get complete windows.


text:
Q: Can't use PHP extension Mcrypt in Ubuntu 13.10 (Nginx, PHP-FPM) I installed a fresh Ubuntu 13.10 on my laptop. Like I usually do, I install the packages I need for Web development, which are nginx, php5-fpm, mysql, php5-mysql, php5-mcrypt and a few others.
After editing some configuration files, this usually works.
But today, since 13.10, an error appears instead of the Web page I expected.
Laravel requires the Mcrypt PHP extension.

The package php5-mcrypt has been installed and reinstalled.
The command php -m doesn't seem to show mcrypt.
Any idea where the problem could come from? I've done this setup many times and it always worked.

A: I had the same problem after I upgraded to 13.10 this evening. Apparently this is a genuine Ubuntu 13.10 bug: "phpmyadmin do not recognize php5-mcrypt". The PHP modules got moved from the conf.d directory to the mods-available directory, and the mcrypt module got left behind.
To fix it I put a symlink to the mcrypt.ini file in the PHP config.
Apache
If you use Apache (rather than php-fpm):
sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/apache2/conf.d/20-mcrypt.ini
sudo service apache2 restart

php-fpm
Or for php-fpm (rather than Apache):

*

*Make symbolic link to ini files in mods-available
sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/mcrypt.ini

*Enable mods
sudo php5enmod mcrypt

*Restart FPM
sudo service php5-fpm restart

A: Or, use:
sudo apt-get install php5-mcrypt

Im not sure of this will work on standard php installs - I installed php 5.5.7 using the package from:
sudo add-apt-repository ppa:ondrej/php5
sudo apt-get update


text:
Q: How IPv6 headers handle next headers? I was reading that IPv6 headers have a fixed size, but then there is a field for next header also present in the header, which can specify the next header.
Even if the main header is being transmitted first and then the later ones than how is this better compared to the variable size in IPv4. Also how is the main header keeping a track of the next headers

A: Fixed header size is for simplicity and speed. Having the basics of source, dest, and hop limit in fixed locations allows for fast forwarding; acceleration of bit operations, possibly in hardware ASICs, is easier with constant offsets.
Next header allows for encapsulation of either the upper protocol payload (TCP) or an IPv6 header extension via the same mechanism. See examples in RFC8200. Essentially, this is a "linked list" of headers, each pointing to the next, and all fitting in the payload size.
This scheme allows fancy header features to be optional. A packet capture on my desktop shows several examples of no extension headers, the next header is direct to TCP.


text:
Q: k-combinations in Python 3.x What is the most efficient way to generate k-tuples with all k-combinations from a given python set? Is there an appropriate built-in function? Something tells me it should be possible with a two-line for loop.
P.S. I did conduct a search and found various entries to the topic "combinations from lists, etc in Python", but all proposed solutions seem rather 'un-python'. I am hoping for a mind-blowing, idiomatic python expression.

A: itertools has all of those types of functions:
import itertools

for combination in itertools.combinations(iterable, k):
    print(combination)


text:
Q: Checking the validity of a given date package MyJava10;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;

public class Test2 {

public static void main(String[] args)
{

    int a,b,c;
    String as,bs,cs;

    System.out.println("enter the date");

    Scanner sc=new Scanner(System.in);
    String s=sc.next();

    as=s.substring(0,2);
    bs=s.substring(3,5);
    cs=s.substring(6);
    a=Integer.valueOf(as);
    b=Integer.valueOf(bs);
    c=Integer.valueOf(cs);

    Calendar cal=new GregorianCalendar();
    cal.setLenient(false);
    cal.set(c, b-1, a);
    System.out.println(cs+'/'+bs+'/'+as);
}
}

As you can see, I am trying to know whether a given date is valid. I have coded as given and have set
cal.setLenient(false);.
Unfortunately, when I am giving an invalid date, no error is shown.
Help of any kind will be greatly appreciable. Thanks :)
Sorry if this question has been asked before by anyone else; if so, giving the URL shall be of great help.

A: You can have a function to check date validity like this:
public static String DATE_FORMAT = "MM/dd/yyyy";

public static boolean isDateValid(String date) {
    try {
        DateFormat df = new SimpleDateFormat(DATE_FORMAT);
        df.setLenient(false);
        df.parse(date);
        return true;
    } catch (ParseException e) {
        return false;
    }
}

You can change DATE_FORMAT according to your needing (documentation). Then your main is:
public static void main(String[] args) {
    System.out.println("Enter the date:");
    Scanner scanner = new Scanner(System.in);
    String date = scanner.next();

    if (isDateValid(date))
        System.out.println("Valid date");
    else
        System.out.println("Invalid date");

    scanner.close();
}

A: If you do something like this,
    Calendar cal=new GregorianCalendar();
    cal.setLenient(false);
    cal.set(2014, 8, 32);
    System.out.println(cal.getTime());

You will get
Exception in thread "main" java.lang.IllegalArgumentException: DAY_OF_MONTH
    at java.util.GregorianCalendar.computeTime(GregorianCalendar.java:2316)
    at java.util.Calendar.updateTime(Calendar.java:2265)
    at java.util.Calendar.getTimeInMillis(Calendar.java:1049)
    at java.util.Calendar.getTime(Calendar.java:1022)
    at Question.main(Question.java:39)


text:
Q: Split cart items when quantity is updated on cart page in WooCommerce I want to split cart items of same product in individual lines. When I increase quantity on single product page and add to cart, it shows as separate cart items.
Im using WooCommerce - Treat cart items separate if quantity is more than 1  answer code.
I want when quantity is updated on cart page and clicked on 'Update cart', then items must split on individual lines.
How can I do that?

A: The code below will split items on individual lines when quantity is updated on the cart page.
Comment with explanation added to the code.
function on_action_cart_updated( $cart_updated ) {
    if ( $cart_updated ) {
        // Get cart
        $cart_items = WC()->cart->get_cart();

        foreach ( $cart_items as $cart_item_key => $cart_item ) {
            $quantity = $cart_item['quantity'];

            // If product has more than 1 quantity
            if ( $quantity > 1 ) {

                // Keep the product but set its quantity to 1
                WC()->cart->set_quantity( $cart_item_key, 1 );

                // Run a loop 1 less than the total quantity
                for ( $j = 1; $j <= $quantity -1; $j++ ) {
                    // Set a unique key.
                    $cart_item['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );

                    // Get vars
                    $product_id = $cart_item['product_id'];
                    $variation_id = $cart_item['variation_id'];
                    $variation = $cart_item['variation'];

                    // Add the product as a new line item with the same variations that were passed
                    WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item );
                }
            }
        }
    }
}
add_action( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );


text:
Q: Accessing Javascript In PHP variable I have a php variable of javascript code which was parsed from another page. Is there a simple way to access the javascript variables individually with php?
PHP:
$cool = "<script type='text/javascript'>
var Title = 'This is the title';
var Text = 'Some text here';

Title.info.showinfo({

    'thumb':'image.jpg',
    'date':'Oct 2',
    'year':'2011'

});
</script>";

What Im trying to accomplish:
$title = "This is the title";
$text = "Some text here";
$thumb = "image.jpg";
$date = "Oct 2";
$year = "2011";

A: try something like this,
<?php
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);
$str = "some string";
?>

then output it using JSON data format,
<script type='text/javascript'>
var data = <?php echo json_encode($data);?>;
var str = <?php echo json_encode($str);?>;

alert(data.key1); // value1
alert(str); // some string
</script>

A: It's not javascript yet. It's just a piece of string.
And there's no simple way to get those values from PHP.
Some ways are.

*

*Dive into the string(code) and get the values by explode()ing or pattern matching with regex.

*Send the code to client first, let the javascript run and send back via AJAX.

*If you have control of the javascript code, make the variables accessible by PHP in the first place.


text:
Q: Offset between two array element addresses in C I have a question asking me to find the offset in bytes between two array element addresses:

double myArray[5][7];

If C stored data in column-major order the offset (in bytes) of &myArray[3][2] from &myArray[0][0] would be:

In column major order, I think elements would be laid out as such:
[0][0] -- [1][0] -- [2][0] -- [3][0] -- ..... -- [3][2]

So in my mind to get the offset in bytes is to count the number of jumps between [0][0] and [3][2] and times that by 8 since it's an array of doubles. However, what's confusing me is that it's asking for the offset using the & operator. Would this somehow change the answer since it's asking between two addresses or is the process still the same? I think it'd be the same but I'm not 100% certain.
If my thinking is correct would this then be 8*15 bytes?

A: The memory lay out for the 2d array would be a contiguous chunk of memory.(Based on your question)
int x[2][3] = {{0,1,2},{3,4,5}};

That will be layed out in (Your question)
--+--+--+--+--+--+
 0| 3| 1| 4|2 |5 |
--+--+--+--+--+--+

But in C this is stored like
--+--+--+--+--+--+
 0| 1| 2| 3|4 |5 |
--+--+--+--+--+--+

Now you are absolutely right, that you can consider jumps between [0][0] and [3][2] but there is a better way to do that without thinking about all this, you can be sure that their offset will be their address differences.
You can simply get their addresses and subtract them.
ptrdiff_t ans = &a[3][2]-&a[0][0];(this is basically the gaps between the two elements)
That yields the answer. printf("answer = %td",ans*sizeof(a[0][0]); (One gap = sizeof(a[0][0])) [In your case double]
Or even better way would be to
ptrdiff_t ans = (char*)&a[3][2] - (char*)&a[0][0];//number of bytes between them.

I will explain a bit why char* is important here:
(char*)&a[0][0] and &a[0][0] both contain the same thing value-wise.(this is not general enough)
But it matters in pointer arithmetic. (Interpretation is different).
When not using the cast, the interpretation is of the data type of array elements. That means now it consider the difference in doubles. When you cast it, it spits the result in or difference in char-s.
And why this works? Because all data memory is byte addressable and char is of single bytes.

There is something more to this than expected , first let's see what is an array in C? †
C does not really have multi-dimensional arrays. In C it is realized as an array of arrays. And yes those multidimensional array elements are stored in row-major order.
To clarify a bit more we can look into an example of standard §6.5.2.1
Consider the array object defined by the declaration
      int x[3][5];

Here x is a 3 x 5 array of ints; more precisely, x is an array of
  three element objects, each of which is an array of five ints. In the
  expression x[i], which is equivalent to (*((x)+(i))), x is first
  converted to a pointer to the initial array of five ints. Then i is
  adjusted according to the type of x, which conceptually entails
  multiplying i by the size of the object to which the pointer points,
  namely an array of five int objects. The results are added and
  indirection is applied to yield an array of five ints. When used in
  the expression x[i][j], that array is in turn converted to a pointer
  to the first of the ints, so x[i][j] yields an int.

So we can say double myArray[5][7]; here myArray[3][2] and myArray[0][0] are not part of the same array.
Now that we are done here - let's get into something else:
From standard §6.5.6.9

When two pointers are subtracted, both shall point to elements of the
  same array object, or one past the last element of the array object;
  the result is the difference of the subscripts of the two array
  elements.

But here myArray[3] and myArray[0] are denoting two different arrays. And that means myArrayp[3][2] and myArray[0][0] both belong to different arrays. And they are not one past the last element. So the behavior of the subtraction &myArray[3][2] - &myArray[0][0] will not be defined by the standard.
†Eric (Eric Postpischil) pointed out this idea.

A: In a row-major traversal, the declaration is array[height][width], and the usage is array[row][column]. In row-major, stepping to the next number gives you the next column, unless you exceed the width and "wrap" to the next row. Each row adds width to your index, and each column adds 1, making rows the "major" index.
In order to get the column-major equivalent, you assume the next value is the next row, and when the row exceeds the height, it "wraps" to the next column. This is described by index = column * height + row.
So, for an array array[5][7] of height 5, the index [3][2] yields 2*5 + 3 = 13.
Let's verify with some code. You can get column-major behavior simply by switching the order of the indices.
#include <stdio.h>

int main() {
    double array[7][5];
    void *root = &array[0][0];
    void *addr = &array[2][3];
    size_t off = addr - root;
    printf("memory offset: %d number offset: %d\n", off, off/sizeof(double));
    return 0;
}

Running this program yields an address offset of 104, or 13 doubles.
EDIT: sorry for wrong answer

A: The Simple Answer
C does not have multidimensional arrays, so we have to interpret double myArray[5][7] as one-dimensional array of one-dimensional arrays. In double myArray[5][7], myArray is an array of 5 elements. Each of those elements is an array of 7 double.
Thus, we can see that myArray[0][0] and myArray[0][1] are both members of myArray[0], and they are adjacent members. Thus, the elements proceed [0][0], [0][1], [0][2], and so on.
When we consider myArray[1], we see it comes after myArray[0]. Since myArray[0] is an array of 7 double, myArray[1] starts 7 double after myArray[0].
Now we can see that myArray[3][2] is 3 arrays (of 7 double) and 2 elements (of double) after myArray[0][0]. If a double is 8 bytes, then this distance is 3•7•8 + 2•8 = 184 bytes.
The Correct Answer
To my surprise, I cannot find text in the C standard that specifies that the size of an array of n elements equals n times the size of one element. Intuitively, it is "obvious"—until we consider that an implementation in an architecture without a flat address space might have some issues that require it to access arrays in complicated ways. Therefore, we do not know what the size of an array of 7 double is, so we cannot calculate how far myArray[3][2] is from myArray[0][0] in general.
I do not know of any C implementations in which the size of an array of n elements is not n times the size of one element, so the calculation will work in all normal C implementations, but I do not see that it is necessarily so according to the C standard.
Calculating the Distance in a Program
It has been suggested the address can be calculated using (char *) &myArray[3][2] - (char *) &myArray[0][0]. Although this is not strictly conforming C, it will work in common C implementations. It works by converting the addresses to pointers to char. Subtracting these two pointers then gives the distance between them in units of char (which are bytes).
Using uintptr_t is another option, but I will omit discussion of it and its caveats as this answer is already too long.
A Wrong Way to Calculate Distance
One might think that &myArray[3][2] is a pointer to double and &myArray[0][0] is a pointer to double, so &myArray[3][2] - &myArray[0][0] is the distance between them, measured in units of double. However, the standard requires that pointers being subtracted must point to elements of the same array object or to one past the last element. (Also, for this purpose, an object can act as an array of one element.) However, myArray[3][2] and myArray[0][0] are not in the same array. myArray[3][2] is in myArray[3], and myArray[0][0] is in myArray[0]. Further, neither of them is an element of myArray, because its elements are arrays, but myArray[3][2] and myArray[0][0] are double, not arrays.
Given this, one might ask how (char *) &myArray[3][2] - (char *) &myArray[0][0] can be expected to work. Isn't it also subtracting pointers to elements in different arrays? However, character types are special. The C standard says character pointers can be used to access the bytes that represent objects. (Technically, I do not see that the standard says these pointers can be subtracted—it only says that a pointer to an object can be converted to a pointer to a character type and then incremented successively to point to the remaining bytes of an object. However, I think the intent here is for character pointers to the bytes of an object to act as if the bytes of the object were an array.)


text:
Q: phoenix framework - invalid argument at new Socket - windows I'm not able to run a new phoenix app. This is the error I'm getting; I'm not sure what the reason could be.
I tried changing the port, which didn't change the behaviour. Also, it seems like I'm able to run node correctly.
Compiled web/views/error_view.ex
Compiled web/controllers/page_controller.ex
Compiled web/views/page_view.ex
Compiled web/views/layout_view.ex
Compiled lib/test_phoenix/endpoint.ex
Generated test_phoenix app
[info] Running TestPhoenix.Endpoint with Cowboy on port 4000 (http)

net.js:156
    this._handle.open(options.fd);
                 ^
Error: EINVAL, invalid argument
  at new Socket (net.js:156:18)
  at process.stdin (node.js:664:19)
  at bindWatcherEvents (c:\Desarrollo\Phoenix\test_phoenix\node_modules\brunch\l
ib\watch.js:597:12)
  at c:\******\Phoenix\test_phoenix\node_modules\brunch\lib\watch.js:667:9
  at c:\******\Phoenix\test_phoenix\node_modules\brunch\lib\watch.js:557:16
  at c:\******\Phoenix\test_phoenix\node_modules\brunch\lib\watch.js:188:12
  at c:\******\Phoenix\test_phoenix\node_modules\brunch\node_modules\async-e
ach\index.js:24:44
  at c:\******\Phoenix\test_phoenix\node_modules\brunch\lib\watch.js:175:14
  at Object.cb [as oncomplete] (fs.js:168:19)

A: I was just running into a similar problem and I updated Node to the latest version as Jose Valim suggested. That fixed the problem.


text:
Q: Does Cocoa's CFHost support IDNs? WINAPI has methods to convert Unicode host names to Punycode. Does Cocoa/Cocoa Touch have a similar mechanism?

A: There's a little hack that works without any external libraries. Assuming you have a Unicode URL in theUrl, you can do:
NSURL *urlToLoad = nil;
NSPasteboard * pasteboard = [NSPasteboard pasteboardWithName:@"RandomPB"];
[pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
@try
{
    if ([pasteboard setString:theUrl forType:NSStringPboardType])
        urlToLoad = [WebView URLFromPasteboard:pasteboard];
}
@catch (NSException * exception)
{
    urlToLoad = nil;
    NSLog(@"Can't create URL from string '%@'.", theUrl);
}
return urlToLoad;

A: Check out SBPunyCode (updated link)


text:
Q: Nested Data Context with Unity I took a course on VB.Net + WPF at university last year. For the final project, I decided to give MVVM a go (we hadn't discussed it at all in the course, I had just researched it and thought it would be a useful exercise). It was a good experience however I'm rather sure I might have made some poor choices when it came to design.
I've since graduated and my job has nothing to do with WPF or Windows development however I'm developing a small application in my own time and thought it would be fun to use C# and WPF (C# is a language I very much like to work with and I enjoyed working with WPF so it's a pretty logical choice).
Anyway, I'm using this as an opportunity to learn more about MVVM and try and implement it in a better way than I did previously. I've done a bit more reading and am finding it a lot easier to graph than I had when trying to implement it alongside learning WPF.
I've used In The Box MVVM Training as a guide and will be using Unity for dependency injection at this.
Now, in the sample app developed in the guide, there is a single view model (MainWindowViewModel). The MainWindow is pretty much a container with 3 or 4 UserControls which all share the DataContext of the MainWindow.
In my app, I'd like to have a tab-based interface. As such, the MainWindow will be primary concerned with displaying a list of buttons to switch the current view (i.e. move from the 'add' view to the 'list view'). Each view will be a self-contained UserControl which will implement it's own DataContext.
The same code in the app is as follows:
MainWindow window = container.Resolve<MainWindow>();
window.DataContext = container.Resolve<MainWindowViewModel>();
window.Show();

That's fine for setting data context of the MainWindow, however how will I handle assigning each user context it's own ViewModel as a DataContext?
EDIT: To be more specific, when I say tab-based interface, I don't mean it in the sense of tabs in a text editor or web browser. Rather, each 'tab' is a different screen of the application - there is only a single active screen at a time.
Also, while Slauma's post was somewhat helpful, it didn't really explain how I'd go about injecting dependencies to those tabs. If the NewStatementView, for example, was required to output it's data, how would I inject an instance of a class that implements the 'IStatementWriter' interface?
EDIT: To simplify my question, I'm basically trying to figure out how to inject a dependency to a class without passing every dependency through the constructor. As a contrived example:
Class A has Class B.
Class B takes as a constructor paramater needs an implementation of Interface I1.
Class B uses Class C.
Class C takes as a constructor paramater needs an implementation of Interface I2.
How would I handle this scenario using DI (and Unity)? What I don't want to do is:
public class A(I1 i1, I2 i2) { .... }
I could register everything using Unity (i.e. create I2, then C, then I1 and B, and then finally insert these into A) but then I would have to instantiate everything when I want to use A even if I might not even need an instance of B (and what if I had a whole bunch of other classes in the same situation as B?).

A: For a Tab-based interface this classical article about MVVM pattern in WPF might be very useful. (It also offers a downloadable sample application.)
The basic idea to connect each tab with a UserControl is as follows (only a rough sketch, details are in the article):
The MainWindow View has a ContentControl ...
<ContentControl Content="{Binding Path=Workspaces}"
                ContentTemplate="{StaticResource WorkspacesTemplate}" />

... which binds to a collection of "Workspaces" in the MainWindowViewModel:
public ObservableCollection<WorkspaceViewModel> Workspaces { get; private set; }

This WorkspaceViewModel serves as a base class for all ViewModels you want to display as a tab.
The WorkspacesTemplate is a DataTemplate which binds a TabControl to the collection of WorkspaceViewModels:
<DataTemplate x:Key="WorkspacesTemplate">
    <TabControl IsSynchronizedWithCurrentItem="True"
                ItemsSource="{Binding}" />
    </TabControl>
</DataTemplate>

And for every specific Tab you have a UserControl with a ViewModel which derives from WorkspaceViewModel ...
public class MySpecialViewModel : WorkspaceViewModel

... and which is related to the UserControl by a DataTemplate:
<DataTemplate DataType="{x:Type vm:MySpecialViewModel}" >
    <v:MySpecialUserControl />
</DataTemplate>

Now, if you want to open a tab you would have a Command in the MainWindowViewModel which creates the ViewModel belonging to that tab and add it to the Workspaces collection of the MainWindowViewModel:
void CreateMySpecialViewModel()
{
    MySpecialViewModel workspace = new MySpecialViewModel();
    Workspaces.Add(workspace);
}

The rest is done by the WPF binding engine. The TabControl recognizes automatically that this special workspace item in the collection is of type MySpecialViewModel and selects the right View/UserControl through the DataTemplate we have defined to connect ViewModel and View and displays it in a new Tab.

A: MVVM has lots of benefits, but in my experience wiring up the view models and the views is one of the biggest complexities.
There are two main ways to do this:
1:
Wire the view models to the views.
In this scenario, the XAML for the MainWindow contains the child controls. In your case, some of these views would probably be hidden (because you are only showing one screen at a time).
The view models get wired to the views, usually in one of two ways:
In the code behind, after the InitializeComponents() call or in a this.Loaded event handler, let this.DataContext = container.Resolve<MyViewModelType>();
Note that in this case the container needs to be globally available. This is typical in applications that use Unity. You asked how children would resolve interfaces like IStatementWriter. If the container is global, the child view models could simply call container.Resolve<IStatementWriter>();
Another way to wire the view models into the views is to create an instance of the view model in XAML like this:
<UserControl ...>
  <UserControl.DataContext>
    <local:MyViewModelType/>
  </UserControl.DataContext>
  ...
</UserControl>

This method is not compatible with Unity. There are a few MVVM frameworks that allow you to resolve types in XAML (I believe Caliburn does). These frameworks accomplish this through markup extensions.
2:
Wire the view up to the view model.
This is usually my preferred method, although it makes the XAML tree more complicated. This method works very well when you need to perform navigation in the main view model.
Create the child view model objects in the main view model.
public class MainViewModel
{
   public MyViewModelType Model1 { get; private set; }
   public ViewModelType2 Model2 { get; private set; }
   public ViewModelType3 Model3 { get; private set; }

   public MainViewModel()
   {
      // This allows us to use Unity to resolve the view models!
      // We can use a global container or pass it into the constructor of the main view model
      // The dependencies for the child view models could then be resolved in their
      //    constructors if you don't want to make the container global.
      Model1 = container.Resolve<MyViewModelType>();
      Model2 = container.Resolve<ViewModelType2>();
      Model3 = container.Resolve<ViewModelType3>();

      CurrentViewModel = Model1;
   }

   // You will need to fire property changed notifications here!
   public object CurrentViewModel { get; set; }
}

In the main view, create one or more content controls and set the content(s) to the view models that you want to display.
<Window ...>
   ...
      <ContentControl Content="{Binding CurrentViewModel}">
         <ContentControl.Resources>
            <DataTemplate DataType="{x:Type local:MyViewModelType}">
               <local:MyViewType/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type local:ViewModelType2}">
               <local:ViewType2/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type local:ViewModelType3}">
               <local:ViewType3/>
            </DataTemplate>
         </ContentControl.Resources>
      </ContentControl>
   ...
</Window>

Notice that we tie the child views to the view models through data templates on the ContentControl. These data templates could have been defined at the Window level or even the Application level, but I like to put them in context so that it's easier to see how the views are getting tied to the view models. If we only had one type of view model for each ContentControl, we could have used the ContentTemplate property instead of using resources.
EDIT: In this method, the view models can be resolved using dependency injection, but the views are resolved through WPF's resource resolution mechanism. This is how it works:
When the content for a ContentPresenter (an underlying component in the ContentControl) is set to an object that is NOT a visual (not derived from the Visual class), WPF looks for a data template to display the object. First it uses any explicit data templates set on the host control (like the ContentTemplate property on the ContentControl). Next it searches up the logical tree, examining the resources of each item in the tree for a DataTemplate with the resource key {x:Type local:OBJECT_TYPE}, where OBJECT_TYPE is the data type of the content. Note that in this case, it finds the data templates that we defined locally. When a style, control template, or data template is defined with a target type but not a named key, the type becomes the key. The Window and Application are in the logical tree, so resources/templates defined here would also be found and resolved if they were not located in the resources of the host control.
One final comment. If a data template is not found, WPF calls ToString() on the content object and uses the result as the visual content. If ToString() is not overridden in some meaningful way, the result is a TextBlock containing the content type.
<--
When you update the CurrentViewModel property on the MainViewModel, the content and view in the main view will change automatically as long as you fire the property changed notification on the main view model.
Let me know if I missed something or you need more info.

A: At the point where you resolve your Views deriving from UserControl, use property injection to resolve a new ViewModel for each one and set the DataContext property of the view to it.


text:
Q: rmarkdown knitr child intermediate_dir I have a main document. Let's call it main.Rmd. In this main document I include a knitr child. Let's call this child.Rmd.  In the child.Rmd I define a variable containing the link to a file containing R chunks, called chunks.R, which I want to load using read_chunk.
If I use the rmarkdown::render('main.Rmd') everything works fine. However, once I set the intermediate_dir to something else (e.g rmarkdown::render('main.Rmd',intermediate_dir=tempdir()) the read_chunk won't work anymore.
If I pass the filepath directly to read_chunk instead of defining it in a variable it works again. I need to pass the filename via variable however.
main.Rmd
---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r,child='~/Desktop/knitr_problem/child.Rmd',}
```

child.Rmd
```{r}
chunkpath=normalizePath('~/Desktop/knitr_problem/chunks.R')
knitr::read_chunk(chunkpath)
```

## Including Plots

You can also embed plots, for example:

```{r cars, echo=FALSE}
```

chunks.R
## @knitr cars
summary(cars)

render(main.Rmd) will work
render(main.Rmd,intermediate_dir=tempdir()) won't work and throw the following error
Error in readLines(path, warn = FALSE) : object 'chunkpath' not found


text:
Q: Get the latest update time of a specific folder in a repo using Github API How can I get the latest update time of a specific folder in a repo using Github API?
I've tried
https://api.github.com/repos/User/Repo/contents
but it did not return any information about the latest update time.
or is it impossible for Github to do it?

A: You can fetch the list of commits for that path with the Commits API:
https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
If you look at the first commit in the returned list, that's the most recent commit which modified something in that folder. The date on which the commit was created is what you're looking for.


text:
Q: Error: Uncaught TypeError: Cannot set property 'onclick' of null Please help to solve the problem:
I want to modify the output of a picture through popup when I click.
There is a code (original):

<img alt="" src="<?php echo JUri::root() . $floor_plan['img']; ?>">

Modified code with javascript,css and html+some php:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
}

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
/* Style the Image Used to Trigger the Modal */
#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (Image) */
.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)}
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)}
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}

<img id="myImg" src="<?php echo JUri::root() . $floor_plan['img']; ?>" alt="">

×

Javascript returns error:
"Uncaught TypeError: Cannot set property 'onclick' of null
What's wrong here?
Thank you in advance for your help!

A: You don't have an element with an id of img01.
var img = document.getElementById('myImg');

Yes, i did'nt add it.
Now the code is:

  <img id="myImg" src="<?php echo JUri::root() . $floor_plan['img']; ?>" alt="">

  ×

But still in the console error:
Uncaught TypeError: Cannot set property 'onclick' of null
at this line in javascript:
img.onclick = function(){


text:
Q: How do I apply a function to a subset of each of several columns? Suppose I had a data.table like this:
> test.dt = data.table(alice = 2:-1, bob = -1:2, claire = 0:-1, x = 2:5)
> test.dt
   alice bob claire x
1:     2  -1      0 2
2:     1   0     -1 3
3:     0   1      0 4
4:    -1   2     -1 5

but in general there are many more names than just "alice", "bob", and "claire" and they are stored in a vector
names = c("alice", "bob", "claire")

Unlike "alice", "bob", or "claire", the column "x" is a special column not in names.
Suppose I had a function f(name, x) taking vector inputs. I would like to do the following: within each column whose name is in names, replace (in place) all positive values with f(name, x) and leave the other values unchanged.
This seems like a simple enough task which could be done as follows in pandas (renaming test.dt to df):
for name in names:
    df.loc[df[name] > 0, name] = f(df.loc[df[name] > 0, name],
                                   df.loc[df[name] > 0, "x"])

but I cannot figure out how to do it in R.

A: With data.table it could be a good choice (as it is in this case) to use a for loop as follows (using the same function as @Ronak):
for (n in nms) {
  test.dt[get(n) > 0, (n) := f(get(n), 2L)]
}

which gives:

> test.dt
   alice bob claire x
1:     4  -1      0 2
2:     2   0     -1 3
3:     0   2      0 4
4:    -1   4     -1 5

Note: try to avoid to give object the same name as a function; hence I renamed the names vector to nms.

A: Consider a function
f <- function(x, n) x * n

We can use .SDcols to specify column by names
library(data.table)
test.dt[, (names) := lapply(.SD, function(x) ifelse(x > 0, f(x, 2), x)), .SDcols = names]

test.dt
#   alice bob claire x
#1:     4  -1      0 2
#2:     2   0     -1 3
#3:     0   2      0 4
#4:    -1   4     -1 5


text:
Q: Error when checking input: expected flatten_1_input to have shape (1, 4) but got array with shape (1, 2) I am facing this error
    def Build_model(states, actions):
model = Sequential()
model.add(Flatten(input_shape = (1,states))) # First layer/state of the model
model.add(Dense(24, activation='relu')) # Second layer/state of the model
model.add(Dense(24, activation='relu')) # Third layer/state of the model
model.add(Dense(actions, activation='linear')) # Last layer/state of the model
return model

dqn = Build_agent(model,actions)

dqn.compile(Adam(learning_rate =1e-3), metrics=['mae'])
dqn.fit(env, nb_steps = 50000, visualize= False, verbose=1)


text:
Q: How can I dynamically reference column names while looping through a query's results? I have successfully written a SELECT statement that uses dynamic variables. It uses variables from the page to know what columns to select from a big, messy table. It looks something like this.
<cfquery name="getCapabilityAndDescription" datasource="Stuff">
SELECT [EntryID],
<cfloop list="#JobLevelList#" index="JobLevelIndex">
   [#getJobDesc.Type##JobLevelIndex#Capability],
   [#getJobDesc.Type##JobLevelIndex#Description],
</cfloop>
[JobID]
FROM [JobCapabilityMatrix]
WHERE JobID = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#URL.JobID#">
AND SkillID = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#URL.SkillID#">
</cfquery>

Say for example, it dynamically selects a column called Baker3Description.
But...How would I be able to output that dynamically? I guess to sum it up, I need to create a dynamic variable and then put it in a query's scope.
So far I have tried setting it and calling it like this:
<cfset DescriptionVariable = #JobTitle# & #JobLevelIndex# & 'Description'>
<cfoutput>
#getCapabilityAndDescription.DescriptionVariable#
</cfoutput>

But it doesn't evaluate the way I want it to, and just tells me

Element DESCRIPTIONVARIABLE is undefined in
GETCAPABILITYANDDESCRIPTION.

I know there's a way to actually return the content of Baker3Description from the query, maybe using array syntax? But I've messed around too much and need a little help. Please & thanks.

A: It's possible using structure notation, but also requires a query row number. The general syntax is
#queryName[ "columnName" ][ rowNum ]#
<!---
.. or specifically
--->
#getCapabilityAndDescription[ DescriptionVariable ][ 1 ]#

To output all of the query columns dynamically. Use GetMetaData() to retrieve an array of query column properties (in select order). Then use the name property to output each column value:
<!--- Demo query --->
<cfset yourQuery = queryNew("EntryID,Baker3Description"
        , "integer,varchar"
        , [[1,"Descrip A"],[2,"Descrip B"]]
    )>

<cfset meta = getMetaData(yourQuery)>
<cfoutput query="yourQuery">
    <cfloop array="#meta#" index="props">
        #yourQuery[props.name][currentRow]#
    </cfloop>
    <br>
</cfoutput>

Though be careful building that kind of dynamic sql. If any of the values used to build the column names are user supplied (for example getJobDesc.Type) the query will be vulnerable to second order sql injection.


text:
Q: run sub-process of a urxvt perl extension in calling urxvt window I am trying to write a rxvt-unicode perl extension to do what mrxvt PrintScreen does. I.e., the extension should pipe urxvt's contents to user-defined commands. The main purpose would be viewing urxvt's contents unwrapped in less -S.
Here are my first attempts. (The command is still hardcoded cat -n, and including color escape codes and joining of wrapped lines is still missing.)
#! perl -w
use strict;

sub on_user_command {
    my ($self, $cmd) = @_;
    open PIPE, "|cat -n" or die "urxvt-pipe: error opening pipe: $^E\n";
    for (my $i = $self->top_row; $i < $self->nrow; $i++) {
        print PIPE $self->ROW_t($i), "\n";
    }
    close PIPE or warn "urxvt-pipe: error closing pipe: $^E\n";
    ()
}

Replacing the pipe with exec_async does not help:
#! perl -w
use strict;

sub on_user_command {
    my ($self, $cmd) = @_;
    open FH, ">/tmp/urxvt.txt" or die "urxvt-pipe: error opening file: $^E\n";

    for (my $i = $self->top_row; $i < $self->nrow; $i++) {
        print FH $self->ROW_t($i), "\n";
    }

    close FH or warn "urxvt-pipe: error closing file: $^E\n";
    $self->exec_async("cat", "-n", "/tmp/urxvt.txt");
    ()
}

The problem with both is that the cat runs inside urxvt's parent (e.g. another urxvt or an emacs buffer if I call urxvt as the "compile" command during extension development). I would like it to run in the instance whose contents I'm piping, or a new tab thereof. Is that possible?
Obviously as a workaround, the exec_async could be modified to open a new window: $self->exec_async("urxvt", "-title", "less urxvt scrollback", "-e", "less", "-S", "/tmp/urxvt.txt"); But I'd prefer the same window, and also rather avoid creating a temporary file.

A: This does not answer the real question, but unfortunately it was rejected as too long for a comment.
I made the workaround less ugly, moving the new window part out of the extension:

*

*The extension uses IPC::Run3::run3 to capture the subprocess's stdout and stderr, and writes that to the "right" urxvt using $term->special_encode and $term->cmd_parse. (Not that less had any usefull output, but just to make it a general purpose extension.)

*The configured command (in a URxvt.keysym... line in ~/.Xdefaults) is: zsh -c 'stdin2fifo | read -r p && urxvt -e less -SNRfI -- "$p"'

*Script stdin2fifo reads stdin and writes it to a temp named pipe. less -f displays the pipe. So there's hopefully no disk I/O for the real data, only for a file system entry.

Script stdin2fifo:
#!/bin/zsh
if [ $# -ne 0 ]; then
    cat <<EOF
Usage: $(basename "$0")
Reads stdin, writes it to a new named pipe (in the background), and prints the
pipe's pathname.
Can be used (in zsh, at least) to "send stdin to another terminal". For example:
... | $(basename "$0") | read -r p && urxvt -e less -f -- "\$p"
EOF
    exit 4
fi

set -e
dir=$(mktemp -d "/tmp/$(basename "$0")_XXXXXX")
pipe=$dir/pipe
mkfifo "$pipe"
(cat > "$pipe")&
echo "$pipe"

EDIT 2022-12-10 in response to @geb's question how far I got. Caveat: I stopped using urxvt years ago and don't know whether this works in current versions and even how much of it worked back in the day. It seems it was last edited in May 2016. So WITHOUT WARRANTY, use at your own risk.
Script stdin2fifo: see above, unchanged.
Script urxvt-pipe:
#! perl -w
use strict;
use Env;
use IPC::Run3;
use feature qw(current_sub);

use constant EXT_NAME => 'urxvt-pipe';
use constant INFO => 8;
use constant DEBUG => 13;
use constant TRACE => 16;

sub msgLevelEnabled { my ($level) = @_; $ENV{URXVT_PERL_VERBOSITY} >= $level; }
sub msg { my $level = shift @_; printf STDERR @_ if msgLevelEnabled($level); }
sub errorMsg { die(sprintf("%s: %s\n", EXT_NAME, join(", ", @_))); }
sub warnMsg { warn(sprintf("%s: %s\n", EXT_NAME, join(", ", @_))); }

sub on_start {
    my ($t) = @_;
    # corresponding .Xdefaults line: URxvt.pipe.stdout-format:  \033[34m%s\033[0m\015\n
    $t->{stdoutFormat} = $t->conf("stdout-format", "\e[34m%s\e[0m\r\n");
    msg(DEBUG, "{stdoutFormat} == '%s'\n", $t->{stdoutFormat});
    $t->{stderrFormat} = $t->conf("stderr-format", "\e[31m%s\e[0m\r\n");
    msg(DEBUG, "{stderrFormat} == '%s'\n", $t->{stderrFormat});
    $t->{statusFormat} = $t->conf("status-format", "\e[41;37;1m Status: %s \e[0m\r\n");
    msg(DEBUG, "{statusFormat} == '%s'\n", $t->{statusFormat});
    $t->{echoFormat} = $t->conf("echo-format", "\r\n\e[34m" . EXT_NAME . "> %s\e[0m\r\n");
    msg(DEBUG, "{echoFormat} == '%s'\n", $t->{echoFormat});
    $t->{promptPattern} = $t->conf("prompt-pattern", '.*?[>$#]\s*+(.+)');
    msg(DEBUG, "{promptPattern} == '%s'\n", $t->{promptPattern});
    $t->{sendBeforeCommand} = $t->conf("send-before-cmd", '');
    msg(DEBUG, "{sendBeforeCommand} == '%s'\n", $t->{sendBeforeCommand});
    $t->{sendAfterCommand} = $t->conf("send-after-cmd", '');
    msg(DEBUG, "{sendAfterCommand} == '%s'\n", $t->{sendAfterCommand});

    msg(TRACE, "DEFAULT_RSTYLE == %032b (%s)\n", urxvt::DEFAULT_RSTYLE, describeRendition(urxvt::DEFAULT_RSTYLE));
    msg(TRACE, "RS_Bold        == %032b\n", urxvt::RS_Bold);
    msg(TRACE, "RS_Italic      == %032b\n", urxvt::RS_Italic);
    msg(TRACE, "RS_Blink       == %032b\n", urxvt::RS_Blink);
    msg(TRACE, "RS_RVid        == %032b\n", urxvt::RS_RVid);
    msg(TRACE, "RS_Uline       == %032b\n", urxvt::RS_Uline);
}

sub conf {
    my ($term, $name, $defaultValue) = @_;
    defined $term->x_resource("%.$name") ? $term->x_resource("%.$name") : $defaultValue;
}

sub on_user_command {
    my ($term, $arg) = @_;

    # === parse $arg ===
    msg(DEBUG, "on_user_command(.., '%s')\n", $arg);
    my (undef, $options, $cmd) = $arg =~ m{.*?:(.)(.*?)\1(.*)} or errorMsg("expected arg format ...:[<options>]:<command>");
    msg(DEBUG, "\$options == '%s', \$cmd == '%s'\n", $options, $cmd);
    my %options = ();
    for (split /,/, $options) { m{(.*?)=(.*)} or errorMsg("options: expected comma-separated key=value pairs"); $options{$1} = $2; };
    msg(DEBUG, "%%options == (%s)\n", join("; ", map { "$_ = $options{$_}" } keys(%options))) if msgLevelEnabled(DEBUG);

    # === prepare $cmd's input ===
    my ($rowNum, $maxRowNum) = selectRows($term, $options{start}, $options{end});
    my $nextLine = sub {
        return undef if $rowNum > $maxRowNum;
        my $l = $term->line($rowNum);
        msg(TRACE, "\nline(%d)->t == \"%s\"\n", $rowNum, $l->t);
        msg(TRACE, "line(%d)->beg == %d, ->end == %d\n", $rowNum, $l->beg, $l->end);
        $rowNum += $l->end - $l->beg + 1;
        return line2string($term, $l, \%options) . "\n";
    };
    $nextLine = logFunction($nextLine, 'nextLine') if msgLevelEnabled(DEBUG);

    # wrap $nextLine() to discard trailing empty results
    my $bufferedEmptyResultsCount = 0;  #buffered empty lines returned by nextLine()
    my $bufferedResult; #buffered non-empty line after $bufferedEmptyResultsCount
    my $nextLineTruncated = sub {
        # prefer buffered results to new $nextLine() invocation
        if ($bufferedEmptyResultsCount > 0) {
            msg(TRACE, "returning buffered empty line\n");
            $bufferedEmptyResultsCount--;
            return "\n";
        }
        if (defined($bufferedResult)) {
            msg(TRACE, "returning buffered non-empty line\n");
            my $result = $bufferedResult;
            $bufferedResult = undef;
            return $result;
        }

        my $origResult = &$nextLine(@_);
        if ($origResult ne "\n") {
            msg(TRACE, "returning original line\n");
            return $origResult;
        }

        msg(TRACE, "buffering empty line; looking for next non-empty line\n");
        $bufferedEmptyResultsCount++;
        # after empty result, search for next non-empty result (or stop at undef)
        while (1) {
            $origResult = &$nextLine(@_);
            if (!defined($origResult)) {
                msg(DEBUG, "discarding %d trailing empty lines\n", $bufferedEmptyResultsCount);
                $bufferedEmptyResultsCount = 0;
                $bufferedResult = undef;
                return undef;
            }
            if ($origResult eq "\n") {
                msg(TRACE, "buffering empty line\n");
                $bufferedEmptyResultsCount++;
            } else {    #found non-empty
                msg(TRACE, "buffering non-empty line, re-invoking %s\n", __SUB__);
                $bufferedResult = $origResult;
                return __SUB__->(@_);
            }
        }
    };

    $nextLineTruncated = logFunction($nextLineTruncated, 'nextLineTruncated') if msgLevelEnabled(DEBUG);

    # === read $cmd from terminal if empty ===
    if (length($cmd) == 0) {
        $cmd = readCommandFromTerminal($term);
        if (!defined($cmd)) { return (); }
    }

    # === sub to e.g. cut current input line (only before 1st output) ===
    my $hasOutput = 0;
    my $beforeOutput = sub {
        if (!$hasOutput) {
            $hasOutput = 1;
            $term->tt_write($term->{sendBeforeCommand}) if length($term->{sendBeforeCommand}) > 0;
        }
    };

    # === print $cmd ===
    if ($options{'echo'}) {
        &$beforeOutput;
        $term->cmd_parse(sprintf($term->{echoFormat}, $term->special_encode($cmd)));
    }

    # === execute $cmd ===
    my($cmdIn, $cmdOut, $cmdErr, %run3options);
    $run3options{binmode_stdin} = $run3options{binmode_stdout} = $run3options{binmode_stderr} = ':utf8';
    my $run = run3($cmd, $nextLineTruncated, \$cmdOut, \$cmdErr, \%run3options)
        or errorMsg("failed to start ${cmd}: $^E");
    my $status = $? >> 8;
    msg(DEBUG, "\$? == %d, \$status == %d\n", $?, $status);

    # === print $cmd's output and status ===
    unless ($options{'quiet'}) {
        if (length($term->{stdoutFormat}) > 0 && length($cmdOut) > 0) {
            msg(DEBUG, "printing stdout\n");
            for (split /\r?\n/, $cmdOut) {
                &$beforeOutput;
                $term->cmd_parse(sprintf($term->{stdoutFormat}, $term->special_encode($_)));
            }
        }
        if (length($term->{stderrFormat}) > 0 && length($cmdErr) > 0) {
            msg(DEBUG, "printing stderr\n");
            for (split /\r?\n/, $cmdErr) {
                &$beforeOutput;
                $term->cmd_parse(sprintf($term->{stderrFormat}, $term->special_encode($_)));
            }
        }
        if ($status != 0 && length($term->{statusFormat}) > 0) {
            msg(DEBUG, "printing status\n");
            &$beforeOutput;
            $term->cmd_parse(sprintf($term->{statusFormat}, $status));
        }
    }

    # === try to correct prompt (e.g. paste current input) ===
    if ($hasOutput && length($term->{sendAfterCommand}) > 0) {
        msg(DEBUG, "printing {sendAfterCommand}\n");
        $term->tt_write($term->{sendAfterCommand});
    }

    msg(DEBUG, "on_user_command returns\n");
    ()
}

sub selectRows {
    my ($term, $startPage, $endPage) = @_;

    msg(DEBUG, "nrow=%d, saveL.=%d, total_rows=%d, view_start=%d [%s], top_row=%d [%s]\n",
        $term->nrow, $term->saveLines, $term->total_rows,
        $term->view_start, substr($term->ROW_t($term->view_start), 0, 30),
        $term->top_row, substr($term->ROW_t($term->top_row), 0, 30))
        if msgLevelEnabled(DEBUG);

    if (!defined $startPage && !defined $endPage) { #neither start nor end set => only current page
        $startPage = 0;
        $endPage = 0;
    }
    # only one of start or end set
    $startPage = '^' unless defined $startPage;
    $endPage = '$' unless defined $endPage;

    my $startRow = selectRow($term, $startPage, 0);
    my $endRow = selectRow($term, $endPage, 1);
    msg(DEBUG, "selectRows(.., %s, %s) == (%s, %s)\n", $startPage, $endPage, $startRow, $endRow);
    return ($startRow, $endRow);
}

sub selectRow {
    my ($term, $page, $bottom) = @_;

    my $min = $term->top_row;
    my $max = $term->total_rows - $term->nrow + 1;
    my $row;
    if ($page eq '^') {
        $row = $min;
    } elsif ($page eq '$') {
        $row = $max;
    } else {
        $row = $term->view_start + $page * $term->nrow;
        if ($row < $min) { $row = $min; }
        if ($row > $max) { $row = $max; }
    }

    if ($bottom) {
        $row += $term->nrow - 1;
    } else {
        # TODO Set environment variable according to (logical) line, not (wrapped) row
        my $envLineNo = $term->view_start - $row;
        msg(DEBUG, "URXVT_PIPE_LINENO = %s\n", $envLineNo);
        $ENV{URXVT_PIPE_LINENO} = $envLineNo if $envLineNo >= 0;
    }

    return $row;
}

sub readLastTerminalLine {
    my ($term) = @_;

    my $lastLineText = '';
    for (my $rowNum = $term->total_rows; $rowNum >= $term->top_row; $rowNum--) {
        my $line = $term->line($rowNum);
        msg(TRACE, "readLastTerminalLine: [%d] \$line->t = '%s'\n", $rowNum, $line->t);
        $lastLineText = $term->special_decode($line->t) . $lastLineText;
        last if $line->l > 0;
        $rowNum -= $line->end - $line->beg;
    }
    $lastLineText =~ s{\n+$}{}g;
    msg(DEBUG, "readLastTerminalLine() == '%s'\n", $lastLineText);
    return $lastLineText;
}

sub readCommandFromTerminal {
    my ($term) = @_;

    my $lastLineText = readLastTerminalLine($term);
    if ($lastLineText =~ m{$term->{promptPattern}}s && length($1) > 0) {
        msg(INFO, "found command '%s'\n", $1);
        return $1;
    }
    warnMsg('No command found using prompt pattern ' . $term->{promptPattern}
            . ' (did you forget a capturing group?)');
    return undef;
}

# converts a urxvt->line object into the string to write to the pipe
sub line2string {
    my ($term, $line, $optionsRef) = @_;

    my %options = %$optionsRef;
    my $text = $line->t;
    if (!$options{'color'}) {
        return $term->special_decode($text);
    }

    my @rendsArray = @{$line->r};
    my $textEsc = '';   # $text with escapes
    my $len = length($text);
    my $prevRend;
    my $resetSuffix = '';

    for (my $i = 0; $i < $len; $i++) {
        my $char = substr($text, $i, 1);
        my $rend = $rendsArray[$i];
        msg(TRACE, "[%d]\t'%s': \$rend == %032b (%s)\n", $i, $char, $rend,
            $rend == $prevRend ? '...' : describeRendition($rend)) if msgLevelEnabled(TRACE);
        if ($i == 0 || $rend != $prevRend) {
            $textEsc .= "\e[m" if $i > 0;   #TODO make escapes configurable
            my $escape = rendition2Escape($rend);
            $resetSuffix = "\e[m" if '' ne $escape; #TODO make escapes configurable
            $textEsc .= $escape;
        }

        $textEsc .= $char;
        $prevRend = $rend;
    }

    return $term->special_decode($textEsc . $resetSuffix);
}

#TODO make escapes configurable
sub rendition2Escape {
    my ($rend) = @_;
    if ($rend == 0) {
        msg(TRACE, "rendition2Escape(0) == ''\n");
        return '';
    }

    my @escapes = ();

    # WTF? GET_BASEFG == 0 / GET_BASEBG == 1 seem to mean default color; otherwise they are color index + 2.
    # TODO: But GET_BASEBG == 1 can also be color 1 (red). How to distinguish?
    # Example (showing output of /usr/share/screen/256colors.pl):
    # "S" in "System colors:" header, default colors:
    # -> $rend == 00000000000010000000000000000001 (fg: 0, bg: 1, bold: 0, it: 0, ul: 0, rv: 0, bl: 0, custom: 0)
    # 3rd " " in line 2, red background:
    # -> $rend == 00000000000010000000000000000011 (fg: 0, bg: 3, bold: 0, it: 0, ul: 0, rv: 0, bl: 0, custom: 0)
    my $bg = urxvt::GET_BASEBG $rend;
    my $fg = urxvt::GET_BASEFG $rend;
    push @escapes, ('38;5;' . ($fg - 2)) if $fg != 0;
    push @escapes, ('48;5;' . ($bg - 2)) if $bg != 1;

    push @escapes, '1' if $rend & urxvt::RS_Bold;
    push @escapes, '3' if $rend & urxvt::RS_Italic;
    push @escapes, '5' if $rend & urxvt::RS_Blink;
    push @escapes, '7' if $rend & urxvt::RS_RVid;
    push @escapes, '4' if $rend & urxvt::RS_Uline;

#   my $escapeSeq = "\e[" . join(';', @escapes) . 'm';
    my $escapeSeq = join('', map { "\e[" . $_ . 'm' } @escapes);
    msg(TRACE, "rendition2Escape(%s): %sxyz\e[0m\n", $rend, $escapeSeq) if @escapes > 0 && msgLevelEnabled(TRACE);
    return $escapeSeq;
}

sub describeRendition {
    my ($rend) = @_;
    sprintf("fg: %d, bg: %d, bold: %d, it: %d, ul: %d, rv: %d, bl: %d, custom: %d",
            urxvt::GET_BASEFG $rend,
            urxvt::GET_BASEBG $rend,
            $rend & urxvt::RS_Bold,
            $rend & urxvt::RS_Italic,
            $rend & urxvt::RS_Uline,
            $rend & urxvt::RS_RVid,
            $rend & urxvt::RS_Blink,
            urxvt::GET_CUSTOM $rend);
}

sub logFunction {
    my ($funcRef, $funcName) = @_;
    my $logF = sub {
        my $res = &$funcRef(@_);
        msg(DEBUG, "%s(..) == '%s'\n", $funcName, defined($res) ? $res : '<undef>');
        return $res;
    };
    msg(TRACE, "logFunction(%s) == %s\n", $funcRef, $logF);
    return $logF;
}

# TODO: documentation

~/.Xdefaults entries (grepping for "pipe", the one called "URxvt.print-pipe" is probably unrelated):
URxvt.print-pipe:   cat > /tmp/urxvt.pp
URxvt.perl-ext-common: default,keyboard-select,pipe
URxvt.pipe.stdout-format:   \033[90m[%s]\033[0m\015\n
URxvt.pipe.stderr-format:   \033[31m[%s]\033[0m\015\n
URxvt.pipe.status-format:   \040\033[101;37;1m\!%d\!\033[0m\040\015\n
urxvt.perl-ext-common:  default,pipe
urxvt.keysym.F5:    perl:pipe::start=-2,end=0,color=1:  zsh -c 'stdin2fifo | read -r f && env URXVT_PERL_VERBOSITY= mintty -t "less urxvt" -s 270x73 -p 0,0 -o BackgroundColour=255,249,216 -i /c/windows/system32/shell32.dll,56 -e less -SRf +${URXVT_PIPE_LINENO:-0}g "$f"&'
urxvt.keysym.S-F5:  perl:pipe::start=-4,end=0,color=1:  zsh -c 'stdin2fifo | read -r f && env URXVT_PERL_VERBOSITY= mintty -t "less urxvt" -s 270x73 -p 0,0 -o BackgroundColour=255,249,216 -i /c/windows/system32/shell32.dll,56 -e less -SRf +${URXVT_PIPE_LINENO:-0}g "$f"&'
urxvt.keysym.F6:    perl:pipe::start=-20,end=$,color=1: zsh -c 'stdin2fifo | read -r f && env URXVT_PERL_VERBOSITY= mintty -t "less urxvt" -s 270x73 -p 0,0 -o BackgroundColour=255,249,216 -i /c/windows/system32/shell32.dll,56 -e less -SRf +G "$f"&'
urxvt.keysym.S-F6:  perl:pipe::start=^,end=$,color=1:   zsh -c 'stdin2fifo | read -r f && env URXVT_PERL_VERBOSITY= mintty -t "less urxvt" -s 270x73 -p 0,0 -o BackgroundColour=255,249,216 -i /c/windows/system32/shell32.dll,56 -e less -SRf +G "$f"&'


text:
Q: Obtaining a render Argument Error: What is the correct syntax or usage? I am new to Ruby, Sinatra and Pusher so this is a basic question. I am attempting to authenticate a Pusher Client (using iOS demo code https://github.com/lukeredpath/libPusher). The server code below fails with error when the iOS client attempts to join a presence channel:
ArgumentError - wrong number of arguments (1 for 2):
    /Users/waveocean/.rvm/gems/ruby-1.9.3-p327/gems/sinatra-1.3.3/lib/sinatra/base.rb:665:in `render'
    web.rb:13:in `auth'
    web.rb:26:in `block in <main>'
    /Users/waveocean/.rvm/gems/ruby-1.9.3-p327/gems/sinatra-1.3.3/lib/sinatra/base.rb:1265:in `call'

... snipped for brevity ...

Here is the code:
require 'sinatra'
require 'pusher'
require 'thin'
Thin::HTTP_STATUS_CODES[403] = "FORBIDDEN"

Pusher.app_id = 'MY-APP-ID'
Pusher.key = 'MY-KEY'
Pusher.secret = 'MY-SECRET'

def auth
  response = Pusher[params[:channel_name]].authenticate(params[:socket_id], {:user_id => 101})
  render :json => response
end

 use Rack::Auth::Basic, "Protected Area" do |username, password|
   username == 'foo' && password == 'bar'
 end

 post '/presence/auth' do
   if params[:channel_name] == 'presence-demo'
      auth
   else
   #   render :text => "Forbidden", :status => '403'
   response.status = 403
   end
 end

Can someone provide a suggestion or correct usage of render?

A: Here's is what I discovered. render is associated with Rails, and not strictly Ruby. To respond to the Sinatra route, use the following in the auth method:
def auth
  response = Pusher[params[:channel_name]].authenticate(params[:socket_id], {:user_id => 101})
  [200, {"Content-Type" => "application/json"}, response.to_json]
end

As it turns out, the Pusher iOS project demo provides a Scripts/auth_server.rb file with the required implementation. It is documented with the installation instructions here: https://github.com/lukeredpath/libPusher/wiki/Adding-libPusher-to-your-project .


text:
Q: Battery Life in ubuntu 14.04 Today i had fresh installation of ubuntu 14.04
previously i had ubuntu 12.04 and had 5 to 6 hours of battery backup even at constant work, but in 14.04 getting 3 hrs only, tried with tlp but no use.
lspci:
0:00.0 Host bridge: Intel Corporation 3rd Gen Core processor DRAM Controller (rev 09)
00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)
00:14.0 USB controller: Intel Corporation 7 Series/C210 Series Chipset Family USB xHCI Host Controller (rev 04)
00:16.0 Communication controller: Intel Corporation 7 Series/C210 Series Chipset Family MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation 7 Series/C210 Series Chipset Family USB Enhanced Host Controller #2 (rev 04)
00:1b.0 Audio device: Intel Corporation 7 Series/C210 Series Chipset Family High Definition Audio Controller (rev 04)
00:1c.0 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 1 (rev c4)
00:1c.1 PCI bridge: Intel Corporation 7 Series/C210 Series Chipset Family PCI Express Root Port 2 (rev c4)
00:1d.0 USB controller: Intel Corporation 7 Series/C210 Series Chipset Family USB Enhanced Host Controller #1 (rev 04)
00:1f.0 ISA bridge: Intel Corporation HM76 Express Chipset LPC Controller (rev 04)
00:1f.2 SATA controller: Intel Corporation 7 Series Chipset Family 6-port SATA Controller [AHCI mode] (rev 04)
00:1f.3 SMBus: Intel Corporation 7 Series/C210 Series Chipset Family SMBus Controller (rev 04)
01:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8101E/RTL8102E PCI Express Fast Ethernet controller (rev 05)
02:00.0 Network controller: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter (rev 01)

A: First remove sudo apt-get remove tlp
install cpu-freq:-
cd && wget -O .laptop-mode.sh http://drive.noobslab.com/data/improve-battery/laptop-mode

chmod +x .laptop-mode.sh && ./.laptop-mode.sh

If You running GPU Nvidia/AMD change setting to Intel Mode.


text:
Q: Start hotspot in Android 10+ using Xamarin Forms hoping you can help, i have tried absolutely everything to get this working. I tried to adapt other code which apparently works in android studio to work in Xamarin. I have reached a point i cant pass. here is what i have...
Ideally i need to create a proxy from the OnStartTetheringCallback class as seen in the android studio examples (https://stackoverflow.com/a/52219887) but the library doesnt appear to be available for xamarin. Please  Help!
public bool EnableTethering()
    {

        try
        {

            var context = Android.App.Application.Context;
            ConnectivityManager manager = ConnectivityManager.FromContext(context);

            var methods = manager.Class.GetDeclaredMethods()
                .Select(m => new KeyValuePair<Java.Lang.Reflect.Method, Java.Lang.Class[]>(m, m.GetParameterTypes()));
            var callbackClass = manager.Class.GetDeclaredClasses().First(c => c.Name == "android.net.ConnectivityManager$OnStartTetheringCallback");
            var method = methods.First(m => m.Key.Name == "startTethering").Key; //manager.Class.GetDeclaredMethod("startTethering");//, new Java.Lang.Class[] { classFromType<int>(), classFromType<bool>(), classOnStartTetheringCallback(), classFromType<Handler>() } );

            if (method == null)
            {
            }
            else
            {
                method.Invoke(manager, new Java.Lang.Object[] { 0, false, callbackClass });

            }
            return true;
        }
        catch (Exception e)
        {
        }
        return false;
    }

===================================================================================================
{Java.Lang.IllegalArgumentException: method android.net.ConnectivityManager.startTethering
argument 3 has type android.net.ConnectivityManager$OnStartTetheringCallback, got java.lang.Class<android.net.ConnectivityManager$OnStartTetheringCallback>
  at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <8b3b636835d84984ba4604c1f57b1983>:0
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeAbstractObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00014] in <8b3b636835d84984ba4604c1f57b1983>:0
  at Java.Lang.Reflect.Method.Invoke (Java.Lang.Object obj, Java.Lang.Object[] args) [0x0004b] in <84ca7e914f6148f0b961431a9ac4287b>:0
  at Millsnet.SpotUp.Services.WifiService.EnableTethering () [0x000af] in C:\Users\djmil\source\repos\Millsnet.SpotUp\Millsnet.SpotUp\Millsnet.SpotUp\Services\WifiService.cs:149
  --- End of managed Java.Lang.IllegalArgumentException stack trace ---
java.lang.IllegalArgumentException: method android.net.ConnectivityManager.startTethering argument 3 has type android.net.ConnectivityManager$OnStartTetheringCallback, got java.lang.Class<android.net.ConnectivityManager$OnStartTetheringCallback>
    at java.lang.reflect.Method.invoke(Native Method)
    at mono.java.lang.RunnableImplementor.n_run(Native Method)
    at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7711)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
}
===========================================================================================

A: I managed to resove this.
I compiled a xamarin library of LindeIn/DexMaker so now i can use the proxy maker.
https://github.com/djmillsuk/LinkedIn-DexMaker-Xamarin
I then targetted android 11 as the starttethering is not working on android 10.
it is now working perfectly.


text:
Q: Using AutoIt functions with Python I am new to using AutoIt, and I am trying to use it to automatically click buttons on Windows programs.  I have been able to access some functions using import win32com.client and win32com.client.Dispatch("AutoItX3.Control").
But I am wondering if anyone knows of another way of doing this without downloading something else.  The thing is, I had to download Pywin32 to do this.  Is there something within the native Python libraries that can use AutoIt or its COMs module to run the functions?

A: Probably, you can use ctypes. For example, follow code sends message Hello to active window:
from ctypes import windll
path = r"C:\Program Files\AutoIt3\AutoItX\AutoItX3.dll"
autoit = windll.LoadLibrary(path)
autoit.AU3_Send(u"Hello{!}", 0)

Also, you can run autoit scripts by using os.system or subprocess.call modules.
With os.system:
import os
os.system(r'lowerchange.au3')

With subprocess.call:
import subprocess
subprocess.call(['C:\Program Files\AutoIt3\AutoIt3.exe',r'lowerchange.au3'])


text:
Q: A good way to get Javascript Object from a page on button click in C# I have an asp:Button that gets clicked and does backend stuff (or I want to do back end stuff).
The issue is that i have a large javascript template block that I want to pass back into my code back end.
Is there a decent/good way to do this? Is there a way to grab the javascript block from the on click method in my code behind (mypage.aspx.cs)?

A: You could pop the json in a hidden field on button click using jquery and then retrieve it on the back end. You should parse the hidden fields value on the backed to a json object using something like json.net so you can play with the content http://james.newtonking.com/json
It will be something like the following
<asp:HiddenField runat="server" id="hfJson" />
<asp:Button ID="btnSubmit" runat="server" Text="Click me" OnClick="btnSubmit_Click"  />
<script>
    $(function () {
        $('#<%=btnSubmit.ClientID %>').click(function () {
            $('#<%=hfJson.ClientID %>').val(anArrayOfOptions);
        });
    });
</script>

Then in your code behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
    JObject anArrayOfOptions = JObject.Parse(hfJson.Value);
}

Hope that helps :)

A: I think you can use a textbox with visibility off. convert that object to json and keep it updated to that textbox. You can keep the updated the object manually or can use knockout.js
and onclick the form will automatically post the values to the server side, where you can use it.


text:
Q: Grayed out option in popupmenu I'm building an Eclipse plugin. When I right click on items in a table a popup menu with selections pops up. I want a certain selection to be grayed out if more than one items are selected. I have tried using enablesFor="1" in the action tag in my plugin.xml file.
<extension point="org.eclipse.ui.popupMenus">
     <objectContribution
            id="se.myproject.xxxxxx.ui.ReplaceItemAsReference"
            objectClass="se.xxxxx.xxxx.core.xxxxx.EntityItem">
         <action
               class="se.myproject.xxxxxx.ui.views.ReferenceAction"
               enablesFor="1"
               id="se.myproject.xxxxxx.ui.views.ReplaceItemAsReference"
               label="Do stuff"
               menubarPath="additions-ext">
         </action>
     </objectContribution>
</extension>

But it's not graying out the selection. I wonder if I have to do some additional coding to achieve this?
I want the result to look like this!

A: Looks like this may be an Eclipse bug. The 'Restore from Local History' popup menu item is declared in a similar way and also stays enabled for multiple selection.
Other menu items declared using '1' for enablesFor do work, the difference seems to be that they use the <menu> element to put the menu item in a sub-menu.


text:
Q: Open sidebar in Google App Script with parent menu I am trying to open sidebar in Google App Script with parent menu but without sub-menu.
but error coming Exception: Cannot call SlidesApp.getUi() from this context.
init.gs
function onOpen() {

  showSidebar();

  SlidesApp.getUi()
      .createMenu('Test Menu')
      .addItem('Add In', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('sidebar')
      .setTitle('My custom sidebar')
      .setWidth(300);
  SlidesApp.getUi()
      .showSidebar(html);
}

A: You should change createHtmlOutputFromFile method or create a sidebar.html
This is working correctly if you change the method. By using your code there should be 2 files.
code.gs
function onOpen() {
  SlidesApp.getUi()
      .createMenu('Test Menu')
      .addItem('Add In', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('sidebar')
      .setTitle('My custom sidebar')
      .setWidth(300);
  SlidesApp.getUi()
      .showSidebar(html);
}

sidebar.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />
  </body>
</html>

Otherwise you can directly define the HTML using the createHtmlOutput method.
code.gs
function onOpen() {
  SlidesApp.getUi()
      .createMenu('Test Menu')
      .addItem('Add In', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutput('Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />')
      .setTitle('My custom sidebar')
      .setWidth(300);
  SlidesApp.getUi()
      .showSidebar(html);
}

PoC


text:
Q: How to make the Title Heading H1 small in size in Generate Pro Genesis Theme for Wordpress I am using Generate Pro theme of Genesis and the biggest con about this theme is the size of the heading when seen in the Mobile. Also the Font.
As the users are shifting more on mobile, is very important for me to make my site look beautiful in Mobile.
What do I mean?
How Title Looks in the Mobile
As you can see it is taking up all the above(up-the-fold) content only for the heading.
All my Content shifts low and I have to scroll for seeing it. Which BTW nobody likes.
Also the Font-Looks Very Bad, it is really light in colour and most of the people have to focus high to see it.
I changed the font with the help of Google Font Plugin but still, the size of H1 is non-changeable, I tried Google Font and also tried changing code font-size in the WordPress but nothing helped. The code I tried changing looks like this.(Below)
h1,
h2,
h3,
h4,
h5,
h6 {
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 300;
    line-height: 1.2;
    margin: 0 0 20px;
}

h1 {
    font-size: 36px;
}

h2 {
    font-size: 30px;
}

h3 {
    font-size: 24px;
}

h4 {
    font-size: 20px;
}

h5 {
    font-size: 18px;
}

h6 {
    font-size: 16px;
}

A: Using @media CSS, you can do things like this:
@media screen and (max-width: 780px) {
  h1 {
    font-size: 25px;
  }

  /* More CSS */
}

A: As Chris mentioned, you can use media queries to make your styles have different behaviors depending on the size of the screen. Here are some examples:
/* Large Devices, Wide Screens */
    @media only screen and (max-width : 1200px) {

    }

    /* Medium Devices, Desktops */
    @media only screen and (max-width : 992px) {

    }

    /* Small Devices, Tablets */
    @media only screen and (max-width : 768px) {

    }

    /* Extra Small Devices, Phones */
    @media only screen and (max-width : 480px) {

    }

    /* Custom, iPhone Retina */
    @media only screen and (max-width : 320px) {

    }

Also, making more specific classes you will make the style has more importance. For example:
body .title h1 {}

will have more importance than:
 body h1

or
h1


text:
Q: Will a locally generated timestamp affect the utc offset and timezone when calling Google maps TimeZone from a different region? I'm using Google maps TimeZone API to get the timezone and utc offset for a location (lat/lng) in New York, London, Paris, Sydney.
Ex. https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810%2C-119.6822510&timestamp=1331161200&key=YOUR_API_KEY'
QUESTION - Will a locally generated timestamp (ex. San Francisco) change the utc offset or time zone for a different location lat/lng (ex. New York, London, Sydney, etc)?
I'm trying to understand the timestamp documentation, but I'm not that smart.

timestamp:

The desired time as seconds since midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied, based on the time zone of the location. Note that the API does not take historical time zones into account. That is, if you specify a past timestamp, the API does not take into account the possibility that the location was previously in a different time zone.

A: It does not matter where the timestamp is generated as long as it is "seconds since midnight, January 1, 1970 UTC".
For example, you can generate such timestamp in C# by -
DateTimeOffset.Now.ToUnixTimeSeconds()

This line of code will return you same number regardless of your machine's timezone, because it is the number of seconds elapsed since a particular time - 1/1/1970 UTC.


text:
Q: Relative paths in WCF service hosted in IIS I'm throwing together a quick data service in WCF to be accessed by a public Silverlight 2.0 application.   As my data is very static and relatively simple I'd like to just store it in local XML files (which is made easier as there are a VERY limited number of people who will ever edit it).
I'm wondering what the best way to find a relative path from within my service will be.  In traditional ASP.NET I could use the Server.MapPath....within this WCF service nothing similar is available.  This solution will ultimately be hosted at a hosting provider I have no control over so I can't hardcode any fixed locations.  I'd much rather just get a relative path to some XML files in my AppData folder.
Any suggestions?

A: Try using HostingEnvironment.ApplicationPhysicalPath.

A: The WCF services still have access to a lot of the same things as your ASP.NET pages (since, in the end there is still an HTTP request and response).  You can still use Server.MapPath like so:
HttpContext.Current.Server.MapPath(...)

A: You could try using Environment.CurrentDirectory or AppDomain.CurrentDomain.BaseDirectory

A: You could store the files in IsolatedStorage instead of in your folder for the application. Look at the example on the linked page to see how it works.

A: First, add an operation to the service to return the current directory. Have the new operation just return Environment.CurrentDirectory. In the client, check to see if you are surprised by what the current directory was. Adjust as needed.


text:
Q: Implementing transition tables as threads I doing implementation of
FSSP.
I want for each thread to represent a soldier, so my question is what most efficient and readable way to implement transition tables of soldiers in c?
I was thinking about 3 dimensional array, but maybe there is a better solution.
Here example of transition tables:

Many thanks!


text:
Q: JavaScript While Loop Not Looping Fully I'm trying to do a while loop with the conditions that the number is lower than 5, and it's divisible by 3 and 5.
Here's my code:
    var beginningNumber = 5;

    while (beginningNumber <= 50 && beginningNumber % 5 === 0 && beginningNumber % 3 === 0) {
      console.log(beginningNumber);
      beginningNumber++;
}

My console log isn't typing out anything.  I've checked if I can use multiple operators in a while loop I can.  I'm not sure what's happening.  What's the issue?

A: beginningNumber % 3 === 0 is not true for 5.

var beginningNumber = 15;
while (beginningNumber <= 50 && beginningNumber % 5 === 0 && beginningNumber % 3 === 0) {
  console.log(beginningNumber);
  beginningNumber++;
}

Set it to something like 15 and it'll work... once, because then it'll become 16.
What you probably are looking for is something like this:

var beginningNumber = 5;
while (beginningNumber <= 50) {
  if (beginningNumber % 5 === 0 && beginningNumber % 3 === 0) {
    console.log(beginningNumber);
  }

  beginningNumber++;
}

This will let you loop through all the numbers from 5 to 50, and output each number that meets the conditions.

A: Your condition is never being fulfilled five is not divisible by 3 so the loop is never run. Have you considered using a for loop for this and doing an if statement in a condition

for (var beginningNumber = 5; beginningNumber <= 50; beginningNumber++) {
  if (beginningNumber % 5 === 0 && beginningNumber % 3 === 0) {
    console.log(beginningNumber);
  }
}


text:
Q: How do we know fusion energies? Crucial to our understanding of stellar evolution is the energies involved in nuclear fusion reactions.
How do we know those energies? How do we know which fusion reactions take place, at which energies, and which is exothermic or endothermic? Have we been able to actually conduct these reactions in accelerators (or some other apparatus)? Or does our knowledge of these energies come from theoretical considerations? Or both?
And what theory tells us what the fusion energies will be?

A: The overall energy yield of the reactions is not so difficult to measure - it simply amounts to measuring the masses of the nuclei and using the Einstein $E = mc^2$ formula - subtract the mass of the nucleus from the sum of masses of protons and and neutrons within it and that is your binding energy. Experimentally this is done using the methods of mass spectrometry. In the end, you get a fully empirical plot for binding energies that looks like this

(Source: wiki)
The measurement of fusion cross-section is much more involved, though. On a theoretical level we know that the two ions need to 1) get over the Coulombic barrier (imagine two positively charged balls trying to hit each other), 2) not to "tunnel through one another" (this has to do with quantum mechanics and their DeBroglie wavelength), and 3) overcome certain finer barriers on a nuclear-nuclear level. From that, first models that will give you correct ballpark numbers for cross-sections can be formulated. However, in a real plasma you also have to account for other effects such as screening by electrons.
Information can also be gained from well understood astrophysical objects such as the Sun and solar neutrinos, whose rates and energies, along with high-fidelity models of the solar interior, constrain fusion cross-sections of light elements. Another interesting example of nuclear physics getting information from astrophysics is Fred Hoyle's 1953 prediction that there must be an additional resonant channel for the fusion of Carbon, because otherwise it would not be so abundant.
Other information can be gleaned from particle-collider experiments. If you take a beam of ions, sufficiently accelerate it with an electrostatic potential, and hit a target or another beam, it is not too hard to reach fusion energies or at least energies that constrain the interaction model even in a medium-sized lab. (What is difficult is translating the results of these experiments into reliable fusion rates/cross-sections.)

A:
How do we know those energies?

Thanks to Rutherford's lab. In 1934 a group led by Mark Oliphant shot protons at lithium foils, to which they later added deuterium from heavy water. Every so many million of such shots would result in a high-energy alpha, which they could see on a screen. By varying the driving voltage and measuring the output energy they could calculate both the threshold energy (the Coulomb barrier) and the resulting energy release of the reaction. This work revealed the isotopes of hydrogen.
Variations on this basic theme have been used continually since then, to test different fusion cycles and refine the measurements. This was a particularly active field in the 1970s.


text:
Q: JavaFX Button visible if number<0 I want to bind a Button visible property so the Button will  be visible when ListNumber is <0.The ListNumber is an int.
I have and one other which similarly i want to be visible if ListNumber<500;
I am searching in Bindings class for a good method but most methods require ObservableNumberValue interface.
I don't want to make ListNumber an IntegerProperty.

A: Don't see any problems making int an IntegerProperty. What do you think encapsulation is for? You can implement it like this:
public class Model {

    private IntegerProperty listNumber = new SimpleIntegerProperty();

    public int getListNumber() {
        return listNumber.get();
    }

    public IntegerProperty listNumberProperty() {
        return listNumber;
    }

    public void setListNumber(int listNumber) {
        this.listNumber.set(listNumber);
    }
}

Than bind it to your buttons:
Button button = new Button("I'm a Button!");
button.visibleProperty().bind(Bindings.lessThan(0, model.listNumberProperty()));

And in all other places just use this property as an int:
int value = model.getListNumber();

Even if you are using listNumber as some static variable, nothing prevents you from wrapping it with a static getter. I think every IDE has replace/refactor functionality, so changing ListNumber to getListNumber() can be done in no time.


text:
Q: Should I have unit tests for known defects? If my code contains a known defect which should be fixed, but isn't yet, and won't be fixed for the current release, and might not be fixed in the forseeable future, should there be a failing unit test for that bug in the test suite? If I add the unit test, it will (obviously) fail, and getting used to having failing tests seems like a bad idea. On the other hand, if it is a known defect, and there is a known failing case, it seems odd to keep it out of the test suite, as it should at some point be fixed, and the test is already available.

A: I think you should have an unit test with the current behaviour and in the comments, add the right test and right behaviour. Example:
@Test
public void test() {
  // this is wrong, it should be fixed some time
  Assert.assertEquals(2, new Calculator().plus(2,2));
  // this is the expected behaviour, replace the above test when the fix is available
  // Assert.assertEquals(4, new Calculator().plus(2, 2));
}

This way, when the fix is available, the build will fail, noticing you the failed test. When you'll look at the test, you will know that you changed the behaviour and the test must be updated.
EDIT:
As Captain Man said, in large projects, this will not get fixed anytime soon but for the documentation sake, the original answer is better than nothing.
A better way to do it is duplicating the current test, making the clone assert the right thing and @Ignore it with a message, e.g.
@Test
public void test() {
  Assert.assertEquals(2, new Calculator().plus(2,2));
}

@Ignore("fix me, Calculator is giving the wrong result, see ticket BUG-12345 and delete #test() when fixed")
@Test
public void fixMe() {
  Assert.assertEquals(4, new Calculator().plus(2, 2));
}

This comes with the convention in your team to reduce the number of @Ignored tests. The same way you'd be doing with introducing or changing the test to reflect the bug, except you don't fail the build if this is critical for your team, like OP said that the bugfix won't be included in the current release.

A: The answer is yes, you should write them and you should run them.
Your testing framework needs a category of "known failing tests" and you should mark these tests as falling into that category. How you do that depends on the framework.
Curiously, a failing test that suddenly passes can be just as interesting as a passing test that unexpectedly fails.

A: Depending on the test tool you may use an omit or pend function.
Example in ruby:
gem 'test-unit', '>= 2.1.1'
require 'test/unit'

MYVERSION = '0.9.0' #Version of the class you test

class Test_omit < Test::Unit::TestCase
  def test_omit
    omit('The following assertion fails - it will be corrected in the next release')
    assert_equal(1,2)
  end

  def test_omit_if
    omit_if(MYVERSION < '1.0.0', "Test skipped for version #{MYVERSION}")
    assert_equal(1,2)
  end

end

The omit command skips a test, the omit_if combines it with a test - in my example I test the version number and execute the test only for versions where I expect the error is solved.
The output of my example is:
Loaded suite test
Started
O
===============================================================================
The following assertion fails - it will be corrected in the next release [test_omit(Test_omit)]
test.rb:10:in `test_omit'
===============================================================================
O
===============================================================================
Test skipped for version 0.9.0 [test_omit_if(Test_omit)]
test.rb:15:in `test_omit_if'
===============================================================================

Finished in 0.0 seconds.

2 tests, 0 assertions, 0 failures, 0 errors, 0 pendings, 2 omissions, 0 notifications
0% passed

So my answer: Yes, implement the test. But don't confuse a tester with errors, where you know it will fail.

A: If the bug is fresh in your mind and you have the time to write the unit test now, then I would write it now and flag it as a known failure so it doesn't fail the build itself. Your bug tracker should be updated to reflect that there is a unit test that is currently failing for this bug so that the person assigned to eventually fix it doesn't write it all over again. This supposes that the buggy code doesn't need a lot of refactoring and that the API changes significantly -- if that's the case then you might be better off not writing the unit test until you have a better idea of how the test should be written.

A: The answer is NO IMHO.
You should not add a unit test for the bug until you start working on the fix for the bug and than you will write the test(s) that proves the bug and when that test(s) is failing in accordance to the bug report(s) you will go and correct the actual code to make the test(s) pass and the bug will be solved and it will be covered after that.
In my world we would have a manual test case that the QEs have failing until the bug gets fixed. And us as developers would be aware of it via the manual failing TC and via the bug tracker.
The reason for not adding failing UTs is simple. UTs are for direct feedback and validation of what I as a developer are currently working. And UTs are used in the CI system to make sure I didn't break something unintentionally in some other area of code for that module. Having UTs failing intentionally for a know bug IMHO would be counter productive and just plain wrong.

A: I suppose the answer really is, it depends. Be pragmatic about it. What does writing it now gain you? Maybe it is fresh in your mind?
When fixing the bug, it makes perfect sense to prove it exists by writing a unit test that exposes the bug. You then fix the bug, and the unit test should pass.
Do you have time to write the failing unit test just now? Are there more pressing features or bug that need to be written/fixed.
Assuming you have competent bug tracking software with the bug logged in it, there is really no need to write the failing unit test right now.
Arguably you might introduce some confusion if you introduce a failing unit test before a release that is happening without the bug fix.

A: I usually feel uneasy about having known failures in test suites, because it's too easy for the list to grow over time, or for unrelated failures in the same tests to be dismissed as "expected". The same things goes for intermittent failures - there could be something evil lurking the code. I'd vote for writing the test for the code as it is now, and as it should be once it's fixed but commented out or disabled somehow.