text:
Q: How to monitor website requests from my home network? I would like to monitor the requests from my home network to see which (and how often) specific sites are visited. How would I go about doing that?
Update: I have signed up for OpenDNS. It was a very easy process. However, the reporting/statistics feature is not as "full featured" as I was expecting. I am not able to determine how much time a user has spent on a particular website. Basically, I am not able to get as detailed as I would like to. Is there another solution that provides more detailed reporting?

A: Create a free account on the OpenDNS.com site. They have a great tutorial on setting up your router to use the service. Once you start monitoring site visits you may wish to use their dashboard to filter out undesirable destinations. They maintain a list of malicious sites that are used by virus/trojan software. These site are prevented by default.

A: While the OpenDNS route is a nice one, you could just as easily open up a Wireshark capture on the local network.

A: I've been using OpenDNS for a while, and it is great.  I recently replaced my wifi router firewall with  the Astaro gateway (http://www.astaro.com/).  I am using the free version which seems incredibly feature rich (for free).  Provides proxy for http & downloads.  Can show http requests by hosts.  Even provides VPN.  It was pretty straightforward to setup, and compliments OpenDNS nicely.


text:
Q: Issue with C++ macros on Red Hat Enterprise Linux (RHEL) using CPPCHECK At my employment we are working on a large C++ project on Red Hat Enterprise Linux (RHEL) 6, soon to be RHEL 8. with Bash shell. We sometimes use Netbeans for editing source code, but I prefer to use vim. We are doing DevOps and Agile with two week sprints, and using Jenkins build engine with AccuRev for source control. Every time a code change is promoted in AccuRev, Jenkins automatically starts a new build of the code base. As part of that build, CPPCHECK is used to do static code analysis on the C++ source code.
In part of our system, we are using C++ macros to define unit test scripts. the macros are not fully defined, since we are allowing the unit test script developer to customize them for doing unit tests. This system works fine with no error at compile time with g++ compiler, and also there is no error at run time either.
However, when Jenkins does a build, and it uses CPPCHECK to analyze the code, it is generating
error-id: unknownMacro
text: There is an unknown macro here somewhere. Configuration is required. If SCRIPT is a macro then please configure it.
Here is an example of the C++ code we are using to complete partially defined C++ macro:
SCRIPT(SampleScript)

BODY()
{
    cout << "SampleScript running." << endl;
}

END_SCRIPT()

SCRIPT, BODY, and END_SCRIPT are C++ macros listed in an include file, but are not completely defined. On the Github site for CPPCHECK there is a supposed solution to this issue by using -I option, but I tried that and the missing macro CPPCHECK errors are still occurring.
This is the CPPCHECK command listed with its arguments, including the -I option, but so far this command is still generating "unknownMacro" error.
cppcheck \
   -I ./* \
    -j 4 \
    --xml-version=2 \

A: Ok, I have many years experience with Unix and Linux, but was not aware of the following fix. The fix is to use the -I option with CPPCHECK, which I was doing, but I was doing the following in the Makefile with an asterisk:
cppcheck \
-I ./* \
-j 4 \
--xml-version=2 \

I just found out from another person that asterisk * is not recognized in Unix and Linux Makefiles, but IS recognized from the command line with Bash and other shells like I have known for a long time. So I removed the asterisk from the CPPCHECK call and now there are no more CPPCHECK errors with the C++ code in the Jenkins build.
cppcheck \
-I ./ \
-j 4 \
--xml-version=2 \

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase random one to one chat I want to create random chat room with random search.
I make user's searching value = 1 when they tap "search for users" button
Then when search finishes search returns with another user's UID and creates an chat intent and pushes a message to other UID user to open an intent. But the problem is it gets stuck if the user that I find finds another pal to chat and starts chat first with me.
How can I implement this random 1-1 chat scenario?
EDIT:
I will set searching active user =1 and other user to 2 1 is active searcher and ontent starter user another 2 is passive waiter for 1
FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("searching").setValue("1");

FirebaseDatabase.getInstance().getReference().child("users").addListenerForSingleValueEvent(new ValueEventListener(){
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    // Get user information
    Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
    // List<users> users = new ArrayList<>();
    while (dataSnapshots.hasNext()) {
        DataSnapshot dataSnapshotChild = dataSnapshots.next();
        final users user = dataSnapshotChild.getValue(users.class);
        if (!TextUtils.equals(user.uid, FirebaseAuth.getInstance().getCurrentUser().getUid())) {
            //users.add(user);
            if (TextUtils.equals(user.searching, "1")) {
                // dialog.dismiss();
                String rdomui = UUID.randomUUID().toString();
                Log.d(TAG,user.uid.toString());
                FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("searching").setValue("0");
                FirebaseDatabase.getInstance().getReference().child("users").child(user.uid).child("searching").setValue("0");

                //send intent starter to notification

                //Intent intent = new Intent(MainActivity.this, action.class);
                // intent.putExtra(EXTRA_MESSAGE, message);
                // startActivity(intent);


text:
Q: "Desktop effects could not be enabled" in VMware I am running on a Windows 7 64 bit host.
I'm use with VMware Player.
Ubuntu 10.10.
And, i get to Visual Effect, and when i press "normal" i get this error:

Desktop effects could not be enabled

and if i press: compiz:

compiz (core) - Fatal: Software
  rendering detected. compiz (core) -
  Error: Failed to manage screen: 0
  compiz (core) - Fatal: No manageable
  screens found on display :0.0

What i can to do?

A: Vmware player doesn't support OpenGL on Linux yet, according to How to enable 3D in VMware Player? You could try the lastest VirtualBox instead.

A: Did you installed/activated your driver for the graphics card?
If not go to System -> Additional Drivers and activate the driver for your graphic card.


text:
Q: Request Permission To Access Contacts How can you setup an app that will ask for permission to access contacts before pulling up the Mail Composer? I know it is fairly recent that apps will do this.

A: Since Apple provides the MFMailComposeViewController it already has access to the users contacts built in, no need to have access granted. If you're looking to use the users contacts elsewhere you should look into the Address Book Programming Guide

A: Here's a simple example since I do not know what you are planning to do. You have a UIButton that reads "Access Contacts." When they click the button, you have the button run a method...Let's call it generatePopover. Well generatePopover should create a UIPopOverController with a statement on it asking for permission to access contacts. This view will have two buttons on it, accept and decline. Decline does nothing, where accept allows you to go ahead and pull up the mail controller.
Here's a link to the popover controller page: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIPopoverController_class/Reference/Reference.html

A: You could do something like this:
//Header (.h)
@interface yourClass : superClass <UIAlertViewDelegate>
@property (nonatomic) BOOL alertShown;
@property (nonatomic) BOOL permissionGranted;

//Implementation (.m)
@synthesize alertShown, permissionGranted;

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if(buttonIndex == 1){

        self.permissionGranted = YES;
    }
    /*If you weren't sure what index the "Yes" button was at, you could do this instead:
    if(buttonIndex == alertView.firstOtherButtonIndex){

        self.permissionGranted = YES;
    }
    Or this:
    if([buttonTitleAtIndex:buttonIndex isEqualToString:@"Yes"]){

        self.permissionGranted = YES;
    }*/
}

-(void)composeMail{
    if(!self.alertShown){

         UIAlertView *permissionsAlert = [[UIAlertView alloc] initWithTitle:@"Permission"
                                                              message:@"Permission to access contacts?"
                                                             delegate:self
                                                    cancelButtonTitle:@"No"
                                                    otherButtonTitles: @"Yes"];
        [permissionsAlert show];
    }
    if(self.alertShown && self.permissionGranted){

        //access mail/contacts
    }
}
//viewDidLoad
self.alertShown = NO;
self.permissionGranted = NO;

I just typed this out without checking or looking up anything, so there may be a mistake somewhere.
Anyway, hope this helps!


text:
Q: Add a from in newly added step in checkout page magento 2 we follow this step to add a new form in checkout page. we need to add some form fields in that newly added steps.
I have updated the checkout_index_index.xml file based on shipping-step. But its not working.
Suggest me, which way i need follow.
what I did:
Vendor/Module/view/frontend/web/js/view/schedule-on-appointment-view.js
  define(
    [
        'ko',
        'uiComponent',
        'underscore',
        'Magento_Checkout/js/model/step-navigator'
    ],
    function (
            ko,
            Component,
            _,
            stepNavigator
            ) {
        'use strict';
        /**
         *
         * schedule-on-appointment - is the name of the component's .html template,
         * <Hicare_Slot>  - is the name of the your module directory.
         *
         */
        return Component.extend({
            defaults: {
                template: 'Vendor_Module/schedule_on_appointment'
            },

            //add here your logic to display step,
            isVisible: ko.observable(true),

            /**
             *
             * @returns {*}
             */
            initialize: function () {
                this._super();
                // register your step
                stepNavigator.registerStep(
                        //step code will be used as step content id in the component template
                        'schedule',
                        //step alias
                        null,
                        //step title value
                        'Schedule On Appontment',
                        //observable property with logic when display step or hide step
                        this.isVisible,
                        _.bind(this.navigate, this),
                        /**
                         * sort order value
                         * 'sort order value' < 10: step displays before shipping step;
                         * 10 < 'sort order value' < 20 : step displays between shipping and payment step
                         * 'sort order value' > 20 : step displays after payment step
                         */
                        15
                        );

                return this;
            },

            /**
             * The navigate() method is responsible for navigation between checkout step
             * during checkout. You can add custom logic, for example some conditions
             * for switching to your custom step
             * When the user navigates to the custom step via url anchor or back button we_must show step manually here
             */
            navigate: function () {

                this.isVisible(true);
            },

            /**
             * @returns void
             */
            navigateToNextStep: function () {
                stepNavigator.next();
            }
        });
    }
);

Vendor/Module/view/frontend/web/template/schedule_on_appointment.html

        <form data-bind="submit: navigateToNextStep" novalidate="novalidate">

                    <button data-role="opc-continue" type="submit" class="button action continue primary">

                    </button>

        </form>

Vendor/Module/view/frontend/layout/checkout_index_index.xml
  <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="steps" xsi:type="array">
                                    <item name="children" xsi:type="array">

                                        <item name="schedule-step" xsi:type="array">
                                            <item name="component" xsi:type="string">Vendor_Module/js/view/schedule-on-appointment-view</item>
                                            <item name="displayArea" xsi:type="string">schedule_on_appointment</item>

                                            <item name="sortOrder" xsi:type="string">2</item>
                                            <item name="children" xsi:type="array">

                                                <item name="schedulesData" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                        <item name="scheduleAdditional" xsi:type="array">
                                                            <item name="component" xsi:type="string">uiComponent</item>
                                                            <item name="displayArea" xsi:type="string">scheduleAdditional</item>
                                                            <item name="children" xsi:type="array">
                                                                <item name="delivery_date" xsi:type="array">
                                                                    <item name="component" xsi:type="string">uiComponent</item>
                                                                    <item name="displayArea" xsi:type="string">schedule_on_appointment_form</item>
                                                                    <item name="deps" xsi:type="string">checkoutProvider</item>
                                                                    <item name="dataScopePrefix" xsi:type="string">delivery_date</item>
                                                                    <item name="children" xsi:type="array">
                                                                        <item name="form-fields" xsi:type="array">
                                                                            <item name="component" xsi:type="string">Vendor_Module/js/view/schedule-on-appointment-data</item>
                                                                            <item name="displayArea" xsi:type="string">schedule_on_appointment_form</item>
                                                                            <item name="children" xsi:type="array">

                                                                                <item name="delivery_date" xsi:type="array">
                                                                                <item name="component" xsi:type="string">Vendor_Module/js/view/delivery-date</item>
                                                                                <item name="config" xsi:type="array">
                                                                                <item name="customScope" xsi:type="string">delivery_date</item>
                                                                                <item name="template" xsi:type="string">ui/form/field</item>
                                                                                <item name="elementTmpl" xsi:type="string">Hicare_Slot/fields/delivery-date</item>
                                                                                <item name="options" xsi:type="string"></item>
                                                                                <item name="id" xsi:type="string">delivery_date</item>
                                                                                <item name="data-bind" xsi:type="array">
                                                                                <item name="datetimepicker" xsi:type="boolean">true</item>
                                                                                </item>

                                                                                </item>
                                                                                <item name="dataScope" xsi:type="string">delivery_date.delivery_date</item>
                                                                                <item name="label" xsi:type="string">Select Date</item>
                                                                                <item name="provider" xsi:type="string">checkoutProvider</item>
                                                                                <item name="visible" xsi:type="boolean">true</item>
                                                                                <item name="validation" xsi:type="array">
                                                                                <item name="required-entry" xsi:type="boolean">true</item>
                                                                                </item>
                                                                                <item name="sortOrder" xsi:type="string">10</item>
                                                                                <item name="id" xsi:type="string">delivery_date</item>

                                                                                </item>

                                                                                <item name="delivery_slot" xsi:type="array">

                                                                                <item name="component" xsi:type="string">Magento_Ui/js/form/element/select</item>
                                                                                <item name="config" xsi:type="array">
                                                                                <item name="customScope" xsi:type="string">delivery_date</item>
                                                                                <item name="template" xsi:type="string">ui/form/field</item>
                                                                                <item name="elementTmpl" xsi:type="string">ui/form/element/select</item>
                                                                                <item name="id" xsi:type="string">delivery_slot</item>
                                                                                <item name="data-bind" xsi:type="array">
                                                                                <item name="datetimepicker" xsi:type="boolean">true</item>
                                                                                </item>

                                                                                </item>
                                                                                <item name="dataScope" xsi:type="string">delivery_date.delivery_slot</item>
                                                                                <item name="label" xsi:type="string">Time Slots</item>
                                                                                <item name="provider" xsi:type="string">checkoutProvider</item>
                                                                                <item name="visible" xsi:type="boolean">true</item>
                                                                                <item name="validation" xsi:type="array">
                                                                                <item name="required-entry" xsi:type="boolean">true</item>
                                                                                </item>
                                                                                <item name="sortOrder" xsi:type="string">20</item>
                                                                                <item name="id" xsi:type="string">delivery_slot</item>

                                                                                </item>

                                                                            </item>
                                                                        </item>
                                                                    </item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>

</page>

Vendor/Module/view/frontend/web/js/view/schedule-on-appointment-data.js
  define([
    'jquery',
    'ko',
    'Magento_Ui/js/form/form'
], function ($, ko, Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Vendor_Module/schedule_on_appointment'
        }
    });
});

This result only I got:

I have to add some custom form fields into this section and save it to the database.
Let me know, what I am doing wrong.
Thanks in advance.


text:
Q: How do I check cocoapods version? How do I check cocoapods version?
I looked in the official site -
https://guides.cocoapods.org/using/getting-started.html
but found only how to install \ update the latest version, or solving versions conflicts of installed gems etc'...

A: $pod --version

Gives you the version. found it on this guide here:
https://www.cocoanetics.com/2013/11/updating-cocoapods/

A: To check version of cocoapods from terminal:
For sudoless:
gem which cocoapods

For sudo:
sudo gem which cocoapods

My previous post


text:
Q: (Rails 3) Is it possible to hardcode ids in a named route? As far as I know, the following is the encouraged way to create a simple named route in Rails 3:
match 'sign-in' => 'sessions#create', :as => :sign_in
Is there a clean way to hardcode an id (or any parameter) in a named route? For a silly example:
match 'first-user' => 'users#show', :as => :first_user, :id => 1

A: Did you try that? It just works like that.


text:
Q: Vectorize loss function with complex indexing I have written a loss function in pytorch, however, it is too slow.
Thus, I'm trying to vectorize it.
Description
Given two meshes, it computes the distortion between patches (i.e. set of vertices) defined on them. The distortion is how much the distances between each pair of points changes.

*

*Patches may have different sizes

*This assumes a correspondence between M and N.

*The loss accept batches.

Non-vectorized code
def loss_func(y_pred, batch):
    y_true = batch['vertices']
    patches: Tuple(Tensor,...) = batch['patches']

    loss = 0
    for i in range(y_pred.shape[0]):
        patch_loss = 0
        for patch in patches:
            dist_a = torch.pdist(y_pred[i][patch])
            dist_b = torch.pdist(y_true[i][patch])

            patch_loss += torch.sum((dist_a - dist_b) ** 2)

        loss += patch_loss
    return loss / y_pred.shape[0]

Vectorization attempt
def loss_func(y_pred, batch):
    y_true = batch['vertices']
    patches: Tuple(Tensor,...) = batch['patches']

    pred_dists = torch.cdist(y_pred, y_pred)
    true_dists = torch.cdist(y_true, y_true)

    diff_dists = (pred_dists - true_dists) ** 2

    loss = 0
    for patch in patches:
        d = diff_dists[:, patch, :][:, :, patch]
        loss += torch.sum(d, dim=(1, 2)) / 2

    return loss.mean()

Problem
It is still too slow.
I'm encountering difficulties in the vectorization since the patches may have different dimensions, thus they can't be put in a tensor.
I have the feeling that I could use directly the adjacency matrix to vectorize the code, without gathering the vertex indices in patches.
The patches are computed in this way:
def get_patch(vertex_index, vertex2vertex):
    return vertex2vertex[vertex_index, :].nonzero().squeeze(-1)

Working example
I prepared a self contained example to test and experiment with the two functions, with some benchmarks.
In the benchmark there is the same loss function without patches (i.e. just the distortion between all the vertices) as reference time
import torch
import time

device = 'cuda'
precision = torch.double
batch_size = 8
num_vertices = 400
dim = 2

y_pred = torch.rand(batch_size, num_vertices, dim, device=device, dtype=precision)
y_true = torch.rand(batch_size, num_vertices, dim, device=device, dtype=precision)

adjacency = (torch.rand(num_vertices, num_vertices, device=device, dtype=precision) > 0.95).to(precision)

def get_patch(vertex_index, vertex2vertex):
    return vertex2vertex[vertex_index, :].nonzero().squeeze(-1)

patches = tuple(get_patch(i, adjacency) for i in range(num_vertices))
batch = {
    'vertices': y_true,
    'patches': patches
}

def loss_func(y_pred, batch):
    y_true = batch['vertices']
    patches: Tuple(Tensor,...) = batch['patches']

    loss = 0
    for i in range(y_pred.shape[0]):
        patch_loss = 0
        for patch in patches:
            dist_a = torch.pdist(y_pred[i][patch])
            dist_b = torch.pdist(y_true[i][patch])

            patch_loss += torch.sum((dist_a - dist_b) ** 2)

        loss += patch_loss
    return loss / y_pred.shape[0]

def loss_func_vec(y_pred, batch):
    y_true = batch['vertices']
    patches: Tuple(Tensor,...) = batch['patches']

    pred_dists = torch.cdist(y_pred, y_pred)
    true_dists = torch.cdist(y_true, y_true)

    diff_dists = (pred_dists - true_dists) ** 2

    loss = 0
    for patch in patches:
        d = diff_dists[:, patch, :][:, :, patch]
        loss += torch.sum(d, dim=(1, 2)) / 2

    return loss.mean()

def reference_no_patches(y_pred, batch):
    y_true = batch['vertices']
    da = torch.cdist(y_pred, y_pred)
    db = torch.cdist(y_true, y_true)
    return torch.sum((da - db) ** 2) / y_true.shape[0] / 2

print(f'LOSS FUNCTION (ITERATION): TIME (LOSS)')
print()

for i in range(5):
    start_time = time.time()
    res = loss_func(y_pred, batch)
    torch.cuda.synchronize()
    print(f'Standard {i}:\t{time.time() - start_time:.4f}s ({res:.5f})')
print()

for i in range(5):
    start_time = time.time()
    res = loss_func_vec(y_pred, batch)
    torch.cuda.synchronize()
    print(f'Vectorized {i}:\t{time.time() - start_time:.4f}s ({res:.5f})')
print()

for i in range(5):
    start_time = time.time()
    res = reference_no_patches(y_pred, batch)
    torch.cuda.synchronize()
    print(f'Reference without patches {i}:\t{time.time() - start_time:.4f}s ({res:.5f})')

LOSS FUNCTION (ITERATION): TIME (LOSS)

Standard 0: 0.3311s (9744.87875)
Standard 1: 0.2853s (9744.87875)
Standard 2: 0.2929s (9744.87875)
Standard 3: 0.2972s (9744.87875)
Standard 4: 0.2714s (9744.87875)

Vectorized 0:   0.0254s (9744.87875)
Vectorized 1:   0.0251s (9744.87875)
Vectorized 2:   0.0262s (9744.87875)
Vectorized 3:   0.0242s (9744.87875)
Vectorized 4:   0.0241s (9744.87875)

Reference without patches 0:    0.0063s (9695.41083)
Reference without patches 1:    0.0062s (9695.41083)
Reference without patches 2:    0.0062s (9695.41083)
Reference without patches 3:    0.0066s (9695.41083)
Reference without patches 4:    0.0067s (9695.41083)

Context
The matrices involved are small. The number of vertices in each mesh is ~500, thus the adjacency matrix is [500, 500].
The patches may vary in dimension, however each one is << 500. There is one patch for each vertex (i.e. each vertex is the center of a patch), thus the number of patches is O(n!) (thus, I can't stack the patches into a single vector to perform the indexing).
I used the double precision in the example only to avoid numerical errors in the results, I plan to use float precision.
Finally, I will be happy to receive any suggestions on how to improve speed!
Update
Due to this bug I have to be careful with the memory allocation.
I rewrote the vectorized code as:
def loss_func_vec_mem(y_pred, batch):
    y_true = batch['vertices']
    patches: Tuple(Tensor,...) = batch['patches']

    loss = 0
    for patch in patches:
        pred = y_pred[:, patch, :]
        true = y_true[:, patch, :]

        pred_dists = torch.cdist(pred, pred)
        true_dists = torch.cdist(true, true)

        diff_dists = (pred_dists - true_dists) ** 2

        loss += torch.sum(diff_dists, dim=(1, 2))
    return loss.mean() / 2

Although it's even slower:
LOSS FUNCTION (ITERATION): TIME (LOSS)

Vec mem 0:  0.0484s (14685.45521)
Vec mem 1:  0.0489s (14685.45521)
Vec mem 2:  0.0471s (14685.45521)
Vec mem 3:  0.0471s (14685.45521)
Vec mem 4:  0.0459s (14685.45521)

Vectorized 0:   0.0271s (29370.91043)
Vectorized 1:   0.0262s (29370.91043)
Vectorized 2:   0.0320s (29370.91043)
Vectorized 3:   0.0266s (29370.91043)
Vectorized 4:   0.0263s (29370.91043)

Standard 0: 0.1680s (14685.45521)
Standard 1: 0.1614s (14685.45521)
Standard 2: 0.1639s (14685.45521)
Standard 3: 0.1606s (14685.45521)
Standard 4: 0.1694s (14685.45521)

Reference without patches 0:    0.0049s (12874.01275)
Reference without patches 1:    0.0105s (12874.01275)
Reference without patches 2:    0.0103s (12874.01275)
Reference without patches 3:    0.0092s (12874.01275)
Reference without patches 4:    0.0100s (12874.01275)


text:
Q: How do I add a form value to a URL using Django I have a simple form. It has a field that accepts a hostname and a submit button. When the form is submitted my app gets some info about the host provided and display it to the user.
What I'd like to do is after the form is submitted have the URL updated to include the hostname provided by the user. For example:
http://my-host-checker.com

becomes
http://my-host-checker.com/acme.com

Also I would then like someone to be able to email the second URL as a link that can be used to automatically submit the request and get to the results page.
I'm very much a Django newbie and would appreciate some code examples if this is indeed possible.

A: Look at the documentation for Django URL dispatcher.  It is pretty straight forward.  For your example, you would probably need to use a catch-all regex like:
r'^(?P<site>.*)$'

I would suggest using a sub-folder, though, so that you can include other pages on your site.  Something like:
r'^sites/(?P<site>.*)$'

A: The general idea is that you do a redirect after your form data is successfully processed.
Take a look at this example (which even shows how to send a mail).
Now, instead of redirecting to a static page (HttpResponseRedirect('/thanks/')) you should redirect to the detail view of your newly created object.
Assumed you already have a view setup for the detail pages of your hosts you can direct the user to the get_absolute_url() of the newly created object (check the permalink docs for more information).
HttpResponseRedirect(new_host.get_absolute_url())


text:
Q: SQL Query filter by status I had the following sort of table:
id      status      iteration
----    -------     ----------
1111    1           1
1111    3           2
1111    4           3
1112    1           1
1113    1           1
1113    4           2
1114    1           1

the problem i am facing is trying to make a query with the IDs whose status is 1 or 3. If the status is ever 4, we should remove that id from the query.
I had made the following query but i can only seem to get the results which have been 1 or 3. if the same id has a status of 4, i can't filter it out.
Select id,status, iteration
from table
WHERE status IN (1,3) ;

Any help is greatly appreciated

A: I think this is what you want:
SELECT id, status, iteration
FROM table
WHERE id NOT IN (SELECT id FROM table WHERE status=4)

...which just excludes the 4's.  If you truly just want 1's and 3's and exclude everything else:
SELECT id, status, iteration
FROM table
WHERE id NOT IN (SELECT id FROM table WHERE status NOT IN (1, 3))

thanks to @sstan for catching some bad logic in the second example!

A: This should give you the expected result:
select *
from table t1
where status in (1,3)
and not EXISTS
(
    select * from table t2 where t2.id = t1.id and t2.status = 4
)

A: The query may need to be changed depending on what Sql version you are looking for but if I understand what you are asking you only expect to get back the 1112 and the 1114 records based on what you described.  If that is correct here is my version of your query request.
select Id, Status, Iteration
from table
where Id not in (select Id from table where Status = 4 )


text:
Q: Optimizing many require_once calls I have a website that has about 150 require_once calls in a "catalog" page. Each page calls require_once on this catalog to make sure all necessary files are loaded. Calling require_once on this catalog takes somewhere between 5 and 15 seconds, and I have no easy way to reduce the number of classes each page needs.
So: is there any way to speed up this process? I assume it will need to be done once, but I also assumed it would be cached for the session, which doesn't seem to be the case since this 5-15 second overhead is the same on every single page load.
Hopefully this makes sense.
Thanks!

A: The idea behind require_once is to make sure:

*

*You don't have the file more than once.

*Make load times faster so that the file isn't included again.

PHP stores in memory what files have already been loaded. If you call require_once on a file and then call it again, PHP won't even look for the file, it'll see that it's already been loaded and won't bother to read the file.
This makes me think that require_once isn't the culprit of your page load issues.
However, I may  be misunderstanding the question. If you mean that each require_once is different, then that's another story. IF they are used to load classes, check out the PHP autoload function. PHP: Autoloading Classes. This will only load the classes that are called upon.

A: My first guess would be that you have some logic defined in one of your required scripts.  If they were all just class definition files, there's no reason requiring them would take 5-15 seconds.
Is there some reason you're including every class on every page?  You should look into autoloading classes instead, if possible.


text:
Q: Remembering a 90's childrens book about disease, female protagonist with a mutant sheep? During the year 2001 I read a children's horror novel, whose title I have forgotten. I would really like to read it again as an adult, I think about this book all the time! Unfortunately it has been difficult to track down, as I can remember 6 things about this book:

*

*It was most likely set in Australia, though I could be wrong.

*It had a greenish cover, possibly with a slightly horrific picture of a zombie sheep. Again, I could be wrong.

*The female main character's father gets remarried, and her male friend (her step brother?) gets infected with an illness.

*Later on they find her late mother's crashed school bus, and get chased by a sheep which is infected with the illness, and it shies away from her dead mum's trainer, because the mould growing on it is the cure.

*The boy and girl are attacked later on by plants infected with the disease, which stop their car and drink the fuel from their tank

*They later take shelter in a sewer and find the boy's father, who also has the disease but has controlled it somehow with this mould stuff.
If anyone recognises any of this please reply- even if it is only to say that you read it too!

A: This is the series "Wicked" by Paul Jennings and Morris Gleitzman, two wonderful Australian authors.

*

*The Slobberers

*Battering rams

*Croaked

*Dead ringer

*Creeper

*Till death us do part

They are published as one book, but I first met them written as one story, spread across 6 short books.  It's been a while since I read them, but from the titles, Battering Rams has the carnivorous sheep, and Creeper has the infected plants.
Here's a link to the book on Paul Jenning's website.


text:
Q: laravel blade echo misplacement From the little I understand of Laravel Im quite thrown off by whats happening.
Browser output
Blade template being loaded
<link rel='stylesheet' type='text/css' href="{{asset('/css/app.css')}}">
Overview
Suppliers
Resources
Prices
Reciepes
Add
@if($modal)

@foreach($modal->get_display_fields() as $e)
     {{$e->label}}
@endforeach

@foreach($items as $item)
    {{$item->init_fields()}}
    @foreach($item->get_display_fields() as $q)

        {{$q->value}}

    @endforeach

@endforeach

@endif

The intention is that a table is created with rows with each having a value printed into it

A: Try this code and lemme know if you face any issues
<link rel='stylesheet' type='text/css' href="{{asset('/css/app.css')}}">
Overview
Suppliers
Resources
Prices
Reciepes
Add
@if($modal)

@foreach($modal->get_display_fields() as $e)
     {{$e->label}}
@endforeach

@foreach($items as $item)
    {{$item->init_fields()}}
    @foreach($item->get_display_fields() as $q)

        {{$q->value}}

    @endforeach
@endforeach

@endif

A: <link rel='stylesheet' type='text/css' href="{{asset('/css/app.css')}}">
Overview
Suppliers
Resources
Prices
Reciepes
Add
@if($modal)

@foreach($modal->get_display_fields() as $e)
     {{$e->label}}
@endforeach

@foreach($items as $item)
    {{$item->init_fields()}}
    @foreach($item->get_display_fields() as $q)

           {{$q->value}}

    @endforeach
@endforeach

@endif


text:
Q: When should I not implement a trait for references to implementors of that trait? If I have a trait, and a function that accepts a generic type constrained to that type, everything works fine. If I try to pass in a reference to that type, I get a compilation error.
trait Trait {
    fn hello(&self) -> u32;
}

struct Struct(u32);

impl Trait for Struct {
    fn hello(&self) -> u32 {
        self.0
    }
}

fn runner<T: Trait>(t: T) {
    println!("{}", t.hello())
}

fn main() {
    let s = Struct(42);

    // Works
    runner(s);

    // Doesn't work
    runner(&s);
}

error[E0277]: the trait bound `&Struct: Trait` is not satisfied
  --> src/main.rs:24:5
   |
24 |     runner(&s);
   |     ^^^^^^ the trait `Trait` is not implemented for `&Struct`
   |
   = help: the following implementations were found:
             <Struct as Trait>
note: required by `runner`
  --> src/main.rs:13:1
   |
13 | fn runner<T: Trait>(t: T) {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^

I can fix the issue by implementing the trait for any reference to a type that implements the trait:
impl<'a, T> Trait for &'a T
where
    T: Trait,
{
    fn hello(&self) -> u32 {
        (*self).hello()
    }
}

The piece of information that I'm missing is when shouldn't I implement this? Asked another way, why doesn't the compiler automatically implement this for me? Since it currently doesn't, I assume there must be cases where having this implementation would be disadvantageous.

A:
when shouldn't I implement this? Asked another way, why doesn't the compiler automatically implement this for me? Since it currently doesn't, I assume there must be cases where having this implementation would be disadvantageous.

As an example, the Default trait immediately came to mind.
pub trait Default {
    fn default() -> Self;
}

I could implement it for T, but there is no way to automatically implement it for &T.

A: The particular trait you are writing here only takes self by reference, and that is the only reason it is possible to write the additional implementation you did.
For this reason, taking the parameter to runner() by value is probably undesirable; you should instead be taking it by reference. This guideline can apply generally: if it is possible to implement the trait for a reference then rather than wondering "should I implement it?" you should wonder "why would I implement it?" for the only cases where you would use it should probably be altered to take the object by reference in the first place.


text:
Q: Theoretical analysis for repeated trust game I am studying trust game (Berg, 1995). There are 2 players in this game: A and B.
A moves first. A sends an amount between 0 and 10 to B. The amount is tripled in B's side. B sends back an amount between 0 and what she got to A.
Suppose A sent 5 to B. B receives 3*5 = 15. B sent back 9 to A. A receives 9.
In this case, the profit of A is 9 - 5 = 4, and the profit of B is 15 - 9 = 6.
(it is a turn-based game).
In fact, I am focusing on repeated trust game, i.e. A and B play again and again. In some rounds A moves first, and in some rounds, B moves first.
I wonder if there exist some studies that analyze the behavior of two players in this repeated game? I tried to look on Google Scholar, but I only found the analysis for repeated prisoner-dilemma or repeated sequential prisoner dilemma (i.e. A and B have only two choices: cooperate or deficit, and they play by turn).
I found a lot of studies that analyze the behavior of players in game empirically, but I did not find a study that analyzes the behavior theoretically, e.g. analyze the Nash equilibrium for two players.
I note that the game sometimes is called investment game.
I appreciate any help.
References:
[1] Berg, Joyce, John Dickhaut, and Kevin McCabe. "Trust, reciprocity, and social history." Games and economic behavior 10.1 (1995): 122-142.

A: I'll assume that turns alternate, there are many turns, and it is unknown when the game will end. The rational cooperative optimum is that each player sends $10$ and gets back $x.$ It doesn't matter what $x$ is as long as it is always the same, so it may as well be $0.$
I could adopt the policy that I will send you $10$ if I go first and otherwise , if you sent me $x$ on the previous turn, I will keep the whole $3x$ and send you $x$ next time.  If you know for sure I will do that then your optimal selfish strategy is to to always send me $10$ and keep what you get (which will be $10$ tripled).
I suppose there may be no harm in my taking into account what you returned to me last time I was the sender, but also questionable competitive advantage. It is simpler, and efficient, to establish a mutual "keep it simple" no send backs policy. Still, if two turns ago I sent you $x$ and you returned $y \leq 3x$ and now you just sent me $z,$ then perhaps I should plan to send you $w=\min(10,y+z)$ on my next turn and return to you now $\max(0,y+z-10).$ If $y+z-10 \gt 3z$ then the best I can do is send you back $3z.$ As I said, no send back is simpler.
This is pretty much like tit for tat in serial prisoners dilemma. The same considerations arise, If periodically a error happens like you send $x$ but I receive only $x-1$ (or vice-versa) then eventually no-one will send anything. Some forgiveness would avoid such a death spiral, but also could be exploited by a selfish opponent.

A: This game is a standard repeated game, hence its analysis follows the standard analysis of repeated games.
Let me assume that in odd stages one player is the sender and in even stages it is the other.
For the infinitely repeated game: the minmax value of each player in the stage game is 0 (each player can send 0, lowering the other player's payoff to 0). The set of equilibrium payoffs of the infinitely repeated game is the set of feasible and individually rational payoffs, which is the intersection of the nonnegative orthant and the triangle whose extreme points are (0,0), (-10,30), and (10,20).
For the finitely repeated game, you should check whether there are end effects. In this case, as in the repeated prisoner's dilemma, there are. The receiver in the last period has no incentive to send anything to the sender. Hence the sender in the last period has no incentive to send anything to the receiver, and this propagates back to the first stage, so that no player will ever send anything to the other player, and the unique equilibrium payoff is (0,0).
If the order by which players play is dictated by some random process, then the set of equilibrium payoffs may be different than above.


text:
Q: ProgressDialog leaked window error only in Portrait mode I am developing an app which takes a picture and does some long processing. During processing I would like to show the status via a ProgressDialog, hence I extended the AsyncTask class as following
private class ResultTask extends AsyncTask<multiCrop, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setTitle("Analyzing, please wait ...");
        progressDialog.setMessage("Loading..");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(multiCrop... mcImgV) {
        String result = null;
        //Long processing that uses view multiCrop and occasional publishProgress() calls, returns String result
    }

    @Override
    protected void onProgressUpdate(String... str) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(str);
        progressDialog.setMessage(str[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        ((TextView)findViewById(R.id.resultText)).append(result);
        progressDialog.dismiss();
    }

}

An instance of ResultTask is created in the onClick handler of one of the buttons in the view as shown below
public void onResultClick(View v){
    ResultTask task = new ResultTask();
    task.execute(babyImageView);
}

When the device is in Landscape the code works without any problem, but if the onResultClick event is triggered in the portrait mode I get an error stating that MainActivity has a LeakedWindow.
What am I missing here ?
* Please note that this error occurs even if there is no orientation change
LogCat when error occurs
12-09 21:34:57.080: E/WindowManager(15365):     Activity com.example.jaundicedetect.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@410f5070 that was originally added here
12-09 21:34:57.080: E/WindowManager(15365):     android.view.WindowLeaked: Activity com.example.jaundicedetect.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@410f5070 that was originally added here
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:350)
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.Window$LocalWindowManager.addView(Window.java:537)
12-09 21:34:57.080: E/WindowManager(15365):     at android.app.Dialog.show(Dialog.java:286)
12-09 21:34:57.080: E/WindowManager(15365):     at com.example.jaundicedetect.MainActivity$ResultTask.onPreExecute(MainActivity.java:328)
12-09 21:34:57.080: E/WindowManager(15365):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
12-09 21:34:57.080: E/WindowManager(15365):     at android.os.AsyncTask.execute(AsyncTask.java:511)
12-09 21:34:57.080: E/WindowManager(15365):     at com.example.jaundicedetect.MainActivity.onResultClick(MainActivity.java:524)
12-09 21:34:57.080: E/WindowManager(15365):     at java.lang.reflect.Method.invokeNative(Native Method)
12-09 21:34:57.080: E/WindowManager(15365):     at java.lang.reflect.Method.invoke(Method.java:511)
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.View$1.onClick(View.java:3039)
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.View.performClick(View.java:3511)
12-09 21:34:57.080: E/WindowManager(15365):     at android.view.View$PerformClick.run(View.java:14110)
12-09 21:34:57.080: E/WindowManager(15365):     at android.os.Handler.handleCallback(Handler.java:605)
12-09 21:34:57.080: E/WindowManager(15365):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-09 21:34:57.080: E/WindowManager(15365):     at android.os.Looper.loop(Looper.java:137)
12-09 21:34:57.080: E/WindowManager(15365):     at android.app.ActivityThread.main(ActivityThread.java:4447)
12-09 21:34:57.080: E/WindowManager(15365):     at java.lang.reflect.Method.invokeNative(Native Method)
12-09 21:34:57.080: E/WindowManager(15365):     at java.lang.reflect.Method.invoke(Method.java:511)
12-09 21:34:57.080: E/WindowManager(15365):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-09 21:34:57.080: E/WindowManager(15365):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-09 21:34:57.080: E/WindowManager(15365):     at dalvik.system.NativeStart.main(Native Method)

A: Try this --
    protected void onPostExecute(String result) {
            super.onPostExecute(result);
   progressDialog.dismiss();

   ((TextView)findViewById(R.id.resultText)).append(result);
         }

A: First thing try to use progress dialog inside the UI thread.
        public class LoginScreen extends FragmentActivity {
        ProgressDialog progressDialog;

        @Override
        protected void onCreate(Bundle arg0) {
            // TODO Auto-generated method stub
            super.onCreate(arg0);
            requestWindowFeature(Window.FEATURE_NO_TITLE);

                setContentView(R.layout.activity_login);
    progressDialog = ProgressDialog.show(
                                                LoginScreen.this, null,
                                                "Logging you in...");
                                        progressDialog.setCancelable(false);
    }
public void progressDialogDismiss() {
        LoginScreen.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
            }
        });
    }
    }

Try to use like this.
use it an util class.

A: Sorry people, apparently the error was in the few lines just before ResultTask instance, I was extracting bitmap from the multiCrop view which was outside the bounds of the view.
Thanks for all your suggestions.


text:
Q: Servlet+jQuery/Ajax - Unexpted token o I'm new to developing web applications with Java. I'm trying to establish an AJAX call. This is some arbitrary code that I've created.
Servlet
        Map<String, String> testJson = new HashMap<String, String>();
    String Key = "someKey";
    String Value = "someValue";

    testJson.put(Key, Value);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(new Gson().toJson(testJson));
}

jQuery
    $(document).on("click","#register-user", function(){
    $.ajax({
        type: 'GET',
        url: 'Register',
        success: function(data){
            alert($.parseJSON(data));
        }
    });
    return false;
});

The callback function is working without any Json so the AJAX is fine. But when I try to send back a Java object that is encoded with Json I get an "Uncaught exception. Unexpected token o". What am I doing wrong?

A: Try this
Gson gson = new GsonBuilder().create();
String json = gson.toJson(testJson);

or try a little something like this
 Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
 String json = gson.toJson(map, typeOfMap);

More examples of the above on this link
and then return the Stringed JSON


text:
Q: Activity doesn't start from two different ones but from only one I have several activities in my app. I'd like to start an activity say A from other two separate ones, B and C.
From B A starts good, from C it alerts me with ANR advise. Cosidering that:
  1. Activities are all declared in the Manifest
  2. There are no incoerent castings

And this is the activity A that must be opened:
package com.wikibuyers.aforismi;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
 import java.io.Writer;

 import android.app.Activity;
 import android.content.Intent;
 import android.graphics.drawable.LayerDrawable;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewTreeObserver;
 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
 import android.view.animation.AlphaAnimation;
 import android.view.animation.Animation;
 import android.widget.Button;
 import android.widget.ImageButton;
 import android.widget.Toast;

public class ElencoAforismiActivity extends Activity{

  public final static String EXTRA_MESSAGE = "com.example.provacomunicazionefraactivity.MESSAGE";

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.elecoalfabeticoautori);

  Button bottoneA = (Button)findViewById(R.id.buttonA);
  Button bottoneB = (Button)findViewById(R.id.buttonB);
  Button bottoneC = (Button)findViewById(R.id.buttonC);
  [...]
        Button bottoneX = (Button)findViewById(R.id.buttonX);
  Button bottoneY = (Button)findViewById(R.id.buttonY);
  Button bottoneZ = (Button)findViewById(R.id.buttonZ);
  ImageButton Preferiti = (ImageButton)findViewById(R.id.buttonPreferiti);

  bottoneA.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Button myButton = (Button) findViewById(R.id.buttonA );
             Animation anim = new AlphaAnimation(0.0f, 1.0f);// LAMPEGGIO BOTTONE 1
              anim.setDuration(20); //SI PUò CONTROLLARE LA DURATA DEL LAMPEGGIO CON QUESTO PARAMETRO
              anim.setStartOffset(20);
              anim.setRepeatMode(Animation.REVERSE);
              myButton.startAnimation(anim);
              anim.setRepeatCount(5);
                 String message = "A" ;

                Intent i = new Intent(getApplicationContext(), LetteraElencoSelezionataActivity.class);
                    i.putExtra(EXTRA_MESSAGE, message);
                   startActivity(i);
        }
    });

  bottoneB.setOnClickListener(new View.OnClickListener() {

      @Override
        public void onClick(View v) {
            Button myButton = (Button) findViewById(R.id.buttonB );
             Animation anim = new AlphaAnimation(0.0f, 1.0f);// LAMPEGGIO BOTTONE 1
              anim.setDuration(20); //SI PUò CONTROLLARE LA DURATA DEL LAMPEGGIO CON QUESTO PARAMETRO
              anim.setStartOffset(20);
              anim.setRepeatMode(Animation.REVERSE);
              myButton.startAnimation(anim);
              anim.setRepeatCount(5);
         String message = "B" ;

        Intent i = new Intent(getApplicationContext(), LetteraElencoSelezionataActivity.class);
            i.putExtra(EXTRA_MESSAGE, message);
           startActivity(i);
        }
    });

  bottoneC.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Button myButton = (Button) findViewById(R.id.buttonC );
             Animation anim = new AlphaAnimation(0.0f, 1.0f);// LAMPEGGIO BOTTONE 1

              anim.setDuration(20); //SI PUò CONTROLLARE LA DURATA DEL LAMPEGGIO CON QUESTO PARAMETRO
              anim.setStartOffset(20);
              anim.setRepeatMode(Animation.REVERSE);
              myButton.startAnimation(anim);

              anim.setRepeatCount(5);

              String message = "C" ;

                Intent i = new Intent(getApplicationContext(), LetteraElencoSelezionataActivity.class);
                    i.putExtra(EXTRA_MESSAGE, message);
                   startActivity(i);
        }
    });

 [...omissis]

  Preferiti.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {ImageButton myButton = (ImageButton) findViewById(R.id.buttonPreferiti );
             Animation anim = new AlphaAnimation(0.0f, 1.0f);// LAMPEGGIO BOTTONE 1
              anim.setDuration(20); //SI PUò CONTROLLARE LA DURATA DEL LAMPEGGIO CON QUESTO PARAMETRO
              anim.setStartOffset(20);
              anim.setRepeatMode(Animation.REVERSE);
              myButton.startAnimation(anim);
              anim.setRepeatCount(5);

        Intent i = new Intent(getApplicationContext(),  PreferitiActivity.class);
                //    i.putExtra(EXTRA_MESSAGE, message);
                   startActivity(i);

        }
    });

      final Button BT1 = (Button)findViewById(R.id.buttonA);
        ViewTreeObserver vto1 = BT1.getViewTreeObserver();
        vto1.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
            @Override
            public void onGlobalLayout() {
                LayerDrawable ld1 = (LayerDrawable)BT1.getBackground();
                ld1.setLayerInset(1,0, 0, 0, BT1.getHeight()/2);}});

     final Button BT2 = (Button)findViewById(R.id.buttonB);
        ViewTreeObserver vto2 = BT2.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
          @Override
          public void onGlobalLayout() {
                LayerDrawable ld1 = (LayerDrawable)BT2.getBackground();
                ld1.setLayerInset(1,0, 0, 0, BT2.getHeight()/2);}});

     final Button BT3 = (Button)findViewById(R.id.buttonC);
        ViewTreeObserver vto3 = BT3.getViewTreeObserver();
        vto3.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
        @Override
        public void onGlobalLayout() {
            LayerDrawable ld1 = (LayerDrawable)BT3.getBackground();
            ld1.setLayerInset(1,0, 0, 0, BT3.getHeight()/2);}});

   [.........omissis]
     final Button BT16 = (Button)findViewById(R.id.buttonP);
        ViewTreeObserver vto16 = BT16.getViewTreeObserver();
        vto16.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
        @Override
        public void onGlobalLayout() {
        LayerDrawable ld1 = (LayerDrawable)BT16.getBackground();
        ld1.setLayerInset(1,0, 0, 0, BT16.getHeight()/2);}});

}
}
The LogCat is this: (excuse me but i never used it before)
 09-09 17:02:54.160: W/dalvikvm(21991): threadid=1: thread exiting with uncaught
     exception         (group=0x41476930)
09-09 17:02:54.223: E/AndroidRuntime(21991): FATAL EXCEPTION: main
09-09 17:02:54.223: E/AndroidRuntime(21991): java.lang.RuntimeException: Unable to
start           activity ComponentInfo
  {com.wikibuyers.aforismi/com.wikibuyers.
                                        java.lang.ArrayIndexOutOfBoundsException: length=48;
 index=48
 09-09 17:02:54.223: E/AndroidRuntime(21991):   at
 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
 09-09 17:02:54.223: E/AndroidRuntime(21991):   at
 android.app.ActivityThread.handleLaunchActivity
  (ActivityThread.java:2230)
  09-09 17:02:54.223: E/AndroidRuntime(21991):
at android.app.ActivityThread.access$600(ActivityThread.java:141)
   09-09 17:02:54.223: E/AndroidRuntime(21991):
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at android.os.Handler.dispatchMessage
(Handler.java:99)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at android.os.Looper.loop(Looper.java:137)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at android.app.ActivityThread.main
(ActivityThread.java:5039)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at java.lang.reflect.Method.invokeNative(Native
Method)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at java.lang.reflect.Method.invoke
(Method.java:511)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:560)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at dalvik.system.NativeStart.main(Native Method)
09-09 17:02:54.223: E/AndroidRuntime(21991): Caused by:
java.lang.ArrayIndexOutOfBoundsException: length=48; index=48
09-09 17:02:54.223: E/AndroidRuntime(21991):    at
com.wikibuyers.aforismi.RandomActivity.onCreate
(RandomActivity.java:1022)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at android.app.Activity.performCreate
(Activity.java:5104)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-09 17:02:54.223: E/AndroidRuntime(21991):    at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-09 17:02:54.223: E/AndroidRuntime(21991):    ... 11 more
09-09 17:03:32.918: D/AndroidRuntime(22223): Shutting down VM
09-09 17:03:32.918: W/dalvikvm(22223): threadid=1: thread exiting with uncaught exception
(group=0x41476930)
09-09 17:03:32.942: E/AndroidRuntime(22223): FATAL EXCEPTION: main
09-09 17:03:32.942: E/AndroidRuntime(22223): java.lang.RuntimeException: Unable to start
activity ComponentInfo{com.wikibuyers.aforismi/com.wikibuyers.aforismi.PreferitiActivity}:
java.lang.NullPointerException
09-09 17:03:32.942: E/AndroidRuntime(22223):    at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2230)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.app.ActivityThread.access$600
(ActivityThread.java:141)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.app.ActivityThread$H.handleMessage
(ActivityThread.java:1234)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.os.Handler.dispatchMessage
(Handler.java:99)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.os.Looper.loop(Looper.java:137)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.app.ActivityThread.main
(ActivityThread.java:5039)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at java.lang.reflect.Method.invokeNative(Native
Method)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at java.lang.reflect.Method.invoke
(Method.java:511)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:560)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at dalvik.system.NativeStart.main(Native Method)
09-09 17:03:32.942: E/AndroidRuntime(22223): Caused by: java.lang.NullPointerException
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.app.ContextImpl.makeFilename
(ContextImpl.java:1963)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.app.ContextImpl.openFileInput
(ContextImpl.java:692)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.content.ContextWrapper.openFileInput
(ContextWrapper.java:167)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at
com.wikibuyers.aforismi.PreferitiActivity.onCreate(PreferitiActivity.java:49)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at android.app.Activity.performCreate
(Activity.java:5104)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-09 17:03:32.942: E/AndroidRuntime(22223):    at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-09 17:03:32.942: E/AndroidRuntime(22223):    ... 11 more
09-09 17:03:57.676: I/Process(22223): Sending signal. PID: 22223 SIG: 9
09-09 17:03:57.981: D/OpenGLRenderer(22275): Enabling debug mode 0
09-09 17:04:04.801: D/AndroidRuntime(22275): Shutting down VM
09-09 17:04:04.801: W/dalvikvm(22275): threadid=1: thread exiting with uncaught exception
(group=0x41476930)
09-09 17:04:04.817: E/AndroidRuntime(22275): FATAL EXCEPTION: main
09-09 17:04:04.817: E/AndroidRuntime(22275): java.lang.RuntimeException: Unable to start
activity ComponentInfo{com.wikibuyers.aforismi/com.wikibuyers.aforismi.PreferitiActivity}:
java.lang.NullPointerException
09-09 17:04:04.817: E/AndroidRuntime(22275):    at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2230)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.app.ActivityThread.access$600
(ActivityThread.java:141)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.app.ActivityThread$H.handleMessage
(ActivityThread.java:1234)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.os.Handler.dispatchMessage
(Handler.java:99)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.os.Looper.loop(Looper.java:137)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.app.ActivityThread.main
(ActivityThread.java:5039)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at java.lang.reflect.Method.invokeNative(Native
Method)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at java.lang.reflect.Method.invoke
(Method.java:511)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:560)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at dalvik.system.NativeStart.main(Native Method)
09-09 17:04:04.817: E/AndroidRuntime(22275): Caused by: java.lang.NullPointerException
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.app.ContextImpl.makeFilename
(ContextImpl.java:1963)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.app.ContextImpl.openFileInput
(ContextImpl.java:692)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.content.ContextWrapper.openFileInput
(ContextWrapper.java:167)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at
com.wikibuyers.aforismi.PreferitiActivity.onCreate(PreferitiActivity.java:49)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at android.app.Activity.performCreate
(Activity.java:5104)
 09-09 17:04:04.817: E/AndroidRuntime(22275):   at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-09 17:04:04.817: E/AndroidRuntime(22275):    at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-09 17:04:04.817: E/AndroidRuntime(22275):    ... 11 more
09-09 17:04:04.832: D/dalvikvm(22275): GC_CONCURRENT freed 350K, 4% free 9283K/9664K, paused
2ms+4ms, total 23ms

Activity PreferitiActivity.java is this:
          package com.wikibuyers.aforismi;

 import java.io.FileNotFoundException;
 import java.io.OutputStreamWriter;
 import java.io.Reader;
 import java.io.InputStreamReader;
 import java.io.Writer;

 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
 import android.widget.Toast;

 import java.io.IOException;
 import java.util.ArrayList;

 public class PreferitiActivity extends Activity{

 public final static String EXTRA_MESSAGE = "com.example.provare.MESSAGE";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.preferiti);

      Intent intent = getIntent();
      String message = intent.getStringExtra(SingolaFraseSelezionataActivity.EXTRA_MESSAGE);

      Writer writer = null;

        try {
            //FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);

            // SPOSTA IL SALVATAGGIO DEL FILE IN PREFERITI IN MODO DA AVERE SALVATAGGIO E LETTURA
            // INSIEME E DA QUI MANDA SOLO LA FRASE AI PREFERITI

            writer = new OutputStreamWriter(openFileOutput(message,
                    MODE_PRIVATE));  //SE NON VA APPEND TORNIAMO A PRIVATE
            writer.write(message);
            Toast.makeText(getApplicationContext(), "Frase aggiunta ai Preferiti", Toast.LENGTH_LONG).show();
        }

              catch (IOException e) {
                    Log.e("Aforismi", "Impossibile salvare il file", e);
                    Toast.makeText(getApplicationContext(), "Errore", Toast.LENGTH_LONG).show();
                } finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (Throwable t) {
                        }
                    }
                }

      Reader reader = null;
        try {
            reader = new InputStreamReader(openFileInput(message));

            StringBuffer aux = new StringBuffer();

            char[] buf = new char[1024];
            int len;
            while ((len = reader.read(buf)) != -1) {
                aux.append(buf, 0, len);
            }

        } catch (FileNotFoundException e) {
            message = "";

        } catch (IOException e) {
            Log.e("FileDemo", "Impossibile aprire il file", e);
            message = "";

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Throwable t) {
                }
            }
        }

        ArrayList<String> FrasiAggiuntePreferiti = new ArrayList<String>();

        FrasiAggiuntePreferiti.add(message);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, FrasiAggiuntePreferiti);

          ListView listView = (ListView) findViewById(R.id.listView3);
          listView.setAdapter(adapter);

    }
}

A: Your issue is something to do with an Array out of bounds:
java.lang.ArrayIndexOutOfBoundsException: length=48;

From what I can tell, this is happenning at line: 2180 of your ActivityThread class.
Bottom line, you have a logic error in your code, which is stopping your Activity from starting up successfully.  Fix your Arrary "off by 1" error, and you should be set.

A: do you get the exception on button click? if so check your activity start code
Intent i = new Intent(getApplicationContext(), PreferitiActivity.class);
 startActivity(i);

otherwise i guess from reading your error message you must define activity c in your manifest
<activity android:name="com.wikibuyers.aforismi.C" >

EDIt
you've got an ArrayIndexOutOfBoundsException, you have lists, arrays that you didn't post and they are causing the problem... cheers :)

A: I must close this discussion because of a change in my stategy. I have understood I should better use a database for my aims so I'll rewrite my app.
Thanks to all for their precious answers.


text:
Q: Replace xml attribute values with constant values by xsl there is that XML Node
<svg>
    <g transform="translate(113.63-359.13)">
        <use fill="#f00" xlink:href="#D"/>
        <g transform="translate(72.59-8.504)">
            <use xlink:href="#E"/>
            <path fill="#f00" stroke="#000" stroke-linejoin="round" stroke-linecap="round" stroke-width=".24" d="m6.04 526.26h19.843v4.961h-19.843z"/>
            <use xlink:href="#F"/>
        </g>
        <text x="20.41" y="527.6" fill="#000" font-family="Arial" font-size="8">ProcessOutbound</text>
    </g>
</svg>

which can be found by this Xpath
/svg/g[text="ProcessOutbound"]/use

also this work fine
/svg/g[text="ProcessOutbound"]/use/@fill

but for some reasons that xsl is not replaceing #f00 with #00f which is what have tired
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
    <xsl:param name="blue" select="'#00f'"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match='/svg/g[text="ProcessOutbound"]/use'>
        <xsl:attribute name='fill'>
            <xsl:value-of select="'$blue'"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

actually the whole svg file is copied but the fill attribute is not replaced. I tried to achive a copy but with the replaced fill value
What is the correct way to replace attribut values with constant values by xsl ?
So the expected result should look like
   <g transform="translate(113.63-359.13)">
    <use fill="#00f" xlink:href="#D"/>
    <g transform="translate(72.59-8.504)">
        <use xlink:href="#E"/>
        <path fill="#f00" stroke="#000" stroke-linejoin="round" stroke-linecap="round" stroke-width=".24" d="m6.04 526.26h19.843v4.961h-19.843z"/>
        <use xlink:href="#F"/>
    </g>
    <text x="20.41" y="527.6" fill="#000" font-family="Arial" font-size="8">ProcessOutbound</text>
</g>

A: There are a few things incorrect with your XSLT:

*

*It is trying to replace the whole 'use' element with an attribute.

*You are using two pairs of quotes around $blue, which causes it to be treated as a string.

*You are not using namespaces even though your XML uses a namespace.

Please try this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:svg="http://www.w3.org/2000/svg">
    <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
    <xsl:param name="blue" select="'#00f'"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

  <xsl:template match='svg:g[svg:text = "ProcessOutbound"]/svg:use/@fill'>
        <xsl:attribute name='fill'>
            <xsl:value-of select="$blue"/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

When run on your sample input, the result is:
<svg xmlns:xlink="...">
    <g transform="translate(113.63-359.13)">
        <use xlink:href="#D" fill="#00f" />
        <g transform="translate(72.59-8.504)">
            <use xlink:href="#E" xmlns:xlink="x" />
            <path fill="#f00" d="m6.04 526.26h19.843v4.961h-19.843z" stroke-width=".24" stroke-linecap="round" stroke-linejoin="round" stroke="#000" />
            <use xlink:href="#F" />
        </g>
        <text font-family="Arial" fill="#000" font-size="8" y="527.6" x="20.41">ProcessOutbound</text>
    </g>
</svg>

http://www.xsltcake.com/slices/d8pdoi

A: Assuming a well-formed input (the prefix xlink: is not bound because you did not include its namespace definition), use the stylesheet below.
Rather than matching the element use, directly match the node you'd like to modify, the fill attribute of use.
Stylesheet
Your question suggests that the second template should actually match /svg/g[8]/use/@fill if I understood correctly.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="blue" select="'#00f'"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/svg/g/use/@fill">
        <xsl:attribute name="fill">
            <xsl:value-of select="$blue"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

XML Output
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns:xlink="http://www.w3.org/1999/xlink">
   <g transform="translate(113.63-359.13)">
      <use fill="#00f" xlink:href="#D"/>
      <g transform="translate(72.59-8.504)">
         <use xlink:href="#E"/>
         <path fill="#f00" stroke="#000" stroke-linejoin="round" stroke-linecap="round" stroke-width=".24" d="m6.04 526.26h19.843v4.961h-19.843z"/>
         <use xlink:href="#F"/>
      </g>
      <text x="20.41" y="527.6" fill="#000" font-family="Arial" font-size="8">ProcessOutbound</text>
   </g>
</svg>

EDIT: As mentioned in a comment, try the following stylesheet if your SVG elements actually are in a namespace:
Stylesheet
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:svg="http://www.w3.org/2000/svg">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="blue" select="'#00f'"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/svg:svg/svg:g/svg:use/@fill">
        <xsl:attribute name="fill">
            <xsl:value-of select="$blue"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

A: If I am guessing correctly and your input is a valid SVG document, then all its elements are in the SVG namespace. IOW, your input example should actually look like this:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g transform="translate(113.63-359.13)">
        <use fill="#f00" xlink:href="#D"/>
        <g transform="translate(72.59-8.504)">
            <use xlink:href="#E"/>
            <path fill="#f00" stroke="#000" stroke-linejoin="round" stroke-linecap="round" stroke-width=".24" d="m6.04 526.26h19.843v4.961h-19.843z"/>
            <use xlink:href="#F"/>
        </g>
        <text x="20.41" y="527.6" fill="#000" font-family="Arial" font-size="8">ProcessOutbound</text>
    </g>
</svg>

And then your XSLT:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="blue" select="'#00f'"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="svg:g[svg:text='ProcessOutbound']/svg:use/@fill">
    <xsl:attribute name='fill'>
        <xsl:value-of select="$blue"/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

A: Try with this,
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xlink="http://www.w3.org/1999/xlink">
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
<xsl:param name="blue" select="'#00f'"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="/svg/g[contains(text, 'ProcessOutbound')]/use">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
    <xsl:attribute name='fill'>
        <xsl:value-of select="$blue"/>
    </xsl:attribute>
    <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

If this not meeting u r requirement, provide u r simple required text.


text:
Q: approximation with polynomials without stone weierstrass This is from a course in real analysis.
Let $f:G\rightarrow \mathbb{R}$ be a continuous bounded function and $G\subset\mathbb{R}^n$ an open bounded set.
Prove that for every compact set $K\subset G$ there is a series of polynomial that converge uniformly on $K$.
I can't use Stone-Weierstrass theorem here
. I can use the fact that polynomials are dense in $L_p$. Any ideas?


text:
Q: Store Values based on Key in PHP Multidimensional Array I would like to store values from the following $cart_item array:
[addons] => Array(
    [0] => Array(
        [name] => First Name - First Name
        [value] => Gary
        [price] =>
    )
    [1] => Array(
        [name] => Church Information - Name
        [value] => Victory Bible Church
        [price] =>
    )
    [2] => Array(
        [name] => Shirt Size
        [value] => XL
        [price] =>
    )
)

I've realized that I can't grab the value based on the index because this array will sometimes have more sub arrays. For example, I can't use the following string to store data:
$shirt_size = $cart_item['addons'][2]['value'];

Because someone might add into the array the name "Church Information - City" and that will take the array index of [2], which will then make the $shirt_size variable take the 'Church Information - City' value. I don't want that happening.
There are only 2 other possible arrays that will be included. I want to store all possible values associated with a name.
Can someone help me with this?

A: If you want each of the values in variables, you can use value of 'name' key to store value of 'value' key.
foreach ($cart_item['addons'] as $key => $val) {
    $name = strtolower(str_replace(' ','_', $val['name']));
    $$name = $val['value'];
}

echo $shirt_size; //output as XL

OR
if you want only the shirt size, then you can apply a condition and get your value.
foreach ($cart_item['addons'] as $key => $val) {
    if ($val['name'] == 'Shirt Size') {
        $shirt_size = $val['value'];
    }
}

echo $shirt_size; //output as XL

Hope this will help you to grab the required values.


text:
Q: Prove that this function is integrable and equal to zero If $f:[a,b] \to R$ is a bounded function such that $f(x)=0$ except for $x \in \{c_1,c_2,...,c_n\} \subset [a,b]$. Prove that $f$ is integrable in $[a,b]$ and that $\int_a^b f=0$.
I think this can be proved by Riemann criterion or by it's corollary. By finding the upper and lower sums, and since there are only certain points where the function isn't equal to zero its upper and lower sums must be 0.
But the only problem is that I don't know what partition to take, any thoughts?
Is there a way to determine what partition to take in this kind of problems, or it's purely intuition/arbitrary?

A: It doesn't matter. As long as the longest length in the partition is less than $\min\{c_{k+1}-c_k\}$, each point will be in a single partition. So, in the Riemann sum, only $n$ intervals will give nonzero values, and you can make these contributions as small as you want by making the partition finer.


text:
Q: Change one character in PostgreSQL column string I have a hundreds of entries in a description column that look like the following:
CAP 0.001UF ±10% 50V X7R 0402

I need to change it to:
CAP 0.001UF +/-10% 50V X7R 040

How can I search through the records and change all instances of ± to +/-?

A: How about using replace() and like?
update t
    set description = replace(description, '±', '+/-')
    where description like '%±%';


text:
Q: iOS 10 How to set UNotificationContent threadIdentifier for remote notification TL;DR: What key needs to be set in the APNs notification payload JSON to correspond to the threadIdentifier property of the UNNotificationContent object? e.g. the "category" key corresponds to the categoryIdentifier property.

iOS 10 introduces the Notification Content Extension allowing us to present a view controller when a notification is expanded.
The view controller that we provide conforms to the UNNotificationContentExtension protocol, that requires us to implement the didReceive(_:) method.
The documentation for this method includes the following paragraph:

This method may be called multiple times while your view controller is visible. Specifically, it is called again when a new notification arrives whose threadIdentifier value matches the thread identifier of the notification already being displayed.

The threadIdentifier property may be set in code for local notifications, but I don't know how to set it for remote notifications that are sent from the server to APNs.
The UNNotificationContent documentation describes the property here: http://developer.apple.com/reference/usernotifications/unnotificationcontent
The following JSON includes the keys I've tried ("thread" and "thread-identifier"):
{
    "aps" : {
        "alert" : "Hello World!",
        "sound" : "default",
        "category" : "example-category",
        "thread" : "example-thread",
        "thread-identifier" : "example-thread-identifier"
    }
    "custom-field" : "some value",
}

I can't find any documentation from Apple about how to set this. Can anyone help?

A: I discovered from a contact at Apple that the correct key to populate this property is the "thread-id" key.
So the JSON sent to APNs is as follows:
{
    "aps" : {
        "alert" : "Hello World!",
        "sound" : "default",
        "category" : "example-category",
        "thread-id" : "my conversation blah blah"
    }
    "custom-field" : "some value",
}

This populates the threadIdentifier property of the UNNotificationContent object accessible in your Notification Content Extension via notification.request.content.threadIdentifier.
By setting this "thread-id" value, it means that the didReceive(_:) method of your content extension will be multiple times. First when expanding the notification initially, and again whenever a new notification arrives with the same "thread-id" value.
I assume (hope) this will be added to the official documentation once iOS 10 is officially released.


text:
Q: How to determine number of IOPS used by a query in SQL Azure This question has arisen because a query we are running intermittently times out. The question is not about sorting out the problem query itself, but how to generally interpret the information available.
I've seen that when these timeouts occur, our "Data IO Percentage" via the Azure Portal and sys.dm_db_resource_stats is hitting 100%.
Using the sys.dm_user_db_resource_governance stored procedure, I see that my primary_group_max_io is 160, therefore my IOPS (input / output per second) limit is 160. So far so good.
Coming from the query side, I'm using a query (shown in full below) that uses the sys.query_store_runtime_stats table to get IO read information (the query only does a select). I can see from this that for the query having problems the avg_physical_io_reads value is 5000, which is bigger than other queries going on (being 0 - 500).
A third angle I used was the "Live Query Statistics" in SQL Server Management Studio, which has an "actual number of rows read" for different nodes of the query plan.
The questions are:

*

*How are the avg_physical_io_reads and IOPS related? Can they be related?

*How do I know if 5000 avg_physical_io_reads is big in relation to my 160 IOPS limit from Azure? It looks like it, but the queries with avg_physical_io_reads of 500 are ok.

*Are the "Live Query Statistics" rows read in any way relatable to the logical and physical io reads of the query_store_runtime_stats?

*Are there any other diagnostics that can tell me how much a particular query will impact my Azure IOPS limits?

Full query for sys.query_store_runtime_stats that I've been using:
SELECT
qsrsi.start_time,
qsrsi.end_time,
qsq.query_id,
qsq.query_text_id,
qsp.plan_id,
qsq.last_execution_time,
count_executions,
qsq.count_compiles,
avg_duration/1000 as [Avg_Duration(ms)],
min_duration/1000 as [Min_Duration(ms)],
max_duration/1000 as [Max_Duration(ms)],
avg_logical_io_reads,
min_logical_io_reads,
max_logical_io_reads,
avg_physical_io_reads,,
min_physical_io_reads,
max_physical_io_reads,
avg_rowcount,
min_rowcount,
max_rowcount,
avg_num_physical_io_reads,
min_num_physical_io_reads,
max_num_physical_io_reads,
qsqt.query_sql_text,
query_plan,
qsq.query_hash
from sys.query_store_query qsq
INNER JOIN sys.query_store_query_text qsqt ON qsq.query_text_id = qsqt.query_text_id
INNER JOIN sys.query_context_settings qcs ON qsq.context_settings_id = qcs.context_settings_id
INNER JOIN sys.query_store_plan qsp ON qsq.query_id = qsp.query_id
INNER JOIN sys.query_store_runtime_stats qsrs ON qsrs.plan_id = qsp.plan_id
INNER JOIN sys.query_store_runtime_stats_interval qsrsi ON qsrs.runtime_stats_interval_id = qsrsi.runtime_stats_interval_id
WHERE qsrsi.start_time >= @starttime and qsrsi.start_time <= @endtime
ORDER BY qsrsi.start_time

A: The configuration only has the maximum data IOPs information. Utilization depends on the resource limit. refer  docs.microsoft.com/en-us/azure/azure-sql/database/…,

*The vCore configuration only has the maximum data IOPs information. Utilization depends on the resource limit. we can get IOPS information using this query
SELECT * FROM sys.dm_user_db_resource_governance

*To verify the sleeping connection instances on Sql Server Database
    SELECT  DB_NAME(dbid) as DBName,  Count(dbid) as NumberOfConnetions,  Status  FROM  sys.sysprocesses with (nolock)  WHERE  dbid>0  GROUP BY  dbid, loginname,status;

*We can verify the query logs / long running queries form Azure portal itself under  Intelligence Performance window


text:
Q: SAS gmap and label centering I have a Problem where I could not find an easy solution and I am looking for some ideas or tipps.
I am working with SAS on a project which result should be a map of europe, where the countries get colored after a certain algorithm. I use the maps.europe data and the %annomac and %maplabel macros to label the countries.
This works pretty fine, except for Portugal and Spain - because theese countries have island far away from the coastside, the calculated centroid from %maplabel of the country is not in the center of the country:
Unfortunately I just can cut portugal completely out of the map but not the Islands
I have tried already this method:

*

*Try to cut the parts of the map via gproject which contains the islands - this delievered unexplaniable results to me (just showing some parts of europe, even if I set the parameters extremly wide)

and now I am a bit stuck.
I already thought about this ideas:
Comnbining the map.europe with the map.spain and and map.portugal where I delete the islands before, but I am not sure how to do that that the labeling and all still works for theese combined data.
Is it possible to set the label points for portugal and spain manually and overwrite the data from the %maplabel macro?
Or is there an even easier solution?
Thanks for your help and best regards
stephan

A: I'm not familiar with those macros, but given how GMAP works, I would indeed override the annotate dataset.  You may want to read up on how annotate datasets work, but in general:
The GMAP statement will have an option, annotate= and some dataset.  Find that dataset, let's say it's called ANNODS.
Then look at that dataset.  Identify a row that has function=text and label=PORTUGAL.  That is the row you need to modify the x/y coordinates of in order to move the label around (x1 and y1).  You might need to play around with this some to get the right coordinates.
Then run the PROC GMAP, and you should have a newly moved-over Portugal.


text:
Q: Calling a Google Form through the Custom Menu of Google Spreadsheet created by the script editor and open it through a pop/modal I want to create a Custom Menu on Google Sheets through the Script Editor that creates a pop up or modal from an HTML file that shows the Google Forms linked in the HTML file. So far this is what I have.
function onOpen() {

  var ui = SpreadsheetApp.getUi();
  ui.createMenu("Records")
  .addItem("Dump","menuItem1")
  .addItem("New Patient Record", "menuItem2")
  .addToUi();
}

function menuItem1() {
    SpreadsheetApp.getUi ()
     .alert('You clicked the first menu item!');
    }

function menuItem2() {

 var htmlOutput = HtmlService.createHtmlOutputFromFile('form')
     .setWidth(250)
     .setHeight(80)

 SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Form');
}

as for my html file which is name form.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>

    <form action='https://docs.google.com/forms/d/e/1FAIpQLSexWWi3ru1bzwDVhG1TU0hqAeS6VCi-6LDju8KqG7zZv1tBxg/viewform' method='get' id='foo'></form>
    <script>document.getElementById('foo').submit();</script>
  </body>
</html>

This is the pop/modal I have for now and it does not call the google form link
modalinsheetspicture

A: On your form.html file, insert your form inside an iframe.
<iframe src="https://docs.google.com/forms/d/e/123/viewform" width="100%" height="100%"></iframe>


text:
Q: Question about Mongoose Nodejs UPDATE AND GET data delay I recently encounter a problem that is regarding to the CRUD development process. When I update a property and send the response to the postman, postman always display the previous data. For example, after I clicked send on Postman, it displays "weeks" : "11" instead of "10". ==>First Click
Then when I click the send button the second times, it updates the postman display "week" : "10" instead. ===> Second Click
 Have anyone encounter this problem before? What is the best solution?
Here is the link to the code related to my questions: https://codesandbox.io/s/pensive-tdd-c9rej
I just don't know if this only happens to postman or it does happen to all the final production as well.

A: I will answer you real quick. You just need to add some options to the query.
You should set the new option to true to return the document after update was applied.
https://mongoosejs.com/docs/tutorials/findoneandupdate.html#:~:text=As%20the%20name%20implies%2C%20findOneAndUpdate,was%20before%20update%20was%20applied.&text=You%20should%20set%20the%20new,document%20after%20update%20was%20applied.
exports.unblockUser = withCatchErrAsync(async (req, res, next) => {
  const { userId } = req.params;

  // **blocked** is set to hidden by default, now we explicitly turn that back on
  const doc = await User.findByIdAndUpdate(
    userId,
    { blocked: false },

 // The key Code is here
    {
      new: true,
      runValidators: true,
    }
  ).select("+blocked");

  if (!doc) {
    return next(new OperationalErr("User ID does not match any user"), 400);
  }

  return res.status(200).json({
    status: "success",
    data: {
      user: doc,
    },
  });
});


text:
Q: How to implement a server side pagination with Material ui and react? Currently you can paginate towards the backend, with the next and previous option, but I can't do it with the rows per page option, how do I make the two options work? Thank you
Here is an image of the options

A: For paging you need:

*

*know the number of records.

*number of records displayed on page.

*page number.

Send to server from client: number of records on page and page number)
Send to client from server: records between from, to

const count = 20; // for example we have 20 records
const size = 7;   // there are 7 records on each page

// number of pages
const countPages = Math.ceil (20/7);

//show records on page 2:
const page = 2; // display 2nd page

const from = (page - 1) * size;
const to = Math.min (from + size- 1, count);

console.log(`we have ${count} records, ${size} per page` )
console.log('number of pages', countPages);
console.log(`on page ${page} records from ${from} to ${to}`);