text:
Q: Associate specific file extensions with my delphi app - any library for this? So far if I had to associate the file extension with my application I used to simply modify the registry. However I haven't been doing it for years, and I'm afraid the things might have changed a bit. I have no idea how to prevent registry access restrictions in Windows 7 / Vista (if there are any for HKEY_CLASSES_ROOT). Thus I'm looking for some delphi library, unit, code snippet or whatever which works reliably under XP, Vista and 7.
Is there any which handles "backup" as well? By backup I mean possibility to revert the changes to the previous association...

A: I would recommend against using a 3rd-party component for this, for it will only make things more complicated.
We all know how to make file associations by editing the HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE hives, right? In Windows Vista+, editing the former implies no trouble, but if you for some reason want to edit the latter, i.e. if you want to edit the associations for all users on the machine, then your app needs to run with elevated privileges.
To make an application run with elevated privileges, the user can right-click the icon and select "Run as administrator". But that is ugly. One can, however, make an application run as administrator automatically, simply by adding a manifest (an XML file) to the application's resource. Then the UAC prompt will popup automatically upon execution of the *.exe file, no matter how the end user starts the program, and the program will be run as an administrator, and is perfectly able to alter the HKEY_LOCAL_MACHINE hive. The details on how to add this manifest has been explain in several SO questions. It really is easy.
As far as I know, it is not possible for a running application to "upgrade" its privileges at runtime. So if you have a button in your app, running with normal privileges, you cannot do something like this:
procedure Button1.Click(Sender: TObject);
begin
  SomehowGetAdminPrivileges;
  ChangeLocalMachineRegistry;
  SomehowGetBackNormalPrivileges;
end;

That is simply not possible. So if you need to do something that requires admin privileges during runtime, you need to call an external application, as in
procedure Button1.Click(Sender: TObject);
begin
  ShellExecute(Application.Handle, nil, PChar('myapp.exe'), nil, nil, SW_SHOWNORMAL);
end;

myapp.exe needs to have a manifest, so that it will run with raised privileges, and is able to do what you want. But preferably myapp.exe should not have a GUI - when the user clicks the button, the UAC prompt appears, and the the myapp.exe performs the registry change and then terminates.
It would be possible but awkward to accomplish this using a 3rd-party component.
Do you need to change the registry during setup? If you use Inno Setup, the professional and free tool, Inno Setup will include the manifest for you. Hence the UAC prompt will appear when starting setup.exe (compiled with Inno Setup) if the setup requires it, e.g. if the setup will make any changes to HKEY_LOCAL_MACHINE.


text:
Q: Galois group of $X^5 - X^3 - 2X^2 - 2X - 1$ over $\mathbb{Q}$. So far I have found that this polynomial is irreducible, and its discriminant is a square. Therefore the Galois group it a transitive subgroup of $A_5$.
I found out that the only transitive subgroups in $A_5$ are $A_5$ and $D_{10}$. Is there a way to tell the Galois group from these two possibilities?

A: $C_5$ is also a transitive subgroup of $A_5$, but yes, the discriminant is a square, so you know it must be $A_5$, $C_5$, or $D_{10}$.
Factoring over small prime numbers can give an idea of the structure of the Galois group. For example, $f(x)=x^5-x^3-2x^2-2x-1=(x+4)(x^2+3)(x^2+x+2)$ over $\mathbb{F}_5$, which instantly rules out $C_5$.
To decide between $A_5$ and $D_{10}$, recall that the Galois group of $f$ permutes its roots. Let $\alpha_1,\dots,\alpha_5$ be the roots of $f$, and consider the connected pentagon with the roots at each vertex:
$\hskip1.7in$
Then we can look at the geometric effect of each subgroup on the roots. In particular, we look at the resolvent. Now calculating the resolvent does require knowing something about the roots of $f$ to some precision, but letting $\alpha_1,\dots,\alpha_5$ be the roots of $f$ we define the resolvent to be:
$$
p(x)=\prod_{1\le i,j\le 5}(x-(\alpha_i+\alpha_j))
$$
Then the roots of $p$ represent the ten edges of the connected pentagon, and in fact, $p$ has the same Galois group as $f$ (it's a separable polynomial over $\mathbb{Q}$ with the same splitting field), but exhibits much nicer qualities.
Alternatively, you can simplify the quintic into Bring-Jerrard form, say $g(x)=x^5+ax+b$, and then the resolvent can be written succinctly as:
$$
p(x)=x^{10}-3ax^6-11bx^5-4a^2x^2+4abx-b^2
$$
$A_5$ is the group of even permutations, and is generated by $\sigma_1=(1,2,3,4,5)$ and $\sigma_2=(1,2,3)$. If $\sigma_2$ acts on $\alpha_1,\dots,\alpha_5$, then only one of the edges of the pentagon can be fixed. By applying $\sigma_1$ before $\sigma_2$, we can change the edge that is fixed. Also note that all the edges of the connected pentagon can permute with one another, so $A_5$ is made up of a single orbit, and $p$ is irreducible over $\mathbb{Q}$.
$D_{10}$ is made up of the 5 rotations and 5 reflections of the pentagon, so the Galois group of $p$ should be made up of two orbits of length $5$: one for the rotations, and a second for the reflections. So $p$ should factor into two irreducible polynomials of degree $5$.

In your case, either approximating the roots of $f$ and calculating the resolvent, or reducing to Bring-Jerrard form and using the formula above, you'll see that it factors into two irreducible factors of degree $5$, and so the Galois group is $D_{10}$.

You could verify this with the following Maple code:
    galois(x^5-x^3-2*x^2-2*x-1);

This will give the following output:
    "5T2", {"5:2", "D(5)"}, "+", 10, {"(1 2 3 4 5)", "(1 4)(2 3)"}

So the Galois group is indeed $D_{10}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generating HTTP errors using Fat-Free-Framework I am using fat-free framework for my Rest API. I have a unique constraint on one of my database field. My question is how can i trigger a proper HTTP error based on mysql duplicate entry error.
Following is my insert function
    $username = $f3->get('username');
    $status=$GLOBALS['db']->exec('INSERT INTO Users
                     VALUES(:userID,:username)',
                     array(':userID'=>'',':username'=>$username));

    header('Content-Type: application/json');
    return (json_encode($status));

My insert statement triggers following error based on unique constraint on field
Internal Server Error
PDOStatement: Duplicate entry 'someUserName' for key 'username'

I want to trigger HTTP error because on the client side i can handle HTTP errors.
Please guide me.

A: You can use a try / catch statement and call $f3->error('400','MSG') to send one of your favorite http status codes and trigger the ONERROR handler,
If you like to only send the status code header, you can use the $f3->status method

A: Try to see this documntation : http://fatfreeframework.com/framework-variables#about-the-f3-error-handler


text:
Q: Default + Zones Show Up in Check out??? - Woocommerce Custom Shipping Method Plugin I've built my first shipping method plugin based on flat rate with a few extra fields.
I have done the following:
1. Installed and activated the plugin
2. Added 2 instances of the shipping method to the UK zone
I can see in the top sub menu in the shipping section there appears to be some kind of "default" instance of the shipping plugin in a menu labelled "UK Flat Rate"
I was wondering if there's a way to remove this and ONLY have the plugin work in the shipping zones section.
The reason I ask is that then in checkout if I enter a UK address I see the 2 UK methods defined and then underneath them both there is also a radio button for UK Flat Rate which I'm trying to get rid of. It shows the default values based on the values entered in the sub-section.
if (!defined('ABSPATH')) {
exit;
}

if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
add_action( 'woocommerce_shipping_init', 'uk_shipping_method');
function uk_shipping_method() {
    if (!class_exists('UK_WC_Shipping_Flat_Rate')) {
    class UK_WC_Shipping_Flat_Rate extends WC_Shipping_Method {

        /** @var string cost passed to [fee] shortcode */
        protected $fee_cost = '';

        /**
         * Constructor.
         *
         * @param int $instance_id
         */

        public function __construct($instance_id = 1) {
            $this->id                    = 'uk_flat_rate';
            $this->instance_id           = absint($instance_id);
            $this->enabled            = "yes"; // This can be added as an setting but for this example its forced enabled
            $this->method_title          = __('UK Flat Rate');
            $this->title          = 'UK Flat Rate';
            $this->method_description    = __('Lets you charge a fixed rate for shipping but flags for UK Status Update.');
            $this->supports              = array(
                'shipping-zones',
                'instance-settings',
                'instance-settings-modal',
            );
            $this->init();

            add_action('woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options'));
        }

        /**
         * init user set variables.
         */
        public function init() {
            $this->instance_form_fields = include('includes/settings-flat-rate.php');
            $this->title                = $this->get_option( 'title' );
            $this->tax_status           = $this->get_option( 'tax_status' );
            $this->cost                 = $this->get_option( 'cost' );
            $this->type                 = $this->get_option( 'type', 'class' );
        }

        /**
         * Evaluate a cost from a sum/string.
         * @param  string $sum
         * @param  array  $args
         * @return string
         */
        protected function evaluate_cost( $sum, $args = array() ) {
            include_once( WC()->plugin_path() . '/includes/libraries/class-wc-eval-math.php' );

            // Allow 3rd parties to process shipping cost arguments
            $args           = apply_filters( 'woocommerce_evaluate_shipping_cost_args', $args, $sum, $this );
            $locale         = localeconv();
            $decimals       = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'], ',' );
            $this->fee_cost = $args['cost'];

            // Expand shortcodes
            add_shortcode( 'fee', array( $this, 'fee' ) );

            $sum = do_shortcode( str_replace(
                array(
                    '[qty]',
                    '[cost]',
                ),
                array(
                    $args['qty'],
                    $args['cost'],
                ),
                $sum
            ) );

            remove_shortcode( 'fee', array( $this, 'fee' ) );

            // Remove whitespace from string
            $sum = preg_replace( '/\s+/', '', $sum );

            // Remove locale from string
            $sum = str_replace( $decimals, '.', $sum );

            // Trim invalid start/end characters
            $sum = rtrim( ltrim( $sum, "\t\n\r\0\x0B+*/" ), "\t\n\r\0\x0B+-*/" );

            // Do the math
            return $sum ? WC_Eval_Math::evaluate( $sum ) : 0;
        }

        /**
         * Work out fee (shortcode).
         * @param  array $atts
         * @return string
         */
        public function fee( $atts ) {
            $atts = shortcode_atts( array(
                'percent' => '',
                'min_fee' => '',
                'max_fee' => '',
            ), $atts, 'fee' );

            $calculated_fee = 0;

            if ( $atts['percent'] ) {
                $calculated_fee = $this->fee_cost * ( floatval( $atts['percent'] ) / 100 );
            }

            if ( $atts['min_fee'] && $calculated_fee < $atts['min_fee'] ) {
                $calculated_fee = $atts['min_fee'];
            }

            if ( $atts['max_fee'] && $calculated_fee > $atts['max_fee'] ) {
                $calculated_fee = $atts['max_fee'];
            }

            return $calculated_fee;
        }

        /**
         * calculate_shipping function.
         *
         * @param array $package (default: array())
         */
        public function calculate_shipping( $package = array() ) {
            $rate = array(
                'id'      => $this->get_rate_id(),
                'label'   => $this->title,
                'cost'    => 0,
                'package' => $package,
            );

            // Calculate the costs
            $has_costs = false; // True when a cost is set. False if all costs are blank strings.
            $cost      = $this->get_option('cost');

            if ( '' !== $cost ) {
                $has_costs    = true;
                $rate['cost'] = $this->evaluate_cost( $cost, array(
                    'qty'  => $this->get_package_item_qty( $package ),
                    'cost' => $package['contents_cost'],
                ) );
            }

            // Add shipping class costs.
            $shipping_classes = WC()->shipping->get_shipping_classes();

            if ( ! empty( $shipping_classes ) ) {
                $found_shipping_classes = $this->find_shipping_classes( $package );
                $highest_class_cost     = 0;

                foreach ( $found_shipping_classes as $shipping_class => $products ) {
                    // Also handles BW compatibility when slugs were used instead of ids
                    $shipping_class_term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
                    $class_cost_string   = $shipping_class_term && $shipping_class_term->term_id ? $this->get_option( 'class_cost_' . $shipping_class_term->term_id, $this->get_option( 'class_cost_' . $shipping_class, '' ) ) : $this->get_option( 'no_class_cost', '' );

                    if ( '' === $class_cost_string ) {
                        continue;
                    }

                    $has_costs  = true;
                    $class_cost = $this->evaluate_cost( $class_cost_string, array(
                        'qty'  => array_sum( wp_list_pluck( $products, 'quantity' ) ),
                        'cost' => array_sum( wp_list_pluck( $products, 'line_total' ) ),
                    ) );

                    if ( 'class' === $this->type ) {
                        $rate['cost'] += $class_cost;
                    } else {
                        $highest_class_cost = $class_cost > $highest_class_cost ? $class_cost : $highest_class_cost;
                    }
                }

                if ( 'order' === $this->type && $highest_class_cost ) {
                    $rate['cost'] += $highest_class_cost;
                }
            }

            // Add the rate
            if ( $has_costs ) {
                $this->add_rate( $rate );
            }

            /**
             * Developers can add additional flat rates based on this one via this action since @version 2.4.
             *
             * Previously there were (overly complex) options to add additional rates however this was not user.
             * friendly and goes against what Flat Rate Shipping was originally intended for.
             *
             * This example shows how you can add an extra rate based on this flat rate via custom function:
             *
             *      add_action( 'woocommerce_flat_rate_shipping_add_rate', 'add_another_custom_flat_rate', 10, 2 );
             *
             *      function add_another_custom_flat_rate( $method, $rate ) {
             *          $new_rate          = $rate;
             *          $new_rate['id']    .= ':' . 'custom_rate_name'; // Append a custom ID.
             *          $new_rate['label'] = 'Rushed Shipping'; // Rename to 'Rushed Shipping'.
             *          $new_rate['cost']  += 2; // Add $2 to the cost.
             *
             *          // Add it to WC.
             *          $method->add_rate( $new_rate );
             *      }.
             */
            do_action( 'woocommerce_' . $this->id . '_shipping_add_rate', $this, $rate );
        }

        /**
         * Get items in package.
         * @param  array $package
         * @return int
         */
        public function get_package_item_qty( $package ) {
            $total_quantity = 0;
            foreach ( $package['contents'] as $item_id => $values ) {
                if ( $values['quantity'] > 0 && $values['data']->needs_shipping() ) {
                    $total_quantity += $values['quantity'];
                }
            }
            return $total_quantity;
        }

        /**
         * Finds and returns shipping classes and the products with said class.
         * @param mixed $package
         * @return array
         */
        public function find_shipping_classes( $package ) {
            $found_shipping_classes = array();

            foreach ( $package['contents'] as $item_id => $values ) {
                if ( $values['data']->needs_shipping() ) {
                    $found_class = $values['data']->get_shipping_class();

                    if ( ! isset( $found_shipping_classes[ $found_class ] ) ) {
                        $found_shipping_classes[ $found_class ] = array();
                    }

                    $found_shipping_classes[ $found_class ][ $item_id ] = $values;
                }
            }

            return $found_shipping_classes;
        }
    }
}

    function add_uk_shipping_method( $methods ) {
        $methods['uk_flat_rate'] = 'UK_WC_Shipping_Flat_Rate';
        return $methods;
    }

    add_filter( 'woocommerce_shipping_methods', 'add_uk_shipping_method' );
}
}

Is there a setting in the plugin I'm missing to enforce the method is only zones based?

A: Turns out I needed to add filters to remove the section and the first instance of the method from shipping like so
woocommerce_shipping_option_remove( $section ) {
    unset($section['uk_flat_rate']);
    return $section;
}

add_filter( 'woocommerce_get_sections_shipping', 'woocommerce_shipping_option_remove' ,1 );
function woocommerce_shipping_remove_method( $rates )
{
    unset($rates['uk_flat_rate:1']);
    return $rates;
}

add_filter('woocommerce_package_rates','woocommerce_shipping_remove_method', 100 );
         }
    }


text:
Q: Stripping \r\n from a line I want to strip the ending \r\n for a line, examples of the line:
abc \r\n
abc \r
abc \n

I want it to remain as
   "abc "
what I do now
line=line.strip('\n')
line=line.strip('\r')
line=line.strip('\n')

is there a better way to achieve this?

A: Use one str.strip() call:
line = line.strip('\r\n')

This removes both characters, in whatever order. The argument to str.strip() is treated as a set of characters, not one longer string:
>>> 'foo bar\r\n\n\r\n\r\n\r\r\r'.strip('\r\n')
'foo bar'

Since you'd expect these lines to only have the characters at the end of each line, you can limit the stripping work to just that side with str.rstrip:
line = line.rstrip('\r\n')

A: If the line is ending with \r\n you can strip-right.
line = line.rstrip(' \r\n')


text:
Q: the max function requires 1 argument(s) I wrote this very simple SP in SQL 2008:
Create procedure dbo.GetNextID
(
    @TableName nvarchar(50),
    @FieldName nvarchar(50)
)
AS
    BEGIN
        exec('select isnull(max('+@FieldName+'),0)+1 as NewGeneratedID from '+ @TableName);
    END

When I execute this procedure in Visual Studio SQL Express and pass a table name and a field name, it works fine. But when I try to add this SP as a query in a QueryTableAdapter in my ADO DataSet, I receive this error before clicking on Finish button:
the max function requires 1 argument(s)
can anyone help me with this?

A: I guess that VS tries to determine a field list by executing the SP. But as it does not know what to pass to the SP, it uses empty parameters. Now, of course, your select statement fails.
You could try adding the following to your SP:
IF ISNULL(@TableName,'') = '' SET @TableName = '<Name of a test table>';
IF ISNULL(@FieldName,'') = '' SET @FieldName = '<Name of some field>';

Use the names of some field and table that do exist here (for example names that you'd use from your application, too).
Alternatively you could add the following above the exec:
IF (ISNULL(@TableName, '') = '') OR (ISNULL(@FieldName, '') = '')
BEGIN
    SELECT -1 AS NewGeneratedId
    RETURN 0
END

EDIT
On a side note, I'd like to warn you about concurrency issues that I see coming up from what your code does. If this code is supposed to return a unique ID for a new record in some table, I'd redesign this as follows:
Create a table NumberSeries where each row contains a unique name, a possible range for IDs and the current ID value.
Create a stored procedure that uses UPDATE ... OUTPUT to update the current ID for a number series and retrieve it in one step.
That way you can make sure that creating a new ID is a single operation that does not cause concurrency problems.


text:
Q: How to synchronise Access database with SQL Server,changes made in access database should reflect in SQL server database How to synchronise Access database with SQL Server, so that changes made in access database should reflect in SQL server database. Provided that the front end is Vb6.

A: There is no easy way. You have to:

*

*add checksum colon in every table

*calculate checksum in Access table for new & changed records

*update changed records (existing key, different checksum)

*add new records (non-existing keys)

at 1. VB6 doesn't have any checksum function. At internet are tons of VB6 checksum functions, find one and implement. Data type with more bytes is better. Hint: join all values in record in a string (something like CSV) and calculate checksum for this string.
at 2. The correct way is calculate checksum in change/new record event in your application. Less correct, but possible, is calculate checksum just before synchronisation (it depends on quantity of records and so on).
Note: Great checksum function in SQL Server is fn_repl_hash_binary. The result you can convert in uniqueidentifier type (number / Replication ID in Access). In this case you should calculate checksum by SQL server via Linked server just before synchronisation.
 SELECT CONVERT(uniqueidentifier, master.sys.fn_repl_hash_binary(@whatever))

at 3. and 4. There are some ways, how to use mdb from SQL Server. Choose the best for you.

*

*Linked servers (Note you need an extra permission, see sp_configure 'Ad Hoc Distributed Queries', 1)

*OPENROWSET and OPENDATASOURCE

*and, off course, process record by record in your VB6 application. Horrible way.


text:
Q: Error on adding action to UIButton with selector I'm trying to add an event to a UIbutton:
UIButton *btn = [[UIButton alloc] init];
[btn setBackgroundImage:[UIImage imageNamed:@"aa.png"]
     forState:UIControlStateNormal];

[btn addTarget:self
     action:@selector(Presed:)];

and I'm getting this warning :
"UIButtom may not respond to addTarget:action"

The interface I'm creating this button for inherits from CDVPlugin
what's wrong with my code?

A: you are calling a method that is not declared.
it should be.
– addTarget:action:forControlEvents:
[btn addTarget:self action:@selector(Presed:)
forControlEvents:UIControlEventTouchUpInside];


text:
Q: Even function of a graph with local maximum at x-axis but no local minima I am having some problems with this question.
Question
Give a possible equation of a function that:

*

*has a single local maximum, located at the x-axis,

*has no local minima,

*is an even function, and

*has $\mathbb R$ for domain and range $[-5, \infty)$
Attempt
I cannot fathom how a graph can have a local maximum at the x-axis but with a range of [-5, infinity).
Initially I thought it can be a quadratic curve with the vertex at the x-axis and opens downwards. However, the range would then by [0,-infinity). So a quadrative curve does not seem possible.
I mean, how can a function with a local maximum at the x-axis have a range of [-5, infinity)? Did I miss out something? Any other functions that I have missed out? Does such a function exist?

A: This is not possible. As the range of the map $f$ is $[-5, \infty)$, it exists $a \in \mathbb R$ such that $-5=f(a) \le f(x)$ for all $x \in \mathbb R$. Therefore $f$ has a local minimum at $a$. In contradiction which the second requested point.


text:
Q: Import RDS file from github into R Windows I am trying to import a RDS file into RStudio in Windows, I tried following this example, which is for Rdata, and I tried both methods:
Method 1:
githubURL <- ("https://github.com/derek-corcoran-barrios/LastBat/blob/master/best2.My.Lu2.rds")
BestMyyu <- readRDS(url(githubURL))

Method 2:
githubURL <- ("https://github.com/derek-corcoran-barrios/LastBat/blob/master/best2.My.Lu2.rds")
download.file(githubURL,"best2.My.Lu2.rds")
BestMyyu <- readRDS("best2.My.Lu2.rds")

I've looked for other threads and I have not found any other example

A: In 2nd method you just need to add method="curl" and also change the url to point to raw (Download link on the page)
githubURL <- ("https://raw.githubusercontent.com/derek-corcoran-barrios/LastBat/master/best2.My.Lu2.rds")
download.file(githubURL,"best2.My.Lu2.rds", method="curl")
BestMyyu <- readRDS("best2.My.Lu2.rds")

If you don't have curl installed, you can get it from here


text:
Q: defining same elements in X macro C I have been exploring X macro and I created this table
#define FAULT_TABLE(FAULT) \
FAULT(INVALID,                            FAULT_CATEGORY_NONE, action_none) \
FAULT(COMMS_FAILURE,                       FAULT_CATEGORY_1, action_1) \
FAULT(QUEUE_FAILURE,                        FAULT_CATEGORY_1, action_1) \
FAULT(SENSOR_FAILURE,                FAULT_CATEGORY_1, action_1) \
FAULT(FAILED_OP                     FAULT_CATEGORY_1, action_1)

I just wanted to know if I can have same values and generate an enum out of it . I meant the enum out of 2nd column in the table .
And how do I assign the same function call to the fault codes above
Update
Just to add more clarity and context: When any of these fault is reported , my fault handler would be looking at the category and function to execute . Some faults have the same action and belong to same category . So I am trying to figure if this can be done through X macro .
So I just want enum to expanded as
typedef enum {
FAULT_CATEGORY_NONE,
FAULT_CATEGORY_1,
FAULT_CATEGORY_N,
}

Also I would the functions defined in table to expanded as Jump table.

A:
I just wanted to know if I can have same values and generate an enum out of it . I meant the enum out of 2nd column in the table .

You cannot duplicate enum constants, but you can give different enum constants the same value.  So, for example, you could do this:
#define FAULT_CATEGORY_NONE 0
#define FAULT_CATEGORY_1 1

#define FAULT_TABLE(FAULT) \
FAULT(INVALID,                            FAULT_CATEGORY_NONE) \
FAULT(COMMS_FAILURE,                       FAULT_CATEGORY_1) \
FAULT(QUEUE_FAILURE,                        FAULT_CATEGORY_1) \
FAULT(SENSOR_FAILURE,                FAULT_CATEGORY_1) \
FAULT(FAILED_OP,                     FAULT_CATEGORY_1)

#define FAULT(x, y) x ## _CAT = (y),

enum category {
FAULT_TABLE(FAULT)
DUMMY_CAT
};

That expands to
enum category {
    INVALID_CAT = (0),        COMMS_FAILURE_CAT = (1), QUEUE_FAILURE_CAT = (1),
    SENSOR_FAILURE_CAT = (1), FAILED_OP_CAT = (1),     DUMMY_CAT
};

(extra whitespace added for clarity).
But I don't see how X macros are actually helping you there.  In particular, it's suspicious that you present a different definition of FAULT_TABLE for the sub-question about assigning functions.
The X macro approach provides some traction when you can re-use the same list (FAULT_TABLE, here) for multiple definitions of X (FAULT).  Your example does not appear to be well suited to that, however, as each use appears to require the list to provide different data.  I guess you could cram it all into the same list by relying on FAULT to accept an additional parameter, but you would probably be better off just creating regular tables.  For example:
enum fault {
    INVALID, COMMS_FAILURE, QUEUE_FAILURE, SENSOR_FAILURE, FAILED_OP
};

const int fault_category[] = {
    [INVALID] = FAULT_CATEGORY_NONE,
    [COMMS_FAILURE] = FAULT_CATEGORY_1,
    [QUEUE_FAILURE] = FAULT_CATEGORY_1,
    [SENSOR_FAILURE] = FAULT_CATEGORY_1,
    [FAILED_OP] = FAULT_CATEGORY_1
};

const void (*fault_action[])(void) = {
    [INVALID] = action_none,
    [COMMS_FAILURE] = action_1,
    [QUEUE_FAILURE] = action_1,
    [SENSOR_FAILURE] = action_1,
    [FAILED_OP] = action_2
};

You could certainly employ X macros to generate such code, but I don't think you would save much space, and I think the result would be considerably less clear.

With respect to the question update
You seem to be looking to use the X macro approach to select and generate output only for each distinct value of some argument to the X macro on some given pass through the list.  I hesitate to say it's impossible, because clever people have squeezed some fairly surprising behaviors out of the preprocessor, but I am confident in saying that there is no straightforward way to make the preprocessor do it.
The jump table is easier, because you want analogous output for each invocation of FAULT.  Thus, you might do this ...
#define FAULT_TABLE(FAULT) \
FAULT(INVALID,                            FAULT_CATEGORY_NONE, action_none) \
FAULT(COMMS_FAILURE,                       FAULT_CATEGORY_1, action_1) \
FAULT(QUEUE_FAILURE,                        FAULT_CATEGORY_1, action_1) \
FAULT(SENSOR_FAILURE,                FAULT_CATEGORY_1, action_1) \
FAULT(FAILED_OP,                     FAULT_CATEGORY_1, action_1)

#define ENUM_CONST(fault, cat, action)   fault,
#define ACTION_ENTRY(fault, cat, action) [fault] = action,

enum fault {
    FAULT_TABLE(ENUM_CONST)
    DUMMY_FAULT
};

const void (*fault_action[])(void) = {
    FAULT_TABLE(ACTION_ENTRY)
    0
};

But again, I don't see much advantage there over just writing the enum and jump table directly.


text:
Q: Problems with migrating a system with JBoss EAP 6.3 Standalone + Apache for Wildfly 15 Domain + Apache with modcluster I'm in the process of migrating a system that uses JBoss EAP 6.3 Standalone + Apache to an environment that uses Wildfly 15 + Apache with modcluster, and I'm having some difficulties to make the system work correctly in this new scenario.
After all settings have been made, I performed the deployment of this .war file for testing and I was able to access the Hello Wolrd page normally, but once I've deployed my application, whenever I try to access it through the browser, the page goes into an infinite loop of requests displaying a 500 error. It is important to say that my application is evidently more complex, since it uses sessions, cookies, redirection of requests, among other things,
and I believe the configuration I did in apache for this new scenario is incorrect, still missing some adjustments.
Here is the Apache configuration for the old scenario using JBoss EAP 6.3 Standalone, note that it's pretty simple:
<VirtualHost *:80>
    ProxyPreserveHost On
    TimeOut 1800
    ServerName test.app.net.br
    ProxyPass /server-status !
    ProxyPass / http://127.0.0.1:8080/app/
    ProxyPassReverse / http://127.0.0.1:8080/app/
    ProxyPassReverseCookiePath / /
    <Location /server-status>
        SetHandler server-status
        Order deny,allow
        Deny from all
        Allow from 192.168.0.0/23
    </Location>
</VirtualHost>

And here's the configuration I tried to do in Apache modecluster to work with Wildfly 15:
<IfModule manager_module>
    Listen 192.168.8.91:8080
    ManagerBalancerName appcluster
    <VirtualHost 192.168.8.91:8080>
        <Directory />
            Require all granted
        </Directory>

        KeepAliveTimeout 60
        MaxKeepAliveRequests 0

        ProxyPass / balancer://appcluster
        ProxyPassReverse / balancer://appcluster
        ProxyPassReverseCookiePath / /

        AdvertiseFrequency 5
        EnableMCPMReceive On
    </VirtualHost>
</IfModule>

So any hint or help that helps me understand what is missing to make my system work in this new scenario is welcome. Thanks.

A: After doing a lot of research, I was able to figure out what the problem...
The problem was in the incompatibility with the version of the Wildfly that I used along with the application, and since I did not have much time to figure out what I was missing, I decided to use an older version of JBoss, the EAP 6.4.


text:
Q: Cannot read property 'toString' of undefined' I encountered a problem that my function does not recognize the IdUtilisateur which is in a parameter in the function navigate() and which was retrieved from the input field.

import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenficationService } from 'src/app/services/AuthenficationService/Authentification.service';

@Component({
  selector: 'bm-authentification',
  templateUrl: './authentification.component.html',
  styleUrls: ['./authentification.component.css']
})
export class AuthentificationComponent implements OnInit {
  IdUtilisateur : Number;
  constructor(private router: Router,private service: AuthenficationService) { }

  ngOnInit(): void {
  }

  // cette méthode retourne true si elle trouve l utulisateur cherché par son id sur le serveur sinon elle retourne false
  Authentification(id):any{
    this.service.getUtilisateur(id).subscribe(response=>{
      console.log("response:",response);
      if (response.length !=0){
      console.log(true ) ;
      return true ;
      }
        else {
          console.log(false) ;
          return false ;
        }
    },error=>{
      console.log("error",error);
    });

  }
navigate(IdUtilisateur){
  if(this.Authentification(IdUtilisateur)== true){
    this.router.navigate(['/accueil']) ;
  }
  else {
    this.router.navigate(['/authentification']) ;
  }

  }

}

Sign In

                <form>

                        <input type="text" class="form-control"  [(ngModel)]="IdUtilisateur" name="IdUtilisateur" placeholder="IdUtilisateur"  required>

                        <input type="checkbox">Remember Me {{IdUtilisateur}}

                        <input type="submit" value="Login" class="btn float-right login_btn" (click)="navigate(IdUtilisateur)" [disabled]="(!IdUtilisateur)">

                </form>

                    Don't have an account?Sign Up

                    Forgot your password?

A: IdUtilisateur : Number = 0;

I think the value was never getting set to IdUtilisateur so it was undefined.

A: You are mixing asynchronous and synchronous code.
Authentification has not actually made the HTTP call yet when it is supposed to return its value.
You should thus redirect in your subscribe lambda or call navigate from there but I don't see the advantage in your case.
Authentification(id): any {
    this.service.getUtilisateur(id).subscribe(response => {
        console.log("response:", response);
        if (response.length != 0) {
            console.log("Authenticated -> redirect to accueil");
            this.router.navigate(['/accueil']);
        }
        else {
            console.log("Authenticated -> redirect to accueil");
            this.router.navigate(['/authentification']) ;
        }
    }, error => {
        console.log("error", error);
    });
}

By the way, I have few remarks:

*

*It is just a convention but methods and properties in Typescript don't begin with a capital letter.

*It should be a verb (whatever the language) otherwise it is confusing.
I suggest you to rename Authentification as authenticate (or authentifier if you prefer using french words).

*Use the any type as less a possible. If you had used boolean as return type of Authentification you would have get directly an error and noticed something was wrong.


text: Q: Does play2-elasticsearch module support updates or upserts in elastic search? I'm not finding any documentation or examples of the play2-elasticsearch module supporting the elasticsearch update api (specifically upsert).  Is this functionality supported in the latest version of play2-elasticsearch for play 2 framework? and Can some provide an example of how to use this functionality.


text:
Q: How can I disable the android emulator keyboard from popping up In the following screenshot, I have an image that is followed by a scrollview. The scrollview contains a tablelayout and then some edittext fields, followed by a button

When I want to enter values into my fields, the keyboard pops up and it's blocking my view of the fields, like so:

As you can see, it blocks my view of the edittext fields. Is there an elegant fix for hiding the keyboard? If not, I will change my layout, however I'm not sure what to change. My layout looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#CCCCCC"
    android:weightSum="1" android:id="@+id/llid">
    <TextView ... >
    </TextView>
    <!-- Image inserted here as an ImageView from my code -->
    <ScrollView
        android:id="@+id/svid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="3dp">
        <LinearLayout>
            <TableLayout ... >
                <TableRow>
                    <TextView ... />
                    <TextView ... />
                </TableRow>
                <TableRow>
                    <TextView ... />
                    <TextView ... />
                </TableRow>
                <TableRow>
                    <TextView ... />
                    <TextView ... />
                </TableRow>
            </TableLayout>
            <EditText>
            ...
            </EditText>
            <EditText>
            ...
            </EditText>
            <EditText>
            ...
            </EditText>
            <Button>
            ...
            </Button>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

A: My first thought is go to the settings within the emulator:
settings -> language and keyboard
and uncheck "Android keyboard" and the other odd ones if they are checked too

A: Since the emulator is suppose to emulate what would be seen on the phone it makes sense that if you are trying to enter values into a text field the keyboard will pop up. I understand it can be irritating but, you should not try to disable it in your code, because that will disable it on the phone and then how will the user enter their inputs?
Also, you can press the hardware back button to dismiss the keyboard when it pops up.

A: Programmatically you can set keyboard disabled by
public void removeKeyboard(EditText e, Context context){
    InputMethodManager keyB = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
    keyB.hideSoftInputFromWindow(e.getWindowToken(), 0);
}

where EditText e or some other view calling for text input
UPDATE!
If you set user input with SearchView i have found some short way to close down the keyboard by just
nameButton.clearFocus();


text:
Q: Constructing a Sorted List with priority items I have a list of news unsorted items, some of which have a priority flag. I need the priority items to float to the top of the list, and then sort the rest by a date.
So, the end result is a list of news items that has the priority items showing at the top and the remainder sorted by date.
There has to be a better way to do it than this but I'm not sure what the best way would be -
foreach (var newsItem in newsItems)
{
    if (newsItem.isPriority)
    {
        addToPriorityList(newsItem);
    }
    else
    {
        addToOtherList(newsItem);
    }
}

foreach (var priorityItem in priorityList)
{
    addtoMainList(priorityItem);
}

OtherList.SortbyDate();
foreach (var otherItem in otherList)
{
    addtoMainList(otherItem);
}

Is there a more elegant way to pull this off? I assume I could use LINQ but I'm very new to it so I'm not comfortable with the syntax.

A: Try this: (edited according to the suggestion in the 1st comment)
var sorteditems = newsItems.OrderByDescending(item => item.IsPriority)
                           .ThenBy(item => item.Date);

A: You should be able to do:
newsItems.OrderBy(item => item.Priority).ThenBy(item => item.Date);


text:
Q: How do I index queries in Firebase? I'm trying to get documents that contain location fields that match with the user's location using:
getLocationListings(placemark) async {
    setState(() {
      isLoading = true;
    });
    QuerySnapshot snapshot = await FirebaseFirestore.instance
        .collectionGroup("posts")
        .where('location', isGreaterThanOrEqualTo: placemark.locality)
        .get();
    setState(() {
      posts = snapshot.docs.map((doc) => Post.fromDocument(doc)).toList();
      isLoading = false;
    });
  }

I'm getting the error:
Operation was rejected because the system is not in a state required for the operation's execution. If performing a query, ensure it has been indexed via the Firebase console.

Yet I have created indexes at the console as
How can I correct this?

A: Something might be wrong in the indexes you created for that collection group. I would recommend you to delete the index you created and run the function again, it's going to throw an error and if you were to check android device logs by executing
adb logcat

on the terminal you will see a message like this:

'FAILED_PRECONDITION: The query requires an index. You can create it here: https://console.firebase.google.com/v1/r/project/XXXXXXXXX/firestore/indexes?create_composite=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'.

Just click on the link and create the proposed index, this should fix the issue.


text:
Q: No Thunderbolt 3 Hotplug in 16.04 I just got a Dell Precision 5510 with a Thunderbolt3 port (USB-C).
The Thunderbolt to Ethernet adapter only seems to be usable if it is plugged in at boot. If I plug it in after Ubuntu has started, it is not recognized. How can I make it 'hotpluggable' in Ubuntu?
I am running Ubuntu 16.04 Beta 2 with kernel 4.4.0-18-generic.
I don't have any other Thunderbolt adapters to test with at the moment (for video etc). Since it is USB-C I have connected my Nexus 6p to the computer and it will charge, but Ubuntu does not show it as a device that is attached. That however may be due to it being a Thunderbolt port and not a USB port, even though its a USB plug?

A: You will potentially have to upgrade your kernel to a newer release in order to get the full Thunderbolt3/USB-C functionality.
The port is capable of both USB and Thunderbolt functionality, but the Linux kernel drivers are still catching up.
Getting to use a Precision 5510 for work since May and working on the imaging process (preseed) I learned that we are using a specific version of the 4.10 kernel in order for the TB3 to work properly with the Dell TB15/TB16 docking stations. It seems like things are hit or miss when updating to the Ubuntu hwe-edge (their semi official 4.10 packages) and the version we are using is closer to mainline than to an Ubuntu build.
I've been deploying the spare 5510s that I was testing on to users, but I'll try a fresh install with the hwe-edge again and see if it works properly with the docks. The USB-C support has been pretty solid, but not everything is back ported to the 4.4 kernel.
Update:
Ubuntu 18.04 and the 4.15 kernel is WAY better than 16.04 and any of the supported Ubuntu kernels available there. Possibly in 16.04.5 with the linux-image-hwe-edge-16.04 if it is 4.15 it will be better in 16.04, but there are some excellent improvements with 18.04 all around, not the least of which includes not needing to limit the Gigabit Ethernet port of the TB15/TB16 to 100 Megabit due to an overflow issue in the drivers.


text:
Q: Ehcache diskstore is deleted during application restart I have an ehcache setup, that works just fine, except that the persistent diskstore data is removed everytime I restart my application/server (Spring application on TcServer/Tomcat). The whole point of using the persistent diskstore was to be able to persist the cache in spite of application restarts.
Here is my ehcache.xml
<?xml version="1.0" encoding="UTF-8"?><ehcache><diskStore path="java.io.tmpdir/ehcache"/><cache name="clusterCache"
  maxElementsInMemory="1"
  maxElementsOnDisk="50"
  eternal="true"
  overflowToDisk="true"
  diskPersistent="true"
  memoryStoreEvictionPolicy="LFU"/></ehcache>

Any ideas why this is happening?

A: As the documentation notes, Ehcache doesn't write the index file that it looks for to restore from the disk unless the cache is properly shutdown, either via a VM shutdown hook or (since this is in a servlet container) the servlet context listener it provides. See the Ehcache documentation on shutting down for details, though it just means adding the below to your web.xml:
<listener>
      <listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class>
</listener>


text:
Q: Execute fontforge in php I wrote a script using Fontforge to Edit and generate fonts
it works fine when i call this script through the terminal
but i need to call this script using php  command line
and it's not working
the regular terminal command is
Fontforge script.py args.json

this command line is not working with php
as usual, php works with commands starts with
exec("Python")

or
exec("java")

but my command start with fontforge script.py


text:
Q: Parse a dictionary of dictionaries using jsonmodel I'm using JSONModel for working with a JSON Api and now got stuck on parsing a Dictionary of Dictionaries.
{
  "locations": {
    "one": {
      "displayName": "Name One",
      "description": "Description One"
    },
    "two": {
      "displayName": "Name Two",
      "description": "Description Two"
    }
  }
}

In my example, I need the keys "one" and "two" and their content so I thought about something like this
@protocol BaseDataModel;

@interface BaseDataModel : JSONModel

@property (nonatomic) NSDictionary<NSString *, LocationModel> *locations;

@end

But this won't work because LocationModel isn't a Objective-C Type.

A: You should just create the class LocationModel:
@interface LocationModel : JSONModel

@property (nonatomic) NSString * displayName;
@property (nonatomic) NSString * description;

@end

A: You are just missing the @protocol declaration for your LocationModel I think
#import "JSONModel.h"

@protocol LocationModel;
@interface LocationModel : JSONModel

@property (nonatomic, retain) NSString *displayName;
@property (nonatomic, retain) NSString *description;

@end


text:
Q: In regards to scraping, how do I prevent blank lists from being created in a for loop? import urllib.request
import bs4 as bs

sauce = urllib.request.urlopen('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies').read().decode()
soup = bs.BeautifulSoup(sauce, 'lxml')

soup.th.decompose()

table = soup.find('table')
trows = soup.find_all('tr')

for trow in trows:
    td = trow.find_all('td')
    row = [x.text for x in td]
    print(row)

I've been playing around with scraping web pages and tables seem to be the hardest. However, I was able to create a list of rows of the table data pretty nicely. The problem is there is a blank list that is printed because of the table header <th>. This creates a problem when I only want to print row[0] and row[1] because it returns this "IndexError: list index out of range". I know this is because <th> falls under <tr> but has no <td>.
After looking through the bs4 documentation I tried using .decompose() to remove the <th> headers to no avail. An empty list is still produced. Any help on this matter would be appreciated. Thank you.

A: You could just have it skip when it gets to an empty row, in your case when your row returns []
for trow in trows:
    td = trow.find_all('td')
    row = [x.text for x in td]

    if row == []:
        continue

    print(row)

I'll also point out too, that I hate trying to parse tables by doing the whole search for <table>, <tr>, <td>, etc. While sometimes is necesary, but whenever I see a <table> tag, I'll try Pandas first, and see if it can give me relatively something I want. I'd rather do a little work manipulating a dataframe, than a lot of work working through nested tags.
import urllib.request
import pandas as pd

sauce = urllib.request.urlopen('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies').read().decode()

tables = pd.read_html(sauce)

So .read_html() will return a list of dataframes. In the case here, theres 2. So to view them, just do print (tables[0]) or print (tables[1])


text:
Q: Faker.js Generating random paths doesn't work I am using faker.js
https://www.npmjs.com/package/faker
to generate random data. It works fine although when I try to create a path like this
faker.system.directoryPath() + '/' + faker.system.filePath()

I have always got undefined in both, so it seems that it exists but doesn't return anything.
Did anyone use one of these methods before?
Thanks in advance, any help would be really appreciated.
Bye

A: Those functionalities are not implemented - take a look into https://github.com/Marak/faker.js/blob/master/lib/system.js#L132 and https://github.com/Marak/faker.js/blob/master/lib/system.js#L141
  /**
   * not yet implemented
   *
   * @method faker.system.filePath
   */
  this.filePath = function () {
    // TODO
  };

Some proof of concept how it can be implemented:
var faker = require('faker');
var path = require('path');

faker.directoryPath = function() {
  return path.format({base: faker.fake("{{random.words}}").replace(/ /g, path.sep).toLowerCase()})
}

console.log(faker.directoryPath() + path.sep + faker.system.fileName()) // e.g. avon\re-engineered\strategist_gorgeous_wooden_fish_cambridgeshire.sm


text:
Q: programming wrt cloud computing I have been wondering over this question for a while. I have read up stuff about cloud computing(and there has been an unusual hype these days). I have understood the theory behind, how using a cloud can help me use my resources efficiently and blah blah blah. So my question is how to use(if we can) this technology in our programs? For example, with multi-core processors dominating the market, we know our programs should support multithreading(and probably should not crash when porting from single-threaded processor to multi-threaded one). So Is there any such programming paradigm we should be following or is the cloud concept completely aloof from our programs written in object-oriented and procedural languages??

A: Cloud computing platforms should be nearly transparent to the applications they host. There should be no need for a particular programming paradigm for cloud computing in most cases.
The cloud platform you use should be capable of providing all the services and dependencies required by your application. There are cloud platforms for most major web development frameworks. This means you can use whatever framework/paradigm best meets your projects needs without worrying much about what the cloud API needs.
If you are developing in PHP, Rails, Sinatra, Java, Node.js, Grails, Groovy, and other open frameworks look at Cloud Foundry
For .net take a look at Windows Azure
In both of these cloud platforms the developer experience actually made simpler.


text:
Q: Nonnegative analytic function as a square It is know that if $f:\mathbb{C}\to \mathbb{C}^*$ is a continuous function, then for every $n>0$ there exists a continuous function $g:\mathbb{C}\to \mathbb{C}^*$ such that $f=g^n$.
Is it true that if $f$ is analytic then $g$ can be chosen analytic?
What happens in the real case? For example, if $n=2$, is it true that if $f:\mathbb{R}\to \mathbb{R}^+_0$ is analytic then there exists $g:\mathbb{R}\to \mathbb{R}$ analytic such that $f=g^2$ ?

A: Yes, this is true. If $f$ is entire and zero-free, there is a well defined holomorphic logarithm of $f$, (i.e. $f = e^g$ for some entire function $g$).
You can take $e^{g/n}$ as an $n$:th root of $f$.

A: I would say yes: extend the Real-Analytic function $f$ into a Complex -Analytic one $f_2$ , which will not be zero, since the Real part is never 0. Then $f_2$ will have a square root, whose Real part will coincide with $f$.


text:
Q: Why is 'rblabla' a valid csv file mode? I have a csv file and a function to read it.
I can open it in many ways, most of these modes produce similar results.
def read(mode):
    with open("file.csv", mode) as inf:
        reader = csv.reader(inf)
        for row in reader:
            print row

read('r')       #prints \r\n characters
read('rb')      #prints \r\n characters
read('rU')      #prints \n characters but not \r characters
read('rblabla') #WAT.

I am wondering why the last example is allowed. It produces the same results as normal read mode.
Is there any reason why it works this way?

A: The mode is not for the csv reader, but for the python default file handler. Python only enforces mode to begin with 'r', 'w' or 'a', after stripping U. This is documented here, and is for python 2.5 and later.
The mode is an attribute of the file handler, and may be used by other applications, hence it may contain more characters.


text:
Q: Customizing Web Parts - hiding prop in edit mode? Update:
private string _catalogIconImageUrl = "http://hostname/images/favicon.ico";

 [WebBrowsableAttribute(false),
    Category("HIDDEN"),
    Personalizable(PersonalizationScope.User),
    WebDisplayName("Catalog Icon Image url"),
    WebDescription("Something")]
    public string CatalogIconImageUrl
    {
        get
        {
            return _catalogIconImageUrl;
        }
        set
        {
            _catalogIconImageUrl = value;
        }
    }

with the above code, it does not show the image and also when i click on edit the webpart i still able to see the catalogIconImageUrl prop in edit mode
Update end
I've declared the property CatalogIconImageURL in the .Webpart file as follows:-
</property>
<property name="CatalogIconImageUrl" type="string">images/company/companylogo.jpg</property>    //sample path...
</properties>

if I click on the Advanced Web Part Gallery as shown below in the screen shot, i able to see that property in editable so my question is, is there a way i can hide this property when user edit the web part? "Catalog Icon Image URL"

A: You can set the WebBrowseable or Browseable attribute to false
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.webbrowsableattribute.aspx
http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.browsable.aspx
Update:
It is also marked as virtual. This property is a OOTB property in WEb Part class. See here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.webpart.catalogiconimageurl.aspx
You should override this property and then set the above attribute to false
     /// <summary>
            /// Catalog Icon
            /// </summary>
            [Category("Properties")]
            [DefaultValue("")]
            [Personalizable(PersonalizationScope.Shared)]
            [WebDisplayName("Catalog icon image URL:")]
            [WebDescription("Enter the WebPart title.")]
            [XmlElement(ElementName = "CatalogIconImageUrl")]
            [WebBrowsable(false)]
            public override string CatalogIconImageUrl
            {
}


text:
Q: why does other have read permissions by default on files/folders? I have noticed that on any default/standard installation of *nix any new files/folders automatically get, at minimum, read permissions on other.
Why is this? Isn't this insecure? Shouldn't *nix systems give no default permissions to other by default? Wouldn't that be more secure?
It makes sense you want the user to have access to the file/folder (duh) and it is understandable why group should have access.
But what benefit is there with other having access by default?

A: A multi-user operating system like Unix gains more benefits from sharing files than it gains in security by locking everything down hard by default.   There's a trade-off between security and convenience. In practice, the default settings are typically used well and are a good compromise.
You can always make permissions on a folder more secure.  chmod 750 ./FOLDER will give Read, Write and Execute permissions to the owner with the 7, Read and Execute permissions to the group with the 5, and no permissions to the other group.
If you look at the /etc/ folder, where a lot of configuration settings are stored, the permissions allow Read and Execute to other:
vagrant@host:~$ ls -ld /etc/
drwxr-xr-x 136 root root 12288 Dec  6 12:48 /etc/
vagrant@host:~$

The idea here is that it can actually help operation of the system. For example, the apache web server, running as user apache, can read its configuration files.  However, the configuration files are owned by root, so if a bad actor gets hold of the apache user, that account cannot write new permissions for itself.
Linux (and Unix) systems are designed to be multi-user Operating Systems.  Having other users read files by default is more helpful more often than it is a security issue.  Sometimes you want members of a team (your group) to be able to edit files, too; so you set chmod g+rwx ./FOLDER which allows members of the group to edit files in that folder.
The permissions system is flexible enough to tune this to your needs.  The Linux Documentation Project explains it well, and has great examples. Security-Enhanced Linux extends it even more.
I suggest you take a look at unix.stackexchange.com in particular the tag marked Permissions where a number of questions are answered in good detail.  In particular:

*

*How do directory permissions in Linux work?

*How to set default file permissions for all folders/files in a directory?

A: Programs which create new files defines their permissions. Permissions given to a newly created file from a shell is often restricted to rwxr-xr-x which is the default umask on most Linux distributions.
You can edit your private login scripts such as ~/.bashrc, or system-wide /etc/profile scripts to edit this default umask and give it a more restrictive value. But most of the time it is okay to keep it as is since you are likely to have all your private files in your home directory. You only need to check your home directory permissions to block unwanted users from listing (r) and traversing (x) it.

On my Linux system, this default behavior is defined in /etc/profile:
# 077 would be more secure, but 022 is generally quite realistic
umask 022


text:
Q: Mod_rewrite is enabled but not working I have read around for a while and I can't get this to work.
mod_rewrite is enabled in Apache and I have changed AllowOverride to all
My .htaccess looks like this:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ profile.php/?username=$1 [L]

and my default file for apache2 looks like this:

        ServerAdmin webmaster@localhost
    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride all
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride all
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

error.log
[Sat May 25 20:13:21 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:13:21 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:13:22 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:13:23 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:14:56 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbf', perhaps misspelled or defined by a module not$
[Sat May 25 20:14:57 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbf', perhaps misspelled or defined by a module not$
[Sat May 25 20:14:59 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbf', perhaps misspelled or defined by a module not$
[Sat May 25 20:14:59 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbf', perhaps misspelled or defined by a module not$
[Sat May 25 20:15:04 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:15:04 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:15:20 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:15:20 2013] [alert] [client (ip)] /var/www/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by$
[Sat May 25 20:15:58 2013] [notice] caught SIGTERM, shutting down

On my website I get a 500 internal server error message. Please help!

A: Try changing your code to this:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ profile.php/?username=$1 [L]

i.e. turn the MultiViews options off.
PS: Looking at your error.log looks like you have some special characters in your .htaccess before RewriteEngine keyword.


text:
Q: Does HttpWebRequest send 200 OK automatically? Background: I am implementing Paypal IPN handler.
This great article on Paypal states that I am required to send a 200 OK back to Paypal after I read the response.
The processing of IPN request is as follows:
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(),
                         System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();

StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd(); //returns VERIFIED
streamIn.Close();

According to the following (from the article), the code (I guess) is supposed to send a 200 OK back to Paypal:
PayPal will respond with either VERIFIED or INVALID. After you receive this response, be sure to send 200 OK to prevent additional attempts from PayPal to send an IPN
I do not see any explicit HTTP response being sent as "200 OK".
Does the used HttpWebRequest send a 200 OK automatically?
If yes, at which point does that occur?
If not, how can one send 200 OK response using HttpWebRequest? Is it easier doing that using HttpWebRequest or sockets?

A: The short answer to the question you're really asking is yes, ASP.NET will send back a 200 if your page executes successfully.  The point in the article that you are referring to is about you sending a request to Paypal in response to it's request to you, so sending 200 has nothing to do with the HttpWebRequest object as someone has already pointed out.
So, in the case of this article, if you want to send back 200 to Paypal, ASP.NET will do so automatically once the page has been successfully executed.

A: The easiest way to get the answer is to use Wireshark and see what exactly is getting sent back and forth.


text:
Q: Does anyone know how iOS Safari 9 handles page crashes or freezing? We have a web app which is freezing in Safari 9 and Safari 10 on iOS 9 and 10. Worth noting this is a web page which is touch responsive, the users then add this web page to the Home screen of the device by opening the page in Safari and clicking 'Add to Home Screen'.
The app seems to sometimes freeze in Safari 9 and Safari 10, and no buttons are clickable. From what I can see the actual device seems to lock up and freeze sometimes but recovers after 1 or 2 seconds, I've tested this by looking through the recent apps, and this seems to freeze, this is happening on multiple devices and we have a theory it could be due to a third party app causing the devices to freeze.
My theory is that when the actual device (iOS) is freezing for 1 or 2 seconds, that the device is trying to unfreeze itself and it kills all the scripts running in Safari which is causing our application not to recover from the freeze, does anyone know if this is how Safari actually works? Or if this theory is possible?
Thank you! :-)

A: Apple engineers wrote the code, but it's not available for inspection so the larger context is yes there is a system but we don't get to see it.
You can look at the logs an iOS device generates by plugging it into Xcode on a Mac or the Apple Configurator. If you do that, you will see that when an application crashes entirely - there will be a log file (that optionally is sent to Apple) explaining what crashed on a technical level.
The second level of logging is when an app (Safari in this case) burns too much CPU. This is likely what you want - when a web page has excessive javascript, buggy javascript, continual tracking and acts more like a program than a short document to be rendered once - you will get a spin dump that again is mostly engineering data - but you will know the OS noticed the app was nor behaving like a short, quick efficient worker. The have spin in the file names.
Lastly, you can avail yourself of the well documented and very powerful Safari development tools by enabling debug and inspecting what Safari is doing on an extremely granular level to include errors, warnings, code inspection, timing to the millisecond, etc...

*

*https://developer.apple.com/safari/tools/


text:
Q: Use full Width and Height of Screen to show Dialog I am using Custom AlertDialog.Builder to show Image from SD Card into that alert dialog.
How can I use full width and height of Screen to show dialog, here is my code:
viewHolder.imageButtonView.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {

    final AlertDialog.Builder imageDialog = new AlertDialog.Builder(XRayActivity.this);

    final LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);

    View layout = inflater.inflate(R.layout.image_dialog, null);

    ImageView image = (ImageView) layout.findViewById(R.id.imageView);

    try
    {
        strFileName = arrayList.get(position).getFilename().toString();

        String file = Environment.getExternalStorageDirectory().getPath() + "/Pictures/XRays/" + strFileName;
        Bitmap bm = BitmapFactory.decodeFile(file);
        image.setScaleType(ImageView.ScaleType.FIT_XY);

        image.setImageBitmap(bm);
    } catch (Exception e) {
        e.printStackTrace();
    }

       imageDialog.setTitle(strFileName);
       imageDialog.setView(layout);
       imageDialog.setPositiveButton(android.R.string.ok, new
       DialogInterface.OnClickListener(){

    public void onClick(DialogInterface dialog, int which) {

          dialog.dismiss();
         }
     });

       imageDialog.create();
       imageDialog.show();

        }
    });

image_dialog.xml:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

In xml I am using only ImageView with match_parent properties of layout_width and layout_height.

A: You can use Dialog Fragment:
@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);

        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        }
    }

A: You can use style to do that
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);

}


text:
Q: grunt usemin and concat: take a file already in dist first instead of app I have two tasks when I build with grunt:
A first task preprocess:dist that copies app/scripts/config.js to dist/scripts/config.js and replaces // @echo FOO to BAR.
Then, usemin, that concats all app/scripts/**/*.js to dist/scripts/application.js.
Build task in Gruntfile:
grunt.registerTask('build', [
    'clean:dist',
    'preprocess:dist',
    'useminPrepare',
    ...
    'htmlmin'
    'concat',
    'usemin'
]

My include scripts in index.html:
<!-- build:js({.tmp,dist,app}) scripts/application.js -->
<script src="/scripts/config.js"></script>
<script src="/scripts/other_file.js"></script>
<script src="/scripts/yet_another_file.js"></script>
<!-- endbuild -->

Everything works fine, except that in the concatenated file dist/scripts/application.js, I have the config.js from app/scripts, and not the one from dist/scripts.
I tought that the ({.tmp,dist,app}) after build:js was for specifying where to take the files when concatenating, but still config.js is taken from the wrong directory (app and not dist).
So I end up with the config.js where // @echo VAR not replaced.
How can I tell concat/usemin to take config.js from dist and not app when concatenating ?

Note: One solution would be to have preprocess to put a config.processed.js in app/scripts, and then including this file instead of config.js, so that I don't have to change the way usemin works.
But then I have to put config.processed.js in .gitignore and I have a generated file inside my sources files...
I would prefer having this file generated in .tmp or dist.

Edit: my whole Gruntfile:
// Generated on 2013-10-31 using generator-angular 0.5.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
  require('time-grunt')(grunt);
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);

  grunt.loadNpmTasks('grunt-preprocess');
  grunt.loadNpmTasks('grunt-include-source');

  grunt.initConfig({
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },
    watch: {
      coffee: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee:dist']
      },
      coffeeTest: {
        files: ['test/spec/{,*/}*.coffee'],
        tasks: ['coffee:test']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      },
      includeSource: {
        files: ['<%= yeoman.app %>/index.html'],
        tasks: ['includeSource:server']
      }
    },
    autoprefixer: {
      options: ['last 1 version'],
      dist: {
        files: [
          {
            expand: true,
            cwd: '.tmp/styles/',
            src: '{,*/}*.css',
            dest: '.tmp/styles/'
          }
        ]
      }
    },
    connect: {
      options: {
        port: 8080,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        livereload: 35729,
        // Modrewrite rule, connect.static(path) for each path in target's base
        middleware: function (connect, options) {
          var optBase = (typeof options.base === 'string') ? [options.base] : options.base;
          return [require('connect-modrewrite')(['!(\\..+)$ / [L]'])].concat(
            optBase.map(function (path) {
              return connect.static(path);
            }));
        }
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ]
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      }
    },
    clean: {
      dist: {
        files: [
          {
            dot: true,
            src: [
              '.tmp',
              '<%= yeoman.dist %>/*',
              '!<%= yeoman.dist %>/.git*'
            ]
          }
        ]
      },
      server: '.tmp'
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ]
    },
    coffee: {
      options: {
        sourceMap: true,
        sourceRoot: ''
      },
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.app %>/scripts',
            src: '{,*/}*.coffee',
            dest: '.tmp/scripts',
            ext: '.js'
          }
        ]
      },
      test: {
        files: [
          {
            expand: true,
            cwd: 'test/spec',
            src: '{,*/}*.coffee',
            dest: '.tmp/spec',
            ext: '.js'
          }
        ]
      }
    },
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: '<%= yeoman.app %>/bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false
      },
      dist: {},
      server: {
        options: {
          debugInfo: true
        }
      }
    },
    // not used since Uglify task does concat,
    // but still available if needed
    /*concat: {
     dist: {}
     },*/
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            //'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            //'<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },
    useminPrepare: {
      // changed from app to dist, to take index.html processed by includeSource in dist
      html: '<%= yeoman.dist %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },
    usemin: {
      //html: ['<%= yeoman.dist %>/{,*/}*.html'],
      html: ['<%= yeoman.dist %>/index.html'],
      //css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      //js: ['<%= yeoman.dist %>/scripts/**/*.js'],
      options: {
        dirs: ['<%= yeoman.dist %>']
      }
    },
    imagemin: {
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.app %>/images',
            src: '{,*/}*.{png,jpg,jpeg}',
            dest: '<%= yeoman.dist %>/images'
          }
        ]
      }
    },
    svgmin: {
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.app %>/images',
            src: '{,*/}*.svg',
            dest: '<%= yeoman.dist %>/images'
          }
        ]
      }
    },
    cssmin: {
      // By default, your `index.html` <!-- Usemin Block --> will take care of
      // minification. This option is pre-configured if you do not wish to use
      // Usemin blocks.
      // dist: {
      //   files: {
      //     '<%= yeoman.dist %>/styles/main.css': [
      //       '.tmp/styles/{,*/}*.css',
      //       '<%= yeoman.app %>/styles/{,*/}*.css'
      //     ]
      //   }
      // }
    },
    htmlmin: {
      dist: {
        options: {
          /*removeCommentsFromCDATA: true,
           // https://github.com/yeoman/grunt-usemin/issues/44
           //collapseWhitespace: true,
           collapseBooleanAttributes: true,
           removeAttributeQuotes: true,
           removeRedundantAttributes: true,
           useShortDoctype: true,
           removeEmptyAttributes: true,
           removeOptionalTags: true*/
        },
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.app %>',
            src: ['*.html', 'views/**/*.html', 'blocs/**/*.html'],
            dest: '<%= yeoman.dist %>'
          }
        ]
      }
    },
    // Put files not handled in other tasks here
    copy: {
      dist: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%= yeoman.app %>',
            dest: '<%= yeoman.dist %>',
            src: [
              '*.{ico,png,txt}',
              '.htaccess',
              'bower_components/**/*',
              'images/{,*/}*.{gif,webp}',
              'assets/**/*',
              'fonts/**/*',
              'styles/fonts/*'
            ]
          },
          {
            expand: true,
            cwd: '.tmp/images',
            dest: '<%= yeoman.dist %>/images',
            src: [
              'generated/*'
            ]
          }
        ]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },
    concurrent: {
      server: [
        'coffee:dist',
        'compass:server',
        'copy:styles'
      ],
      test: [
        'coffee',
        'compass',
        'copy:styles'
      ],
      dist: [
        'coffee',
        'compass:dist',
        'copy:styles',
        'imagemin',
        'svgmin',
        'htmlmin'
      ]
    },
    //karma: {
    //  unit: {
    //    configFile: 'karma.conf.js',
    //    singleRun: true
    //  }
    //},
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },
    ngmin: {
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%= yeoman.dist %>/scripts',
            src: '*.js',
            dest: '<%= yeoman.dist %>/scripts'
          }
        ]
      }
    },
    uglify: {
      dist: {
        files: {
          '<%= yeoman.dist %>/scripts/scripts.js': [
            '<%= yeoman.dist %>/scripts/scripts.js'
          ]
        }
      }
    },

    preprocess: {
      options: {
        context: {
          // /!\ Security warning:
          // On heroku, process.env might contain sensitive information. (such as DATABASE_URL)
          // To make sure what fields we pass, we specify every field explicitly.
          // So DON'T do this: ENV: JSON.stringify(process.env)

          ENV: JSON.stringify({
            FIRST_VAR: process.env.FIRST_VAR || '',
            SECOND_VAR: process.env.SECOND_VAR || '',
            NODE_ENV: process.env.NODE_ENV || 'production'
          })
        }
      },
      server: {
        src: 'app/scripts/config.js', dest: 'app/scripts/config.processed.js'//dest: '.tmp/scripts/config.js'
      },
      dist: {
        src: 'app/scripts/config.js', dest: 'app/scripts/config.processed.js'//dest: 'dist/scripts/config.js'
      }
    },
    includeSource: {
      options: {
        basePath: 'app',
        baseUrl: '/',
      },
      server: {
        files: {
          '.tmp/index.html': 'app/index.html'
        }
      },
      dist: {
        files: {
          'dist/index.html': 'app/index.html'
        }
      }
    }
  });

  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'includeSource:server',
      'preprocess:server',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test'
    //'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'includeSource:dist',
    'preprocess:dist',
    'useminPrepare',

    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'cdnify',
    'ngmin',
    'cssmin',
    //'uglify',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);

  // building the app on heroku
  grunt.registerTask('heroku', 'build');

};

A: I had the same problem, and I resolved with the following steps:
1) Use a Build Type different that "js" for your script, so the usemin plugin will ignore it on the build process. For example, "dev".
<!-- build:dev({.tmp,dist,app}) --><script src="/scripts/config.js"></script><!-- endbuild -->

Note that there is no spaces due to a bug on usemin (Issue 128). I'm running usemin version 2.1.1
With this, grunt sever will use your config.js from your Source Code.
2) Modify your preprocess task to put your preprocessed file in a temporary folder, like .tmp. For example:
dist: {
        src: 'app/scripts/config.js', dest: '.tmp/scripts/config.processed.js'
      }

3) Now you need to create a Grunt Task to Concat your config.processed.js in .tmp folder with the scripts/application.js in your dist folder that was generated dynamically by usemin.
For example:
concat: {
          environment: {
              dest: 'dist/scripts/application.js',
              src: ['dist/scripts/application.js', '.tmp/scripts/config.processed.js']
          }
        },

If you are on Windows, you will need to use \\ instead of /
4) Finally, you need to put all together. Your build task should look like this:
 grunt.registerTask('build', [
    'clean:dist',
    'includeSource:dist',
    'preprocess:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'cdnify',
    'ngmin',
    'cssmin',
    'concat:environment',
    'uglify',
    'rev',
    'usemin'
  ]);

A: With this package:
https://www.npmjs.org/package/grunt-file-append
You could append the generated file to the concatenated temp file.
You should remove the config js's reference completely from the html, and add the file-append task after the concat task in the build tasklist to append the generated config file to the concatenated js.


text:
Q: Xpath not contains Is there a way to select the xpath which doesn't contain ng-show
Please find the xpath below:
I'm familiar with not(contains()), but it has 2 parameters.
I would like it to not contain the ng-showitself, because I have a few more element containing ng-show and I don't want to select any of them.
0 km

Thanks in Advance

A: Try this below xpath
//span[not(@ng-show)][not(@class='percent ng-binding')][@class='ng-binding']

Explanation of xpath:- Only those  tag will return, which attribute does not contains ng-show


text:
Q: Binding public fields with ASP.NET MVC as well as public properties? Obviously, ASP.NET MVC's binding functionality takes care of binding a model's public properties when passing it to a controller, so for instance in the following example, Surname and Email will be bound with their submitted values:
public ActionResult Create(UserModel mdlNewUser) {
    // ...
}

// ...

public class UserModel {
    public string Firstname;
    public string Surname { get; set; }
    public string Email { get; set; }
}

However, it doesn't seem to auto-bind public fields such as Firstname in the above example; these will be left untouched.  Is there any way to get public fields (and for that matter, any other type of class member) to be automatically bound, or will it only ever bind public properties?
This article seems to imply that it's only public properties because it only ever refers to them all the way through, but it doesn't explicitly seem to say that only public properties will be bound.

A: That's correct, only public properties will be bound.
Fields cannot be used for binding.


text:
Q: How to access data in this format: {variable1={key:value,key2:value2.....}, variable2={key3:value3,key4:value4.....}} I have a dataframe where some columns are formatted this way:
example value of ColX:
 {variable1={key:value,key2:value2.....}, variable2={key3:value3,key4:value4.....}}

Let's say I want to access value2 and value4. How can I address them using Python?
My desired result is to make a column key2 with value2's and column key4 with all the value4's
Sorry. I could not google the name of this data structure. It's something like a list of dictionary definitions packed into strings.

A: You are using dictionnaries of dictionnaries (I think). In order to get to value 2 you need to get first to variable 1, and then to key2 so you can do this, if your dictionnary is stored in ColX :
ColX.get(variable1).get(key2)

By the way are you sure of the syntax of ColX ? Isn't it :
{variable1:{key:value,key2:value2.....}, variable2:{key3:value3,key4:value4.....}}

A: The data structure is simply a nested dict. Try some of the answers given here: Safe method to get value of nested dictionary. Dict methods can be concatenated, so you can do:
dictionary.get(keyname, value).get(keyname, value)


text:
Q: Python/Tkinter - Identify object on click I am trying to create a program that changes the object colour on click from white to black or from white to black depending of the previous colour. I would want the program change the colour only if the object is a rectangle. How can I make the this happen?
Here is my code:
import tkinter as tk

root = tk.Tk()

cv = tk.Canvas(root, height=800, width=800)
cv.pack()

def onclick(event):
    item = cv.find_closest(event.x, event.y)

    current_color = cv.itemcget(item, 'fill')

    if current_color == 'black':
        cv.itemconfig(item, fill='white')

    else:
        cv.itemconfig(item, fill='black')

cv.bind('<Button-1>', onclick)

cv.create_line(50, 50, 60, 60, width=2)

cv. create_rectangle(80, 80, 100, 100)

root.mainloop()

In this code the program changes the fill colour for any object. I would want it to change it only for rectangles.
Thanks for the help.

A: Here are three common solutions to this problem:
Using the item type
You can ask the canvas for the type of the object:
item_type = cv.type(item)
if item_type == "rectangle":
    # this item is a rectangle
else:
    # this item is NOT a rectangle

Using tags
Another solution is to give each item one or more tags. You can then query the tags for the current item.
First, include one or more tags on the items you want to be clickable:
cv. create_rectangle(80, 80, 100, 100, tags=("clickable",))

Next, check for the tags on the item you're curious about, and check to see if your tag is in the set of tags for that item:
tags = cv.itemcget(item, "tags")
if "clickable" in tags:
    # this item has the "clickable" tag
else:
    # this item does NOT have the "clickable" tag

Create bindings on tags
A third option is to attach the bindings to the tags rather than the canvas as a whole. When you do this, your function will only be called when you click on item with the given tag, eliminating the need to do any sort of runtime check:
cv.tag_bind("clickable", "<1>", onclick)

A: The solution of BPL is fine. Here is another solution that doesn't require any global variable. There's a system of tags in Tkinter which could be compared with "class" from HTML/CSS. It enables us to associate a list of tags to a graphic object. See item specifiers.
Here is how it would be:
import tkinter as tk

def onclick(event):
    global rectangles
    item = cv.find_closest(event.x, event.y)
    if 'rect' in cv.gettags(item):
        current_color = cv.itemcget(item, 'fill')

        if current_color == 'black':
            cv.itemconfig(item, fill='white')
        else:
            cv.itemconfig(item, fill='black')

rectangles = []

root = tk.Tk()
cv = tk.Canvas(root, height=800, width=800)
cv.pack()
cv.bind('<Button-1>', onclick)

id_a = cv.create_line(50, 50, 60, 60, width=2)
id_b = cv.create_rectangle(80, 80, 100, 100, tags=('rect'))

root.mainloop()

I think it's a bit more object oriented in some way. ;)

A: What about this solution:
import tkinter as tk

def onclick(event):
    global rectangles
    item = cv.find_closest(event.x, event.y)
    if item[0] in rectangles:
        current_color = cv.itemcget(item, 'fill')

        if current_color == 'black':
            cv.itemconfig(item, fill='white')
        else:
            cv.itemconfig(item, fill='black')

rectangles = []

root = tk.Tk()
cv = tk.Canvas(root, height=800, width=800)
cv.pack()
cv.bind('<Button-1>', onclick)

id_a = cv.create_line(50, 50, 60, 60, width=2)
id_b = cv.create_rectangle(80, 80, 100, 100)
rectangles.append(id_b)

root.mainloop()

The main idea of this is you add the items id you want to change color to a global array (global variables are discouraged though). Then when you click with the mouse, the itemcget function will give you the id from the closest item, so you need to check whether this id is inside of the array of your rectangle items.

A: Based on this accepted answer you need to tag_bind your rectangles.  Also, you should be assigning IDs to each object you create.  If you need to do this repeatedly, you can wrap the process in a loop or functions, but the base theory won't change.  GL with tkinter!


text:
Q: Replace last forward slash in string with other character I'm trying to replace the last forward slash in a series of url strings, to exchange that forward slash for a number sign, like so -
http://example.com/about/our-company

to
http://example.com/about#our-company

Using JS with jQuery I've tried applying the replace function on each string but not sure as how to target just the last forward slash.
$('.submenu a').each(function() {
    var url = $(this).attr('href');
    url = url.replace(/\//g, '#');
    console.log(url);
    // replaces all
});

A: Try this:
var str = "http://one/two/three/four";
console.log(str.replace(/\/(?=[^\/]*$)/, '#'));

That says: "replace the slash that is followed by either nothing or characters that do not include another slash, right to the end."

A: You can try splitting Url based on /:
url = 'http://example.com/about/our-company';
tokens = url.split('/');
expected_url = tokens.slice(0, tokens.length-1).join('/') + '#' + tokens[tokens.length-1];

console.log(expected_url);
# Prints 'http://example.com/about#our-company'

A: $('.submenu a').each(function() {
    var url = $(this).attr('href');
    var idx = url.lastIndexOf("/");
    url = url.substring(0, idx) + '#' + url.substring(idx+1);
    console.log(url);
});

A: A simple solution:
var str="http://example.com/about/our-company";
var tmp=str.split("").reverse().join("");
tmp=tmp.replace("/","#");
str=tmp.split("").reverse().join("");

//output:

str = http://example.com/about#our-company


text:
Q: How to include 2 words within Regex and result must be based on only those 2 words VB.NET I would like to know how to include only 2 or more keywords within a Regex.  and ending results should only show those words defined, not only one word.
What I currently have works with multiple keywords but I want it to use BOTH words not either one of the other.
For example:
Dim pattern As String = "(?i)[\t ](?<w>((arma)|(crapo))[a-z0-9]*)[\t ]"

Now the code works fine by including 'arma' or 'crapo'. I only want it to include BOTH 'arma' AND 'crapo' otherwise do not show any results.
Dealing with finding certain keywords within a PDF document and I only want to be shown results if the PDF document includes BOTH 'arma' and 'crapo'      (Works fine by showing results for 'arma' OR 'crapo' I want to see results based on 'arma' AND 'crapo'.
Sorry for sounding so repetitive.
Edit: Here is my code. Please read comment.
Dim filesz() As String = GetPatternedFiles("c:\temp\", New String() {"tes*.pdf", "fes*.pdf", "Bas*.pdf"})

'The getpatterenedfiles is a function"  also gettextfromPDF is another function.
    For Each s As String In filesz

        Dim thetext As String = Nothing

        Dim pattern As String = "(?i)[\t ](?<w>(crapo)|(arma)[a-z0-9]*)[\t ]"

        thetext = GetTextFromPDF(s)

            For Each m As Match In Regex.Matches(thetext, pattern)

                ListBox1.Items.Add(s)
            Next

    Next

A: You can use this regex:
\barma\b.*?\bcrapo\b|\bcrapo\b.*?\barma\b

Working demo

The idea is to match arma whatever crapo or crapo whatever arma and use word boundaries to avoid words like karma.
However, if you want to match karma or crapotos as you asked in your comment you can use:
arma.*?crapo|crapo.*?arma


text:
Q: How to sort ascending the dictionary GUYS i reversed a dictionary...but how can i sort ascending the dict exactly like this:
 {'precise': ['accurate', 'exact'],
 'clever': ['astute', 'smart'],
 'talented': ['smart'],
 'bright': ['smart'],
 'exact': ['accurate'],
 'smart': ['astute']}

MY Solution don't return that i want:
def reverse_dictionary(input_dict):
   d = {}
   s=input_dict
   for key, value in s.items():
       value=" ".join(value)
       value=value.lower()
       value=value.split(' ')
       key=key.lower()
       for i in sorted(value):
           d.setdefault(i, []).append(key)
   return d
input_dict=({'Accurate': ['exact', 'precise'],
            'exact': ['precise'],
            'astute': ['Smart', 'clever'],
            'smart': ['clever', 'bright', 'talented']})
print(reverse_dictionary(input_dict))

it returns:
{'exact': ['accurate'],
 'precise': ['accurate', 'exact'],
 'clever': ['astute', 'smart'],
 'smart': ['astute'],
 'bright': ['smart'],
 'talented': ['smart']}

but it's not true!